Release 5.13e
[org-mode/org-tableheadings.git] / org.el
blob9d08a280d8f43b5264db403179b27f34ed1e79f1
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.13e
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.13e"
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 an entry is a directory, all files in that directory that are matched by
1991 `org-agenda-file-regexp' will be part of the file list.
1993 If the value of the variable is not a list but a single file name, then
1994 the list of agenda files is actually stored and maintained in that file, one
1995 agenda file per line."
1996 :group 'org-agenda
1997 :type '(choice
1998 (repeat :tag "List of files and directories" file)
1999 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2001 (defcustom org-agenda-file-regexp "\\.org\\'"
2002 "Regular expression to match files for `org-agenda-files'.
2003 If any element in the list in that variable contains a directory instead
2004 of a normal file, all files in that directory that are matched by this
2005 regular expression will be included."
2006 :group 'org-agenda
2007 :type 'regexp)
2009 (defcustom org-agenda-skip-unavailable-files nil
2010 "t means to just skip non-reachable files in `org-agenda-files'.
2011 Nil means to remove them, after a query, from the list."
2012 :group 'org-agenda
2013 :type 'boolean)
2015 (defcustom org-agenda-multi-occur-extra-files nil
2016 "List of extra files to be searched by `org-occur-in-agenda-files'.
2017 The files in `org-agenda-files' are always searched."
2018 :group 'org-agenda
2019 :type '(repeat file))
2021 (defcustom org-agenda-confirm-kill 1
2022 "When set, remote killing from the agenda buffer needs confirmation.
2023 When t, a confirmation is always needed. When a number N, confirmation is
2024 only needed when the text to be killed contains more than N non-white lines."
2025 :group 'org-agenda
2026 :type '(choice
2027 (const :tag "Never" nil)
2028 (const :tag "Always" t)
2029 (number :tag "When more than N lines")))
2031 (defcustom org-calendar-to-agenda-key [?c]
2032 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2033 The command `org-calendar-goto-agenda' will be bound to this key. The
2034 default is the character `c' because then `c' can be used to switch back and
2035 forth between agenda and calendar."
2036 :group 'org-agenda
2037 :type 'sexp)
2039 (defcustom org-agenda-compact-blocks nil
2040 "Non-nil means, make the block agenda more compact.
2041 This is done by leaving out unnecessary lines."
2042 :group 'org-agenda
2043 :type nil)
2045 (defgroup org-agenda-export nil
2046 "Options concerning exporting agenda views in Org-mode."
2047 :tag "Org Agenda Export"
2048 :group 'org-agenda)
2050 (defcustom org-agenda-with-colors t
2051 "Non-nil means, use colors in agenda views."
2052 :group 'org-agenda-export
2053 :type 'boolean)
2055 (defcustom org-agenda-exporter-settings nil
2056 "Alist of variable/value pairs that should be active during agenda export.
2057 This is a good place to set uptions for ps-print and for htmlize."
2058 :group 'org-agenda-export
2059 :type '(repeat
2060 (list
2061 (variable)
2062 (sexp :tag "Value"))))
2064 (defcustom org-agenda-export-html-style ""
2065 "The style specification for exported HTML Agenda files.
2066 If this variable contains a string, it will replace the default <style>
2067 section as produced by `htmlize'.
2068 Since there are different ways of setting style information, this variable
2069 needs to contain the full HTML structure to provide a style, including the
2070 surrounding HTML tags. The style specifications should include definitions
2071 the fonts used by the agenda, here is an example:
2073 <style type=\"text/css\">
2074 p { font-weight: normal; color: gray; }
2075 .org-agenda-structure {
2076 font-size: 110%;
2077 color: #003399;
2078 font-weight: 600;
2080 .org-todo {
2081 color: #cc6666;Week-agenda:
2082 font-weight: bold;
2084 .org-done {
2085 color: #339933;
2087 .title { text-align: center; }
2088 .todo, .deadline { color: red; }
2089 .done { color: green; }
2090 </style>
2092 or, if you want to keep the style in a file,
2094 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2096 As the value of this option simply gets inserted into the HTML <head> header,
2097 you can \"misuse\" it to also add other text to the header. However,
2098 <style>...</style> is required, if not present the variable will be ignored."
2099 :group 'org-agenda-export
2100 :group 'org-export-html
2101 :type 'string)
2103 (defgroup org-agenda-custom-commands nil
2104 "Options concerning agenda views in Org-mode."
2105 :tag "Org Agenda Custom Commands"
2106 :group 'org-agenda)
2108 (defcustom org-agenda-custom-commands nil
2109 "Custom commands for the agenda.
2110 These commands will be offered on the splash screen displayed by the
2111 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2113 (key desc type match options files)
2115 key The key (one or more characters as a string) to be associated
2116 with the command.
2117 desc A description of the commend, when omitted or nil, a default
2118 description is built using MATCH.
2119 type The command type, any of the following symbols:
2120 todo Entries with a specific TODO keyword, in all agenda files.
2121 tags Tags match in all agenda files.
2122 tags-todo Tags match in all agenda files, TODO entries only.
2123 todo-tree Sparse tree of specific TODO keyword in *current* file.
2124 tags-tree Sparse tree with all tags matches in *current* file.
2125 occur-tree Occur sparse tree for *current* file.
2126 ... A user-defined function.
2127 match What to search for:
2128 - a single keyword for TODO keyword searches
2129 - a tags match expression for tags searches
2130 - a regular expression for occur searches
2131 options A list of option settings, similar to that in a let form, so like
2132 this: ((opt1 val1) (opt2 val2) ...)
2133 files A list of files file to write the produced agenda buffer to
2134 with the command `org-store-agenda-views'.
2135 If a file name ends in \".html\", an HTML version of the buffer
2136 is written out. If it ends in \".ps\", a postscript version is
2137 produced. Otherwide, only the plain text is written to the file.
2139 You can also define a set of commands, to create a composite agenda buffer.
2140 In this case, an entry looks like this:
2142 (key desc (cmd1 cmd2 ...) general-options file)
2144 where
2146 desc A description string to be displayed in the dispatcher menu.
2147 cmd An agenda command, similar to the above. However, tree commands
2148 are no allowed, but instead you can get agenda and global todo list.
2149 So valid commands for a set are:
2150 (agenda)
2151 (alltodo)
2152 (stuck)
2153 (todo \"match\" options files)
2154 (tags \"match\" options files)
2155 (tags-todo \"match\" options files)
2157 Each command can carry a list of options, and another set of options can be
2158 given for the whole set of commands. Individual command options take
2159 precedence over the general options.
2161 When using several characters as key to a command, the first characters
2162 are prefix commands. For the dispatcher to display useful information, you
2163 should provide a description for the prefix, like
2165 (setq org-agenda-custom-commands
2166 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2167 (\"hl\" tags \"+HOME+Lisa\")
2168 (\"hp\" tags \"+HOME+Peter\")
2169 (\"hk\" tags \"+HOME+Kim\")))"
2170 :group 'org-agenda-custom-commands
2171 :type '(repeat
2172 (choice :value ("a" "" tags "" nil)
2173 (list :tag "Single command"
2174 (string :tag "Access Key(s) ")
2175 (option (string :tag "Description"))
2176 (choice
2177 (const :tag "Agenda" agenda)
2178 (const :tag "TODO list" alltodo)
2179 (const :tag "Stuck projects" stuck)
2180 (const :tag "Tags search (all agenda files)" tags)
2181 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2182 (const :tag "TODO keyword search (all agenda files)" todo)
2183 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2184 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2185 (const :tag "Occur tree (current buffer)" occur-tree)
2186 (sexp :tag "Other, user-defined function"))
2187 (string :tag "Match")
2188 (repeat :tag "Local options"
2189 (list (variable :tag "Option") (sexp :tag "Value")))
2190 (option (repeat :tag "Export" (file :tag "Export to"))))
2191 (list :tag "Command series, all agenda files"
2192 (string :tag "Access Key(s)")
2193 (string :tag "Description ")
2194 (repeat
2195 (choice
2196 (const :tag "Agenda" (agenda))
2197 (const :tag "TODO list" (alltodo))
2198 (const :tag "Stuck projects" (stuck))
2199 (list :tag "Tags search"
2200 (const :format "" tags)
2201 (string :tag "Match")
2202 (repeat :tag "Local options"
2203 (list (variable :tag "Option")
2204 (sexp :tag "Value"))))
2206 (list :tag "Tags search, TODO entries only"
2207 (const :format "" tags-todo)
2208 (string :tag "Match")
2209 (repeat :tag "Local options"
2210 (list (variable :tag "Option")
2211 (sexp :tag "Value"))))
2213 (list :tag "TODO keyword search"
2214 (const :format "" todo)
2215 (string :tag "Match")
2216 (repeat :tag "Local options"
2217 (list (variable :tag "Option")
2218 (sexp :tag "Value"))))
2220 (list :tag "Other, user-defined function"
2221 (symbol :tag "function")
2222 (string :tag "Match")
2223 (repeat :tag "Local options"
2224 (list (variable :tag "Option")
2225 (sexp :tag "Value"))))))
2227 (repeat :tag "General options"
2228 (list (variable :tag "Option")
2229 (sexp :tag "Value")))
2230 (option (repeat :tag "Export" (file :tag "Export to"))))
2231 (cons :tag "Prefix key documentation"
2232 (string :tag "Access Key(s)")
2233 (string :tag "Description ")))))
2235 (defcustom org-stuck-projects
2236 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2237 "How to identify stuck projects.
2238 This is a list of four items:
2239 1. A tags/todo matcher string that is used to identify a project.
2240 The entire tree below a headline matched by this is considered one project.
2241 2. A list of TODO keywords identifying non-stuck projects.
2242 If the project subtree contains any headline with one of these todo
2243 keywords, the project is considered to be not stuck. If you specify
2244 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2245 3. A list of tags identifying non-stuck projects.
2246 If the project subtree contains any headline with one of these tags,
2247 the project is considered to be not stuck. If you specify \"*\" as
2248 a tag, any tag will mark the project unstuck.
2249 4. An arbitrary regular expression matching non-stuck projects.
2251 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2252 or `C-c a #' to produce the list."
2253 :group 'org-agenda-custom-commands
2254 :type '(list
2255 (string :tag "Tags/TODO match to identify a project")
2256 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2257 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2258 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2261 (defgroup org-agenda-skip nil
2262 "Options concerning skipping parts of agenda files."
2263 :tag "Org Agenda Skip"
2264 :group 'org-agenda)
2266 (defcustom org-agenda-todo-list-sublevels t
2267 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2268 When nil, the sublevels of a TODO entry are not checked, resulting in
2269 potentially much shorter TODO lists."
2270 :group 'org-agenda-skip
2271 :group 'org-todo
2272 :type 'boolean)
2274 (defcustom org-agenda-todo-ignore-with-date nil
2275 "Non-nil means, don't show entries with a date in the global todo list.
2276 You can use this if you prefer to mark mere appointments with a TODO keyword,
2277 but don't want them to show up in the TODO list.
2278 When this is set, it also covers deadlines and scheduled items, the settings
2279 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2280 will be ignored."
2281 :group 'org-agenda-skip
2282 :group 'org-todo
2283 :type 'boolean)
2285 (defcustom org-agenda-todo-ignore-scheduled nil
2286 "Non-nil means, don't show scheduled entries in the global todo list.
2287 The idea behind this is that by scheduling it, you have already taken care
2288 of this item.
2289 See also `org-agenda-todo-ignore-with-date'."
2290 :group 'org-agenda-skip
2291 :group 'org-todo
2292 :type 'boolean)
2294 (defcustom org-agenda-todo-ignore-deadlines nil
2295 "Non-nil means, don't show near deadline entries in the global todo list.
2296 Near means closer than `org-deadline-warning-days' days.
2297 The idea behind this is that such items will appear in the agenda anyway.
2298 See also `org-agenda-todo-ignore-with-date'."
2299 :group 'org-agenda-skip
2300 :group 'org-todo
2301 :type 'boolean)
2303 (defcustom org-agenda-skip-scheduled-if-done nil
2304 "Non-nil means don't show scheduled items in agenda when they are done.
2305 This is relevant for the daily/weekly agenda, not for the TODO list. And
2306 it applies only to the actual date of the scheduling. Warnings about
2307 an item with a past scheduling dates are always turned off when the item
2308 is DONE."
2309 :group 'org-agenda-skip
2310 :type 'boolean)
2312 (defcustom org-agenda-skip-deadline-if-done nil
2313 "Non-nil means don't show deadines when the corresponding item is done.
2314 When nil, the deadline is still shown and should give you a happy feeling.
2315 This is relevant for the daily/weekly agenda. And it applied only to the
2316 actualy date of the deadline. Warnings about approching and past-due
2317 deadlines are always turned off when the item is DONE."
2318 :group 'org-agenda-skip
2319 :type 'boolean)
2321 (defcustom org-timeline-show-empty-dates 3
2322 "Non-nil means, `org-timeline' also shows dates without an entry.
2323 When nil, only the days which actually have entries are shown.
2324 When t, all days between the first and the last date are shown.
2325 When an integer, show also empty dates, but if there is a gap of more than
2326 N days, just insert a special line indicating the size of the gap."
2327 :group 'org-agenda-skip
2328 :type '(choice
2329 (const :tag "None" nil)
2330 (const :tag "All" t)
2331 (number :tag "at most")))
2334 (defgroup org-agenda-startup nil
2335 "Options concerning initial settings in the Agenda in Org Mode."
2336 :tag "Org Agenda Startup"
2337 :group 'org-agenda)
2339 (defcustom org-finalize-agenda-hook nil
2340 "Hook run just before displaying an agenda buffer."
2341 :group 'org-agenda-startup
2342 :type 'hook)
2344 (defcustom org-agenda-mouse-1-follows-link nil
2345 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2346 A longer mouse click will still set point. Does not wortk on XEmacs.
2347 Needs to be set before org.el is loaded."
2348 :group 'org-agenda-startup
2349 :type 'boolean)
2351 (defcustom org-agenda-start-with-follow-mode nil
2352 "The initial value of follow-mode in a newly created agenda window."
2353 :group 'org-agenda-startup
2354 :type 'boolean)
2356 (defgroup org-agenda-windows nil
2357 "Options concerning the windows used by the Agenda in Org Mode."
2358 :tag "Org Agenda Windows"
2359 :group 'org-agenda)
2361 (defcustom org-agenda-window-setup 'reorganize-frame
2362 "How the agenda buffer should be displayed.
2363 Possible values for this option are:
2365 current-window Show agenda in the current window, keeping all other windows.
2366 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2367 other-window Use `switch-to-buffer-other-window' to display agenda.
2368 reorganize-frame Show only two windows on the current frame, the current
2369 window and the agenda.
2370 See also the variable `org-agenda-restore-windows-after-quit'."
2371 :group 'org-agenda-windows
2372 :type '(choice
2373 (const current-window)
2374 (const other-frame)
2375 (const other-window)
2376 (const reorganize-frame)))
2378 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2379 "The min and max height of the agenda window as a fraction of frame height.
2380 The value of the variable is a cons cell with two numbers between 0 and 1.
2381 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2382 :group 'org-agenda-windows
2383 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2385 (defcustom org-agenda-restore-windows-after-quit nil
2386 "Non-nil means, restore window configuration open exiting agenda.
2387 Before the window configuration is changed for displaying the agenda,
2388 the current status is recorded. When the agenda is exited with
2389 `q' or `x' and this option is set, the old state is restored. If
2390 `org-agenda-window-setup' is `other-frame', the value of this
2391 option will be ignored.."
2392 :group 'org-agenda-windows
2393 :type 'boolean)
2395 (defcustom org-indirect-buffer-display 'other-window
2396 "How should indirect tree buffers be displayed?
2397 This applies to indirect buffers created with the commands
2398 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2399 Valid values are:
2400 current-window Display in the current window
2401 other-window Just display in another window.
2402 dedicated-frame Create one new frame, and re-use it each time.
2403 new-frame Make a new frame each time."
2404 :group 'org-structure
2405 :group 'org-agenda-windows
2406 :type '(choice
2407 (const :tag "In current window" current-window)
2408 (const :tag "In current frame, other window" other-window)
2409 (const :tag "Each time a new frame" new-frame)
2410 (const :tag "One dedicated frame" dedicated-frame)))
2412 (defgroup org-agenda-daily/weekly nil
2413 "Options concerning the daily/weekly agenda."
2414 :tag "Org Agenda Daily/Weekly"
2415 :group 'org-agenda)
2417 (defcustom org-agenda-ndays 7
2418 "Number of days to include in overview display.
2419 Should be 1 or 7."
2420 :group 'org-agenda-daily/weekly
2421 :type 'number)
2423 (defcustom org-agenda-start-on-weekday 1
2424 "Non-nil means, start the overview always on the specified weekday.
2425 0 denotes Sunday, 1 denotes Monday etc.
2426 When nil, always start on the current day."
2427 :group 'org-agenda-daily/weekly
2428 :type '(choice (const :tag "Today" nil)
2429 (number :tag "Weekday No.")))
2431 (defcustom org-agenda-show-all-dates t
2432 "Non-nil means, `org-agenda' shows every day in the selected range.
2433 When nil, only the days which actually have entries are shown."
2434 :group 'org-agenda-daily/weekly
2435 :type 'boolean)
2437 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2438 "Format string for displaying dates in the agenda.
2439 Used by the daily/weekly agenda and by the timeline. This should be
2440 a format string understood by `format-time-string', or a function returning
2441 the formatted date as a string. The function must take a single argument,
2442 a calendar-style date list like (month day year)."
2443 :group 'org-agenda-daily/weekly
2444 :type '(choice
2445 (string :tag "Format string")
2446 (function :tag "Function")))
2448 (defun org-agenda-format-date-aligned (date)
2449 "Format a date string for display in the daily/weekly agenda, or timeline.
2450 This function makes sure that dates are aligned for easy reading."
2451 (format "%-9s %2d %s %4d"
2452 (calendar-day-name date)
2453 (extract-calendar-day date)
2454 (calendar-month-name (extract-calendar-month date))
2455 (extract-calendar-year date)))
2457 (defcustom org-agenda-include-diary nil
2458 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2459 :group 'org-agenda-daily/weekly
2460 :type 'boolean)
2462 (defcustom org-agenda-include-all-todo nil
2463 "Set means weekly/daily agenda will always contain all TODO entries.
2464 The TODO entries will be listed at the top of the agenda, before
2465 the entries for specific days."
2466 :group 'org-agenda-daily/weekly
2467 :type 'boolean)
2469 (defcustom org-agenda-repeating-timestamp-show-all t
2470 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2471 When nil, only one occurence is shown, either today or the
2472 nearest into the future."
2473 :group 'org-agenda-daily/weekly
2474 :type 'boolean)
2476 (defcustom org-deadline-warning-days 14
2477 "No. of days before expiration during which a deadline becomes active.
2478 This variable governs the display in sparse trees and in the agenda.
2479 When negative, it means use this number (the absolute value of it)
2480 even if a deadline has a different individual lead time specified."
2481 :group 'org-time
2482 :group 'org-agenda-daily/weekly
2483 :type 'number)
2485 (defcustom org-scheduled-past-days 10000
2486 "No. of days to continue listing scheduled items that are not marked DONE.
2487 When an item is scheduled on a date, it shows up in the agenda on this
2488 day and will be listed until it is marked done for the number of days
2489 given here."
2490 :group 'org-agenda-daily/weekly
2491 :type 'number)
2493 (defgroup org-agenda-time-grid nil
2494 "Options concerning the time grid in the Org-mode Agenda."
2495 :tag "Org Agenda Time Grid"
2496 :group 'org-agenda)
2498 (defcustom org-agenda-use-time-grid t
2499 "Non-nil means, show a time grid in the agenda schedule.
2500 A time grid is a set of lines for specific times (like every two hours between
2501 8:00 and 20:00). The items scheduled for a day at specific times are
2502 sorted in between these lines.
2503 For details about when the grid will be shown, and what it will look like, see
2504 the variable `org-agenda-time-grid'."
2505 :group 'org-agenda-time-grid
2506 :type 'boolean)
2508 (defcustom org-agenda-time-grid
2509 '((daily today require-timed)
2510 "----------------"
2511 (800 1000 1200 1400 1600 1800 2000))
2513 "The settings for time grid for agenda display.
2514 This is a list of three items. The first item is again a list. It contains
2515 symbols specifying conditions when the grid should be displayed:
2517 daily if the agenda shows a single day
2518 weekly if the agenda shows an entire week
2519 today show grid on current date, independent of daily/weekly display
2520 require-timed show grid only if at least one item has a time specification
2522 The second item is a string which will be places behing the grid time.
2524 The third item is a list of integers, indicating the times that should have
2525 a grid line."
2526 :group 'org-agenda-time-grid
2527 :type
2528 '(list
2529 (set :greedy t :tag "Grid Display Options"
2530 (const :tag "Show grid in single day agenda display" daily)
2531 (const :tag "Show grid in weekly agenda display" weekly)
2532 (const :tag "Always show grid for today" today)
2533 (const :tag "Show grid only if any timed entries are present"
2534 require-timed)
2535 (const :tag "Skip grid times already present in an entry"
2536 remove-match))
2537 (string :tag "Grid String")
2538 (repeat :tag "Grid Times" (integer :tag "Time"))))
2540 (defgroup org-agenda-sorting nil
2541 "Options concerning sorting in the Org-mode Agenda."
2542 :tag "Org Agenda Sorting"
2543 :group 'org-agenda)
2545 (let ((sorting-choice
2546 '(choice
2547 (const time-up) (const time-down)
2548 (const category-keep) (const category-up) (const category-down)
2549 (const tag-down) (const tag-up)
2550 (const priority-up) (const priority-down))))
2552 (defcustom org-agenda-sorting-strategy
2553 '((agenda time-up category-keep priority-down)
2554 (todo category-keep priority-down)
2555 (tags category-keep priority-down))
2556 "Sorting structure for the agenda items of a single day.
2557 This is a list of symbols which will be used in sequence to determine
2558 if an entry should be listed before another entry. The following
2559 symbols are recognized:
2561 time-up Put entries with time-of-day indications first, early first
2562 time-down Put entries with time-of-day indications first, late first
2563 category-keep Keep the default order of categories, corresponding to the
2564 sequence in `org-agenda-files'.
2565 category-up Sort alphabetically by category, A-Z.
2566 category-down Sort alphabetically by category, Z-A.
2567 tag-up Sort alphabetically by last tag, A-Z.
2568 tag-down Sort alphabetically by last tag, Z-A.
2569 priority-up Sort numerically by priority, high priority last.
2570 priority-down Sort numerically by priority, high priority first.
2572 The different possibilities will be tried in sequence, and testing stops
2573 if one comparison returns a \"not-equal\". For example, the default
2574 '(time-up category-keep priority-down)
2575 means: Pull out all entries having a specified time of day and sort them,
2576 in order to make a time schedule for the current day the first thing in the
2577 agenda listing for the day. Of the entries without a time indication, keep
2578 the grouped in categories, don't sort the categories, but keep them in
2579 the sequence given in `org-agenda-files'. Within each category sort by
2580 priority.
2582 Leaving out `category-keep' would mean that items will be sorted across
2583 categories by priority."
2584 :group 'org-agenda-sorting
2585 :type `(choice
2586 (repeat :tag "General" ,sorting-choice)
2587 (list :tag "Individually"
2588 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2589 (repeat ,sorting-choice))
2590 (cons (const :tag "Strategy for TODO lists" todo)
2591 (repeat ,sorting-choice))
2592 (cons (const :tag "Strategy for Tags matches" tags)
2593 (repeat ,sorting-choice))))))
2595 (defcustom org-sort-agenda-notime-is-late t
2596 "Non-nil means, items without time are considered late.
2597 This is only relevant for sorting. When t, items which have no explicit
2598 time like 15:30 will be considered as 99:01, i.e. later than any items which
2599 do have a time. When nil, the default time is before 0:00. You can use this
2600 option to decide if the schedule for today should come before or after timeless
2601 agenda entries."
2602 :group 'org-agenda-sorting
2603 :type 'boolean)
2605 (defgroup org-agenda-line-format nil
2606 "Options concerning the entry prefix in the Org-mode agenda display."
2607 :tag "Org Agenda Line Format"
2608 :group 'org-agenda)
2610 (defcustom org-agenda-prefix-format
2611 '((agenda . " %-12:c%?-12t% s")
2612 (timeline . " % s")
2613 (todo . " %-12:c")
2614 (tags . " %-12:c"))
2615 "Format specifications for the prefix of items in the agenda views.
2616 An alist with four entries, for the different agenda types. The keys to the
2617 sublists are `agenda', `timeline', `todo', and `tags'. The values
2618 are format strings.
2619 This format works similar to a printf format, with the following meaning:
2621 %c the category of the item, \"Diary\" for entries from the diary, or
2622 as given by the CATEGORY keyword or derived from the file name.
2623 %T the *last* tag of the item. Last because inherited tags come
2624 first in the list.
2625 %t the time-of-day specification if one applies to the entry, in the
2626 format HH:MM
2627 %s Scheduling/Deadline information, a short string
2629 All specifiers work basically like the standard `%s' of printf, but may
2630 contain two additional characters: A question mark just after the `%' and
2631 a whitespace/punctuation character just before the final letter.
2633 If the first character after `%' is a question mark, the entire field
2634 will only be included if the corresponding value applies to the
2635 current entry. This is useful for fields which should have fixed
2636 width when present, but zero width when absent. For example,
2637 \"%?-12t\" will result in a 12 character time field if a time of the
2638 day is specified, but will completely disappear in entries which do
2639 not contain a time.
2641 If there is punctuation or whitespace character just before the final
2642 format letter, this character will be appended to the field value if
2643 the value is not empty. For example, the format \"%-12:c\" leads to
2644 \"Diary: \" if the category is \"Diary\". If the category were be
2645 empty, no additional colon would be interted.
2647 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2648 - Indent the line with two space characters
2649 - Give the category in a 12 chars wide field, padded with whitespace on
2650 the right (because of `-'). Append a colon if there is a category
2651 (because of `:').
2652 - If there is a time-of-day, put it into a 12 chars wide field. If no
2653 time, don't put in an empty field, just skip it (because of '?').
2654 - Finally, put the scheduling information and append a whitespace.
2656 As another example, if you don't want the time-of-day of entries in
2657 the prefix, you could use:
2659 (setq org-agenda-prefix-format \" %-11:c% s\")
2661 See also the variables `org-agenda-remove-times-when-in-prefix' and
2662 `org-agenda-remove-tags'."
2663 :type '(choice
2664 (string :tag "General format")
2665 (list :greedy t :tag "View dependent"
2666 (cons (const agenda) (string :tag "Format"))
2667 (cons (const timeline) (string :tag "Format"))
2668 (cons (const todo) (string :tag "Format"))
2669 (cons (const tags) (string :tag "Format"))))
2670 :group 'org-agenda-line-format)
2672 (defvar org-prefix-format-compiled nil
2673 "The compiled version of the most recently used prefix format.
2674 See the variable `org-agenda-prefix-format'.")
2676 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
2677 "Text preceeding scheduled items in the agenda view.
2678 THis is a list with two strings. The first applies when the item is
2679 scheduled on the current day. The second applies when it has been scheduled
2680 previously, it may contain a %d to capture how many days ago the item was
2681 scheduled."
2682 :group 'org-agenda-line-format
2683 :type '(list
2684 (string :tag "Scheduled today ")
2685 (string :tag "Scheduled previously")))
2687 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
2688 "Text preceeding deadline items in the agenda view.
2689 This is a list with two strings. The first applies when the item has its
2690 deadline on the current day. The second applies when it is in the past or
2691 in the future, it may contain %d to capture how many days away the deadline
2692 is (was)."
2693 :group 'org-agenda-line-format
2694 :type '(list
2695 (string :tag "Deadline today ")
2696 (string :tag "Deadline relative")))
2698 (defcustom org-agenda-remove-times-when-in-prefix t
2699 "Non-nil means, remove duplicate time specifications in agenda items.
2700 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2701 time-of-day specification in a headline or diary entry is extracted and
2702 placed into the prefix. If this option is non-nil, the original specification
2703 \(a timestamp or -range, or just a plain time(range) specification like
2704 11:30-4pm) will be removed for agenda display. This makes the agenda less
2705 cluttered.
2706 The option can be t or nil. It may also be the symbol `beg', indicating
2707 that the time should only be removed what it is located at the beginning of
2708 the headline/diary entry."
2709 :group 'org-agenda-line-format
2710 :type '(choice
2711 (const :tag "Always" t)
2712 (const :tag "Never" nil)
2713 (const :tag "When at beginning of entry" beg)))
2716 (defcustom org-agenda-default-appointment-duration nil
2717 "Default duration for appointments that only have a starting time.
2718 When nil, no duration is specified in such cases.
2719 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
2720 :group 'org-agenda-line-format
2721 :type '(choice
2722 (integer :tag "Minutes")
2723 (const :tag "No default duration")))
2726 (defcustom org-agenda-remove-tags nil
2727 "Non-nil means, remove the tags from the headline copy in the agenda.
2728 When this is the symbol `prefix', only remove tags when
2729 `org-agenda-prefix-format' contains a `%T' specifier."
2730 :group 'org-agenda-line-format
2731 :type '(choice
2732 (const :tag "Always" t)
2733 (const :tag "Never" nil)
2734 (const :tag "When prefix format contains %T" prefix)))
2736 (if (fboundp 'defvaralias)
2737 (defvaralias 'org-agenda-remove-tags-when-in-prefix
2738 'org-agenda-remove-tags))
2740 (defcustom org-agenda-tags-column -80
2741 "Shift tags in agenda items to this column.
2742 If this number is positive, it specifies the column. If it is negative,
2743 it means that the tags should be flushright to that column. For example,
2744 -80 works well for a normal 80 character screen."
2745 :group 'org-agenda-line-format
2746 :type 'integer)
2748 (if (fboundp 'defvaralias)
2749 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
2751 (defcustom org-agenda-fontify-priorities t
2752 "Non-nil means, highlight low and high priorities in agenda.
2753 When t, the highest priority entries are bold, lowest priority italic.
2754 This may also be an association list of priority faces. The face may be
2755 a names face, or a list like `(:background \"Red\")'."
2756 :group 'org-agenda-line-format
2757 :type '(choice
2758 (const :tag "Never" nil)
2759 (const :tag "Defaults" t)
2760 (repeat :tag "Specify"
2761 (list (character :tag "Priority" :value ?A)
2762 (sexp :tag "face")))))
2764 (defgroup org-latex nil
2765 "Options for embedding LaTeX code into Org-mode"
2766 :tag "Org LaTeX"
2767 :group 'org)
2769 (defcustom org-format-latex-options
2770 '(:foreground default :background default :scale 1.0
2771 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2772 :matchers ("begin" "$" "$$" "\\(" "\\["))
2773 "Options for creating images from LaTeX fragments.
2774 This is a property list with the following properties:
2775 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
2776 `default' means use the forground of the default face.
2777 :background the background color, or \"Transparent\".
2778 `default' means use the background of the default face.
2779 :scale a scaling factor for the size of the images
2780 :html-foreground, :html-background, :html-scale
2781 The same numbers for HTML export.
2782 :matchers a list indicating which matchers should be used to
2783 find LaTeX fragments. Valid members of this list are:
2784 \"begin\" find environments
2785 \"$\" find math expressions surrounded by $...$
2786 \"$$\" find math expressions surrounded by $$....$$
2787 \"\\(\" find math expressions surrounded by \\(...\\)
2788 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2789 :group 'org-latex
2790 :type 'plist)
2792 (defcustom org-format-latex-header "\\documentclass{article}
2793 \\usepackage{fullpage} % do not remove
2794 \\usepackage{amssymb}
2795 \\usepackage[usenames]{color}
2796 \\usepackage{amsmath}
2797 \\usepackage{latexsym}
2798 \\usepackage[mathscr]{eucal}
2799 \\pagestyle{empty} % do not remove"
2800 "The document header used for processing LaTeX fragments."
2801 :group 'org-latex
2802 :type 'string)
2804 (defgroup org-export nil
2805 "Options for exporting org-listings."
2806 :tag "Org Export"
2807 :group 'org)
2809 (defgroup org-export-general nil
2810 "General options for exporting Org-mode files."
2811 :tag "Org Export General"
2812 :group 'org-export)
2814 (defcustom org-export-publishing-directory "."
2815 "Path to the location where exported files should be located.
2816 This path may be relative to the directory where the Org-mode file lives.
2817 The default is to put them into the same directory as the Org-mode file.
2818 The variable may also be an alist with export types `:html', `:ascii',
2819 `:ical', `:LaTeX', or `:xoxo' and the corresponding directories.
2820 If a directory path is relative, it is interpreted relative to the
2821 directory where the exported Org-mode files lives."
2822 :group 'org-export-general
2823 :type '(choice
2824 (directory)
2825 (repeat
2826 (cons
2827 (choice :tag "Type"
2828 (const :html) (const :LaTeX)
2829 (const :ascii) (const :ical) (const :xoxo))
2830 (directory)))))
2832 (defcustom org-export-language-setup
2833 '(("en" "Author" "Date" "Table of Contents")
2834 ("cs" "Autor" "Datum" "Obsah")
2835 ("da" "Ophavsmand" "Dato" "Indhold")
2836 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
2837 ("es" "Autor" "Fecha" "\xcdndice")
2838 ("fr" "Auteur" "Date" "Table des mati\xe8res")
2839 ("it" "Autore" "Data" "Indice")
2840 ("nl" "Auteur" "Datum" "Inhoudsopgave")
2841 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
2842 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
2843 "Terms used in export text, translated to different languages.
2844 Use the variable `org-export-default-language' to set the language,
2845 or use the +OPTION lines for a per-file setting."
2846 :group 'org-export-general
2847 :type '(repeat
2848 (list
2849 (string :tag "HTML language tag")
2850 (string :tag "Author")
2851 (string :tag "Date")
2852 (string :tag "Table of Contents"))))
2854 (defcustom org-export-default-language "en"
2855 "The default language of HTML export, as a string.
2856 This should have an association in `org-export-language-setup'."
2857 :group 'org-export-general
2858 :type 'string)
2860 (defcustom org-export-skip-text-before-1st-heading t
2861 "Non-nil means, skip all text before the first headline when exporting.
2862 When nil, that text is exported as well."
2863 :group 'org-export-general
2864 :type 'boolean)
2866 (defcustom org-export-headline-levels 3
2867 "The last level which is still exported as a headline.
2868 Inferior levels will produce itemize lists when exported.
2869 Note that a numeric prefix argument to an exporter function overrides
2870 this setting.
2872 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
2873 :group 'org-export-general
2874 :type 'number)
2876 (defcustom org-export-with-section-numbers t
2877 "Non-nil means, add section numbers to headlines when exporting.
2879 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
2880 :group 'org-export-general
2881 :type 'boolean)
2883 (defcustom org-export-with-toc t
2884 "Non-nil means, create a table of contents in exported files.
2885 The TOC contains headlines with levels up to`org-export-headline-levels'.
2886 When an integer, include levels up to N in the toc, this may then be
2887 different from `org-export-headline-levels', but it will not be allowed
2888 to be larger than the number of headline levels.
2889 When nil, no table of contents is made.
2891 Headlines which contain any TODO items will be marked with \"(*)\" in
2892 ASCII export, and with red color in HTML output, if the option
2893 `org-export-mark-todo-in-toc' is set.
2895 In HTML output, the TOC will be clickable.
2897 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
2898 or \"toc:3\"."
2899 :group 'org-export-general
2900 :type '(choice
2901 (const :tag "No Table of Contents" nil)
2902 (const :tag "Full Table of Contents" t)
2903 (integer :tag "TOC to level")))
2905 (defcustom org-export-mark-todo-in-toc nil
2906 "Non-nil means, mark TOC lines that contain any open TODO items."
2907 :group 'org-export-general
2908 :type 'boolean)
2910 (defcustom org-export-preserve-breaks nil
2911 "Non-nil means, preserve all line breaks when exporting.
2912 Normally, in HTML output paragraphs will be reformatted. In ASCII
2913 export, line breaks will always be preserved, regardless of this variable.
2915 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
2916 :group 'org-export-general
2917 :type 'boolean)
2919 (defcustom org-export-with-archived-trees 'headline
2920 "Whether subtrees with the ARCHIVE tag should be exported.
2921 This can have three different values
2922 nil Do not export, pretend this tree is not present
2923 t Do export the entire tree
2924 headline Only export the headline, but skip the tree below it."
2925 :group 'org-export-general
2926 :group 'org-archive
2927 :type '(choice
2928 (const :tag "not at all" nil)
2929 (const :tag "headline only" 'headline)
2930 (const :tag "entirely" t)))
2932 (defcustom org-export-author-info t
2933 "Non-nil means, insert author name and email into the exported file.
2935 This option can also be set with the +OPTIONS line,
2936 e.g. \"author-info:nil\"."
2937 :group 'org-export-general
2938 :type 'boolean)
2940 (defcustom org-export-time-stamp-file t
2941 "Non-nil means, insert a time stamp into the exported file.
2942 The time stamp shows when the file was created.
2944 This option can also be set with the +OPTIONS line,
2945 e.g. \"timestamp:nil\"."
2946 :group 'org-export-general
2947 :type 'boolean)
2949 (defcustom org-export-with-timestamps t
2950 "If nil, do not export time stamps and associated keywords."
2951 :group 'org-export-general
2952 :type 'boolean)
2954 (defcustom org-export-remove-timestamps-from-toc t
2955 "If nil, remove timestamps from the table of contents entries."
2956 :group 'org-export-general
2957 :type 'boolean)
2959 (defcustom org-export-with-tags 'not-in-toc
2960 "If nil, do not export tags, just remove them from headlines.
2961 If this is the symbol `not-in-toc', tags will be removed from table of
2962 contents entries, but still be shown in the headlines of the document.
2964 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
2965 :group 'org-export-general
2966 :type '(choice
2967 (const :tag "Off" nil)
2968 (const :tag "Not in TOC" not-in-toc)
2969 (const :tag "On" t)))
2971 (defcustom org-export-with-drawers nil
2972 "Non-nil means, export with drawers like the property drawer.
2973 When t, all drawers are exported. This may also be a list of
2974 drawer names to export."
2975 :group 'org-export-general
2976 :type '(choice
2977 (const :tag "All drawers" t)
2978 (const :tag "None" nil)
2979 (repeat :tag "Selected drawers"
2980 (string :tag "Drawer name"))))
2982 (defgroup org-export-translation nil
2983 "Options for translating special ascii sequences for the export backends."
2984 :tag "Org Export Translation"
2985 :group 'org-export)
2987 (defcustom org-export-with-emphasize t
2988 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
2989 If the export target supports emphasizing text, the word will be
2990 typeset in bold, italic, or underlined, respectively. Works only for
2991 single words, but you can say: I *really* *mean* *this*.
2992 Not all export backends support this.
2994 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
2995 :group 'org-export-translation
2996 :type 'boolean)
2998 (defcustom org-export-with-footnotes t
2999 "If nil, export [1] as a footnote marker.
3000 Lines starting with [1] will be formatted as footnotes.
3002 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3003 :group 'org-export-translation
3004 :type 'boolean)
3006 (defcustom org-export-with-sub-superscripts t
3007 "Non-nil means, interpret \"_\" and \"^\" for export.
3008 When this option is turned on, you can use TeX-like syntax for sub- and
3009 superscripts. Several characters after \"_\" or \"^\" will be
3010 considered as a single item - so grouping with {} is normally not
3011 needed. For example, the following things will be parsed as single
3012 sub- or superscripts.
3014 10^24 or 10^tau several digits will be considered 1 item.
3015 10^-12 or 10^-tau a leading sign with digits or a word
3016 x^2-y^3 will be read as x^2 - y^3, because items are
3017 terminated by almost any nonword/nondigit char.
3018 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3020 Still, ambiguity is possible - so when in doubt use {} to enclose the
3021 sub/superscript. If you set this variable to the symbol `{}',
3022 the braces are *required* in order to trigger interpretations as
3023 sub/superscript. This can be helpful in documents that need \"_\"
3024 frequently in plain text.
3026 Not all export backends support this, but HTML does.
3028 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3029 :group 'org-export-translation
3030 :type '(choice
3031 (const :tag "Always interpret" t)
3032 (const :tag "Only with braces" {})
3033 (const :tag "Never interpret" nil)))
3035 (defcustom org-export-with-TeX-macros t
3036 "Non-nil means, interpret simple TeX-like macros when exporting.
3037 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3038 No only real TeX macros will work here, but the standard HTML entities
3039 for math can be used as macro names as well. For a list of supported
3040 names in HTML export, see the constant `org-html-entities'.
3041 Not all export backends support this.
3043 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3044 :group 'org-export-translation
3045 :group 'org-export-latex
3046 :type 'boolean)
3048 (defcustom org-export-with-LaTeX-fragments nil
3049 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3050 When set, the exporter will find LaTeX environments if the \\begin line is
3051 the first non-white thing on a line. It will also find the math delimiters
3052 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3053 display math.
3055 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3056 :group 'org-export-translation
3057 :group 'org-export-latex
3058 :type 'boolean)
3060 (defcustom org-export-with-fixed-width t
3061 "Non-nil means, lines starting with \":\" will be in fixed width font.
3062 This can be used to have pre-formatted text, fragments of code etc. For
3063 example:
3064 : ;; Some Lisp examples
3065 : (while (defc cnt)
3066 : (ding))
3067 will be looking just like this in also HTML. See also the QUOTE keyword.
3068 Not all export backends support this.
3070 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3071 :group 'org-export-translation
3072 :type 'boolean)
3074 (defcustom org-match-sexp-depth 3
3075 "Number of stacked braces for sub/superscript matching.
3076 This has to be set before loading org.el to be effective."
3077 :group 'org-export-translation
3078 :type 'integer)
3080 (defgroup org-export-tables nil
3081 "Options for exporting tables in Org-mode."
3082 :tag "Org Export Tables"
3083 :group 'org-export)
3085 (defcustom org-export-with-tables t
3086 "If non-nil, lines starting with \"|\" define a table.
3087 For example:
3089 | Name | Address | Birthday |
3090 |-------------+----------+-----------|
3091 | Arthur Dent | England | 29.2.2100 |
3093 Not all export backends support this.
3095 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3096 :group 'org-export-tables
3097 :type 'boolean)
3099 (defcustom org-export-highlight-first-table-line t
3100 "Non-nil means, highlight the first table line.
3101 In HTML export, this means use <th> instead of <td>.
3102 In tables created with table.el, this applies to the first table line.
3103 In Org-mode tables, all lines before the first horizontal separator
3104 line will be formatted with <th> tags."
3105 :group 'org-export-tables
3106 :type 'boolean)
3108 (defcustom org-export-table-remove-special-lines t
3109 "Remove special lines and marking characters in calculating tables.
3110 This removes the special marking character column from tables that are set
3111 up for spreadsheet calculations. It also removes the entire lines
3112 marked with `!', `_', or `^'. The lines with `$' are kept, because
3113 the values of constants may be useful to have."
3114 :group 'org-export-tables
3115 :type 'boolean)
3117 (defcustom org-export-prefer-native-exporter-for-tables nil
3118 "Non-nil means, always export tables created with table.el natively.
3119 Natively means, use the HTML code generator in table.el.
3120 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3121 the table does not use row- or column-spanning). This has the
3122 advantage, that the automatic HTML conversions for math symbols and
3123 sub/superscripts can be applied. Org-mode's HTML generator is also
3124 much faster."
3125 :group 'org-export-tables
3126 :type 'boolean)
3128 (defgroup org-export-ascii nil
3129 "Options specific for ASCII export of Org-mode files."
3130 :tag "Org Export ASCII"
3131 :group 'org-export)
3133 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3134 "Characters for underlining headings in ASCII export.
3135 In the given sequence, these characters will be used for level 1, 2, ..."
3136 :group 'org-export-ascii
3137 :type '(repeat character))
3139 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3140 "Bullet characters for headlines converted to lists in ASCII export.
3141 The first character is is used for the first lest level generated in this
3142 way, and so on. If there are more levels than characters given here,
3143 the list will be repeated.
3144 Note that plain lists will keep the same bullets as the have in the
3145 Org-mode file."
3146 :group 'org-export-ascii
3147 :type '(repeat character))
3149 (defgroup org-export-xml nil
3150 "Options specific for XML export of Org-mode files."
3151 :tag "Org Export XML"
3152 :group 'org-export)
3154 (defgroup org-export-html nil
3155 "Options specific for HTML export of Org-mode files."
3156 :tag "Org Export HTML"
3157 :group 'org-export)
3159 (defcustom org-export-html-coding-system nil
3161 :group 'org-export-html
3162 :type 'coding-system)
3164 (defcustom org-export-html-extension "html"
3165 "The extension for exported HTML files."
3166 :group 'org-export-html
3167 :type 'string)
3169 (defcustom org-export-html-style
3170 "<style type=\"text/css\">
3171 html {
3172 font-family: Times, serif;
3173 font-size: 12pt;
3175 .title { text-align: center; }
3176 .todo { color: red; }
3177 .done { color: green; }
3178 .timestamp { color: grey }
3179 .timestamp-kwd { color: CadetBlue }
3180 .tag { background-color:lightblue; font-weight:normal }
3181 .target { background-color: lavender; }
3182 pre {
3183 border: 1pt solid #AEBDCC;
3184 background-color: #F3F5F7;
3185 padding: 5pt;
3186 font-family: courier, monospace;
3188 table { border-collapse: collapse; }
3189 td, th {
3190 vertical-align: top;
3191 <!--border: 1pt solid #ADB9CC;-->
3193 </style>"
3194 "The default style specification for exported HTML files.
3195 Since there are different ways of setting style information, this variable
3196 needs to contain the full HTML structure to provide a style, including the
3197 surrounding HTML tags. The style specifications should include definitions
3198 for new classes todo, done, title, and deadline. For example, legal values
3199 would be:
3201 <style type=\"text/css\">
3202 p { font-weight: normal; color: gray; }
3203 h1 { color: black; }
3204 .title { text-align: center; }
3205 .todo, .deadline { color: red; }
3206 .done { color: green; }
3207 </style>
3209 or, if you want to keep the style in a file,
3211 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3213 As the value of this option simply gets inserted into the HTML <head> header,
3214 you can \"misuse\" it to add arbitrary text to the header."
3215 :group 'org-export-html
3216 :type 'string)
3219 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3220 "Format for typesetting the document title in HTML export."
3221 :group 'org-export-html
3222 :type 'string)
3224 (defcustom org-export-html-toplevel-hlevel 2
3225 "The <H> level for level 1 headings in HTML export."
3226 :group 'org-export-html
3227 :type 'string)
3229 (defcustom org-export-html-link-org-files-as-html t
3230 "Non-nil means, make file links to `file.org' point to `file.html'.
3231 When org-mode is exporting an org-mode file to HTML, links to
3232 non-html files are directly put into a href tag in HTML.
3233 However, links to other Org-mode files (recognized by the
3234 extension `.org.) should become links to the corresponding html
3235 file, assuming that the linked org-mode file will also be
3236 converted to HTML.
3237 When nil, the links still point to the plain `.org' file."
3238 :group 'org-export-html
3239 :type 'boolean)
3241 (defcustom org-export-html-inline-images 'maybe
3242 "Non-nil means, inline images into exported HTML pages.
3243 This is done using an <img> tag. When nil, an anchor with href is used to
3244 link to the image. If this option is `maybe', then images in links with
3245 an empty description will be inlined, while images with a description will
3246 be linked only."
3247 :group 'org-export-html
3248 :type '(choice (const :tag "Never" nil)
3249 (const :tag "Always" t)
3250 (const :tag "When there is no description" maybe)))
3252 ;; FIXME: rename
3253 (defcustom org-export-html-expand t
3254 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3255 When nil, these tags will be exported as plain text and therefore
3256 not be interpreted by a browser.
3258 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3259 :group 'org-export-html
3260 :type 'boolean)
3262 (defcustom org-export-html-table-tag
3263 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3264 "The HTML tag that is used to start a table.
3265 This must be a <table> tag, but you may change the options like
3266 borders and spacing."
3267 :group 'org-export-html
3268 :type 'string)
3270 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3271 "The opening tag for table header fields.
3272 This is customizable so that alignment options can be specified."
3273 :group 'org-export-tables
3274 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3276 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3277 "The opening tag for table data fields.
3278 This is customizable so that alignment options can be specified."
3279 :group 'org-export-tables
3280 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3282 (defcustom org-export-html-with-timestamp nil
3283 "If non-nil, write `org-export-html-html-helper-timestamp'
3284 into the exported HTML text. Otherwise, the buffer will just be saved
3285 to a file."
3286 :group 'org-export-html
3287 :type 'boolean)
3289 (defcustom org-export-html-html-helper-timestamp
3290 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3291 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3292 :group 'org-export-html
3293 :type 'string)
3295 (defgroup org-export-icalendar nil
3296 "Options specific for iCalendar export of Org-mode files."
3297 :tag "Org Export iCalendar"
3298 :group 'org-export)
3300 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3301 "The file name for the iCalendar file covering all agenda files.
3302 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3303 The file name should be absolute, the file will be overwritten without warning."
3304 :group 'org-export-icalendar
3305 :type 'file)
3307 (defcustom org-icalendar-include-todo nil
3308 "Non-nil means, export to iCalendar files should also cover TODO items."
3309 :group 'org-export-icalendar
3310 :type '(choice
3311 (const :tag "None" nil)
3312 (const :tag "Unfinished" t)
3313 (const :tag "All" all)))
3315 (defcustom org-icalendar-include-sexps t
3316 "Non-nil means, export to iCalendar files should also cover sexp entries.
3317 These are entries like in the diary, but directly in an Org-mode file."
3318 :group 'org-export-icalendar
3319 :type 'boolean)
3321 (defcustom org-icalendar-include-body 100
3322 "Amount of text below headline to be included in iCalendar export.
3323 This is a number of characters that should maximally be included.
3324 Properties, scheduling and clocking lines will always be removed.
3325 The text will be inserted into the DESCRIPTION field."
3326 :group 'org-export-icalendar
3327 :type '(choice
3328 (const :tag "Nothing" nil)
3329 (const :tag "Everything" t)
3330 (integer :tag "Max characters")))
3332 (defcustom org-icalendar-combined-name "OrgMode"
3333 "Calendar name for the combined iCalendar representing all agenda files."
3334 :group 'org-export-icalendar
3335 :type 'string)
3337 (defgroup org-font-lock nil
3338 "Font-lock settings for highlighting in Org-mode."
3339 :tag "Org Font Lock"
3340 :group 'org)
3342 (defcustom org-level-color-stars-only nil
3343 "Non-nil means fontify only the stars in each headline.
3344 When nil, the entire headline is fontified.
3345 Changing it requires restart of `font-lock-mode' to become effective
3346 also in regions already fontified."
3347 :group 'org-font-lock
3348 :type 'boolean)
3350 (defcustom org-hide-leading-stars nil
3351 "Non-nil means, hide the first N-1 stars in a headline.
3352 This works by using the face `org-hide' for these stars. This
3353 face is white for a light background, and black for a dark
3354 background. You may have to customize the face `org-hide' to
3355 make this work.
3356 Changing it requires restart of `font-lock-mode' to become effective
3357 also in regions already fontified.
3358 You may also set this on a per-file basis by adding one of the following
3359 lines to the buffer:
3361 #+STARTUP: hidestars
3362 #+STARTUP: showstars"
3363 :group 'org-font-lock
3364 :type 'boolean)
3366 (defcustom org-fontify-done-headline nil
3367 "Non-nil means, change the face of a headline if it is marked DONE.
3368 Normally, only the TODO/DONE keyword indicates the state of a headline.
3369 When this is non-nil, the headline after the keyword is set to the
3370 `org-headline-done' as an additional indication."
3371 :group 'org-font-lock
3372 :type 'boolean)
3374 (defcustom org-fontify-emphasized-text t
3375 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3376 Changing this variable requires a restart of Emacs to take effect."
3377 :group 'org-font-lock
3378 :type 'boolean)
3380 (defvar org-emph-re nil
3381 "Regular expression for matching emphasis.")
3382 (defvar org-emphasis-regexp-components) ; defined just below
3383 (defvar org-emphasis-alist) ; defined just below
3384 (defun org-set-emph-re (var val)
3385 "Set variable and compute the emphasis regular expression."
3386 (set var val)
3387 (when (and (boundp 'org-emphasis-alist)
3388 (boundp 'org-emphasis-regexp-components)
3389 org-emphasis-alist org-emphasis-regexp-components)
3390 (let* ((e org-emphasis-regexp-components)
3391 (pre (car e))
3392 (post (nth 1 e))
3393 (border (nth 2 e))
3394 (body (nth 3 e))
3395 (nl (nth 4 e))
3396 (stacked (nth 5 e))
3397 (body1 (concat body "*?"))
3398 (markers (mapconcat 'car org-emphasis-alist "")))
3399 ;; make sure special characters appear at the right position in the class
3400 (if (string-match "\\^" markers)
3401 (setq markers (concat (replace-match "" t t markers) "^")))
3402 (if (string-match "-" markers)
3403 (setq markers (concat (replace-match "" t t markers) "-")))
3404 (if (> nl 0)
3405 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3406 (int-to-string nl) "\\}")))
3407 ;; Make the regexp
3408 (setq org-emph-re
3409 (concat "\\([" pre (if stacked markers) "]\\|^\\)"
3410 "\\("
3411 "\\([" markers "]\\)"
3412 "\\("
3413 "[^" border (if (and nil stacked) markers) "]"
3414 body1
3415 "[^" border (if (and nil stacked) markers) "]"
3416 "\\)"
3417 "\\3\\)"
3418 "\\([" post (if stacked markers) "]\\|$\\)")))))
3420 (defcustom org-emphasis-regexp-components
3421 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1 nil)
3422 "Components used to build the reqular expression for emphasis.
3423 This is a list with 6 entries. Terminology: In an emphasis string
3424 like \" *strong word* \", we call the initial space PREMATCH, the final
3425 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3426 and \"trong wor\" is the body. The different components in this variable
3427 specify what is allowed/forbidden in each part:
3429 pre Chars allowed as prematch. Beginning of line will be allowed too.
3430 post Chars allowed as postmatch. End of line will be allowed too.
3431 border The chars *forbidden* as border characters.
3432 body-regexp A regexp like \".\" to match a body character. Don't use
3433 non-shy groups here, and don't allow newline here.
3434 newline The maximum number of newlines allowed in an emphasis exp.
3435 stacked Non-nil means, allow stacked styles. This works only in HTML
3436 export. When this is set, all marker characters (as given in
3437 `org-emphasis-alist') will be allowed as pre/post, aiding
3438 inside-out matching.
3439 Use customize to modify this, or restart Emacs after changing it."
3440 :group 'org-font-lock
3441 :set 'org-set-emph-re
3442 :type '(list
3443 (sexp :tag "Allowed chars in pre ")
3444 (sexp :tag "Allowed chars in post ")
3445 (sexp :tag "Forbidden chars in border ")
3446 (sexp :tag "Regexp for body ")
3447 (integer :tag "number of newlines allowed")
3448 (boolean :tag "Stacking allowed ")))
3450 (defcustom org-emphasis-alist
3451 '(("*" bold "<b>" "</b>")
3452 ("/" italic "<i>" "</i>")
3453 ("_" underline "<u>" "</u>")
3454 ("=" org-code "<code>" "</code>")
3455 ("+" (:strike-through t) "<del>" "</del>")
3457 "Special syntax for emphasized text.
3458 Text starting and ending with a special character will be emphasized, for
3459 example *bold*, _underlined_ and /italic/. This variable sets the marker
3460 characters, the face to be used by font-lock for highlighting in Org-mode
3461 Emacs buffers, and the HTML tags to be used for this.
3462 Use customize to modify this, or restart Emacs after changing it."
3463 :group 'org-font-lock
3464 :set 'org-set-emph-re
3465 :type '(repeat
3466 (list
3467 (string :tag "Marker character")
3468 (choice
3469 (face :tag "Font-lock-face")
3470 (plist :tag "Face property list"))
3471 (string :tag "HTML start tag")
3472 (string :tag "HTML end tag"))))
3474 ;;; The faces
3476 (defgroup org-faces nil
3477 "Faces in Org-mode."
3478 :tag "Org Faces"
3479 :group 'org-font-lock)
3481 (defun org-compatible-face (inherits specs)
3482 "Make a compatible face specification.
3483 If INHERITS is an existing face and if the Emacs version supports it,
3484 just inherit the face. If not, use SPECS to define the face.
3485 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3486 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3487 to the top of the list. The `min-colors' attribute will be removed from
3488 any other entries, and any resulting duplicates will be removed entirely."
3489 (cond
3490 ((and inherits (facep inherits)
3491 (not (featurep 'xemacs)) (> emacs-major-version 22))
3492 ;; In Emacs 23, we use inheritance where possible.
3493 ;; We only do this in Emacs 23, because only there the outline
3494 ;; faces have been changed to the original org-mode-level-faces.
3495 (list (list t :inherit inherits)))
3496 ((or (featurep 'xemacs) (< emacs-major-version 22))
3497 ;; These do not understand the `min-colors' attribute.
3498 (let (r e a)
3499 (while (setq e (pop specs))
3500 (cond
3501 ((memq (car e) '(t default)) (push e r))
3502 ((setq a (member '(min-colors 8) (car e)))
3503 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3504 (cdr e)))))
3505 ((setq a (assq 'min-colors (car e)))
3506 (setq e (cons (delq a (car e)) (cdr e)))
3507 (or (assoc (car e) r) (push e r)))
3508 (t (or (assoc (car e) r) (push e r)))))
3509 (nreverse r)))
3510 (t specs)))
3512 (defface org-hide
3513 '((((background light)) (:foreground "white"))
3514 (((background dark)) (:foreground "black")))
3515 "Face used to hide leading stars in headlines.
3516 The forground color of this face should be equal to the background
3517 color of the frame."
3518 :group 'org-faces)
3520 (defface org-level-1 ;; font-lock-function-name-face
3521 (org-compatible-face
3522 'outline-1
3523 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3524 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3525 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3526 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3527 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3528 (t (:bold t))))
3529 "Face used for level 1 headlines."
3530 :group 'org-faces)
3532 (defface org-level-2 ;; font-lock-variable-name-face
3533 (org-compatible-face
3534 'outline-2
3535 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3536 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3537 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3538 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3539 (t (:bold t))))
3540 "Face used for level 2 headlines."
3541 :group 'org-faces)
3543 (defface org-level-3 ;; font-lock-keyword-face
3544 (org-compatible-face
3545 'outline-3
3546 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3547 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3548 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3549 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3550 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3551 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3552 (t (:bold t))))
3553 "Face used for level 3 headlines."
3554 :group 'org-faces)
3556 (defface org-level-4 ;; font-lock-comment-face
3557 (org-compatible-face
3558 'outline-4
3559 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3560 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3561 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3562 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3563 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3564 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3565 (t (:bold t))))
3566 "Face used for level 4 headlines."
3567 :group 'org-faces)
3569 (defface org-level-5 ;; font-lock-type-face
3570 (org-compatible-face
3571 'outline-5
3572 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3573 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3574 (((class color) (min-colors 8)) (:foreground "green"))))
3575 "Face used for level 5 headlines."
3576 :group 'org-faces)
3578 (defface org-level-6 ;; font-lock-constant-face
3579 (org-compatible-face
3580 'outline-6
3581 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3582 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3583 (((class color) (min-colors 8)) (:foreground "magenta"))))
3584 "Face used for level 6 headlines."
3585 :group 'org-faces)
3587 (defface org-level-7 ;; font-lock-builtin-face
3588 (org-compatible-face
3589 'outline-7
3590 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3591 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3592 (((class color) (min-colors 8)) (:foreground "blue"))))
3593 "Face used for level 7 headlines."
3594 :group 'org-faces)
3596 (defface org-level-8 ;; font-lock-string-face
3597 (org-compatible-face
3598 'outline-8
3599 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3600 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3601 (((class color) (min-colors 8)) (:foreground "green"))))
3602 "Face used for level 8 headlines."
3603 :group 'org-faces)
3605 (defface org-special-keyword ;; font-lock-string-face
3606 (org-compatible-face
3608 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3609 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3610 (t (:italic t))))
3611 "Face used for special keywords."
3612 :group 'org-faces)
3614 (defface org-drawer ;; font-lock-function-name-face
3615 (org-compatible-face
3617 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3618 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3619 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3620 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3621 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3622 (t (:bold t))))
3623 "Face used for drawers."
3624 :group 'org-faces)
3626 (defface org-property-value nil
3627 "Face used for the value of a property."
3628 :group 'org-faces)
3630 (defface org-column
3631 (org-compatible-face
3633 '((((class color) (min-colors 16) (background light))
3634 (:background "grey90"))
3635 (((class color) (min-colors 16) (background dark))
3636 (:background "grey30"))
3637 (((class color) (min-colors 8))
3638 (:background "cyan" :foreground "black"))
3639 (t (:inverse-video t))))
3640 "Face for column display of entry properties."
3641 :group 'org-faces)
3643 (when (fboundp 'set-face-attribute)
3644 ;; Make sure that a fixed-width face is used when we have a column table.
3645 (set-face-attribute 'org-column nil
3646 :height (face-attribute 'default :height)
3647 :family (face-attribute 'default :family)))
3649 (defface org-warning
3650 (org-compatible-face
3651 'font-lock-warning-face
3652 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3653 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3654 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3655 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3656 (t (:bold t))))
3657 "Face for deadlines and TODO keywords."
3658 :group 'org-faces)
3660 (defface org-archived ; similar to shadow
3661 (org-compatible-face
3662 'shadow
3663 '((((class color grayscale) (min-colors 88) (background light))
3664 (:foreground "grey50"))
3665 (((class color grayscale) (min-colors 88) (background dark))
3666 (:foreground "grey70"))
3667 (((class color) (min-colors 8) (background light))
3668 (:foreground "green"))
3669 (((class color) (min-colors 8) (background dark))
3670 (:foreground "yellow"))))
3671 "Face for headline with the ARCHIVE tag."
3672 :group 'org-faces)
3674 (defface org-link
3675 '((((class color) (background light)) (:foreground "Purple" :underline t))
3676 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3677 (t (:underline t)))
3678 "Face for links."
3679 :group 'org-faces)
3681 (defface org-ellipsis
3682 '((((class color) (background light)) (:foreground "DarkGoldenrod" :strike-through t))
3683 (((class color) (background dark)) (:foreground "LightGoldenrod" :strike-through t))
3684 (t (:strike-through t)))
3685 "Face for the ellipsis in folded text."
3686 :group 'org-faces)
3688 (defface org-target
3689 '((((class color) (background light)) (:underline t))
3690 (((class color) (background dark)) (:underline t))
3691 (t (:underline t)))
3692 "Face for links."
3693 :group 'org-faces)
3695 (defface org-date
3696 '((((class color) (background light)) (:foreground "Purple" :underline t))
3697 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3698 (t (:underline t)))
3699 "Face for links."
3700 :group 'org-faces)
3702 (defface org-sexp-date
3703 '((((class color) (background light)) (:foreground "Purple"))
3704 (((class color) (background dark)) (:foreground "Cyan"))
3705 (t (:underline t)))
3706 "Face for links."
3707 :group 'org-faces)
3709 (defface org-tag
3710 '((t (:bold t)))
3711 "Face for tags."
3712 :group 'org-faces)
3714 (defface org-todo ; font-lock-warning-face
3715 (org-compatible-face
3717 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3718 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3719 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3720 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3721 (t (:inverse-video t :bold t))))
3722 "Face for TODO keywords."
3723 :group 'org-faces)
3725 (defface org-done ;; font-lock-type-face
3726 (org-compatible-face
3728 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
3729 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
3730 (((class color) (min-colors 8)) (:foreground "green"))
3731 (t (:bold t))))
3732 "Face used for todo keywords that indicate DONE items."
3733 :group 'org-faces)
3735 (defface org-headline-done ;; font-lock-string-face
3736 (org-compatible-face
3738 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3739 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3740 (((class color) (min-colors 8) (background light)) (:bold nil))))
3741 "Face used to indicate that a headline is DONE.
3742 This face is only used if `org-fontify-done-headline' is set. If applies
3743 to the part of the headline after the DONE keyword."
3744 :group 'org-faces)
3746 (defcustom org-todo-keyword-faces nil
3747 "Faces for specific TODO keywords.
3748 This is a list of cons cells, with TODO keywords in the car
3749 and faces in the cdr. The face can be a symbol, or a property
3750 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
3751 :group 'org-faces
3752 :group 'org-todo
3753 :type '(repeat
3754 (cons
3755 (string :tag "keyword")
3756 (sexp :tag "face"))))
3758 (defface org-table ;; font-lock-function-name-face
3759 (org-compatible-face
3761 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3762 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3763 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3764 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3765 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
3766 (((class color) (min-colors 8) (background dark)))))
3767 "Face used for tables."
3768 :group 'org-faces)
3770 (defface org-formula
3771 (org-compatible-face
3773 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3774 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3775 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3776 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
3777 (t (:bold t :italic t))))
3778 "Face for formulas."
3779 :group 'org-faces)
3781 (defface org-code
3782 (org-compatible-face
3784 '((((class color grayscale) (min-colors 88) (background light))
3785 (:foreground "grey50"))
3786 (((class color grayscale) (min-colors 88) (background dark))
3787 (:foreground "grey70"))
3788 (((class color) (min-colors 8) (background light))
3789 (:foreground "green"))
3790 (((class color) (min-colors 8) (background dark))
3791 (:foreground "yellow"))))
3792 "Face for fixed-with text like code snippets."
3793 :group 'org-faces
3794 :version "22.1")
3796 (defface org-agenda-structure ;; font-lock-function-name-face
3797 (org-compatible-face
3799 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3800 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3801 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3802 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3803 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3804 (t (:bold t))))
3805 "Face used in agenda for captions and dates."
3806 :group 'org-faces)
3808 (defface org-scheduled-today
3809 (org-compatible-face
3811 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
3812 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
3813 (((class color) (min-colors 8)) (:foreground "green"))
3814 (t (:bold t :italic t))))
3815 "Face for items scheduled for a certain day."
3816 :group 'org-faces)
3818 (defface org-scheduled-previously
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 (defface org-upcoming-deadline
3830 (org-compatible-face
3832 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3833 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3834 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3835 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3836 (t (:bold t))))
3837 "Face for items scheduled previously, and not yet done."
3838 :group 'org-faces)
3840 (defcustom org-agenda-deadline-faces
3841 '((1.0 . org-warning)
3842 (0.5 . org-upcoming-deadline)
3843 (0.0 . default))
3844 "Faces for showing deadlines in the agenda.
3845 This is a list of cons cells. The cdr of each cess is a face to be used,
3846 and it can also just be a like like '(:foreground \"yellow\").
3847 Each car is a fraction of the head-warning time that must have passed for
3848 this the face in the cdr to be used for display. The numbers must be
3849 given in descending order. The head-warning time is normally taken
3850 from `org-deadline-warning-days', but can also be specified in the deadline
3851 timestamp itself, like this:
3853 DEADLINE: <2007-08-13 Mon -8d>
3855 You may use d for days, w for weeks, m for months and y for years. Months
3856 and years will only be treated in an approximate fashion (30.4 days for a
3857 month and 365.24 days for a year)."
3858 :group 'org-faces
3859 :group 'org-agenda-daily/weekly
3860 :type '(repeat
3861 (cons
3862 (number :tag "Fraction of head-warning time passed")
3863 (sexp :tag "Face"))))
3865 (defface org-time-grid ;; font-lock-variable-name-face
3866 (org-compatible-face
3868 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3869 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3870 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
3871 "Face used for time grids."
3872 :group 'org-faces)
3874 (defconst org-level-faces
3875 '(org-level-1 org-level-2 org-level-3 org-level-4
3876 org-level-5 org-level-6 org-level-7 org-level-8
3879 (defcustom org-n-level-faces (length org-level-faces)
3880 "The number different faces to be used for headlines.
3881 Org-mode defines 8 different headline faces, so this can be at most 8.
3882 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
3883 :type 'number
3884 :group 'org-faces)
3886 ;;; Variables for pre-computed regular expressions, all buffer local
3888 (defvar org-drawer-regexp nil
3889 "Matches first line of a hidden block.")
3890 (make-variable-buffer-local 'org-drawer-regexp)
3891 (defvar org-todo-regexp nil
3892 "Matches any of the TODO state keywords.")
3893 (make-variable-buffer-local 'org-todo-regexp)
3894 (defvar org-not-done-regexp nil
3895 "Matches any of the TODO state keywords except the last one.")
3896 (make-variable-buffer-local 'org-not-done-regexp)
3897 (defvar org-todo-line-regexp nil
3898 "Matches a headline and puts TODO state into group 2 if present.")
3899 (make-variable-buffer-local 'org-todo-line-regexp)
3900 (defvar org-complex-heading-regexp nil
3901 "Matches a headline and puts everything into groups:
3902 group 1: the stars
3903 group 2: The todo keyword, maybe
3904 group 3: Priority cookie
3905 group 4: True headline
3906 group 5: Tags")
3907 (make-variable-buffer-local 'org-complex-heading-regexp)
3908 (defvar org-todo-line-tags-regexp nil
3909 "Matches a headline and puts TODO state into group 2 if present.
3910 Also put tags into group 4 if tags are present.")
3911 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3912 (defvar org-nl-done-regexp nil
3913 "Matches newline followed by a headline with the DONE keyword.")
3914 (make-variable-buffer-local 'org-nl-done-regexp)
3915 (defvar org-looking-at-done-regexp nil
3916 "Matches the DONE keyword a point.")
3917 (make-variable-buffer-local 'org-looking-at-done-regexp)
3918 (defvar org-ds-keyword-length 12
3919 "Maximum length of the Deadline and SCHEDULED keywords.")
3920 (make-variable-buffer-local 'org-ds-keyword-length)
3921 (defvar org-deadline-regexp nil
3922 "Matches the DEADLINE keyword.")
3923 (make-variable-buffer-local 'org-deadline-regexp)
3924 (defvar org-deadline-time-regexp nil
3925 "Matches the DEADLINE keyword together with a time stamp.")
3926 (make-variable-buffer-local 'org-deadline-time-regexp)
3927 (defvar org-deadline-line-regexp nil
3928 "Matches the DEADLINE keyword and the rest of the line.")
3929 (make-variable-buffer-local 'org-deadline-line-regexp)
3930 (defvar org-scheduled-regexp nil
3931 "Matches the SCHEDULED keyword.")
3932 (make-variable-buffer-local 'org-scheduled-regexp)
3933 (defvar org-scheduled-time-regexp nil
3934 "Matches the SCHEDULED keyword together with a time stamp.")
3935 (make-variable-buffer-local 'org-scheduled-time-regexp)
3936 (defvar org-closed-time-regexp nil
3937 "Matches the CLOSED keyword together with a time stamp.")
3938 (make-variable-buffer-local 'org-closed-time-regexp)
3940 (defvar org-keyword-time-regexp nil
3941 "Matches any of the 4 keywords, together with the time stamp.")
3942 (make-variable-buffer-local 'org-keyword-time-regexp)
3943 (defvar org-keyword-time-not-clock-regexp nil
3944 "Matches any of the 3 keywords, together with the time stamp.")
3945 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3946 (defvar org-maybe-keyword-time-regexp nil
3947 "Matches a timestamp, possibly preceeded by a keyword.")
3948 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3949 (defvar org-planning-or-clock-line-re nil
3950 "Matches a line with planning or clock info.")
3951 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3953 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
3954 rear-nonsticky t mouse-map t fontified t)
3955 "Properties to remove when a string without properties is wanted.")
3957 (defsubst org-match-string-no-properties (num &optional string)
3958 (if (featurep 'xemacs)
3959 (let ((s (match-string num string)))
3960 (remove-text-properties 0 (length s) org-rm-props s)
3962 (match-string-no-properties num string)))
3964 (defsubst org-no-properties (s)
3965 (if (fboundp 'set-text-properties)
3966 (set-text-properties 0 (length s) nil s)
3967 (remove-text-properties 0 (length s) org-rm-props s))
3970 (defsubst org-get-alist-option (option key)
3971 (cond ((eq key t) t)
3972 ((eq option t) t)
3973 ((assoc key option) (cdr (assoc key option)))
3974 (t (cdr (assq 'default option)))))
3976 (defsubst org-inhibit-invisibility ()
3977 "Modified `buffer-invisibility-spec' for Emacs 21.
3978 Some ops with invisible text do not work correctly on Emacs 21. For these
3979 we turn off invisibility temporarily. Use this in a `let' form."
3980 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
3982 (defsubst org-set-local (var value)
3983 "Make VAR local in current buffer and set it to VALUE."
3984 (set (make-variable-buffer-local var) value))
3986 (defsubst org-mode-p ()
3987 "Check if the current buffer is in Org-mode."
3988 (eq major-mode 'org-mode))
3990 (defsubst org-last (list)
3991 "Return the last element of LIST."
3992 (car (last list)))
3994 (defun org-let (list &rest body)
3995 (eval (cons 'let (cons list body))))
3996 (put 'org-let 'lisp-indent-function 1)
3998 (defun org-let2 (list1 list2 &rest body)
3999 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4000 (put 'org-let2 'lisp-indent-function 2)
4001 (defconst org-startup-options
4002 '(("fold" org-startup-folded t)
4003 ("overview" org-startup-folded t)
4004 ("nofold" org-startup-folded nil)
4005 ("showall" org-startup-folded nil)
4006 ("content" org-startup-folded content)
4007 ("hidestars" org-hide-leading-stars t)
4008 ("showstars" org-hide-leading-stars nil)
4009 ("odd" org-odd-levels-only t)
4010 ("oddeven" org-odd-levels-only nil)
4011 ("align" org-startup-align-all-tables t)
4012 ("noalign" org-startup-align-all-tables nil)
4013 ("customtime" org-display-custom-times t)
4014 ("logging" org-log-done t)
4015 ("logdone" org-log-done t)
4016 ("nologging" org-log-done nil)
4017 ("lognotedone" org-log-done done push)
4018 ("lognotestate" org-log-done state push)
4019 ("lognoteclock-out" org-log-done clock-out push)
4020 ("logrepeat" org-log-repeat t)
4021 ("nologrepeat" org-log-repeat nil)
4022 ("constcgs" constants-unit-system cgs)
4023 ("constSI" constants-unit-system SI))
4024 "Variable associated with STARTUP options for org-mode.
4025 Each element is a list of three items: The startup options as written
4026 in the #+STARTUP line, the corresponding variable, and the value to
4027 set this variable to if the option is found. An optional forth element PUSH
4028 means to push this value onto the list in the variable.")
4030 (defun org-set-regexps-and-options ()
4031 "Precompute regular expressions for current buffer."
4032 (when (org-mode-p)
4033 (org-set-local 'org-todo-kwd-alist nil)
4034 (org-set-local 'org-todo-key-alist nil)
4035 (org-set-local 'org-todo-key-trigger nil)
4036 (org-set-local 'org-todo-keywords-1 nil)
4037 (org-set-local 'org-done-keywords nil)
4038 (org-set-local 'org-todo-heads nil)
4039 (org-set-local 'org-todo-sets nil)
4040 (org-set-local 'org-todo-log-states nil)
4041 (let ((re (org-make-options-regexp
4042 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4043 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4044 "CONSTANTS" "PROPERTY" "DRAWERS")))
4045 (splitre "[ \t]+")
4046 kwds kws0 kwsa key value cat arch tags const links hw dws
4047 tail sep kws1 prio props drawers
4048 ex log)
4049 (save-excursion
4050 (save-restriction
4051 (widen)
4052 (goto-char (point-min))
4053 (while (re-search-forward re nil t)
4054 (setq key (match-string 1) value (org-match-string-no-properties 2))
4055 (cond
4056 ((equal key "CATEGORY")
4057 (if (string-match "[ \t]+$" value)
4058 (setq value (replace-match "" t t value)))
4059 (setq cat (intern value)))
4060 ((member key '("SEQ_TODO" "TODO"))
4061 (push (cons 'sequence (org-split-string value splitre)) kwds))
4062 ((equal key "TYP_TODO")
4063 (push (cons 'type (org-split-string value splitre)) kwds))
4064 ((equal key "TAGS")
4065 (setq tags (append tags (org-split-string value splitre))))
4066 ((equal key "COLUMNS")
4067 (org-set-local 'org-columns-default-format value))
4068 ((equal key "LINK")
4069 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4070 (push (cons (match-string 1 value)
4071 (org-trim (match-string 2 value)))
4072 links)))
4073 ((equal key "PRIORITIES")
4074 (setq prio (org-split-string value " +")))
4075 ((equal key "PROPERTY")
4076 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4077 (push (cons (match-string 1 value) (match-string 2 value))
4078 props)))
4079 ((equal key "DRAWERS")
4080 (setq drawers (org-split-string value splitre)))
4081 ((equal key "CONSTANTS")
4082 (setq const (append const (org-split-string value splitre))))
4083 ((equal key "STARTUP")
4084 (let ((opts (org-split-string value splitre))
4085 l var val)
4086 (while (setq l (pop opts))
4087 (when (setq l (assoc l org-startup-options))
4088 (setq var (nth 1 l) val (nth 2 l))
4089 (if (not (nth 3 l))
4090 (set (make-local-variable var) val)
4091 (if (not (listp (symbol-value var)))
4092 (set (make-local-variable var) nil))
4093 (set (make-local-variable var) (symbol-value var))
4094 (add-to-list var val))))))
4095 ((equal key "ARCHIVE")
4096 (string-match " *$" value)
4097 (setq arch (replace-match "" t t value))
4098 (remove-text-properties 0 (length arch)
4099 '(face t fontified t) arch)))
4101 (and cat (org-set-local 'org-category cat))
4102 (when prio
4103 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4104 (setq prio (mapcar 'string-to-char prio))
4105 (org-set-local 'org-highest-priority (nth 0 prio))
4106 (org-set-local 'org-lowest-priority (nth 1 prio))
4107 (org-set-local 'org-default-priority (nth 2 prio)))
4108 (and props (org-set-local 'org-local-properties (nreverse props)))
4109 (and drawers (org-set-local 'org-drawers drawers))
4110 (and arch (org-set-local 'org-archive-location arch))
4111 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4112 ;; Process the TODO keywords
4113 (unless kwds
4114 ;; Use the global values as if they had been given locally.
4115 (setq kwds (default-value 'org-todo-keywords))
4116 (if (stringp (car kwds))
4117 (setq kwds (list (cons org-todo-interpretation
4118 (default-value 'org-todo-keywords)))))
4119 (setq kwds (reverse kwds)))
4120 (setq kwds (nreverse kwds))
4121 (let (inter kws kw)
4122 (while (setq kws (pop kwds))
4123 (setq inter (pop kws) sep (member "|" kws)
4124 kws0 (delete "|" (copy-sequence kws))
4125 kwsa nil
4126 kws1 (mapcar
4127 (lambda (x)
4128 (if (string-match "^\\(.*?\\)\\(?:(\\(..?\\))\\)?$" x)
4129 (progn
4130 (setq kw (match-string 1 x)
4131 ex (and (match-end 2) (match-string 2 x))
4132 log (and ex (string-match "@" ex))
4133 key (and ex (substring ex 0 1)))
4134 (if (equal key "@") (setq key nil))
4135 (push (cons kw (and key (string-to-char key))) kwsa)
4136 (and log (push kw org-todo-log-states))
4138 (error "Invalid TODO keyword %s" x)))
4139 kws0)
4140 kwsa (if kwsa (append '((:startgroup))
4141 (nreverse kwsa)
4142 '((:endgroup))))
4143 hw (car kws1)
4144 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4145 tail (list inter hw (car dws) (org-last dws)))
4146 (add-to-list 'org-todo-heads hw 'append)
4147 (push kws1 org-todo-sets)
4148 (setq org-done-keywords (append org-done-keywords dws nil))
4149 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4150 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4151 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4152 (setq org-todo-sets (nreverse org-todo-sets)
4153 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4154 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4155 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4156 ;; Process the constants
4157 (when const
4158 (let (e cst)
4159 (while (setq e (pop const))
4160 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4161 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4162 (setq org-table-formula-constants-local cst)))
4164 ;; Process the tags.
4165 (when tags
4166 (let (e tgs)
4167 (while (setq e (pop tags))
4168 (cond
4169 ((equal e "{") (push '(:startgroup) tgs))
4170 ((equal e "}") (push '(:endgroup) tgs))
4171 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4172 (push (cons (match-string 1 e)
4173 (string-to-char (match-string 2 e)))
4174 tgs))
4175 (t (push (list e) tgs))))
4176 (org-set-local 'org-tag-alist nil)
4177 (while (setq e (pop tgs))
4178 (or (and (stringp (car e))
4179 (assoc (car e) org-tag-alist))
4180 (push e org-tag-alist))))))
4182 ;; Compute the regular expressions and other local variables
4183 (if (not org-done-keywords)
4184 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4185 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4186 (length org-scheduled-string)))
4187 org-drawer-regexp
4188 (concat "^[ \t]*:\\("
4189 (mapconcat 'regexp-quote org-drawers "\\|")
4190 "\\):[ \t]*$")
4191 org-not-done-keywords
4192 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4193 org-todo-regexp
4194 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4195 "\\|") "\\)\\>")
4196 org-not-done-regexp
4197 (concat "\\<\\("
4198 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4199 "\\)\\>")
4200 org-todo-line-regexp
4201 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4202 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4203 "\\)\\>\\)?[ \t]*\\(.*\\)")
4204 org-complex-heading-regexp
4205 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4206 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4207 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4208 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4209 org-nl-done-regexp
4210 (concat "\n\\*+[ \t]+"
4211 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4212 "\\)" "\\>")
4213 org-todo-line-tags-regexp
4214 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4215 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4216 (org-re
4217 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4218 org-looking-at-done-regexp
4219 (concat "^" "\\(?:"
4220 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4221 "\\>")
4222 org-deadline-regexp (concat "\\<" org-deadline-string)
4223 org-deadline-time-regexp
4224 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4225 org-deadline-line-regexp
4226 (concat "\\<\\(" org-deadline-string "\\).*")
4227 org-scheduled-regexp
4228 (concat "\\<" org-scheduled-string)
4229 org-scheduled-time-regexp
4230 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4231 org-closed-time-regexp
4232 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4233 org-keyword-time-regexp
4234 (concat "\\<\\(" org-scheduled-string
4235 "\\|" org-deadline-string
4236 "\\|" org-closed-string
4237 "\\|" org-clock-string "\\)"
4238 " *[[<]\\([^]>]+\\)[]>]")
4239 org-keyword-time-not-clock-regexp
4240 (concat "\\<\\(" org-scheduled-string
4241 "\\|" org-deadline-string
4242 "\\|" org-closed-string
4243 "\\)"
4244 " *[[<]\\([^]>]+\\)[]>]")
4245 org-maybe-keyword-time-regexp
4246 (concat "\\(\\<\\(" org-scheduled-string
4247 "\\|" org-deadline-string
4248 "\\|" org-closed-string
4249 "\\|" org-clock-string "\\)\\)?"
4250 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4251 org-planning-or-clock-line-re
4252 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4253 "\\|" org-deadline-string
4254 "\\|" org-closed-string "\\|" org-clock-string
4255 "\\)\\>\\)")
4258 (org-set-font-lock-defaults)))
4260 (defun org-remove-keyword-keys (list)
4261 (mapcar (lambda (x)
4262 (if (string-match "(..?)$" x)
4263 (substring x 0 (match-beginning 0))
4265 list))
4267 ;;; Some variables ujsed in various places
4269 (defvar org-window-configuration nil
4270 "Used in various places to store a window configuration.")
4271 (defvar org-finish-function nil
4272 "Function to be called when `C-c C-c' is used.
4273 This is for getting out of special buffers like remember.")
4275 ;;; Foreign variables, to inform the compiler
4277 ;; XEmacs only
4278 (defvar outline-mode-menu-heading)
4279 (defvar outline-mode-menu-show)
4280 (defvar outline-mode-menu-hide)
4281 (defvar zmacs-regions) ; XEmacs regions
4282 ;; Emacs only
4283 (defvar mark-active)
4285 ;; Packages that org-mode interacts with
4286 (defvar calc-embedded-close-formula)
4287 (defvar calc-embedded-open-formula)
4288 (defvar font-lock-unfontify-region-function)
4289 (defvar org-goto-start-pos)
4290 (defvar vm-message-pointer)
4291 (defvar vm-folder-directory)
4292 (defvar wl-summary-buffer-elmo-folder)
4293 (defvar wl-summary-buffer-folder-name)
4294 (defvar gnus-other-frame-object)
4295 (defvar gnus-group-name)
4296 (defvar gnus-article-current)
4297 (defvar w3m-current-url)
4298 (defvar w3m-current-title)
4299 (defvar mh-progs)
4300 (defvar mh-current-folder)
4301 (defvar mh-show-folder-buffer)
4302 (defvar mh-index-folder)
4303 (defvar mh-searcher)
4304 (defvar calendar-mode-map)
4305 (defvar Info-current-file)
4306 (defvar Info-current-node)
4307 (defvar texmathp-why)
4308 (defvar remember-save-after-remembering)
4309 (defvar remember-data-file)
4310 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
4311 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
4312 (defvar org-latex-regexps)
4313 (defvar constants-unit-system)
4315 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4317 ;; FIXME: Occasionally check by commenting these, to make sure
4318 ;; no other functions uses these, forgetting to let-bind them.
4319 (defvar entry)
4320 (defvar state)
4321 (defvar last-state)
4322 (defvar date)
4323 (defvar description)
4326 ;; Defined somewhere in this file, but used before definition.
4327 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4328 (defvar org-agenda-buffer-name)
4329 (defvar org-agenda-undo-list)
4330 (defvar org-agenda-pending-undo-list)
4331 (defvar org-agenda-overriding-header)
4332 (defvar orgtbl-mode)
4333 (defvar org-html-entities)
4334 (defvar org-struct-menu)
4335 (defvar org-org-menu)
4336 (defvar org-tbl-menu)
4337 (defvar org-agenda-keymap)
4339 ;;;; Emacs/XEmacs compatibility
4341 ;; Overlay compatibility functions
4342 (defun org-make-overlay (beg end &optional buffer)
4343 (if (featurep 'xemacs)
4344 (make-extent beg end buffer)
4345 (make-overlay beg end buffer)))
4346 (defun org-delete-overlay (ovl)
4347 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4348 (defun org-detach-overlay (ovl)
4349 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4350 (defun org-move-overlay (ovl beg end &optional buffer)
4351 (if (featurep 'xemacs)
4352 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4353 (move-overlay ovl beg end buffer)))
4354 (defun org-overlay-put (ovl prop value)
4355 (if (featurep 'xemacs)
4356 (set-extent-property ovl prop value)
4357 (overlay-put ovl prop value)))
4358 (defun org-overlay-display (ovl text &optional face evap)
4359 "Make overlay OVL display TEXT with face FACE."
4360 (if (featurep 'xemacs)
4361 (let ((gl (make-glyph text)))
4362 (and face (set-glyph-face gl face))
4363 (set-extent-property ovl 'invisible t)
4364 (set-extent-property ovl 'end-glyph gl))
4365 (overlay-put ovl 'display text)
4366 (if face (overlay-put ovl 'face face))
4367 (if evap (overlay-put ovl 'evaporate t))))
4368 (defun org-overlay-before-string (ovl text &optional face evap)
4369 "Make overlay OVL display TEXT with face FACE."
4370 (if (featurep 'xemacs)
4371 (let ((gl (make-glyph text)))
4372 (and face (set-glyph-face gl face))
4373 (set-extent-property ovl 'begin-glyph gl))
4374 (if face (org-add-props text nil 'face face))
4375 (overlay-put ovl 'before-string text)
4376 (if evap (overlay-put ovl 'evaporate t))))
4377 (defun org-overlay-get (ovl prop)
4378 (if (featurep 'xemacs)
4379 (extent-property ovl prop)
4380 (overlay-get ovl prop)))
4381 (defun org-overlays-at (pos)
4382 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4383 (defun org-overlays-in (&optional start end)
4384 (if (featurep 'xemacs)
4385 (extent-list nil start end)
4386 (overlays-in start end)))
4387 (defun org-overlay-start (o)
4388 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4389 (defun org-overlay-end (o)
4390 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4391 (defun org-find-overlays (prop &optional pos delete)
4392 "Find all overlays specifying PROP at POS or point.
4393 If DELETE is non-nil, delete all those overlays."
4394 (let ((overlays (org-overlays-at (or pos (point))))
4395 ov found)
4396 (while (setq ov (pop overlays))
4397 (if (org-overlay-get ov prop)
4398 (if delete (org-delete-overlay ov) (push ov found))))
4399 found))
4401 ;; Region compatibility
4403 (defun org-add-hook (hook function &optional append local)
4404 "Add-hook, compatible with both Emacsen."
4405 (if (and local (featurep 'xemacs))
4406 (add-local-hook hook function append)
4407 (add-hook hook function append local)))
4409 (defvar org-ignore-region nil
4410 "To temporarily disable the active region.")
4412 (defun org-region-active-p ()
4413 "Is `transient-mark-mode' on and the region active?
4414 Works on both Emacs and XEmacs."
4415 (if org-ignore-region
4417 (if (featurep 'xemacs)
4418 (and zmacs-regions (region-active-p))
4419 (and transient-mark-mode mark-active))))
4421 ;; Invisibility compatibility
4423 (defun org-add-to-invisibility-spec (arg)
4424 "Add elements to `buffer-invisibility-spec'.
4425 See documentation for `buffer-invisibility-spec' for the kind of elements
4426 that can be added."
4427 (cond
4428 ((fboundp 'add-to-invisibility-spec)
4429 (add-to-invisibility-spec arg))
4430 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4431 (setq buffer-invisibility-spec (list arg)))
4433 (setq buffer-invisibility-spec
4434 (cons arg buffer-invisibility-spec)))))
4436 (defun org-remove-from-invisibility-spec (arg)
4437 "Remove elements from `buffer-invisibility-spec'."
4438 (if (fboundp 'remove-from-invisibility-spec)
4439 (remove-from-invisibility-spec arg)
4440 (if (consp buffer-invisibility-spec)
4441 (setq buffer-invisibility-spec
4442 (delete arg buffer-invisibility-spec)))))
4444 (defun org-in-invisibility-spec-p (arg)
4445 "Is ARG a member of `buffer-invisibility-spec'?"
4446 (if (consp buffer-invisibility-spec)
4447 (member arg buffer-invisibility-spec)
4448 nil))
4450 ;;;; Define the Org-mode
4452 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4453 (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."))
4456 ;; We use a before-change function to check if a table might need
4457 ;; an update.
4458 (defvar org-table-may-need-update t
4459 "Indicates that a table might need an update.
4460 This variable is set by `org-before-change-function'.
4461 `org-table-align' sets it back to nil.")
4462 (defvar org-mode-map)
4463 (defvar org-mode-hook nil)
4464 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4465 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4466 (defvar org-table-buffer-is-an nil)
4467 (defconst org-outline-regexp "\\*+ ")
4469 ;;;###autoload
4470 (define-derived-mode org-mode outline-mode "Org"
4471 "Outline-based notes management and organizer, alias
4472 \"Carsten's outline-mode for keeping track of everything.\"
4474 Org-mode develops organizational tasks around a NOTES file which
4475 contains information about projects as plain text. Org-mode is
4476 implemented on top of outline-mode, which is ideal to keep the content
4477 of large files well structured. It supports ToDo items, deadlines and
4478 time stamps, which magically appear in the diary listing of the Emacs
4479 calendar. Tables are easily created with a built-in table editor.
4480 Plain text URL-like links connect to websites, emails (VM), Usenet
4481 messages (Gnus), BBDB entries, and any files related to the project.
4482 For printing and sharing of notes, an Org-mode file (or a part of it)
4483 can be exported as a structured ASCII or HTML file.
4485 The following commands are available:
4487 \\{org-mode-map}"
4489 ;; Get rid of Outline menus, they are not needed
4490 ;; Need to do this here because define-derived-mode sets up
4491 ;; the keymap so late. Still, it is a waste to call this each time
4492 ;; we switch another buffer into org-mode.
4493 (if (featurep 'xemacs)
4494 (when (boundp 'outline-mode-menu-heading)
4495 ;; Assume this is Greg's port, it used easymenu
4496 (easy-menu-remove outline-mode-menu-heading)
4497 (easy-menu-remove outline-mode-menu-show)
4498 (easy-menu-remove outline-mode-menu-hide))
4499 (define-key org-mode-map [menu-bar headings] 'undefined)
4500 (define-key org-mode-map [menu-bar hide] 'undefined)
4501 (define-key org-mode-map [menu-bar show] 'undefined))
4503 (easy-menu-add org-org-menu)
4504 (easy-menu-add org-tbl-menu)
4505 (org-install-agenda-files-menu)
4506 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4507 (org-add-to-invisibility-spec '(org-cwidth))
4508 (when (featurep 'xemacs)
4509 (org-set-local 'line-move-ignore-invisible t))
4510 (org-set-local 'outline-regexp org-outline-regexp)
4511 (org-set-local 'outline-level 'org-outline-level)
4512 (when (and org-ellipsis
4513 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4514 (fboundp 'make-glyph-code))
4515 (unless org-display-table
4516 (setq org-display-table (make-display-table)))
4517 (set-display-table-slot
4518 org-display-table 4
4519 (vconcat (mapcar
4520 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4521 org-ellipsis)))
4522 (if (stringp org-ellipsis) org-ellipsis "..."))))
4523 (setq buffer-display-table org-display-table))
4524 (org-set-regexps-and-options)
4525 ;; Calc embedded
4526 (org-set-local 'calc-embedded-open-mode "# ")
4527 (modify-syntax-entry ?# "<")
4528 (modify-syntax-entry ?@ "w")
4529 (if org-startup-truncated (setq truncate-lines t))
4530 (org-set-local 'font-lock-unfontify-region-function
4531 'org-unfontify-region)
4532 ;; Activate before-change-function
4533 (org-set-local 'org-table-may-need-update t)
4534 (org-add-hook 'before-change-functions 'org-before-change-function nil
4535 'local)
4536 ;; Check for running clock before killing a buffer
4537 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4538 ;; Paragraphs and auto-filling
4539 (org-set-autofill-regexps)
4540 (setq indent-line-function 'org-indent-line-function)
4541 (org-update-radio-target-regexp)
4543 ;; Comment characters
4544 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4545 (org-set-local 'comment-padding " ")
4547 ;; Make isearch reveal context
4548 (if (or (featurep 'xemacs)
4549 (not (boundp 'outline-isearch-open-invisible-function)))
4550 ;; Emacs 21 and XEmacs make use of the hook
4551 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4552 ;; Emacs 22 deals with this through a special variable
4553 (org-set-local 'outline-isearch-open-invisible-function
4554 (lambda (&rest ignore) (org-show-context 'isearch))))
4556 ;; If empty file that did not turn on org-mode automatically, make it to.
4557 (if (and org-insert-mode-line-in-empty-file
4558 (interactive-p)
4559 (= (point-min) (point-max)))
4560 (insert "# -*- mode: org -*-\n\n"))
4562 (unless org-inhibit-startup
4563 (when org-startup-align-all-tables
4564 (let ((bmp (buffer-modified-p)))
4565 (org-table-map-tables 'org-table-align)
4566 (set-buffer-modified-p bmp)))
4567 (org-cycle-hide-drawers 'all)
4568 (cond
4569 ((eq org-startup-folded t)
4570 (org-cycle '(4)))
4571 ((eq org-startup-folded 'content)
4572 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4573 (org-cycle '(4)) (org-cycle '(4)))))))
4575 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4577 (defsubst org-call-with-arg (command arg)
4578 "Call COMMAND interactively, but pretend prefix are was ARG."
4579 (let ((current-prefix-arg arg)) (call-interactively command)))
4581 (defsubst org-current-line (&optional pos)
4582 (save-excursion
4583 (and pos (goto-char pos))
4584 ;; works also in narrowed buffer, because we start at 1, not point-min
4585 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
4587 (defun org-current-time ()
4588 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4589 (if (> org-time-stamp-rounding-minutes 0)
4590 (let ((r org-time-stamp-rounding-minutes)
4591 (time (decode-time)))
4592 (apply 'encode-time
4593 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4594 (nthcdr 2 time))))
4595 (current-time)))
4597 (defun org-add-props (string plist &rest props)
4598 "Add text properties to entire string, from beginning to end.
4599 PLIST may be a list of properties, PROPS are individual properties and values
4600 that will be added to PLIST. Returns the string that was modified."
4601 (add-text-properties
4602 0 (length string) (if props (append plist props) plist) string)
4603 string)
4604 (put 'org-add-props 'lisp-indent-function 2)
4607 ;;;; Font-Lock stuff, including the activators
4609 (defvar org-mouse-map (make-sparse-keymap))
4610 (org-defkey org-mouse-map
4611 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4612 (org-defkey org-mouse-map
4613 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4614 (when org-mouse-1-follows-link
4615 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4616 (when org-tab-follows-link
4617 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4618 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4619 (when org-return-follows-link
4620 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
4621 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
4623 (require 'font-lock)
4625 (defconst org-non-link-chars "]\t\n\r<>")
4626 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
4627 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
4628 (defvar org-link-re-with-space nil
4629 "Matches a link with spaces, optional angular brackets around it.")
4630 (defvar org-link-re-with-space2 nil
4631 "Matches a link with spaces, optional angular brackets around it.")
4632 (defvar org-angle-link-re nil
4633 "Matches link with angular brackets, spaces are allowed.")
4634 (defvar org-plain-link-re nil
4635 "Matches plain link, without spaces.")
4636 (defvar org-bracket-link-regexp nil
4637 "Matches a link in double brackets.")
4638 (defvar org-bracket-link-analytic-regexp nil
4639 "Regular expression used to analyze links.
4640 Here is what the match groups contain after a match:
4641 1: http:
4642 2: http
4643 3: path
4644 4: [desc]
4645 5: desc")
4646 (defvar org-any-link-re nil
4647 "Regular expression matching any link.")
4649 (defun org-make-link-regexps ()
4650 "Update the link regular expressions.
4651 This should be called after the variable `org-link-types' has changed."
4652 (setq org-link-re-with-space
4653 (concat
4654 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4655 "\\([^" org-non-link-chars " ]"
4656 "[^" org-non-link-chars "]*"
4657 "[^" org-non-link-chars " ]\\)>?")
4658 org-link-re-with-space2
4659 (concat
4660 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4661 "\\([^" org-non-link-chars " ]"
4662 "[^]\t\n\r]*"
4663 "[^" org-non-link-chars " ]\\)>?")
4664 org-angle-link-re
4665 (concat
4666 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4667 "\\([^" org-non-link-chars " ]"
4668 "[^" org-non-link-chars "]*"
4669 "\\)>")
4670 org-plain-link-re
4671 (concat
4672 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4673 "\\([^]\t\n\r<>,;() ]+\\)")
4674 org-bracket-link-regexp
4675 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4676 org-bracket-link-analytic-regexp
4677 (concat
4678 "\\[\\["
4679 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4680 "\\([^]]+\\)"
4681 "\\]"
4682 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4683 "\\]")
4684 org-any-link-re
4685 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4686 org-angle-link-re "\\)\\|\\("
4687 org-plain-link-re "\\)")))
4689 (org-make-link-regexps)
4691 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4692 "Regular expression for fast time stamp matching.")
4693 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4694 "Regular expression for fast time stamp matching.")
4695 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4696 "Regular expression matching time strings for analysis.
4697 This one does not require the space after the date.")
4698 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4699 "Regular expression matching time strings for analysis.")
4700 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4701 "Regular expression matching time stamps, with groups.")
4702 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4703 "Regular expression matching time stamps (also [..]), with groups.")
4704 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4705 "Regular expression matching a time stamp range.")
4706 (defconst org-tr-regexp-both
4707 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4708 "Regular expression matching a time stamp range.")
4709 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4710 org-ts-regexp "\\)?")
4711 "Regular expression matching a time stamp or time stamp range.")
4712 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4713 org-ts-regexp-both "\\)?")
4714 "Regular expression matching a time stamp or time stamp range.
4715 The time stamps may be either active or inactive.")
4717 (defvar org-emph-face nil)
4719 (defun org-do-emphasis-faces (limit)
4720 "Run through the buffer and add overlays to links."
4721 (let (rtn)
4722 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4723 (if (not (= (char-after (match-beginning 3))
4724 (char-after (match-beginning 4))))
4725 (progn
4726 (setq rtn t)
4727 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4728 'face
4729 (nth 1 (assoc (match-string 3)
4730 org-emphasis-alist)))
4731 (add-text-properties (match-beginning 2) (match-end 2)
4732 '(font-lock-multiline t))
4733 (backward-char 1))))
4734 rtn))
4736 (defun org-emphasize (&optional char)
4737 "Insert or change an emphasis, i.e. a font like bold or italic.
4738 If there is an active region, change that region to a new emphasis.
4739 If there is no region, just insert the marker characters and position
4740 the cursor between them.
4741 CHAR should be either the marker character, or the first character of the
4742 HTML tag associated with that emphasis. If CHAR is a space, the means
4743 to remove the emphasis of the selected region.
4744 If char is not given (for example in an interactive call) it
4745 will be prompted for."
4746 (interactive)
4747 (let ((eal org-emphasis-alist) e det
4748 (erc org-emphasis-regexp-components)
4749 (prompt "")
4750 (string "") beg end move tag c s)
4751 (if (org-region-active-p)
4752 (setq beg (region-beginning) end (region-end)
4753 string (buffer-substring beg end))
4754 (setq move t))
4756 (while (setq e (pop eal))
4757 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4758 c (aref tag 0))
4759 (push (cons c (string-to-char (car e))) det)
4760 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4761 (substring tag 1)))))
4762 (unless char
4763 (message "%s" (concat "Emphasis marker or tag:" prompt))
4764 (setq char (read-char-exclusive)))
4765 (setq char (or (cdr (assoc char det)) char))
4766 (if (equal char ?\ )
4767 (setq s "" move nil)
4768 (unless (assoc (char-to-string char) org-emphasis-alist)
4769 (error "No such emphasis marker: \"%c\"" char))
4770 (setq s (char-to-string char)))
4771 (while (and (> (length string) 1)
4772 (equal (substring string 0 1) (substring string -1))
4773 (assoc (substring string 0 1) org-emphasis-alist))
4774 (setq string (substring string 1 -1)))
4775 (setq string (concat s string s))
4776 (if beg (delete-region beg end))
4777 (unless (or (bolp)
4778 (string-match (concat "[" (nth 0 erc) "\n]")
4779 (char-to-string (char-before (point)))))
4780 (insert " "))
4781 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4782 (char-to-string (char-after (point))))
4783 (insert " ") (backward-char 1))
4784 (insert string)
4785 (and move (backward-char 1))))
4787 (defconst org-nonsticky-props
4788 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4791 (defun org-activate-plain-links (limit)
4792 "Run through the buffer and add overlays to links."
4793 (catch 'exit
4794 (let (f)
4795 (while (re-search-forward org-plain-link-re limit t)
4796 (setq f (get-text-property (match-beginning 0) 'face))
4797 (if (or (eq f 'org-tag)
4798 (and (listp f) (memq 'org-tag f)))
4800 (add-text-properties (match-beginning 0) (match-end 0)
4801 (list 'mouse-face 'highlight
4802 'rear-nonsticky org-nonsticky-props
4803 'keymap org-mouse-map
4805 (throw 'exit t))))))
4807 (defun org-activate-code (limit)
4808 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
4809 (unless (get-text-property (match-beginning 1) 'face)
4810 (remove-text-properties (match-beginning 0) (match-end 0)
4811 '(display t invisible t intangible t))
4812 t)))
4814 (defun org-activate-angle-links (limit)
4815 "Run through the buffer and add overlays to links."
4816 (if (re-search-forward org-angle-link-re limit t)
4817 (progn
4818 (add-text-properties (match-beginning 0) (match-end 0)
4819 (list 'mouse-face 'highlight
4820 'rear-nonsticky org-nonsticky-props
4821 'keymap org-mouse-map
4823 t)))
4825 (defmacro org-maybe-intangible (props)
4826 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
4827 In emacs 21, invisible text is not avoided by the command loop, so the
4828 intangible property is needed to make sure point skips this text.
4829 In Emacs 22, this is not necessary. The intangible text property has
4830 led to problems with flyspell. These problems are fixed in flyspell.el,
4831 but we still avoid setting the property in Emacs 22 and later.
4832 We use a macro so that the test can happen at compilation time."
4833 (if (< emacs-major-version 22)
4834 `(append '(intangible t) ,props)
4835 props))
4837 (defun org-activate-bracket-links (limit)
4838 "Run through the buffer and add overlays to bracketed links."
4839 (if (re-search-forward org-bracket-link-regexp limit t)
4840 (let* ((help (concat "LINK: "
4841 (org-match-string-no-properties 1)))
4842 ;; FIXME: above we should remove the escapes.
4843 ;; but that requires another match, protecting match data,
4844 ;; a lot of overhead for font-lock.
4845 (ip (org-maybe-intangible
4846 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
4847 'keymap org-mouse-map 'mouse-face 'highlight
4848 'help-echo help)))
4849 (vp (list 'rear-nonsticky org-nonsticky-props
4850 'keymap org-mouse-map 'mouse-face 'highlight
4851 'help-echo help)))
4852 ;; We need to remove the invisible property here. Table narrowing
4853 ;; may have made some of this invisible.
4854 (remove-text-properties (match-beginning 0) (match-end 0)
4855 '(invisible nil))
4856 (if (match-end 3)
4857 (progn
4858 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4859 (add-text-properties (match-beginning 3) (match-end 3) vp)
4860 (add-text-properties (match-end 3) (match-end 0) ip))
4861 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4862 (add-text-properties (match-beginning 1) (match-end 1) vp)
4863 (add-text-properties (match-end 1) (match-end 0) ip))
4864 t)))
4866 (defun org-activate-dates (limit)
4867 "Run through the buffer and add overlays to dates."
4868 (if (re-search-forward org-tsr-regexp-both limit t)
4869 (progn
4870 (add-text-properties (match-beginning 0) (match-end 0)
4871 (list 'mouse-face 'highlight
4872 'rear-nonsticky org-nonsticky-props
4873 'keymap org-mouse-map))
4874 (when org-display-custom-times
4875 (if (match-end 3)
4876 (org-display-custom-time (match-beginning 3) (match-end 3)))
4877 (org-display-custom-time (match-beginning 1) (match-end 1)))
4878 t)))
4880 (defvar org-target-link-regexp nil
4881 "Regular expression matching radio targets in plain text.")
4882 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4883 "Regular expression matching a link target.")
4884 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4885 "Regular expression matching a radio target.")
4886 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4887 "Regular expression matching any target.")
4889 (defun org-activate-target-links (limit)
4890 "Run through the buffer and add overlays to target matches."
4891 (when org-target-link-regexp
4892 (let ((case-fold-search t))
4893 (if (re-search-forward org-target-link-regexp limit t)
4894 (progn
4895 (add-text-properties (match-beginning 0) (match-end 0)
4896 (list 'mouse-face 'highlight
4897 'rear-nonsticky org-nonsticky-props
4898 'keymap org-mouse-map
4899 'help-echo "Radio target link"
4900 'org-linked-text t))
4901 t)))))
4903 (defun org-update-radio-target-regexp ()
4904 "Find all radio targets in this file and update the regular expression."
4905 (interactive)
4906 (when (memq 'radio org-activate-links)
4907 (setq org-target-link-regexp
4908 (org-make-target-link-regexp (org-all-targets 'radio)))
4909 (org-restart-font-lock)))
4911 (defun org-hide-wide-columns (limit)
4912 (let (s e)
4913 (setq s (text-property-any (point) (or limit (point-max))
4914 'org-cwidth t))
4915 (when s
4916 (setq e (next-single-property-change s 'org-cwidth))
4917 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4918 (goto-char e)
4919 t)))
4921 (defun org-restart-font-lock ()
4922 "Restart font-lock-mode, to force refontification."
4923 (when (and (boundp 'font-lock-mode) font-lock-mode)
4924 (font-lock-mode -1)
4925 (font-lock-mode 1)))
4927 (defun org-all-targets (&optional radio)
4928 "Return a list of all targets in this file.
4929 With optional argument RADIO, only find radio targets."
4930 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4931 rtn)
4932 (save-excursion
4933 (goto-char (point-min))
4934 (while (re-search-forward re nil t)
4935 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4936 rtn)))
4938 (defun org-make-target-link-regexp (targets)
4939 "Make regular expression matching all strings in TARGETS.
4940 The regular expression finds the targets also if there is a line break
4941 between words."
4942 (and targets
4943 (concat
4944 "\\<\\("
4945 (mapconcat
4946 (lambda (x)
4947 (while (string-match " +" x)
4948 (setq x (replace-match "\\s-+" t t x)))
4950 targets
4951 "\\|")
4952 "\\)\\>")))
4954 (defun org-activate-tags (limit)
4955 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4956 (progn
4957 (add-text-properties (match-beginning 1) (match-end 1)
4958 (list 'mouse-face 'highlight
4959 'rear-nonsticky org-nonsticky-props
4960 'keymap org-mouse-map))
4961 t)))
4963 (defun org-outline-level ()
4964 (save-excursion
4965 (looking-at outline-regexp)
4966 (if (match-beginning 1)
4967 (+ (org-get-string-indentation (match-string 1)) 1000)
4968 (1- (- (match-end 0) (match-beginning 0))))))
4970 (defvar org-font-lock-keywords nil)
4972 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
4973 "Regular expression matching a property line.")
4975 (defun org-set-font-lock-defaults ()
4976 (let* ((em org-fontify-emphasized-text)
4977 (lk org-activate-links)
4978 (org-font-lock-extra-keywords
4979 (list
4980 ;; Headlines
4981 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4982 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4983 ;; Table lines
4984 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4985 (1 'org-table t))
4986 ;; Table internals
4987 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4988 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4989 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4990 ;; Drawers
4991 (list org-drawer-regexp '(0 'org-special-keyword t))
4992 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4993 ;; Properties
4994 (list org-property-re
4995 '(1 'org-special-keyword t)
4996 '(3 'org-property-value t))
4997 (if org-format-transports-properties-p
4998 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4999 ;; Links
5000 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5001 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5002 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5003 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5004 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5005 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5006 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5007 '(org-hide-wide-columns (0 nil append))
5008 ;; TODO lines
5009 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5010 '(1 (org-get-todo-face 1) t))
5011 ;; DONE
5012 (if org-fontify-done-headline
5013 (list (concat "^[*]+ +\\<\\("
5014 (mapconcat 'regexp-quote org-done-keywords "\\|")
5015 "\\)\\(.*\\)")
5016 '(2 'org-headline-done t))
5017 nil)
5018 ;; Priorities
5019 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5020 ;; Special keywords
5021 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5022 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5023 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5024 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5025 ;; Emphasis
5026 (if em
5027 (if (featurep 'xemacs)
5028 '(org-do-emphasis-faces (0 nil append))
5029 '(org-do-emphasis-faces)))
5030 ;; Checkboxes
5031 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5032 2 'bold prepend)
5033 (if org-provide-checkbox-statistics
5034 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5035 (0 (org-get-checkbox-statistics-face) t)))
5036 ;; COMMENT
5037 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5038 "\\|" org-quote-string "\\)\\>")
5039 '(1 'org-special-keyword t))
5040 '("^#.*" (0 'font-lock-comment-face t))
5041 '("^\\*+ \\(.*:ARCHIVE:.*\\)" (1 'org-archived prepend))
5042 ;; Code
5043 '(org-activate-code (1 'org-code t))
5045 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5046 ;; Now set the full font-lock-keywords
5047 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5048 (org-set-local 'font-lock-defaults
5049 '(org-font-lock-keywords t nil nil backward-paragraph))
5050 (kill-local-variable 'font-lock-keywords) nil))
5052 (defvar org-m nil)
5053 (defvar org-l nil)
5054 (defvar org-f nil)
5055 (defun org-get-level-face (n)
5056 "Get the right face for match N in font-lock matching of healdines."
5057 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5058 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5059 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5060 (cond
5061 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5062 ((eq n 2) org-f)
5063 (t (if org-level-color-stars-only nil org-f))))
5065 (defun org-get-todo-face (kwd)
5066 "Get the right face for a TODO keyword KWD.
5067 If KWD is a number, get the corresponding match group."
5068 (if (numberp kwd) (setq kwd (match-string kwd)))
5069 (or (cdr (assoc kwd org-todo-keyword-faces))
5070 (and (member kwd org-done-keywords) 'org-done)
5071 'org-todo))
5073 (defun org-unfontify-region (beg end &optional maybe_loudly)
5074 "Remove fontification and activation overlays from links."
5075 (font-lock-default-unfontify-region beg end)
5076 (let* ((buffer-undo-list t)
5077 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5078 (inhibit-modification-hooks t)
5079 deactivate-mark buffer-file-name buffer-file-truename)
5080 (remove-text-properties beg end
5081 '(mouse-face t keymap t org-linked-text t
5082 invisible t intangible t))))
5084 ;;;; Visibility cycling, including org-goto and indirect buffer
5086 ;;; Cycling
5088 (defvar org-cycle-global-status nil)
5089 (make-variable-buffer-local 'org-cycle-global-status)
5090 (defvar org-cycle-subtree-status nil)
5091 (make-variable-buffer-local 'org-cycle-subtree-status)
5093 ;;;###autoload
5094 (defun org-cycle (&optional arg)
5095 "Visibility cycling for Org-mode.
5097 - When this function is called with a prefix argument, rotate the entire
5098 buffer through 3 states (global cycling)
5099 1. OVERVIEW: Show only top-level headlines.
5100 2. CONTENTS: Show all headlines of all levels, but no body text.
5101 3. SHOW ALL: Show everything.
5103 - When point is at the beginning of a headline, rotate the subtree started
5104 by this line through 3 different states (local cycling)
5105 1. FOLDED: Only the main headline is shown.
5106 2. CHILDREN: The main headline and the direct children are shown.
5107 From this state, you can move to one of the children
5108 and zoom in further.
5109 3. SUBTREE: Show the entire subtree, including body text.
5111 - When there is a numeric prefix, go up to a heading with level ARG, do
5112 a `show-subtree' and return to the previous cursor position. If ARG
5113 is negative, go up that many levels.
5115 - When point is not at the beginning of a headline, execute
5116 `indent-relative', like TAB normally does. See the option
5117 `org-cycle-emulate-tab' for details.
5119 - Special case: if point is at the beginning of the buffer and there is
5120 no headline in line 1, this function will act as if called with prefix arg.
5121 But only if also the variable `org-cycle-global-at-bob' is t."
5122 (interactive "P")
5123 (let* ((outline-regexp
5124 (if (and (org-mode-p) org-cycle-include-plain-lists)
5125 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5126 outline-regexp))
5127 (bob-special (and org-cycle-global-at-bob (bobp)
5128 (not (looking-at outline-regexp))))
5129 (org-cycle-hook
5130 (if bob-special
5131 (delq 'org-optimize-window-after-visibility-change
5132 (copy-sequence org-cycle-hook))
5133 org-cycle-hook))
5134 (pos (point)))
5136 (if (or bob-special (equal arg '(4)))
5137 ;; special case: use global cycling
5138 (setq arg t))
5140 (cond
5142 ((org-at-table-p 'any)
5143 ;; Enter the table or move to the next field in the table
5144 (or (org-table-recognize-table.el)
5145 (progn
5146 (if arg (org-table-edit-field t)
5147 (org-table-justify-field-maybe)
5148 (call-interactively 'org-table-next-field)))))
5150 ((eq arg t) ;; Global cycling
5152 (cond
5153 ((and (eq last-command this-command)
5154 (eq org-cycle-global-status 'overview))
5155 ;; We just created the overview - now do table of contents
5156 ;; This can be slow in very large buffers, so indicate action
5157 (message "CONTENTS...")
5158 (org-content)
5159 (message "CONTENTS...done")
5160 (setq org-cycle-global-status 'contents)
5161 (run-hook-with-args 'org-cycle-hook 'contents))
5163 ((and (eq last-command this-command)
5164 (eq org-cycle-global-status 'contents))
5165 ;; We just showed the table of contents - now show everything
5166 (show-all)
5167 (message "SHOW ALL")
5168 (setq org-cycle-global-status 'all)
5169 (run-hook-with-args 'org-cycle-hook 'all))
5172 ;; Default action: go to overview
5173 (org-overview)
5174 (message "OVERVIEW")
5175 (setq org-cycle-global-status 'overview)
5176 (run-hook-with-args 'org-cycle-hook 'overview))))
5178 ((and org-drawers org-drawer-regexp
5179 (save-excursion
5180 (beginning-of-line 1)
5181 (looking-at org-drawer-regexp)))
5182 ;; Toggle block visibility
5183 (org-flag-drawer
5184 (not (get-char-property (match-end 0) 'invisible))))
5186 ((integerp arg)
5187 ;; Show-subtree, ARG levels up from here.
5188 (save-excursion
5189 (org-back-to-heading)
5190 (outline-up-heading (if (< arg 0) (- arg)
5191 (- (funcall outline-level) arg)))
5192 (org-show-subtree)))
5194 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5195 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5196 ;; At a heading: rotate between three different views
5197 (org-back-to-heading)
5198 (let ((goal-column 0) eoh eol eos)
5199 ;; First, some boundaries
5200 (save-excursion
5201 (org-back-to-heading)
5202 (save-excursion
5203 (beginning-of-line 2)
5204 (while (and (not (eobp)) ;; this is like `next-line'
5205 (get-char-property (1- (point)) 'invisible))
5206 (beginning-of-line 2)) (setq eol (point)))
5207 (outline-end-of-heading) (setq eoh (point))
5208 (org-end-of-subtree t)
5209 (unless (eobp)
5210 (skip-chars-forward " \t\n")
5211 (beginning-of-line 1) ; in case this is an item
5213 (setq eos (1- (point))))
5214 ;; Find out what to do next and set `this-command'
5215 (cond
5216 ((= eos eoh)
5217 ;; Nothing is hidden behind this heading
5218 (message "EMPTY ENTRY")
5219 (setq org-cycle-subtree-status nil)
5220 (save-excursion
5221 (goto-char eos)
5222 (outline-next-heading)
5223 (if (org-invisible-p) (org-flag-heading nil))))
5224 ((or (>= eol eos)
5225 (not (string-match "\\S-" (buffer-substring eol eos))))
5226 ;; Entire subtree is hidden in one line: open it
5227 (org-show-entry)
5228 (show-children)
5229 (message "CHILDREN")
5230 (save-excursion
5231 (goto-char eos)
5232 (outline-next-heading)
5233 (if (org-invisible-p) (org-flag-heading nil)))
5234 (setq org-cycle-subtree-status 'children)
5235 (run-hook-with-args 'org-cycle-hook 'children))
5236 ((and (eq last-command this-command)
5237 (eq org-cycle-subtree-status 'children))
5238 ;; We just showed the children, now show everything.
5239 (org-show-subtree)
5240 (message "SUBTREE")
5241 (setq org-cycle-subtree-status 'subtree)
5242 (run-hook-with-args 'org-cycle-hook 'subtree))
5244 ;; Default action: hide the subtree.
5245 (hide-subtree)
5246 (message "FOLDED")
5247 (setq org-cycle-subtree-status 'folded)
5248 (run-hook-with-args 'org-cycle-hook 'folded)))))
5250 ;; TAB emulation
5251 (buffer-read-only (org-back-to-heading))
5253 ((org-try-cdlatex-tab))
5255 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5256 (or (not (bolp))
5257 (not (looking-at outline-regexp))))
5258 (call-interactively (global-key-binding "\t")))
5260 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5261 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5262 (or (and (eq org-cycle-emulate-tab 'white)
5263 (= (match-end 0) (point-at-eol)))
5264 (and (eq org-cycle-emulate-tab 'whitestart)
5265 (>= (match-end 0) pos))))
5267 (eq org-cycle-emulate-tab t))
5268 (if (and (looking-at "[ \n\r\t]")
5269 (string-match "^[ \t]*$" (buffer-substring
5270 (point-at-bol) (point))))
5271 (progn
5272 (beginning-of-line 1)
5273 (and (looking-at "[ \t]+") (replace-match ""))))
5274 (call-interactively (global-key-binding "\t")))
5276 (t (save-excursion
5277 (org-back-to-heading)
5278 (org-cycle))))))
5280 ;;;###autoload
5281 (defun org-global-cycle (&optional arg)
5282 "Cycle the global visibility. For details see `org-cycle'."
5283 (interactive "P")
5284 (let ((org-cycle-include-plain-lists
5285 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5286 (if (integerp arg)
5287 (progn
5288 (show-all)
5289 (hide-sublevels arg)
5290 (setq org-cycle-global-status 'contents))
5291 (org-cycle '(4)))))
5293 (defun org-overview ()
5294 "Switch to overview mode, shoing only top-level headlines.
5295 Really, this shows all headlines with level equal or greater than the level
5296 of the first headline in the buffer. This is important, because if the
5297 first headline is not level one, then (hide-sublevels 1) gives confusing
5298 results."
5299 (interactive)
5300 (let ((level (save-excursion
5301 (goto-char (point-min))
5302 (if (re-search-forward (concat "^" outline-regexp) nil t)
5303 (progn
5304 (goto-char (match-beginning 0))
5305 (funcall outline-level))))))
5306 (and level (hide-sublevels level))))
5308 (defun org-content (&optional arg)
5309 "Show all headlines in the buffer, like a table of contents.
5310 With numerical argument N, show content up to level N."
5311 (interactive "P")
5312 (save-excursion
5313 ;; Visit all headings and show their offspring
5314 (and (integerp arg) (org-overview))
5315 (goto-char (point-max))
5316 (catch 'exit
5317 (while (and (progn (condition-case nil
5318 (outline-previous-visible-heading 1)
5319 (error (goto-char (point-min))))
5321 (looking-at outline-regexp))
5322 (if (integerp arg)
5323 (show-children (1- arg))
5324 (show-branches))
5325 (if (bobp) (throw 'exit nil))))))
5328 (defun org-optimize-window-after-visibility-change (state)
5329 "Adjust the window after a change in outline visibility.
5330 This function is the default value of the hook `org-cycle-hook'."
5331 (when (get-buffer-window (current-buffer))
5332 (cond
5333 ; ((eq state 'overview) (org-first-headline-recenter 1))
5334 ; ((eq state 'overview) (org-beginning-of-line))
5335 ((eq state 'content) nil)
5336 ((eq state 'all) nil)
5337 ((eq state 'folded) nil)
5338 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5339 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5342 (defun org-cycle-show-empty-lines (state)
5343 "Show empty lines above all visible headlines.
5344 The region to be covered depends on STATE when called through
5345 `org-cycle-hook'. Lisp program can use t for STATE to get the
5346 entire buffer covered. Note that an empty line is only shown if there
5347 are at least `org-cycle-separator-lines' empty lines before the headeline."
5348 (when (> org-cycle-separator-lines 0)
5349 (save-excursion
5350 (let* ((n org-cycle-separator-lines)
5351 (re (cond
5352 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5353 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5354 (t (let ((ns (number-to-string (- n 2))))
5355 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5356 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5357 beg end)
5358 (cond
5359 ((memq state '(overview contents t))
5360 (setq beg (point-min) end (point-max)))
5361 ((memq state '(children folded))
5362 (setq beg (point) end (progn (org-end-of-subtree t t)
5363 (beginning-of-line 2)
5364 (point)))))
5365 (when beg
5366 (goto-char beg)
5367 (while (re-search-forward re end t)
5368 (if (not (get-char-property (match-end 1) 'invisible))
5369 (outline-flag-region
5370 (match-beginning 1) (match-end 1) nil)))))))
5371 ;; Never hide empty lines at the end of the file.
5372 (save-excursion
5373 (goto-char (point-max))
5374 (outline-previous-heading)
5375 (outline-end-of-heading)
5376 (if (and (looking-at "[ \t\n]+")
5377 (= (match-end 0) (point-max)))
5378 (outline-flag-region (point) (match-end 0) nil))))
5380 (defun org-subtree-end-visible-p ()
5381 "Is the end of the current subtree visible?"
5382 (pos-visible-in-window-p
5383 (save-excursion (org-end-of-subtree t) (point))))
5385 (defun org-first-headline-recenter (&optional N)
5386 "Move cursor to the first headline and recenter the headline.
5387 Optional argument N means, put the headline into the Nth line of the window."
5388 (goto-char (point-min))
5389 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5390 (beginning-of-line)
5391 (recenter (prefix-numeric-value N))))
5393 ;;; Org-goto
5395 (defvar org-goto-window-configuration nil)
5396 (defvar org-goto-marker nil)
5397 (defvar org-goto-map
5398 (let ((map (make-sparse-keymap)))
5399 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5400 (while (setq cmd (pop cmds))
5401 (substitute-key-definition cmd cmd map global-map)))
5402 (suppress-keymap map)
5403 (org-defkey map "\C-m" 'org-goto-ret)
5404 (org-defkey map [(left)] 'org-goto-left)
5405 (org-defkey map [(right)] 'org-goto-right)
5406 (org-defkey map [(?q)] 'org-goto-quit)
5407 (org-defkey map [(control ?g)] 'org-goto-quit)
5408 (org-defkey map "\C-i" 'org-cycle)
5409 (org-defkey map [(tab)] 'org-cycle)
5410 (org-defkey map [(down)] 'outline-next-visible-heading)
5411 (org-defkey map [(up)] 'outline-previous-visible-heading)
5412 (org-defkey map "n" 'outline-next-visible-heading)
5413 (org-defkey map "p" 'outline-previous-visible-heading)
5414 (org-defkey map "f" 'outline-forward-same-level)
5415 (org-defkey map "b" 'outline-backward-same-level)
5416 (org-defkey map "u" 'outline-up-heading)
5417 (org-defkey map "/" 'org-occur)
5418 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5419 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5420 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5421 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5422 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5423 map))
5425 (defconst org-goto-help
5426 "Browse copy of buffer to find location or copy text.
5427 RET=jump to location [Q]uit and return to previous location
5428 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur"
5431 (defun org-goto ()
5432 "Look up a different location in the current file, keeping current visibility.
5434 When you want look-up or go to a different location in a document, the
5435 fastest way is often to fold the entire buffer and then dive into the tree.
5436 This method has the disadvantage, that the previous location will be folded,
5437 which may not be what you want.
5439 This command works around this by showing a copy of the current buffer
5440 in an indirect buffer, in overview mode. You can dive into the tree in
5441 that copy, use org-occur and incremental search to find a location.
5442 When pressing RET or `Q', the command returns to the original buffer in
5443 which the visibility is still unchanged. After RET is will also jump to
5444 the location selected in the indirect buffer and expose the
5445 the headline hierarchy above."
5446 (interactive)
5447 (let* ((org-goto-start-pos (point))
5448 (selected-point
5449 (car (org-get-location (current-buffer) org-goto-help))))
5450 (if selected-point
5451 (progn
5452 (org-mark-ring-push org-goto-start-pos)
5453 (goto-char selected-point)
5454 (if (or (org-invisible-p) (org-invisible-p2))
5455 (org-show-context 'org-goto)))
5456 (message "Quit"))))
5458 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5459 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5461 (defun org-get-location (buf help)
5462 "Let the user select a location in the Org-mode buffer BUF.
5463 This function uses a recursive edit. It returns the selected position
5464 or nil."
5465 (let (org-goto-selected-point org-goto-exit-command)
5466 (save-excursion
5467 (save-window-excursion
5468 (delete-other-windows)
5469 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5470 (switch-to-buffer
5471 (condition-case nil
5472 (make-indirect-buffer (current-buffer) "*org-goto*")
5473 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5474 (with-output-to-temp-buffer "*Help*"
5475 (princ help))
5476 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
5477 (setq buffer-read-only nil)
5478 (let ((org-startup-truncated t)
5479 (org-startup-folded nil)
5480 (org-startup-align-all-tables nil))
5481 (org-mode)
5482 (org-overview))
5483 (setq buffer-read-only t)
5484 (if (and (boundp 'org-goto-start-pos)
5485 (integer-or-marker-p org-goto-start-pos))
5486 (let ((org-show-hierarchy-above t)
5487 (org-show-siblings t)
5488 (org-show-following-heading t))
5489 (goto-char org-goto-start-pos)
5490 (and (org-invisible-p) (org-show-context)))
5491 (goto-char (point-min)))
5492 (org-beginning-of-line)
5493 (message "Select location and press RET")
5494 ;; now we make sure that during selection, ony very few keys work
5495 ;; and that it is impossible to switch to another window.
5496 ; (let ((gm (current-global-map))
5497 ; (overriding-local-map org-goto-map))
5498 ; (unwind-protect
5499 ; (progn
5500 ; (use-global-map org-goto-map)
5501 ; (recursive-edit))
5502 ; (use-global-map gm)))
5503 (use-local-map org-goto-map)
5504 (recursive-edit)
5506 (kill-buffer "*org-goto*")
5507 (cons org-goto-selected-point org-goto-exit-command)))
5509 (defun org-goto-ret (&optional arg)
5510 "Finish `org-goto' by going to the new location."
5511 (interactive "P")
5512 (setq org-goto-selected-point (point)
5513 org-goto-exit-command 'return)
5514 (throw 'exit nil))
5516 (defun org-goto-left ()
5517 "Finish `org-goto' by going to the new location."
5518 (interactive)
5519 (if (org-on-heading-p)
5520 (progn
5521 (beginning-of-line 1)
5522 (setq org-goto-selected-point (point)
5523 org-goto-exit-command 'left)
5524 (throw 'exit nil))
5525 (error "Not on a heading")))
5527 (defun org-goto-right ()
5528 "Finish `org-goto' by going to the new location."
5529 (interactive)
5530 (if (org-on-heading-p)
5531 (progn
5532 (setq org-goto-selected-point (point)
5533 org-goto-exit-command 'right)
5534 (throw 'exit nil))
5535 (error "Not on a heading")))
5537 (defun org-goto-quit ()
5538 "Finish `org-goto' without cursor motion."
5539 (interactive)
5540 (setq org-goto-selected-point nil)
5541 (setq org-goto-exit-command 'quit)
5542 (throw 'exit nil))
5544 ;;; Indirect buffer display of subtrees
5546 (defvar org-indirect-dedicated-frame nil
5547 "This is the frame being used for indirect tree display.")
5548 (defvar org-last-indirect-buffer nil)
5550 (defun org-tree-to-indirect-buffer (&optional arg)
5551 "Create indirect buffer and narrow it to current subtree.
5552 With numerical prefix ARG, go up to this level and then take that tree.
5553 If ARG is negative, go up that many levels.
5554 Normally this command removes the indirect buffer previously made
5555 with this command. However, when called with a C-u prefix, the last buffer
5556 is kept so that you can work with several indirect buffers at the same time.
5557 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5558 requests that a new frame be made for the new buffer, so that the dedicated
5559 frame is not changed."
5560 (interactive "P")
5561 (let ((cbuf (current-buffer))
5562 (cwin (selected-window))
5563 (pos (point))
5564 beg end level heading ibuf)
5565 (save-excursion
5566 (org-back-to-heading t)
5567 (when (numberp arg)
5568 (setq level (org-outline-level))
5569 (if (< arg 0) (setq arg (+ level arg)))
5570 (while (> (setq level (org-outline-level)) arg)
5571 (outline-up-heading 1 t)))
5572 (setq beg (point)
5573 heading (org-get-heading))
5574 (org-end-of-subtree t) (setq end (point)))
5575 (if (and (not arg)
5576 (buffer-live-p org-last-indirect-buffer))
5577 (kill-buffer org-last-indirect-buffer))
5578 (setq ibuf (org-get-indirect-buffer cbuf)
5579 org-last-indirect-buffer ibuf)
5580 (cond
5581 ((or (eq org-indirect-buffer-display 'new-frame)
5582 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5583 (select-frame (make-frame))
5584 (delete-other-windows)
5585 (switch-to-buffer ibuf)
5586 (org-set-frame-title heading))
5587 ((eq org-indirect-buffer-display 'dedicated-frame)
5588 (raise-frame
5589 (select-frame (or (and org-indirect-dedicated-frame
5590 (frame-live-p org-indirect-dedicated-frame)
5591 org-indirect-dedicated-frame)
5592 (setq org-indirect-dedicated-frame (make-frame)))))
5593 (delete-other-windows)
5594 (switch-to-buffer ibuf)
5595 (org-set-frame-title (concat "Indirect: " heading)))
5596 ((eq org-indirect-buffer-display 'current-window)
5597 (switch-to-buffer ibuf))
5598 ((eq org-indirect-buffer-display 'other-window)
5599 (pop-to-buffer ibuf))
5600 (t (error "Invalid value.")))
5601 (if (featurep 'xemacs)
5602 (save-excursion (org-mode) (turn-on-font-lock)))
5603 (narrow-to-region beg end)
5604 (show-all)
5605 (goto-char pos)
5606 (and (window-live-p cwin) (select-window cwin))))
5608 (defun org-get-indirect-buffer (&optional buffer)
5609 (setq buffer (or buffer (current-buffer)))
5610 (let ((n 1) (base (buffer-name buffer)) bname)
5611 (while (buffer-live-p
5612 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5613 (setq n (1+ n)))
5614 (condition-case nil
5615 (make-indirect-buffer buffer bname 'clone)
5616 (error (make-indirect-buffer buffer bname)))))
5618 (defun org-set-frame-title (title)
5619 "Set the title of the current frame to the string TITLE."
5620 ;; FIXME: how to name a single frame in XEmacs???
5621 (unless (featurep 'xemacs)
5622 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5624 ;;;; Structure editing
5626 ;;; Inserting headlines
5628 (defun org-insert-heading (&optional force-heading)
5629 "Insert a new heading or item with same depth at point.
5630 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5631 If point is at the beginning of a headline, insert a sibling before the
5632 current headline. If point is in the middle of a headline, split the headline
5633 at that position and make the rest of the headline part of the sibling below
5634 the current headline."
5635 (interactive "P")
5636 (if (= (buffer-size) 0)
5637 (insert "\n* ")
5638 (when (or force-heading (not (org-insert-item)))
5639 (let* ((head (save-excursion
5640 (condition-case nil
5641 (progn
5642 (org-back-to-heading)
5643 (match-string 0))
5644 (error "*"))))
5645 (blank (cdr (assq 'heading org-blank-before-new-entry)))
5646 pos)
5647 (cond
5648 ((and (org-on-heading-p) (bolp)
5649 (or (bobp)
5650 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5651 (open-line (if blank 2 1)))
5652 ((and (bolp)
5653 (or (bobp)
5654 (save-excursion
5655 (backward-char 1) (not (org-invisible-p)))))
5656 nil)
5657 (t (newline (if blank 2 1))))
5658 (insert head) (just-one-space)
5659 (setq pos (point))
5660 (end-of-line 1)
5661 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5662 (run-hooks 'org-insert-heading-hook)))))
5664 (defun org-insert-heading-after-current ()
5665 "Insert a new heading with same level as current, after current subtree."
5666 (interactive)
5667 (org-back-to-heading)
5668 (org-insert-heading)
5669 (org-move-subtree-down)
5670 (end-of-line 1))
5672 (defun org-insert-todo-heading (arg)
5673 "Insert a new heading with the same level and TODO state as current heading.
5674 If the heading has no TODO state, or if the state is DONE, use the first
5675 state (TODO by default). Also with prefix arg, force first state."
5676 (interactive "P")
5677 (when (not (org-insert-item 'checkbox))
5678 (org-insert-heading)
5679 (save-excursion
5680 (org-back-to-heading)
5681 (outline-previous-heading)
5682 (looking-at org-todo-line-regexp))
5683 (if (or arg
5684 (not (match-beginning 2))
5685 (member (match-string 2) org-done-keywords))
5686 (insert (car org-todo-keywords-1) " ")
5687 (insert (match-string 2) " "))))
5689 (defun org-insert-subheading (arg)
5690 "Insert a new subheading and demote it.
5691 Works for outline headings and for plain lists alike."
5692 (interactive "P")
5693 (org-insert-heading arg)
5694 (cond
5695 ((org-on-heading-p) (org-do-demote))
5696 ((org-at-item-p) (org-indent-item 1))))
5698 (defun org-insert-todo-subheading (arg)
5699 "Insert a new subheading with TODO keyword or checkbox and demote it.
5700 Works for outline headings and for plain lists alike."
5701 (interactive "P")
5702 (org-insert-todo-heading arg)
5703 (cond
5704 ((org-on-heading-p) (org-do-demote))
5705 ((org-at-item-p) (org-indent-item 1))))
5707 ;;; Promotion and Demotion
5709 (defun org-promote-subtree ()
5710 "Promote the entire subtree.
5711 See also `org-promote'."
5712 (interactive)
5713 (save-excursion
5714 (org-map-tree 'org-promote))
5715 (org-fix-position-after-promote))
5717 (defun org-demote-subtree ()
5718 "Demote the entire subtree. See `org-demote'.
5719 See also `org-promote'."
5720 (interactive)
5721 (save-excursion
5722 (org-map-tree 'org-demote))
5723 (org-fix-position-after-promote))
5726 (defun org-do-promote ()
5727 "Promote the current heading higher up the tree.
5728 If the region is active in `transient-mark-mode', promote all headings
5729 in the region."
5730 (interactive)
5731 (save-excursion
5732 (if (org-region-active-p)
5733 (org-map-region 'org-promote (region-beginning) (region-end))
5734 (org-promote)))
5735 (org-fix-position-after-promote))
5737 (defun org-do-demote ()
5738 "Demote the current heading lower down the tree.
5739 If the region is active in `transient-mark-mode', demote all headings
5740 in the region."
5741 (interactive)
5742 (save-excursion
5743 (if (org-region-active-p)
5744 (org-map-region 'org-demote (region-beginning) (region-end))
5745 (org-demote)))
5746 (org-fix-position-after-promote))
5748 (defun org-fix-position-after-promote ()
5749 "Make sure that after pro/demotion cursor position is right."
5750 (let ((pos (point)))
5751 (when (save-excursion
5752 (beginning-of-line 1)
5753 (looking-at org-todo-line-regexp)
5754 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5755 (cond ((eobp) (insert " "))
5756 ((eolp) (insert " "))
5757 ((equal (char-after) ?\ ) (forward-char 1))))))
5759 (defun org-reduced-level (l)
5760 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5762 (defun org-get-legal-level (level &optional change)
5763 "Rectify a level change under the influence of `org-odd-levels-only'
5764 LEVEL is a current level, CHANGE is by how much the level should be
5765 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5766 even level numbers will become the next higher odd number."
5767 (if org-odd-levels-only
5768 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5769 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5770 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5771 (max 1 (+ level change))))
5773 (defun org-promote ()
5774 "Promote the current heading higher up the tree.
5775 If the region is active in `transient-mark-mode', promote all headings
5776 in the region."
5777 (org-back-to-heading t)
5778 (let* ((level (save-match-data (funcall outline-level)))
5779 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
5780 (diff (abs (- level (length up-head) -1))))
5781 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5782 (replace-match up-head nil t)
5783 ;; Fixup tag positioning
5784 (and org-auto-align-tags (org-set-tags nil t))
5785 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5787 (defun org-demote ()
5788 "Demote the current heading lower down the tree.
5789 If the region is active in `transient-mark-mode', demote all headings
5790 in the region."
5791 (org-back-to-heading t)
5792 (let* ((level (save-match-data (funcall outline-level)))
5793 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
5794 (diff (abs (- level (length down-head) -1))))
5795 (replace-match down-head nil t)
5796 ;; Fixup tag positioning
5797 (and org-auto-align-tags (org-set-tags nil t))
5798 (if org-adapt-indentation (org-fixup-indentation diff))))
5800 (defun org-map-tree (fun)
5801 "Call FUN for every heading underneath the current one."
5802 (org-back-to-heading)
5803 (let ((level (funcall outline-level)))
5804 (save-excursion
5805 (funcall fun)
5806 (while (and (progn
5807 (outline-next-heading)
5808 (> (funcall outline-level) level))
5809 (not (eobp)))
5810 (funcall fun)))))
5812 (defun org-map-region (fun beg end)
5813 "Call FUN for every heading between BEG and END."
5814 (let ((org-ignore-region t))
5815 (save-excursion
5816 (setq end (copy-marker end))
5817 (goto-char beg)
5818 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5819 (< (point) end))
5820 (funcall fun))
5821 (while (and (progn
5822 (outline-next-heading)
5823 (< (point) end))
5824 (not (eobp)))
5825 (funcall fun)))))
5827 (defun org-fixup-indentation (diff)
5828 "Change the indentation in the current entry by DIFF
5829 However, if any line in the current entry has no indentation, or if it
5830 would end up with no indentation after the change, nothing at all is done."
5831 (save-excursion
5832 (let ((end (save-excursion (outline-next-heading)
5833 (point-marker)))
5834 (prohibit (if (> diff 0)
5835 "^\\S-"
5836 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5837 col)
5838 (unless (save-excursion (end-of-line 1)
5839 (re-search-forward prohibit end t))
5840 (while (re-search-forward "^[ \t]+" end t)
5841 (goto-char (match-end 0))
5842 (setq col (current-column))
5843 (if (< diff 0) (replace-match ""))
5844 (indent-to (+ diff col))))
5845 (move-marker end nil))))
5847 (defun org-convert-to-odd-levels ()
5848 "Convert an org-mode file with all levels allowed to one with odd levels.
5849 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5850 level 5 etc."
5851 (interactive)
5852 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5853 (let ((org-odd-levels-only nil) n)
5854 (save-excursion
5855 (goto-char (point-min))
5856 (while (re-search-forward "^\\*\\*+ " nil t)
5857 (setq n (- (length (match-string 0)) 2))
5858 (while (>= (setq n (1- n)) 0)
5859 (org-demote))
5860 (end-of-line 1))))))
5863 (defun org-convert-to-oddeven-levels ()
5864 "Convert an org-mode file with only odd levels to one with odd and even levels.
5865 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5866 section with an even level, conversion would destroy the structure of the file. An error
5867 is signaled in this case."
5868 (interactive)
5869 (goto-char (point-min))
5870 ;; First check if there are no even levels
5871 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5872 (org-show-context t)
5873 (error "Not all levels are odd in this file. Conversion not possible."))
5874 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5875 (let ((org-odd-levels-only nil) n)
5876 (save-excursion
5877 (goto-char (point-min))
5878 (while (re-search-forward "^\\*\\*+ " nil t)
5879 (setq n (/ (1- (length (match-string 0))) 2))
5880 (while (>= (setq n (1- n)) 0)
5881 (org-promote))
5882 (end-of-line 1))))))
5884 (defun org-tr-level (n)
5885 "Make N odd if required."
5886 (if org-odd-levels-only (1+ (/ n 2)) n))
5888 ;;; Vertical tree motion, cutting and pasting of subtrees
5890 (defun org-move-subtree-up (&optional arg)
5891 "Move the current subtree up past ARG headlines of the same level."
5892 (interactive "p")
5893 (org-move-subtree-down (- (prefix-numeric-value arg))))
5895 (defun org-move-subtree-down (&optional arg)
5896 "Move the current subtree down past ARG headlines of the same level."
5897 (interactive "p")
5898 (setq arg (prefix-numeric-value arg))
5899 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5900 'outline-get-last-sibling))
5901 (ins-point (make-marker))
5902 (cnt (abs arg))
5903 beg end txt folded)
5904 ;; Select the tree
5905 (org-back-to-heading)
5906 (setq beg (point))
5907 (save-match-data
5908 (save-excursion (outline-end-of-heading)
5909 (setq folded (org-invisible-p)))
5910 (outline-end-of-subtree))
5911 (outline-next-heading)
5912 (setq end (point))
5913 ;; Find insertion point, with error handling
5914 (goto-char beg)
5915 (while (> cnt 0)
5916 (or (and (funcall movfunc) (looking-at outline-regexp))
5917 (progn (goto-char beg)
5918 (error "Cannot move past superior level or buffer limit")))
5919 (setq cnt (1- cnt)))
5920 (if (> arg 0)
5921 ;; Moving forward - still need to move over subtree
5922 (progn (outline-end-of-subtree)
5923 (outline-next-heading)
5924 (if (not (or (looking-at (concat "^" outline-regexp))
5925 (bolp)))
5926 (newline))))
5927 (move-marker ins-point (point))
5928 (setq txt (buffer-substring beg end))
5929 (delete-region beg end)
5930 (insert txt)
5931 (or (bolp) (insert "\n"))
5932 (goto-char ins-point)
5933 (if folded (hide-subtree))
5934 (move-marker ins-point nil)))
5936 (defvar org-subtree-clip ""
5937 "Clipboard for cut and paste of subtrees.
5938 This is actually only a copy of the kill, because we use the normal kill
5939 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5941 (defvar org-subtree-clip-folded nil
5942 "Was the last copied subtree folded?
5943 This is used to fold the tree back after pasting.")
5945 (defun org-cut-subtree (&optional n)
5946 "Cut the current subtree into the clipboard.
5947 With prefix arg N, cut this many sequential subtrees.
5948 This is a short-hand for marking the subtree and then cutting it."
5949 (interactive "p")
5950 (org-copy-subtree n 'cut))
5952 (defun org-copy-subtree (&optional n cut)
5953 "Cut the current subtree into the clipboard.
5954 With prefix arg N, cut this many sequential subtrees.
5955 This is a short-hand for marking the subtree and then copying it.
5956 If CUT is non-nil, actually cut the subtree."
5957 (interactive "p")
5958 (let (beg end folded)
5959 (if (interactive-p)
5960 (org-back-to-heading nil) ; take what looks like a subtree
5961 (org-back-to-heading t)) ; take what is really there
5962 (setq beg (point))
5963 (save-match-data
5964 (save-excursion (outline-end-of-heading)
5965 (setq folded (org-invisible-p)))
5966 (condition-case nil
5967 (outline-forward-same-level (1- n))
5968 (error nil))
5969 (org-end-of-subtree t t))
5970 (setq end (point))
5971 (goto-char beg)
5972 (when (> end beg)
5973 (setq org-subtree-clip-folded folded)
5974 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5975 (setq org-subtree-clip (current-kill 0))
5976 (message "%s: Subtree(s) with %d characters"
5977 (if cut "Cut" "Copied")
5978 (length org-subtree-clip)))))
5980 (defun org-paste-subtree (&optional level tree)
5981 "Paste the clipboard as a subtree, with modification of headline level.
5982 The entire subtree is promoted or demoted in order to match a new headline
5983 level. By default, the new level is derived from the visible headings
5984 before and after the insertion point, and taken to be the inferior headline
5985 level of the two. So if the previous visible heading is level 3 and the
5986 next is level 4 (or vice versa), level 4 will be used for insertion.
5987 This makes sure that the subtree remains an independent subtree and does
5988 not swallow low level entries.
5990 You can also force a different level, either by using a numeric prefix
5991 argument, or by inserting the heading marker by hand. For example, if the
5992 cursor is after \"*****\", then the tree will be shifted to level 5.
5994 If you want to insert the tree as is, just use \\[yank].
5996 If optional TREE is given, use this text instead of the kill ring."
5997 (interactive "P")
5998 (unless (org-kill-is-subtree-p tree)
5999 (error
6000 (substitute-command-keys
6001 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6002 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6003 (^re (concat "^\\(" outline-regexp "\\)"))
6004 (re (concat "\\(" outline-regexp "\\)"))
6005 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6007 (old-level (if (string-match ^re txt)
6008 (- (match-end 0) (match-beginning 0) 1)
6009 -1))
6010 (force-level (cond (level (prefix-numeric-value level))
6011 ((string-match
6012 ^re_ (buffer-substring (point-at-bol) (point)))
6013 (- (match-end 1) (match-beginning 1)))
6014 (t nil)))
6015 (previous-level (save-excursion
6016 (condition-case nil
6017 (progn
6018 (outline-previous-visible-heading 1)
6019 (if (looking-at re)
6020 (- (match-end 0) (match-beginning 0) 1)
6022 (error 1))))
6023 (next-level (save-excursion
6024 (condition-case nil
6025 (progn
6026 (or (looking-at outline-regexp)
6027 (outline-next-visible-heading 1))
6028 (if (looking-at re)
6029 (- (match-end 0) (match-beginning 0) 1)
6031 (error 1))))
6032 (new-level (or force-level (max previous-level next-level)))
6033 (shift (if (or (= old-level -1)
6034 (= new-level -1)
6035 (= old-level new-level))
6037 (- new-level old-level)))
6038 (delta (if (> shift 0) -1 1))
6039 (func (if (> shift 0) 'org-demote 'org-promote))
6040 (org-odd-levels-only nil)
6041 beg end)
6042 ;; Remove the forced level indicator
6043 (if force-level
6044 (delete-region (point-at-bol) (point)))
6045 ;; Paste
6046 (beginning-of-line 1)
6047 (setq beg (point))
6048 (insert txt)
6049 (unless (string-match "\n[ \t]*\\'" txt) (insert "\n"))
6050 (setq end (point))
6051 (goto-char beg)
6052 ;; Shift if necessary
6053 (unless (= shift 0)
6054 (save-restriction
6055 (narrow-to-region beg end)
6056 (while (not (= shift 0))
6057 (org-map-region func (point-min) (point-max))
6058 (setq shift (+ delta shift)))
6059 (goto-char (point-min))))
6060 (when (interactive-p)
6061 (message "Clipboard pasted as level %d subtree" new-level))
6062 (if (and kill-ring
6063 (eq org-subtree-clip (current-kill 0))
6064 org-subtree-clip-folded)
6065 ;; The tree was folded before it was killed/copied
6066 (hide-subtree))))
6068 (defun org-kill-is-subtree-p (&optional txt)
6069 "Check if the current kill is an outline subtree, or a set of trees.
6070 Returns nil if kill does not start with a headline, or if the first
6071 headline level is not the largest headline level in the tree.
6072 So this will actually accept several entries of equal levels as well,
6073 which is OK for `org-paste-subtree'.
6074 If optional TXT is given, check this string instead of the current kill."
6075 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6076 (start-level (and kill
6077 (string-match (concat "\\`" org-outline-regexp) kill)
6078 (- (match-end 0) (match-beginning 0) 1)))
6079 (re (concat "^" org-outline-regexp))
6080 (start 1))
6081 (if (not start-level)
6082 (progn
6083 nil) ;; does not even start with a heading
6084 (catch 'exit
6085 (while (setq start (string-match re kill (1+ start)))
6086 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6087 (throw 'exit nil)))
6088 t))))
6090 (defun org-narrow-to-subtree ()
6091 "Narrow buffer to the current subtree."
6092 (interactive)
6093 (save-excursion
6094 (narrow-to-region
6095 (progn (org-back-to-heading) (point))
6096 (progn (org-end-of-subtree t t) (point)))))
6099 ;;; Outline Sorting
6101 (defun org-sort (with-case)
6102 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6103 Optional argument WITH-CASE means sort case-sensitively."
6104 (interactive "P")
6105 (if (org-at-table-p)
6106 (org-call-with-arg 'org-table-sort-lines with-case)
6107 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6109 (defvar org-priority-regexp) ; defined later in the file
6111 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6112 "Sort entries on a certain level of an outline tree.
6113 If there is an active region, the entries in the region are sorted.
6114 Else, if the cursor is before the first entry, sort the top-level items.
6115 Else, the children of the entry at point are sorted.
6117 Sorting can be alphabetically, numerically, and by date/time as given by
6118 the first time stamp in the entry. The command prompts for the sorting
6119 type unless it has been given to the function through the SORTING-TYPE
6120 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6121 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6122 called with point at the beginning of the record. It must return either
6123 a string or a number that should serve as the sorting key for that record.
6125 Comparing entries ignores case by default. However, with an optional argument
6126 WITH-CASE, the sorting considers case as well."
6127 (interactive "P")
6128 (let ((case-func (if with-case 'identity 'downcase))
6129 start beg end stars re re2
6130 txt what tmp plain-list-p)
6131 ;; Find beginning and end of region to sort
6132 (cond
6133 ((org-region-active-p)
6134 ;; we will sort the region
6135 (setq end (region-end)
6136 what "region")
6137 (goto-char (region-beginning))
6138 (if (not (org-on-heading-p)) (outline-next-heading))
6139 (setq start (point)))
6140 ((org-at-item-p)
6141 ;; we will sort this plain list
6142 (org-beginning-of-item-list) (setq start (point))
6143 (org-end-of-item-list) (setq end (point))
6144 (goto-char start)
6145 (setq plain-list-p t
6146 what "plain list"))
6147 ((or (org-on-heading-p)
6148 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6149 ;; we will sort the children of the current headline
6150 (org-back-to-heading)
6151 (setq start (point) end (org-end-of-subtree) what "children")
6152 (goto-char start)
6153 (show-subtree)
6154 (outline-next-heading))
6156 ;; we will sort the top-level entries in this file
6157 (goto-char (point-min))
6158 (or (org-on-heading-p) (outline-next-heading))
6159 (setq start (point) end (point-max) what "top-level")
6160 (goto-char start)
6161 (show-all)))
6163 (setq beg (point))
6164 (if (>= beg end) (error "Nothing to sort"))
6166 (unless plain-list-p
6167 (looking-at "\\(\\*+\\)")
6168 (setq stars (match-string 1)
6169 re (concat "^" (regexp-quote stars) " +")
6170 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6171 txt (buffer-substring beg end))
6172 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6173 (if (and (not (equal stars "*")) (string-match re2 txt))
6174 (error "Region to sort contains a level above the first entry")))
6176 (unless sorting-type
6177 (message
6178 (if plain-list-p
6179 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6180 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
6181 what)
6182 (setq sorting-type (read-char-exclusive))
6184 (and (= (downcase sorting-type) ?f)
6185 (setq getkey-func
6186 (completing-read "Sort using function: "
6187 obarray 'fboundp t nil nil))
6188 (setq getkey-func (intern getkey-func)))
6190 (and (= (downcase sorting-type) ?r)
6191 (setq property
6192 (completing-read "Property: "
6193 (mapcar 'list (org-buffer-property-keys t))
6194 nil t))))
6196 (message "Sorting entries...")
6198 (save-restriction
6199 (narrow-to-region start end)
6201 (let ((dcst (downcase sorting-type))
6202 (now (current-time)))
6203 (sort-subr
6204 (/= dcst sorting-type)
6205 ;; This function moves to the beginning character of the "record" to
6206 ;; be sorted.
6207 (if plain-list-p
6208 (lambda nil
6209 (if (org-at-item-p) t (goto-char (point-max))))
6210 (lambda nil
6211 (if (re-search-forward re nil t)
6212 (goto-char (match-beginning 0))
6213 (goto-char (point-max)))))
6214 ;; This function moves to the last character of the "record" being
6215 ;; sorted.
6216 (if plain-list-p
6217 'org-end-of-item
6218 (lambda nil
6219 (save-match-data
6220 (condition-case nil
6221 (outline-forward-same-level 1)
6222 (error
6223 (goto-char (point-max)))))))
6225 ;; This function returns the value that gets sorted against.
6226 (if plain-list-p
6227 (lambda nil
6228 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6229 (cond
6230 ((= dcst ?n)
6231 (string-to-number (buffer-substring (match-end 0)
6232 (line-end-position))))
6233 ((= dcst ?a)
6234 (buffer-substring (match-end 0) (line-end-position)))
6235 ((= dcst ?t)
6236 (if (re-search-forward org-ts-regexp
6237 (line-end-position) t)
6238 (org-time-string-to-time (match-string 0))
6239 now))
6240 ((= dcst ?f)
6241 (if getkey-func
6242 (progn
6243 (setq tmp (funcall getkey-func))
6244 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6245 tmp)
6246 (error "Invalid key function `%s'" getkey-func)))
6247 (t (error "Invalid sorting type `%c'" sorting-type)))))
6248 (lambda nil
6249 (cond
6250 ((= dcst ?n)
6251 (if (looking-at outline-regexp)
6252 (string-to-number (buffer-substring (match-end 0)
6253 (line-end-position)))
6254 nil))
6255 ((= dcst ?a)
6256 (funcall case-func (buffer-substring (line-beginning-position)
6257 (line-end-position))))
6258 ((= dcst ?t)
6259 (if (re-search-forward org-ts-regexp
6260 (save-excursion
6261 (forward-line 2)
6262 (point)) t)
6263 (org-time-string-to-time (match-string 0))
6264 now))
6265 ((= dcst ?p)
6266 (if (re-search-forward org-priority-regexp (line-end-position) t)
6267 (string-to-char (match-string 2))
6268 org-default-priority))
6269 ((= dcst ?r)
6270 (or (org-entry-get nil property) ""))
6271 ((= dcst ?f)
6272 (if getkey-func
6273 (progn
6274 (setq tmp (funcall getkey-func))
6275 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6276 tmp)
6277 (error "Invalid key function `%s'" getkey-func)))
6278 (t (error "Invalid sorting type `%c'" sorting-type)))))
6280 (cond
6281 ((= dcst ?a) 'string<)
6282 ((= dcst ?t) 'time-less-p)
6283 (t nil)))))
6284 (message "Sorting entries...done")))
6286 (defun org-do-sort (table what &optional with-case sorting-type)
6287 "Sort TABLE of WHAT according to SORTING-TYPE.
6288 The user will be prompted for the SORTING-TYPE if the call to this
6289 function does not specify it. WHAT is only for the prompt, to indicate
6290 what is being sorted. The sorting key will be extracted from
6291 the car of the elements of the table.
6292 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6293 (unless sorting-type
6294 (message
6295 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6296 what)
6297 (setq sorting-type (read-char-exclusive)))
6298 (let ((dcst (downcase sorting-type))
6299 extractfun comparefun)
6300 ;; Define the appropriate functions
6301 (cond
6302 ((= dcst ?n)
6303 (setq extractfun 'string-to-number
6304 comparefun (if (= dcst sorting-type) '< '>)))
6305 ((= dcst ?a)
6306 (setq extractfun (if with-case 'identity 'downcase)
6307 comparefun (if (= dcst sorting-type)
6308 'string<
6309 (lambda (a b) (and (not (string< a b))
6310 (not (string= a b)))))))
6311 ((= dcst ?t)
6312 (setq extractfun
6313 (lambda (x)
6314 (if (string-match org-ts-regexp x)
6315 (time-to-seconds
6316 (org-time-string-to-time (match-string 0 x)))
6318 comparefun (if (= dcst sorting-type) '< '>)))
6319 (t (error "Invalid sorting type `%c'" sorting-type)))
6321 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6322 table)
6323 (lambda (a b) (funcall comparefun (car a) (car b))))))
6325 ;;;; Plain list items, including checkboxes
6327 ;;; Plain list items
6329 (defun org-at-item-p ()
6330 "Is point in a line starting a hand-formatted item?"
6331 (let ((llt org-plain-list-ordered-item-terminator))
6332 (save-excursion
6333 (goto-char (point-at-bol))
6334 (looking-at
6335 (cond
6336 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6337 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6338 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6339 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
6341 (defun org-in-item-p ()
6342 "It the cursor inside a plain list item.
6343 Does not have to be the first line."
6344 (save-excursion
6345 (condition-case nil
6346 (progn
6347 (org-beginning-of-item)
6348 (org-at-item-p)
6350 (error nil))))
6352 (defun org-insert-item (&optional checkbox)
6353 "Insert a new item at the current level.
6354 Return t when things worked, nil when we are not in an item."
6355 (when (save-excursion
6356 (condition-case nil
6357 (progn
6358 (org-beginning-of-item)
6359 (org-at-item-p)
6360 (if (org-invisible-p) (error "Invisible item"))
6362 (error nil)))
6363 (let* ((bul (match-string 0))
6364 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
6365 (match-end 0)))
6366 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
6367 pos)
6368 (cond
6369 ((and (org-at-item-p) (<= (point) eow))
6370 ;; before the bullet
6371 (beginning-of-line 1)
6372 (open-line (if blank 2 1)))
6373 ((<= (point) eow)
6374 (beginning-of-line 1))
6375 (t (newline (if blank 2 1))))
6376 (insert bul (if checkbox "[ ]" ""))
6377 (just-one-space)
6378 (setq pos (point))
6379 (end-of-line 1)
6380 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
6381 (org-maybe-renumber-ordered-list)
6382 (and checkbox (org-update-checkbox-count-maybe))
6385 ;;; Checkboxes
6387 (defun org-at-item-checkbox-p ()
6388 "Is point at a line starting a plain-list item with a checklet?"
6389 (and (org-at-item-p)
6390 (save-excursion
6391 (goto-char (match-end 0))
6392 (skip-chars-forward " \t")
6393 (looking-at "\\[[- X]\\]"))))
6395 (defun org-toggle-checkbox (&optional arg)
6396 "Toggle the checkbox in the current line."
6397 (interactive "P")
6398 (catch 'exit
6399 (let (beg end status (firstnew 'unknown))
6400 (cond
6401 ((org-region-active-p)
6402 (setq beg (region-beginning) end (region-end)))
6403 ((org-on-heading-p)
6404 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
6405 ((org-at-item-checkbox-p)
6406 (save-excursion
6407 (replace-match
6408 (cond (arg "[-]")
6409 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
6410 (t "[ ]"))
6411 t t))
6412 (throw 'exit t))
6413 (t (error "Not at a checkbox or heading, and no active region")))
6414 (save-excursion
6415 (goto-char beg)
6416 (while (< (point) end)
6417 (when (org-at-item-checkbox-p)
6418 (setq status (equal (match-string 0) "[X]"))
6419 (when (eq firstnew 'unknown)
6420 (setq firstnew (not status)))
6421 (replace-match
6422 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
6423 (beginning-of-line 2)))))
6424 (org-update-checkbox-count-maybe))
6426 (defun org-update-checkbox-count-maybe ()
6427 "Update checkbox statistics unless turned off by user."
6428 (when org-provide-checkbox-statistics
6429 (org-update-checkbox-count)))
6431 (defun org-update-checkbox-count (&optional all)
6432 "Update the checkbox statistics in the current section.
6433 This will find all statistic cookies like [57%] and [6/12] and update them
6434 with the current numbers. With optional prefix argument ALL, do this for
6435 the whole buffer."
6436 (interactive "P")
6437 (save-excursion
6438 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
6439 (beg (condition-case nil
6440 (progn (outline-back-to-heading) (point))
6441 (error (point-min))))
6442 (end (move-marker (make-marker)
6443 (progn (outline-next-heading) (point))))
6444 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
6445 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
6446 b1 e1 f1 c-on c-off lim (cstat 0))
6447 (when all
6448 (goto-char (point-min))
6449 (outline-next-heading)
6450 (setq beg (point) end (point-max)))
6451 (goto-char beg)
6452 (while (re-search-forward re end t)
6453 (setq cstat (1+ cstat)
6454 b1 (match-beginning 0)
6455 e1 (match-end 0)
6456 f1 (match-beginning 1)
6457 lim (cond
6458 ((org-on-heading-p) (outline-next-heading) (point))
6459 ((org-at-item-p) (org-end-of-item) (point))
6460 (t nil))
6461 c-on 0 c-off 0)
6462 (goto-char e1)
6463 (when lim
6464 (while (re-search-forward re-box lim t)
6465 (if (member (match-string 2) '("[ ]" "[-]"))
6466 (setq c-off (1+ c-off))
6467 (setq c-on (1+ c-on))))
6468 ; (delete-region b1 e1)
6469 (goto-char b1)
6470 (insert (if f1
6471 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
6472 (format "[%d/%d]" c-on (+ c-on c-off))))
6473 (and (looking-at "\\[.*?\\]")
6474 (replace-match ""))))
6475 (when (interactive-p)
6476 (message "Checkbox satistics updated %s (%d places)"
6477 (if all "in entire file" "in current outline entry") cstat)))))
6479 (defun org-get-checkbox-statistics-face ()
6480 "Select the face for checkbox statistics.
6481 The face will be `org-done' when all relevant boxes are checked. Otherwise
6482 it will be `org-todo'."
6483 (if (match-end 1)
6484 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
6485 (if (and (> (match-end 2) (match-beginning 2))
6486 (equal (match-string 2) (match-string 3)))
6487 'org-done
6488 'org-todo)))
6490 (defun org-get-indentation (&optional line)
6491 "Get the indentation of the current line, interpreting tabs.
6492 When LINE is given, assume it represents a line and compute its indentation."
6493 (if line
6494 (if (string-match "^ *" (org-remove-tabs line))
6495 (match-end 0))
6496 (save-excursion
6497 (beginning-of-line 1)
6498 (skip-chars-forward " \t")
6499 (current-column))))
6501 (defun org-remove-tabs (s &optional width)
6502 "Replace tabulators in S with spaces.
6503 Assumes that s is a single line, starting in column 0."
6504 (setq width (or width tab-width))
6505 (while (string-match "\t" s)
6506 (setq s (replace-match
6507 (make-string
6508 (- (* width (/ (+ (match-beginning 0) width) width))
6509 (match-beginning 0)) ?\ )
6510 t t s)))
6513 (defun org-fix-indentation (line ind)
6514 "Fix indentation in LINE.
6515 IND is a cons cell with target and minimum indentation.
6516 If the current indenation in LINE is smaller than the minimum,
6517 leave it alone. If it is larger than ind, set it to the target."
6518 (let* ((l (org-remove-tabs line))
6519 (i (org-get-indentation l))
6520 (i1 (car ind)) (i2 (cdr ind)))
6521 (if (>= i i2) (setq l (substring line i2)))
6522 (if (> i1 0)
6523 (concat (make-string i1 ?\ ) l)
6524 l)))
6526 (defcustom org-empty-line-terminates-plain-lists nil
6527 "Non-nil means, an empty line ends all plain list levels.
6528 When nil, empty lines are part of the preceeding item."
6529 :group 'org-plain-lists
6530 :type 'boolean)
6532 (defun org-beginning-of-item ()
6533 "Go to the beginning of the current hand-formatted item.
6534 If the cursor is not in an item, throw an error."
6535 (interactive)
6536 (let ((pos (point))
6537 (limit (save-excursion
6538 (condition-case nil
6539 (progn
6540 (org-back-to-heading)
6541 (beginning-of-line 2) (point))
6542 (error (point-min)))))
6543 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
6544 ind ind1)
6545 (if (org-at-item-p)
6546 (beginning-of-line 1)
6547 (beginning-of-line 1)
6548 (skip-chars-forward " \t")
6549 (setq ind (current-column))
6550 (if (catch 'exit
6551 (while t
6552 (beginning-of-line 0)
6553 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
6555 (if (looking-at "[ \t]*$")
6556 (setq ind1 ind-empty)
6557 (skip-chars-forward " \t")
6558 (setq ind1 (current-column)))
6559 (if (< ind1 ind)
6560 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
6562 (goto-char pos)
6563 (error "Not in an item")))))
6565 (defun org-end-of-item ()
6566 "Go to the end of the current hand-formatted item.
6567 If the cursor is not in an item, throw an error."
6568 (interactive)
6569 (let* ((pos (point))
6570 ind1
6571 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
6572 (limit (save-excursion (outline-next-heading) (point)))
6573 (ind (save-excursion
6574 (org-beginning-of-item)
6575 (skip-chars-forward " \t")
6576 (current-column)))
6577 (end (catch 'exit
6578 (while t
6579 (beginning-of-line 2)
6580 (if (eobp) (throw 'exit (point)))
6581 (if (>= (point) limit) (throw 'exit (point-at-bol)))
6582 (if (looking-at "[ \t]*$")
6583 (setq ind1 ind-empty)
6584 (skip-chars-forward " \t")
6585 (setq ind1 (current-column)))
6586 (if (<= ind1 ind)
6587 (throw 'exit (point-at-bol)))))))
6588 (if end
6589 (goto-char end)
6590 (goto-char pos)
6591 (error "Not in an item"))))
6593 (defun org-next-item ()
6594 "Move to the beginning of the next item in the current plain list.
6595 Error if not at a plain list, or if this is the last item in the list."
6596 (interactive)
6597 (let (ind ind1 (pos (point)))
6598 (org-beginning-of-item)
6599 (setq ind (org-get-indentation))
6600 (org-end-of-item)
6601 (setq ind1 (org-get-indentation))
6602 (unless (and (org-at-item-p) (= ind ind1))
6603 (goto-char pos)
6604 (error "On last item"))))
6606 (defun org-previous-item ()
6607 "Move to the beginning of the previous item in the current plain list.
6608 Error if not at a plain list, or if this is the first item in the list."
6609 (interactive)
6610 (let (beg ind ind1 (pos (point)))
6611 (org-beginning-of-item)
6612 (setq beg (point))
6613 (setq ind (org-get-indentation))
6614 (goto-char beg)
6615 (catch 'exit
6616 (while t
6617 (beginning-of-line 0)
6618 (if (looking-at "[ \t]*$")
6620 (if (<= (setq ind1 (org-get-indentation)) ind)
6621 (throw 'exit t)))))
6622 (condition-case nil
6623 (if (or (not (org-at-item-p))
6624 (< ind1 (1- ind)))
6625 (error "")
6626 (org-beginning-of-item))
6627 (error (goto-char pos)
6628 (error "On first item")))))
6630 (defun org-move-item-down ()
6631 "Move the plain list item at point down, i.e. swap with following item.
6632 Subitems (items with larger indentation) are considered part of the item,
6633 so this really moves item trees."
6634 (interactive)
6635 (let (beg end ind ind1 (pos (point)) txt)
6636 (org-beginning-of-item)
6637 (setq beg (point))
6638 (setq ind (org-get-indentation))
6639 (org-end-of-item)
6640 (setq end (point))
6641 (setq ind1 (org-get-indentation))
6642 (if (and (org-at-item-p) (= ind ind1))
6643 (progn
6644 (org-end-of-item)
6645 (setq txt (buffer-substring beg end))
6646 (save-excursion
6647 (delete-region beg end))
6648 (setq pos (point))
6649 (insert txt)
6650 (goto-char pos)
6651 (org-maybe-renumber-ordered-list))
6652 (goto-char pos)
6653 (error "Cannot move this item further down"))))
6655 (defun org-move-item-up (arg)
6656 "Move the plain list item at point up, i.e. swap with previous item.
6657 Subitems (items with larger indentation) are considered part of the item,
6658 so this really moves item trees."
6659 (interactive "p")
6660 (let (beg end ind ind1 (pos (point)) txt)
6661 (org-beginning-of-item)
6662 (setq beg (point))
6663 (setq ind (org-get-indentation))
6664 (org-end-of-item)
6665 (setq end (point))
6666 (goto-char beg)
6667 (catch 'exit
6668 (while t
6669 (beginning-of-line 0)
6670 (if (looking-at "[ \t]*$")
6671 (if org-empty-line-terminates-plain-lists
6672 (progn
6673 (goto-char pos)
6674 (error "Cannot move this item further up"))
6675 nil)
6676 (if (<= (setq ind1 (org-get-indentation)) ind)
6677 (throw 'exit t)))))
6678 (condition-case nil
6679 (org-beginning-of-item)
6680 (error (goto-char beg)
6681 (error "Cannot move this item further up")))
6682 (setq ind1 (org-get-indentation))
6683 (if (and (org-at-item-p) (= ind ind1))
6684 (progn
6685 (setq txt (buffer-substring beg end))
6686 (save-excursion
6687 (delete-region beg end))
6688 (setq pos (point))
6689 (insert txt)
6690 (goto-char pos)
6691 (org-maybe-renumber-ordered-list))
6692 (goto-char pos)
6693 (error "Cannot move this item further up"))))
6695 (defun org-maybe-renumber-ordered-list ()
6696 "Renumber the ordered list at point if setup allows it.
6697 This tests the user option `org-auto-renumber-ordered-lists' before
6698 doing the renumbering."
6699 (interactive)
6700 (when (and org-auto-renumber-ordered-lists
6701 (org-at-item-p))
6702 (if (match-beginning 3)
6703 (org-renumber-ordered-list 1)
6704 (org-fix-bullet-type))))
6706 (defun org-maybe-renumber-ordered-list-safe ()
6707 (condition-case nil
6708 (save-excursion
6709 (org-maybe-renumber-ordered-list))
6710 (error nil)))
6712 (defun org-cycle-list-bullet (&optional which)
6713 "Cycle through the different itemize/enumerate bullets.
6714 This cycle the entire list level through the sequence:
6716 `-' -> `+' -> `*' -> `1.' -> `1)'
6718 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
6719 0 meand `-', 1 means `+' etc."
6720 (interactive "P")
6721 (org-preserve-lc
6722 (org-beginning-of-item-list)
6723 (org-at-item-p)
6724 (beginning-of-line 1)
6725 (let ((current (match-string 0))
6726 (prevp (eq which 'previous))
6727 new)
6728 (setq new (cond
6729 ((and (numberp which)
6730 (nth (1- which) '("-" "+" "*" "1." "1)"))))
6731 ((string-match "-" current) (if prevp "1)" "+"))
6732 ((string-match "\\+" current)
6733 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
6734 ((string-match "\\*" current) (if prevp "+" "1."))
6735 ((string-match "\\." current) (if prevp "*" "1)"))
6736 ((string-match ")" current) (if prevp "1." "-"))
6737 (t (error "This should not happen"))))
6738 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
6739 (org-fix-bullet-type)
6740 (org-maybe-renumber-ordered-list))))
6742 (defun org-get-string-indentation (s)
6743 "What indentation has S due to SPACE and TAB at the beginning of the string?"
6744 (let ((n -1) (i 0) (w tab-width) c)
6745 (catch 'exit
6746 (while (< (setq n (1+ n)) (length s))
6747 (setq c (aref s n))
6748 (cond ((= c ?\ ) (setq i (1+ i)))
6749 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
6750 (t (throw 'exit t)))))
6753 (defun org-renumber-ordered-list (arg)
6754 "Renumber an ordered plain list.
6755 Cursor needs to be in the first line of an item, the line that starts
6756 with something like \"1.\" or \"2)\"."
6757 (interactive "p")
6758 (unless (and (org-at-item-p)
6759 (match-beginning 3))
6760 (error "This is not an ordered list"))
6761 (let ((line (org-current-line))
6762 (col (current-column))
6763 (ind (org-get-string-indentation
6764 (buffer-substring (point-at-bol) (match-beginning 3))))
6765 ;; (term (substring (match-string 3) -1))
6766 ind1 (n (1- arg))
6767 fmt)
6768 ;; find where this list begins
6769 (org-beginning-of-item-list)
6770 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
6771 (setq fmt (concat "%d" (match-string 1)))
6772 (beginning-of-line 0)
6773 ;; walk forward and replace these numbers
6774 (catch 'exit
6775 (while t
6776 (catch 'next
6777 (beginning-of-line 2)
6778 (if (eobp) (throw 'exit nil))
6779 (if (looking-at "[ \t]*$") (throw 'next nil))
6780 (skip-chars-forward " \t") (setq ind1 (current-column))
6781 (if (> ind1 ind) (throw 'next t))
6782 (if (< ind1 ind) (throw 'exit t))
6783 (if (not (org-at-item-p)) (throw 'exit nil))
6784 (delete-region (match-beginning 2) (match-end 2))
6785 (goto-char (match-beginning 2))
6786 (insert (format fmt (setq n (1+ n)))))))
6787 (goto-line line)
6788 (move-to-column col)))
6790 (defun org-fix-bullet-type ()
6791 "Make sure all items in this list have the same bullet as the firsst item."
6792 (interactive)
6793 (unless (org-at-item-p) (error "This is not a list"))
6794 (let ((line (org-current-line))
6795 (col (current-column))
6796 (ind (current-indentation))
6797 ind1 bullet)
6798 ;; find where this list begins
6799 (org-beginning-of-item-list)
6800 (beginning-of-line 1)
6801 ;; find out what the bullet type is
6802 (looking-at "[ \t]*\\(\\S-+\\)")
6803 (setq bullet (match-string 1))
6804 ;; walk forward and replace these numbers
6805 (beginning-of-line 0)
6806 (catch 'exit
6807 (while t
6808 (catch 'next
6809 (beginning-of-line 2)
6810 (if (eobp) (throw 'exit nil))
6811 (if (looking-at "[ \t]*$") (throw 'next nil))
6812 (skip-chars-forward " \t") (setq ind1 (current-column))
6813 (if (> ind1 ind) (throw 'next t))
6814 (if (< ind1 ind) (throw 'exit t))
6815 (if (not (org-at-item-p)) (throw 'exit nil))
6816 (skip-chars-forward " \t")
6817 (looking-at "\\S-+")
6818 (replace-match bullet))))
6819 (goto-line line)
6820 (move-to-column col)
6821 (if (string-match "[0-9]" bullet)
6822 (org-renumber-ordered-list 1))))
6824 (defun org-beginning-of-item-list ()
6825 "Go to the beginning of the current item list.
6826 I.e. to the first item in this list."
6827 (interactive)
6828 (org-beginning-of-item)
6829 (let ((pos (point-at-bol))
6830 (ind (org-get-indentation))
6831 ind1)
6832 ;; find where this list begins
6833 (catch 'exit
6834 (while t
6835 (catch 'next
6836 (beginning-of-line 0)
6837 (if (looking-at "[ \t]*$")
6838 (throw (if (bobp) 'exit 'next) t))
6839 (skip-chars-forward " \t") (setq ind1 (current-column))
6840 (if (or (< ind1 ind)
6841 (and (= ind1 ind)
6842 (not (org-at-item-p)))
6843 (bobp))
6844 (throw 'exit t)
6845 (when (org-at-item-p) (setq pos (point-at-bol)))))))
6846 (goto-char pos)))
6849 (defun org-end-of-item-list ()
6850 "Go to the end of the current item list.
6851 I.e. to the text after the last item."
6852 (interactive)
6853 (org-beginning-of-item)
6854 (let ((pos (point-at-bol))
6855 (ind (org-get-indentation))
6856 ind1)
6857 ;; find where this list begins
6858 (catch 'exit
6859 (while t
6860 (catch 'next
6861 (beginning-of-line 2)
6862 (if (looking-at "[ \t]*$")
6863 (throw (if (eobp) 'exit 'next) t))
6864 (skip-chars-forward " \t") (setq ind1 (current-column))
6865 (if (or (< ind1 ind)
6866 (and (= ind1 ind)
6867 (not (org-at-item-p)))
6868 (eobp))
6869 (progn
6870 (setq pos (point-at-bol))
6871 (throw 'exit t))))))
6872 (goto-char pos)))
6875 (defvar org-last-indent-begin-marker (make-marker))
6876 (defvar org-last-indent-end-marker (make-marker))
6878 (defun org-outdent-item (arg)
6879 "Outdent a local list item."
6880 (interactive "p")
6881 (org-indent-item (- arg)))
6883 (defun org-indent-item (arg)
6884 "Indent a local list item."
6885 (interactive "p")
6886 (unless (org-at-item-p)
6887 (error "Not on an item"))
6888 (save-excursion
6889 (let (beg end ind ind1 tmp delta ind-down ind-up)
6890 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
6891 (setq beg org-last-indent-begin-marker
6892 end org-last-indent-end-marker)
6893 (org-beginning-of-item)
6894 (setq beg (move-marker org-last-indent-begin-marker (point)))
6895 (org-end-of-item)
6896 (setq end (move-marker org-last-indent-end-marker (point))))
6897 (goto-char beg)
6898 (setq tmp (org-item-indent-positions)
6899 ind (car tmp)
6900 ind-down (nth 2 tmp)
6901 ind-up (nth 1 tmp)
6902 delta (if (> arg 0)
6903 (if ind-down (- ind-down ind) 2)
6904 (if ind-up (- ind-up ind) -2)))
6905 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
6906 (while (< (point) end)
6907 (beginning-of-line 1)
6908 (skip-chars-forward " \t") (setq ind1 (current-column))
6909 (delete-region (point-at-bol) (point))
6910 (or (eolp) (indent-to-column (+ ind1 delta)))
6911 (beginning-of-line 2))))
6912 (org-fix-bullet-type)
6913 (org-maybe-renumber-ordered-list-safe)
6914 (save-excursion
6915 (beginning-of-line 0)
6916 (condition-case nil (org-beginning-of-item) (error nil))
6917 (org-maybe-renumber-ordered-list-safe)))
6919 (defun org-item-indent-positions ()
6920 "Return indentation for plain list items.
6921 This returns a list with three values: The current indentation, the
6922 parent indentation and the indentation a child should habe.
6923 Assumes cursor in item line."
6924 (let* ((bolpos (point-at-bol))
6925 (ind (org-get-indentation))
6926 ind-down ind-up pos)
6927 (save-excursion
6928 (org-beginning-of-item-list)
6929 (skip-chars-backward "\n\r \t")
6930 (when (org-in-item-p)
6931 (org-beginning-of-item)
6932 (setq ind-up (org-get-indentation))))
6933 (setq pos (point))
6934 (save-excursion
6935 (cond
6936 ((and (condition-case nil (progn (org-previous-item) t)
6937 (error nil))
6938 (or (forward-char 1) t)
6939 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
6940 (setq ind-down (org-get-indentation)))
6941 ((and (goto-char pos)
6942 (org-at-item-p))
6943 (goto-char (match-end 0))
6944 (skip-chars-forward " \t")
6945 (setq ind-down (current-column)))))
6946 (list ind ind-up ind-down)))
6948 ;;; The orgstruct minor mode
6950 ;; Define a minor mode which can be used in other modes in order to
6951 ;; integrate the org-mode structure editing commands.
6953 ;; This is really a hack, because the org-mode structure commands use
6954 ;; keys which normally belong to the major mode. Here is how it
6955 ;; works: The minor mode defines all the keys necessary to operate the
6956 ;; structure commands, but wraps the commands into a function which
6957 ;; tests if the cursor is currently at a headline or a plain list
6958 ;; item. If that is the case, the structure command is used,
6959 ;; temporarily setting many Org-mode variables like regular
6960 ;; expressions for filling etc. However, when any of those keys is
6961 ;; used at a different location, function uses `key-binding' to look
6962 ;; up if the key has an associated command in another currently active
6963 ;; keymap (minor modes, major mode, global), and executes that
6964 ;; command. There might be problems if any of the keys is otherwise
6965 ;; used as a prefix key.
6967 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6968 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6969 ;; addresses this by checking explicitly for both bindings.
6971 (defvar orgstruct-mode-map (make-sparse-keymap)
6972 "Keymap for the minor `orgstruct-mode'.")
6974 (defvar org-local-vars nil
6975 "List of local variables, for use by `orgstruct-mode'")
6977 ;;;###autoload
6978 (define-minor-mode orgstruct-mode
6979 "Toggle the minor more `orgstruct-mode'.
6980 This mode is for using Org-mode structure commands in other modes.
6981 The following key behave as if Org-mode was active, if the cursor
6982 is on a headline, or on a plain list item (both in the definition
6983 of Org-mode).
6985 M-up Move entry/item up
6986 M-down Move entry/item down
6987 M-left Promote
6988 M-right Demote
6989 M-S-up Move entry/item up
6990 M-S-down Move entry/item down
6991 M-S-left Promote subtree
6992 M-S-right Demote subtree
6993 M-q Fill paragraph and items like in Org-mode
6994 C-c ^ Sort entries
6995 C-c - Cycle list bullet
6996 TAB Cycle item visibility
6997 M-RET Insert new heading/item
6998 S-M-RET Insert new TODO heading / Chekbox item
6999 C-c C-c Set tags / toggle checkbox"
7000 nil " OrgStruct" nil
7001 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7003 ;;;###autoload
7004 (defun turn-on-orgstruct ()
7005 "Unconditionally turn on `orgstruct-mode'."
7006 (orgstruct-mode 1))
7008 ;;;###autoload
7009 (defun turn-on-orgstruct++ ()
7010 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7011 In addition to setting orgstruct-mode, this also exports all indentation and
7012 autofilling variables from org-mode into the buffer. Note that turning
7013 off orgstruct-mode will *not* remove these additonal settings."
7014 (orgstruct-mode 1)
7015 (let (var val)
7016 (mapc
7017 (lambda (x)
7018 (when (string-match
7019 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7020 (symbol-name (car x)))
7021 (setq var (car x) val (nth 1 x))
7022 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7023 org-local-vars)))
7025 (defun orgstruct-error ()
7026 "Error when there is no default binding for a structure key."
7027 (interactive)
7028 (error "This key is has no function outside structure elements"))
7030 (defun orgstruct-setup ()
7031 "Setup orgstruct keymaps."
7032 (let ((nfunc 0)
7033 (bindings
7034 (list
7035 '([(meta up)] org-metaup)
7036 '([(meta down)] org-metadown)
7037 '([(meta left)] org-metaleft)
7038 '([(meta right)] org-metaright)
7039 '([(meta shift up)] org-shiftmetaup)
7040 '([(meta shift down)] org-shiftmetadown)
7041 '([(meta shift left)] org-shiftmetaleft)
7042 '([(meta shift right)] org-shiftmetaright)
7043 '([(shift up)] org-shiftup)
7044 '([(shift down)] org-shiftdown)
7045 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7046 '("\M-q" fill-paragraph)
7047 '("\C-c^" org-sort)
7048 '("\C-c-" org-cycle-list-bullet)))
7049 elt key fun cmd)
7050 (while (setq elt (pop bindings))
7051 (setq nfunc (1+ nfunc))
7052 (setq key (org-key (car elt))
7053 fun (nth 1 elt)
7054 cmd (orgstruct-make-binding fun nfunc key))
7055 (org-defkey orgstruct-mode-map key cmd))
7057 ;; Special treatment needed for TAB and RET
7058 (org-defkey orgstruct-mode-map [(tab)]
7059 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7060 (org-defkey orgstruct-mode-map "\C-i"
7061 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7063 (org-defkey orgstruct-mode-map "\M-\C-m"
7064 (orgstruct-make-binding 'org-insert-heading 105
7065 "\M-\C-m" [(meta return)]))
7066 (org-defkey orgstruct-mode-map [(meta return)]
7067 (orgstruct-make-binding 'org-insert-heading 106
7068 [(meta return)] "\M-\C-m"))
7070 (org-defkey orgstruct-mode-map [(shift meta return)]
7071 (orgstruct-make-binding 'org-insert-todo-heading 107
7072 [(meta return)] "\M-\C-m"))
7074 (unless org-local-vars
7075 (setq org-local-vars (org-get-local-variables)))
7079 (defun orgstruct-make-binding (fun n &rest keys)
7080 "Create a function for binding in the structure minor mode.
7081 FUN is the command to call inside a table. N is used to create a unique
7082 command name. KEYS are keys that should be checked in for a command
7083 to execute outside of tables."
7084 (eval
7085 (list 'defun
7086 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7087 '(arg)
7088 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7089 "Outside of structure, run the binding of `"
7090 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7091 "'.")
7092 '(interactive "p")
7093 (list 'if
7094 '(org-context-p 'headline 'item)
7095 (list 'org-run-like-in-org-mode (list 'quote fun))
7096 (list 'let '(orgstruct-mode)
7097 (list 'call-interactively
7098 (append '(or)
7099 (mapcar (lambda (k)
7100 (list 'key-binding k))
7101 keys)
7102 '('orgstruct-error))))))))
7104 (defun org-context-p (&rest contexts)
7105 "Check if local context is and of CONTEXTS.
7106 Possible values in the list of contexts are `table', `headline', and `item'."
7107 (let ((pos (point)))
7108 (goto-char (point-at-bol))
7109 (prog1 (or (and (memq 'table contexts)
7110 (looking-at "[ \t]*|"))
7111 (and (memq 'headline contexts)
7112 (looking-at "\\*+"))
7113 (and (memq 'item contexts)
7114 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
7115 (goto-char pos))))
7117 (defun org-get-local-variables ()
7118 "Return a list of all local variables in an org-mode buffer."
7119 (let (varlist)
7120 (with-current-buffer (get-buffer-create "*Org tmp*")
7121 (erase-buffer)
7122 (org-mode)
7123 (setq varlist (buffer-local-variables)))
7124 (kill-buffer "*Org tmp*")
7125 (delq nil
7126 (mapcar
7127 (lambda (x)
7128 (setq x
7129 (if (symbolp x)
7130 (list x)
7131 (list (car x) (list 'quote (cdr x)))))
7132 (if (string-match
7133 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7134 (symbol-name (car x)))
7135 x nil))
7136 varlist))))
7138 ;;;###autoload
7139 (defun org-run-like-in-org-mode (cmd)
7140 (unless org-local-vars
7141 (setq org-local-vars (org-get-local-variables)))
7142 (eval (list 'let org-local-vars
7143 (list 'call-interactively (list 'quote cmd)))))
7145 ;;;; Archiving
7147 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
7149 (defun org-archive-subtree (&optional find-done)
7150 "Move the current subtree to the archive.
7151 The archive can be a certain top-level heading in the current file, or in
7152 a different file. The tree will be moved to that location, the subtree
7153 heading be marked DONE, and the current time will be added.
7155 When called with prefix argument FIND-DONE, find whole trees without any
7156 open TODO items and archive them (after getting confirmation from the user).
7157 If the cursor is not at a headline when this comand is called, try all level
7158 1 trees. If the cursor is on a headline, only try the direct children of
7159 this heading."
7160 (interactive "P")
7161 (if find-done
7162 (org-archive-all-done)
7163 ;; Save all relevant TODO keyword-relatex variables
7165 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
7166 (tr-org-todo-keywords-1 org-todo-keywords-1)
7167 (tr-org-todo-kwd-alist org-todo-kwd-alist)
7168 (tr-org-done-keywords org-done-keywords)
7169 (tr-org-todo-regexp org-todo-regexp)
7170 (tr-org-todo-line-regexp org-todo-line-regexp)
7171 (tr-org-odd-levels-only org-odd-levels-only)
7172 (this-buffer (current-buffer))
7173 (org-archive-location org-archive-location)
7174 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
7175 ;; start of variables that will be used for savind context
7176 (file (abbreviate-file-name (buffer-file-name)))
7177 (time (format-time-string
7178 (substring (cdr org-time-stamp-formats) 1 -1)
7179 (current-time)))
7180 afile heading buffer level newfile-p
7181 category todo priority
7182 ;; start of variables that will be used for savind context
7183 ltags itags prop)
7185 ;; Try to find a local archive location
7186 (save-excursion
7187 (save-restriction
7188 (widen)
7189 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
7190 (if (and prop (string-match "\\S-" prop))
7191 (setq org-archive-location prop)
7192 (if (or (re-search-backward re nil t)
7193 (re-search-forward re nil t))
7194 (setq org-archive-location (match-string 1))))))
7196 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
7197 (progn
7198 (setq afile (format (match-string 1 org-archive-location)
7199 (file-name-nondirectory buffer-file-name))
7200 heading (match-string 2 org-archive-location)))
7201 (error "Invalid `org-archive-location'"))
7202 (if (> (length afile) 0)
7203 (setq newfile-p (not (file-exists-p afile))
7204 buffer (find-file-noselect afile))
7205 (setq buffer (current-buffer)))
7206 (unless buffer
7207 (error "Cannot access file \"%s\"" afile))
7208 (if (and (> (length heading) 0)
7209 (string-match "^\\*+" heading))
7210 (setq level (match-end 0))
7211 (setq heading nil level 0))
7212 (save-excursion
7213 (org-back-to-heading t)
7214 ;; Get context information that will be lost by moving the tree
7215 (org-refresh-category-properties)
7216 (setq category (org-get-category)
7217 todo (and (looking-at org-todo-line-regexp)
7218 (match-string 2))
7219 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
7220 ltags (org-get-tags)
7221 itags (org-delete-all ltags (org-get-tags-at)))
7222 (setq ltags (mapconcat 'identity ltags " ")
7223 itags (mapconcat 'identity itags " "))
7224 ;; We first only copy, in case something goes wrong
7225 ;; we need to protect this-command, to avoid kill-region sets it,
7226 ;; which would lead to duplication of subtrees
7227 (let (this-command) (org-copy-subtree))
7228 (set-buffer buffer)
7229 ;; Enforce org-mode for the archive buffer
7230 (if (not (org-mode-p))
7231 ;; Force the mode for future visits.
7232 (let ((org-insert-mode-line-in-empty-file t)
7233 (org-inhibit-startup t))
7234 (call-interactively 'org-mode)))
7235 (when newfile-p
7236 (goto-char (point-max))
7237 (insert (format "\nArchived entries from file %s\n\n"
7238 (buffer-file-name this-buffer))))
7239 ;; Force the TODO keywords of the original buffer
7240 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
7241 (org-todo-keywords-1 tr-org-todo-keywords-1)
7242 (org-todo-kwd-alist tr-org-todo-kwd-alist)
7243 (org-done-keywords tr-org-done-keywords)
7244 (org-todo-regexp tr-org-todo-regexp)
7245 (org-todo-line-regexp tr-org-todo-line-regexp)
7246 (org-odd-levels-only
7247 (if (local-variable-p 'org-odd-levels-only (current-buffer))
7248 org-odd-levels-only
7249 tr-org-odd-levels-only)))
7250 (goto-char (point-min))
7251 (if heading
7252 (progn
7253 (if (re-search-forward
7254 (concat "^" (regexp-quote heading)
7255 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
7256 nil t)
7257 (goto-char (match-end 0))
7258 ;; Heading not found, just insert it at the end
7259 (goto-char (point-max))
7260 (or (bolp) (insert "\n"))
7261 (insert "\n" heading "\n")
7262 (end-of-line 0))
7263 ;; Make the subtree visible
7264 (show-subtree)
7265 (org-end-of-subtree t)
7266 (skip-chars-backward " \t\r\n")
7267 (and (looking-at "[ \t\r\n]*")
7268 (replace-match "\n\n")))
7269 ;; No specific heading, just go to end of file.
7270 (goto-char (point-max)) (insert "\n"))
7271 ;; Paste
7272 (org-paste-subtree (org-get-legal-level level 1))
7274 ;; Mark the entry as done
7275 (when (and org-archive-mark-done
7276 (looking-at org-todo-line-regexp)
7277 (or (not (match-end 2))
7278 (not (member (match-string 2) org-done-keywords))))
7279 (let (org-log-done)
7280 (org-todo
7281 (car (or (member org-archive-mark-done org-done-keywords)
7282 org-done-keywords)))))
7284 ;; Add the context info
7285 (when org-archive-save-context-info
7286 (let ((l org-archive-save-context-info) e n v)
7287 (while (setq e (pop l))
7288 (when (and (setq v (symbol-value e))
7289 (stringp v) (string-match "\\S-" v))
7290 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
7291 (org-entry-put (point) n v)))))
7293 ;; Save the buffer, if it is not the same buffer.
7294 (if (not (eq this-buffer buffer)) (save-buffer))))
7295 ;; Here we are back in the original buffer. Everything seems to have
7296 ;; worked. So now cut the tree and finish up.
7297 (let (this-command) (org-cut-subtree))
7298 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
7299 (message "Subtree archived %s"
7300 (if (eq this-buffer buffer)
7301 (concat "under heading: " heading)
7302 (concat "in file: " (abbreviate-file-name afile)))))))
7304 (defun org-refresh-category-properties ()
7305 "Refresh category text properties in teh buffer."
7306 (let ((def-cat (cond
7307 ((null org-category)
7308 (if buffer-file-name
7309 (file-name-sans-extension
7310 (file-name-nondirectory buffer-file-name))
7311 "???"))
7312 ((symbolp org-category) (symbol-name org-category))
7313 (t org-category)))
7314 beg end cat pos optionp)
7315 (org-unmodified
7316 (save-excursion
7317 (save-restriction
7318 (widen)
7319 (goto-char (point-min))
7320 (put-text-property (point) (point-max) 'org-category def-cat)
7321 (while (re-search-forward
7322 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7323 (setq pos (match-end 0)
7324 optionp (equal (char-after (match-beginning 0)) ?#)
7325 cat (org-trim (match-string 2)))
7326 (if optionp
7327 (setq beg (point-at-bol) end (point-max))
7328 (org-back-to-heading t)
7329 (setq beg (point) end (org-end-of-subtree t t)))
7330 (put-text-property beg end 'org-category cat)
7331 (goto-char pos)))))))
7333 (defun org-archive-all-done (&optional tag)
7334 "Archive sublevels of the current tree without open TODO items.
7335 If the cursor is not on a headline, try all level 1 trees. If
7336 it is on a headline, try all direct children.
7337 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
7338 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
7339 (rea (concat ".*:" org-archive-tag ":"))
7340 (begm (make-marker))
7341 (endm (make-marker))
7342 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
7343 "Move subtree to archive (no open TODO items)? "))
7344 beg end (cntarch 0))
7345 (if (org-on-heading-p)
7346 (progn
7347 (setq re1 (concat "^" (regexp-quote
7348 (make-string
7349 (1+ (- (match-end 0) (match-beginning 0)))
7350 ?*))
7351 " "))
7352 (move-marker begm (point))
7353 (move-marker endm (org-end-of-subtree t)))
7354 (setq re1 "^* ")
7355 (move-marker begm (point-min))
7356 (move-marker endm (point-max)))
7357 (save-excursion
7358 (goto-char begm)
7359 (while (re-search-forward re1 endm t)
7360 (setq beg (match-beginning 0)
7361 end (save-excursion (org-end-of-subtree t) (point)))
7362 (goto-char beg)
7363 (if (re-search-forward re end t)
7364 (goto-char end)
7365 (goto-char beg)
7366 (if (and (or (not tag) (not (looking-at rea)))
7367 (y-or-n-p question))
7368 (progn
7369 (if tag
7370 (org-toggle-tag org-archive-tag 'on)
7371 (org-archive-subtree))
7372 (setq cntarch (1+ cntarch)))
7373 (goto-char end)))))
7374 (message "%d trees archived" cntarch)))
7376 (defun org-cycle-hide-drawers (state)
7377 "Re-hide all drawers after a visibility state change."
7378 (when (and (org-mode-p)
7379 (not (memq state '(overview folded))))
7380 (save-excursion
7381 (let* ((globalp (memq state '(contents all)))
7382 (beg (if globalp (point-min) (point)))
7383 (end (if globalp (point-max) (org-end-of-subtree t))))
7384 (goto-char beg)
7385 (while (re-search-forward org-drawer-regexp end t)
7386 (org-flag-drawer t))))))
7388 (defun org-flag-drawer (flag)
7389 (save-excursion
7390 (beginning-of-line 1)
7391 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7392 (let ((b (match-end 0)))
7393 (if (re-search-forward
7394 "^[ \t]*:END:"
7395 (save-excursion (outline-next-heading) (point)) t)
7396 (outline-flag-region b (point-at-eol) flag)
7397 (error ":END: line missing"))))))
7399 (defun org-cycle-hide-archived-subtrees (state)
7400 "Re-hide all archived subtrees after a visibility state change."
7401 (when (and (not org-cycle-open-archived-trees)
7402 (not (memq state '(overview folded))))
7403 (save-excursion
7404 (let* ((globalp (memq state '(contents all)))
7405 (beg (if globalp (point-min) (point)))
7406 (end (if globalp (point-max) (org-end-of-subtree t))))
7407 (org-hide-archived-subtrees beg end)
7408 (goto-char beg)
7409 (if (looking-at (concat ".*:" org-archive-tag ":"))
7410 (message (substitute-command-keys
7411 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
7413 (defun org-force-cycle-archived ()
7414 "Cycle subtree even if it is archived."
7415 (interactive)
7416 (setq this-command 'org-cycle)
7417 (let ((org-cycle-open-archived-trees t))
7418 (call-interactively 'org-cycle)))
7420 (defun org-hide-archived-subtrees (beg end)
7421 "Re-hide all archived subtrees after a visibility state change."
7422 (save-excursion
7423 (let* ((re (concat ":" org-archive-tag ":")))
7424 (goto-char beg)
7425 (while (re-search-forward re end t)
7426 (and (org-on-heading-p) (hide-subtree))
7427 (org-end-of-subtree t)))))
7429 (defun org-toggle-tag (tag &optional onoff)
7430 "Toggle the tag TAG for the current line.
7431 If ONOFF is `on' or `off', don't toggle but set to this state."
7432 (unless (org-on-heading-p t) (error "Not on headling"))
7433 (let (res current)
7434 (save-excursion
7435 (beginning-of-line)
7436 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
7437 (point-at-eol) t)
7438 (progn
7439 (setq current (match-string 1))
7440 (replace-match ""))
7441 (setq current ""))
7442 (setq current (nreverse (org-split-string current ":")))
7443 (cond
7444 ((eq onoff 'on)
7445 (setq res t)
7446 (or (member tag current) (push tag current)))
7447 ((eq onoff 'off)
7448 (or (not (member tag current)) (setq current (delete tag current))))
7449 (t (if (member tag current)
7450 (setq current (delete tag current))
7451 (setq res t)
7452 (push tag current))))
7453 (end-of-line 1)
7454 (if current
7455 (progn
7456 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
7457 (org-set-tags nil t))
7458 (delete-horizontal-space))
7459 (run-hooks 'org-after-tags-change-hook))
7460 res))
7462 (defun org-toggle-archive-tag (&optional arg)
7463 "Toggle the archive tag for the current headline.
7464 With prefix ARG, check all children of current headline and offer tagging
7465 the children that do not contain any open TODO items."
7466 (interactive "P")
7467 (if arg
7468 (org-archive-all-done 'tag)
7469 (let (set)
7470 (save-excursion
7471 (org-back-to-heading t)
7472 (setq set (org-toggle-tag org-archive-tag))
7473 (when set (hide-subtree)))
7474 (and set (beginning-of-line 1))
7475 (message "Subtree %s" (if set "archived" "unarchived")))))
7478 ;;;; Tables
7480 ;;; The table editor
7482 ;; Watch out: Here we are talking about two different kind of tables.
7483 ;; Most of the code is for the tables created with the Org-mode table editor.
7484 ;; Sometimes, we talk about tables created and edited with the table.el
7485 ;; Emacs package. We call the former org-type tables, and the latter
7486 ;; table.el-type tables.
7488 (defun org-before-change-function (beg end)
7489 "Every change indicates that a table might need an update."
7490 (setq org-table-may-need-update t))
7492 (defconst org-table-line-regexp "^[ \t]*|"
7493 "Detects an org-type table line.")
7494 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
7495 "Detects an org-type table line.")
7496 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
7497 "Detects a table line marked for automatic recalculation.")
7498 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
7499 "Detects a table line marked for automatic recalculation.")
7500 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
7501 "Detects a table line marked for automatic recalculation.")
7502 (defconst org-table-hline-regexp "^[ \t]*|-"
7503 "Detects an org-type table hline.")
7504 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
7505 "Detects a table-type table hline.")
7506 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
7507 "Detects an org-type or table-type table.")
7508 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
7509 "Searching from within a table (any type) this finds the first line
7510 outside the table.")
7511 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
7512 "Searching from within a table (any type) this finds the first line
7513 outside the table.")
7515 (defvar org-table-last-highlighted-reference nil)
7516 (defvar org-table-formula-history nil)
7518 (defvar org-table-column-names nil
7519 "Alist with column names, derived from the `!' line.")
7520 (defvar org-table-column-name-regexp nil
7521 "Regular expression matching the current column names.")
7522 (defvar org-table-local-parameters nil
7523 "Alist with parameter names, derived from the `$' line.")
7524 (defvar org-table-named-field-locations nil
7525 "Alist with locations of named fields.")
7527 (defvar org-table-current-line-types nil
7528 "Table row types, non-nil only for the duration of a comand.")
7529 (defvar org-table-current-begin-line nil
7530 "Table begin line, non-nil only for the duration of a comand.")
7531 (defvar org-table-current-begin-pos nil
7532 "Table begin position, non-nil only for the duration of a comand.")
7533 (defvar org-table-dlines nil
7534 "Vector of data line line numbers in the current table.")
7535 (defvar org-table-hlines nil
7536 "Vector of hline line numbers in the current table.")
7538 (defconst org-table-range-regexp
7539 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
7540 ;; 1 2 3 4 5
7541 "Regular expression for matching ranges in formulas.")
7543 (defconst org-table-range-regexp2
7544 (concat
7545 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
7546 "\\.\\."
7547 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
7548 "Match a range for reference display.")
7550 (defconst org-table-translate-regexp
7551 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
7552 "Match a reference that needs translation, for reference display.")
7554 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
7556 (defun org-table-create-with-table.el ()
7557 "Use the table.el package to insert a new table.
7558 If there is already a table at point, convert between Org-mode tables
7559 and table.el tables."
7560 (interactive)
7561 (require 'table)
7562 (cond
7563 ((org-at-table.el-p)
7564 (if (y-or-n-p "Convert table to Org-mode table? ")
7565 (org-table-convert)))
7566 ((org-at-table-p)
7567 (if (y-or-n-p "Convert table to table.el table? ")
7568 (org-table-convert)))
7569 (t (call-interactively 'table-insert))))
7571 (defun org-table-create-or-convert-from-region (arg)
7572 "Convert region to table, or create an empty table.
7573 If there is an active region, convert it to a table, using the function
7574 `org-table-convert-region'. See the documentation of that function
7575 to learn how the prefix argument is interpreted to determine the field
7576 separator.
7577 If there is no such region, create an empty table with `org-table-create'."
7578 (interactive "P")
7579 (if (org-region-active-p)
7580 (org-table-convert-region (region-beginning) (region-end) arg)
7581 (org-table-create arg)))
7583 (defun org-table-create (&optional size)
7584 "Query for a size and insert a table skeleton.
7585 SIZE is a string Columns x Rows like for example \"3x2\"."
7586 (interactive "P")
7587 (unless size
7588 (setq size (read-string
7589 (concat "Table size Columns x Rows [e.g. "
7590 org-table-default-size "]: ")
7591 "" nil org-table-default-size)))
7593 (let* ((pos (point))
7594 (indent (make-string (current-column) ?\ ))
7595 (split (org-split-string size " *x *"))
7596 (rows (string-to-number (nth 1 split)))
7597 (columns (string-to-number (car split)))
7598 (line (concat (apply 'concat indent "|" (make-list columns " |"))
7599 "\n")))
7600 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
7601 (point-at-bol) (point)))
7602 (beginning-of-line 1)
7603 (newline))
7604 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
7605 (dotimes (i rows) (insert line))
7606 (goto-char pos)
7607 (if (> rows 1)
7608 ;; Insert a hline after the first row.
7609 (progn
7610 (end-of-line 1)
7611 (insert "\n|-")
7612 (goto-char pos)))
7613 (org-table-align)))
7615 (defun org-table-convert-region (beg0 end0 &optional separator)
7616 "Convert region to a table.
7617 The region goes from BEG0 to END0, but these borders will be moved
7618 slightly, to make sure a beginning of line in the first line is included.
7620 SEPARATOR specifies the field separator in the lines. It can have the
7621 following values:
7623 '(4) Use the comma as a field separator
7624 '(16) Use a TAB as field separator
7625 integer When a number, use that many spaces as field separator
7626 nil When nil, the command tries to be smart and figure out the
7627 separator in the following way:
7628 - when each line contains a TAB, assume TAB-separated material
7629 - when each line contains a comme, assume CSV material
7630 - else, assume one or more SPACE charcters as separator."
7631 (interactive "rP")
7632 (let* ((beg (min beg0 end0))
7633 (end (max beg0 end0))
7635 (goto-char beg)
7636 (beginning-of-line 1)
7637 (setq beg (move-marker (make-marker) (point)))
7638 (goto-char end)
7639 (if (bolp) (backward-char 1) (end-of-line 1))
7640 (setq end (move-marker (make-marker) (point)))
7641 ;; Get the right field separator
7642 (unless separator
7643 (goto-char beg)
7644 (setq separator
7645 (cond
7646 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
7647 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
7648 (t 1))))
7649 (setq re (cond
7650 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
7651 ((equal separator '(16)) "^\\|\t")
7652 ((integerp separator)
7653 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
7654 (t (error "This should not happen"))))
7655 (goto-char beg)
7656 (while (re-search-forward re end t)
7657 (replace-match "| " t t))
7658 (goto-char beg)
7659 (insert " ")
7660 (org-table-align)))
7662 (defun org-table-import (file arg)
7663 "Import FILE as a table.
7664 The file is assumed to be tab-separated. Such files can be produced by most
7665 spreadsheet and database applications. If no tabs (at least one per line)
7666 are found, lines will be split on whitespace into fields."
7667 (interactive "f\nP")
7668 (or (bolp) (newline))
7669 (let ((beg (point))
7670 (pm (point-max)))
7671 (insert-file-contents file)
7672 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
7674 (defun org-table-export ()
7675 "Export table as a tab-separated file.
7676 Such a file can be imported into a spreadsheet program like Excel."
7677 (interactive)
7678 (let* ((beg (org-table-begin))
7679 (end (org-table-end))
7680 (table (buffer-substring beg end))
7681 (file (read-file-name "Export table to: "))
7682 buf)
7683 (unless (or (not (file-exists-p file))
7684 (y-or-n-p (format "Overwrite file %s? " file)))
7685 (error "Abort"))
7686 (with-current-buffer (find-file-noselect file)
7687 (setq buf (current-buffer))
7688 (erase-buffer)
7689 (fundamental-mode)
7690 (insert table)
7691 (goto-char (point-min))
7692 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
7693 (replace-match "" t t)
7694 (end-of-line 1))
7695 (goto-char (point-min))
7696 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
7697 (replace-match "" t t)
7698 (goto-char (min (1+ (point)) (point-max))))
7699 (goto-char (point-min))
7700 (while (re-search-forward "^-[-+]*$" nil t)
7701 (replace-match "")
7702 (if (looking-at "\n")
7703 (delete-char 1)))
7704 (goto-char (point-min))
7705 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
7706 (replace-match "\t" t t))
7707 (save-buffer))
7708 (kill-buffer buf)))
7710 (defvar org-table-aligned-begin-marker (make-marker)
7711 "Marker at the beginning of the table last aligned.
7712 Used to check if cursor still is in that table, to minimize realignment.")
7713 (defvar org-table-aligned-end-marker (make-marker)
7714 "Marker at the end of the table last aligned.
7715 Used to check if cursor still is in that table, to minimize realignment.")
7716 (defvar org-table-last-alignment nil
7717 "List of flags for flushright alignment, from the last re-alignment.
7718 This is being used to correctly align a single field after TAB or RET.")
7719 (defvar org-table-last-column-widths nil
7720 "List of max width of fields in each column.
7721 This is being used to correctly align a single field after TAB or RET.")
7722 (defvar org-table-overlay-coordinates nil
7723 "Overlay coordinates after each align of a table.")
7724 (make-variable-buffer-local 'org-table-overlay-coordinates)
7726 (defvar org-last-recalc-line nil)
7727 (defconst org-narrow-column-arrow "=>"
7728 "Used as display property in narrowed table columns.")
7730 (defun org-table-align ()
7731 "Align the table at point by aligning all vertical bars."
7732 (interactive)
7733 (let* (
7734 ;; Limits of table
7735 (beg (org-table-begin))
7736 (end (org-table-end))
7737 ;; Current cursor position
7738 (linepos (org-current-line))
7739 (colpos (org-table-current-column))
7740 (winstart (window-start))
7741 (winstartline (org-current-line (min winstart (1- (point-max)))))
7742 lines (new "") lengths l typenums ty fields maxfields i
7743 column
7744 (indent "") cnt frac
7745 rfmt hfmt
7746 (spaces '(1 . 1))
7747 (sp1 (car spaces))
7748 (sp2 (cdr spaces))
7749 (rfmt1 (concat
7750 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
7751 (hfmt1 (concat
7752 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
7753 emptystrings links dates narrow fmax f1 len c e)
7754 (untabify beg end)
7755 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
7756 ;; Check if we have links or dates
7757 (goto-char beg)
7758 (setq links (re-search-forward org-bracket-link-regexp end t))
7759 (goto-char beg)
7760 (setq dates (and org-display-custom-times
7761 (re-search-forward org-ts-regexp-both end t)))
7762 ;; Make sure the link properties are right
7763 (when links (goto-char beg) (while (org-activate-bracket-links end)))
7764 ;; Make sure the date properties are right
7765 (when dates (goto-char beg) (while (org-activate-dates end)))
7767 ;; Check if we are narrowing any columns
7768 (goto-char beg)
7769 (setq narrow (and org-format-transports-properties-p
7770 (re-search-forward "<[0-9]+>" end t)))
7771 ;; Get the rows
7772 (setq lines (org-split-string
7773 (buffer-substring beg end) "\n"))
7774 ;; Store the indentation of the first line
7775 (if (string-match "^ *" (car lines))
7776 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
7777 ;; Mark the hlines by setting the corresponding element to nil
7778 ;; At the same time, we remove trailing space.
7779 (setq lines (mapcar (lambda (l)
7780 (if (string-match "^ *|-" l)
7782 (if (string-match "[ \t]+$" l)
7783 (substring l 0 (match-beginning 0))
7784 l)))
7785 lines))
7786 ;; Get the data fields by splitting the lines.
7787 (setq fields (mapcar
7788 (lambda (l)
7789 (org-split-string l " *| *"))
7790 (delq nil (copy-sequence lines))))
7791 ;; How many fields in the longest line?
7792 (condition-case nil
7793 (setq maxfields (apply 'max (mapcar 'length fields)))
7794 (error
7795 (kill-region beg end)
7796 (org-table-create org-table-default-size)
7797 (error "Empty table - created default table")))
7798 ;; A list of empty strings to fill any short rows on output
7799 (setq emptystrings (make-list maxfields ""))
7800 ;; Check for special formatting.
7801 (setq i -1)
7802 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
7803 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
7804 ;; Check if there is an explicit width specified
7805 (when narrow
7806 (setq c column fmax nil)
7807 (while c
7808 (setq e (pop c))
7809 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
7810 (setq fmax (string-to-number (match-string 1 e)) c nil)))
7811 ;; Find fields that are wider than fmax, and shorten them
7812 (when fmax
7813 (loop for xx in column do
7814 (when (and (stringp xx)
7815 (> (org-string-width xx) fmax))
7816 (org-add-props xx nil
7817 'help-echo
7818 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
7819 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
7820 (unless (> f1 1)
7821 (error "Cannot narrow field starting with wide link \"%s\""
7822 (match-string 0 xx)))
7823 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
7824 (add-text-properties (- f1 2) f1
7825 (list 'display org-narrow-column-arrow)
7826 xx)))))
7827 ;; Get the maximum width for each column
7828 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
7829 ;; Get the fraction of numbers, to decide about alignment of the column
7830 (setq cnt 0 frac 0.0)
7831 (loop for x in column do
7832 (if (equal x "")
7834 (setq frac ( / (+ (* frac cnt)
7835 (if (string-match org-table-number-regexp x) 1 0))
7836 (setq cnt (1+ cnt))))))
7837 (push (>= frac org-table-number-fraction) typenums))
7838 (setq lengths (nreverse lengths) typenums (nreverse typenums))
7840 ;; Store the alignment of this table, for later editing of single fields
7841 (setq org-table-last-alignment typenums
7842 org-table-last-column-widths lengths)
7844 ;; With invisible characters, `format' does not get the field width right
7845 ;; So we need to make these fields wide by hand.
7846 (when links
7847 (loop for i from 0 upto (1- maxfields) do
7848 (setq len (nth i lengths))
7849 (loop for j from 0 upto (1- (length fields)) do
7850 (setq c (nthcdr i (car (nthcdr j fields))))
7851 (if (and (stringp (car c))
7852 (string-match org-bracket-link-regexp (car c))
7853 (< (org-string-width (car c)) len))
7854 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
7856 ;; Compute the formats needed for output of the table
7857 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
7858 (while (setq l (pop lengths))
7859 (setq ty (if (pop typenums) "" "-")) ; number types flushright
7860 (setq rfmt (concat rfmt (format rfmt1 ty l))
7861 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
7862 (setq rfmt (concat rfmt "\n")
7863 hfmt (concat (substring hfmt 0 -1) "|\n"))
7865 (setq new (mapconcat
7866 (lambda (l)
7867 (if l (apply 'format rfmt
7868 (append (pop fields) emptystrings))
7869 hfmt))
7870 lines ""))
7871 ;; Replace the old one
7872 (delete-region beg end)
7873 (move-marker end nil)
7874 (move-marker org-table-aligned-begin-marker (point))
7875 (insert new)
7876 (move-marker org-table-aligned-end-marker (point))
7877 (when (and orgtbl-mode (not (org-mode-p)))
7878 (goto-char org-table-aligned-begin-marker)
7879 (while (org-hide-wide-columns org-table-aligned-end-marker)))
7880 ;; Try to move to the old location
7881 (goto-line winstartline)
7882 (setq winstart (point-at-bol))
7883 (goto-line linepos)
7884 (set-window-start (selected-window) winstart 'noforce)
7885 (org-table-goto-column colpos)
7886 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
7887 (setq org-table-may-need-update nil)
7890 (defun org-string-width (s)
7891 "Compute width of string, ignoring invisible characters.
7892 This ignores character with invisibility property `org-link', and also
7893 characters with property `org-cwidth', because these will become invisible
7894 upon the next fontification round."
7895 (let (b l)
7896 (when (or (eq t buffer-invisibility-spec)
7897 (assq 'org-link buffer-invisibility-spec))
7898 (while (setq b (text-property-any 0 (length s)
7899 'invisible 'org-link s))
7900 (setq s (concat (substring s 0 b)
7901 (substring s (or (next-single-property-change
7902 b 'invisible s) (length s)))))))
7903 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
7904 (setq s (concat (substring s 0 b)
7905 (substring s (or (next-single-property-change
7906 b 'org-cwidth s) (length s))))))
7907 (setq l (string-width s) b -1)
7908 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
7909 (setq l (- l (get-text-property b 'org-dwidth-n s))))
7912 (defun org-table-begin (&optional table-type)
7913 "Find the beginning of the table and return its position.
7914 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
7915 (save-excursion
7916 (if (not (re-search-backward
7917 (if table-type org-table-any-border-regexp
7918 org-table-border-regexp)
7919 nil t))
7920 (progn (goto-char (point-min)) (point))
7921 (goto-char (match-beginning 0))
7922 (beginning-of-line 2)
7923 (point))))
7925 (defun org-table-end (&optional table-type)
7926 "Find the end of the table and return its position.
7927 With argument TABLE-TYPE, go to the end of a table.el-type table."
7928 (save-excursion
7929 (if (not (re-search-forward
7930 (if table-type org-table-any-border-regexp
7931 org-table-border-regexp)
7932 nil t))
7933 (goto-char (point-max))
7934 (goto-char (match-beginning 0)))
7935 (point-marker)))
7937 (defun org-table-justify-field-maybe (&optional new)
7938 "Justify the current field, text to left, number to right.
7939 Optional argument NEW may specify text to replace the current field content."
7940 (cond
7941 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
7942 ((org-at-table-hline-p))
7943 ((and (not new)
7944 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
7945 (current-buffer)))
7946 (< (point) org-table-aligned-begin-marker)
7947 (>= (point) org-table-aligned-end-marker)))
7948 ;; This is not the same table, force a full re-align
7949 (setq org-table-may-need-update t))
7950 (t ;; realign the current field, based on previous full realign
7951 (let* ((pos (point)) s
7952 (col (org-table-current-column))
7953 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
7954 l f n o e)
7955 (when (> col 0)
7956 (skip-chars-backward "^|\n")
7957 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
7958 (progn
7959 (setq s (match-string 1)
7960 o (match-string 0)
7961 l (max 1 (- (match-end 0) (match-beginning 0) 3))
7962 e (not (= (match-beginning 2) (match-end 2))))
7963 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
7964 l (if e "|" (setq org-table-may-need-update t) ""))
7965 n (format f s))
7966 (if new
7967 (if (<= (length new) l) ;; FIXME: length -> str-width?
7968 (setq n (format f new))
7969 (setq n (concat new "|") org-table-may-need-update t)))
7970 (or (equal n o)
7971 (let (org-table-may-need-update)
7972 (replace-match n t t))))
7973 (setq org-table-may-need-update t))
7974 (goto-char pos))))))
7976 (defun org-table-next-field ()
7977 "Go to the next field in the current table, creating new lines as needed.
7978 Before doing so, re-align the table if necessary."
7979 (interactive)
7980 (org-table-maybe-eval-formula)
7981 (org-table-maybe-recalculate-line)
7982 (if (and org-table-automatic-realign
7983 org-table-may-need-update)
7984 (org-table-align))
7985 (let ((end (org-table-end)))
7986 (if (org-at-table-hline-p)
7987 (end-of-line 1))
7988 (condition-case nil
7989 (progn
7990 (re-search-forward "|" end)
7991 (if (looking-at "[ \t]*$")
7992 (re-search-forward "|" end))
7993 (if (and (looking-at "-")
7994 org-table-tab-jumps-over-hlines
7995 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
7996 (goto-char (match-beginning 1)))
7997 (if (looking-at "-")
7998 (progn
7999 (beginning-of-line 0)
8000 (org-table-insert-row 'below))
8001 (if (looking-at " ") (forward-char 1))))
8002 (error
8003 (org-table-insert-row 'below)))))
8005 (defun org-table-previous-field ()
8006 "Go to the previous field in the table.
8007 Before doing so, re-align the table if necessary."
8008 (interactive)
8009 (org-table-justify-field-maybe)
8010 (org-table-maybe-recalculate-line)
8011 (if (and org-table-automatic-realign
8012 org-table-may-need-update)
8013 (org-table-align))
8014 (if (org-at-table-hline-p)
8015 (end-of-line 1))
8016 (re-search-backward "|" (org-table-begin))
8017 (re-search-backward "|" (org-table-begin))
8018 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8019 (re-search-backward "|" (org-table-begin)))
8020 (if (looking-at "| ?")
8021 (goto-char (match-end 0))))
8023 (defun org-table-next-row ()
8024 "Go to the next row (same column) in the current table.
8025 Before doing so, re-align the table if necessary."
8026 (interactive)
8027 (org-table-maybe-eval-formula)
8028 (org-table-maybe-recalculate-line)
8029 (if (or (looking-at "[ \t]*$")
8030 (save-excursion (skip-chars-backward " \t") (bolp)))
8031 (newline)
8032 (if (and org-table-automatic-realign
8033 org-table-may-need-update)
8034 (org-table-align))
8035 (let ((col (org-table-current-column)))
8036 (beginning-of-line 2)
8037 (if (or (not (org-at-table-p))
8038 (org-at-table-hline-p))
8039 (progn
8040 (beginning-of-line 0)
8041 (org-table-insert-row 'below)))
8042 (org-table-goto-column col)
8043 (skip-chars-backward "^|\n\r")
8044 (if (looking-at " ") (forward-char 1)))))
8046 (defun org-table-copy-down (n)
8047 "Copy a field down in the current column.
8048 If the field at the cursor is empty, copy into it the content of the nearest
8049 non-empty field above. With argument N, use the Nth non-empty field.
8050 If the current field is not empty, it is copied down to the next row, and
8051 the cursor is moved with it. Therefore, repeating this command causes the
8052 column to be filled row-by-row.
8053 If the variable `org-table-copy-increment' is non-nil and the field is an
8054 integer or a timestamp, it will be incremented while copying. In the case of
8055 a timestamp, if the cursor is on the year, change the year. If it is on the
8056 month or the day, change that. Point will stay on the current date field
8057 in order to easily repeat the interval."
8058 (interactive "p")
8059 (let* ((colpos (org-table-current-column))
8060 (col (current-column))
8061 (field (org-table-get-field))
8062 (non-empty (string-match "[^ \t]" field))
8063 (beg (org-table-begin))
8064 txt)
8065 (org-table-check-inside-data-field)
8066 (if non-empty
8067 (progn
8068 (setq txt (org-trim field))
8069 (org-table-next-row)
8070 (org-table-blank-field))
8071 (save-excursion
8072 (setq txt
8073 (catch 'exit
8074 (while (progn (beginning-of-line 1)
8075 (re-search-backward org-table-dataline-regexp
8076 beg t))
8077 (org-table-goto-column colpos t)
8078 (if (and (looking-at
8079 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8080 (= (setq n (1- n)) 0))
8081 (throw 'exit (match-string 1))))))))
8082 (if txt
8083 (progn
8084 (if (and org-table-copy-increment
8085 (string-match "^[0-9]+$" txt))
8086 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8087 (insert txt)
8088 (move-to-column col)
8089 (if (and org-table-copy-increment (org-at-timestamp-p t))
8090 (org-timestamp-up 1)
8091 (org-table-maybe-recalculate-line))
8092 (org-table-align)
8093 (move-to-column col))
8094 (error "No non-empty field found"))))
8096 (defun org-table-check-inside-data-field ()
8097 "Is point inside a table data field?
8098 I.e. not on a hline or before the first or after the last column?
8099 This actually throws an error, so it aborts the current command."
8100 (if (or (not (org-at-table-p))
8101 (= (org-table-current-column) 0)
8102 (org-at-table-hline-p)
8103 (looking-at "[ \t]*$"))
8104 (error "Not in table data field")))
8106 (defvar org-table-clip nil
8107 "Clipboard for table regions.")
8109 (defun org-table-blank-field ()
8110 "Blank the current table field or active region."
8111 (interactive)
8112 (org-table-check-inside-data-field)
8113 (if (and (interactive-p) (org-region-active-p))
8114 (let (org-table-clip)
8115 (org-table-cut-region (region-beginning) (region-end)))
8116 (skip-chars-backward "^|")
8117 (backward-char 1)
8118 (if (looking-at "|[^|\n]+")
8119 (let* ((pos (match-beginning 0))
8120 (match (match-string 0))
8121 (len (org-string-width match)))
8122 (replace-match (concat "|" (make-string (1- len) ?\ )))
8123 (goto-char (+ 2 pos))
8124 (substring match 1)))))
8126 (defun org-table-get-field (&optional n replace)
8127 "Return the value of the field in column N of current row.
8128 N defaults to current field.
8129 If REPLACE is a string, replace field with this value. The return value
8130 is always the old value."
8131 (and n (org-table-goto-column n))
8132 (skip-chars-backward "^|\n")
8133 (backward-char 1)
8134 (if (looking-at "|[^|\r\n]*")
8135 (let* ((pos (match-beginning 0))
8136 (val (buffer-substring (1+ pos) (match-end 0))))
8137 (if replace
8138 (replace-match (concat "|" replace) t t))
8139 (goto-char (min (point-at-eol) (+ 2 pos)))
8140 val)
8141 (forward-char 1) ""))
8143 (defun org-table-field-info (arg)
8144 "Show info about the current field, and highlight any reference at point."
8145 (interactive "P")
8146 (org-table-get-specials)
8147 (save-excursion
8148 (let* ((pos (point))
8149 (col (org-table-current-column))
8150 (cname (car (rassoc (int-to-string col) org-table-column-names)))
8151 (name (car (rassoc (list (org-current-line) col)
8152 org-table-named-field-locations)))
8153 (eql (org-table-get-stored-formulas))
8154 (dline (org-table-current-dline))
8155 (ref (format "@%d$%d" dline col))
8156 (ref1 (org-table-convert-refs-to-an ref))
8157 (fequation (or (assoc name eql) (assoc ref eql)))
8158 (cequation (assoc (int-to-string col) eql))
8159 (eqn (or fequation cequation)))
8160 (goto-char pos)
8161 (condition-case nil
8162 (org-table-show-reference 'local)
8163 (error nil))
8164 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
8165 dline col
8166 (if cname (concat " or $" cname) "")
8167 dline col ref1
8168 (if name (concat " or $" name) "")
8169 ;; FIXME: formula info not correct if special table line
8170 (if eqn
8171 (concat ", formula: "
8172 (org-table-formula-to-user
8173 (concat
8174 (if (string-match "^[$@]"(car eqn)) "" "$")
8175 (car eqn) "=" (cdr eqn))))
8176 "")))))
8178 (defun org-table-current-column ()
8179 "Find out which column we are in.
8180 When called interactively, column is also displayed in echo area."
8181 (interactive)
8182 (if (interactive-p) (org-table-check-inside-data-field))
8183 (save-excursion
8184 (let ((cnt 0) (pos (point)))
8185 (beginning-of-line 1)
8186 (while (search-forward "|" pos t)
8187 (setq cnt (1+ cnt)))
8188 (if (interactive-p) (message "This is table column %d" cnt))
8189 cnt)))
8191 (defun org-table-current-dline ()
8192 "Find out what table data line we are in.
8193 Only datalins count for this."
8194 (interactive)
8195 (if (interactive-p) (org-table-check-inside-data-field))
8196 (save-excursion
8197 (let ((cnt 0) (pos (point)))
8198 (goto-char (org-table-begin))
8199 (while (<= (point) pos)
8200 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
8201 (beginning-of-line 2))
8202 (if (interactive-p) (message "This is table line %d" cnt))
8203 cnt)))
8205 (defun org-table-goto-column (n &optional on-delim force)
8206 "Move the cursor to the Nth column in the current table line.
8207 With optional argument ON-DELIM, stop with point before the left delimiter
8208 of the field.
8209 If there are less than N fields, just go to after the last delimiter.
8210 However, when FORCE is non-nil, create new columns if necessary."
8211 (interactive "p")
8212 (let ((pos (point-at-eol)))
8213 (beginning-of-line 1)
8214 (when (> n 0)
8215 (while (and (> (setq n (1- n)) -1)
8216 (or (search-forward "|" pos t)
8217 (and force
8218 (progn (end-of-line 1)
8219 (skip-chars-backward "^|")
8220 (insert " | "))))))
8221 ; (backward-char 2) t)))))
8222 (when (and force (not (looking-at ".*|")))
8223 (save-excursion (end-of-line 1) (insert " | ")))
8224 (if on-delim
8225 (backward-char 1)
8226 (if (looking-at " ") (forward-char 1))))))
8228 (defun org-at-table-p (&optional table-type)
8229 "Return t if the cursor is inside an org-type table.
8230 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8231 (if org-enable-table-editor
8232 (save-excursion
8233 (beginning-of-line 1)
8234 (looking-at (if table-type org-table-any-line-regexp
8235 org-table-line-regexp)))
8236 nil))
8238 (defun org-at-table.el-p ()
8239 "Return t if and only if we are at a table.el table."
8240 (and (org-at-table-p 'any)
8241 (save-excursion
8242 (goto-char (org-table-begin 'any))
8243 (looking-at org-table1-hline-regexp))))
8245 (defun org-table-recognize-table.el ()
8246 "If there is a table.el table nearby, recognize it and move into it."
8247 (if org-table-tab-recognizes-table.el
8248 (if (org-at-table.el-p)
8249 (progn
8250 (beginning-of-line 1)
8251 (if (looking-at org-table-dataline-regexp)
8253 (if (looking-at org-table1-hline-regexp)
8254 (progn
8255 (beginning-of-line 2)
8256 (if (looking-at org-table-any-border-regexp)
8257 (beginning-of-line -1)))))
8258 (if (re-search-forward "|" (org-table-end t) t)
8259 (progn
8260 (require 'table)
8261 (if (table--at-cell-p (point))
8263 (message "recognizing table.el table...")
8264 (table-recognize-table)
8265 (message "recognizing table.el table...done")))
8266 (error "This should not happen..."))
8268 nil)
8269 nil))
8271 (defun org-at-table-hline-p ()
8272 "Return t if the cursor is inside a hline in a table."
8273 (if org-enable-table-editor
8274 (save-excursion
8275 (beginning-of-line 1)
8276 (looking-at org-table-hline-regexp))
8277 nil))
8279 (defun org-table-insert-column ()
8280 "Insert a new column into the table."
8281 (interactive)
8282 (if (not (org-at-table-p))
8283 (error "Not at a table"))
8284 (org-table-find-dataline)
8285 (let* ((col (max 1 (org-table-current-column)))
8286 (beg (org-table-begin))
8287 (end (org-table-end))
8288 ;; Current cursor position
8289 (linepos (org-current-line))
8290 (colpos col))
8291 (goto-char beg)
8292 (while (< (point) end)
8293 (if (org-at-table-hline-p)
8295 (org-table-goto-column col t)
8296 (insert "| "))
8297 (beginning-of-line 2))
8298 (move-marker end nil)
8299 (goto-line linepos)
8300 (org-table-goto-column colpos)
8301 (org-table-align)
8302 (org-table-fix-formulas "$" nil (1- col) 1)))
8304 (defun org-table-find-dataline ()
8305 "Find a dataline in the current table, which is needed for column commands."
8306 (if (and (org-at-table-p)
8307 (not (org-at-table-hline-p)))
8309 (let ((col (current-column))
8310 (end (org-table-end)))
8311 (move-to-column col)
8312 (while (and (< (point) end)
8313 (or (not (= (current-column) col))
8314 (org-at-table-hline-p)))
8315 (beginning-of-line 2)
8316 (move-to-column col))
8317 (if (and (org-at-table-p)
8318 (not (org-at-table-hline-p)))
8320 (error
8321 "Please position cursor in a data line for column operations")))))
8323 (defun org-table-delete-column ()
8324 "Delete a column from the table."
8325 (interactive)
8326 (if (not (org-at-table-p))
8327 (error "Not at a table"))
8328 (org-table-find-dataline)
8329 (org-table-check-inside-data-field)
8330 (let* ((col (org-table-current-column))
8331 (beg (org-table-begin))
8332 (end (org-table-end))
8333 ;; Current cursor position
8334 (linepos (org-current-line))
8335 (colpos col))
8336 (goto-char beg)
8337 (while (< (point) end)
8338 (if (org-at-table-hline-p)
8340 (org-table-goto-column col t)
8341 (and (looking-at "|[^|\n]+|")
8342 (replace-match "|")))
8343 (beginning-of-line 2))
8344 (move-marker end nil)
8345 (goto-line linepos)
8346 (org-table-goto-column colpos)
8347 (org-table-align)
8348 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
8349 col -1 col)))
8351 (defun org-table-move-column-right ()
8352 "Move column to the right."
8353 (interactive)
8354 (org-table-move-column nil))
8355 (defun org-table-move-column-left ()
8356 "Move column to the left."
8357 (interactive)
8358 (org-table-move-column 'left))
8360 (defun org-table-move-column (&optional left)
8361 "Move the current column to the right. With arg LEFT, move to the left."
8362 (interactive "P")
8363 (if (not (org-at-table-p))
8364 (error "Not at a table"))
8365 (org-table-find-dataline)
8366 (org-table-check-inside-data-field)
8367 (let* ((col (org-table-current-column))
8368 (col1 (if left (1- col) col))
8369 (beg (org-table-begin))
8370 (end (org-table-end))
8371 ;; Current cursor position
8372 (linepos (org-current-line))
8373 (colpos (if left (1- col) (1+ col))))
8374 (if (and left (= col 1))
8375 (error "Cannot move column further left"))
8376 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8377 (error "Cannot move column further right"))
8378 (goto-char beg)
8379 (while (< (point) end)
8380 (if (org-at-table-hline-p)
8382 (org-table-goto-column col1 t)
8383 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8384 (replace-match "|\\2|\\1|")))
8385 (beginning-of-line 2))
8386 (move-marker end nil)
8387 (goto-line linepos)
8388 (org-table-goto-column colpos)
8389 (org-table-align)
8390 (org-table-fix-formulas
8391 "$" (list (cons (number-to-string col) (number-to-string colpos))
8392 (cons (number-to-string colpos) (number-to-string col))))))
8394 (defun org-table-move-row-down ()
8395 "Move table row down."
8396 (interactive)
8397 (org-table-move-row nil))
8398 (defun org-table-move-row-up ()
8399 "Move table row up."
8400 (interactive)
8401 (org-table-move-row 'up))
8403 (defun org-table-move-row (&optional up)
8404 "Move the current table line down. With arg UP, move it up."
8405 (interactive "P")
8406 (let* ((col (current-column))
8407 (pos (point))
8408 (hline1p (save-excursion (beginning-of-line 1)
8409 (looking-at org-table-hline-regexp)))
8410 (dline1 (org-table-current-dline))
8411 (dline2 (+ dline1 (if up -1 1)))
8412 (tonew (if up 0 2))
8413 txt hline2p)
8414 (beginning-of-line tonew)
8415 (unless (org-at-table-p)
8416 (goto-char pos)
8417 (error "Cannot move row further"))
8418 (setq hline2p (looking-at org-table-hline-regexp))
8419 (goto-char pos)
8420 (beginning-of-line 1)
8421 (setq pos (point))
8422 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
8423 (delete-region (point) (1+ (point-at-eol)))
8424 (beginning-of-line tonew)
8425 (insert txt)
8426 (beginning-of-line 0)
8427 (move-to-column col)
8428 (unless (or hline1p hline2p)
8429 (org-table-fix-formulas
8430 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
8431 (cons (number-to-string dline2) (number-to-string dline1)))))))
8433 (defun org-table-insert-row (&optional arg)
8434 "Insert a new row above the current line into the table.
8435 With prefix ARG, insert below the current line."
8436 (interactive "P")
8437 (if (not (org-at-table-p))
8438 (error "Not at a table"))
8439 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
8440 (new (org-table-clean-line line)))
8441 ;; Fix the first field if necessary
8442 (if (string-match "^[ \t]*| *[#$] *|" line)
8443 (setq new (replace-match (match-string 0 line) t t new)))
8444 (beginning-of-line (if arg 2 1))
8445 (let (org-table-may-need-update) (insert-before-markers new "\n"))
8446 (beginning-of-line 0)
8447 (re-search-forward "| ?" (point-at-eol) t)
8448 (and (or org-table-may-need-update org-table-overlay-coordinates)
8449 (org-table-align))
8450 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
8452 (defun org-table-insert-hline (&optional above)
8453 "Insert a horizontal-line below the current line into the table.
8454 With prefix ABOVE, insert above the current line."
8455 (interactive "P")
8456 (if (not (org-at-table-p))
8457 (error "Not at a table"))
8458 (let ((line (org-table-clean-line
8459 (buffer-substring (point-at-bol) (point-at-eol))))
8460 (col (current-column)))
8461 (while (string-match "|\\( +\\)|" line)
8462 (setq line (replace-match
8463 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
8464 ?-) "|") t t line)))
8465 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
8466 (beginning-of-line (if above 1 2))
8467 (insert line "\n")
8468 (beginning-of-line (if above 1 -1))
8469 (move-to-column col)
8470 (and org-table-overlay-coordinates (org-table-align))))
8472 (defun org-table-hline-and-move (&optional same-column)
8473 "Insert a hline and move to the row below that line."
8474 (interactive "P")
8475 (let ((col (org-table-current-column)))
8476 (org-table-maybe-eval-formula)
8477 (org-table-maybe-recalculate-line)
8478 (org-table-insert-hline)
8479 (end-of-line 2)
8480 (if (looking-at "\n[ \t]*|-")
8481 (progn (insert "\n|") (org-table-align))
8482 (org-table-next-field))
8483 (if same-column (org-table-goto-column col))))
8485 (defun org-table-clean-line (s)
8486 "Convert a table line S into a string with only \"|\" and space.
8487 In particular, this does handle wide and invisible characters."
8488 (if (string-match "^[ \t]*|-" s)
8489 ;; It's a hline, just map the characters
8490 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
8491 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
8492 (setq s (replace-match
8493 (concat "|" (make-string (org-string-width (match-string 1 s))
8494 ?\ ) "|")
8495 t t s)))
8498 (defun org-table-kill-row ()
8499 "Delete the current row or horizontal line from the table."
8500 (interactive)
8501 (if (not (org-at-table-p))
8502 (error "Not at a table"))
8503 (let ((col (current-column))
8504 (dline (org-table-current-dline)))
8505 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
8506 (if (not (org-at-table-p)) (beginning-of-line 0))
8507 (move-to-column col)
8508 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
8509 dline -1 dline)))
8511 (defun org-table-sort-lines (with-case &optional sorting-type)
8512 "Sort table lines according to the column at point.
8514 The position of point indicates the column to be used for
8515 sorting, and the range of lines is the range between the nearest
8516 horizontal separator lines, or the entire table of no such lines
8517 exist. If point is before the first column, you will be prompted
8518 for the sorting column. If there is an active region, the mark
8519 specifies the first line and the sorting column, while point
8520 should be in the last line to be included into the sorting.
8522 The command then prompts for the sorting type which can be
8523 alphabetically, numerically, or by time (as given in a time stamp
8524 in the field). Sorting in reverse order is also possible.
8526 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
8528 If SORTING-TYPE is specified when this function is called from a Lisp
8529 program, no prompting will take place. SORTING-TYPE must be a character,
8530 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
8531 should be done in reverse order."
8532 (interactive "P")
8533 (let* ((thisline (org-current-line))
8534 (thiscol (org-table-current-column))
8535 beg end bcol ecol tend tbeg column lns pos)
8536 (when (equal thiscol 0)
8537 (if (interactive-p)
8538 (setq thiscol
8539 (string-to-number
8540 (read-string "Use column N for sorting: ")))
8541 (setq thiscol 1))
8542 (org-table-goto-column thiscol))
8543 (org-table-check-inside-data-field)
8544 (if (org-region-active-p)
8545 (progn
8546 (setq beg (region-beginning) end (region-end))
8547 (goto-char beg)
8548 (setq column (org-table-current-column)
8549 beg (point-at-bol))
8550 (goto-char end)
8551 (setq end (point-at-bol 2)))
8552 (setq column (org-table-current-column)
8553 pos (point)
8554 tbeg (org-table-begin)
8555 tend (org-table-end))
8556 (if (re-search-backward org-table-hline-regexp tbeg t)
8557 (setq beg (point-at-bol 2))
8558 (goto-char tbeg)
8559 (setq beg (point-at-bol 1)))
8560 (goto-char pos)
8561 (if (re-search-forward org-table-hline-regexp tend t)
8562 (setq end (point-at-bol 1))
8563 (goto-char tend)
8564 (setq end (point-at-bol))))
8565 (setq beg (move-marker (make-marker) beg)
8566 end (move-marker (make-marker) end))
8567 (untabify beg end)
8568 (goto-char beg)
8569 (org-table-goto-column column)
8570 (skip-chars-backward "^|")
8571 (setq bcol (current-column))
8572 (org-table-goto-column (1+ column))
8573 (skip-chars-backward "^|")
8574 (setq ecol (1- (current-column)))
8575 (org-table-goto-column column)
8576 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
8577 (org-split-string (buffer-substring beg end) "\n")))
8578 (setq lns (org-do-sort lns "Table" with-case sorting-type))
8579 (delete-region beg end)
8580 (move-marker beg nil)
8581 (move-marker end nil)
8582 (insert (mapconcat 'cdr lns "\n") "\n")
8583 (goto-line thisline)
8584 (org-table-goto-column thiscol)
8585 (message "%d lines sorted, based on column %d" (length lns) column)))
8587 (defun org-table-cut-region (beg end)
8588 "Copy region in table to the clipboard and blank all relevant fields."
8589 (interactive "r")
8590 (org-table-copy-region beg end 'cut))
8592 (defun org-table-copy-region (beg end &optional cut)
8593 "Copy rectangular region in table to clipboard.
8594 A special clipboard is used which can only be accessed
8595 with `org-table-paste-rectangle'."
8596 (interactive "rP")
8597 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
8598 region cols
8599 (rpl (if cut " " nil)))
8600 (goto-char beg)
8601 (org-table-check-inside-data-field)
8602 (setq l01 (org-current-line)
8603 c01 (org-table-current-column))
8604 (goto-char end)
8605 (org-table-check-inside-data-field)
8606 (setq l02 (org-current-line)
8607 c02 (org-table-current-column))
8608 (setq l1 (min l01 l02) l2 (max l01 l02)
8609 c1 (min c01 c02) c2 (max c01 c02))
8610 (catch 'exit
8611 (while t
8612 (catch 'nextline
8613 (if (> l1 l2) (throw 'exit t))
8614 (goto-line l1)
8615 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
8616 (setq cols nil ic1 c1 ic2 c2)
8617 (while (< ic1 (1+ ic2))
8618 (push (org-table-get-field ic1 rpl) cols)
8619 (setq ic1 (1+ ic1)))
8620 (push (nreverse cols) region)
8621 (setq l1 (1+ l1)))))
8622 (setq org-table-clip (nreverse region))
8623 (if cut (org-table-align))
8624 org-table-clip))
8626 (defun org-table-paste-rectangle ()
8627 "Paste a rectangular region into a table.
8628 The upper right corner ends up in the current field. All involved fields
8629 will be overwritten. If the rectangle does not fit into the present table,
8630 the table is enlarged as needed. The process ignores horizontal separator
8631 lines."
8632 (interactive)
8633 (unless (and org-table-clip (listp org-table-clip))
8634 (error "First cut/copy a region to paste!"))
8635 (org-table-check-inside-data-field)
8636 (let* ((clip org-table-clip)
8637 (line (org-current-line))
8638 (col (org-table-current-column))
8639 (org-enable-table-editor t)
8640 (org-table-automatic-realign nil)
8641 c cols field)
8642 (while (setq cols (pop clip))
8643 (while (org-at-table-hline-p) (beginning-of-line 2))
8644 (if (not (org-at-table-p))
8645 (progn (end-of-line 0) (org-table-next-field)))
8646 (setq c col)
8647 (while (setq field (pop cols))
8648 (org-table-goto-column c nil 'force)
8649 (org-table-get-field nil field)
8650 (setq c (1+ c)))
8651 (beginning-of-line 2))
8652 (goto-line line)
8653 (org-table-goto-column col)
8654 (org-table-align)))
8656 (defun org-table-convert ()
8657 "Convert from `org-mode' table to table.el and back.
8658 Obviously, this only works within limits. When an Org-mode table is
8659 converted to table.el, all horizontal separator lines get lost, because
8660 table.el uses these as cell boundaries and has no notion of horizontal lines.
8661 A table.el table can be converted to an Org-mode table only if it does not
8662 do row or column spanning. Multiline cells will become multiple cells.
8663 Beware, Org-mode does not test if the table can be successfully converted - it
8664 blindly applies a recipe that works for simple tables."
8665 (interactive)
8666 (require 'table)
8667 (if (org-at-table.el-p)
8668 ;; convert to Org-mode table
8669 (let ((beg (move-marker (make-marker) (org-table-begin t)))
8670 (end (move-marker (make-marker) (org-table-end t))))
8671 (table-unrecognize-region beg end)
8672 (goto-char beg)
8673 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
8674 (replace-match ""))
8675 (goto-char beg))
8676 (if (org-at-table-p)
8677 ;; convert to table.el table
8678 (let ((beg (move-marker (make-marker) (org-table-begin)))
8679 (end (move-marker (make-marker) (org-table-end))))
8680 ;; first, get rid of all horizontal lines
8681 (goto-char beg)
8682 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
8683 (replace-match ""))
8684 ;; insert a hline before first
8685 (goto-char beg)
8686 (org-table-insert-hline 'above)
8687 (beginning-of-line -1)
8688 ;; insert a hline after each line
8689 (while (progn (beginning-of-line 3) (< (point) end))
8690 (org-table-insert-hline))
8691 (goto-char beg)
8692 (setq end (move-marker end (org-table-end)))
8693 ;; replace "+" at beginning and ending of hlines
8694 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
8695 (replace-match "\\1+-"))
8696 (goto-char beg)
8697 (while (re-search-forward "-|[ \t]*$" end t)
8698 (replace-match "-+"))
8699 (goto-char beg)))))
8701 (defun org-table-wrap-region (arg)
8702 "Wrap several fields in a column like a paragraph.
8703 This is useful if you'd like to spread the contents of a field over several
8704 lines, in order to keep the table compact.
8706 If there is an active region, and both point and mark are in the same column,
8707 the text in the column is wrapped to minimum width for the given number of
8708 lines. Generally, this makes the table more compact. A prefix ARG may be
8709 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
8710 formats the selected text to two lines. If the region was longer than two
8711 lines, the remaining lines remain empty. A negative prefix argument reduces
8712 the current number of lines by that amount. The wrapped text is pasted back
8713 into the table. If you formatted it to more lines than it was before, fields
8714 further down in the table get overwritten - so you might need to make space in
8715 the table first.
8717 If there is no region, the current field is split at the cursor position and
8718 the text fragment to the right of the cursor is prepended to the field one
8719 line down.
8721 If there is no region, but you specify a prefix ARG, the current field gets
8722 blank, and the content is appended to the field above."
8723 (interactive "P")
8724 (org-table-check-inside-data-field)
8725 (if (org-region-active-p)
8726 ;; There is a region: fill as a paragraph
8727 (let* ((beg (region-beginning))
8728 (cline (save-excursion (goto-char beg) (org-current-line)))
8729 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
8730 nlines)
8731 (org-table-cut-region (region-beginning) (region-end))
8732 (if (> (length (car org-table-clip)) 1)
8733 (error "Region must be limited to single column"))
8734 (setq nlines (if arg
8735 (if (< arg 1)
8736 (+ (length org-table-clip) arg)
8737 arg)
8738 (length org-table-clip)))
8739 (setq org-table-clip
8740 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
8741 nil nlines)))
8742 (goto-line cline)
8743 (org-table-goto-column ccol)
8744 (org-table-paste-rectangle))
8745 ;; No region, split the current field at point
8746 (if arg
8747 ;; combine with field above
8748 (let ((s (org-table-blank-field))
8749 (col (org-table-current-column)))
8750 (beginning-of-line 0)
8751 (while (org-at-table-hline-p) (beginning-of-line 0))
8752 (org-table-goto-column col)
8753 (skip-chars-forward "^|")
8754 (skip-chars-backward " ")
8755 (insert " " (org-trim s))
8756 (org-table-align))
8757 ;; split field
8758 (when (looking-at "\\([^|]+\\)+|")
8759 (let ((s (match-string 1)))
8760 (replace-match " |")
8761 (goto-char (match-beginning 0))
8762 (org-table-next-row)
8763 (insert (org-trim s) " ")
8764 (org-table-align))))))
8766 (defvar org-field-marker nil)
8768 (defun org-table-edit-field (arg)
8769 "Edit table field in a different window.
8770 This is mainly useful for fields that contain hidden parts.
8771 When called with a \\[universal-argument] prefix, just make the full field visible so that
8772 it can be edited in place."
8773 (interactive "P")
8774 (if arg
8775 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
8776 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
8777 (remove-text-properties b e '(org-cwidth t invisible t
8778 display t intangible t))
8779 (if (and (boundp 'font-lock-mode) font-lock-mode)
8780 (font-lock-fontify-block)))
8781 (let ((pos (move-marker (make-marker) (point)))
8782 (field (org-table-get-field))
8783 (cw (current-window-configuration))
8785 (org-switch-to-buffer-other-window "*Org tmp*")
8786 (erase-buffer)
8787 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
8788 (let ((org-inhibit-startup t)) (org-mode))
8789 (goto-char (setq p (point-max)))
8790 (insert (org-trim field))
8791 (remove-text-properties p (point-max)
8792 '(invisible t org-cwidth t display t
8793 intangible t))
8794 (goto-char p)
8795 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
8796 (org-set-local 'org-window-configuration cw)
8797 (org-set-local 'org-field-marker pos)
8798 (message "Edit and finish with C-c C-c"))))
8800 (defun org-table-finish-edit-field ()
8801 "Finish editing a table data field.
8802 Remove all newline characters, insert the result into the table, realign
8803 the table and kill the editing buffer."
8804 (let ((pos org-field-marker)
8805 (cw org-window-configuration)
8806 (cb (current-buffer))
8807 text)
8808 (goto-char (point-min))
8809 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
8810 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
8811 (replace-match " "))
8812 (setq text (org-trim (buffer-string)))
8813 (set-window-configuration cw)
8814 (kill-buffer cb)
8815 (select-window (get-buffer-window (marker-buffer pos)))
8816 (goto-char pos)
8817 (move-marker pos nil)
8818 (org-table-check-inside-data-field)
8819 (org-table-get-field nil text)
8820 (org-table-align)
8821 (message "New field value inserted")))
8823 (defun org-trim (s)
8824 "Remove whitespace at beginning and end of string."
8825 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
8826 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
8829 (defun org-wrap (string &optional width lines)
8830 "Wrap string to either a number of lines, or a width in characters.
8831 If WIDTH is non-nil, the string is wrapped to that width, however many lines
8832 that costs. If there is a word longer than WIDTH, the text is actually
8833 wrapped to the length of that word.
8834 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
8835 many lines, whatever width that takes.
8836 The return value is a list of lines, without newlines at the end."
8837 (let* ((words (org-split-string string "[ \t\n]+"))
8838 (maxword (apply 'max (mapcar 'org-string-width words)))
8839 w ll)
8840 (cond (width
8841 (org-do-wrap words (max maxword width)))
8842 (lines
8843 (setq w maxword)
8844 (setq ll (org-do-wrap words maxword))
8845 (if (<= (length ll) lines)
8847 (setq ll words)
8848 (while (> (length ll) lines)
8849 (setq w (1+ w))
8850 (setq ll (org-do-wrap words w)))
8851 ll))
8852 (t (error "Cannot wrap this")))))
8855 (defun org-do-wrap (words width)
8856 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
8857 (let (lines line)
8858 (while words
8859 (setq line (pop words))
8860 (while (and words (< (+ (length line) (length (car words))) width))
8861 (setq line (concat line " " (pop words))))
8862 (setq lines (push line lines)))
8863 (nreverse lines)))
8865 (defun org-split-string (string &optional separators)
8866 "Splits STRING into substrings at SEPARATORS.
8867 No empty strings are returned if there are matches at the beginning
8868 and end of string."
8869 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
8870 (start 0)
8871 notfirst
8872 (list nil))
8873 (while (and (string-match rexp string
8874 (if (and notfirst
8875 (= start (match-beginning 0))
8876 (< start (length string)))
8877 (1+ start) start))
8878 (< (match-beginning 0) (length string)))
8879 (setq notfirst t)
8880 (or (eq (match-beginning 0) 0)
8881 (and (eq (match-beginning 0) (match-end 0))
8882 (eq (match-beginning 0) start))
8883 (setq list
8884 (cons (substring string start (match-beginning 0))
8885 list)))
8886 (setq start (match-end 0)))
8887 (or (eq start (length string))
8888 (setq list
8889 (cons (substring string start)
8890 list)))
8891 (nreverse list)))
8893 (defun org-table-map-tables (function)
8894 "Apply FUNCTION to the start of all tables in the buffer."
8895 (save-excursion
8896 (save-restriction
8897 (widen)
8898 (goto-char (point-min))
8899 (while (re-search-forward org-table-any-line-regexp nil t)
8900 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
8901 (beginning-of-line 1)
8902 (if (looking-at org-table-line-regexp)
8903 (save-excursion (funcall function)))
8904 (re-search-forward org-table-any-border-regexp nil 1))))
8905 (message "Mapping tables: done"))
8907 (defvar org-timecnt) ; dynamically scoped parameter
8909 (defun org-table-sum (&optional beg end nlast)
8910 "Sum numbers in region of current table column.
8911 The result will be displayed in the echo area, and will be available
8912 as kill to be inserted with \\[yank].
8914 If there is an active region, it is interpreted as a rectangle and all
8915 numbers in that rectangle will be summed. If there is no active
8916 region and point is located in a table column, sum all numbers in that
8917 column.
8919 If at least one number looks like a time HH:MM or HH:MM:SS, all other
8920 numbers are assumed to be times as well (in decimal hours) and the
8921 numbers are added as such.
8923 If NLAST is a number, only the NLAST fields will actually be summed."
8924 (interactive)
8925 (save-excursion
8926 (let (col (org-timecnt 0) diff h m s org-table-clip)
8927 (cond
8928 ((and beg end)) ; beg and end given explicitly
8929 ((org-region-active-p)
8930 (setq beg (region-beginning) end (region-end)))
8932 (setq col (org-table-current-column))
8933 (goto-char (org-table-begin))
8934 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
8935 (error "No table data"))
8936 (org-table-goto-column col)
8937 (setq beg (point))
8938 (goto-char (org-table-end))
8939 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
8940 (error "No table data"))
8941 (org-table-goto-column col)
8942 (setq end (point))))
8943 (let* ((items (apply 'append (org-table-copy-region beg end)))
8944 (items1 (cond ((not nlast) items)
8945 ((>= nlast (length items)) items)
8946 (t (setq items (reverse items))
8947 (setcdr (nthcdr (1- nlast) items) nil)
8948 (nreverse items))))
8949 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
8950 items1)))
8951 (res (apply '+ numbers))
8952 (sres (if (= org-timecnt 0)
8953 (format "%g" res)
8954 (setq diff (* 3600 res)
8955 h (floor (/ diff 3600)) diff (mod diff 3600)
8956 m (floor (/ diff 60)) diff (mod diff 60)
8957 s diff)
8958 (format "%d:%02d:%02d" h m s))))
8959 (kill-new sres)
8960 (if (interactive-p)
8961 (message "%s"
8962 (substitute-command-keys
8963 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
8964 (length numbers) sres))))
8965 sres))))
8967 (defun org-table-get-number-for-summing (s)
8968 (let (n)
8969 (if (string-match "^ *|? *" s)
8970 (setq s (replace-match "" nil nil s)))
8971 (if (string-match " *|? *$" s)
8972 (setq s (replace-match "" nil nil s)))
8973 (setq n (string-to-number s))
8974 (cond
8975 ((and (string-match "0" s)
8976 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
8977 ((string-match "\\`[ \t]+\\'" s) nil)
8978 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
8979 (let ((h (string-to-number (or (match-string 1 s) "0")))
8980 (m (string-to-number (or (match-string 2 s) "0")))
8981 (s (string-to-number (or (match-string 4 s) "0"))))
8982 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
8983 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
8984 ((equal n 0) nil)
8985 (t n))))
8987 (defun org-table-current-field-formula (&optional key noerror)
8988 "Return the formula active for the current field.
8989 Assumes that specials are in place.
8990 If KEY is given, return the key to this formula.
8991 Otherwise return the formula preceeded with \"=\" or \":=\"."
8992 (let* ((name (car (rassoc (list (org-current-line)
8993 (org-table-current-column))
8994 org-table-named-field-locations)))
8995 (col (org-table-current-column))
8996 (scol (int-to-string col))
8997 (ref (format "@%d$%d" (org-table-current-dline) col))
8998 (stored-list (org-table-get-stored-formulas noerror))
8999 (ass (or (assoc name stored-list)
9000 (assoc ref stored-list)
9001 (assoc scol stored-list))))
9002 (if key
9003 (car ass)
9004 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9005 (cdr ass))))))
9007 (defun org-table-get-formula (&optional equation named)
9008 "Read a formula from the minibuffer, offer stored formula as default.
9009 When NAMED is non-nil, look for a named equation."
9010 (let* ((stored-list (org-table-get-stored-formulas))
9011 (name (car (rassoc (list (org-current-line)
9012 (org-table-current-column))
9013 org-table-named-field-locations)))
9014 (ref (format "@%d$%d" (org-table-current-dline)
9015 (org-table-current-column)))
9016 (refass (assoc ref stored-list))
9017 (scol (if named
9018 (if name name ref)
9019 (int-to-string (org-table-current-column))))
9020 (dummy (and (or name refass) (not named)
9021 (not (y-or-n-p "Replace field formula with column formula? " ))
9022 (error "Abort")))
9023 (name (or name ref))
9024 (org-table-may-need-update nil)
9025 (stored (cdr (assoc scol stored-list)))
9026 (eq (cond
9027 ((and stored equation (string-match "^ *=? *$" equation))
9028 stored)
9029 ((stringp equation)
9030 equation)
9031 (t (org-table-formula-from-user
9032 (read-string
9033 (org-table-formula-to-user
9034 (format "%s formula %s%s="
9035 (if named "Field" "Column")
9036 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9037 scol))
9038 (if stored (org-table-formula-to-user stored) "")
9039 'org-table-formula-history
9040 )))))
9041 mustsave)
9042 (when (not (string-match "\\S-" eq))
9043 ;; remove formula
9044 (setq stored-list (delq (assoc scol stored-list) stored-list))
9045 (org-table-store-formulas stored-list)
9046 (error "Formula removed"))
9047 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9048 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9049 (if (and name (not named))
9050 ;; We set the column equation, delete the named one.
9051 (setq stored-list (delq (assoc name stored-list) stored-list)
9052 mustsave t))
9053 (if stored
9054 (setcdr (assoc scol stored-list) eq)
9055 (setq stored-list (cons (cons scol eq) stored-list)))
9056 (if (or mustsave (not (equal stored eq)))
9057 (org-table-store-formulas stored-list))
9058 eq))
9060 (defun org-table-store-formulas (alist)
9061 "Store the list of formulas below the current table."
9062 (setq alist (sort alist 'org-table-formula-less-p))
9063 (save-excursion
9064 (goto-char (org-table-end))
9065 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9066 (progn
9067 ;; don't overwrite TBLFM, we might use text properties to store stuff
9068 (goto-char (match-beginning 2))
9069 (delete-region (match-beginning 2) (match-end 0)))
9070 (insert "#+TBLFM:"))
9071 (insert " "
9072 (mapconcat (lambda (x)
9073 (concat
9074 (if (equal (string-to-char (car x)) ?@) "" "$")
9075 (car x) "=" (cdr x)))
9076 alist "::")
9077 "\n")))
9079 (defsubst org-table-formula-make-cmp-string (a)
9080 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9081 (concat
9082 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9083 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9084 (if (match-end 5) (concat "@@" (match-string 5 a))))))
9086 (defun org-table-formula-less-p (a b)
9087 "Compare two formulas for sorting."
9088 (let ((as (org-table-formula-make-cmp-string (car a)))
9089 (bs (org-table-formula-make-cmp-string (car b))))
9090 (and as bs (string< as bs))))
9092 (defun org-table-get-stored-formulas (&optional noerror)
9093 "Return an alist with the stored formulas directly after current table."
9094 (interactive)
9095 (let (scol eq eq-alist strings string seen)
9096 (save-excursion
9097 (goto-char (org-table-end))
9098 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9099 (setq strings (org-split-string (match-string 2) " *:: *"))
9100 (while (setq string (pop strings))
9101 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
9102 (setq scol (if (match-end 2)
9103 (match-string 2 string)
9104 (match-string 1 string))
9105 eq (match-string 3 string)
9106 eq-alist (cons (cons scol eq) eq-alist))
9107 (if (member scol seen)
9108 (if noerror
9109 (progn
9110 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9111 (ding)
9112 (sit-for 2))
9113 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
9114 (push scol seen))))))
9115 (nreverse eq-alist)))
9117 (defun org-table-fix-formulas (key replace &optional limit delta remove)
9118 "Modify the equations after the table structure has been edited.
9119 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
9120 For all numbers larger than LIMIT, shift them by DELTA."
9121 (save-excursion
9122 (goto-char (org-table-end))
9123 (when (looking-at "#\\+TBLFM:")
9124 (let ((re (concat key "\\([0-9]+\\)"))
9125 (re2
9126 (when remove
9127 (if (equal key "$")
9128 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
9129 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
9130 s n a)
9131 (when remove
9132 (while (re-search-forward re2 (point-at-eol) t)
9133 (replace-match "")))
9134 (while (re-search-forward re (point-at-eol) t)
9135 (setq s (match-string 1) n (string-to-number s))
9136 (cond
9137 ((setq a (assoc s replace))
9138 (replace-match (concat key (cdr a)) t t))
9139 ((and limit (> n limit))
9140 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
9142 (defun org-table-get-specials ()
9143 "Get the column names and local parameters for this table."
9144 (save-excursion
9145 (let ((beg (org-table-begin)) (end (org-table-end))
9146 names name fields fields1 field cnt
9147 c v l line col types dlines hlines)
9148 (setq org-table-column-names nil
9149 org-table-local-parameters nil
9150 org-table-named-field-locations nil
9151 org-table-current-begin-line nil
9152 org-table-current-begin-pos nil
9153 org-table-current-line-types nil)
9154 (goto-char beg)
9155 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9156 (setq names (org-split-string (match-string 1) " *| *")
9157 cnt 1)
9158 (while (setq name (pop names))
9159 (setq cnt (1+ cnt))
9160 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9161 (push (cons name (int-to-string cnt)) org-table-column-names))))
9162 (setq org-table-column-names (nreverse org-table-column-names))
9163 (setq org-table-column-name-regexp
9164 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9165 (goto-char beg)
9166 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9167 (setq fields (org-split-string (match-string 1) " *| *"))
9168 (while (setq field (pop fields))
9169 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9170 (push (cons (match-string 1 field) (match-string 2 field))
9171 org-table-local-parameters))))
9172 (goto-char beg)
9173 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9174 (setq c (match-string 1)
9175 fields (org-split-string (match-string 2) " *| *"))
9176 (save-excursion
9177 (beginning-of-line (if (equal c "_") 2 0))
9178 (setq line (org-current-line) col 1)
9179 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9180 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9181 (while (and fields1 (setq field (pop fields)))
9182 (setq v (pop fields1) col (1+ col))
9183 (when (and (stringp field) (stringp v)
9184 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9185 (push (cons field v) org-table-local-parameters)
9186 (push (list field line col) org-table-named-field-locations))))
9187 ;; Analyse the line types
9188 (goto-char beg)
9189 (setq org-table-current-begin-line (org-current-line)
9190 org-table-current-begin-pos (point)
9191 l org-table-current-begin-line)
9192 (while (looking-at "[ \t]*|\\(-\\)?")
9193 (push (if (match-end 1) 'hline 'dline) types)
9194 (if (match-end 1) (push l hlines) (push l dlines))
9195 (beginning-of-line 2)
9196 (setq l (1+ l)))
9197 (setq org-table-current-line-types (apply 'vector (nreverse types))
9198 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
9199 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
9201 (defun org-table-maybe-eval-formula ()
9202 "Check if the current field starts with \"=\" or \":=\".
9203 If yes, store the formula and apply it."
9204 ;; We already know we are in a table. Get field will only return a formula
9205 ;; when appropriate. It might return a separator line, but no problem.
9206 (when org-table-formula-evaluate-inline
9207 (let* ((field (org-trim (or (org-table-get-field) "")))
9208 named eq)
9209 (when (string-match "^:?=\\(.*\\)" field)
9210 (setq named (equal (string-to-char field) ?:)
9211 eq (match-string 1 field))
9212 (if (or (fboundp 'calc-eval)
9213 (equal (substring eq 0 (min 2 (length eq))) "'("))
9214 (org-table-eval-formula (if named '(4) nil)
9215 (org-table-formula-from-user eq))
9216 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
9218 (defvar org-recalc-commands nil
9219 "List of commands triggering the recalculation of a line.
9220 Will be filled automatically during use.")
9222 (defvar org-recalc-marks
9223 '((" " . "Unmarked: no special line, no automatic recalculation")
9224 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9225 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9226 ("!" . "Column name definition line. Reference in formula as $name.")
9227 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9228 ("_" . "Names for values in row below this one.")
9229 ("^" . "Names for values in row above this one.")))
9231 (defun org-table-rotate-recalc-marks (&optional newchar)
9232 "Rotate the recalculation mark in the first column.
9233 If in any row, the first field is not consistent with a mark,
9234 insert a new column for the markers.
9235 When there is an active region, change all the lines in the region,
9236 after prompting for the marking character.
9237 After each change, a message will be displayed indicating the meaning
9238 of the new mark."
9239 (interactive)
9240 (unless (org-at-table-p) (error "Not at a table"))
9241 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9242 (beg (org-table-begin))
9243 (end (org-table-end))
9244 (l (org-current-line))
9245 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9246 (l2 (if (org-region-active-p) (org-current-line (region-end))))
9247 (have-col
9248 (save-excursion
9249 (goto-char beg)
9250 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
9251 (col (org-table-current-column))
9252 (forcenew (car (assoc newchar org-recalc-marks)))
9253 epos new)
9254 (when l1
9255 (message "Change region to what mark? Type # * ! $ or SPC: ")
9256 (setq newchar (char-to-string (read-char-exclusive))
9257 forcenew (car (assoc newchar org-recalc-marks))))
9258 (if (and newchar (not forcenew))
9259 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
9260 newchar))
9261 (if l1 (goto-line l1))
9262 (save-excursion
9263 (beginning-of-line 1)
9264 (unless (looking-at org-table-dataline-regexp)
9265 (error "Not at a table data line")))
9266 (unless have-col
9267 (org-table-goto-column 1)
9268 (org-table-insert-column)
9269 (org-table-goto-column (1+ col)))
9270 (setq epos (point-at-eol))
9271 (save-excursion
9272 (beginning-of-line 1)
9273 (org-table-get-field
9274 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
9275 (concat " "
9276 (setq new (or forcenew
9277 (cadr (member (match-string 1) marks))))
9278 " ")
9279 " # ")))
9280 (if (and l1 l2)
9281 (progn
9282 (goto-line l1)
9283 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
9284 (and (looking-at org-table-dataline-regexp)
9285 (org-table-get-field 1 (concat " " new " "))))
9286 (goto-line l1)))
9287 (if (not (= epos (point-at-eol))) (org-table-align))
9288 (goto-line l)
9289 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
9291 (defun org-table-maybe-recalculate-line ()
9292 "Recompute the current line if marked for it, and if we haven't just done it."
9293 (interactive)
9294 (and org-table-allow-automatic-line-recalculation
9295 (not (and (memq last-command org-recalc-commands)
9296 (equal org-last-recalc-line (org-current-line))))
9297 (save-excursion (beginning-of-line 1)
9298 (looking-at org-table-auto-recalculate-regexp))
9299 (org-table-recalculate) t))
9301 (defvar org-table-formula-debug nil
9302 "Non-nil means, debug table formulas.
9303 When nil, simply write \"#ERROR\" in corrupted fields.")
9304 (make-variable-buffer-local 'org-table-formula-debug)
9306 (defvar modes)
9307 (defsubst org-set-calc-mode (var &optional value)
9308 (if (stringp var)
9309 (setq var (assoc var '(("D" calc-angle-mode deg)
9310 ("R" calc-angle-mode rad)
9311 ("F" calc-prefer-frac t)
9312 ("S" calc-symbolic-mode t)))
9313 value (nth 2 var) var (nth 1 var)))
9314 (if (memq var modes)
9315 (setcar (cdr (memq var modes)) value)
9316 (cons var (cons value modes)))
9317 modes)
9319 (defun org-table-eval-formula (&optional arg equation
9320 suppress-align suppress-const
9321 suppress-store suppress-analysis)
9322 "Replace the table field value at the cursor by the result of a calculation.
9324 This function makes use of Dave Gillespie's Calc package, in my view the
9325 most exciting program ever written for GNU Emacs. So you need to have Calc
9326 installed in order to use this function.
9328 In a table, this command replaces the value in the current field with the
9329 result of a formula. It also installs the formula as the \"current\" column
9330 formula, by storing it in a special line below the table. When called
9331 with a `C-u' prefix, the current field must ba a named field, and the
9332 formula is installed as valid in only this specific field.
9334 When called with two `C-u' prefixes, insert the active equation
9335 for the field back into the current field, so that it can be
9336 edited there. This is useful in order to use \\[org-table-show-reference]
9337 to check the referenced fields.
9339 When called, the command first prompts for a formula, which is read in
9340 the minibuffer. Previously entered formulas are available through the
9341 history list, and the last used formula is offered as a default.
9342 These stored formulas are adapted correctly when moving, inserting, or
9343 deleting columns with the corresponding commands.
9345 The formula can be any algebraic expression understood by the Calc package.
9346 For details, see the Org-mode manual.
9348 This function can also be called from Lisp programs and offers
9349 additional arguments: EQUATION can be the formula to apply. If this
9350 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
9351 used to speed-up recursive calls by by-passing unnecessary aligns.
9352 SUPPRESS-CONST suppresses the interpretation of constants in the
9353 formula, assuming that this has been done already outside the function.
9354 SUPPRESS-STORE means the formula should not be stored, either because
9355 it is already stored, or because it is a modified equation that should
9356 not overwrite the stored one."
9357 (interactive "P")
9358 (org-table-check-inside-data-field)
9359 (or suppress-analysis (org-table-get-specials))
9360 (if (equal arg '(16))
9361 (let ((eq (org-table-current-field-formula)))
9362 (or eq (error "No equation active for current field"))
9363 (org-table-get-field nil eq)
9364 (org-table-align)
9365 (setq org-table-may-need-update t))
9366 (let* (fields
9367 (ndown (if (integerp arg) arg 1))
9368 (org-table-automatic-realign nil)
9369 (case-fold-search nil)
9370 (down (> ndown 1))
9371 (formula (if (and equation suppress-store)
9372 equation
9373 (org-table-get-formula equation (equal arg '(4)))))
9374 (n0 (org-table-current-column))
9375 (modes (copy-sequence org-calc-default-modes))
9376 (numbers nil) ; was a variable, now fixed default
9377 (keep-empty nil)
9378 n form form0 bw fmt x ev orig c lispp literal)
9379 ;; Parse the format string. Since we have a lot of modes, this is
9380 ;; a lot of work. However, I think calc still uses most of the time.
9381 (if (string-match ";" formula)
9382 (let ((tmp (org-split-string formula ";")))
9383 (setq formula (car tmp)
9384 fmt (concat (cdr (assoc "%" org-table-local-parameters))
9385 (nth 1 tmp)))
9386 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
9387 (setq c (string-to-char (match-string 1 fmt))
9388 n (string-to-number (match-string 2 fmt)))
9389 (if (= c ?p)
9390 (setq modes (org-set-calc-mode 'calc-internal-prec n))
9391 (setq modes (org-set-calc-mode
9392 'calc-float-format
9393 (list (cdr (assoc c '((?n . float) (?f . fix)
9394 (?s . sci) (?e . eng))))
9395 n))))
9396 (setq fmt (replace-match "" t t fmt)))
9397 (if (string-match "[NT]" fmt)
9398 (setq numbers (equal (match-string 0 fmt) "N")
9399 fmt (replace-match "" t t fmt)))
9400 (if (string-match "L" fmt)
9401 (setq literal t
9402 fmt (replace-match "" t t fmt)))
9403 (if (string-match "E" fmt)
9404 (setq keep-empty t
9405 fmt (replace-match "" t t fmt)))
9406 (while (string-match "[DRFS]" fmt)
9407 (setq modes (org-set-calc-mode (match-string 0 fmt)))
9408 (setq fmt (replace-match "" t t fmt)))
9409 (unless (string-match "\\S-" fmt)
9410 (setq fmt nil))))
9411 (if (and (not suppress-const) org-table-formula-use-constants)
9412 (setq formula (org-table-formula-substitute-names formula)))
9413 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
9414 (while (> ndown 0)
9415 (setq fields (org-split-string
9416 (org-no-properties
9417 (buffer-substring (point-at-bol) (point-at-eol)))
9418 " *| *"))
9419 (if (eq numbers t)
9420 (setq fields (mapcar
9421 (lambda (x) (number-to-string (string-to-number x)))
9422 fields)))
9423 (setq ndown (1- ndown))
9424 (setq form (copy-sequence formula)
9425 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
9426 (if (and lispp literal) (setq lispp 'literal))
9427 ;; Check for old vertical references
9428 (setq form (org-rewrite-old-row-references form))
9429 ;; Insert complex ranges
9430 (while (string-match org-table-range-regexp form)
9431 (setq form
9432 (replace-match
9433 (save-match-data
9434 (org-table-make-reference
9435 (org-table-get-range (match-string 0 form) nil n0)
9436 keep-empty numbers lispp))
9437 t t form)))
9438 ;; Insert simple ranges
9439 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
9440 (setq form
9441 (replace-match
9442 (save-match-data
9443 (org-table-make-reference
9444 (org-sublist
9445 fields (string-to-number (match-string 1 form))
9446 (string-to-number (match-string 2 form)))
9447 keep-empty numbers lispp))
9448 t t form)))
9449 (setq form0 form)
9450 ;; Insert the references to fields in same row
9451 (while (string-match "\\$\\([0-9]+\\)" form)
9452 (setq n (string-to-number (match-string 1 form))
9453 x (nth (1- (if (= n 0) n0 n)) fields))
9454 (unless x (error "Invalid field specifier \"%s\""
9455 (match-string 0 form)))
9456 (setq form (replace-match
9457 (save-match-data
9458 (org-table-make-reference x nil numbers lispp))
9459 t t form)))
9461 (if lispp
9462 (setq ev (condition-case nil
9463 (eval (eval (read form)))
9464 (error "#ERROR"))
9465 ev (if (numberp ev) (number-to-string ev) ev))
9466 (or (fboundp 'calc-eval)
9467 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
9468 (setq ev (calc-eval (cons form modes)
9469 (if numbers 'num))))
9471 (when org-table-formula-debug
9472 (with-output-to-temp-buffer "*Substitution History*"
9473 (princ (format "Substitution history of formula
9474 Orig: %s
9475 $xyz-> %s
9476 @r$c-> %s
9477 $1-> %s\n" orig formula form0 form))
9478 (if (listp ev)
9479 (princ (format " %s^\nError: %s"
9480 (make-string (car ev) ?\-) (nth 1 ev)))
9481 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
9482 ev (or fmt "NONE")
9483 (if fmt (format fmt (string-to-number ev)) ev)))))
9484 (setq bw (get-buffer-window "*Substitution History*"))
9485 (shrink-window-if-larger-than-buffer bw)
9486 (unless (and (interactive-p) (not ndown))
9487 (unless (let (inhibit-redisplay)
9488 (y-or-n-p "Debugging Formula. Continue to next? "))
9489 (org-table-align)
9490 (error "Abort"))
9491 (delete-window bw)
9492 (message "")))
9493 (if (listp ev) (setq fmt nil ev "#ERROR"))
9494 (org-table-justify-field-maybe
9495 (if fmt (format fmt (string-to-number ev)) ev))
9496 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
9497 (call-interactively 'org-return)
9498 (setq ndown 0)))
9499 (and down (org-table-maybe-recalculate-line))
9500 (or suppress-align (and org-table-may-need-update
9501 (org-table-align))))))
9503 (defun org-table-put-field-property (prop value)
9504 (save-excursion
9505 (put-text-property (progn (skip-chars-backward "^|") (point))
9506 (progn (skip-chars-forward "^|") (point))
9507 prop value)))
9509 (defun org-table-get-range (desc &optional tbeg col highlight)
9510 "Get a calc vector from a column, accorting to descriptor DESC.
9511 Optional arguments TBEG and COL can give the beginning of the table and
9512 the current column, to avoid unnecessary parsing.
9513 HIGHLIGHT means, just highlight the range."
9514 (if (not (equal (string-to-char desc) ?@))
9515 (setq desc (concat "@" desc)))
9516 (save-excursion
9517 (or tbeg (setq tbeg (org-table-begin)))
9518 (or col (setq col (org-table-current-column)))
9519 (let ((thisline (org-current-line))
9520 beg end c1 c2 r1 r2 rangep tmp)
9521 (unless (string-match org-table-range-regexp desc)
9522 (error "Invalid table range specifier `%s'" desc))
9523 (setq rangep (match-end 3)
9524 r1 (and (match-end 1) (match-string 1 desc))
9525 r2 (and (match-end 4) (match-string 4 desc))
9526 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
9527 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
9529 (and c1 (setq c1 (+ (string-to-number c1)
9530 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
9531 (and c2 (setq c2 (+ (string-to-number c2)
9532 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
9533 (if (equal r1 "") (setq r1 nil))
9534 (if (equal r2 "") (setq r2 nil))
9535 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
9536 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
9537 ; (setq r2 (or r2 r1) c2 (or c2 c1))
9538 (if (not r1) (setq r1 thisline))
9539 (if (not r2) (setq r2 thisline))
9540 (if (not c1) (setq c1 col))
9541 (if (not c2) (setq c2 col))
9542 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
9543 ;; just one field
9544 (progn
9545 (goto-line r1)
9546 (while (not (looking-at org-table-dataline-regexp))
9547 (beginning-of-line 2))
9548 (prog1 (org-trim (org-table-get-field c1))
9549 (if highlight (org-table-highlight-rectangle (point) (point)))))
9550 ;; A range, return a vector
9551 ;; First sort the numbers to get a regular ractangle
9552 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
9553 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
9554 (goto-line r1)
9555 (while (not (looking-at org-table-dataline-regexp))
9556 (beginning-of-line 2))
9557 (org-table-goto-column c1)
9558 (setq beg (point))
9559 (goto-line r2)
9560 (while (not (looking-at org-table-dataline-regexp))
9561 (beginning-of-line 0))
9562 (org-table-goto-column c2)
9563 (setq end (point))
9564 (if highlight
9565 (org-table-highlight-rectangle
9566 beg (progn (skip-chars-forward "^|\n") (point))))
9567 ;; return string representation of calc vector
9568 (mapcar 'org-trim
9569 (apply 'append (org-table-copy-region beg end)))))))
9571 (defun org-table-get-descriptor-line (desc &optional cline bline table)
9572 "Analyze descriptor DESC and retrieve the corresponding line number.
9573 The cursor is currently in line CLINE, the table begins in line BLINE,
9574 and TABLE is a vector with line types."
9575 (if (string-match "^[0-9]+$" desc)
9576 (aref org-table-dlines (string-to-number desc))
9577 (setq cline (or cline (org-current-line))
9578 bline (or bline org-table-current-begin-line)
9579 table (or table org-table-current-line-types))
9580 (if (or
9581 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
9582 ;; 1 2 3 4 5 6
9583 (and (not (match-end 3)) (not (match-end 6)))
9584 (and (match-end 3) (match-end 6) (not (match-end 5))))
9585 (error "invalid row descriptor `%s'" desc))
9586 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
9587 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
9588 (odir (and (match-end 5) (match-string 5 desc)))
9589 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
9590 (i (- cline bline))
9591 (rel (and (match-end 6)
9592 (or (and (match-end 1) (not (match-end 3)))
9593 (match-end 5)))))
9594 (if (and hn (not hdir))
9595 (progn
9596 (setq i 0 hdir "+")
9597 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
9598 (if (and (not hn) on (not odir))
9599 (error "should never happen");;(aref org-table-dlines on)
9600 (if (and hn (> hn 0))
9601 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
9602 (if on
9603 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
9604 (+ bline i)))))
9606 (defun org-find-row-type (table i type backwards relative n)
9607 (let ((l (length table)))
9608 (while (> n 0)
9609 (while (and (setq i (+ i (if backwards -1 1)))
9610 (>= i 0) (< i l)
9611 (not (eq (aref table i) type))
9612 (if (and relative (eq (aref table i) 'hline))
9613 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
9614 t)))
9615 (setq n (1- n)))
9616 (if (or (< i 0) (>= i l))
9617 (error "Row descriptior leads outside table")
9618 i)))
9620 (defun org-rewrite-old-row-references (s)
9621 (if (string-match "&[-+0-9I]" s)
9622 (error "Formula contains old &row reference, please rewrite using @-syntax")
9625 (defun org-table-make-reference (elements keep-empty numbers lispp)
9626 "Convert list ELEMENTS to something appropriate to insert into formula.
9627 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
9628 NUMBERS indicates that everything should be converted to numbers.
9629 LISPP means to return something appropriate for a Lisp list."
9630 (if (stringp elements) ; just a single val
9631 (if lispp
9632 (if (eq lispp 'literal)
9633 elements
9634 (prin1-to-string (if numbers (string-to-number elements) elements)))
9635 (if (equal elements "") (setq elements "0"))
9636 (if numbers (number-to-string (string-to-number elements)) elements))
9637 (unless keep-empty
9638 (setq elements
9639 (delq nil
9640 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
9641 elements))))
9642 (setq elements (or elements '("0")))
9643 (if lispp
9644 (mapconcat
9645 (lambda (x)
9646 (if (eq lispp 'literal)
9648 (prin1-to-string (if numbers (string-to-number x) x))))
9649 elements " ")
9650 (concat "[" (mapconcat
9651 (lambda (x)
9652 (if numbers (number-to-string (string-to-number x)) x))
9653 elements
9654 ",") "]"))))
9656 (defun org-table-recalculate (&optional all noalign)
9657 "Recalculate the current table line by applying all stored formulas.
9658 With prefix arg ALL, do this for all lines in the table."
9659 (interactive "P")
9660 (or (memq this-command org-recalc-commands)
9661 (setq org-recalc-commands (cons this-command org-recalc-commands)))
9662 (unless (org-at-table-p) (error "Not at a table"))
9663 (if (equal all '(16))
9664 (org-table-iterate)
9665 (org-table-get-specials)
9666 (let* ((eqlist (sort (org-table-get-stored-formulas)
9667 (lambda (a b) (string< (car a) (car b)))))
9668 (inhibit-redisplay (not debug-on-error))
9669 (line-re org-table-dataline-regexp)
9670 (thisline (org-current-line))
9671 (thiscol (org-table-current-column))
9672 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
9673 ;; Insert constants in all formulas
9674 (setq eqlist
9675 (mapcar (lambda (x)
9676 (setcdr x (org-table-formula-substitute-names (cdr x)))
9678 eqlist))
9679 ;; Split the equation list
9680 (while (setq eq (pop eqlist))
9681 (if (<= (string-to-char (car eq)) ?9)
9682 (push eq eqlnum)
9683 (push eq eqlname)))
9684 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
9685 (if all
9686 (progn
9687 (setq end (move-marker (make-marker) (1+ (org-table-end))))
9688 (goto-char (setq beg (org-table-begin)))
9689 (if (re-search-forward org-table-calculate-mark-regexp end t)
9690 ;; This is a table with marked lines, compute selected lines
9691 (setq line-re org-table-recalculate-regexp)
9692 ;; Move forward to the first non-header line
9693 (if (and (re-search-forward org-table-dataline-regexp end t)
9694 (re-search-forward org-table-hline-regexp end t)
9695 (re-search-forward org-table-dataline-regexp end t))
9696 (setq beg (match-beginning 0))
9697 nil))) ;; just leave beg where it is
9698 (setq beg (point-at-bol)
9699 end (move-marker (make-marker) (1+ (point-at-eol)))))
9700 (goto-char beg)
9701 (and all (message "Re-applying formulas to full table..."))
9703 ;; First find the named fields, and mark them untouchanble
9704 (remove-text-properties beg end '(org-untouchable t))
9705 (while (setq eq (pop eqlname))
9706 (setq name (car eq)
9707 a (assoc name org-table-named-field-locations))
9708 (and (not a)
9709 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
9710 (setq a (list name
9711 (aref org-table-dlines
9712 (string-to-number (match-string 1 name)))
9713 (string-to-number (match-string 2 name)))))
9714 (when (and a (or all (equal (nth 1 a) thisline)))
9715 (message "Re-applying formula to field: %s" name)
9716 (goto-line (nth 1 a))
9717 (org-table-goto-column (nth 2 a))
9718 (push (append a (list (cdr eq))) eqlname1)
9719 (org-table-put-field-property :org-untouchable t)))
9721 ;; Now evauluate the column formulas, but skip fields covered by
9722 ;; field formulas
9723 (goto-char beg)
9724 (while (re-search-forward line-re end t)
9725 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
9726 ;; Unprotected line, recalculate
9727 (and all (message "Re-applying formulas to full table...(line %d)"
9728 (setq cnt (1+ cnt))))
9729 (setq org-last-recalc-line (org-current-line))
9730 (setq eql eqlnum)
9731 (while (setq entry (pop eql))
9732 (goto-line org-last-recalc-line)
9733 (org-table-goto-column (string-to-number (car entry)) nil 'force)
9734 (unless (get-text-property (point) :org-untouchable)
9735 (org-table-eval-formula nil (cdr entry)
9736 'noalign 'nocst 'nostore 'noanalysis)))))
9738 ;; Now evaluate the field formulas
9739 (while (setq eq (pop eqlname1))
9740 (message "Re-applying formula to field: %s" (car eq))
9741 (goto-line (nth 1 eq))
9742 (org-table-goto-column (nth 2 eq))
9743 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
9744 'nostore 'noanalysis))
9746 (goto-line thisline)
9747 (org-table-goto-column thiscol)
9748 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
9749 (or noalign (and org-table-may-need-update (org-table-align))
9750 (and all (message "Re-applying formulas to %d lines...done" cnt)))
9752 ;; back to initial position
9753 (message "Re-applying formulas...done")
9754 (goto-line thisline)
9755 (org-table-goto-column thiscol)
9756 (or noalign (and org-table-may-need-update (org-table-align))
9757 (and all (message "Re-applying formulas...done"))))))
9759 (defun org-table-iterate (&optional arg)
9760 "Recalculate the table until it does not change anymore."
9761 (interactive "P")
9762 (let ((imax (if arg (prefix-numeric-value arg) 10))
9763 (i 0)
9764 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
9765 thistbl)
9766 (catch 'exit
9767 (while (< i imax)
9768 (setq i (1+ i))
9769 (org-table-recalculate 'all)
9770 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
9771 (if (not (string= lasttbl thistbl))
9772 (setq lasttbl thistbl)
9773 (if (> i 1)
9774 (message "Convergence after %d iterations" i)
9775 (message "Table was already stable"))
9776 (throw 'exit t)))
9777 (error "No convergence after %d iterations" i))))
9779 (defun org-table-formula-substitute-names (f)
9780 "Replace $const with values in string F."
9781 (message "form %s" f) (sit-for 1)
9782 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
9783 ;; First, check for column names
9784 (while (setq start (string-match org-table-column-name-regexp f start))
9785 (setq start (1+ start))
9786 (setq a (assoc (match-string 1 f) org-table-column-names))
9787 (setq f (replace-match (concat "$" (cdr a)) t t f)))
9788 ;; Parameters and constants
9789 (setq start 0)
9790 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
9791 (setq start (1+ start))
9792 (if (setq a (save-match-data
9793 (org-table-get-constant (match-string 1 f))))
9794 (setq f (replace-match
9795 (concat (if pp "(") a (if pp ")")) t t f))))
9796 (if org-table-formula-debug
9797 (put-text-property 0 (length f) :orig-formula f1 f))
9800 (defun org-table-get-constant (const)
9801 "Find the value for a parameter or constant in a formula.
9802 Parameters get priority."
9803 (or (cdr (assoc const org-table-local-parameters))
9804 (cdr (assoc const org-table-formula-constants-local))
9805 (cdr (assoc const org-table-formula-constants))
9806 (and (fboundp 'constants-get) (constants-get const))
9807 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
9808 (org-entry-get nil (substring const 5) 'inherit))
9809 "#UNDEFINED_NAME"))
9811 (defvar org-table-fedit-map
9812 (let ((map (make-sparse-keymap)))
9813 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
9814 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
9815 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
9816 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
9817 (org-defkey map "\C-c?" 'org-table-show-reference)
9818 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
9819 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
9820 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
9821 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
9822 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
9823 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
9824 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
9825 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
9826 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
9827 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
9828 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
9829 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
9830 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
9831 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
9832 map))
9834 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
9835 '("Edit-Formulas"
9836 ["Finish and Install" org-table-fedit-finish t]
9837 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
9838 ["Abort" org-table-fedit-abort t]
9839 "--"
9840 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
9841 ["Complete Lisp Symbol" lisp-complete-symbol t]
9842 "--"
9843 "Shift Reference at Point"
9844 ["Up" org-table-fedit-ref-up t]
9845 ["Down" org-table-fedit-ref-down t]
9846 ["Left" org-table-fedit-ref-left t]
9847 ["Right" org-table-fedit-ref-right t]
9849 "Change Test Row for Column Formulas"
9850 ["Up" org-table-fedit-line-up t]
9851 ["Down" org-table-fedit-line-down t]
9852 "--"
9853 ["Scroll Table Window" org-table-fedit-scroll t]
9854 ["Scroll Table Window down" org-table-fedit-scroll-down t]
9855 ["Show Table Grid" org-table-fedit-toggle-coordinates
9856 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
9857 org-table-overlay-coordinates)]
9858 "--"
9859 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
9860 :style toggle :selected org-table-buffer-is-an]))
9862 (defvar org-pos)
9864 (defun org-table-edit-formulas ()
9865 "Edit the formulas of the current table in a separate buffer."
9866 (interactive)
9867 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
9868 (beginning-of-line 0))
9869 (unless (org-at-table-p) (error "Not at a table"))
9870 (org-table-get-specials)
9871 (let ((key (org-table-current-field-formula 'key 'noerror))
9872 (eql (sort (org-table-get-stored-formulas 'noerror)
9873 'org-table-formula-less-p))
9874 (pos (move-marker (make-marker) (point)))
9875 (startline 1)
9876 (wc (current-window-configuration))
9877 (titles '((column . "# Column Formulas\n")
9878 (field . "# Field Formulas\n")
9879 (named . "# Named Field Formulas\n")))
9880 entry s type title)
9881 (org-switch-to-buffer-other-window "*Edit Formulas*")
9882 (erase-buffer)
9883 ;; Keep global-font-lock-mode from turning on font-lock-mode
9884 (let ((font-lock-global-modes '(not fundamental-mode)))
9885 (fundamental-mode))
9886 (org-set-local 'font-lock-global-modes (list 'not major-mode))
9887 (org-set-local 'org-pos pos)
9888 (org-set-local 'org-window-configuration wc)
9889 (use-local-map org-table-fedit-map)
9890 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
9891 (easy-menu-add org-table-fedit-menu)
9892 (setq startline (org-current-line))
9893 (while (setq entry (pop eql))
9894 (setq type (cond
9895 ((equal (string-to-char (car entry)) ?@) 'field)
9896 ((string-match "^[0-9]" (car entry)) 'column)
9897 (t 'named)))
9898 (when (setq title (assq type titles))
9899 (or (bobp) (insert "\n"))
9900 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
9901 (setq titles (delq title titles)))
9902 (if (equal key (car entry)) (setq startline (org-current-line)))
9903 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
9904 (car entry) " = " (cdr entry) "\n"))
9905 (remove-text-properties 0 (length s) '(face nil) s)
9906 (insert s))
9907 (if (eq org-table-use-standard-references t)
9908 (org-table-fedit-toggle-ref-type))
9909 (goto-line startline)
9910 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
9912 (defun org-table-fedit-post-command ()
9913 (when (not (memq this-command '(lisp-complete-symbol)))
9914 (let ((win (selected-window)))
9915 (save-excursion
9916 (condition-case nil
9917 (org-table-show-reference)
9918 (error nil))
9919 (select-window win)))))
9921 (defun org-table-formula-to-user (s)
9922 "Convert a formula from internal to user representation."
9923 (if (eq org-table-use-standard-references t)
9924 (org-table-convert-refs-to-an s)
9927 (defun org-table-formula-from-user (s)
9928 "Convert a formula from user to internal representation."
9929 (if org-table-use-standard-references
9930 (org-table-convert-refs-to-rc s)
9933 (defun org-table-convert-refs-to-rc (s)
9934 "Convert spreadsheet references from AB7 to @7$28.
9935 Works for single references, but also for entire formulas and even the
9936 full TBLFM line."
9937 (let ((start 0))
9938 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
9939 (cond
9940 ((match-end 3)
9941 ;; format match, just advance
9942 (setq start (match-end 0)))
9943 ((and (> (match-beginning 0) 0)
9944 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
9945 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
9946 ;; 3.e5 or something like this.
9947 (setq start (match-end 0)))
9949 (setq start (match-beginning 0)
9950 s (replace-match
9951 (if (equal (match-string 2 s) "&")
9952 (format "$%d" (org-letters-to-number (match-string 1 s)))
9953 (format "@%d$%d"
9954 (string-to-number (match-string 2 s))
9955 (org-letters-to-number (match-string 1 s))))
9956 t t s)))))
9959 (defun org-table-convert-refs-to-an (s)
9960 "Convert spreadsheet references from to @7$28 to AB7.
9961 Works for single references, but also for entire formulas and even the
9962 full TBLFM line."
9963 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
9964 (setq s (replace-match
9965 (format "%s%d"
9966 (org-number-to-letters
9967 (string-to-number (match-string 2 s)))
9968 (string-to-number (match-string 1 s)))
9969 t t s)))
9970 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
9971 (setq s (replace-match (concat "\\1"
9972 (org-number-to-letters
9973 (string-to-number (match-string 2 s))) "&")
9974 t nil s)))
9977 (defun org-letters-to-number (s)
9978 "Convert a base 26 number represented by letters into an integer.
9979 For example: AB -> 28."
9980 (let ((n 0))
9981 (setq s (upcase s))
9982 (while (> (length s) 0)
9983 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
9984 s (substring s 1)))
9987 (defun org-number-to-letters (n)
9988 "Convert an integer into a base 26 number represented by letters.
9989 For example: 28 -> AB."
9990 (let ((s ""))
9991 (while (> n 0)
9992 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
9993 n (/ (1- n) 26)))
9996 (defun org-table-fedit-convert-buffer (function)
9997 "Convert all references in this buffer, using FUNTION."
9998 (let ((line (org-current-line)))
9999 (goto-char (point-min))
10000 (while (not (eobp))
10001 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10002 (delete-region (point) (point-at-eol))
10003 (or (eobp) (forward-char 1)))
10004 (goto-line line)))
10006 (defun org-table-fedit-toggle-ref-type ()
10007 "Convert all references in the buffer from B3 to @3$2 and back."
10008 (interactive)
10009 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10010 (org-table-fedit-convert-buffer
10011 (if org-table-buffer-is-an
10012 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10013 (message "Reference type switched to %s"
10014 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10016 (defun org-table-fedit-ref-up ()
10017 "Shift the reference at point one row/hline up."
10018 (interactive)
10019 (org-table-fedit-shift-reference 'up))
10020 (defun org-table-fedit-ref-down ()
10021 "Shift the reference at point one row/hline down."
10022 (interactive)
10023 (org-table-fedit-shift-reference 'down))
10024 (defun org-table-fedit-ref-left ()
10025 "Shift the reference at point one field to the left."
10026 (interactive)
10027 (org-table-fedit-shift-reference 'left))
10028 (defun org-table-fedit-ref-right ()
10029 "Shift the reference at point one field to the right."
10030 (interactive)
10031 (org-table-fedit-shift-reference 'right))
10033 (defun org-table-fedit-shift-reference (dir)
10034 (cond
10035 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10036 (if (memq dir '(left right))
10037 (org-rematch-and-replace 1 (eq dir 'left))
10038 (error "Cannot shift reference in this direction")))
10039 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10040 ;; A B3-like reference
10041 (if (memq dir '(up down))
10042 (org-rematch-and-replace 2 (eq dir 'up))
10043 (org-rematch-and-replace 1 (eq dir 'left))))
10044 ((org-at-regexp-p
10045 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10046 ;; An internal reference
10047 (if (memq dir '(up down))
10048 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10049 (org-rematch-and-replace 5 (eq dir 'left))))))
10051 (defun org-rematch-and-replace (n &optional decr hline)
10052 "Re-match the group N, and replace it with the shifted refrence."
10053 (or (match-end n) (error "Cannot shift reference in this direction"))
10054 (goto-char (match-beginning n))
10055 (and (looking-at (regexp-quote (match-string n)))
10056 (replace-match (org-shift-refpart (match-string 0) decr hline)
10057 t t)))
10059 (defun org-shift-refpart (ref &optional decr hline)
10060 "Shift a refrence part REF.
10061 If DECR is set, decrease the references row/column, else increase.
10062 If HLINE is set, this may be a hline reference, it certainly is not
10063 a translation reference."
10064 (save-match-data
10065 (let* ((sign (string-match "^[-+]" ref)) n)
10067 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10068 (cond
10069 ((and hline (string-match "^I+" ref))
10070 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10071 (setq n (+ n (if decr -1 1)))
10072 (if (= n 0) (setq n (+ n (if decr -1 1))))
10073 (if sign
10074 (setq sign (if (< n 0) "-" "+") n (abs n))
10075 (setq n (max 1 n)))
10076 (concat sign (make-string n ?I)))
10078 ((string-match "^[0-9]+" ref)
10079 (setq n (string-to-number (concat sign ref)))
10080 (setq n (+ n (if decr -1 1)))
10081 (if sign
10082 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10083 (number-to-string (max 1 n))))
10085 ((string-match "^[a-zA-Z]+" ref)
10086 (org-number-to-letters
10087 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10089 (t (error "Cannot shift reference"))))))
10091 (defun org-table-fedit-toggle-coordinates ()
10092 "Toggle the display of coordinates in the refrenced table."
10093 (interactive)
10094 (let ((pos (marker-position org-pos)))
10095 (with-current-buffer (marker-buffer org-pos)
10096 (save-excursion
10097 (goto-char pos)
10098 (org-table-toggle-coordinate-overlays)))))
10100 (defun org-table-fedit-finish (&optional arg)
10101 "Parse the buffer for formula definitions and install them.
10102 With prefix ARG, apply the new formulas to the table."
10103 (interactive "P")
10104 (org-table-remove-rectangle-highlight)
10105 (if org-table-use-standard-references
10106 (progn
10107 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
10108 (setq org-table-buffer-is-an nil)))
10109 (let ((pos org-pos) eql var form)
10110 (goto-char (point-min))
10111 (while (re-search-forward
10112 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
10113 nil t)
10114 (setq var (if (match-end 2) (match-string 2) (match-string 1))
10115 form (match-string 3))
10116 (setq form (org-trim form))
10117 (when (not (equal form ""))
10118 (while (string-match "[ \t]*\n[ \t]*" form)
10119 (setq form (replace-match " " t t form)))
10120 (when (assoc var eql)
10121 (error "Double formulas for %s" var))
10122 (push (cons var form) eql)))
10123 (setq org-pos nil)
10124 (set-window-configuration org-window-configuration)
10125 (select-window (get-buffer-window (marker-buffer pos)))
10126 (goto-char pos)
10127 (unless (org-at-table-p)
10128 (error "Lost table position - cannot install formulae"))
10129 (org-table-store-formulas eql)
10130 (move-marker pos nil)
10131 (kill-buffer "*Edit Formulas*")
10132 (if arg
10133 (org-table-recalculate 'all)
10134 (message "New formulas installed - press C-u C-c C-c to apply."))))
10136 (defun org-table-fedit-abort ()
10137 "Abort editing formulas, without installing the changes."
10138 (interactive)
10139 (org-table-remove-rectangle-highlight)
10140 (let ((pos org-pos))
10141 (set-window-configuration org-window-configuration)
10142 (select-window (get-buffer-window (marker-buffer pos)))
10143 (goto-char pos)
10144 (move-marker pos nil)
10145 (message "Formula editing aborted without installing changes")))
10147 (defun org-table-fedit-lisp-indent ()
10148 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
10149 (interactive)
10150 (let ((pos (point)) beg end ind)
10151 (beginning-of-line 1)
10152 (cond
10153 ((looking-at "[ \t]")
10154 (goto-char pos)
10155 (call-interactively 'lisp-indent-line))
10156 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
10157 ((not (fboundp 'pp-buffer))
10158 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
10159 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
10160 (goto-char (- (match-end 0) 2))
10161 (setq beg (point))
10162 (setq ind (make-string (current-column) ?\ ))
10163 (condition-case nil (forward-sexp 1)
10164 (error
10165 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
10166 (setq end (point))
10167 (save-restriction
10168 (narrow-to-region beg end)
10169 (if (eq last-command this-command)
10170 (progn
10171 (goto-char (point-min))
10172 (setq this-command nil)
10173 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
10174 (replace-match " ")))
10175 (pp-buffer)
10176 (untabify (point-min) (point-max))
10177 (goto-char (1+ (point-min)))
10178 (while (re-search-forward "^." nil t)
10179 (beginning-of-line 1)
10180 (insert ind))
10181 (goto-char (point-max))
10182 (backward-delete-char 1)))
10183 (goto-char beg))
10184 (t nil))))
10186 (defvar org-show-positions nil)
10188 (defun org-table-show-reference (&optional local)
10189 "Show the location/value of the $ expression at point."
10190 (interactive)
10191 (org-table-remove-rectangle-highlight)
10192 (catch 'exit
10193 (let ((pos (if local (point) org-pos))
10194 (face2 'highlight)
10195 (org-inhibit-highlight-removal t)
10196 (win (selected-window))
10197 (org-show-positions nil)
10198 var name e what match dest)
10199 (if local (org-table-get-specials))
10200 (setq what (cond
10201 ((or (org-at-regexp-p org-table-range-regexp2)
10202 (org-at-regexp-p org-table-translate-regexp)
10203 (org-at-regexp-p org-table-range-regexp))
10204 (setq match
10205 (save-match-data
10206 (org-table-convert-refs-to-rc (match-string 0))))
10207 'range)
10208 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
10209 ((org-at-regexp-p "\\$[0-9]+") 'column)
10210 ((not local) nil)
10211 (t (error "No reference at point")))
10212 match (and what (or match (match-string 0))))
10213 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
10214 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
10215 'secondary-selection))
10216 (org-add-hook 'before-change-functions
10217 'org-table-remove-rectangle-highlight)
10218 (if (eq what 'name) (setq var (substring match 1)))
10219 (when (eq what 'range)
10220 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
10221 (setq match (org-table-formula-substitute-names match)))
10222 (unless local
10223 (save-excursion
10224 (end-of-line 1)
10225 (re-search-backward "^\\S-" nil t)
10226 (beginning-of-line 1)
10227 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
10228 (setq dest
10229 (save-match-data
10230 (org-table-convert-refs-to-rc (match-string 1))))
10231 (org-table-add-rectangle-overlay
10232 (match-beginning 1) (match-end 1) face2))))
10233 (if (and (markerp pos) (marker-buffer pos))
10234 (if (get-buffer-window (marker-buffer pos))
10235 (select-window (get-buffer-window (marker-buffer pos)))
10236 (org-switch-to-buffer-other-window (get-buffer-window
10237 (marker-buffer pos)))))
10238 (goto-char pos)
10239 (org-table-force-dataline)
10240 (when dest
10241 (setq name (substring dest 1))
10242 (cond
10243 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
10244 (setq e (assoc name org-table-named-field-locations))
10245 (goto-line (nth 1 e))
10246 (org-table-goto-column (nth 2 e)))
10247 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
10248 (let ((l (string-to-number (match-string 1 dest)))
10249 (c (string-to-number (match-string 2 dest))))
10250 (goto-line (aref org-table-dlines l))
10251 (org-table-goto-column c)))
10252 (t (org-table-goto-column (string-to-number name))))
10253 (move-marker pos (point))
10254 (org-table-highlight-rectangle nil nil face2))
10255 (cond
10256 ((equal dest match))
10257 ((not match))
10258 ((eq what 'range)
10259 (condition-case nil
10260 (save-excursion
10261 (org-table-get-range match nil nil 'highlight))
10262 (error nil)))
10263 ((setq e (assoc var org-table-named-field-locations))
10264 (goto-line (nth 1 e))
10265 (org-table-goto-column (nth 2 e))
10266 (org-table-highlight-rectangle (point) (point))
10267 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
10268 ((setq e (assoc var org-table-column-names))
10269 (org-table-goto-column (string-to-number (cdr e)))
10270 (org-table-highlight-rectangle (point) (point))
10271 (goto-char (org-table-begin))
10272 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
10273 (org-table-end) t)
10274 (progn
10275 (goto-char (match-beginning 1))
10276 (org-table-highlight-rectangle)
10277 (message "Named column (column %s)" (cdr e)))
10278 (error "Column name not found")))
10279 ((eq what 'column)
10280 ;; column number
10281 (org-table-goto-column (string-to-number (substring match 1)))
10282 (org-table-highlight-rectangle (point) (point))
10283 (message "Column %s" (substring match 1)))
10284 ((setq e (assoc var org-table-local-parameters))
10285 (goto-char (org-table-begin))
10286 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
10287 (progn
10288 (goto-char (match-beginning 1))
10289 (org-table-highlight-rectangle)
10290 (message "Local parameter."))
10291 (error "Parameter not found")))
10293 (cond
10294 ((not var) (error "No reference at point"))
10295 ((setq e (assoc var org-table-formula-constants-local))
10296 (message "Local Constant: $%s=%s in #+CONSTANTS line."
10297 var (cdr e)))
10298 ((setq e (assoc var org-table-formula-constants))
10299 (message "Constant: $%s=%s in `org-table-formula-constants'."
10300 var (cdr e)))
10301 ((setq e (and (fboundp 'constants-get) (constants-get var)))
10302 (message "Constant: $%s=%s, from `constants.el'%s."
10303 var e (format " (%s units)" constants-unit-system)))
10304 (t (error "Undefined name $%s" var)))))
10305 (goto-char pos)
10306 (when (and org-show-positions
10307 (not (memq this-command '(org-table-fedit-scroll
10308 org-table-fedit-scroll-down))))
10309 (push pos org-show-positions)
10310 (push org-table-current-begin-pos org-show-positions)
10311 (let ((min (apply 'min org-show-positions))
10312 (max (apply 'max org-show-positions)))
10313 (goto-char min) (recenter 0)
10314 (goto-char max)
10315 (or (pos-visible-in-window-p max) (recenter -1))))
10316 (select-window win))))
10318 (defun org-table-force-dataline ()
10319 "Make sure the cursor is in a dataline in a table."
10320 (unless (save-excursion
10321 (beginning-of-line 1)
10322 (looking-at org-table-dataline-regexp))
10323 (let* ((re org-table-dataline-regexp)
10324 (p1 (save-excursion (re-search-forward re nil 'move)))
10325 (p2 (save-excursion (re-search-backward re nil 'move))))
10326 (cond ((and p1 p2)
10327 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
10328 p1 p2)))
10329 ((or p1 p2) (goto-char (or p1 p2)))
10330 (t (error "No table dataline around here"))))))
10332 (defun org-table-fedit-line-up ()
10333 "Move cursor one line up in the window showing the table."
10334 (interactive)
10335 (org-table-fedit-move 'previous-line))
10337 (defun org-table-fedit-line-down ()
10338 "Move cursor one line down in the window showing the table."
10339 (interactive)
10340 (org-table-fedit-move 'next-line))
10342 (defun org-table-fedit-move (command)
10343 "Move the cursor in the window shoinw the table.
10344 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
10345 (let ((org-table-allow-automatic-line-recalculation nil)
10346 (pos org-pos) (win (selected-window)) p)
10347 (select-window (get-buffer-window (marker-buffer org-pos)))
10348 (setq p (point))
10349 (call-interactively command)
10350 (while (and (org-at-table-p)
10351 (org-at-table-hline-p))
10352 (call-interactively command))
10353 (or (org-at-table-p) (goto-char p))
10354 (move-marker pos (point))
10355 (select-window win)))
10357 (defun org-table-fedit-scroll (N)
10358 (interactive "p")
10359 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
10360 (scroll-other-window N)))
10362 (defun org-table-fedit-scroll-down (N)
10363 (interactive "p")
10364 (org-table-fedit-scroll (- N)))
10366 (defvar org-table-rectangle-overlays nil)
10368 (defun org-table-add-rectangle-overlay (beg end &optional face)
10369 "Add a new overlay."
10370 (let ((ov (org-make-overlay beg end)))
10371 (org-overlay-put ov 'face (or face 'secondary-selection))
10372 (push ov org-table-rectangle-overlays)))
10374 (defun org-table-highlight-rectangle (&optional beg end face)
10375 "Highlight rectangular region in a table."
10376 (setq beg (or beg (point)) end (or end (point)))
10377 (let ((b (min beg end))
10378 (e (max beg end))
10379 l1 c1 l2 c2 tmp)
10380 (and (boundp 'org-show-positions)
10381 (setq org-show-positions (cons b (cons e org-show-positions))))
10382 (goto-char (min beg end))
10383 (setq l1 (org-current-line)
10384 c1 (org-table-current-column))
10385 (goto-char (max beg end))
10386 (setq l2 (org-current-line)
10387 c2 (org-table-current-column))
10388 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
10389 (goto-line l1)
10390 (beginning-of-line 1)
10391 (loop for line from l1 to l2 do
10392 (when (looking-at org-table-dataline-regexp)
10393 (org-table-goto-column c1)
10394 (skip-chars-backward "^|\n") (setq beg (point))
10395 (org-table-goto-column c2)
10396 (skip-chars-forward "^|\n") (setq end (point))
10397 (org-table-add-rectangle-overlay beg end face))
10398 (beginning-of-line 2))
10399 (goto-char b))
10400 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
10402 (defun org-table-remove-rectangle-highlight (&rest ignore)
10403 "Remove the rectangle overlays."
10404 (unless org-inhibit-highlight-removal
10405 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
10406 (mapc 'org-delete-overlay org-table-rectangle-overlays)
10407 (setq org-table-rectangle-overlays nil)))
10409 (defvar org-table-coordinate-overlays nil
10410 "Collects the cooordinate grid overlays, so that they can be removed.")
10411 (make-variable-buffer-local 'org-table-coordinate-overlays)
10413 (defun org-table-overlay-coordinates ()
10414 "Add overlays to the table at point, to show row/column coordinates."
10415 (interactive)
10416 (mapc 'org-delete-overlay org-table-coordinate-overlays)
10417 (setq org-table-coordinate-overlays nil)
10418 (save-excursion
10419 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
10420 (goto-char (org-table-begin))
10421 (while (org-at-table-p)
10422 (setq eol (point-at-eol))
10423 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
10424 (push ov org-table-coordinate-overlays)
10425 (setq hline (looking-at org-table-hline-regexp))
10426 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
10427 (format "%4d" (setq id (1+ id)))))
10428 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
10429 (when hline
10430 (setq ic 0)
10431 (while (re-search-forward "[+|]\\(-+\\)" eol t)
10432 (setq beg (1+ (match-beginning 0))
10433 ic (1+ ic)
10434 s1 (concat "$" (int-to-string ic))
10435 s2 (org-number-to-letters ic)
10436 str (if (eq org-table-use-standard-references t) s2 s1))
10437 (setq ov (org-make-overlay beg (+ beg (length str))))
10438 (push ov org-table-coordinate-overlays)
10439 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
10440 (beginning-of-line 2)))))
10442 (defun org-table-toggle-coordinate-overlays ()
10443 "Toggle the display of Row/Column numbers in tables."
10444 (interactive)
10445 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
10446 (message "Row/Column number display turned %s"
10447 (if org-table-overlay-coordinates "on" "off"))
10448 (if (and (org-at-table-p) org-table-overlay-coordinates)
10449 (org-table-align))
10450 (unless org-table-overlay-coordinates
10451 (mapc 'org-delete-overlay org-table-coordinate-overlays)
10452 (setq org-table-coordinate-overlays nil)))
10454 (defun org-table-toggle-formula-debugger ()
10455 "Toggle the formula debugger in tables."
10456 (interactive)
10457 (setq org-table-formula-debug (not org-table-formula-debug))
10458 (message "Formula debugging has been turned %s"
10459 (if org-table-formula-debug "on" "off")))
10461 ;;; The orgtbl minor mode
10463 ;; Define a minor mode which can be used in other modes in order to
10464 ;; integrate the org-mode table editor.
10466 ;; This is really a hack, because the org-mode table editor uses several
10467 ;; keys which normally belong to the major mode, for example the TAB and
10468 ;; RET keys. Here is how it works: The minor mode defines all the keys
10469 ;; necessary to operate the table editor, but wraps the commands into a
10470 ;; function which tests if the cursor is currently inside a table. If that
10471 ;; is the case, the table editor command is executed. However, when any of
10472 ;; those keys is used outside a table, the function uses `key-binding' to
10473 ;; look up if the key has an associated command in another currently active
10474 ;; keymap (minor modes, major mode, global), and executes that command.
10475 ;; There might be problems if any of the keys used by the table editor is
10476 ;; otherwise used as a prefix key.
10478 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
10479 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
10480 ;; addresses this by checking explicitly for both bindings.
10482 ;; The optimized version (see variable `orgtbl-optimized') takes over
10483 ;; all keys which are bound to `self-insert-command' in the *global map*.
10484 ;; Some modes bind other commands to simple characters, for example
10485 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
10486 ;; active, this binding is ignored inside tables and replaced with a
10487 ;; modified self-insert.
10489 (defvar orgtbl-mode nil
10490 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
10491 table editor in arbitrary modes.")
10492 (make-variable-buffer-local 'orgtbl-mode)
10494 (defvar orgtbl-mode-map (make-keymap)
10495 "Keymap for `orgtbl-mode'.")
10497 ;;;###autoload
10498 (defun turn-on-orgtbl ()
10499 "Unconditionally turn on `orgtbl-mode'."
10500 (orgtbl-mode 1))
10502 (defvar org-old-auto-fill-inhibit-regexp nil
10503 "Local variable used by `orgtbl-mode'")
10505 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
10506 "Matches a line belonging to an orgtbl.")
10508 (defconst orgtbl-extra-font-lock-keywords
10509 (list (list (concat "^" orgtbl-line-start-regexp ".*")
10510 0 (quote 'org-table) 'prepend))
10511 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
10513 ;;;###autoload
10514 (defun orgtbl-mode (&optional arg)
10515 "The `org-mode' table editor as a minor mode for use in other modes."
10516 (interactive)
10517 (if (org-mode-p)
10518 ;; Exit without error, in case some hook functions calls this
10519 ;; by accident in org-mode.
10520 (message "Orgtbl-mode is not useful in org-mode, command ignored")
10521 (setq orgtbl-mode
10522 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
10523 (if orgtbl-mode
10524 (progn
10525 (and (orgtbl-setup) (defun orgtbl-setup () nil))
10526 ;; Make sure we are first in minor-mode-map-alist
10527 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
10528 (and c (setq minor-mode-map-alist
10529 (cons c (delq c minor-mode-map-alist)))))
10530 (org-set-local (quote org-table-may-need-update) t)
10531 (org-add-hook 'before-change-functions 'org-before-change-function
10532 nil 'local)
10533 (org-set-local 'org-old-auto-fill-inhibit-regexp
10534 auto-fill-inhibit-regexp)
10535 (org-set-local 'auto-fill-inhibit-regexp
10536 (if auto-fill-inhibit-regexp
10537 (concat orgtbl-line-start-regexp "\\|"
10538 auto-fill-inhibit-regexp)
10539 orgtbl-line-start-regexp))
10540 (org-add-to-invisibility-spec '(org-cwidth))
10541 (when (fboundp 'font-lock-add-keywords)
10542 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
10543 (org-restart-font-lock))
10544 (easy-menu-add orgtbl-mode-menu)
10545 (run-hooks 'orgtbl-mode-hook))
10546 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
10547 (org-cleanup-narrow-column-properties)
10548 (org-remove-from-invisibility-spec '(org-cwidth))
10549 (remove-hook 'before-change-functions 'org-before-change-function t)
10550 (when (fboundp 'font-lock-remove-keywords)
10551 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
10552 (org-restart-font-lock))
10553 (easy-menu-remove orgtbl-mode-menu)
10554 (force-mode-line-update 'all))))
10556 (defun org-cleanup-narrow-column-properties ()
10557 "Remove all properties related to narrow-column invisibility."
10558 (let ((s 1))
10559 (while (setq s (text-property-any s (point-max)
10560 'display org-narrow-column-arrow))
10561 (remove-text-properties s (1+ s) '(display t)))
10562 (setq s 1)
10563 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
10564 (remove-text-properties s (1+ s) '(org-cwidth t)))
10565 (setq s 1)
10566 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
10567 (remove-text-properties s (1+ s) '(invisible t)))))
10569 ;; Install it as a minor mode.
10570 (put 'orgtbl-mode :included t)
10571 (put 'orgtbl-mode :menu-tag "Org Table Mode")
10572 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
10574 (defun orgtbl-make-binding (fun n &rest keys)
10575 "Create a function for binding in the table minor mode.
10576 FUN is the command to call inside a table. N is used to create a unique
10577 command name. KEYS are keys that should be checked in for a command
10578 to execute outside of tables."
10579 (eval
10580 (list 'defun
10581 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
10582 '(arg)
10583 (concat "In tables, run `" (symbol-name fun) "'.\n"
10584 "Outside of tables, run the binding of `"
10585 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
10586 "'.")
10587 '(interactive "p")
10588 (list 'if
10589 '(org-at-table-p)
10590 (list 'call-interactively (list 'quote fun))
10591 (list 'let '(orgtbl-mode)
10592 (list 'call-interactively
10593 (append '(or)
10594 (mapcar (lambda (k)
10595 (list 'key-binding k))
10596 keys)
10597 '('orgtbl-error))))))))
10599 (defun orgtbl-error ()
10600 "Error when there is no default binding for a table key."
10601 (interactive)
10602 (error "This key is has no function outside tables"))
10604 (defun orgtbl-setup ()
10605 "Setup orgtbl keymaps."
10606 (let ((nfunc 0)
10607 (bindings
10608 (list
10609 '([(meta shift left)] org-table-delete-column)
10610 '([(meta left)] org-table-move-column-left)
10611 '([(meta right)] org-table-move-column-right)
10612 '([(meta shift right)] org-table-insert-column)
10613 '([(meta shift up)] org-table-kill-row)
10614 '([(meta shift down)] org-table-insert-row)
10615 '([(meta up)] org-table-move-row-up)
10616 '([(meta down)] org-table-move-row-down)
10617 '("\C-c\C-w" org-table-cut-region)
10618 '("\C-c\M-w" org-table-copy-region)
10619 '("\C-c\C-y" org-table-paste-rectangle)
10620 '("\C-c-" org-table-insert-hline)
10621 '("\C-c}" org-table-toggle-coordinate-overlays)
10622 '("\C-c{" org-table-toggle-formula-debugger)
10623 '("\C-m" org-table-next-row)
10624 '([(shift return)] org-table-copy-down)
10625 '("\C-c\C-q" org-table-wrap-region)
10626 '("\C-c?" org-table-field-info)
10627 '("\C-c " org-table-blank-field)
10628 '("\C-c+" org-table-sum)
10629 '("\C-c=" org-table-eval-formula)
10630 '("\C-c'" org-table-edit-formulas)
10631 '("\C-c`" org-table-edit-field)
10632 '("\C-c*" org-table-recalculate)
10633 '("\C-c|" org-table-create-or-convert-from-region)
10634 '("\C-c^" org-table-sort-lines)
10635 '([(control ?#)] org-table-rotate-recalc-marks)))
10636 elt key fun cmd)
10637 (while (setq elt (pop bindings))
10638 (setq nfunc (1+ nfunc))
10639 (setq key (org-key (car elt))
10640 fun (nth 1 elt)
10641 cmd (orgtbl-make-binding fun nfunc key))
10642 (org-defkey orgtbl-mode-map key cmd))
10644 ;; Special treatment needed for TAB and RET
10645 (org-defkey orgtbl-mode-map [(return)]
10646 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
10647 (org-defkey orgtbl-mode-map "\C-m"
10648 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
10650 (org-defkey orgtbl-mode-map [(tab)]
10651 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
10652 (org-defkey orgtbl-mode-map "\C-i"
10653 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
10655 (org-defkey orgtbl-mode-map [(shift tab)]
10656 (orgtbl-make-binding 'org-table-previous-field 104
10657 [(shift tab)] [(tab)] "\C-i"))
10659 (org-defkey orgtbl-mode-map "\M-\C-m"
10660 (orgtbl-make-binding 'org-table-wrap-region 105
10661 "\M-\C-m" [(meta return)]))
10662 (org-defkey orgtbl-mode-map [(meta return)]
10663 (orgtbl-make-binding 'org-table-wrap-region 106
10664 [(meta return)] "\M-\C-m"))
10666 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
10667 (when orgtbl-optimized
10668 ;; If the user wants maximum table support, we need to hijack
10669 ;; some standard editing functions
10670 (org-remap orgtbl-mode-map
10671 'self-insert-command 'orgtbl-self-insert-command
10672 'delete-char 'org-delete-char
10673 'delete-backward-char 'org-delete-backward-char)
10674 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
10675 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
10676 '("OrgTbl"
10677 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
10678 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
10679 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
10680 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
10681 "--"
10682 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
10683 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
10684 ["Copy Field from Above"
10685 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
10686 "--"
10687 ("Column"
10688 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
10689 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
10690 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
10691 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
10692 ("Row"
10693 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
10694 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
10695 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
10696 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
10697 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
10698 "--"
10699 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
10700 ("Rectangle"
10701 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
10702 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
10703 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
10704 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
10705 "--"
10706 ("Radio tables"
10707 ["Insert table template" orgtbl-insert-radio-table
10708 (assq major-mode orgtbl-radio-table-templates)]
10709 ["Comment/uncomment table" orgtbl-toggle-comment t])
10710 "--"
10711 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
10712 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
10713 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
10714 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
10715 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
10716 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
10717 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
10718 ["Sum Column/Rectangle" org-table-sum
10719 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
10720 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
10721 ["Debug Formulas"
10722 org-table-toggle-formula-debugger :active (org-at-table-p)
10723 :keys "C-c {"
10724 :style toggle :selected org-table-formula-debug]
10725 ["Show Col/Row Numbers"
10726 org-table-toggle-coordinate-overlays :active (org-at-table-p)
10727 :keys "C-c }"
10728 :style toggle :selected org-table-overlay-coordinates]
10732 (defun orgtbl-ctrl-c-ctrl-c (arg)
10733 "If the cursor is inside a table, realign the table.
10734 It it is a table to be sent away to a receiver, do it.
10735 With prefix arg, also recompute table."
10736 (interactive "P")
10737 (let ((pos (point)) action)
10738 (save-excursion
10739 (beginning-of-line 1)
10740 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
10741 ((looking-at "[ \t]*|") pos)
10742 ((looking-at "#\\+TBLFM:") 'recalc))))
10743 (cond
10744 ((integerp action)
10745 (goto-char action)
10746 (org-table-maybe-eval-formula)
10747 (if arg
10748 (call-interactively 'org-table-recalculate)
10749 (org-table-maybe-recalculate-line))
10750 (call-interactively 'org-table-align)
10751 (orgtbl-send-table 'maybe))
10752 ((eq action 'recalc)
10753 (save-excursion
10754 (beginning-of-line 1)
10755 (skip-chars-backward " \r\n\t")
10756 (if (org-at-table-p)
10757 (org-call-with-arg 'org-table-recalculate t))))
10758 (t (let (orgtbl-mode)
10759 (call-interactively (key-binding "\C-c\C-c")))))))
10761 (defun orgtbl-tab (arg)
10762 "Justification and field motion for `orgtbl-mode'."
10763 (interactive "P")
10764 (if arg (org-table-edit-field t)
10765 (org-table-justify-field-maybe)
10766 (org-table-next-field)))
10768 (defun orgtbl-ret ()
10769 "Justification and field motion for `orgtbl-mode'."
10770 (interactive)
10771 (org-table-justify-field-maybe)
10772 (org-table-next-row))
10774 (defun orgtbl-self-insert-command (N)
10775 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
10776 If the cursor is in a table looking at whitespace, the whitespace is
10777 overwritten, and the table is not marked as requiring realignment."
10778 (interactive "p")
10779 (if (and (org-at-table-p)
10781 (and org-table-auto-blank-field
10782 (member last-command
10783 '(orgtbl-hijacker-command-100
10784 orgtbl-hijacker-command-101
10785 orgtbl-hijacker-command-102
10786 orgtbl-hijacker-command-103
10787 orgtbl-hijacker-command-104
10788 orgtbl-hijacker-command-105))
10789 (org-table-blank-field))
10791 (eq N 1)
10792 (looking-at "[^|\n]* +|"))
10793 (let (org-table-may-need-update)
10794 (goto-char (1- (match-end 0)))
10795 (delete-backward-char 1)
10796 (goto-char (match-beginning 0))
10797 (self-insert-command N))
10798 (setq org-table-may-need-update t)
10799 (let (orgtbl-mode)
10800 (call-interactively (key-binding (vector last-input-event))))))
10802 (defun org-force-self-insert (N)
10803 "Needed to enforce self-insert under remapping."
10804 (interactive "p")
10805 (self-insert-command N))
10807 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
10808 "Regula expression matching exponentials as produced by calc.")
10810 (defvar org-table-clean-did-remove-column nil)
10812 (defun orgtbl-export (table target)
10813 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
10814 (lines (org-split-string table "[ \t]*\n[ \t]*"))
10815 org-table-last-alignment org-table-last-column-widths
10816 maxcol column)
10817 (if (not (fboundp func))
10818 (error "Cannot export orgtbl table to %s" target))
10819 (setq lines (org-table-clean-before-export lines))
10820 (setq table
10821 (mapcar
10822 (lambda (x)
10823 (if (string-match org-table-hline-regexp x)
10824 'hline
10825 (org-split-string (org-trim x) "\\s-*|\\s-*")))
10826 lines))
10827 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
10828 table)))
10829 (loop for i from (1- maxcol) downto 0 do
10830 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
10831 (setq column (delq nil column))
10832 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
10833 (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))
10834 (funcall func table nil)))
10836 (defun orgtbl-send-table (&optional maybe)
10837 "Send a tranformed version of this table to the receiver position.
10838 With argument MAYBE, fail quietly if no transformation is defined for
10839 this table."
10840 (interactive)
10841 (catch 'exit
10842 (unless (org-at-table-p) (error "Not at a table"))
10843 ;; when non-interactive, we assume align has just happened.
10844 (when (interactive-p) (org-table-align))
10845 (save-excursion
10846 (goto-char (org-table-begin))
10847 (beginning-of-line 0)
10848 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
10849 (if maybe
10850 (throw 'exit nil)
10851 (error "Don't know how to transform this table."))))
10852 (let* ((name (match-string 1))
10854 (transform (intern (match-string 2)))
10855 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
10856 (skip (plist-get params :skip))
10857 (skipcols (plist-get params :skipcols))
10858 (txt (buffer-substring-no-properties
10859 (org-table-begin) (org-table-end)))
10860 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
10861 (lines (org-table-clean-before-export lines))
10862 (i0 (if org-table-clean-did-remove-column 2 1))
10863 (table (mapcar
10864 (lambda (x)
10865 (if (string-match org-table-hline-regexp x)
10866 'hline
10867 (org-remove-by-index
10868 (org-split-string (org-trim x) "\\s-*|\\s-*")
10869 skipcols i0)))
10870 lines))
10871 (fun (if (= i0 2) 'cdr 'identity))
10872 (org-table-last-alignment
10873 (org-remove-by-index (funcall fun org-table-last-alignment)
10874 skipcols i0))
10875 (org-table-last-column-widths
10876 (org-remove-by-index (funcall fun org-table-last-column-widths)
10877 skipcols i0)))
10879 (unless (fboundp transform)
10880 (error "No such transformation function %s" transform))
10881 (setq txt (funcall transform table params))
10882 ;; Find the insertion place
10883 (save-excursion
10884 (goto-char (point-min))
10885 (unless (re-search-forward
10886 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
10887 (error "Don't know where to insert translated table"))
10888 (goto-char (match-beginning 0))
10889 (beginning-of-line 2)
10890 (setq beg (point))
10891 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
10892 (error "Cannot find end of insertion region"))
10893 (beginning-of-line 1)
10894 (delete-region beg (point))
10895 (goto-char beg)
10896 (insert txt "\n"))
10897 (message "Table converted and installed at receiver location"))))
10899 (defun org-remove-by-index (list indices &optional i0)
10900 "Remove the elements in LIST with indices in INDICES.
10901 First element has index 0, or I0 if given."
10902 (if (not indices)
10903 list
10904 (if (integerp indices) (setq indices (list indices)))
10905 (setq i0 (1- (or i0 0)))
10906 (delq :rm (mapcar (lambda (x)
10907 (setq i0 (1+ i0))
10908 (if (memq i0 indices) :rm x))
10909 list))))
10911 (defun orgtbl-toggle-comment ()
10912 "Comment or uncomment the orgtbl at point."
10913 (interactive)
10914 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
10915 (re2 (concat "^" orgtbl-line-start-regexp))
10916 (commented (save-excursion (beginning-of-line 1)
10917 (cond ((looking-at re1) t)
10918 ((looking-at re2) nil)
10919 (t (error "Not at an org table")))))
10920 (re (if commented re1 re2))
10921 beg end)
10922 (save-excursion
10923 (beginning-of-line 1)
10924 (while (looking-at re) (beginning-of-line 0))
10925 (beginning-of-line 2)
10926 (setq beg (point))
10927 (while (looking-at re) (beginning-of-line 2))
10928 (setq end (point)))
10929 (comment-region beg end (if commented '(4) nil))))
10931 (defun orgtbl-insert-radio-table ()
10932 "Insert a radio table template appropriate for this major mode."
10933 (interactive)
10934 (let* ((e (assq major-mode orgtbl-radio-table-templates))
10935 (txt (nth 1 e))
10936 name pos)
10937 (unless e (error "No radio table setup defined for %s" major-mode))
10938 (setq name (read-string "Table name: "))
10939 (while (string-match "%n" txt)
10940 (setq txt (replace-match name t t txt)))
10941 (or (bolp) (insert "\n"))
10942 (setq pos (point))
10943 (insert txt)
10944 (goto-char pos)))
10946 (defun org-get-param (params header i sym &optional hsym)
10947 "Get parameter value for symbol SYM.
10948 If this is a header line, actually get the value for the symbol with an
10949 additional \"h\" inserted after the colon.
10950 If the value is a protperty list, get the element for the current column.
10951 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
10952 (let ((val (plist-get params sym)))
10953 (and hsym header (setq val (or (plist-get params hsym) val)))
10954 (if (consp val) (plist-get val i) val)))
10956 (defun orgtbl-to-generic (table params)
10957 "Convert the orgtbl-mode TABLE to some other format.
10958 This generic routine can be used for many standard cases.
10959 TABLE is a list, each entry either the symbol `hline' for a horizontal
10960 separator line, or a list of fields for that line.
10961 PARAMS is a property list of parameters that can influence the conversion.
10962 For the generic converter, some parameters are obligatory: You need to
10963 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
10964 :splice, you must have :tstart and :tend.
10966 Valid parameters are
10968 :tstart String to start the table. Ignored when :splice is t.
10969 :tend String to end the table. Ignored when :splice is t.
10971 :splice When set to t, return only table body lines, don't wrap
10972 them into :tstart and :tend. Default is nil.
10974 :hline String to be inserted on horizontal separation lines.
10975 May be nil to ignore hlines.
10977 :lstart String to start a new table line.
10978 :lend String to end a table line
10979 :sep Separator between two fields
10980 :lfmt Format for entire line, with enough %s to capture all fields.
10981 If this is present, :lstart, :lend, and :sep are ignored.
10982 :fmt A format to be used to wrap the field, should contain
10983 %s for the original field value. For example, to wrap
10984 everything in dollars, you could use :fmt \"$%s$\".
10985 This may also be a property list with column numbers and
10986 formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
10988 :hlstart :hlend :hlsep :hlfmt :hfmt
10989 Same as above, specific for the header lines in the table.
10990 All lines before the first hline are treated as header.
10991 If any of these is not present, the data line value is used.
10993 :efmt Use this format to print numbers with exponentials.
10994 The format should have %s twice for inserting mantissa
10995 and exponent, for example \"%s\\\\times10^{%s}\". This
10996 may also be a property list with column numbers and
10997 formats. :fmt will still be applied after :efmt.
10999 In addition to this, the parameters :skip and :skipcols are always handled
11000 directly by `orgtbl-send-table'. See manual."
11001 (interactive)
11002 (let* ((p params)
11003 (splicep (plist-get p :splice))
11004 (hline (plist-get p :hline))
11005 rtn line i fm efm lfmt h)
11007 ;; Do we have a header?
11008 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11009 (setq h t))
11011 ;; Put header
11012 (unless splicep
11013 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11015 ;; Now loop over all lines
11016 (while (setq line (pop table))
11017 (if (eq line 'hline)
11018 ;; A horizontal separator line
11019 (progn (if hline (push hline rtn))
11020 (setq h nil)) ; no longer in header
11021 ;; A normal line. Convert the fields, push line onto the result list
11022 (setq i 0)
11023 (setq line
11024 (mapcar
11025 (lambda (f)
11026 (setq i (1+ i)
11027 fm (org-get-param p h i :fmt :hfmt)
11028 efm (org-get-param p h i :efmt))
11029 (if (and efm (string-match orgtbl-exp-regexp f))
11030 (setq f (format
11031 efm (match-string 1 f) (match-string 2 f))))
11032 (if fm (setq f (format fm f)))
11034 line))
11035 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11036 (push (apply 'format lfmt line) rtn)
11037 (push (concat
11038 (org-get-param p h i :lstart :hlstart)
11039 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11040 (org-get-param p h i :lend :hlend))
11041 rtn))))
11043 (unless splicep
11044 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11046 (mapconcat 'identity (nreverse rtn) "\n")))
11048 (defun orgtbl-to-latex (table params)
11049 "Convert the orgtbl-mode TABLE to LaTeX.
11050 TABLE is a list, each entry either the symbol `hline' for a horizontal
11051 separator line, or a list of fields for that line.
11052 PARAMS is a property list of parameters that can influence the conversion.
11053 Supports all parameters from `orgtbl-to-generic'. Most important for
11054 LaTeX are:
11056 :splice When set to t, return only table body lines, don't wrap
11057 them into a tabular environment. Default is nil.
11059 :fmt A format to be used to wrap the field, should contain %s for the
11060 original field value. For example, to wrap everything in dollars,
11061 use :fmt \"$%s$\". This may also be a property list with column
11062 numbers and formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11064 :efmt Format for transforming numbers with exponentials. The format
11065 should have %s twice for inserting mantissa and exponent, for
11066 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11067 This may also be a property list with column numbers and formats.
11069 The general parameters :skip and :skipcols have already been applied when
11070 this function is called."
11071 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11072 org-table-last-alignment ""))
11073 (params2
11074 (list
11075 :tstart (concat "\\begin{tabular}{" alignment "}")
11076 :tend "\\end{tabular}"
11077 :lstart "" :lend " \\\\" :sep " & "
11078 :efmt "%s\\,(%s)" :hline "\\hline")))
11079 (orgtbl-to-generic table (org-combine-plists params2 params))))
11081 (defun orgtbl-to-html (table params)
11082 "Convert the orgtbl-mode TABLE to LaTeX.
11083 TABLE is a list, each entry either the symbol `hline' for a horizontal
11084 separator line, or a list of fields for that line.
11085 PARAMS is a property list of parameters that can influence the conversion.
11086 Currently this function recognizes the following parameters:
11088 :splice When set to t, return only table body lines, don't wrap
11089 them into a <table> environment. Default is nil.
11091 The general parameters :skip and :skipcols have already been applied when
11092 this function is called. The function does *not* use `orgtbl-to-generic',
11093 so you cannot specify parameters for it."
11094 (let* ((splicep (plist-get params :splice))
11095 html)
11096 ;; Just call the formatter we already have
11097 ;; We need to make text lines for it, so put the fields back together.
11098 (setq html (org-format-org-table-html
11099 (mapcar
11100 (lambda (x)
11101 (if (eq x 'hline)
11102 "|----+----|"
11103 (concat "| " (mapconcat 'identity x " | ") " |")))
11104 table)
11105 splicep))
11106 (if (string-match "\n+\\'" html)
11107 (setq html (replace-match "" t t html)))
11108 html))
11110 (defun orgtbl-to-texinfo (table params)
11111 "Convert the orgtbl-mode TABLE to TeXInfo.
11112 TABLE is a list, each entry either the symbol `hline' for a horizontal
11113 separator line, or a list of fields for that line.
11114 PARAMS is a property list of parameters that can influence the conversion.
11115 Supports all parameters from `orgtbl-to-generic'. Most important for
11116 TeXInfo are:
11118 :splice nil/t When set to t, return only table body lines, don't wrap
11119 them into a multitable environment. Default is nil.
11121 :fmt fmt A format to be used to wrap the field, should contain
11122 %s for the original field value. For example, to wrap
11123 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
11124 This may also be a property list with column numbers and
11125 formats. for example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
11127 :cf \"f1 f2..\" The column fractions for the table. Bye default these
11128 are computed automatically from the width of the columns
11129 under org-mode.
11131 The general parameters :skip and :skipcols have already been applied when
11132 this function is called."
11133 (let* ((total (float (apply '+ org-table-last-column-widths)))
11134 (colfrac (or (plist-get params :cf)
11135 (mapconcat
11136 (lambda (x) (format "%.3f" (/ (float x) total)))
11137 org-table-last-column-widths " ")))
11138 (params2
11139 (list
11140 :tstart (concat "@multitable @columnfractions " colfrac)
11141 :tend "@end multitable"
11142 :lstart "@item " :lend "" :sep " @tab "
11143 :hlstart "@headitem ")))
11144 (orgtbl-to-generic table (org-combine-plists params2 params))))
11146 ;;;; Link Stuff
11148 ;;; Link abbreviations
11150 (defun org-link-expand-abbrev (link)
11151 "Apply replacements as defined in `org-link-abbrev-alist."
11152 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
11153 (let* ((key (match-string 1 link))
11154 (as (or (assoc key org-link-abbrev-alist-local)
11155 (assoc key org-link-abbrev-alist)))
11156 (tag (and (match-end 2) (match-string 3 link)))
11157 rpl)
11158 (if (not as)
11159 link
11160 (setq rpl (cdr as))
11161 (cond
11162 ((symbolp rpl) (funcall rpl tag))
11163 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
11164 (t (concat rpl tag)))))
11165 link))
11167 ;;; Storing and inserting links
11169 (defvar org-insert-link-history nil
11170 "Minibuffer history for links inserted with `org-insert-link'.")
11172 (defvar org-stored-links nil
11173 "Contains the links stored with `org-store-link'.")
11175 (defvar org-store-link-plist nil
11176 "Plist with info about the most recently link created with `org-store-link'.")
11178 (defvar org-link-protocols nil
11179 "Link protocols added to Org-mode using `org-add-link-type'.")
11181 (defvar org-store-link-functions nil
11182 "List of functions that are called to create and store a link.
11183 Each function will be called in turn until one returns a non-nil
11184 value. Each function should check if it is responsible for creating
11185 this link (for example by looking at the major mode).
11186 If not, it must exit and return nil.
11187 If yes, it should return a non-nil value after a calling
11188 `org-store-link-properties' with a list of properties and values.
11189 Special properties are:
11191 :type The link prefix. like \"http\". This must be given.
11192 :link The link, like \"http://www.astro.uva.nl/~dominik\".
11193 This is obligatory as well.
11194 :description Optional default description for the second pair
11195 of brackets in an Org-mode link. The user can still change
11196 this when inserting this link into an Org-mode buffer.
11198 In addition to these, any additional properties can be specified
11199 and then used in remember templates.")
11201 (defun org-add-link-type (type &optional follow publish)
11202 "Add TYPE to the list of `org-link-types'.
11203 Re-compute all regular expressions depending on `org-link-types'
11204 FOLLOW and PUBLISH are two functions. Both take the link path as
11205 an argument.
11206 FOLLOW should do whatever is necessary to follow the link, for example
11207 to find a file or display a mail message.
11208 PUBLISH takes the path and retuns the string that should be used when
11209 this document is published."
11210 (add-to-list 'org-link-types type t)
11211 (org-make-link-regexps)
11212 (add-to-list 'org-link-protocols
11213 (list type follow publish)))
11215 (defun org-add-agenda-custom-command (entry)
11216 "Replace or add a command in `org-agenda-custom-commands'.
11217 This is mostly for hacking and trying a new command - once the command
11218 works you probably want to add it to `org-agenda-custom-commands' for good."
11219 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
11220 (if ass
11221 (setcdr ass (cdr entry))
11222 (push entry org-agenda-custom-commands))))
11224 ;;;###autoload
11225 (defun org-store-link (arg)
11226 "\\<org-mode-map>Store an org-link to the current location.
11227 This link can later be inserted into an org-buffer with
11228 \\[org-insert-link].
11229 For some link types, a prefix arg is interpreted:
11230 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
11231 For file links, arg negates `org-context-in-file-links'."
11232 (interactive "P")
11233 (setq org-store-link-plist nil) ; reset
11234 (let (link cpltxt desc description search txt)
11235 (cond
11237 ((run-hook-with-args-until-success 'org-store-link-functions)
11238 (setq link (plist-get org-store-link-plist :link)
11239 desc (or (plist-get org-store-link-plist :description) link)))
11241 ((eq major-mode 'bbdb-mode)
11242 (let ((name (bbdb-record-name (bbdb-current-record)))
11243 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
11244 (setq cpltxt (concat "bbdb:" (or name company))
11245 link (org-make-link cpltxt))
11246 (org-store-link-props :type "bbdb" :name name :company company)))
11248 ((eq major-mode 'Info-mode)
11249 (setq link (org-make-link "info:"
11250 (file-name-nondirectory Info-current-file)
11251 ":" Info-current-node))
11252 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
11253 ":" Info-current-node))
11254 (org-store-link-props :type "info" :file Info-current-file
11255 :node Info-current-node))
11257 ((eq major-mode 'calendar-mode)
11258 (let ((cd (calendar-cursor-to-date)))
11259 (setq link
11260 (format-time-string
11261 (car org-time-stamp-formats)
11262 (apply 'encode-time
11263 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
11264 nil nil nil))))
11265 (org-store-link-props :type "calendar" :date cd)))
11267 ((or (eq major-mode 'vm-summary-mode)
11268 (eq major-mode 'vm-presentation-mode))
11269 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
11270 (vm-follow-summary-cursor)
11271 (save-excursion
11272 (vm-select-folder-buffer)
11273 (let* ((message (car vm-message-pointer))
11274 (folder buffer-file-name)
11275 (subject (vm-su-subject message))
11276 (to (vm-get-header-contents message "To"))
11277 (from (vm-get-header-contents message "From"))
11278 (message-id (vm-su-message-id message)))
11279 (org-store-link-props :type "vm" :from from :to to :subject subject
11280 :message-id message-id)
11281 (setq message-id (org-remove-angle-brackets message-id))
11282 (setq folder (abbreviate-file-name folder))
11283 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
11284 folder)
11285 (setq folder (replace-match "" t t folder)))
11286 (setq cpltxt (org-email-link-description))
11287 (setq link (org-make-link "vm:" folder "#" message-id)))))
11289 ((eq major-mode 'wl-summary-mode)
11290 (let* ((msgnum (wl-summary-message-number))
11291 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
11292 msgnum 'message-id))
11293 (wl-message-entity
11294 (if (fboundp 'elmo-message-entity)
11295 (elmo-message-entity
11296 wl-summary-buffer-elmo-folder msgnum)
11297 (elmo-msgdb-overview-get-entity
11298 msgnum (wl-summary-buffer-msgdb))))
11299 (from (wl-summary-line-from))
11300 (to (elmo-message-entity-field wl-message-entity 'to))
11301 (subject (let (wl-thr-indent-string wl-parent-message-entity)
11302 (wl-summary-line-subject))))
11303 (org-store-link-props :type "wl" :from from :to to
11304 :subject subject :message-id message-id)
11305 (setq message-id (org-remove-angle-brackets message-id))
11306 (setq cpltxt (org-email-link-description))
11307 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
11308 "#" message-id))))
11310 ((or (equal major-mode 'mh-folder-mode)
11311 (equal major-mode 'mh-show-mode))
11312 (let ((from (org-mhe-get-header "From:"))
11313 (to (org-mhe-get-header "To:"))
11314 (message-id (org-mhe-get-header "Message-Id:"))
11315 (subject (org-mhe-get-header "Subject:")))
11316 (org-store-link-props :type "mh" :from from :to to
11317 :subject subject :message-id message-id)
11318 (setq cpltxt (org-email-link-description))
11319 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
11320 (org-remove-angle-brackets message-id)))))
11322 ((eq major-mode 'rmail-mode)
11323 (save-excursion
11324 (save-restriction
11325 (rmail-narrow-to-non-pruned-header)
11326 (let ((folder buffer-file-name)
11327 (message-id (mail-fetch-field "message-id"))
11328 (from (mail-fetch-field "from"))
11329 (to (mail-fetch-field "to"))
11330 (subject (mail-fetch-field "subject")))
11331 (org-store-link-props
11332 :type "rmail" :from from :to to
11333 :subject subject :message-id message-id)
11334 (setq message-id (org-remove-angle-brackets message-id))
11335 (setq cpltxt (org-email-link-description))
11336 (setq link (org-make-link "rmail:" folder "#" message-id))))))
11338 ((eq major-mode 'gnus-group-mode)
11339 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
11340 (gnus-group-group-name)) ; version
11341 ((fboundp 'gnus-group-name)
11342 (gnus-group-name))
11343 (t "???"))))
11344 (unless group (error "Not on a group"))
11345 (org-store-link-props :type "gnus" :group group)
11346 (setq cpltxt (concat
11347 (if (org-xor arg org-usenet-links-prefer-google)
11348 "http://groups.google.com/groups?group="
11349 "gnus:")
11350 group)
11351 link (org-make-link cpltxt))))
11353 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
11354 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
11355 (let* ((group gnus-newsgroup-name)
11356 (article (gnus-summary-article-number))
11357 (header (gnus-summary-article-header article))
11358 (from (mail-header-from header))
11359 (message-id (mail-header-id header))
11360 (date (mail-header-date header))
11361 (subject (gnus-summary-subject-string)))
11362 (org-store-link-props :type "gnus" :from from :subject subject
11363 :message-id message-id :group group)
11364 (setq cpltxt (org-email-link-description))
11365 (if (org-xor arg org-usenet-links-prefer-google)
11366 (setq link
11367 (concat
11368 cpltxt "\n "
11369 (format "http://groups.google.com/groups?as_umsgid=%s"
11370 (org-fixup-message-id-for-http message-id))))
11371 (setq link (org-make-link "gnus:" group
11372 "#" (number-to-string article))))))
11374 ((eq major-mode 'w3-mode)
11375 (setq cpltxt (url-view-url t)
11376 link (org-make-link cpltxt))
11377 (org-store-link-props :type "w3" :url (url-view-url t)))
11379 ((eq major-mode 'w3m-mode)
11380 (setq cpltxt (or w3m-current-title w3m-current-url)
11381 link (org-make-link w3m-current-url))
11382 (org-store-link-props :type "w3m" :url (url-view-url t)))
11384 ((setq search (run-hook-with-args-until-success
11385 'org-create-file-search-functions))
11386 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
11387 "::" search))
11388 (setq cpltxt (or description link)))
11390 ((eq major-mode 'image-mode)
11391 (setq cpltxt (concat "file:"
11392 (abbreviate-file-name buffer-file-name))
11393 link (org-make-link cpltxt))
11394 (org-store-link-props :type "image" :file buffer-file-name))
11396 ((eq major-mode 'dired-mode)
11397 ;; link to the file in the current line
11398 (setq cpltxt (concat "file:"
11399 (abbreviate-file-name
11400 (expand-file-name
11401 (dired-get-filename nil t))))
11402 link (org-make-link cpltxt)))
11404 ((and buffer-file-name (org-mode-p))
11405 ;; Just link to current headline
11406 (setq cpltxt (concat "file:"
11407 (abbreviate-file-name buffer-file-name)))
11408 ;; Add a context search string
11409 (when (org-xor org-context-in-file-links arg)
11410 ;; Check if we are on a target
11411 (if (org-in-regexp "<<\\(.*?\\)>>")
11412 (setq cpltxt (concat cpltxt "::" (match-string 1)))
11413 (setq txt (cond
11414 ((org-on-heading-p) nil)
11415 ((org-region-active-p)
11416 (buffer-substring (region-beginning) (region-end)))
11417 (t (buffer-substring (point-at-bol) (point-at-eol)))))
11418 (when (or (null txt) (string-match "\\S-" txt))
11419 (setq cpltxt
11420 (concat cpltxt "::" (org-make-org-heading-search-string txt))
11421 desc "NONE"))))
11422 (if (string-match "::\\'" cpltxt)
11423 (setq cpltxt (substring cpltxt 0 -2)))
11424 (setq link (org-make-link cpltxt)))
11426 ((buffer-file-name (buffer-base-buffer))
11427 ;; Just link to this file here.
11428 (setq cpltxt (concat "file:"
11429 (abbreviate-file-name
11430 (buffer-file-name (buffer-base-buffer)))))
11431 ;; Add a context string
11432 (when (org-xor org-context-in-file-links arg)
11433 (setq txt (if (org-region-active-p)
11434 (buffer-substring (region-beginning) (region-end))
11435 (buffer-substring (point-at-bol) (point-at-eol))))
11436 ;; Only use search option if there is some text.
11437 (when (string-match "\\S-" txt)
11438 (setq cpltxt
11439 (concat cpltxt "::" (org-make-org-heading-search-string txt))
11440 desc "NONE")))
11441 (setq link (org-make-link cpltxt)))
11443 ((interactive-p)
11444 (error "Cannot link to a buffer which is not visiting a file"))
11446 (t (setq link nil)))
11448 (if (consp link) (setq cpltxt (car link) link (cdr link)))
11449 (setq link (or link cpltxt)
11450 desc (or desc cpltxt))
11451 (if (equal desc "NONE") (setq desc nil))
11453 (if (and (interactive-p) link)
11454 (progn
11455 (setq org-stored-links
11456 (cons (list link desc) org-stored-links))
11457 (message "Stored: %s" (or desc link)))
11458 (and link (org-make-link-string link desc)))))
11460 (defun org-store-link-props (&rest plist)
11461 "Store link properties, extract names and addresses."
11462 (let (x adr)
11463 (when (setq x (plist-get plist :from))
11464 (setq adr (mail-extract-address-components x))
11465 (plist-put plist :fromname (car adr))
11466 (plist-put plist :fromaddress (nth 1 adr)))
11467 (when (setq x (plist-get plist :to))
11468 (setq adr (mail-extract-address-components x))
11469 (plist-put plist :toname (car adr))
11470 (plist-put plist :toaddress (nth 1 adr))))
11471 (let ((from (plist-get plist :from))
11472 (to (plist-get plist :to)))
11473 (when (and from to org-from-is-user-regexp)
11474 (plist-put plist :fromto
11475 (if (string-match org-from-is-user-regexp from)
11476 (concat "to %t")
11477 (concat "from %f")))))
11478 (setq org-store-link-plist plist))
11480 (defun org-email-link-description (&optional fmt)
11481 "Return the description part of an email link.
11482 This takes information from `org-store-link-plist' and formats it
11483 according to FMT (default from `org-email-link-description-format')."
11484 (setq fmt (or fmt org-email-link-description-format))
11485 (let* ((p org-store-link-plist)
11486 (to (plist-get p :toaddress))
11487 (from (plist-get p :fromaddress))
11488 (table
11489 (list
11490 (cons "%c" (plist-get p :fromto))
11491 (cons "%F" (plist-get p :from))
11492 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
11493 (cons "%T" (plist-get p :to))
11494 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
11495 (cons "%s" (plist-get p :subject))
11496 (cons "%m" (plist-get p :message-id)))))
11497 (when (string-match "%c" fmt)
11498 ;; Check if the user wrote this message
11499 (if (and org-from-is-user-regexp from to
11500 (save-match-data (string-match org-from-is-user-regexp from)))
11501 (setq fmt (replace-match "to %t" t t fmt))
11502 (setq fmt (replace-match "from %f" t t fmt))))
11503 (org-replace-escapes fmt table)))
11505 (defun org-make-org-heading-search-string (&optional string heading)
11506 "Make search string for STRING or current headline."
11507 (interactive)
11508 (let ((s (or string (org-get-heading))))
11509 (unless (and string (not heading))
11510 ;; We are using a headline, clean up garbage in there.
11511 (if (string-match org-todo-regexp s)
11512 (setq s (replace-match "" t t s)))
11513 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
11514 (setq s (replace-match "" t t s)))
11515 (setq s (org-trim s))
11516 (if (string-match (concat "^\\(" org-quote-string "\\|"
11517 org-comment-string "\\)") s)
11518 (setq s (replace-match "" t t s)))
11519 (while (string-match org-ts-regexp s)
11520 (setq s (replace-match "" t t s))))
11521 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
11522 (setq s (replace-match " " t t s)))
11523 (or string (setq s (concat "*" s))) ; Add * for headlines
11524 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
11526 (defun org-make-link (&rest strings)
11527 "Concatenate STRINGS."
11528 (apply 'concat strings))
11530 (defun org-make-link-string (link &optional description)
11531 "Make a link with brackets, consisting of LINK and DESCRIPTION."
11532 (unless (string-match "\\S-" link)
11533 (error "Empty link"))
11534 (when (stringp description)
11535 ;; Remove brackets from the description, they are fatal.
11536 (while (string-match "\\[\\|\\]" description)
11537 (setq description (replace-match "" t t description))))
11538 (when (equal (org-link-escape link) description)
11539 ;; No description needed, it is identical
11540 (setq description nil))
11541 (when (and (not description)
11542 (not (equal link (org-link-escape link))))
11543 (setq description link))
11544 (concat "[[" (org-link-escape link) "]"
11545 (if description (concat "[" description "]") "")
11546 "]"))
11548 (defconst org-link-escape-chars
11549 '((" " . "%20")
11550 ("[" . "%5B")
11551 ("]" . "%5d")
11552 ("\340" . "%E0") ; `a
11553 ("\342" . "%E2") ; ^a
11554 ("\347" . "%E7") ; ,c
11555 ("\350" . "%E8") ; `e
11556 ("\351" . "%E9") ; 'e
11557 ("\352" . "%EA") ; ^e
11558 ("\356" . "%EE") ; ^i
11559 ("\364" . "%F4") ; ^o
11560 ("\371" . "%F9") ; `u
11561 ("\373" . "%FB") ; ^u
11562 (";" . "%3B")
11563 ("?" . "%3F")
11564 ("=" . "%3D")
11565 ("+" . "%2B")
11567 "Association list of escapes for some characters problematic in links.
11568 This is the list that is used for internal purposes.")
11570 (defconst org-link-escape-chars-browser
11571 '((" " . "%20"))
11572 "Association list of escapes for some characters problematic in links.
11573 This is the list that is used before handing over to the browser.")
11575 (defun org-link-escape (text &optional table)
11576 "Escape charaters in TEXT that are problematic for links."
11577 (setq table (or table org-link-escape-chars))
11578 (when text
11579 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
11580 table "\\|")))
11581 (while (string-match re text)
11582 (setq text
11583 (replace-match
11584 (cdr (assoc (match-string 0 text) table))
11585 t t text)))
11586 text)))
11588 (defun org-link-unescape (text &optional table)
11589 "Reverse the action of `org-link-escape'."
11590 (setq table (or table org-link-escape-chars))
11591 (when text
11592 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
11593 table "\\|")))
11594 (while (string-match re text)
11595 (setq text
11596 (replace-match
11597 (car (rassoc (match-string 0 text) table))
11598 t t text)))
11599 text)))
11601 (defun org-xor (a b)
11602 "Exclusive or."
11603 (if a (not b) b))
11605 (defun org-get-header (header)
11606 "Find a header field in the current buffer."
11607 (save-excursion
11608 (goto-char (point-min))
11609 (let ((case-fold-search t) s)
11610 (cond
11611 ((eq header 'from)
11612 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
11613 (setq s (match-string 1)))
11614 (while (string-match "\"" s)
11615 (setq s (replace-match "" t t s)))
11616 (if (string-match "[<(].*" s)
11617 (setq s (replace-match "" t t s))))
11618 ((eq header 'message-id)
11619 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
11620 (setq s (match-string 1))))
11621 ((eq header 'subject)
11622 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
11623 (setq s (match-string 1)))))
11624 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
11625 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
11626 s)))
11629 (defun org-fixup-message-id-for-http (s)
11630 "Replace special characters in a message id, so it can be used in an http query."
11631 (while (string-match "<" s)
11632 (setq s (replace-match "%3C" t t s)))
11633 (while (string-match ">" s)
11634 (setq s (replace-match "%3E" t t s)))
11635 (while (string-match "@" s)
11636 (setq s (replace-match "%40" t t s)))
11639 ;;;###autoload
11640 (defun org-insert-link-global ()
11641 "Insert a link like Org-mode does.
11642 This command can be called in any mode to insert a link in Org-mode syntax."
11643 (interactive)
11644 (org-run-like-in-org-mode 'org-insert-link))
11646 (defun org-insert-link (&optional complete-file)
11647 "Insert a link. At the prompt, enter the link.
11649 Completion can be used to select a link previously stored with
11650 `org-store-link'. When the empty string is entered (i.e. if you just
11651 press RET at the prompt), the link defaults to the most recently
11652 stored link. As SPC triggers completion in the minibuffer, you need to
11653 use M-SPC or C-q SPC to force the insertion of a space character.
11655 You will also be prompted for a description, and if one is given, it will
11656 be displayed in the buffer instead of the link.
11658 If there is already a link at point, this command will allow you to edit link
11659 and description parts.
11661 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
11662 selected using completion. The path to the file will be relative to
11663 the current directory if the file is in the current directory or a
11664 subdirectory. Otherwise, the link will be the absolute path as
11665 completed in the minibuffer (i.e. normally ~/path/to/file).
11667 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
11668 is in the current directory or below.
11669 With three \\[universal-argument] prefixes, negate the meaning of
11670 `org-keep-stored-link-after-insertion'."
11671 (interactive "P")
11672 (let* ((wcf (current-window-configuration))
11673 (region (if (org-region-active-p)
11674 (buffer-substring (region-beginning) (region-end))))
11675 (remove (and region (list (region-beginning) (region-end))))
11676 (desc region)
11677 tmphist ; byte-compile incorrectly complains about this
11678 link entry file)
11679 (cond
11680 ((org-in-regexp org-bracket-link-regexp 1)
11681 ;; We do have a link at point, and we are going to edit it.
11682 (setq remove (list (match-beginning 0) (match-end 0)))
11683 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
11684 (setq link (read-string "Link: "
11685 (org-link-unescape
11686 (org-match-string-no-properties 1)))))
11687 ((or (org-in-regexp org-angle-link-re)
11688 (org-in-regexp org-plain-link-re))
11689 ;; Convert to bracket link
11690 (setq remove (list (match-beginning 0) (match-end 0))
11691 link (read-string "Link: "
11692 (org-remove-angle-brackets (match-string 0)))))
11693 ((equal complete-file '(4))
11694 ;; Completing read for file names.
11695 (setq file (read-file-name "File: "))
11696 (let ((pwd (file-name-as-directory (expand-file-name ".")))
11697 (pwd1 (file-name-as-directory (abbreviate-file-name
11698 (expand-file-name ".")))))
11699 (cond
11700 ((equal complete-file '(16))
11701 (setq link (org-make-link
11702 "file:"
11703 (abbreviate-file-name (expand-file-name file)))))
11704 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
11705 (setq link (org-make-link "file:" (match-string 1 file))))
11706 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
11707 (expand-file-name file))
11708 (setq link (org-make-link
11709 "file:" (match-string 1 (expand-file-name file)))))
11710 (t (setq link (org-make-link "file:" file))))))
11712 ;; Read link, with completion for stored links.
11713 (with-output-to-temp-buffer "*Org Links*"
11714 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
11715 (when org-stored-links
11716 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
11717 (princ (mapconcat
11718 (lambda (x)
11719 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
11720 (reverse org-stored-links) "\n"))))
11721 (let ((cw (selected-window)))
11722 (select-window (get-buffer-window "*Org Links*"))
11723 (shrink-window-if-larger-than-buffer)
11724 (setq truncate-lines t)
11725 (select-window cw))
11726 ;; Fake a link history, containing the stored links.
11727 (setq tmphist (append (mapcar 'car org-stored-links)
11728 org-insert-link-history))
11729 (unwind-protect
11730 (setq link (org-completing-read
11731 "Link: "
11732 (append
11733 (mapcar (lambda (x) (list (concat (car x) ":")))
11734 (append org-link-abbrev-alist-local org-link-abbrev-alist))
11735 (mapcar (lambda (x) (list (concat x ":")))
11736 org-link-types))
11737 nil nil nil
11738 'tmphist
11739 (or (car (car org-stored-links)))))
11740 (set-window-configuration wcf)
11741 (kill-buffer "*Org Links*"))
11742 (setq entry (assoc link org-stored-links))
11743 (or entry (push link org-insert-link-history))
11744 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
11745 (not org-keep-stored-link-after-insertion))
11746 (setq org-stored-links (delq (assoc link org-stored-links)
11747 org-stored-links)))
11748 (setq desc (or desc (nth 1 entry)))))
11750 (if (string-match org-plain-link-re link)
11751 ;; URL-like link, normalize the use of angular brackets.
11752 (setq link (org-make-link (org-remove-angle-brackets link))))
11754 ;; Check if we are linking to the current file with a search option
11755 ;; If yes, simplify the link by using only the search option.
11756 (when (and buffer-file-name
11757 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
11758 (let* ((path (match-string 1 link))
11759 (case-fold-search nil)
11760 (search (match-string 2 link)))
11761 (save-match-data
11762 (if (equal (file-truename buffer-file-name) (file-truename path))
11763 ;; We are linking to this same file, with a search option
11764 (setq link search)))))
11766 ;; Check if we can/should use a relative path. If yes, simplify the link
11767 (when (string-match "\\<file:\\(.*\\)" link)
11768 (let* ((path (match-string 1 link))
11769 (origpath path)
11770 (desc-is-link (equal link desc))
11771 (case-fold-search nil))
11772 (cond
11773 ((eq org-link-file-path-type 'absolute)
11774 (setq path (abbreviate-file-name (expand-file-name path))))
11775 ((eq org-link-file-path-type 'noabbrev)
11776 (setq path (expand-file-name path)))
11777 ((eq org-link-file-path-type 'relative)
11778 (setq path (file-relative-name path)))
11780 (save-match-data
11781 (if (string-match (concat "^" (regexp-quote
11782 (file-name-as-directory
11783 (expand-file-name "."))))
11784 (expand-file-name path))
11785 ;; We are linking a file with relative path name.
11786 (setq path (substring (expand-file-name path)
11787 (match-end 0)))))))
11788 (setq link (concat "file:" path))
11789 (if (equal desc origpath)
11790 (setq desc path))))
11792 (setq desc (read-string "Description: " desc))
11793 (unless (string-match "\\S-" desc) (setq desc nil))
11794 (if remove (apply 'delete-region remove))
11795 (insert (org-make-link-string link desc))))
11797 (defun org-completing-read (&rest args)
11798 (let ((minibuffer-local-completion-map
11799 (copy-keymap minibuffer-local-completion-map)))
11800 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
11801 (apply 'completing-read args)))
11803 ;;; Opening/following a link
11804 (defvar org-link-search-failed nil)
11806 (defun org-next-link ()
11807 "Move forward to the next link.
11808 If the link is in hidden text, expose it."
11809 (interactive)
11810 (when (and org-link-search-failed (eq this-command last-command))
11811 (goto-char (point-min))
11812 (message "Link search wrapped back to beginning of buffer"))
11813 (setq org-link-search-failed nil)
11814 (let* ((pos (point))
11815 (ct (org-context))
11816 (a (assoc :link ct)))
11817 (if a (goto-char (nth 2 a)))
11818 (if (re-search-forward org-any-link-re nil t)
11819 (progn
11820 (goto-char (match-beginning 0))
11821 (if (org-invisible-p) (org-show-context)))
11822 (goto-char pos)
11823 (setq org-link-search-failed t)
11824 (error "No further link found"))))
11826 (defun org-previous-link ()
11827 "Move backward to the previous link.
11828 If the link is in hidden text, expose it."
11829 (interactive)
11830 (when (and org-link-search-failed (eq this-command last-command))
11831 (goto-char (point-max))
11832 (message "Link search wrapped back to end of buffer"))
11833 (setq org-link-search-failed nil)
11834 (let* ((pos (point))
11835 (ct (org-context))
11836 (a (assoc :link ct)))
11837 (if a (goto-char (nth 1 a)))
11838 (if (re-search-backward org-any-link-re nil t)
11839 (progn
11840 (goto-char (match-beginning 0))
11841 (if (org-invisible-p) (org-show-context)))
11842 (goto-char pos)
11843 (setq org-link-search-failed t)
11844 (error "No further link found"))))
11846 (defun org-find-file-at-mouse (ev)
11847 "Open file link or URL at mouse."
11848 (interactive "e")
11849 (mouse-set-point ev)
11850 (org-open-at-point 'in-emacs))
11852 (defun org-open-at-mouse (ev)
11853 "Open file link or URL at mouse."
11854 (interactive "e")
11855 (mouse-set-point ev)
11856 (org-open-at-point))
11858 (defvar org-window-config-before-follow-link nil
11859 "The window configuration before following a link.
11860 This is saved in case the need arises to restore it.")
11862 (defvar org-open-link-marker (make-marker)
11863 "Marker pointing to the location where `org-open-at-point; was called.")
11865 ;;;###autoload
11866 (defun org-open-at-point-global ()
11867 "Follow a link like Org-mode does.
11868 This command can be called in any mode to follow a link that has
11869 Org-mode syntax."
11870 (interactive)
11871 (org-run-like-in-org-mode 'org-open-at-point))
11873 (defun org-open-at-point (&optional in-emacs)
11874 "Open link at or after point.
11875 If there is no link at point, this function will search forward up to
11876 the end of the current subtree.
11877 Normally, files will be opened by an appropriate application. If the
11878 optional argument IN-EMACS is non-nil, Emacs will visit the file."
11879 (interactive "P")
11880 (move-marker org-open-link-marker (point))
11881 (setq org-window-config-before-follow-link (current-window-configuration))
11882 (org-remove-occur-highlights nil nil t)
11883 (if (org-at-timestamp-p t)
11884 (org-follow-timestamp-link)
11885 (let (type path link line search (pos (point)))
11886 (catch 'match
11887 (save-excursion
11888 (skip-chars-forward "^]\n\r")
11889 (when (org-in-regexp org-bracket-link-regexp)
11890 (setq link (org-link-unescape (org-match-string-no-properties 1)))
11891 (while (string-match " *\n *" link)
11892 (setq link (replace-match " " t t link)))
11893 (setq link (org-link-expand-abbrev link))
11894 (if (string-match org-link-re-with-space2 link)
11895 (setq type (match-string 1 link) path (match-string 2 link))
11896 (setq type "thisfile" path link))
11897 (throw 'match t)))
11899 (when (get-text-property (point) 'org-linked-text)
11900 (setq type "thisfile"
11901 pos (if (get-text-property (1+ (point)) 'org-linked-text)
11902 (1+ (point)) (point))
11903 path (buffer-substring
11904 (previous-single-property-change pos 'org-linked-text)
11905 (next-single-property-change pos 'org-linked-text)))
11906 (throw 'match t))
11908 (save-excursion
11909 (when (or (org-in-regexp org-angle-link-re)
11910 (org-in-regexp org-plain-link-re))
11911 (setq type (match-string 1) path (match-string 2))
11912 (throw 'match t)))
11913 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
11914 (setq type "tree-match"
11915 path (match-string 1))
11916 (throw 'match t))
11917 (save-excursion
11918 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
11919 (setq type "tags"
11920 path (match-string 1))
11921 (while (string-match ":" path)
11922 (setq path (replace-match "+" t t path)))
11923 (throw 'match t))))
11924 (unless path
11925 (error "No link found"))
11926 ;; Remove any trailing spaces in path
11927 (if (string-match " +\\'" path)
11928 (setq path (replace-match "" t t path)))
11930 (cond
11932 ((assoc type org-link-protocols)
11933 (funcall (nth 1 (assoc type org-link-protocols)) path))
11935 ((equal type "mailto")
11936 (let ((cmd (car org-link-mailto-program))
11937 (args (cdr org-link-mailto-program)) args1
11938 (address path) (subject "") a)
11939 (if (string-match "\\(.*\\)::\\(.*\\)" path)
11940 (setq address (match-string 1 path)
11941 subject (org-link-escape (match-string 2 path))))
11942 (while args
11943 (cond
11944 ((not (stringp (car args))) (push (pop args) args1))
11945 (t (setq a (pop args))
11946 (if (string-match "%a" a)
11947 (setq a (replace-match address t t a)))
11948 (if (string-match "%s" a)
11949 (setq a (replace-match subject t t a)))
11950 (push a args1))))
11951 (apply cmd (nreverse args1))))
11953 ((member type '("http" "https" "ftp" "news"))
11954 (browse-url (concat type ":" (org-link-escape
11955 path org-link-escape-chars-browser))))
11957 ((string= type "tags")
11958 (org-tags-view in-emacs path))
11959 ((string= type "thisfile")
11960 (if in-emacs
11961 (switch-to-buffer-other-window
11962 (org-get-buffer-for-internal-link (current-buffer)))
11963 (org-mark-ring-push))
11964 (let ((cmd `(org-link-search
11965 ,path
11966 ,(cond ((equal in-emacs '(4)) 'occur)
11967 ((equal in-emacs '(16)) 'org-occur)
11968 (t nil))
11969 ,pos)))
11970 (condition-case nil (eval cmd)
11971 (error (progn (widen) (eval cmd))))))
11973 ((string= type "tree-match")
11974 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
11976 ((string= type "file")
11977 (if (string-match "::\\([0-9]+\\)\\'" path)
11978 (setq line (string-to-number (match-string 1 path))
11979 path (substring path 0 (match-beginning 0)))
11980 (if (string-match "::\\(.+\\)\\'" path)
11981 (setq search (match-string 1 path)
11982 path (substring path 0 (match-beginning 0)))))
11983 (org-open-file path in-emacs line search))
11985 ((string= type "news")
11986 (org-follow-gnus-link path))
11988 ((string= type "bbdb")
11989 (org-follow-bbdb-link path))
11991 ((string= type "info")
11992 (org-follow-info-link path))
11994 ((string= type "gnus")
11995 (let (group article)
11996 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11997 (error "Error in Gnus link"))
11998 (setq group (match-string 1 path)
11999 article (match-string 3 path))
12000 (org-follow-gnus-link group article)))
12002 ((string= type "vm")
12003 (let (folder article)
12004 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12005 (error "Error in VM link"))
12006 (setq folder (match-string 1 path)
12007 article (match-string 3 path))
12008 ;; in-emacs is the prefix arg, will be interpreted as read-only
12009 (org-follow-vm-link folder article in-emacs)))
12011 ((string= type "wl")
12012 (let (folder article)
12013 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12014 (error "Error in Wanderlust link"))
12015 (setq folder (match-string 1 path)
12016 article (match-string 3 path))
12017 (org-follow-wl-link folder article)))
12019 ((string= type "mhe")
12020 (let (folder article)
12021 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12022 (error "Error in MHE link"))
12023 (setq folder (match-string 1 path)
12024 article (match-string 3 path))
12025 (org-follow-mhe-link folder article)))
12027 ((string= type "rmail")
12028 (let (folder article)
12029 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12030 (error "Error in RMAIL link"))
12031 (setq folder (match-string 1 path)
12032 article (match-string 3 path))
12033 (org-follow-rmail-link folder article)))
12035 ((string= type "shell")
12036 (let ((cmd path))
12037 ;; The following is only for backward compatibility
12038 (while (string-match "@{" cmd) (setq cmd (replace-match "<" t t cmd)))
12039 (while (string-match "@}" cmd) (setq cmd (replace-match ">" t t cmd)))
12040 (if (or (not org-confirm-shell-link-function)
12041 (funcall org-confirm-shell-link-function
12042 (format "Execute \"%s\" in shell? "
12043 (org-add-props cmd nil
12044 'face 'org-warning))))
12045 (progn
12046 (message "Executing %s" cmd)
12047 (shell-command cmd))
12048 (error "Abort"))))
12050 ((string= type "elisp")
12051 (let ((cmd path))
12052 (if (or (not org-confirm-elisp-link-function)
12053 (funcall org-confirm-elisp-link-function
12054 (format "Execute \"%s\" as elisp? "
12055 (org-add-props cmd nil
12056 'face 'org-warning))))
12057 (message "%s => %s" cmd (eval (read cmd)))
12058 (error "Abort"))))
12061 (browse-url-at-point)))))
12062 (move-marker org-open-link-marker nil))
12064 ;;; File search
12066 (defvar org-create-file-search-functions nil
12067 "List of functions to construct the right search string for a file link.
12068 These functions are called in turn with point at the location to
12069 which the link should point.
12071 A function in the hook should first test if it would like to
12072 handle this file type, for example by checking the major-mode or
12073 the file extension. If it decides not to handle this file, it
12074 should just return nil to give other functions a chance. If it
12075 does handle the file, it must return the search string to be used
12076 when following the link. The search string will be part of the
12077 file link, given after a double colon, and `org-open-at-point'
12078 will automatically search for it. If special measures must be
12079 taken to make the search successful, another function should be
12080 added to the companion hook `org-execute-file-search-functions',
12081 which see.
12083 A function in this hook may also use `setq' to set the variable
12084 `description' to provide a suggestion for the descriptive text to
12085 be used for this link when it gets inserted into an Org-mode
12086 buffer with \\[org-insert-link].")
12088 (defvar org-execute-file-search-functions nil
12089 "List of functions to execute a file search triggered by a link.
12091 Functions added to this hook must accept a single argument, the
12092 search string that was part of the file link, the part after the
12093 double colon. The function must first check if it would like to
12094 handle this search, for example by checking the major-mode or the
12095 file extension. If it decides not to handle this search, it
12096 should just return nil to give other functions a chance. If it
12097 does handle the search, it must return a non-nil value to keep
12098 other functions from trying.
12100 Each function can access the current prefix argument through the
12101 variable `current-prefix-argument'. Note that a single prefix is
12102 used to force opening a link in Emacs, so it may be good to only
12103 use a numeric or double prefix to guide the search function.
12105 In case this is needed, a function in this hook can also restore
12106 the window configuration before `org-open-at-point' was called using:
12108 (set-window-configuration org-window-config-before-follow-link)")
12110 (defun org-link-search (s &optional type avoid-pos)
12111 "Search for a link search option.
12112 If S is surrounded by forward slashes, it is interpreted as a
12113 regular expression. In org-mode files, this will create an `org-occur'
12114 sparse tree. In ordinary files, `occur' will be used to list matches.
12115 If the current buffer is in `dired-mode', grep will be used to search
12116 in all files. If AVOID-POS is given, ignore matches near that position."
12117 (let ((case-fold-search t)
12118 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12119 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12120 (append '(("") (" ") ("\t") ("\n"))
12121 org-emphasis-alist)
12122 "\\|") "\\)"))
12123 (pos (point))
12124 (pre "") (post "")
12125 words re0 re1 re2 re3 re4 re5 re2a reall)
12126 (cond
12127 ;; First check if there are any special
12128 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12129 ;; Now try the builtin stuff
12130 ((save-excursion
12131 (goto-char (point-min))
12132 (and
12133 (re-search-forward
12134 (concat "<<" (regexp-quote s0) ">>") nil t)
12135 (setq pos (match-beginning 0))))
12136 ;; There is an exact target for this
12137 (goto-char pos))
12138 ((string-match "^/\\(.*\\)/$" s)
12139 ;; A regular expression
12140 (cond
12141 ((org-mode-p)
12142 (org-occur (match-string 1 s)))
12143 ;;((eq major-mode 'dired-mode)
12144 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12145 (t (org-do-occur (match-string 1 s)))))
12147 ;; A normal search strings
12148 (when (equal (string-to-char s) ?*)
12149 ;; Anchor on headlines, post may include tags.
12150 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
12151 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
12152 s (substring s 1)))
12153 (remove-text-properties
12154 0 (length s)
12155 '(face nil mouse-face nil keymap nil fontified nil) s)
12156 ;; Make a series of regular expressions to find a match
12157 (setq words (org-split-string s "[ \n\r\t]+")
12158 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
12159 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
12160 "\\)" markers)
12161 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
12162 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
12163 re1 (concat pre re2 post)
12164 re3 (concat pre re4 post)
12165 re5 (concat pre ".*" re4)
12166 re2 (concat pre re2)
12167 re2a (concat pre re2a)
12168 re4 (concat pre re4)
12169 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
12170 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
12171 re5 "\\)"
12173 (cond
12174 ((eq type 'org-occur) (org-occur reall))
12175 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
12176 (t (goto-char (point-min))
12177 (if (or (org-search-not-self 1 re0 nil t)
12178 (org-search-not-self 1 re1 nil t)
12179 (org-search-not-self 1 re2 nil t)
12180 (org-search-not-self 1 re2a nil t)
12181 (org-search-not-self 1 re3 nil t)
12182 (org-search-not-self 1 re4 nil t)
12183 (org-search-not-self 1 re5 nil t)
12185 (goto-char (match-beginning 1))
12186 (goto-char pos)
12187 (error "No match")))))
12189 ;; Normal string-search
12190 (goto-char (point-min))
12191 (if (search-forward s nil t)
12192 (goto-char (match-beginning 0))
12193 (error "No match"))))
12194 (and (org-mode-p) (org-show-context 'link-search))))
12196 (defun org-search-not-self (group &rest args)
12197 "Execute `re-search-forward', but only accept matches that do not
12198 enclose the position of `org-open-link-marker'."
12199 (let ((m org-open-link-marker))
12200 (catch 'exit
12201 (while (apply 're-search-forward args)
12202 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
12203 (goto-char (match-end group))
12204 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
12205 (> (match-beginning 0) (marker-position m))
12206 (< (match-end 0) (marker-position m)))
12207 (save-match-data
12208 (or (not (org-in-regexp
12209 org-bracket-link-analytic-regexp 1))
12210 (not (match-end 4)) ; no description
12211 (and (<= (match-beginning 4) (point))
12212 (>= (match-end 4) (point))))))
12213 (throw 'exit (point))))))))
12215 (defun org-get-buffer-for-internal-link (buffer)
12216 "Return a buffer to be used for displaying the link target of internal links."
12217 (cond
12218 ((not org-display-internal-link-with-indirect-buffer)
12219 buffer)
12220 ((string-match "(Clone)$" (buffer-name buffer))
12221 (message "Buffer is already a clone, not making another one")
12222 ;; we also do not modify visibility in this case
12223 buffer)
12224 (t ; make a new indirect buffer for displaying the link
12225 (let* ((bn (buffer-name buffer))
12226 (ibn (concat bn "(Clone)"))
12227 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
12228 (with-current-buffer ib (org-overview))
12229 ib))))
12231 (defun org-do-occur (regexp &optional cleanup)
12232 "Call the Emacs command `occur'.
12233 If CLEANUP is non-nil, remove the printout of the regular expression
12234 in the *Occur* buffer. This is useful if the regex is long and not useful
12235 to read."
12236 (occur regexp)
12237 (when cleanup
12238 (let ((cwin (selected-window)) win beg end)
12239 (when (setq win (get-buffer-window "*Occur*"))
12240 (select-window win))
12241 (goto-char (point-min))
12242 (when (re-search-forward "match[a-z]+" nil t)
12243 (setq beg (match-end 0))
12244 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
12245 (setq end (1- (match-beginning 0)))))
12246 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
12247 (goto-char (point-min))
12248 (select-window cwin))))
12250 ;;; The mark ring for links jumps
12252 (defvar org-mark-ring nil
12253 "Mark ring for positions before jumps in Org-mode.")
12254 (defvar org-mark-ring-last-goto nil
12255 "Last position in the mark ring used to go back.")
12256 ;; Fill and close the ring
12257 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
12258 (loop for i from 1 to org-mark-ring-length do
12259 (push (make-marker) org-mark-ring))
12260 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
12261 org-mark-ring)
12263 (defun org-mark-ring-push (&optional pos buffer)
12264 "Put the current position or POS into the mark ring and rotate it."
12265 (interactive)
12266 (setq pos (or pos (point)))
12267 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
12268 (move-marker (car org-mark-ring)
12269 (or pos (point))
12270 (or buffer (current-buffer)))
12271 (message
12272 (substitute-command-keys
12273 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
12275 (defun org-mark-ring-goto (&optional n)
12276 "Jump to the previous position in the mark ring.
12277 With prefix arg N, jump back that many stored positions. When
12278 called several times in succession, walk through the entire ring.
12279 Org-mode commands jumping to a different position in the current file,
12280 or to another Org-mode file, automatically push the old position
12281 onto the ring."
12282 (interactive "p")
12283 (let (p m)
12284 (if (eq last-command this-command)
12285 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
12286 (setq p org-mark-ring))
12287 (setq org-mark-ring-last-goto p)
12288 (setq m (car p))
12289 (switch-to-buffer (marker-buffer m))
12290 (goto-char m)
12291 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
12293 (defun org-remove-angle-brackets (s)
12294 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
12295 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
12297 (defun org-add-angle-brackets (s)
12298 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
12299 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
12302 ;;; Following specific links
12304 (defun org-follow-timestamp-link ()
12305 (cond
12306 ((org-at-date-range-p t)
12307 (let ((org-agenda-start-on-weekday)
12308 (t1 (match-string 1))
12309 (t2 (match-string 2)))
12310 (setq t1 (time-to-days (org-time-string-to-time t1))
12311 t2 (time-to-days (org-time-string-to-time t2)))
12312 (org-agenda-list nil t1 (1+ (- t2 t1)))))
12313 ((org-at-timestamp-p t)
12314 (org-agenda-list nil (time-to-days (org-time-string-to-time
12315 (substring (match-string 1) 0 10)))
12317 (t (error "This should not happen"))))
12320 (defun org-follow-bbdb-link (name)
12321 "Follow a BBDB link to NAME."
12322 (require 'bbdb)
12323 (let ((inhibit-redisplay (not debug-on-error))
12324 (bbdb-electric-p nil))
12325 (catch 'exit
12326 ;; Exact match on name
12327 (bbdb-name (concat "\\`" name "\\'") nil)
12328 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12329 ;; Exact match on name
12330 (bbdb-company (concat "\\`" name "\\'") nil)
12331 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12332 ;; Partial match on name
12333 (bbdb-name name nil)
12334 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12335 ;; Partial match on company
12336 (bbdb-company name nil)
12337 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12338 ;; General match including network address and notes
12339 (bbdb name nil)
12340 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
12341 (delete-window (get-buffer-window "*BBDB*"))
12342 (error "No matching BBDB record")))))
12344 (defun org-follow-info-link (name)
12345 "Follow an info file & node link to NAME."
12346 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
12347 (string-match "\\(.*\\)" name))
12348 (progn
12349 (require 'info)
12350 (if (match-string 2 name) ; If there isn't a node, choose "Top"
12351 (Info-find-node (match-string 1 name) (match-string 2 name))
12352 (Info-find-node (match-string 1 name) "Top")))
12353 (message (concat "Could not open: " name))))
12355 (defun org-follow-gnus-link (&optional group article)
12356 "Follow a Gnus link to GROUP and ARTICLE."
12357 (require 'gnus)
12358 (funcall (cdr (assq 'gnus org-link-frame-setup)))
12359 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
12360 (cond ((and group article)
12361 (gnus-group-read-group 1 nil group)
12362 (gnus-summary-goto-article (string-to-number article) nil t))
12363 (group (gnus-group-jump-to-group group))))
12365 (defun org-follow-vm-link (&optional folder article readonly)
12366 "Follow a VM link to FOLDER and ARTICLE."
12367 (require 'vm)
12368 (setq article (org-add-angle-brackets article))
12369 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
12370 ;; ange-ftp or efs or tramp access
12371 (let ((user (or (match-string 1 folder) (user-login-name)))
12372 (host (match-string 2 folder))
12373 (file (match-string 3 folder)))
12374 (cond
12375 ((featurep 'tramp)
12376 ;; use tramp to access the file
12377 (if (featurep 'xemacs)
12378 (setq folder (format "[%s@%s]%s" user host file))
12379 (setq folder (format "/%s@%s:%s" user host file))))
12381 ;; use ange-ftp or efs
12382 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
12383 (setq folder (format "/%s@%s:%s" user host file))))))
12384 (when folder
12385 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
12386 (sit-for 0.1)
12387 (when article
12388 (vm-select-folder-buffer)
12389 (widen)
12390 (let ((case-fold-search t))
12391 (goto-char (point-min))
12392 (if (not (re-search-forward
12393 (concat "^" "message-id: *" (regexp-quote article))))
12394 (error "Could not find the specified message in this folder"))
12395 (vm-isearch-update)
12396 (vm-isearch-narrow)
12397 (vm-beginning-of-message)
12398 (vm-summarize)))))
12400 (defun org-follow-wl-link (folder article)
12401 "Follow a Wanderlust link to FOLDER and ARTICLE."
12402 (if (and (string= folder "%")
12403 article
12404 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
12405 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
12406 ;; Thus, we recompose folder and article ids.
12407 (setq folder (format "%s#%s" folder (match-string 1 article))
12408 article (match-string 3 article)))
12409 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
12410 (error "No such folder: %s" folder))
12411 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
12412 (and article
12413 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
12414 (wl-summary-redisplay)))
12416 (defun org-follow-rmail-link (folder article)
12417 "Follow an RMAIL link to FOLDER and ARTICLE."
12418 (setq article (org-add-angle-brackets article))
12419 (let (message-number)
12420 (save-excursion
12421 (save-window-excursion
12422 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
12423 (setq message-number
12424 (save-restriction
12425 (widen)
12426 (goto-char (point-max))
12427 (if (re-search-backward
12428 (concat "^Message-ID:\\s-+" (regexp-quote
12429 (or article "")))
12430 nil t)
12431 (rmail-what-message))))))
12432 (if message-number
12433 (progn
12434 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
12435 (rmail-show-message message-number)
12436 message-number)
12437 (error "Message not found"))))
12439 ;;; mh-e integration based on planner-mode
12440 (defun org-mhe-get-message-real-folder ()
12441 "Return the name of the current message real folder, so if you use
12442 sequences, it will now work."
12443 (save-excursion
12444 (let* ((folder
12445 (if (equal major-mode 'mh-folder-mode)
12446 mh-current-folder
12447 ;; Refer to the show buffer
12448 mh-show-folder-buffer))
12449 (end-index
12450 (if (boundp 'mh-index-folder)
12451 (min (length mh-index-folder) (length folder))))
12453 ;; a simple test on mh-index-data does not work, because
12454 ;; mh-index-data is always nil in a show buffer.
12455 (if (and (boundp 'mh-index-folder)
12456 (string= mh-index-folder (substring folder 0 end-index)))
12457 (if (equal major-mode 'mh-show-mode)
12458 (save-window-excursion
12459 (let (pop-up-frames)
12460 (when (buffer-live-p (get-buffer folder))
12461 (progn
12462 (pop-to-buffer folder)
12463 (org-mhe-get-message-folder-from-index)
12466 (org-mhe-get-message-folder-from-index)
12468 folder
12472 (defun org-mhe-get-message-folder-from-index ()
12473 "Returns the name of the message folder in a index folder buffer."
12474 (save-excursion
12475 (mh-index-previous-folder)
12476 (re-search-forward "^\\(+.*\\)$" nil t)
12477 (message (match-string 1))))
12479 (defun org-mhe-get-message-folder ()
12480 "Return the name of the current message folder. Be careful if you
12481 use sequences."
12482 (save-excursion
12483 (if (equal major-mode 'mh-folder-mode)
12484 mh-current-folder
12485 ;; Refer to the show buffer
12486 mh-show-folder-buffer)))
12488 (defun org-mhe-get-message-num ()
12489 "Return the number of the current message. Be careful if you
12490 use sequences."
12491 (save-excursion
12492 (if (equal major-mode 'mh-folder-mode)
12493 (mh-get-msg-num nil)
12494 ;; Refer to the show buffer
12495 (mh-show-buffer-message-number))))
12497 (defun org-mhe-get-header (header)
12498 "Return a header of the message in folder mode. This will create a
12499 show buffer for the corresponding message. If you have a more clever
12500 idea..."
12501 (let* ((folder (org-mhe-get-message-folder))
12502 (num (org-mhe-get-message-num))
12503 (buffer (get-buffer-create (concat "show-" folder)))
12504 (header-field))
12505 (with-current-buffer buffer
12506 (mh-display-msg num folder)
12507 (if (equal major-mode 'mh-folder-mode)
12508 (mh-header-display)
12509 (mh-show-header-display))
12510 (set-buffer buffer)
12511 (setq header-field (mh-get-header-field header))
12512 (if (equal major-mode 'mh-folder-mode)
12513 (mh-show)
12514 (mh-show-show))
12515 header-field)))
12517 (defun org-follow-mhe-link (folder article)
12518 "Follow an MHE link to FOLDER and ARTICLE.
12519 If ARTICLE is nil FOLDER is shown. If the configuration variable
12520 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
12521 ARTICLE is searched in all folders. Indexed searches (swish++,
12522 namazu, and others supported by MH-E) will always search in all
12523 folders."
12524 (require 'mh-e)
12525 (require 'mh-search)
12526 (require 'mh-utils)
12527 (mh-find-path)
12528 (if (not article)
12529 (mh-visit-folder (mh-normalize-folder-name folder))
12530 (setq article (org-add-angle-brackets article))
12531 (mh-search-choose)
12532 (if (equal mh-searcher 'pick)
12533 (progn
12534 (mh-search folder (list "--message-id" article))
12535 (when (and org-mhe-search-all-folders
12536 (not (org-mhe-get-message-real-folder)))
12537 (kill-this-buffer)
12538 (mh-search "+" (list "--message-id" article))))
12539 (mh-search "+" article))
12540 (if (org-mhe-get-message-real-folder)
12541 (mh-show-msg 1)
12542 (kill-this-buffer)
12543 (error "Message not found"))))
12545 ;;; BibTeX links
12547 ;; Use the custom search meachnism to construct and use search strings for
12548 ;; file links to BibTeX database entries.
12550 (defun org-create-file-search-in-bibtex ()
12551 "Create the search string and description for a BibTeX database entry."
12552 (when (eq major-mode 'bibtex-mode)
12553 ;; yes, we want to construct this search string.
12554 ;; Make a good description for this entry, using names, year and the title
12555 ;; Put it into the `description' variable which is dynamically scoped.
12556 (let ((bibtex-autokey-names 1)
12557 (bibtex-autokey-names-stretch 1)
12558 (bibtex-autokey-name-case-convert-function 'identity)
12559 (bibtex-autokey-name-separator " & ")
12560 (bibtex-autokey-additional-names " et al.")
12561 (bibtex-autokey-year-length 4)
12562 (bibtex-autokey-name-year-separator " ")
12563 (bibtex-autokey-titlewords 3)
12564 (bibtex-autokey-titleword-separator " ")
12565 (bibtex-autokey-titleword-case-convert-function 'identity)
12566 (bibtex-autokey-titleword-length 'infty)
12567 (bibtex-autokey-year-title-separator ": "))
12568 (setq description (bibtex-generate-autokey)))
12569 ;; Now parse the entry, get the key and return it.
12570 (save-excursion
12571 (bibtex-beginning-of-entry)
12572 (cdr (assoc "=key=" (bibtex-parse-entry))))))
12574 (defun org-execute-file-search-in-bibtex (s)
12575 "Find the link search string S as a key for a database entry."
12576 (when (eq major-mode 'bibtex-mode)
12577 ;; Yes, we want to do the search in this file.
12578 ;; We construct a regexp that searches for "@entrytype{" followed by the key
12579 (goto-char (point-min))
12580 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
12581 (regexp-quote s) "[ \t\n]*,") nil t)
12582 (goto-char (match-beginning 0)))
12583 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
12584 ;; Use double prefix to indicate that any web link should be browsed
12585 (let ((b (current-buffer)) (p (point)))
12586 ;; Restore the window configuration because we just use the web link
12587 (set-window-configuration org-window-config-before-follow-link)
12588 (save-excursion (set-buffer b) (goto-char p)
12589 (bibtex-url)))
12590 (recenter 0)) ; Move entry start to beginning of window
12591 ;; return t to indicate that the search is done.
12594 ;; Finally add the functions to the right hooks.
12595 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
12596 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
12598 ;; end of Bibtex link setup
12600 ;;; Following file links
12602 (defun org-open-file (path &optional in-emacs line search)
12603 "Open the file at PATH.
12604 First, this expands any special file name abbreviations. Then the
12605 configuration variable `org-file-apps' is checked if it contains an
12606 entry for this file type, and if yes, the corresponding command is launched.
12607 If no application is found, Emacs simply visits the file.
12608 With optional argument IN-EMACS, Emacs will visit the file.
12609 Optional LINE specifies a line to go to, optional SEARCH a string to
12610 search for. If LINE or SEARCH is given, the file will always be
12611 opened in Emacs.
12612 If the file does not exist, an error is thrown."
12613 (setq in-emacs (or in-emacs line search))
12614 (let* ((file (if (equal path "")
12615 buffer-file-name
12616 (substitute-in-file-name (expand-file-name path))))
12617 (apps (append org-file-apps (org-default-apps)))
12618 (remp (and (assq 'remote apps) (org-file-remote-p file)))
12619 (dirp (if remp nil (file-directory-p file)))
12620 (dfile (downcase file))
12621 (old-buffer (current-buffer))
12622 (old-pos (point))
12623 (old-mode major-mode)
12624 ext cmd)
12625 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
12626 (setq ext (match-string 1 dfile))
12627 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
12628 (setq ext (match-string 1 dfile))))
12629 (if in-emacs
12630 (setq cmd 'emacs)
12631 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
12632 (and dirp (cdr (assoc 'directory apps)))
12633 (cdr (assoc ext apps))
12634 (cdr (assoc t apps)))))
12635 (when (eq cmd 'mailcap)
12636 (require 'mailcap)
12637 (mailcap-parse-mailcaps)
12638 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
12639 (command (mailcap-mime-info mime-type)))
12640 (if (stringp command)
12641 (setq cmd command)
12642 (setq cmd 'emacs))))
12643 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
12644 (not (file-exists-p file))
12645 (not org-open-non-existing-files))
12646 (error "No such file: %s" file))
12647 (cond
12648 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
12649 ;; Remove quotes around the file name - we'll use shell-quote-argument.
12650 (if (string-match "['\"]%s['\"]" cmd)
12651 (setq cmd (replace-match "%s" t t cmd)))
12652 (setq cmd (format cmd (shell-quote-argument file)))
12653 (save-window-excursion
12654 (start-process-shell-command cmd nil cmd)))
12655 ((or (stringp cmd)
12656 (eq cmd 'emacs))
12657 (funcall (cdr (assq 'file org-link-frame-setup)) file)
12658 (widen)
12659 (if line (goto-line line)
12660 (if search (org-link-search search))))
12661 ((consp cmd)
12662 (eval cmd))
12663 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
12664 (and (org-mode-p) (eq old-mode 'org-mode)
12665 (or (not (equal old-buffer (current-buffer)))
12666 (not (equal old-pos (point))))
12667 (org-mark-ring-push old-pos old-buffer))))
12669 (defun org-default-apps ()
12670 "Return the default applications for this operating system."
12671 (cond
12672 ((eq system-type 'darwin)
12673 org-file-apps-defaults-macosx)
12674 ((eq system-type 'windows-nt)
12675 org-file-apps-defaults-windowsnt)
12676 (t org-file-apps-defaults-gnu)))
12678 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
12679 (defun org-file-remote-p (file)
12680 "Test whether FILE specifies a location on a remote system.
12681 Return non-nil if the location is indeed remote.
12683 For example, the filename \"/user@host:/foo\" specifies a location
12684 on the system \"/user@host:\"."
12685 (cond ((fboundp 'file-remote-p)
12686 (file-remote-p file))
12687 ((fboundp 'tramp-handle-file-remote-p)
12688 (tramp-handle-file-remote-p file))
12689 ((and (boundp 'ange-ftp-name-format)
12690 (string-match (car ange-ftp-name-format) file))
12692 (t nil)))
12695 ;;;; Hooks for remember.el
12697 ;;;###autoload
12698 (defun org-remember-annotation ()
12699 "Return a link to the current location as an annotation for remember.el.
12700 If you are using Org-mode files as target for data storage with
12701 remember.el, then the annotations should include a link compatible with the
12702 conventions in Org-mode. This function returns such a link."
12703 (org-store-link nil))
12705 (defconst org-remember-help
12706 "Select a destination location for the note.
12707 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
12708 RET on headline -> Store as sublevel entry to current headline
12709 RET at beg-of-buf -> Append to file as level 2 headline
12710 <left>/<right> -> before/after current headline, same headings level")
12712 (defvar org-remember-previous-location nil)
12713 (defvar org-force-remember-template-char) ;; dynamically scoped
12715 ;;;###autoload
12716 (defun org-remember-apply-template (&optional use-char skip-interactive)
12717 "Initialize *remember* buffer with template, invoke `org-mode'.
12718 This function should be placed into `remember-mode-hook' and in fact requires
12719 to be run from that hook to fucntion properly."
12720 (if org-remember-templates
12721 (let* ((templates (mapcar (lambda (x)
12722 (if (stringp (car x))
12723 (append (list (nth 1 x) (car x)) (cddr x))
12724 (append (list (car x) "") (cdr x))))
12725 org-remember-templates))
12726 (char (or use-char
12727 (cond
12728 ((= (length templates) 1)
12729 (caar templates))
12730 ((and (boundp 'org-force-remember-template-char)
12731 org-force-remember-template-char)
12732 (if (stringp org-force-remember-template-char)
12733 (string-to-char org-force-remember-template-char)
12734 org-force-remember-template-char))
12736 (message "Select template: %s"
12737 (mapconcat
12738 (lambda (x)
12739 (cond
12740 ((not (string-match "\\S-" (nth 1 x)))
12741 (format "[%c]" (car x)))
12742 ((equal (downcase (car x))
12743 (downcase (aref (nth 1 x) 0)))
12744 (format "[%c]%s" (car x) (substring (nth 1 x) 1)))
12745 (t (format "[%c]%s" (car x) (nth 1 x)))))
12746 templates " "))
12747 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
12748 (when (equal char0 ?\C-g)
12749 (jump-to-register remember-register)
12750 (kill-buffer remember-buffer))
12751 char0)))))
12752 (entry (cddr (assoc char templates)))
12753 (tpl (car entry))
12754 (plist-p (if org-store-link-plist t nil))
12755 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
12756 (string-match "\\S-" (nth 1 entry)))
12757 (nth 1 entry)
12758 org-default-notes-file))
12759 (headline (nth 2 entry))
12760 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
12761 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
12762 (v-u (concat "[" (substring v-t 1 -1) "]"))
12763 (v-U (concat "[" (substring v-T 1 -1) "]"))
12764 ;; `initial' and `annotation' are bound in `remember'
12765 (v-i (if (boundp 'initial) initial))
12766 (v-a (if (and (boundp 'annotation) annotation)
12767 (if (equal annotation "[[]]") "" annotation)
12768 ""))
12769 (v-A (if (and v-a
12770 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
12771 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
12772 v-a))
12773 (v-n user-full-name)
12774 (org-startup-folded nil)
12775 org-time-was-given org-end-time-was-given x prompt char time)
12776 (setq org-store-link-plist
12777 (append (list :annotation v-a :initial v-i)
12778 org-store-link-plist))
12779 (unless tpl (setq tpl "") (message "No template") (ding))
12780 (erase-buffer)
12781 (insert (substitute-command-keys
12782 (format
12783 "## Filing location: Select interactively, default, or last used:
12784 ## %s to select file and header location interactively.
12785 ## %s \"%s\" -> \"* %s\"
12786 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
12787 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
12788 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
12789 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
12790 (abbreviate-file-name (or file org-default-notes-file))
12791 (or headline "")
12792 (or (car org-remember-previous-location) "???")
12793 (or (cdr org-remember-previous-location) "???"))))
12794 (insert tpl) (goto-char (point-min))
12795 ;; Simple %-escapes
12796 (while (re-search-forward "%\\([tTuUaiA]\\)" nil t)
12797 (when (and initial (equal (match-string 0) "%i"))
12798 (save-match-data
12799 (let* ((lead (buffer-substring
12800 (point-at-bol) (match-beginning 0))))
12801 (setq v-i (mapconcat 'identity
12802 (org-split-string initial "\n")
12803 (concat "\n" lead))))))
12804 (replace-match
12805 (or (eval (intern (concat "v-" (match-string 1)))) "")
12806 t t))
12807 ;; From the property list
12808 (when plist-p
12809 (goto-char (point-min))
12810 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
12811 (and (setq x (plist-get org-store-link-plist
12812 (intern (match-string 1))))
12813 (replace-match x t t))))
12814 ;; Turn on org-mode in the remember buffer, set local variables
12815 (org-mode)
12816 (org-set-local 'org-finish-function 'remember-buffer)
12817 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
12818 (org-set-local 'org-default-notes-file file))
12819 (if (and headline (stringp headline) (string-match "\\S-" headline))
12820 (org-set-local 'org-remember-default-headline headline))
12821 ;; Interactive template entries
12822 (goto-char (point-min))
12823 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([guUtT]\\)?" nil t)
12824 (setq char (if (match-end 3) (match-string 3))
12825 prompt (if (match-end 2) (match-string 2)))
12826 (goto-char (match-beginning 0))
12827 (replace-match "")
12828 (cond
12829 ((member char '("G" "g"))
12830 (let* ((org-last-tags-completion-table
12831 (org-global-tags-completion-table
12832 (if (equal char "G") (org-agenda-files) (and file (list file)))))
12833 (org-add-colon-after-tag-completion t)
12834 (ins (completing-read
12835 (if prompt (concat prompt ": ") "Tags: ")
12836 'org-tags-completion-function nil nil nil
12837 'org-tags-history)))
12838 (setq ins (mapconcat 'identity
12839 (org-split-string ins (org-re "[^[:alnum:]]+"))
12840 ":"))
12841 (when (string-match "\\S-" ins)
12842 (or (equal (char-before) ?:) (insert ":"))
12843 (insert ins)
12844 (or (equal (char-after) ?:) (insert ":")))))
12845 (char
12846 (setq org-time-was-given (equal (upcase char) char))
12847 (setq time (org-read-date (equal (upcase char) "U") t nil
12848 prompt))
12849 (org-insert-time-stamp time org-time-was-given
12850 (member char '("u" "U"))
12851 nil nil (list org-end-time-was-given)))
12853 (insert (read-string
12854 (if prompt (concat prompt ": ") "Enter string"))))))
12855 (goto-char (point-min))
12856 (if (re-search-forward "%\\?" nil t)
12857 (replace-match "")
12858 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
12859 (org-mode)
12860 (org-set-local 'org-finish-function 'remember-buffer)))
12862 ;;;###autoload
12863 (defun org-remember (&optional org-force-remember-template-char)
12864 "Call `remember'. If this is already a remember buffer, re-apply template.
12865 If there is an active region, make sure remember uses it as initial content
12866 of the remember buffer."
12867 (interactive)
12868 (if (eq org-finish-function 'remember-buffer)
12869 (progn
12870 (when (< (length org-remember-templates) 2)
12871 (error "No other template available"))
12872 (erase-buffer)
12873 (let ((annotation (plist-get org-store-link-plist :annotation))
12874 (initial (plist-get org-store-link-plist :initial)))
12875 (org-remember-apply-template))
12876 (message "Press C-c C-c to remember data"))
12877 (if (org-region-active-p)
12878 (remember (buffer-substring (point) (mark)))
12879 (call-interactively 'remember))))
12881 (defvar org-note-abort nil) ; dynamically scoped
12883 ;;;###autoload
12884 (defun org-remember-handler ()
12885 "Store stuff from remember.el into an org file.
12886 First prompts for an org file. If the user just presses return, the value
12887 of `org-default-notes-file' is used.
12888 Then the command offers the headings tree of the selected file in order to
12889 file the text at a specific location.
12890 You can either immediately press RET to get the note appended to the
12891 file, or you can use vertical cursor motion and visibility cycling (TAB) to
12892 find a better place. Then press RET or <left> or <right> in insert the note.
12894 Key Cursor position Note gets inserted
12895 -----------------------------------------------------------------------------
12896 RET buffer-start as level 1 heading at end of file
12897 RET on headline as sublevel of the heading at cursor
12898 RET no heading at cursor position, level taken from context.
12899 Or use prefix arg to specify level manually.
12900 <left> on headline as same level, before current heading
12901 <right> on headline as same level, after current heading
12903 So the fastest way to store the note is to press RET RET to append it to
12904 the default file. This way your current train of thought is not
12905 interrupted, in accordance with the principles of remember.el.
12906 You can also get the fast execution without prompting by using
12907 C-u C-c C-c to exit the remember buffer. See also the variable
12908 `org-remember-store-without-prompt'.
12910 Before being stored away, the function ensures that the text has a
12911 headline, i.e. a first line that starts with a \"*\". If not, a headline
12912 is constructed from the current date and some additional data.
12914 If the variable `org-adapt-indentation' is non-nil, the entire text is
12915 also indented so that it starts in the same column as the headline
12916 \(i.e. after the stars).
12918 See also the variable `org-reverse-note-order'."
12919 (goto-char (point-min))
12920 (while (looking-at "^[ \t]*\n\\|^##.*\n")
12921 (replace-match ""))
12922 (goto-char (point-max))
12923 (unless (equal (char-before) ?\n) (insert "\n"))
12924 (catch 'quit
12925 (if org-note-abort (throw 'quit nil))
12926 (let* ((txt (buffer-substring (point-min) (point-max)))
12927 (fastp (org-xor (equal current-prefix-arg '(4))
12928 org-remember-store-without-prompt))
12929 (file (if fastp org-default-notes-file (org-get-org-file)))
12930 (heading org-remember-default-headline)
12931 (visiting (org-find-base-buffer-visiting file))
12932 (org-startup-folded nil)
12933 (org-startup-align-all-tables nil)
12934 (org-goto-start-pos 1)
12935 spos exitcmd level indent reversed)
12936 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
12937 (setq file (car org-remember-previous-location)
12938 heading (cdr org-remember-previous-location)))
12939 (setq current-prefix-arg nil)
12940 ;; Modify text so that it becomes a nice subtree which can be inserted
12941 ;; into an org tree.
12942 (let* ((lines (split-string txt "\n"))
12943 first)
12944 (setq first (car lines) lines (cdr lines))
12945 (if (string-match "^\\*+ " first)
12946 ;; Is already a headline
12947 (setq indent nil)
12948 ;; We need to add a headline: Use time and first buffer line
12949 (setq lines (cons first lines)
12950 first (concat "* " (current-time-string)
12951 " (" (remember-buffer-desc) ")")
12952 indent " "))
12953 (if (and org-adapt-indentation indent)
12954 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
12955 (setq txt (concat first "\n"
12956 (mapconcat 'identity lines "\n"))))
12957 ;; Find the file
12958 (if (not visiting) (find-file-noselect file))
12959 (with-current-buffer (or visiting (get-file-buffer file))
12960 (unless (org-mode-p)
12961 (error "Target files for remember notes must be in Org-mode"))
12962 (save-excursion
12963 (save-restriction
12964 (widen)
12965 (and (goto-char (point-min))
12966 (not (re-search-forward "^\\* " nil t))
12967 (insert "\n* " (or heading "Notes") "\n"))
12968 (setq reversed (org-notes-order-reversed-p))
12970 ;; Find the default location
12971 (when (and heading (stringp heading) (string-match "\\S-" heading))
12972 (goto-char (point-min))
12973 (if (re-search-forward
12974 (concat "^\\*+[ \t]+" (regexp-quote heading)
12975 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
12976 nil t)
12977 (setq org-goto-start-pos (match-beginning 0))
12978 (when fastp
12979 (goto-char (point-max))
12980 (unless (bolp) (newline))
12981 (insert "* " heading "\n")
12982 (setq org-goto-start-pos (point-at-bol 0)))))
12984 ;; Ask the User for a location
12985 (if fastp
12986 (setq spos org-goto-start-pos
12987 exitcmd 'return)
12988 (setq spos (org-get-location (current-buffer) org-remember-help)
12989 exitcmd (cdr spos)
12990 spos (car spos)))
12991 (if (not spos) (throw 'quit nil)) ; return nil to show we did
12992 ; not handle this note
12993 (goto-char spos)
12994 (cond ((org-on-heading-p t)
12995 (org-back-to-heading t)
12996 (setq level (funcall outline-level))
12997 (cond
12998 ((eq exitcmd 'return)
12999 ;; sublevel of current
13000 (setq org-remember-previous-location
13001 (cons (abbreviate-file-name file)
13002 (org-get-heading 'notags)))
13003 (if reversed
13004 (outline-next-heading)
13005 (org-end-of-subtree)
13006 (if (not (bolp))
13007 (if (looking-at "[ \t]*\n")
13008 (beginning-of-line 2)
13009 (end-of-line 1)
13010 (insert "\n"))))
13011 (org-paste-subtree (org-get-legal-level level 1) txt))
13012 ((eq exitcmd 'left)
13013 ;; before current
13014 (org-paste-subtree level txt))
13015 ((eq exitcmd 'right)
13016 ;; after current
13017 (org-end-of-subtree t)
13018 (org-paste-subtree level txt))
13019 (t (error "This should not happen"))))
13021 ((and (bobp) (not reversed))
13022 ;; Put it at the end, one level below level 1
13023 (save-restriction
13024 (widen)
13025 (goto-char (point-max))
13026 (if (not (bolp)) (newline))
13027 (org-paste-subtree (org-get-legal-level 1 1) txt)))
13029 ((and (bobp) reversed)
13030 ;; Put it at the start, as level 1
13031 (save-restriction
13032 (widen)
13033 (goto-char (point-min))
13034 (re-search-forward "^\\*+ " nil t)
13035 (beginning-of-line 1)
13036 (org-paste-subtree 1 txt)))
13038 ;; Put it right there, with automatic level determined by
13039 ;; org-paste-subtree or from prefix arg
13040 (org-paste-subtree
13041 (if (numberp current-prefix-arg) current-prefix-arg)
13042 txt)))
13043 (when remember-save-after-remembering
13044 (save-buffer)
13045 (if (not visiting) (kill-buffer (current-buffer)))))))))
13046 t) ;; return t to indicate that we took care of this note.
13048 (defun org-get-org-file ()
13049 "Read a filename, with default directory `org-directory'."
13050 (let ((default (or org-default-notes-file remember-data-file)))
13051 (read-file-name (format "File name [%s]: " default)
13052 (file-name-as-directory org-directory)
13053 default)))
13055 (defun org-notes-order-reversed-p ()
13056 "Check if the current file should receive notes in reversed order."
13057 (cond
13058 ((not org-reverse-note-order) nil)
13059 ((eq t org-reverse-note-order) t)
13060 ((not (listp org-reverse-note-order)) nil)
13061 (t (catch 'exit
13062 (let ((all org-reverse-note-order)
13063 entry)
13064 (while (setq entry (pop all))
13065 (if (string-match (car entry) buffer-file-name)
13066 (throw 'exit (cdr entry))))
13067 nil)))))
13069 ;;;; Dynamic blocks
13071 (defun org-find-dblock (name)
13072 "Find the first dynamic block with name NAME in the buffer.
13073 If not found, stay at current position and return nil."
13074 (let (pos)
13075 (save-excursion
13076 (goto-char (point-min))
13077 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
13078 nil t)
13079 (match-beginning 0))))
13080 (if pos (goto-char pos))
13081 pos))
13083 (defconst org-dblock-start-re
13084 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
13085 "Matches the startline of a dynamic block, with parameters.")
13087 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
13088 "Matches the end of a dyhamic block.")
13090 (defun org-create-dblock (plist)
13091 "Create a dynamic block section, with parameters taken from PLIST.
13092 PLIST must containe a :name entry which is used as name of the block."
13093 (unless (bolp) (newline))
13094 (let ((name (plist-get plist :name)))
13095 (insert "#+BEGIN: " name)
13096 (while plist
13097 (if (eq (car plist) :name)
13098 (setq plist (cddr plist))
13099 (insert " " (prin1-to-string (pop plist)))))
13100 (insert "\n\n#+END:\n")
13101 (beginning-of-line -2)))
13103 (defun org-prepare-dblock ()
13104 "Prepare dynamic block for refresh.
13105 This empties the block, puts the cursor at the insert position and returns
13106 the property list including an extra property :name with the block name."
13107 (unless (looking-at org-dblock-start-re)
13108 (error "Not at a dynamic block"))
13109 (let* ((begdel (1+ (match-end 0)))
13110 (name (org-no-properties (match-string 1)))
13111 (params (append (list :name name)
13112 (read (concat "(" (match-string 3) ")")))))
13113 (unless (re-search-forward org-dblock-end-re nil t)
13114 (error "Dynamic block not terminated"))
13115 (delete-region begdel (match-beginning 0))
13116 (goto-char begdel)
13117 (open-line 1)
13118 params))
13120 (defun org-map-dblocks (&optional command)
13121 "Apply COMMAND to all dynamic blocks in the current buffer.
13122 If COMMAND is not given, use `org-update-dblock'."
13123 (let ((cmd (or command 'org-update-dblock))
13124 pos)
13125 (save-excursion
13126 (goto-char (point-min))
13127 (while (re-search-forward org-dblock-start-re nil t)
13128 (goto-char (setq pos (match-beginning 0)))
13129 (condition-case nil
13130 (funcall cmd)
13131 (error (message "Error during update of dynamic block")))
13132 (goto-char pos)
13133 (unless (re-search-forward org-dblock-end-re nil t)
13134 (error "Dynamic block not terminated"))))))
13136 (defun org-dblock-update (&optional arg)
13137 "User command for updating dynamic blocks.
13138 Update the dynamic block at point. With prefix ARG, update all dynamic
13139 blocks in the buffer."
13140 (interactive "P")
13141 (if arg
13142 (org-update-all-dblocks)
13143 (or (looking-at org-dblock-start-re)
13144 (org-beginning-of-dblock))
13145 (org-update-dblock)))
13147 (defun org-update-dblock ()
13148 "Update the dynamic block at point
13149 This means to empty the block, parse for parameters and then call
13150 the correct writing function."
13151 (save-window-excursion
13152 (let* ((pos (point))
13153 (line (org-current-line))
13154 (params (org-prepare-dblock))
13155 (name (plist-get params :name))
13156 (cmd (intern (concat "org-dblock-write:" name))))
13157 (message "Updating dynamic block `%s' at line %d..." name line)
13158 (funcall cmd params)
13159 (message "Updating dynamic block `%s' at line %d...done" name line)
13160 (goto-char pos))))
13162 (defun org-beginning-of-dblock ()
13163 "Find the beginning of the dynamic block at point.
13164 Error if there is no scuh block at point."
13165 (let ((pos (point))
13166 beg)
13167 (end-of-line 1)
13168 (if (and (re-search-backward org-dblock-start-re nil t)
13169 (setq beg (match-beginning 0))
13170 (re-search-forward org-dblock-end-re nil t)
13171 (> (match-end 0) pos))
13172 (goto-char beg)
13173 (goto-char pos)
13174 (error "Not in a dynamic block"))))
13176 (defun org-update-all-dblocks ()
13177 "Update all dynamic blocks in the buffer.
13178 This function can be used in a hook."
13179 (when (org-mode-p)
13180 (org-map-dblocks 'org-update-dblock)))
13183 ;;;; Completion
13185 (defconst org-additional-option-like-keywords
13186 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
13187 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:"))
13189 (defun org-complete (&optional arg)
13190 "Perform completion on word at point.
13191 At the beginning of a headline, this completes TODO keywords as given in
13192 `org-todo-keywords'.
13193 If the current word is preceded by a backslash, completes the TeX symbols
13194 that are supported for HTML support.
13195 If the current word is preceded by \"#+\", completes special words for
13196 setting file options.
13197 In the line after \"#+STARTUP:, complete valid keywords.\"
13198 At all other locations, this simply calls the value of
13199 `org-completion-fallback-command'."
13200 (interactive "P")
13201 (org-without-partial-completion
13202 (catch 'exit
13203 (let* ((end (point))
13204 (beg1 (save-excursion
13205 (skip-chars-backward (org-re "[:alnum:]_@"))
13206 (point)))
13207 (beg (save-excursion
13208 (skip-chars-backward "a-zA-Z0-9_:$")
13209 (point)))
13210 (confirm (lambda (x) (stringp (car x))))
13211 (searchhead (equal (char-before beg) ?*))
13212 (tag (and (equal (char-before beg1) ?:)
13213 (equal (char-after (point-at-bol)) ?*)))
13214 (prop (and (equal (char-before beg1) ?:)
13215 (not (equal (char-after (point-at-bol)) ?*))))
13216 (texp (equal (char-before beg) ?\\))
13217 (link (equal (char-before beg) ?\[))
13218 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
13219 beg)
13220 "#+"))
13221 (startup (string-match "^#\\+STARTUP:.*"
13222 (buffer-substring (point-at-bol) (point))))
13223 (completion-ignore-case opt)
13224 (type nil)
13225 (tbl nil)
13226 (table (cond
13227 (opt
13228 (setq type :opt)
13229 (append
13230 (mapcar
13231 (lambda (x)
13232 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
13233 (cons (match-string 2 x) (match-string 1 x)))
13234 (org-split-string (org-get-current-options) "\n"))
13235 (mapcar 'list org-additional-option-like-keywords)))
13236 (startup
13237 (setq type :startup)
13238 org-startup-options)
13239 (link (append org-link-abbrev-alist-local
13240 org-link-abbrev-alist))
13241 (texp
13242 (setq type :tex)
13243 org-html-entities)
13244 ((string-match "\\`\\*+[ \t]+\\'"
13245 (buffer-substring (point-at-bol) beg))
13246 (setq type :todo)
13247 (mapcar 'list org-todo-keywords-1))
13248 (searchhead
13249 (setq type :searchhead)
13250 (save-excursion
13251 (goto-char (point-min))
13252 (while (re-search-forward org-todo-line-regexp nil t)
13253 (push (list
13254 (org-make-org-heading-search-string
13255 (match-string 3) t))
13256 tbl)))
13257 tbl)
13258 (tag (setq type :tag beg beg1)
13259 (or org-tag-alist (org-get-buffer-tags)))
13260 (prop (setq type :prop beg beg1)
13261 (mapcar 'list (org-buffer-property-keys)))
13262 (t (progn
13263 (call-interactively org-completion-fallback-command)
13264 (throw 'exit nil)))))
13265 (pattern (buffer-substring-no-properties beg end))
13266 (completion (try-completion pattern table confirm)))
13267 (cond ((eq completion t)
13268 (if (not (assoc (upcase pattern) table))
13269 (message "Already complete")
13270 (if (equal type :opt)
13271 (insert (substring (cdr (assoc (upcase pattern) table))
13272 (length pattern)))
13273 (if (memq type '(:tag :prop)) (insert ":")))))
13274 ((null completion)
13275 (message "Can't find completion for \"%s\"" pattern)
13276 (ding))
13277 ((not (string= pattern completion))
13278 (delete-region beg end)
13279 (if (string-match " +$" completion)
13280 (setq completion (replace-match "" t t completion)))
13281 (insert completion)
13282 (if (get-buffer-window "*Completions*")
13283 (delete-window (get-buffer-window "*Completions*")))
13284 (if (assoc completion table)
13285 (if (eq type :todo) (insert " ")
13286 (if (memq type '(:tag :prop)) (insert ":"))))
13287 (if (and (equal type :opt) (assoc completion table))
13288 (message "%s" (substitute-command-keys
13289 "Press \\[org-complete] again to insert example settings"))))
13291 (message "Making completion list...")
13292 (let ((list (sort (all-completions pattern table confirm)
13293 'string<)))
13294 (with-output-to-temp-buffer "*Completions*"
13295 (condition-case nil
13296 ;; Protection needed for XEmacs and emacs 21
13297 (display-completion-list list pattern)
13298 (error (display-completion-list list)))))
13299 (message "Making completion list...%s" "done")))))))
13301 ;;;; TODO, DEADLINE, Comments
13303 (defun org-toggle-comment ()
13304 "Change the COMMENT state of an entry."
13305 (interactive)
13306 (save-excursion
13307 (org-back-to-heading)
13308 (if (looking-at (concat outline-regexp
13309 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
13310 (replace-match "" t t nil 1)
13311 (if (looking-at outline-regexp)
13312 (progn
13313 (goto-char (match-end 0))
13314 (insert org-comment-string " "))))))
13316 (defvar org-last-todo-state-is-todo nil
13317 "This is non-nil when the last TODO state change led to a TODO state.
13318 If the last change removed the TODO tag or switched to DONE, then
13319 this is nil.")
13321 (defvar org-setting-tags nil) ; dynamically skiped
13323 ;; FIXME: better place
13324 (defun org-property-or-variable-value (var &optional inherit)
13325 "Check if there is a property fixing the value of VAR.
13326 If yes, return this value. If not, return the current value of the variable."
13327 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13328 (if (and prop (stringp prop) (string-match "\\S-" prop))
13329 (read prop)
13330 (symbol-value var))))
13332 (defun org-parse-local-options (string var)
13333 "Parse STRING for startup setting relevant for variable VAR."
13334 (let ((rtn (symbol-value var))
13335 e opts)
13336 (save-match-data
13337 (if (or (not string) (not (string-match "\\S-" string)))
13339 (setq opts (delq nil (mapcar (lambda (x)
13340 (setq e (assoc x org-startup-options))
13341 (if (eq (nth 1 e) var) e nil))
13342 (org-split-string string "[ \t]+"))))
13343 (if (not opts)
13345 (setq rtn nil)
13346 (while (setq e (pop opts))
13347 (if (not (nth 3 e))
13348 (setq rtn (nth 2 e))
13349 (if (not (listp rtn)) (setq rtn nil))
13350 (push (nth 2 e) rtn)))
13351 rtn)))))
13353 (defvar org-blocker-hook nil
13354 "Hook for functions that are allowed to block a state change.
13356 Each function gets as its single argument a property list, see
13357 `org-trigger-hook' for more information about this list.
13359 If any of the functions in this hook returns nil, the state change
13360 is blocked.")
13362 (defvar org-trigger-hook nil
13363 "Hook for functions that are triggered by a state change.
13365 Each function gets as its single argument a property list with at least
13366 the following elements:
13368 (:type type-of-change :position pos-at-entry-start
13369 :from old-state :to new-state)
13371 Depending on the type, more properties may be present.
13373 This mechanism is currently implemented for:
13375 TODO state changes
13376 ------------------
13377 :type todo-state-change
13378 :from previous state (keyword as a string), or nil
13379 :to new state (keyword as a string), or nil")
13382 (defun org-todo (&optional arg)
13383 "Change the TODO state of an item.
13384 The state of an item is given by a keyword at the start of the heading,
13385 like
13386 *** TODO Write paper
13387 *** DONE Call mom
13389 The different keywords are specified in the variable `org-todo-keywords'.
13390 By default the available states are \"TODO\" and \"DONE\".
13391 So for this example: when the item starts with TODO, it is changed to DONE.
13392 When it starts with DONE, the DONE is removed. And when neither TODO nor
13393 DONE are present, add TODO at the beginning of the heading.
13395 With C-u prefix arg, use completion to determine the new state.
13396 With numeric prefix arg, switch to that state.
13398 For calling through lisp, arg is also interpreted in the following way:
13399 'none -> empty state
13400 \"\"(empty string) -> switch to empty state
13401 'done -> switch to DONE
13402 'nextset -> switch to the next set of keywords
13403 'previousset -> switch to the previous set of keywords
13404 \"WAITING\" -> switch to the specified keyword, but only if it
13405 really is a member of `org-todo-keywords'."
13406 (interactive "P")
13407 (save-excursion
13408 (catch 'exit
13409 (org-back-to-heading)
13410 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
13411 (or (looking-at (concat " +" org-todo-regexp " *"))
13412 (looking-at " *"))
13413 (let* ((startpos (line-beginning-position))
13414 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
13415 (org-log-done (org-parse-local-options logging 'org-log-done))
13416 (org-log-repeat (org-parse-local-options logging 'org-log-repeat))
13417 (this (match-string 1))
13418 (hl-pos (match-beginning 0))
13419 (head (org-get-todo-sequence-head this))
13420 (ass (assoc head org-todo-kwd-alist))
13421 (interpret (nth 1 ass))
13422 (done-word (nth 3 ass))
13423 (final-done-word (nth 4 ass))
13424 (last-state (or this ""))
13425 (completion-ignore-case t)
13426 (member (member this org-todo-keywords-1))
13427 (tail (cdr member))
13428 (state (cond
13429 ((and org-todo-key-trigger
13430 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
13431 (and (not arg) org-use-fast-todo-selection
13432 (not (eq org-use-fast-todo-selection 'prefix)))))
13433 ;; Use fast selection
13434 (org-fast-todo-selection))
13435 ((and (equal arg '(4))
13436 (or (not org-use-fast-todo-selection)
13437 (not org-todo-key-trigger)))
13438 ;; Read a state with completion
13439 (completing-read "State: " (mapcar (lambda(x) (list x))
13440 org-todo-keywords-1)
13441 nil t))
13442 ((eq arg 'right)
13443 (if this
13444 (if tail (car tail) nil)
13445 (car org-todo-keywords-1)))
13446 ((eq arg 'left)
13447 (if (equal member org-todo-keywords-1)
13449 (if this
13450 (nth (- (length org-todo-keywords-1) (length tail) 2)
13451 org-todo-keywords-1)
13452 (org-last org-todo-keywords-1))))
13453 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
13454 (setq arg nil))) ; hack to fall back to cycling
13455 (arg
13456 ;; user or caller requests a specific state
13457 (cond
13458 ((equal arg "") nil)
13459 ((eq arg 'none) nil)
13460 ((eq arg 'done) (or done-word (car org-done-keywords)))
13461 ((eq arg 'nextset)
13462 (or (car (cdr (member head org-todo-heads)))
13463 (car org-todo-heads)))
13464 ((eq arg 'previousset)
13465 (let ((org-todo-heads (reverse org-todo-heads)))
13466 (or (car (cdr (member head org-todo-heads)))
13467 (car org-todo-heads))))
13468 ((car (member arg org-todo-keywords-1)))
13469 ((nth (1- (prefix-numeric-value arg))
13470 org-todo-keywords-1))))
13471 ((null member) (or head (car org-todo-keywords-1)))
13472 ((equal this final-done-word) nil) ;; -> make empty
13473 ((null tail) nil) ;; -> first entry
13474 ((eq interpret 'sequence)
13475 (car tail))
13476 ((memq interpret '(type priority))
13477 (if (eq this-command last-command)
13478 (car tail)
13479 (if (> (length tail) 0)
13480 (or done-word (car org-done-keywords))
13481 nil)))
13482 (t nil)))
13483 (next (if state (concat " " state " ") " "))
13484 (change-plist (list :type 'todo-state-change :from this :to state
13485 :position startpos))
13486 dostates)
13487 (when org-blocker-hook
13488 (unless (save-excursion
13489 (save-match-data
13490 (run-hook-with-args-until-failure
13491 'org-blocker-hook change-plist)))
13492 (if (interactive-p)
13493 (error "TODO state change from %s to %s blocked" this state)
13494 ;; fail silently
13495 (message "TODO state change from %s to %s blocked" this state)
13496 (throw 'exit nil))))
13497 (replace-match next t t)
13498 (unless (pos-visible-in-window-p hl-pos)
13499 (message "TODO state changed to %s" (org-trim next)))
13500 (unless head
13501 (setq head (org-get-todo-sequence-head state)
13502 ass (assoc head org-todo-kwd-alist)
13503 interpret (nth 1 ass)
13504 done-word (nth 3 ass)
13505 final-done-word (nth 4 ass)))
13506 (when (memq arg '(nextset previousset))
13507 (message "Keyword-Set %d/%d: %s"
13508 (- (length org-todo-sets) -1
13509 (length (memq (assoc state org-todo-sets) org-todo-sets)))
13510 (length org-todo-sets)
13511 (mapconcat 'identity (assoc state org-todo-sets) " ")))
13512 (setq org-last-todo-state-is-todo
13513 (not (member state org-done-keywords)))
13514 (when (and org-log-done (not (memq arg '(nextset previousset))))
13515 (setq dostates (and (listp org-log-done) (memq 'state org-log-done)
13516 (or (not org-todo-log-states)
13517 (member state org-todo-log-states))))
13519 (cond
13520 ((and state (member state org-not-done-keywords)
13521 (not (member this org-not-done-keywords)))
13522 ;; This is now a todo state and was not one before
13523 ;; Remove any CLOSED timestamp, and possibly log the state change
13524 (org-add-planning-info nil nil 'closed)
13525 (and dostates (org-add-log-maybe 'state state 'findpos)))
13526 ((and state dostates)
13527 ;; This is a non-nil state, and we need to log it
13528 (org-add-log-maybe 'state state 'findpos))
13529 ((and (member state org-done-keywords)
13530 (not (member this org-done-keywords)))
13531 ;; It is now done, and it was not done before
13532 (org-add-planning-info 'closed (org-current-time))
13533 (org-add-log-maybe 'done state 'findpos))))
13534 ;; Fixup tag positioning
13535 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
13536 (run-hooks 'org-after-todo-state-change-hook)
13537 (and (member state org-done-keywords) (org-auto-repeat-maybe))
13538 (if (and arg (not (member state org-done-keywords)))
13539 (setq head (org-get-todo-sequence-head state)))
13540 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
13541 ;; Fixup cursor location if close to the keyword
13542 (if (and (outline-on-heading-p)
13543 (not (bolp))
13544 (save-excursion (beginning-of-line 1)
13545 (looking-at org-todo-line-regexp))
13546 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
13547 (progn
13548 (goto-char (or (match-end 2) (match-end 1)))
13549 (just-one-space)))
13550 (when org-trigger-hook
13551 (save-excursion
13552 (run-hook-with-args 'org-trigger-hook change-plist)))))))
13554 (defun org-get-todo-sequence-head (kwd)
13555 "Return the head of the TODO sequence to which KWD belongs.
13556 If KWD is not set, check if there is a text property remembering the
13557 right sequence."
13558 (let (p)
13559 (cond
13560 ((not kwd)
13561 (or (get-text-property (point-at-bol) 'org-todo-head)
13562 (progn
13563 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13564 nil (point-at-eol)))
13565 (get-text-property p 'org-todo-head))))
13566 ((not (member kwd org-todo-keywords-1))
13567 (car org-todo-keywords-1))
13568 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13570 (defun org-fast-todo-selection ()
13571 "Fast TODO keyword selection with single keys.
13572 Returns the new TODO keyword, or nil if no state change should occur."
13573 (let* ((fulltable org-todo-key-alist)
13574 (done-keywords org-done-keywords) ;; needed for the faces.
13575 (maxlen (apply 'max (mapcar
13576 (lambda (x)
13577 (if (stringp (car x)) (string-width (car x)) 0))
13578 fulltable)))
13579 (expert nil)
13580 (fwidth (+ maxlen 3 1 3))
13581 (ncol (/ (- (window-width) 4) fwidth))
13582 tg cnt e c tbl
13583 groups ingroup)
13584 (save-window-excursion
13585 (if expert
13586 (set-buffer (get-buffer-create " *Org todo*"))
13587 ; (delete-other-windows)
13588 ; (split-window-vertically)
13589 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13590 (erase-buffer)
13591 (org-set-local 'org-done-keywords done-keywords)
13592 (setq tbl fulltable cnt 0)
13593 (while (setq e (pop tbl))
13594 (cond
13595 ((equal e '(:startgroup))
13596 (push '() groups) (setq ingroup t)
13597 (when (not (= cnt 0))
13598 (setq cnt 0)
13599 (insert "\n"))
13600 (insert "{ "))
13601 ((equal e '(:endgroup))
13602 (setq ingroup nil cnt 0)
13603 (insert "}\n"))
13605 (setq tg (car e) c (cdr e))
13606 (if ingroup (push tg (car groups)))
13607 (setq tg (org-add-props tg nil 'face
13608 (org-get-todo-face tg)))
13609 (if (and (= cnt 0) (not ingroup)) (insert " "))
13610 (insert "[" c "] " tg (make-string
13611 (- fwidth 4 (length tg)) ?\ ))
13612 (when (= (setq cnt (1+ cnt)) ncol)
13613 (insert "\n")
13614 (if ingroup (insert " "))
13615 (setq cnt 0)))))
13616 (insert "\n")
13617 (goto-char (point-min))
13618 (if (and (not expert) (fboundp 'fit-window-to-buffer))
13619 (fit-window-to-buffer))
13620 (message "[a-z..]:Set [SPC]:clear")
13621 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13622 (cond
13623 ((or (= c ?\C-g)
13624 (and (= c ?q) (not (rassoc c fulltable))))
13625 (setq quit-flag t))
13626 ((= c ?\ ) nil)
13627 ((setq e (rassoc c fulltable) tg (car e))
13629 (t (setq quit-flag t))))))
13631 (defun org-get-repeat ()
13632 "Check if tere is a deadline/schedule with repeater in this entry."
13633 (save-match-data
13634 (save-excursion
13635 (org-back-to-heading t)
13636 (if (re-search-forward
13637 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
13638 (match-string 1)))))
13640 (defvar org-last-changed-timestamp)
13641 (defvar org-log-post-message)
13642 (defun org-auto-repeat-maybe ()
13643 "Check if the current headline contains a repeated deadline/schedule.
13644 If yes, set TODO state back to what it was and change the base date
13645 of repeating deadline/scheduled time stamps to new date.
13646 This function should be run in the `org-after-todo-state-change-hook'."
13647 ;; last-state is dynamically scoped into this function
13648 (let* ((repeat (org-get-repeat))
13649 (aa (assoc last-state org-todo-kwd-alist))
13650 (interpret (nth 1 aa))
13651 (head (nth 2 aa))
13652 (done-word (nth 3 aa))
13653 (whata '(("d" . day) ("m" . month) ("y" . year)))
13654 (msg "Entry repeats: ")
13655 (org-log-done)
13656 re type n what ts)
13657 (when repeat
13658 (org-todo (if (eq interpret 'type) last-state head))
13659 (when (and org-log-repeat
13660 (not (memq 'org-add-log-note
13661 (default-value 'post-command-hook))))
13662 ;; Make sure a note is taken
13663 (let ((org-log-done '(done)))
13664 (org-add-log-maybe 'done (or done-word (car org-done-keywords))
13665 'findpos)))
13666 (org-back-to-heading t)
13667 (org-add-planning-info nil nil 'closed)
13668 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
13669 org-deadline-time-regexp "\\)"))
13670 (while (re-search-forward
13671 re (save-excursion (outline-next-heading) (point)) t)
13672 (setq type (if (match-end 1) org-scheduled-string org-deadline-string)
13673 ts (match-string (if (match-end 2) 2 4)))
13674 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
13675 (setq n (string-to-number (match-string 1 ts))
13676 what (match-string 2 ts))
13677 (if (equal what "w") (setq n (* n 7) what "d"))
13678 (org-timestamp-change n (cdr (assoc what whata))))
13679 (setq msg (concat msg type org-last-changed-timestamp " ")))
13680 (setq org-log-post-message msg)
13681 (message msg))))
13683 (defun org-show-todo-tree (arg)
13684 "Make a compact tree which shows all headlines marked with TODO.
13685 The tree will show the lines where the regexp matches, and all higher
13686 headlines above the match.
13687 With \\[universal-argument] prefix, also show the DONE entries.
13688 With a numeric prefix N, construct a sparse tree for the Nth element
13689 of `org-todo-keywords-1'."
13690 (interactive "P")
13691 (let ((case-fold-search nil)
13692 (kwd-re
13693 (cond ((null arg) org-not-done-regexp)
13694 ((equal arg '(4))
13695 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
13696 (mapcar 'list org-todo-keywords-1))))
13697 (concat "\\("
13698 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13699 "\\)\\>")))
13700 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13701 (regexp-quote (nth (1- (prefix-numeric-value arg))
13702 org-todo-keywords-1)))
13703 (t (error "Invalid prefix argument: %s" arg)))))
13704 (message "%d TODO entries found"
13705 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
13707 (defun org-deadline (&optional remove)
13708 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13709 With argument REMOVE, remove any deadline from the item."
13710 (interactive "P")
13711 (if remove
13712 (progn
13713 (org-add-planning-info nil nil 'deadline)
13714 (message "Item no longer has a deadline."))
13715 (org-add-planning-info 'deadline nil 'closed)))
13717 (defun org-schedule (&optional remove)
13718 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13719 With argument REMOVE, remove any scheduling date from the item."
13720 (interactive "P")
13721 (if remove
13722 (progn
13723 (org-add-planning-info nil nil 'scheduled)
13724 (message "Item is no longer scheduled."))
13725 (org-add-planning-info 'scheduled nil 'closed)))
13727 (defun org-add-planning-info (what &optional time &rest remove)
13728 "Insert new timestamp with keyword in the line directly after the headline.
13729 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
13730 If non is given, the user is prompted for a date.
13731 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13732 be removed."
13733 (interactive)
13734 (let (org-time-was-given org-end-time-was-given)
13735 (when what (setq time (or time (org-read-date nil 'to-time))))
13736 (when (and org-insert-labeled-timestamps-at-point
13737 (member what '(scheduled deadline)))
13738 (insert
13739 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13740 (org-insert-time-stamp time org-time-was-given
13741 nil nil nil (list org-end-time-was-given))
13742 (setq what nil))
13743 (save-excursion
13744 (save-restriction
13745 (let (col list elt ts buffer-invisibility-spec)
13746 (org-back-to-heading t)
13747 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
13748 (goto-char (match-end 1))
13749 (setq col (current-column))
13750 (goto-char (match-end 0))
13751 (if (eobp) (insert "\n") (forward-char 1))
13752 (if (and (not (looking-at outline-regexp))
13753 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13754 "[^\r\n]*"))
13755 (not (equal (match-string 1) org-clock-string)))
13756 (narrow-to-region (match-beginning 0) (match-end 0))
13757 (insert-before-markers "\n")
13758 (backward-char 1)
13759 (narrow-to-region (point) (point))
13760 (indent-to-column col))
13761 ;; Check if we have to remove something.
13762 (setq list (cons what remove))
13763 (while list
13764 (setq elt (pop list))
13765 (goto-char (point-min))
13766 (when (or (and (eq elt 'scheduled)
13767 (re-search-forward org-scheduled-time-regexp nil t))
13768 (and (eq elt 'deadline)
13769 (re-search-forward org-deadline-time-regexp nil t))
13770 (and (eq elt 'closed)
13771 (re-search-forward org-closed-time-regexp nil t)))
13772 (replace-match "")
13773 (if (looking-at "--+<[^>]+>") (replace-match ""))
13774 (if (looking-at " +") (replace-match ""))))
13775 (goto-char (point-max))
13776 (when what
13777 (insert
13778 (if (not (equal (char-before) ?\ )) " " "")
13779 (cond ((eq what 'scheduled) org-scheduled-string)
13780 ((eq what 'deadline) org-deadline-string)
13781 ((eq what 'closed) org-closed-string))
13782 " ")
13783 (setq ts (org-insert-time-stamp
13784 time
13785 (or org-time-was-given
13786 (and (eq what 'closed) org-log-done-with-time))
13787 (eq what 'closed)
13788 nil nil (list org-end-time-was-given)))
13789 (end-of-line 1))
13790 (goto-char (point-min))
13791 (widen)
13792 (if (looking-at "[ \t]+\r?\n")
13793 (replace-match ""))
13794 ts)))))
13796 (defvar org-log-note-marker (make-marker))
13797 (defvar org-log-note-purpose nil)
13798 (defvar org-log-note-state nil)
13799 (defvar org-log-note-window-configuration nil)
13800 (defvar org-log-note-return-to (make-marker))
13801 (defvar org-log-post-message nil
13802 "Message to be displayed after a log note has been stored.
13803 The auto-repeater uses this.")
13805 (defun org-add-log-maybe (&optional purpose state findpos)
13806 "Set up the post command hook to take a note."
13807 (save-excursion
13808 (when (and (listp org-log-done)
13809 (memq purpose org-log-done))
13810 (when findpos
13811 (org-back-to-heading t)
13812 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
13813 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13814 "[^\r\n]*\\)?"))
13815 (goto-char (match-end 0))
13816 (unless org-log-states-order-reversed
13817 (and (= (char-after) ?\n) (forward-char 1))
13818 (org-skip-over-state-notes)
13819 (skip-chars-backward " \t\n\r")))
13820 (move-marker org-log-note-marker (point))
13821 (setq org-log-note-purpose purpose)
13822 (setq org-log-note-state state)
13823 (add-hook 'post-command-hook 'org-add-log-note 'append))))
13825 (defun org-skip-over-state-notes ()
13826 "Skip past the list of State notes in an entry."
13827 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13828 (while (looking-at "[ \t]*- State")
13829 (condition-case nil
13830 (org-next-item)
13831 (error (org-end-of-item)))))
13833 (defun org-add-log-note (&optional purpose)
13834 "Pop up a window for taking a note, and add this note later at point."
13835 (remove-hook 'post-command-hook 'org-add-log-note)
13836 (setq org-log-note-window-configuration (current-window-configuration))
13837 (delete-other-windows)
13838 (move-marker org-log-note-return-to (point))
13839 (switch-to-buffer (marker-buffer org-log-note-marker))
13840 (goto-char org-log-note-marker)
13841 (org-switch-to-buffer-other-window "*Org Note*")
13842 (erase-buffer)
13843 (let ((org-inhibit-startup t)) (org-mode))
13844 (insert (format "# Insert note for %s.
13845 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13846 (cond
13847 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13848 ((eq org-log-note-purpose 'done) "closed todo item")
13849 ((eq org-log-note-purpose 'state)
13850 (format "state change to \"%s\"" org-log-note-state))
13851 (t (error "This should not happen")))))
13852 (org-set-local 'org-finish-function 'org-store-log-note))
13854 (defun org-store-log-note ()
13855 "Finish taking a log note, and insert it to where it belongs."
13856 (let ((txt (buffer-string))
13857 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13858 lines ind)
13859 (kill-buffer (current-buffer))
13860 (while (string-match "\\`#.*\n[ \t\n]*" txt)
13861 (setq txt (replace-match "" t t txt)))
13862 (if (string-match "\\s-+\\'" txt)
13863 (setq txt (replace-match "" t t txt)))
13864 (setq lines (org-split-string txt "\n"))
13865 (when (and note (string-match "\\S-" note))
13866 (setq note
13867 (org-replace-escapes
13868 note
13869 (list (cons "%u" (user-login-name))
13870 (cons "%U" user-full-name)
13871 (cons "%t" (format-time-string
13872 (org-time-stamp-format 'long 'inactive)
13873 (current-time)))
13874 (cons "%s" (if org-log-note-state
13875 (concat "\"" org-log-note-state "\"")
13876 "")))))
13877 (if lines (setq note (concat note " \\\\")))
13878 (push note lines))
13879 (when (or current-prefix-arg org-note-abort) (setq lines nil))
13880 (when lines
13881 (save-excursion
13882 (set-buffer (marker-buffer org-log-note-marker))
13883 (save-excursion
13884 (goto-char org-log-note-marker)
13885 (move-marker org-log-note-marker nil)
13886 (end-of-line 1)
13887 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13888 (indent-relative nil)
13889 (insert " - " (pop lines))
13890 (org-indent-line-function)
13891 (beginning-of-line 1)
13892 (looking-at "[ \t]*")
13893 (setq ind (concat (match-string 0) " "))
13894 (end-of-line 1)
13895 (while lines (insert "\n" ind (pop lines)))))))
13896 (set-window-configuration org-log-note-window-configuration)
13897 (with-current-buffer (marker-buffer org-log-note-return-to)
13898 (goto-char org-log-note-return-to))
13899 (move-marker org-log-note-return-to nil)
13900 (and org-log-post-message (message org-log-post-message)))
13902 ;; FIXME: what else would be useful?
13903 ;; - priority
13904 ;; - date
13906 (defun org-sparse-tree (&optional arg)
13907 "Create a sparse tree, prompt for the details.
13908 This command can create sparse trees. You first need to select the type
13909 of match used to create the tree:
13911 t Show entries with a specific TODO keyword.
13912 T Show entries selected by a tags match.
13913 p Enter a property name and its value (both with completion on existing
13914 names/values) and show entries with that property.
13915 r Show entries matching a regular expression"
13916 (interactive "P")
13917 (let (ans kwd value)
13918 (message "Sparse tree: [r]egexp [t]odo-kwd [T]ag [p]roperty")
13919 (setq ans (read-char-exclusive))
13920 (cond
13921 ((equal ans ?t)
13922 (org-show-todo-tree '(4)))
13923 ((equal ans ?T)
13924 (call-interactively 'org-tags-sparse-tree))
13925 ((member ans '(?p ?P))
13926 (setq kwd (completing-read "Property: "
13927 (mapcar 'list (org-buffer-property-keys))))
13928 (setq value (completing-read "Value: "
13929 (mapcar 'list (org-property-values kwd))))
13930 (unless (string-match "\\`{.*}\\'" value)
13931 (setq value (concat "\"" value "\"")))
13932 (org-tags-sparse-tree arg (concat kwd "=" value)))
13933 ((member ans '(?r ?R))
13934 (call-interactively 'org-occur))
13935 (t (error "No such sparse tree command \"%c\"" ans)))))
13937 (defvar org-occur-highlights nil)
13938 (make-variable-buffer-local 'org-occur-highlights)
13940 (defun org-occur (regexp &optional keep-previous callback)
13941 "Make a compact tree which shows all matches of REGEXP.
13942 The tree will show the lines where the regexp matches, and all higher
13943 headlines above the match. It will also show the heading after the match,
13944 to make sure editing the matching entry is easy.
13945 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13946 call to `org-occur' will be kept, to allow stacking of calls to this
13947 command.
13948 If CALLBACK is non-nil, it is a function which is called to confirm
13949 that the match should indeed be shown."
13950 (interactive "sRegexp: \nP")
13951 (or keep-previous (org-remove-occur-highlights nil nil t))
13952 (let ((cnt 0))
13953 (save-excursion
13954 (goto-char (point-min))
13955 (if (or (not keep-previous) ; do not want to keep
13956 (not org-occur-highlights)) ; no previous matches
13957 ;; hide everything
13958 (org-overview))
13959 (while (re-search-forward regexp nil t)
13960 (when (or (not callback)
13961 (save-match-data (funcall callback)))
13962 (setq cnt (1+ cnt))
13963 (when org-highlight-sparse-tree-matches
13964 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13965 (org-show-context 'occur-tree))))
13966 (when org-remove-highlights-with-change
13967 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13968 nil 'local))
13969 (unless org-sparse-tree-open-archived-trees
13970 (org-hide-archived-subtrees (point-min) (point-max)))
13971 (run-hooks 'org-occur-hook)
13972 (if (interactive-p)
13973 (message "%d match(es) for regexp %s" cnt regexp))
13974 cnt))
13976 (defun org-show-context (&optional key)
13977 "Make sure point and context and visible.
13978 How much context is shown depends upon the variables
13979 `org-show-hierarchy-above', `org-show-following-heading'. and
13980 `org-show-siblings'."
13981 (let ((heading-p (org-on-heading-p t))
13982 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13983 (following-p (org-get-alist-option org-show-following-heading key))
13984 (siblings-p (org-get-alist-option org-show-siblings key)))
13985 (catch 'exit
13986 ;; Show heading or entry text
13987 (if heading-p
13988 (org-flag-heading nil) ; only show the heading
13989 (and (or (org-invisible-p) (org-invisible-p2))
13990 (org-show-hidden-entry))) ; show entire entry
13991 (when following-p
13992 ;; Show next sibling, or heading below text
13993 (save-excursion
13994 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13995 (org-flag-heading nil))))
13996 (when siblings-p (org-show-siblings))
13997 (when hierarchy-p
13998 ;; show all higher headings, possibly with siblings
13999 (save-excursion
14000 (while (and (condition-case nil
14001 (progn (org-up-heading-all 1) t)
14002 (error nil))
14003 (not (bobp)))
14004 (org-flag-heading nil)
14005 (when siblings-p (org-show-siblings))))))))
14007 (defun org-reveal (&optional siblings)
14008 "Show current entry, hierarchy above it, and the following headline.
14009 This can be used to show a consistent set of context around locations
14010 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
14011 not t for the search context.
14013 With optional argument SIBLINGS, on each level of the hierarchy all
14014 siblings are shown. This repairs the tree structure to what it would
14015 look like when opened with hierarchical calls to `org-cycle'."
14016 (interactive "P")
14017 (let ((org-show-hierarchy-above t)
14018 (org-show-following-heading t)
14019 (org-show-siblings (if siblings t org-show-siblings)))
14020 (org-show-context nil)))
14022 (defun org-highlight-new-match (beg end)
14023 "Highlight from BEG to END and mark the highlight is an occur headline."
14024 (let ((ov (org-make-overlay beg end)))
14025 (org-overlay-put ov 'face 'secondary-selection)
14026 (push ov org-occur-highlights)))
14028 (defun org-remove-occur-highlights (&optional beg end noremove)
14029 "Remove the occur highlights from the buffer.
14030 BEG and END are ignored. If NOREMOVE is nil, remove this function
14031 from the `before-change-functions' in the current buffer."
14032 (interactive)
14033 (unless org-inhibit-highlight-removal
14034 (mapc 'org-delete-overlay org-occur-highlights)
14035 (setq org-occur-highlights nil)
14036 (unless noremove
14037 (remove-hook 'before-change-functions
14038 'org-remove-occur-highlights 'local))))
14040 ;;;; Priorities
14042 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14043 "Regular expression matching the priority indicator.")
14045 (defvar org-remove-priority-next-time nil)
14047 (defun org-priority-up ()
14048 "Increase the priority of the current item."
14049 (interactive)
14050 (org-priority 'up))
14052 (defun org-priority-down ()
14053 "Decrease the priority of the current item."
14054 (interactive)
14055 (org-priority 'down))
14057 (defun org-priority (&optional action)
14058 "Change the priority of an item by ARG.
14059 ACTION can be `set', `up', `down', or a character."
14060 (interactive)
14061 (setq action (or action 'set))
14062 (let (current new news have remove)
14063 (save-excursion
14064 (org-back-to-heading)
14065 (if (looking-at org-priority-regexp)
14066 (setq current (string-to-char (match-string 2))
14067 have t)
14068 (setq current org-default-priority))
14069 (cond
14070 ((or (eq action 'set) (integerp action))
14071 (if (integerp action)
14072 (setq new action)
14073 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
14074 (setq new (read-char-exclusive)))
14075 (if (and (= (upcase org-highest-priority) org-highest-priority)
14076 (= (upcase org-lowest-priority) org-lowest-priority))
14077 (setq new (upcase new)))
14078 (cond ((equal new ?\ ) (setq remove t))
14079 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14080 (error "Priority must be between `%c' and `%c'"
14081 org-highest-priority org-lowest-priority))))
14082 ((eq action 'up)
14083 (if (and (not have) (eq last-command this-command))
14084 (setq new org-lowest-priority)
14085 (setq new (if (and org-priority-start-cycle-with-default (not have))
14086 org-default-priority (1- current)))))
14087 ((eq action 'down)
14088 (if (and (not have) (eq last-command this-command))
14089 (setq new org-highest-priority)
14090 (setq new (if (and org-priority-start-cycle-with-default (not have))
14091 org-default-priority (1+ current)))))
14092 (t (error "Invalid action")))
14093 (if (or (< (upcase new) org-highest-priority)
14094 (> (upcase new) org-lowest-priority))
14095 (setq remove t))
14096 (setq news (format "%c" new))
14097 (if have
14098 (if remove
14099 (replace-match "" t t nil 1)
14100 (replace-match news t t nil 2))
14101 (if remove
14102 (error "No priority cookie found in line")
14103 (looking-at org-todo-line-regexp)
14104 (if (match-end 2)
14105 (progn
14106 (goto-char (match-end 2))
14107 (insert " [#" news "]"))
14108 (goto-char (match-beginning 3))
14109 (insert "[#" news "] ")))))
14110 (org-preserve-lc (org-set-tags nil 'align))
14111 (if remove
14112 (message "Priority removed")
14113 (message "Priority of current item set to %s" news))))
14116 (defun org-get-priority (s)
14117 "Find priority cookie and return priority."
14118 (save-match-data
14119 (if (not (string-match org-priority-regexp s))
14120 (* 1000 (- org-lowest-priority org-default-priority))
14121 (* 1000 (- org-lowest-priority
14122 (string-to-char (match-string 2 s)))))))
14124 ;;;; Tags
14126 (defun org-scan-tags (action matcher &optional todo-only)
14127 "Scan headline tags with inheritance and produce output ACTION.
14128 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
14129 evaluated, testing if a given set of tags qualifies a headline for
14130 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
14131 are included in the output."
14132 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
14133 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14134 (org-re
14135 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
14136 (props (list 'face nil
14137 'done-face 'org-done
14138 'undone-face nil
14139 'mouse-face 'highlight
14140 'org-not-done-regexp org-not-done-regexp
14141 'org-todo-regexp org-todo-regexp
14142 'keymap org-agenda-keymap
14143 'help-echo
14144 (format "mouse-2 or RET jump to org file %s"
14145 (abbreviate-file-name
14146 (or (buffer-file-name (buffer-base-buffer))
14147 (buffer-name (buffer-base-buffer)))))))
14148 (case-fold-search nil)
14149 lspos
14150 tags tags-list tags-alist (llast 0) rtn level category i txt
14151 todo marker entry priority)
14152 (save-excursion
14153 (goto-char (point-min))
14154 (when (eq action 'sparse-tree)
14155 (org-overview)
14156 (org-remove-occur-highlights))
14157 (while (re-search-forward re nil t)
14158 (catch :skip
14159 (setq todo (if (match-end 1) (match-string 2))
14160 tags (if (match-end 4) (match-string 4)))
14161 (goto-char (setq lspos (1+ (match-beginning 0))))
14162 (setq level (org-reduced-level (funcall outline-level))
14163 category (org-get-category))
14164 (setq i llast llast level)
14165 ;; remove tag lists from same and sublevels
14166 (while (>= i level)
14167 (when (setq entry (assoc i tags-alist))
14168 (setq tags-alist (delete entry tags-alist)))
14169 (setq i (1- i)))
14170 ;; add the nex tags
14171 (when tags
14172 (setq tags (mapcar 'downcase (org-split-string tags ":"))
14173 tags-alist
14174 (cons (cons level tags) tags-alist)))
14175 ;; compile tags for current headline
14176 (setq tags-list
14177 (if org-use-tag-inheritance
14178 (apply 'append (mapcar 'cdr tags-alist))
14179 tags))
14180 (when (and (or (not todo-only) (member todo org-not-done-keywords))
14181 (eval matcher)
14182 (or (not org-agenda-skip-archived-trees)
14183 (not (member org-archive-tag tags-list))))
14184 (and (eq action 'agenda) (org-agenda-skip))
14185 ;; list this headline
14187 (if (eq action 'sparse-tree)
14188 (progn
14189 (and org-highlight-sparse-tree-matches
14190 (org-get-heading) (match-end 0)
14191 (org-highlight-new-match
14192 (match-beginning 0) (match-beginning 1)))
14193 (org-show-context 'tags-tree))
14194 (setq txt (org-format-agenda-item
14196 (concat
14197 (if org-tags-match-list-sublevels
14198 (make-string (1- level) ?.) "")
14199 (org-get-heading))
14200 category tags-list)
14201 priority (org-get-priority txt))
14202 (goto-char lspos)
14203 (setq marker (org-agenda-new-marker))
14204 (org-add-props txt props
14205 'org-marker marker 'org-hd-marker marker 'org-category category
14206 'priority priority 'type "tagsmatch")
14207 (push txt rtn))
14208 ;; if we are to skip sublevels, jump to end of subtree
14209 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
14210 (when (and (eq action 'sparse-tree)
14211 (not org-sparse-tree-open-archived-trees))
14212 (org-hide-archived-subtrees (point-min) (point-max)))
14213 (nreverse rtn)))
14215 (defvar todo-only) ;; dynamically scoped
14217 (defun org-tags-sparse-tree (&optional todo-only match)
14218 "Create a sparse tree according to tags string MATCH.
14219 MATCH can contain positive and negative selection of tags, like
14220 \"+WORK+URGENT-WITHBOSS\".
14221 If optional argument TODO_ONLY is non-nil, only select lines that are
14222 also TODO lines."
14223 (interactive "P")
14224 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14226 (defvar org-cached-props nil)
14227 (defun org-cached-entry-get (pom property)
14228 (if org-use-property-inheritance
14229 ;; Caching is not possible, check it directly
14230 (org-entry-get pom property 'inherit)
14231 ;; Get all properties, so that we can do complicated checks easily
14232 (cdr (assoc property (or org-cached-props
14233 (setq org-cached-props
14234 (org-entry-properties pom)))))))
14236 (defun org-global-tags-completion-table (&optional files)
14237 "Return the list of all tags in all agenda buffer/files."
14238 (save-excursion
14239 (org-uniquify
14240 (apply 'append
14241 (mapcar
14242 (lambda (file)
14243 (set-buffer (find-file-noselect file))
14244 (org-get-buffer-tags))
14245 (if (and files (car files))
14246 files
14247 (org-agenda-files)))))))
14249 (defun org-make-tags-matcher (match)
14250 "Create the TAGS//TODO matcher form for the selection string MATCH."
14251 ;; todo-only is scoped dynamically into this function, and the function
14252 ;; may change it it the matcher asksk for it.
14253 (unless match
14254 ;; Get a new match request, with completion
14255 (let ((org-last-tags-completion-table
14256 (org-global-tags-completion-table)))
14257 (setq match (completing-read
14258 "Match: " 'org-tags-completion-function nil nil nil
14259 'org-tags-history))))
14261 ;; Parse the string and create a lisp form
14262 (let ((match0 match)
14263 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]+\"\\)\\|[[:alnum:]_@]+\\)"))
14264 minus tag mm
14265 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14266 orterms term orlist re-p level-p prop-p pn pv)
14267 (if (string-match "/+" match)
14268 ;; match contains also a todo-matching request
14269 (progn
14270 (setq tagsmatch (substring match 0 (match-beginning 0))
14271 todomatch (substring match (match-end 0)))
14272 (if (string-match "^!" todomatch)
14273 (setq todo-only t todomatch (substring todomatch 1)))
14274 (if (string-match "^\\s-*$" todomatch)
14275 (setq todomatch nil)))
14276 ;; only matching tags
14277 (setq tagsmatch match todomatch nil))
14279 ;; Make the tags matcher
14280 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14281 (setq tagsmatcher t)
14282 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14283 (while (setq term (pop orterms))
14284 (while (and (equal (substring term -1) "\\") orterms)
14285 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14286 (while (string-match re term)
14287 (setq minus (and (match-end 1)
14288 (equal (match-string 1 term) "-"))
14289 tag (match-string 2 term)
14290 re-p (equal (string-to-char tag) ?{)
14291 level-p (match-end 3)
14292 prop-p (match-end 4)
14293 mm (cond
14294 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14295 (level-p `(= level ,(string-to-number
14296 (match-string 3 term))))
14297 (prop-p
14298 (setq pn (match-string 4 term)
14299 pv (match-string 5 term)
14300 re-p (equal (string-to-char pv) ?{)
14301 pv (substring pv 1 -1))
14302 (if re-p
14303 `(string-match ,pv (or (org-cached-entry-get nil ,pn) ""))
14304 `(equal ,pv (org-cached-entry-get nil ,pn))))
14305 (t `(member ,(downcase tag) tags-list)))
14306 mm (if minus (list 'not mm) mm)
14307 term (substring term (match-end 0)))
14308 (push mm tagsmatcher))
14309 (push (if (> (length tagsmatcher) 1)
14310 (cons 'and tagsmatcher)
14311 (car tagsmatcher))
14312 orlist)
14313 (setq tagsmatcher nil))
14314 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14315 (setq tagsmatcher
14316 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14318 ;; Make the todo matcher
14319 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14320 (setq todomatcher t)
14321 (setq orterms (org-split-string todomatch "|") orlist nil)
14322 (while (setq term (pop orterms))
14323 (while (string-match re term)
14324 (setq minus (and (match-end 1)
14325 (equal (match-string 1 term) "-"))
14326 kwd (match-string 2 term)
14327 re-p (equal (string-to-char kwd) ?{)
14328 term (substring term (match-end 0))
14329 mm (if re-p
14330 `(string-match ,(substring kwd 1 -1) todo)
14331 (list 'equal 'todo kwd))
14332 mm (if minus (list 'not mm) mm))
14333 (push mm todomatcher))
14334 (push (if (> (length todomatcher) 1)
14335 (cons 'and todomatcher)
14336 (car todomatcher))
14337 orlist)
14338 (setq todomatcher nil))
14339 (setq todomatcher (if (> (length orlist) 1)
14340 (cons 'or orlist) (car orlist))))
14342 ;; Return the string and lisp forms of the matcher
14343 (setq matcher (if todomatcher
14344 (list 'and tagsmatcher todomatcher)
14345 tagsmatcher))
14346 (cons match0 matcher)))
14348 (defun org-match-any-p (re list)
14349 "Does re match any element of list?"
14350 (setq list (mapcar (lambda (x) (string-match re x)) list))
14351 (delq nil list))
14353 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
14354 (defvar org-tags-overlay (org-make-overlay 1 1))
14355 (org-detach-overlay org-tags-overlay)
14357 (defun org-align-tags-here (to-col)
14358 ;; Assumes that this is a headline
14359 (let ((pos (point)) (col (current-column)) tags)
14360 (beginning-of-line 1)
14361 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14362 (< pos (match-beginning 2)))
14363 (progn
14364 (setq tags (match-string 2))
14365 (goto-char (match-beginning 1))
14366 (insert " ")
14367 (delete-region (point) (1+ (match-end 0)))
14368 (backward-char 1)
14369 (move-to-column
14370 (max (1+ (current-column))
14371 (1+ col)
14372 (if (> to-col 0)
14373 to-col
14374 (- (abs to-col) (length tags))))
14376 (insert tags)
14377 (move-to-column (min (current-column) col) t))
14378 (goto-char pos))))
14380 (defun org-set-tags (&optional arg just-align)
14381 "Set the tags for the current headline.
14382 With prefix ARG, realign all tags in headings in the current buffer."
14383 (interactive "P")
14384 (let* ((re (concat "^" outline-regexp))
14385 (current (org-get-tags-string))
14386 (col (current-column))
14387 (org-setting-tags t)
14388 table current-tags inherited-tags ; computed below when needed
14389 tags p0 c0 c1 rpl)
14390 (if arg
14391 (save-excursion
14392 (goto-char (point-min))
14393 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14394 (while (re-search-forward re nil t)
14395 (org-set-tags nil t)
14396 (end-of-line 1)))
14397 (message "All tags realigned to column %d" org-tags-column))
14398 (if just-align
14399 (setq tags current)
14400 ;; Get a new set of tags from the user
14401 (save-excursion
14402 (setq table (or org-tag-alist (org-get-buffer-tags))
14403 org-last-tags-completion-table table
14404 current-tags (org-split-string current ":")
14405 inherited-tags (nreverse
14406 (nthcdr (length current-tags)
14407 (nreverse (org-get-tags-at))))
14408 tags
14409 (if (or (eq t org-use-fast-tag-selection)
14410 (and org-use-fast-tag-selection
14411 (delq nil (mapcar 'cdr table))))
14412 (org-fast-tag-selection
14413 current-tags inherited-tags table
14414 (if org-fast-tag-selection-include-todo org-todo-key-alist))
14415 (let ((org-add-colon-after-tag-completion t))
14416 (org-trim
14417 (org-without-partial-completion
14418 (completing-read "Tags: " 'org-tags-completion-function
14419 nil nil current 'org-tags-history)))))))
14420 (while (string-match "[-+&]+" tags)
14421 ;; No boolean logic, just a list
14422 (setq tags (replace-match ":" t t tags))))
14424 (if (string-match "\\`[\t ]*\\'" tags)
14425 (setq tags "")
14426 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14427 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14429 ;; Insert new tags at the correct column
14430 (beginning-of-line 1)
14431 (cond
14432 ((and (equal current "") (equal tags "")))
14433 ((re-search-forward
14434 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14435 (point-at-eol) t)
14436 (if (equal tags "")
14437 (setq rpl "")
14438 (goto-char (match-beginning 0))
14439 (setq c0 (current-column) p0 (point)
14440 c1 (max (1+ c0) (if (> org-tags-column 0)
14441 org-tags-column
14442 (- (- org-tags-column) (length tags))))
14443 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14444 (replace-match rpl t t)
14445 (and (not (featurep 'xemacs)) c0 (tabify p0 (point)))
14446 tags)
14447 (t (error "Tags alignment failed")))
14448 (move-to-column col)
14449 (unless just-align
14450 (run-hooks 'org-after-tags-change-hook)))))
14452 (defun org-change-tag-in-region (beg end tag off)
14453 "Add or remove TAG for each entry in the region.
14454 This works in the agenda, and also in an org-mode buffer."
14455 (interactive
14456 (list (region-beginning) (region-end)
14457 (let ((org-last-tags-completion-table
14458 (if (org-mode-p)
14459 (org-get-buffer-tags)
14460 (org-global-tags-completion-table))))
14461 (completing-read
14462 "Tag: " 'org-tags-completion-function nil nil nil
14463 'org-tags-history))
14464 (progn
14465 (message "[s]et or [r]emove? ")
14466 (equal (read-char-exclusive) ?r))))
14467 (if (fboundp 'deactivate-mark) (deactivate-mark))
14468 (let ((agendap (equal major-mode 'org-agenda-mode))
14469 l1 l2 m buf pos newhead (cnt 0))
14470 (goto-char end)
14471 (setq l2 (1- (org-current-line)))
14472 (goto-char beg)
14473 (setq l1 (org-current-line))
14474 (loop for l from l1 to l2 do
14475 (goto-line l)
14476 (setq m (get-text-property (point) 'org-hd-marker))
14477 (when (or (and (org-mode-p) (org-on-heading-p))
14478 (and agendap m))
14479 (setq buf (if agendap (marker-buffer m) (current-buffer))
14480 pos (if agendap m (point)))
14481 (with-current-buffer buf
14482 (save-excursion
14483 (save-restriction
14484 (goto-char pos)
14485 (setq cnt (1+ cnt))
14486 (org-toggle-tag tag (if off 'off 'on))
14487 (setq newhead (org-get-heading)))))
14488 (and agendap (org-agenda-change-all-lines newhead m))))
14489 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14491 (defun org-tags-completion-function (string predicate &optional flag)
14492 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14493 (confirm (lambda (x) (stringp (car x)))))
14494 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
14495 (setq s1 (match-string 1 string)
14496 s2 (match-string 2 string))
14497 (setq s1 "" s2 string))
14498 (cond
14499 ((eq flag nil)
14500 ;; try completion
14501 (setq rtn (try-completion s2 ctable confirm))
14502 (if (stringp rtn)
14503 (setq rtn
14504 (concat s1 s2 (substring rtn (length s2))
14505 (if (and org-add-colon-after-tag-completion
14506 (assoc rtn ctable))
14507 ":" ""))))
14508 rtn)
14509 ((eq flag t)
14510 ;; all-completions
14511 (all-completions s2 ctable confirm)
14513 ((eq flag 'lambda)
14514 ;; exact match?
14515 (assoc s2 ctable)))
14518 (defun org-fast-tag-insert (kwd tags face &optional end)
14519 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
14520 (insert (format "%-12s" (concat kwd ":"))
14521 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14522 (or end "")))
14524 (defun org-fast-tag-show-exit (flag)
14525 (save-excursion
14526 (goto-line 3)
14527 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14528 (replace-match ""))
14529 (when flag
14530 (end-of-line 1)
14531 (move-to-column (- (window-width) 19) t)
14532 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14534 (defun org-set-current-tags-overlay (current prefix)
14535 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14536 (if (featurep 'xemacs)
14537 (org-overlay-display org-tags-overlay (concat prefix s)
14538 'secondary-selection)
14539 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14540 (org-overlay-display org-tags-overlay (concat prefix s)))))
14542 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14543 "Fast tag selection with single keys.
14544 CURRENT is the current list of tags in the headline, INHERITED is the
14545 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14546 possibly with grouping information. TODO-TABLE is a similar table with
14547 TODO keywords, should these have keys assigned to them.
14548 If the keys are nil, a-z are automatically assigned.
14549 Returns the new tags string, or nil to not change the current settings."
14550 (let* ((fulltable (append table todo-table))
14551 (maxlen (apply 'max (mapcar
14552 (lambda (x)
14553 (if (stringp (car x)) (string-width (car x)) 0))
14554 fulltable)))
14555 (buf (current-buffer))
14556 (expert (eq org-fast-tag-selection-single-key 'expert))
14557 (buffer-tags nil)
14558 (fwidth (+ maxlen 3 1 3))
14559 (ncol (/ (- (window-width) 4) fwidth))
14560 (i-face 'org-done)
14561 (c-face 'org-todo)
14562 tg cnt e c char c1 c2 ntable tbl rtn
14563 ov-start ov-end ov-prefix
14564 (exit-after-next org-fast-tag-selection-single-key)
14565 (done-keywords org-done-keywords)
14566 groups ingroup)
14567 (save-excursion
14568 (beginning-of-line 1)
14569 (if (looking-at
14570 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14571 (setq ov-start (match-beginning 1)
14572 ov-end (match-end 1)
14573 ov-prefix "")
14574 (setq ov-start (1- (point-at-eol))
14575 ov-end (1+ ov-start))
14576 (skip-chars-forward "^\n\r")
14577 (setq ov-prefix
14578 (concat
14579 (buffer-substring (1- (point)) (point))
14580 (if (> (current-column) org-tags-column)
14582 (make-string (- org-tags-column (current-column)) ?\ ))))))
14583 (org-move-overlay org-tags-overlay ov-start ov-end)
14584 (save-window-excursion
14585 (if expert
14586 (set-buffer (get-buffer-create " *Org tags*"))
14587 (delete-other-windows)
14588 (split-window-vertically)
14589 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14590 (erase-buffer)
14591 (org-set-local 'org-done-keywords done-keywords)
14592 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14593 (org-fast-tag-insert "Current" current c-face "\n\n")
14594 (org-fast-tag-show-exit exit-after-next)
14595 (org-set-current-tags-overlay current ov-prefix)
14596 (setq tbl fulltable char ?a cnt 0)
14597 (while (setq e (pop tbl))
14598 (cond
14599 ((equal e '(:startgroup))
14600 (push '() groups) (setq ingroup t)
14601 (when (not (= cnt 0))
14602 (setq cnt 0)
14603 (insert "\n"))
14604 (insert "{ "))
14605 ((equal e '(:endgroup))
14606 (setq ingroup nil cnt 0)
14607 (insert "}\n"))
14609 (setq tg (car e) c2 nil)
14610 (if (cdr e)
14611 (setq c (cdr e))
14612 ;; automatically assign a character.
14613 (setq c1 (string-to-char
14614 (downcase (substring
14615 tg (if (= (string-to-char tg) ?@) 1 0)))))
14616 (if (or (rassoc c1 ntable) (rassoc c1 table))
14617 (while (or (rassoc char ntable) (rassoc char table))
14618 (setq char (1+ char)))
14619 (setq c2 c1))
14620 (setq c (or c2 char)))
14621 (if ingroup (push tg (car groups)))
14622 (setq tg (org-add-props tg nil 'face
14623 (cond
14624 ((not (assoc tg table))
14625 (org-get-todo-face tg))
14626 ((member tg current) c-face)
14627 ((member tg inherited) i-face)
14628 (t nil))))
14629 (if (and (= cnt 0) (not ingroup)) (insert " "))
14630 (insert "[" c "] " tg (make-string
14631 (- fwidth 4 (length tg)) ?\ ))
14632 (push (cons tg c) ntable)
14633 (when (= (setq cnt (1+ cnt)) ncol)
14634 (insert "\n")
14635 (if ingroup (insert " "))
14636 (setq cnt 0)))))
14637 (setq ntable (nreverse ntable))
14638 (insert "\n")
14639 (goto-char (point-min))
14640 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14641 (fit-window-to-buffer))
14642 (setq rtn
14643 (catch 'exit
14644 (while t
14645 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
14646 (if groups " [!] no groups" " [!]groups")
14647 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14648 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14649 (cond
14650 ((= c ?\r) (throw 'exit t))
14651 ((= c ?!)
14652 (setq groups (not groups))
14653 (goto-char (point-min))
14654 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14655 ((= c ?\C-c)
14656 (if (not expert)
14657 (org-fast-tag-show-exit
14658 (setq exit-after-next (not exit-after-next)))
14659 (setq expert nil)
14660 (delete-other-windows)
14661 (split-window-vertically)
14662 (org-switch-to-buffer-other-window " *Org tags*")
14663 (and (fboundp 'fit-window-to-buffer)
14664 (fit-window-to-buffer))))
14665 ((or (= c ?\C-g)
14666 (and (= c ?q) (not (rassoc c ntable))))
14667 (org-detach-overlay org-tags-overlay)
14668 (setq quit-flag t))
14669 ((= c ?\ )
14670 (setq current nil)
14671 (if exit-after-next (setq exit-after-next 'now)))
14672 ((= c ?\t)
14673 (condition-case nil
14674 (setq tg (completing-read
14675 "Tag: "
14676 (or buffer-tags
14677 (with-current-buffer buf
14678 (org-get-buffer-tags)))))
14679 (quit (setq tg "")))
14680 (when (string-match "\\S-" tg)
14681 (add-to-list 'buffer-tags (list tg))
14682 (if (member tg current)
14683 (setq current (delete tg current))
14684 (push tg current)))
14685 (if exit-after-next (setq exit-after-next 'now)))
14686 ((setq e (rassoc c todo-table) tg (car e))
14687 (with-current-buffer buf
14688 (save-excursion (org-todo tg)))
14689 (if exit-after-next (setq exit-after-next 'now)))
14690 ((setq e (rassoc c ntable) tg (car e))
14691 (if (member tg current)
14692 (setq current (delete tg current))
14693 (loop for g in groups do
14694 (if (member tg g)
14695 (mapc (lambda (x)
14696 (setq current (delete x current)))
14697 g)))
14698 (push tg current))
14699 (if exit-after-next (setq exit-after-next 'now))))
14701 ;; Create a sorted list
14702 (setq current
14703 (sort current
14704 (lambda (a b)
14705 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14706 (if (eq exit-after-next 'now) (throw 'exit t))
14707 (goto-char (point-min))
14708 (beginning-of-line 2)
14709 (delete-region (point) (point-at-eol))
14710 (org-fast-tag-insert "Current" current c-face)
14711 (org-set-current-tags-overlay current ov-prefix)
14712 (while (re-search-forward
14713 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
14714 (setq tg (match-string 1))
14715 (add-text-properties
14716 (match-beginning 1) (match-end 1)
14717 (list 'face
14718 (cond
14719 ((member tg current) c-face)
14720 ((member tg inherited) i-face)
14721 (t (get-text-property (match-beginning 1) 'face))))))
14722 (goto-char (point-min)))))
14723 (org-detach-overlay org-tags-overlay)
14724 (if rtn
14725 (mapconcat 'identity current ":")
14726 nil))))
14728 (defun org-get-tags-string ()
14729 "Get the TAGS string in the current headline."
14730 (unless (org-on-heading-p t)
14731 (error "Not on a heading"))
14732 (save-excursion
14733 (beginning-of-line 1)
14734 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14735 (org-match-string-no-properties 1)
14736 "")))
14738 (defun org-get-tags ()
14739 "Get the list of tags specified in the current headline."
14740 (org-split-string (org-get-tags-string) ":"))
14742 (defun org-get-buffer-tags ()
14743 "Get a table of all tags used in the buffer, for completion."
14744 (let (tags)
14745 (save-excursion
14746 (goto-char (point-min))
14747 (while (re-search-forward
14748 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
14749 (when (equal (char-after (point-at-bol 0)) ?*)
14750 (mapc (lambda (x) (add-to-list 'tags x))
14751 (org-split-string (org-match-string-no-properties 1) ":")))))
14752 (mapcar 'list tags)))
14755 ;;;; Properties
14757 ;;; Setting and retrieving properties
14759 (defconst org-special-properties
14760 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY")
14761 "The special properties valid in Org-mode.
14763 These are properties that are not defined in the property drawer,
14764 but in some other way.")
14766 (defconst org-default-properties
14767 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
14768 "LOCATION" "LOGGING" "COLUMNS")
14769 "Some properties that are used by Org-mode for various purposes.
14770 Being in this list makes sure that they are offered for completion.")
14772 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14773 "Regular expression matching the first line of a property drawer.")
14775 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14776 "Regular expression matching the first line of a property drawer.")
14778 (defun org-property-action ()
14779 "Do an action on properties."
14780 (interactive)
14781 (let (c)
14782 (org-at-property-p)
14783 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14784 (setq c (read-char-exclusive))
14785 (cond
14786 ((equal c ?s)
14787 (call-interactively 'org-set-property))
14788 ((equal c ?d)
14789 (call-interactively 'org-delete-property))
14790 ((equal c ?D)
14791 (call-interactively 'org-delete-property-globally))
14792 ((equal c ?c)
14793 (call-interactively 'org-compute-property-at-point))
14794 (t (error "No such property action %c" c)))))
14796 (defun org-at-property-p ()
14797 "Is the cursor in a property line?"
14798 ;; FIXME: Does not check if we are actually in the drawer.
14799 ;; FIXME: also returns true on any drawers.....
14800 ;; This is used by C-c C-c for property action.
14801 (save-excursion
14802 (beginning-of-line 1)
14803 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
14805 (defmacro org-with-point-at (pom &rest body)
14806 "Move to buffer and point of point-or-marker POM for the duration of BODY."
14807 (declare (indent 1) (debug t))
14808 `(save-excursion
14809 (if (markerp pom) (set-buffer (marker-buffer pom)))
14810 (save-excursion
14811 (goto-char (or pom (point)))
14812 ,@body)))
14814 (defun org-get-property-block (&optional beg end force)
14815 "Return the (beg . end) range of the body of the property drawer.
14816 BEG and END can be beginning and end of subtree, if not given
14817 they will be found.
14818 If the drawer does not exist and FORCE is non-nil, create the drawer."
14819 (catch 'exit
14820 (save-excursion
14821 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
14822 (end (or end (progn (outline-next-heading) (point)))))
14823 (goto-char beg)
14824 (if (re-search-forward org-property-start-re end t)
14825 (setq beg (1+ (match-end 0)))
14826 (if force
14827 (save-excursion
14828 (org-insert-property-drawer)
14829 (setq end (progn (outline-next-heading) (point))))
14830 (throw 'exit nil))
14831 (goto-char beg)
14832 (if (re-search-forward org-property-start-re end t)
14833 (setq beg (1+ (match-end 0)))))
14834 (if (re-search-forward org-property-end-re end t)
14835 (setq end (match-beginning 0))
14836 (or force (throw 'exit nil))
14837 (goto-char beg)
14838 (setq end beg)
14839 (org-indent-line-function)
14840 (insert ":END:\n"))
14841 (cons beg end)))))
14843 (defun org-entry-properties (&optional pom which)
14844 "Get all properties of the entry at point-or-marker POM.
14845 This includes the TODO keyword, the tags, time strings for deadline,
14846 scheduled, and clocking, and any additional properties defined in the
14847 entry. The return value is an alist, keys may occur multiple times
14848 if the property key was used several times.
14849 POM may also be nil, in which case the current entry is used.
14850 If WHICH is nil or `all', get all properties. If WHICH is
14851 `special' or `standard', only get that subclass."
14852 (setq which (or which 'all))
14853 (org-with-point-at pom
14854 (let ((clockstr (substring org-clock-string 0 -1))
14855 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
14856 beg end range props sum-props key value)
14857 (save-excursion
14858 (when (condition-case nil (org-back-to-heading t) (error nil))
14859 (setq beg (point))
14860 (setq sum-props (get-text-property (point) 'org-summaries))
14861 (outline-next-heading)
14862 (setq end (point))
14863 (when (memq which '(all special))
14864 ;; Get the special properties, like TODO and tags
14865 (goto-char beg)
14866 (when (and (looking-at org-todo-line-regexp) (match-end 2))
14867 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14868 (when (looking-at org-priority-regexp)
14869 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14870 (when (and (setq value (org-get-tags-string))
14871 (string-match "\\S-" value))
14872 (push (cons "TAGS" value) props))
14873 (when (setq value (org-get-tags-at))
14874 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
14875 props))
14876 (while (re-search-forward org-keyword-time-regexp end t)
14877 (setq key (substring (org-match-string-no-properties 1) 0 -1))
14878 (unless (member key excluded) (push key excluded))
14879 (push (cons key
14880 (if (equal key clockstr)
14881 (org-no-properties
14882 (org-trim
14883 (buffer-substring
14884 (match-beginning 2) (point-at-eol))))
14885 (org-match-string-no-properties 2)))
14886 props)))
14887 (when (memq which '(all standard))
14888 ;; Get the standard properties, like :PORP: ...
14889 (setq range (org-get-property-block beg end))
14890 (when range
14891 (goto-char (car range))
14892 (while (re-search-forward
14893 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14894 (cdr range) t)
14895 (setq key (org-match-string-no-properties 1)
14896 value (org-trim (or (org-match-string-no-properties 2) "")))
14897 (unless (member key excluded)
14898 (push (cons key (or value "")) props)))))
14899 (append sum-props (nreverse props)))))))
14901 (defun org-entry-get (pom property &optional inherit)
14902 "Get value of PROPERTY for entry at point-or-marker POM.
14903 If INHERIT is non-nil and the entry does not have the property,
14904 then also check higher levels of the hierarchy.
14905 If the property is present but empty, the return value is the empty string.
14906 If the property is not present at all, nil is returned."
14907 (org-with-point-at pom
14908 (if inherit
14909 (org-entry-get-with-inheritance property)
14910 (if (member property org-special-properties)
14911 ;; We need a special property. Use brute force, get all properties.
14912 (cdr (assoc property (org-entry-properties nil 'special)))
14913 (let ((range (org-get-property-block)))
14914 (if (and range
14915 (goto-char (car range))
14916 (re-search-forward
14917 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
14918 (cdr range) t))
14919 ;; Found the property, return it.
14920 (if (match-end 1)
14921 (org-match-string-no-properties 1)
14922 "")))))))
14924 (defun org-entry-delete (pom property)
14925 "Delete the property PROPERTY from entry at point-or-marker POM."
14926 (org-with-point-at pom
14927 (if (member property org-special-properties)
14928 nil ; cannot delete these properties.
14929 (let ((range (org-get-property-block)))
14930 (if (and range
14931 (goto-char (car range))
14932 (re-search-forward
14933 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
14934 (cdr range) t))
14935 (progn
14936 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14938 nil)))))
14940 ;; Multi-values properties are properties that contain multiple values
14941 ;; These values are assumed to be single words, separated by whitespace.
14942 (defun org-entry-add-to-multivalued-property (pom property value)
14943 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14944 (let* ((old (org-entry-get pom property))
14945 (values (and old (org-split-string old "[ \t]"))))
14946 (unless (member value values)
14947 (setq values (cons value values))
14948 (org-entry-put pom property
14949 (mapconcat 'identity values " ")))))
14951 (defun org-entry-remove-from-multivalued-property (pom property value)
14952 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14953 (let* ((old (org-entry-get pom property))
14954 (values (and old (org-split-string old "[ \t]"))))
14955 (when (member value values)
14956 (setq values (delete value values))
14957 (org-entry-put pom property
14958 (mapconcat 'identity values " ")))))
14960 (defun org-entry-member-in-multivalued-property (pom property value)
14961 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14962 (let* ((old (org-entry-get pom property))
14963 (values (and old (org-split-string old "[ \t]"))))
14964 (member value values)))
14966 (defvar org-entry-property-inherited-from (make-marker))
14968 (defun org-entry-get-with-inheritance (property)
14969 "Get entry property, and search higher levels if not present."
14970 (let (tmp)
14971 (save-excursion
14972 (save-restriction
14973 (widen)
14974 (catch 'ex
14975 (while t
14976 (when (setq tmp (org-entry-get nil property))
14977 (org-back-to-heading t)
14978 (move-marker org-entry-property-inherited-from (point))
14979 (throw 'ex tmp))
14980 (or (org-up-heading-safe) (throw 'ex nil)))))
14981 (or tmp (cdr (assoc property org-local-properties))
14982 (cdr (assoc property org-global-properties))))))
14984 (defun org-entry-put (pom property value)
14985 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14986 (org-with-point-at pom
14987 (org-back-to-heading t)
14988 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14989 range)
14990 (cond
14991 ((equal property "TODO")
14992 (when (and (stringp value) (string-match "\\S-" value)
14993 (not (member value org-todo-keywords-1)))
14994 (error "\"%s\" is not a valid TODO state" value))
14995 (if (or (not value)
14996 (not (string-match "\\S-" value)))
14997 (setq value 'none))
14998 (org-todo value)
14999 (org-set-tags nil 'align))
15000 ((equal property "PRIORITY")
15001 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15002 (string-to-char value) ?\ ))
15003 (org-set-tags nil 'align))
15004 ((equal property "SCHEDULED")
15005 (if (re-search-forward org-scheduled-time-regexp end t)
15006 (cond
15007 ((eq value 'earlier) (org-timestamp-change -1 'day))
15008 ((eq value 'later) (org-timestamp-change 1 'day))
15009 (t (call-interactively 'org-schedule)))
15010 (call-interactively 'org-schedule)))
15011 ((equal property "DEADLINE")
15012 (if (re-search-forward org-deadline-time-regexp end t)
15013 (cond
15014 ((eq value 'earlier) (org-timestamp-change -1 'day))
15015 ((eq value 'later) (org-timestamp-change 1 'day))
15016 (t (call-interactively 'org-deadline)))
15017 (call-interactively 'org-deadline)))
15018 ((member property org-special-properties)
15019 (error "The %s property can not yet be set with `org-entry-put'"
15020 property))
15021 (t ; a non-special property
15022 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15023 (setq range (org-get-property-block beg end 'force))
15024 (goto-char (car range))
15025 (if (re-search-forward
15026 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
15027 (progn
15028 (delete-region (match-beginning 1) (match-end 1))
15029 (goto-char (match-beginning 1)))
15030 (goto-char (cdr range))
15031 (insert "\n")
15032 (backward-char 1)
15033 (org-indent-line-function)
15034 (insert ":" property ":"))
15035 (and value (insert " " value))
15036 (org-indent-line-function)))))))
15038 (defun org-buffer-property-keys (&optional include-specials include-defaults)
15039 "Get all property keys in the current buffer.
15040 With INCLUDE-SPECIALS, also list the special properties that relect things
15041 like tags and TODO state.
15042 With INCLUDE-DEFAULTS, also include properties that has special meaning
15043 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING."
15044 (let (rtn range)
15045 (save-excursion
15046 (save-restriction
15047 (widen)
15048 (goto-char (point-min))
15049 (while (re-search-forward org-property-start-re nil t)
15050 (setq range (org-get-property-block))
15051 (goto-char (car range))
15052 (while (re-search-forward
15053 (org-re "^[ \t]*:\\([[:alnum:]_-]+\\):")
15054 (cdr range) t)
15055 (add-to-list 'rtn (org-match-string-no-properties 1)))
15056 (outline-next-heading))))
15058 (when include-specials
15059 (setq rtn (append org-special-properties rtn)))
15061 (when include-defaults
15062 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
15064 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15066 (defun org-property-values (key)
15067 "Return a list of all values of property KEY."
15068 (save-excursion
15069 (save-restriction
15070 (widen)
15071 (goto-char (point-min))
15072 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
15073 values)
15074 (while (re-search-forward re nil t)
15075 (add-to-list 'values (org-trim (match-string 1))))
15076 (delete "" values)))))
15078 (defun org-insert-property-drawer ()
15079 "Insert a property drawer into the current entry."
15080 (interactive)
15081 (org-back-to-heading t)
15082 (looking-at outline-regexp)
15083 (let ((indent (- (match-end 0)(match-beginning 0)))
15084 (beg (point))
15085 (re (concat "^[ \t]*" org-keyword-time-regexp))
15086 end hiddenp)
15087 (outline-next-heading)
15088 (setq end (point))
15089 (goto-char beg)
15090 (while (re-search-forward re end t))
15091 (setq hiddenp (org-invisible-p))
15092 (end-of-line 1)
15093 (and (equal (char-after) ?\n) (forward-char 1))
15094 (org-skip-over-state-notes)
15095 (skip-chars-backward " \t\n\r")
15096 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15097 (beginning-of-line 0)
15098 (indent-to-column indent)
15099 (beginning-of-line 2)
15100 (indent-to-column indent)
15101 (beginning-of-line 0)
15102 (if hiddenp
15103 (save-excursion
15104 (org-back-to-heading t)
15105 (hide-entry))
15106 (org-flag-drawer t))))
15108 (defun org-set-property (property value)
15109 "In the current entry, set PROPERTY to VALUE.
15110 When called interactively, this will prompt for a property name, offering
15111 completion on existing and default properties. And then it will prompt
15112 for a value, offering competion either on allowed values (via an inherited
15113 xxx_ALL property) or on existing values in other instances of this property
15114 in the current file."
15115 (interactive
15116 (let* ((prop (completing-read
15117 "Property: " (mapcar 'list (org-buffer-property-keys nil t))))
15118 (cur (org-entry-get nil prop))
15119 (allowed (org-property-get-allowed-values nil prop 'table))
15120 (existing (mapcar 'list (org-property-values prop)))
15121 (val (if allowed
15122 (completing-read "Value: " allowed nil 'req-match)
15123 (completing-read
15124 (concat "Value" (if (and cur (string-match "\\S-" cur))
15125 (concat "[" cur "]") "")
15126 ": ")
15127 existing nil nil "" nil cur))))
15128 (list prop (if (equal val "") cur val))))
15129 (unless (equal (org-entry-get nil property) value)
15130 (org-entry-put nil property value)))
15132 (defun org-delete-property (property)
15133 "In the current entry, delete PROPERTY."
15134 (interactive
15135 (let* ((prop (completing-read
15136 "Property: " (org-entry-properties nil 'standard))))
15137 (list prop)))
15138 (message (concat "Property " property
15139 (if (org-entry-delete nil property)
15140 " deleted"
15141 " was not present in the entry"))))
15143 (defun org-delete-property-globally (property)
15144 "Remove PROPERTY globally, from all entries."
15145 (interactive
15146 (let* ((prop (completing-read
15147 "Globally remove property: "
15148 (mapcar 'list (org-buffer-property-keys)))))
15149 (list prop)))
15150 (save-excursion
15151 (save-restriction
15152 (widen)
15153 (goto-char (point-min))
15154 (let ((cnt 0))
15155 (while (re-search-forward
15156 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
15157 nil t)
15158 (setq cnt (1+ cnt))
15159 (replace-match ""))
15160 (message "Property \"%s\" removed from %d entries" property cnt)))))
15162 (defvar org-columns-current-fmt-compiled) ; defined below
15164 (defun org-compute-property-at-point ()
15165 "Compute the property at point.
15166 This looks for an enclosing column format, extracts the operator and
15167 then applies it to the proerty in the column format's scope."
15168 (interactive)
15169 (unless (org-at-property-p)
15170 (error "Not at a property"))
15171 (let ((prop (org-match-string-no-properties 2)))
15172 (org-columns-get-format-and-top-level)
15173 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15174 (error "No operator defined for property %s" prop))
15175 (org-columns-compute prop)))
15177 (defun org-property-get-allowed-values (pom property &optional table)
15178 "Get allowed values for the property PROPERTY.
15179 When TABLE is non-nil, return an alist that can directly be used for
15180 completion."
15181 (let (vals)
15182 (cond
15183 ((equal property "TODO")
15184 (setq vals (org-with-point-at pom
15185 (append org-todo-keywords-1 '("")))))
15186 ((equal property "PRIORITY")
15187 (let ((n org-lowest-priority))
15188 (while (>= n org-highest-priority)
15189 (push (char-to-string n) vals)
15190 (setq n (1- n)))))
15191 ((member property org-special-properties))
15193 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15195 (when (and vals (string-match "\\S-" vals))
15196 (setq vals (car (read-from-string (concat "(" vals ")"))))
15197 (setq vals (mapcar (lambda (x)
15198 (cond ((stringp x) x)
15199 ((numberp x) (number-to-string x))
15200 ((symbolp x) (symbol-name x))
15201 (t "???")))
15202 vals)))))
15203 (if table (mapcar 'list vals) vals)))
15205 (defun org-property-previous-allowed-value (&optional previous)
15206 "Switch to the next allowed value for this property."
15207 (interactive)
15208 (org-property-next-allowed-value t))
15210 (defun org-property-next-allowed-value (&optional previous)
15211 "Switch to the next allowed value for this property."
15212 (interactive)
15213 (unless (org-at-property-p)
15214 (error "Not at a property"))
15215 (let* ((key (match-string 2))
15216 (value (match-string 3))
15217 (allowed (or (org-property-get-allowed-values (point) key)
15218 (and (member value '("[ ]" "[-]" "[X]"))
15219 '("[ ]" "[X]"))))
15220 nval)
15221 (unless allowed
15222 (error "Allowed values for this property have not been defined"))
15223 (if previous (setq allowed (reverse allowed)))
15224 (if (member value allowed)
15225 (setq nval (car (cdr (member value allowed)))))
15226 (setq nval (or nval (car allowed)))
15227 (if (equal nval value)
15228 (error "Only one allowed value for this property"))
15229 (org-at-property-p)
15230 (replace-match (concat " :" key ": " nval) t t)
15231 (org-indent-line-function)
15232 (beginning-of-line 1)
15233 (skip-chars-forward " \t")))
15235 (defun org-find-entry-with-id (ident)
15236 "Locate the entry that contains the ID property with exact value IDENT.
15237 IDENT can be a string, a symbol or a number, this function will search for
15238 the string representation of it.
15239 Return the position where this entry starts, or nil if there is no such entry."
15240 (let ((id (cond
15241 ((stringp ident) ident)
15242 ((symbol-name ident) (symbol-name ident))
15243 ((numberp ident) (number-to-string ident))
15244 (t (error "IDENT %s must be a string, symbol or number" ident))))
15245 (case-fold-search nil))
15246 (save-excursion
15247 (save-restriction
15248 (goto-char (point-min))
15249 (when (re-search-forward
15250 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15251 nil t)
15252 (org-back-to-heading)
15253 (point))))))
15255 ;;; Column View
15257 (defvar org-columns-overlays nil
15258 "Holds the list of current column overlays.")
15260 (defvar org-columns-current-fmt nil
15261 "Local variable, holds the currently active column format.")
15262 (defvar org-columns-current-fmt-compiled nil
15263 "Local variable, holds the currently active column format.
15264 This is the compiled version of the format.")
15265 (defvar org-columns-current-widths nil
15266 "Loval variable, holds the currently widths of fields.")
15267 (defvar org-columns-current-maxwidths nil
15268 "Loval variable, holds the currently active maximum column widths.")
15269 (defvar org-columns-begin-marker (make-marker)
15270 "Points to the position where last a column creation command was called.")
15271 (defvar org-columns-top-level-marker (make-marker)
15272 "Points to the position where current columns region starts.")
15274 (defvar org-columns-map (make-sparse-keymap)
15275 "The keymap valid in column display.")
15277 (defun org-columns-content ()
15278 "Switch to contents view while in columns view."
15279 (interactive)
15280 (org-overview)
15281 (org-content))
15283 (org-defkey org-columns-map "c" 'org-columns-content)
15284 (org-defkey org-columns-map "o" 'org-overview)
15285 (org-defkey org-columns-map "e" 'org-columns-edit-value)
15286 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
15287 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
15288 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
15289 (org-defkey org-columns-map "v" 'org-columns-show-value)
15290 (org-defkey org-columns-map "q" 'org-columns-quit)
15291 (org-defkey org-columns-map "r" 'org-columns-redo)
15292 (org-defkey org-columns-map [left] 'backward-char)
15293 (org-defkey org-columns-map "\M-b" 'backward-char)
15294 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
15295 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
15296 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
15297 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
15298 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
15299 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
15300 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
15301 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
15302 (org-defkey org-columns-map "<" 'org-columns-narrow)
15303 (org-defkey org-columns-map ">" 'org-columns-widen)
15304 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
15305 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
15306 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
15307 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
15309 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
15310 '("Column"
15311 ["Edit property" org-columns-edit-value t]
15312 ["Next allowed value" org-columns-next-allowed-value t]
15313 ["Previous allowed value" org-columns-previous-allowed-value t]
15314 ["Show full value" org-columns-show-value t]
15315 ["Edit allowed values" org-columns-edit-allowed t]
15316 "--"
15317 ["Edit column attributes" org-columns-edit-attributes t]
15318 ["Increase column width" org-columns-widen t]
15319 ["Decrease column width" org-columns-narrow t]
15320 "--"
15321 ["Move column right" org-columns-move-right t]
15322 ["Move column left" org-columns-move-left t]
15323 ["Add column" org-columns-new t]
15324 ["Delete column" org-columns-delete t]
15325 "--"
15326 ["CONTENTS" org-columns-content t]
15327 ["OVERVIEW" org-overview t]
15328 ["Refresh columns display" org-columns-redo t]
15329 "--"
15330 ["Open link" org-columns-open-link t]
15331 "--"
15332 ["Quit" org-columns-quit t]))
15334 (defun org-columns-new-overlay (beg end &optional string face)
15335 "Create a new column overlay and add it to the list."
15336 (let ((ov (org-make-overlay beg end)))
15337 (org-overlay-put ov 'face (or face 'secondary-selection))
15338 (org-overlay-display ov string face)
15339 (push ov org-columns-overlays)
15340 ov))
15342 (defun org-columns-display-here (&optional props)
15343 "Overlay the current line with column display."
15344 (interactive)
15345 (let* ((fmt org-columns-current-fmt-compiled)
15346 (beg (point-at-bol))
15347 (level-face (save-excursion
15348 (beginning-of-line 1)
15349 (and (looking-at "\\(\\**\\)\\(\\* \\)")
15350 (org-get-level-face 2))))
15351 (color (list :foreground
15352 (face-attribute (or level-face 'default) :foreground)))
15353 props pom property ass width f string ov column val modval)
15354 ;; Check if the entry is in another buffer.
15355 (unless props
15356 (if (eq major-mode 'org-agenda-mode)
15357 (setq pom (or (get-text-property (point) 'org-hd-marker)
15358 (get-text-property (point) 'org-marker))
15359 props (if pom (org-entry-properties pom) nil))
15360 (setq props (org-entry-properties nil))))
15361 ;; Walk the format
15362 (while (setq column (pop fmt))
15363 (setq property (car column)
15364 ass (if (equal property "ITEM")
15365 (cons "ITEM"
15366 (save-match-data
15367 (org-no-properties
15368 (org-remove-tabs
15369 (buffer-substring-no-properties
15370 (point-at-bol) (point-at-eol))))))
15371 (assoc property props))
15372 width (or (cdr (assoc property org-columns-current-maxwidths))
15373 (nth 2 column)
15374 (length property))
15375 f (format "%%-%d.%ds | " width width)
15376 val (or (cdr ass) "")
15377 modval (if (equal property "ITEM")
15378 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
15379 string (format f (or modval val)))
15380 ;; Create the overlay
15381 (org-unmodified
15382 (setq ov (org-columns-new-overlay
15383 beg (setq beg (1+ beg)) string
15384 (list color 'org-column)))
15385 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
15386 (org-overlay-put ov 'keymap org-columns-map)
15387 (org-overlay-put ov 'org-columns-key property)
15388 (org-overlay-put ov 'org-columns-value (cdr ass))
15389 (org-overlay-put ov 'org-columns-value-modified modval)
15390 (org-overlay-put ov 'org-columns-pom pom)
15391 (org-overlay-put ov 'org-columns-format f))
15392 (if (or (not (char-after beg))
15393 (equal (char-after beg) ?\n))
15394 (let ((inhibit-read-only t))
15395 (save-excursion
15396 (goto-char beg)
15397 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
15398 ;; Make the rest of the line disappear.
15399 (org-unmodified
15400 (setq ov (org-columns-new-overlay beg (point-at-eol)))
15401 (org-overlay-put ov 'invisible t)
15402 (org-overlay-put ov 'keymap org-columns-map)
15403 (org-overlay-put ov 'intangible t)
15404 (push ov org-columns-overlays)
15405 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
15406 (org-overlay-put ov 'keymap org-columns-map)
15407 (push ov org-columns-overlays)
15408 (let ((inhibit-read-only t))
15409 (put-text-property (max (point-min) (1- (point-at-bol)))
15410 (min (point-max) (1+ (point-at-eol)))
15411 'read-only "Type `e' to edit property")))))
15413 (defvar org-previous-header-line-format nil
15414 "The header line format before column view was turned on.")
15415 (defvar org-columns-inhibit-recalculation nil
15416 "Inhibit recomputing of columns on column view startup.")
15419 (defvar header-line-format)
15420 (defun org-columns-display-here-title ()
15421 "Overlay the newline before the current line with the table title."
15422 (interactive)
15423 (let ((fmt org-columns-current-fmt-compiled)
15424 string (title "")
15425 property width f column str widths)
15426 (while (setq column (pop fmt))
15427 (setq property (car column)
15428 str (or (nth 1 column) property)
15429 width (or (cdr (assoc property org-columns-current-maxwidths))
15430 (nth 2 column)
15431 (length str))
15432 widths (push width widths)
15433 f (format "%%-%d.%ds | " width width)
15434 string (format f str)
15435 title (concat title string)))
15436 (setq title (concat
15437 (org-add-props " " nil 'display '(space :align-to 0))
15438 (org-add-props title nil 'face '(:weight bold :underline t))))
15439 (org-set-local 'org-previous-header-line-format header-line-format)
15440 (org-set-local 'org-columns-current-widths (nreverse widths))
15441 (setq header-line-format title)))
15443 (defun org-columns-remove-overlays ()
15444 "Remove all currently active column overlays."
15445 (interactive)
15446 (when (marker-buffer org-columns-begin-marker)
15447 (with-current-buffer (marker-buffer org-columns-begin-marker)
15448 (when (local-variable-p 'org-previous-header-line-format)
15449 (setq header-line-format org-previous-header-line-format)
15450 (kill-local-variable 'org-previous-header-line-format))
15451 (move-marker org-columns-begin-marker nil)
15452 (move-marker org-columns-top-level-marker nil)
15453 (org-unmodified
15454 (mapc 'org-delete-overlay org-columns-overlays)
15455 (setq org-columns-overlays nil)
15456 (let ((inhibit-read-only t))
15457 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
15459 (defun org-columns-cleanup-item (item fmt)
15460 "Remove from ITEM what is a column in the format FMT."
15461 (if (not org-complex-heading-regexp)
15462 item
15463 (when (string-match org-complex-heading-regexp item)
15464 (concat
15465 (org-add-props (concat (match-string 1 item) " ") nil
15466 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
15467 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
15468 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
15469 " " (match-string 4 item)
15470 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
15472 (defun org-columns-show-value ()
15473 "Show the full value of the property."
15474 (interactive)
15475 (let ((value (get-char-property (point) 'org-columns-value)))
15476 (message "Value is: %s" (or value ""))))
15478 (defun org-columns-quit ()
15479 "Remove the column overlays and in this way exit column editing."
15480 (interactive)
15481 (org-unmodified
15482 (org-columns-remove-overlays)
15483 (let ((inhibit-read-only t))
15484 (remove-text-properties (point-min) (point-max) '(read-only t))))
15485 (when (eq major-mode 'org-agenda-mode)
15486 (message
15487 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
15489 (defun org-columns-check-computed ()
15490 "Check if this column value is computed.
15491 If yes, throw an error indicating that changing it does not make sense."
15492 (let ((val (get-char-property (point) 'org-columns-value)))
15493 (when (and (stringp val)
15494 (get-char-property 0 'org-computed val))
15495 (error "This value is computed from the entry's children"))))
15497 (defun org-columns-todo (&optional arg)
15498 "Change the TODO state during column view."
15499 (interactive "P")
15500 (org-columns-edit-value "TODO"))
15502 (defun org-columns-set-tags-or-toggle (&optional arg)
15503 "Toggle checkbox at point, or set tags for current headline."
15504 (interactive "P")
15505 (if (string-match "\\`\\[[ xX-]\\]\\'"
15506 (get-char-property (point) 'org-columns-value))
15507 (org-columns-next-allowed-value)
15508 (org-columns-edit-value "TAGS")))
15510 (defun org-columns-edit-value (&optional key)
15511 "Edit the value of the property at point in column view.
15512 Where possible, use the standard interface for changing this line."
15513 (interactive)
15514 (org-columns-check-computed)
15515 (let* ((external-key key)
15516 (col (current-column))
15517 (key (or key (get-char-property (point) 'org-columns-key)))
15518 (value (get-char-property (point) 'org-columns-value))
15519 (bol (point-at-bol)) (eol (point-at-eol))
15520 (pom (or (get-text-property bol 'org-hd-marker)
15521 (point))) ; keep despite of compiler waring
15522 (line-overlays
15523 (delq nil (mapcar (lambda (x)
15524 (and (eq (overlay-buffer x) (current-buffer))
15525 (>= (overlay-start x) bol)
15526 (<= (overlay-start x) eol)
15528 org-columns-overlays)))
15529 nval eval allowed)
15530 (cond
15531 ((equal key "ITEM")
15532 (setq eval '(org-with-point-at pom
15533 (org-edit-headline))))
15534 ((equal key "TODO")
15535 (setq eval '(org-with-point-at pom
15536 (let ((current-prefix-arg
15537 (if external-key current-prefix-arg '(4))))
15538 (call-interactively 'org-todo)))))
15539 ((equal key "PRIORITY")
15540 (setq eval '(org-with-point-at pom
15541 (call-interactively 'org-priority))))
15542 ((equal key "TAGS")
15543 (setq eval '(org-with-point-at pom
15544 (let ((org-fast-tag-selection-single-key
15545 (if (eq org-fast-tag-selection-single-key 'expert)
15546 t org-fast-tag-selection-single-key)))
15547 (call-interactively 'org-set-tags)))))
15548 ((equal key "DEADLINE")
15549 (setq eval '(org-with-point-at pom
15550 (call-interactively 'org-deadline))))
15551 ((equal key "SCHEDULED")
15552 (setq eval '(org-with-point-at pom
15553 (call-interactively 'org-schedule))))
15555 (setq allowed (org-property-get-allowed-values pom key 'table))
15556 (if allowed
15557 (setq nval (completing-read "Value: " allowed nil t))
15558 (setq nval (read-string "Edit: " value)))
15559 (setq nval (org-trim nval))
15560 (when (not (equal nval value))
15561 (setq eval '(org-entry-put pom key nval)))))
15562 (when eval
15563 (let ((inhibit-read-only t))
15564 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
15565 (unwind-protect
15566 (progn
15567 (setq org-columns-overlays
15568 (org-delete-all line-overlays org-columns-overlays))
15569 (mapc 'org-delete-overlay line-overlays)
15570 (org-columns-eval eval))
15571 (org-columns-display-here))))
15572 (move-to-column col)
15573 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
15574 (org-columns-update key))))
15576 (defun org-edit-headline () ; FIXME: this is not columns specific
15577 "Edit the current headline, the part without TODO keyword, TAGS."
15578 (org-back-to-heading)
15579 (when (looking-at org-todo-line-regexp)
15580 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
15581 (txt (match-string 3))
15582 (post "")
15583 txt2)
15584 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
15585 (setq post (match-string 0 txt)
15586 txt (substring txt 0 (match-beginning 0))))
15587 (setq txt2 (read-string "Edit: " txt))
15588 (when (not (equal txt txt2))
15589 (beginning-of-line 1)
15590 (insert pre txt2 post)
15591 (delete-region (point) (point-at-eol))
15592 (org-set-tags nil t)))))
15594 (defun org-columns-edit-allowed ()
15595 "Edit the list of allowed values for the current property."
15596 (interactive)
15597 (let* ((key (get-char-property (point) 'org-columns-key))
15598 (key1 (concat key "_ALL"))
15599 (allowed (org-entry-get (point) key1 t))
15600 nval)
15601 ;; FIXME: Cover editing TODO, TAGS etc inbiffer settings.????
15602 (setq nval (read-string "Allowed: " allowed))
15603 (org-entry-put
15604 (cond ((marker-position org-entry-property-inherited-from)
15605 org-entry-property-inherited-from)
15606 ((marker-position org-columns-top-level-marker)
15607 org-columns-top-level-marker))
15608 key1 nval)))
15610 (defun org-columns-eval (form)
15611 (let (hidep)
15612 (save-excursion
15613 (beginning-of-line 1)
15614 ;; `next-line' is needed here, because it skips invisible line.
15615 (condition-case nil (next-line 1) (error nil))
15616 (setq hidep (org-on-heading-p 1)))
15617 (eval form)
15618 (and hidep (hide-entry))))
15620 (defun org-columns-previous-allowed-value ()
15621 "Switch to the previous allowed value for this column."
15622 (interactive)
15623 (org-columns-next-allowed-value t))
15625 (defun org-columns-next-allowed-value (&optional previous)
15626 "Switch to the next allowed value for this column."
15627 (interactive)
15628 (org-columns-check-computed)
15629 (let* ((col (current-column))
15630 (key (get-char-property (point) 'org-columns-key))
15631 (value (get-char-property (point) 'org-columns-value))
15632 (bol (point-at-bol)) (eol (point-at-eol))
15633 (pom (or (get-text-property bol 'org-hd-marker)
15634 (point))) ; keep despite of compiler waring
15635 (line-overlays
15636 (delq nil (mapcar (lambda (x)
15637 (and (eq (overlay-buffer x) (current-buffer))
15638 (>= (overlay-start x) bol)
15639 (<= (overlay-start x) eol)
15641 org-columns-overlays)))
15642 (allowed (or (org-property-get-allowed-values pom key)
15643 (and (equal
15644 (nth 4 (assoc key org-columns-current-fmt-compiled))
15645 'checkbox) '("[ ]" "[X]"))))
15646 nval)
15647 (when (equal key "ITEM")
15648 (error "Cannot edit item headline from here"))
15649 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
15650 (error "Allowed values for this property have not been defined"))
15651 (if (member key '("SCHEDULED" "DEADLINE"))
15652 (setq nval (if previous 'earlier 'later))
15653 (if previous (setq allowed (reverse allowed)))
15654 (if (member value allowed)
15655 (setq nval (car (cdr (member value allowed)))))
15656 (setq nval (or nval (car allowed)))
15657 (if (equal nval value)
15658 (error "Only one allowed value for this property")))
15659 (let ((inhibit-read-only t))
15660 (remove-text-properties (1- bol) eol '(read-only t))
15661 (unwind-protect
15662 (progn
15663 (setq org-columns-overlays
15664 (org-delete-all line-overlays org-columns-overlays))
15665 (mapc 'org-delete-overlay line-overlays)
15666 (org-columns-eval '(org-entry-put pom key nval)))
15667 (org-columns-display-here)))
15668 (move-to-column col)
15669 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
15670 (org-columns-update key))))
15672 (defun org-verify-version (task)
15673 (cond
15674 ((eq task 'columns)
15675 (if (or (featurep 'xemacs)
15676 (< emacs-major-version 22))
15677 (error "Emacs 22 is required for the columns feature")))))
15679 (defun org-columns-open-link (&optional arg)
15680 (interactive "P")
15681 (let ((key (get-char-property (point) 'org-columns-key))
15682 (value (get-char-property (point) 'org-columns-value)))
15683 (org-open-link-from-string arg)))
15685 (defun org-open-link-from-string (s &optional arg)
15686 "Open a link in the string S, as if it was in Org-mode."
15687 (interactive)
15688 (with-temp-buffer
15689 (let ((org-inhibit-startup t))
15690 (org-mode)
15691 (insert s)
15692 (goto-char (point-min))
15693 (org-open-at-point arg))))
15695 (defun org-columns-get-format-and-top-level ()
15696 (let (fmt)
15697 (when (condition-case nil (org-back-to-heading) (error nil))
15698 (move-marker org-entry-property-inherited-from nil)
15699 (setq fmt (org-entry-get nil "COLUMNS" t)))
15700 (setq fmt (or fmt org-columns-default-format))
15701 (org-set-local 'org-columns-current-fmt fmt)
15702 (org-columns-compile-format fmt)
15703 (if (marker-position org-entry-property-inherited-from)
15704 (move-marker org-columns-top-level-marker
15705 org-entry-property-inherited-from)
15706 (move-marker org-columns-top-level-marker (point)))
15707 fmt))
15709 (defun org-columns ()
15710 "Turn on column view on an org-mode file."
15711 (interactive)
15712 (org-verify-version 'columns)
15713 (org-columns-remove-overlays)
15714 (move-marker org-columns-begin-marker (point))
15715 (let (beg end fmt cache maxwidths)
15716 (setq fmt (org-columns-get-format-and-top-level))
15717 (save-excursion
15718 (goto-char org-columns-top-level-marker)
15719 (setq beg (point))
15720 (unless org-columns-inhibit-recalculation
15721 (org-columns-compute-all))
15722 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
15723 (point-max)))
15724 (goto-char beg)
15725 ;; Get and cache the properties
15726 (while (re-search-forward (concat "^" outline-regexp) end t)
15727 (push (cons (org-current-line) (org-entry-properties)) cache))
15728 (when cache
15729 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
15730 (org-set-local 'org-columns-current-maxwidths maxwidths)
15731 (org-columns-display-here-title)
15732 (mapc (lambda (x)
15733 (goto-line (car x))
15734 (org-columns-display-here (cdr x)))
15735 cache)))))
15737 (defun org-columns-new (&optional prop title width op fmt)
15738 "Insert a new column, to the leeft o the current column."
15739 (interactive)
15740 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
15741 cell)
15742 (setq prop (completing-read
15743 "Property: " (mapcar 'list (org-buffer-property-keys t))
15744 nil nil prop))
15745 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
15746 (setq width (read-string "Column width: " (if width (number-to-string width))))
15747 (if (string-match "\\S-" width)
15748 (setq width (string-to-number width))
15749 (setq width nil))
15750 (setq fmt (completing-read "Summary [none]: "
15751 '(("none") ("add_numbers") ("add_times") ("checkbox"))
15752 nil t))
15753 (if (string-match "\\S-" fmt)
15754 (setq fmt (intern fmt))
15755 (setq fmt nil))
15756 (if (eq fmt 'none) (setq fmt nil))
15757 (if editp
15758 (progn
15759 (setcar editp prop)
15760 (setcdr editp (list title width nil fmt)))
15761 (setq cell (nthcdr (1- (current-column))
15762 org-columns-current-fmt-compiled))
15763 (setcdr cell (cons (list prop title width nil fmt)
15764 (cdr cell))))
15765 (org-columns-store-format)
15766 (org-columns-redo)))
15768 (defun org-columns-delete ()
15769 "Delete the column at point from columns view."
15770 (interactive)
15771 (let* ((n (current-column))
15772 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
15773 (when (y-or-n-p
15774 (format "Are you sure you want to remove column \"%s\"? " title))
15775 (setq org-columns-current-fmt-compiled
15776 (delq (nth n org-columns-current-fmt-compiled)
15777 org-columns-current-fmt-compiled))
15778 (org-columns-store-format)
15779 (org-columns-redo)
15780 (if (>= (current-column) (length org-columns-current-fmt-compiled))
15781 (backward-char 1)))))
15783 (defun org-columns-edit-attributes ()
15784 "Edit the attributes of the current column."
15785 (interactive)
15786 (let* ((n (current-column))
15787 (info (nth n org-columns-current-fmt-compiled)))
15788 (apply 'org-columns-new info)))
15790 (defun org-columns-widen (arg)
15791 "Make the column wider by ARG characters."
15792 (interactive "p")
15793 (let* ((n (current-column))
15794 (entry (nth n org-columns-current-fmt-compiled))
15795 (width (or (nth 2 entry)
15796 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
15797 (setq width (max 1 (+ width arg)))
15798 (setcar (nthcdr 2 entry) width)
15799 (org-columns-store-format)
15800 (org-columns-redo)))
15802 (defun org-columns-narrow (arg)
15803 "Make the column nrrower by ARG characters."
15804 (interactive "p")
15805 (org-columns-widen (- arg)))
15807 (defun org-columns-move-right ()
15808 "Swap this column with the one to the right."
15809 (interactive)
15810 (let* ((n (current-column))
15811 (cell (nthcdr n org-columns-current-fmt-compiled))
15813 (when (>= n (1- (length org-columns-current-fmt-compiled)))
15814 (error "Cannot shift this column further to the right"))
15815 (setq e (car cell))
15816 (setcar cell (car (cdr cell)))
15817 (setcdr cell (cons e (cdr (cdr cell))))
15818 (org-columns-store-format)
15819 (org-columns-redo)
15820 (forward-char 1)))
15822 (defun org-columns-move-left ()
15823 "Swap this column with the one to the left."
15824 (interactive)
15825 (let* ((n (current-column)))
15826 (when (= n 0)
15827 (error "Cannot shift this column further to the left"))
15828 (backward-char 1)
15829 (org-columns-move-right)
15830 (backward-char 1)))
15832 (defun org-columns-store-format ()
15833 "Store the text version of the current columns format in appropriate place.
15834 This is either in the COLUMNS property of the node starting the current column
15835 display, or in the #+COLUMNS line of the current buffer."
15836 (let (fmt (cnt 0))
15837 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
15838 (org-set-local 'org-columns-current-fmt fmt)
15839 (if (marker-position org-columns-top-level-marker)
15840 (save-excursion
15841 (goto-char org-columns-top-level-marker)
15842 (if (and (org-at-heading-p)
15843 (org-entry-get nil "COLUMNS"))
15844 (org-entry-put nil "COLUMNS" fmt)
15845 (goto-char (point-min))
15846 ;; Overwrite all #+COLUMNS lines....
15847 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
15848 (setq cnt (1+ cnt))
15849 (replace-match (concat "#+COLUMNS: " fmt) t t))
15850 (unless (> cnt 0)
15851 (goto-char (point-min))
15852 (or (org-on-heading-p t) (outline-next-heading))
15853 (let ((inhibit-read-only t))
15854 (insert-before-markers "#+COLUMNS: " fmt "\n")))
15855 (org-set-local 'org-columns-default-format fmt))))))
15857 (defvar org-overriding-columns-format nil
15858 "When set, overrides any other definition.")
15859 (defvar org-agenda-view-columns-initially nil
15860 "When set, switch to columns view immediately after creating the agenda.")
15862 (defun org-agenda-columns ()
15863 "Turn on column view in the agenda."
15864 (interactive)
15865 (org-verify-version 'columns)
15866 (org-columns-remove-overlays)
15867 (move-marker org-columns-begin-marker (point))
15868 (let (fmt cache maxwidths m)
15869 (cond
15870 ((and (local-variable-p 'org-overriding-columns-format)
15871 org-overriding-columns-format)
15872 (setq fmt org-overriding-columns-format))
15873 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
15874 (setq fmt (org-entry-get m "COLUMNS" t)))
15875 ((and (boundp 'org-columns-current-fmt)
15876 (local-variable-p 'org-columns-current-fmt)
15877 org-columns-current-fmt)
15878 (setq fmt org-columns-current-fmt))
15879 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
15880 (setq m (get-text-property m 'org-hd-marker))
15881 (setq fmt (org-entry-get m "COLUMNS" t))))
15882 (setq fmt (or fmt org-columns-default-format))
15883 (org-set-local 'org-columns-current-fmt fmt)
15884 (org-columns-compile-format fmt)
15885 (save-excursion
15886 ;; Get and cache the properties
15887 (goto-char (point-min))
15888 (while (not (eobp))
15889 (when (setq m (or (get-text-property (point) 'org-hd-marker)
15890 (get-text-property (point) 'org-marker)))
15891 (push (cons (org-current-line) (org-entry-properties m)) cache))
15892 (beginning-of-line 2))
15893 (when cache
15894 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
15895 (org-set-local 'org-columns-current-maxwidths maxwidths)
15896 (org-columns-display-here-title)
15897 (mapc (lambda (x)
15898 (goto-line (car x))
15899 (org-columns-display-here (cdr x)))
15900 cache)))))
15902 (defun org-columns-get-autowidth-alist (s cache)
15903 "Derive the maximum column widths from the format and the cache."
15904 (let ((start 0) rtn)
15905 (while (string-match (org-re "%\\([[:alpha:]]\\S-*\\)") s start)
15906 (push (cons (match-string 1 s) 1) rtn)
15907 (setq start (match-end 0)))
15908 (mapc (lambda (x)
15909 (setcdr x (apply 'max
15910 (mapcar
15911 (lambda (y)
15912 (length (or (cdr (assoc (car x) (cdr y))) " ")))
15913 cache))))
15914 rtn)
15915 rtn))
15917 (defun org-columns-compute-all ()
15918 "Compute all columns that have operators defined."
15919 (org-unmodified
15920 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
15921 (let ((columns org-columns-current-fmt-compiled) col)
15922 (while (setq col (pop columns))
15923 (when (nth 3 col)
15924 (save-excursion
15925 (org-columns-compute (car col)))))))
15927 (defun org-columns-update (property)
15928 "Recompute PROPERTY, and update the columns display for it."
15929 (org-columns-compute property)
15930 (let (fmt val pos)
15931 (save-excursion
15932 (mapc (lambda (ov)
15933 (when (equal (org-overlay-get ov 'org-columns-key) property)
15934 (setq pos (org-overlay-start ov))
15935 (goto-char pos)
15936 (when (setq val (cdr (assoc property
15937 (get-text-property
15938 (point-at-bol) 'org-summaries))))
15939 (setq fmt (org-overlay-get ov 'org-columns-format))
15940 (org-overlay-put ov 'org-columns-value val)
15941 (org-overlay-put ov 'display (format fmt val)))))
15942 org-columns-overlays))))
15944 (defun org-columns-compute (property)
15945 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
15946 (interactive)
15947 (let* ((re (concat "^" outline-regexp))
15948 (lmax 30) ; Does anyone use deeper levels???
15949 (lsum (make-vector lmax 0))
15950 (lflag (make-vector lmax nil))
15951 (level 0)
15952 (ass (assoc property org-columns-current-fmt-compiled))
15953 (format (nth 4 ass))
15954 (beg org-columns-top-level-marker)
15955 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
15956 (save-excursion
15957 ;; Find the region to compute
15958 (goto-char beg)
15959 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
15960 (goto-char end)
15961 ;; Walk the tree from the back and do the computations
15962 (while (re-search-backward re beg t)
15963 (setq sumpos (match-beginning 0)
15964 last-level level
15965 level (org-outline-level)
15966 val (org-entry-get nil property)
15967 valflag (and val (string-match "\\S-" val)))
15968 (cond
15969 ((< level last-level)
15970 ;; put the sum of lower levels here as a property
15971 (setq sum (aref lsum last-level) ; current sum
15972 flag (aref lflag last-level) ; any valid entries from children?
15973 str (org-column-number-to-string sum format)
15974 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
15975 useval (if flag str1 (if valflag val ""))
15976 sum-alist (get-text-property sumpos 'org-summaries))
15977 (if (assoc property sum-alist)
15978 (setcdr (assoc property sum-alist) useval)
15979 (push (cons property useval) sum-alist)
15980 (org-unmodified
15981 (add-text-properties sumpos (1+ sumpos)
15982 (list 'org-summaries sum-alist))))
15983 (when val
15984 (org-entry-put nil property (if flag str val)))
15985 ;; add current to current level accumulator
15986 (when (or flag valflag)
15987 ;; FIXME: is this ok?????????
15988 (aset lsum level (+ (aref lsum level)
15989 (if flag sum (org-column-string-to-number
15990 (if flag str val) format))))
15991 (aset lflag level t))
15992 ;; clear accumulators for deeper levels
15993 (loop for l from (1+ level) to (1- lmax) do
15994 (aset lsum l 0)
15995 (aset lflag l nil)))
15996 ((>= level last-level)
15997 ;; add what we have here to the accumulator for this level
15998 (aset lsum level (+ (aref lsum level)
15999 (org-column-string-to-number (or val "0") format)))
16000 (and valflag (aset lflag level t)))
16001 (t (error "This should not happen")))))))
16003 (defun org-columns-redo ()
16004 "Construct the column display again."
16005 (interactive)
16006 (message "Recomputing columns...")
16007 (save-excursion
16008 (if (marker-position org-columns-begin-marker)
16009 (goto-char org-columns-begin-marker))
16010 (org-columns-remove-overlays)
16011 (if (org-mode-p)
16012 (call-interactively 'org-columns)
16013 (call-interactively 'org-agenda-columns)))
16014 (message "Recomputing columns...done"))
16016 (defun org-columns-not-in-agenda ()
16017 (if (eq major-mode 'org-agenda-mode)
16018 (error "This command is only allowed in Org-mode buffers")))
16021 (defun org-string-to-number (s)
16022 "Convert string to number, and interpret hh:mm:ss."
16023 (if (not (string-match ":" s))
16024 (string-to-number s)
16025 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
16026 (while l
16027 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
16028 sum)))
16030 (defun org-column-number-to-string (n fmt)
16031 "Convert a computed column number to a string value, according to FMT."
16032 (cond
16033 ((eq fmt 'add_times)
16034 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
16035 (format "%d:%02d" h m)))
16036 ((eq fmt 'checkbox)
16037 (cond ((= n (floor n)) "[X]")
16038 ((> n 1.) "[-]")
16039 (t "[ ]")))
16040 (t (number-to-string n))))
16042 (defun org-column-string-to-number (s fmt)
16043 "Convert a column value to a number that can be used for column computing."
16044 (cond
16045 ((string-match ":" s)
16046 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
16047 (while l
16048 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
16049 sum))
16050 ((eq fmt 'checkbox)
16051 (if (equal s "[X]") 1. 0.000001))
16052 (t (string-to-number s))))
16054 (defun org-columns-uncompile-format (cfmt)
16055 "Turn the compiled columns format back into a string representation."
16056 (let ((rtn "") e s prop title op width fmt)
16057 (while (setq e (pop cfmt))
16058 (setq prop (car e)
16059 title (nth 1 e)
16060 width (nth 2 e)
16061 op (nth 3 e)
16062 fmt (nth 4 e))
16063 (cond
16064 ((eq fmt 'add_times) (setq op ":"))
16065 ((eq fmt 'checkbox) (setq op "X"))
16066 ((eq fmt 'add_numbers) (setq op "+")))
16067 (if (equal title prop) (setq title nil))
16068 (setq s (concat "%" (if width (number-to-string width))
16069 prop
16070 (if title (concat "(" title ")"))
16071 (if op (concat "{" op "}"))))
16072 (setq rtn (concat rtn " " s)))
16073 (org-trim rtn)))
16075 (defun org-columns-compile-format (fmt)
16076 "Turn a column format string into an alist of specifications.
16077 The alist has one entry for each column in the format. The elements of
16078 that list are:
16079 property the property
16080 title the title field for the columns
16081 width the column width in characters, can be nil for automatic
16082 operator the operator if any
16083 format the output format for computed results, derived from operator"
16084 (let ((start 0) width prop title op f)
16085 (setq org-columns-current-fmt-compiled nil)
16086 (while (string-match
16087 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
16088 fmt start)
16089 (setq start (match-end 0)
16090 width (match-string 1 fmt)
16091 prop (match-string 2 fmt)
16092 title (or (match-string 3 fmt) prop)
16093 op (match-string 4 fmt)
16094 f nil)
16095 (if width (setq width (string-to-number width)))
16096 (cond
16097 ((equal op "+") (setq f 'add_numbers))
16098 ((equal op ":") (setq f 'add_times))
16099 ((equal op "X") (setq f 'checkbox)))
16100 (push (list prop title width op f) org-columns-current-fmt-compiled))
16101 (setq org-columns-current-fmt-compiled
16102 (nreverse org-columns-current-fmt-compiled))))
16105 ;;; Dynamic block for Column view
16107 (defun org-columns-capture-view ()
16108 "Get the column view of the current buffer and return it as a list.
16109 The list will contains the title row and all other rows. Each row is
16110 a list of fields."
16111 (save-excursion
16112 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
16113 (n (length title)) row tbl)
16114 (goto-char (point-min))
16115 (while (re-search-forward "^\\*+ " nil t)
16116 (when (get-char-property (match-beginning 0) 'org-columns-key)
16117 (setq row nil)
16118 (loop for i from 0 to (1- n) do
16119 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
16120 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
16122 row))
16123 (setq row (nreverse row))
16124 (push row tbl)))
16125 (append (list title 'hline) (nreverse tbl)))))
16127 (defun org-dblock-write:columnview (params)
16128 "Write the column view table.
16129 PARAMS is a property list of parameters:
16131 :width enforce same column widths with <N> specifiers.
16132 :id the :ID: property of the entry where the columns view
16133 should be built, as a string. When `local', call locally.
16134 When `global' call column view with the cursor at the beginning
16135 of the buffer (usually this means that the whole buffer switches
16136 to column view).
16137 :hlines When t, insert a hline before each item. When a number, insert
16138 a hline before each level <= that number.
16139 :vlines When t, make each column a colgroup to enforce vertical lines."
16140 (let ((pos (move-marker (make-marker) (point)))
16141 (hlines (plist-get params :hlines))
16142 (vlines (plist-get params :vlines))
16143 tbl id idpos nfields tmp)
16144 (save-excursion
16145 (save-restriction
16146 (when (setq id (plist-get params :id))
16147 (cond ((not id) nil)
16148 ((eq id 'global) (goto-char (point-min)))
16149 ((eq id 'local) nil)
16150 ((setq idpos (org-find-entry-with-id id))
16151 (goto-char idpos))
16152 (t (error "Cannot find entry with :ID: %s" id))))
16153 (org-columns)
16154 (setq tbl (org-columns-capture-view))
16155 (setq nfields (length (car tbl)))
16156 (org-columns-quit)))
16157 (goto-char pos)
16158 (move-marker pos nil)
16159 (when tbl
16160 (when (plist-get params :hlines)
16161 (setq tmp nil)
16162 (while tbl
16163 (if (eq (car tbl) 'hline)
16164 (push (pop tbl) tmp)
16165 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
16166 (if (and (not (eq (car tmp) 'hline))
16167 (or (eq hlines t)
16168 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
16169 (push 'hline tmp)))
16170 (push (pop tbl) tmp)))
16171 (setq tbl (nreverse tmp)))
16172 (when vlines
16173 (setq tbl (mapcar (lambda (x)
16174 (if (eq 'hline x) x (cons "" x)))
16175 tbl))
16176 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
16177 (setq pos (point))
16178 (insert (org-listtable-to-string tbl))
16179 (when (plist-get params :width)
16180 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
16181 org-columns-current-widths "|")))
16182 (goto-char pos)
16183 (org-table-align))))
16185 (defun org-listtable-to-string (tbl)
16186 "Convert a listtable TBL to a string that contains the Org-mode table.
16187 The table still need to be alligned. The resulting string has no leading
16188 and tailing newline characters."
16189 (mapconcat
16190 (lambda (x)
16191 (cond
16192 ((listp x)
16193 (concat "|" (mapconcat 'identity x "|") "|"))
16194 ((eq x 'hline) "|-|")
16195 (t (error "Garbage in listtable: %s" x))))
16196 tbl "\n"))
16198 (defun org-insert-columns-dblock ()
16199 "Create a dynamic block capturing a column view table."
16200 (interactive)
16201 (let ((defaults '(:name "columnview" :hlines 1))
16202 (id (completing-read
16203 "Capture columns (local, global, entry with :ID: property) [local]: "
16204 (append '(("global") ("local"))
16205 (mapcar 'list (org-property-values "ID"))))))
16206 (if (equal id "") (setq id 'local))
16207 (if (equal id "global") (setq id 'global))
16208 (setq defaults (append defaults (list :id id)))
16209 (org-create-dblock defaults)
16210 (org-update-dblock)))
16212 ;;;; Timestamps
16214 (defvar org-last-changed-timestamp nil)
16215 (defvar org-time-was-given) ; dynamically scoped parameter
16216 (defvar org-end-time-was-given) ; dynamically scoped parameter
16217 (defvar org-ts-what) ; dynamically scoped parameter
16219 (defun org-time-stamp (arg)
16220 "Prompt for a date/time and insert a time stamp.
16221 If the user specifies a time like HH:MM, or if this command is called
16222 with a prefix argument, the time stamp will contain date and time.
16223 Otherwise, only the date will be included. All parts of a date not
16224 specified by the user will be filled in from the current date/time.
16225 So if you press just return without typing anything, the time stamp
16226 will represent the current date/time. If there is already a timestamp
16227 at the cursor, it will be modified."
16228 (interactive "P")
16229 (let ((default-time
16230 ;; Default time is either today, or, when entering a range,
16231 ;; the range start.
16232 (if (or (org-at-timestamp-p t)
16233 (save-excursion
16234 (re-search-backward
16235 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16236 (- (point) 20) t)))
16237 (apply 'encode-time (org-parse-time-string (match-string 1)))
16238 (current-time)))
16239 org-time-was-given org-end-time-was-given time)
16240 (cond
16241 ((and (org-at-timestamp-p)
16242 (eq last-command 'org-time-stamp)
16243 (eq this-command 'org-time-stamp))
16244 (insert "--")
16245 (setq time (let ((this-command this-command))
16246 (org-read-date arg 'totime nil nil default-time)))
16247 (org-insert-time-stamp time (or org-time-was-given arg)))
16248 ((org-at-timestamp-p)
16249 (setq time (let ((this-command this-command))
16250 (org-read-date arg 'totime nil nil default-time)))
16251 (when (org-at-timestamp-p) ; just to get the match data
16252 (replace-match "")
16253 (setq org-last-changed-timestamp
16254 (org-insert-time-stamp
16255 time (or org-time-was-given arg)
16256 nil nil nil (list org-end-time-was-given))))
16257 (message "Timestamp updated"))
16259 (setq time (let ((this-command this-command))
16260 (org-read-date arg 'totime nil nil default-time)))
16261 (org-insert-time-stamp time (or org-time-was-given arg)
16262 nil nil nil (list org-end-time-was-given))))))
16264 (defun org-time-stamp-inactive (&optional arg)
16265 "Insert an inactive time stamp.
16266 An inactive time stamp is enclosed in square brackets instead of angle
16267 brackets. It is inactive in the sense that it does not trigger agenda entries,
16268 does not link to the calendar and cannot be changed with the S-cursor keys.
16269 So these are more for recording a certain time/date."
16270 (interactive "P")
16271 (let (org-time-was-given org-end-time-was-given time)
16272 (setq time (org-read-date arg 'totime))
16273 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
16274 nil nil (list org-end-time-was-given))))
16276 (defvar org-date-ovl (org-make-overlay 1 1))
16277 (org-overlay-put org-date-ovl 'face 'org-warning)
16278 (org-detach-overlay org-date-ovl)
16280 (defvar org-ans1) ; dynamically scoped parameter
16281 (defvar org-ans2) ; dynamically scoped parameter
16283 (defvar org-plain-time-of-day-regexp) ; defined below
16284 (defun org-read-date (&optional with-time to-time from-string prompt
16285 default-time)
16286 "Read a date and make things smooth for the user.
16287 The prompt will suggest to enter an ISO date, but you can also enter anything
16288 which will at least partially be understood by `parse-time-string'.
16289 Unrecognized parts of the date will default to the current day, month, year,
16290 hour and minute. If this command is called to replace a timestamp at point,
16291 of to enter the second timestamp of a range, the default time is taken from the
16292 existing stamp. For example,
16293 3-2-5 --> 2003-02-05
16294 feb 15 --> currentyear-02-15
16295 sep 12 9 --> 2009-09-12
16296 12:45 --> today 12:45
16297 22 sept 0:34 --> currentyear-09-22 0:34
16298 12 --> currentyear-currentmonth-12
16299 Fri --> nearest Friday (today or later)
16300 etc.
16302 Furthermore you can specify a relative date by giving, as the *first* thing
16303 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
16304 change in days weeks, months, years.
16305 With a single plus or minus, the date is relative to today. With a double
16306 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16307 +4d --> four days from today
16308 +4 --> same as above
16309 +2w --> two weeks from today
16310 ++5 --> five days from default date
16312 The function understands only English month and weekday abbreviations,
16313 but this can be configured with the variables `parse-time-months' and
16314 `parse-time-weekdays'.
16316 While prompting, a calendar is popped up - you can also select the
16317 date with the mouse (button 1). The calendar shows a period of three
16318 months. To scroll it to other months, use the keys `>' and `<'.
16319 If you don't like the calendar, turn it off with
16320 \(setq org-popup-calendar-for-date-prompt nil)
16322 With optional argument TO-TIME, the date will immediately be converted
16323 to an internal time.
16324 With an optional argument WITH-TIME, the prompt will suggest to also
16325 insert a time. Note that when WITH-TIME is not set, you can still
16326 enter a time, and this function will inform the calling routine about
16327 this change. The calling routine may then choose to change the format
16328 used to insert the time stamp into the buffer to include the time.
16329 With optional argument FROM-STRING, read fomr this string instead from
16330 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16331 the time/date that is used for everything that is not specified by the
16332 user."
16333 (require 'parse-time)
16334 (let* ((org-time-stamp-rounding-minutes
16335 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
16336 (ct (org-current-time))
16337 (def (or default-time ct))
16338 (defdecode (decode-time def))
16339 (calendar-move-hook nil)
16340 (view-diary-entries-initially nil)
16341 (view-calendar-holidays-initially nil)
16342 (timestr (format-time-string
16343 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
16344 (prompt (concat (if prompt (concat prompt " ") "")
16345 (format "Date and/or time (default [%s]): " timestr)))
16346 ans (org-ans0 "") org-ans1 org-ans2 delta deltan deltaw deltadef
16347 second minute hour day month year tl wday wday1 pm h2 m2)
16349 (cond
16350 (from-string (setq ans from-string))
16351 (org-popup-calendar-for-date-prompt
16352 (save-excursion
16353 (save-window-excursion
16354 (calendar)
16355 (calendar-forward-day (- (time-to-days def)
16356 (calendar-absolute-from-gregorian
16357 (calendar-current-date))))
16358 (org-eval-in-calendar nil t)
16359 (let* ((old-map (current-local-map))
16360 (map (copy-keymap calendar-mode-map))
16361 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
16362 (org-defkey map (kbd "RET") 'org-calendar-select)
16363 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
16364 'org-calendar-select-mouse)
16365 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
16366 'org-calendar-select-mouse)
16367 (org-defkey minibuffer-local-map [(meta shift left)]
16368 (lambda () (interactive)
16369 (org-eval-in-calendar '(calendar-backward-month 1))))
16370 (org-defkey minibuffer-local-map [(meta shift right)]
16371 (lambda () (interactive)
16372 (org-eval-in-calendar '(calendar-forward-month 1))))
16373 (org-defkey minibuffer-local-map [(shift up)]
16374 (lambda () (interactive)
16375 (org-eval-in-calendar '(calendar-backward-week 1))))
16376 (org-defkey minibuffer-local-map [(shift down)]
16377 (lambda () (interactive)
16378 (org-eval-in-calendar '(calendar-forward-week 1))))
16379 (org-defkey minibuffer-local-map [(shift left)]
16380 (lambda () (interactive)
16381 (org-eval-in-calendar '(calendar-backward-day 1))))
16382 (org-defkey minibuffer-local-map [(shift right)]
16383 (lambda () (interactive)
16384 (org-eval-in-calendar '(calendar-forward-day 1))))
16385 (org-defkey minibuffer-local-map ">"
16386 (lambda () (interactive)
16387 (org-eval-in-calendar '(scroll-calendar-left 1))))
16388 (org-defkey minibuffer-local-map "<"
16389 (lambda () (interactive)
16390 (org-eval-in-calendar '(scroll-calendar-right 1))))
16391 (unwind-protect
16392 (progn
16393 (use-local-map map)
16394 (setq org-ans0 (read-string prompt "" nil nil))
16395 ;; org-ans0: from prompt
16396 ;; org-ans1: from mouse click
16397 ;; org-ans2: from calendar motion
16398 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16399 (use-local-map old-map))))))
16400 (t ; Naked prompt only
16401 (setq ans (read-string prompt "" nil timestr))))
16402 (org-detach-overlay org-date-ovl)
16404 (when (setq delta (org-read-date-get-relative ans (current-time) def))
16405 (setq ans (replace-match "" t t ans)
16406 deltan (car delta)
16407 deltaw (nth 1 delta)
16408 deltadef (nth 2 delta)))
16410 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
16411 (when (string-match
16412 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16413 (setq year (if (match-end 2)
16414 (string-to-number (match-string 2 ans))
16415 (string-to-number (format-time-string "%Y")))
16416 month (string-to-number (match-string 3 ans))
16417 day (string-to-number (match-string 4 ans)))
16418 (if (< year 100) (setq year (+ 2000 year)))
16419 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16420 t nil ans)))
16421 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16422 ;; If there is a time with am/pm, and *no* time without it, we convert
16423 ;; so that matching will be successful.
16424 (loop for i from 1 to 2 do ; twice, for end time as well
16425 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16426 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16427 (setq hour (string-to-number (match-string 1 ans))
16428 minute (if (match-end 3)
16429 (string-to-number (match-string 3 ans))
16431 pm (equal ?p
16432 (string-to-char (downcase (match-string 4 ans)))))
16433 (if (and (= hour 12) (not pm))
16434 (setq hour 0)
16435 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16436 (setq ans (replace-match (format "%02d:%02d" hour minute)
16437 t t ans))))
16439 ;; Check if a time range is given as a duration
16440 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16441 (setq hour (string-to-number (match-string 1 ans))
16442 h2 (+ hour (string-to-number (match-string 3 ans)))
16443 minute (string-to-number (match-string 2 ans))
16444 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
16445 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
16447 ;; Check if there is a time range
16448 (when (and (boundp 'org-end-time-was-given)
16449 (string-match org-plain-time-of-day-regexp ans)
16450 (match-end 8))
16451 (setq org-end-time-was-given (match-string 8 ans))
16452 (setq ans (concat (substring ans 0 (match-beginning 7))
16453 (substring ans (match-end 7)))))
16455 (setq tl (parse-time-string ans)
16456 day (or (nth 3 tl) (string-to-number (format-time-string "%d" def)))
16457 month (or (nth 4 tl) (string-to-number (format-time-string "%m" def)))
16458 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" def)))
16459 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" def)))
16460 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" def)))
16461 second (or (nth 0 tl) 0)
16462 wday (nth 6 tl))
16463 (when deltan
16464 (unless deltadef
16465 (let ((now (decode-time (current-time))))
16466 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16467 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16468 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16469 ((equal deltaw "m") (setq month (+ month deltan)))
16470 ((equal deltaw "y") (setq year (+ year deltan)))))
16471 (when (and wday (not (nth 3 tl)))
16472 ;; Weekday was given, but no day, so pick that day in the week
16473 ;; on or after the derived date.
16474 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16475 (unless (equal wday wday1)
16476 (setq day (+ day (% (- wday wday1 -7) 7)))))
16477 (if (and (boundp 'org-time-was-given)
16478 (nth 2 tl))
16479 (setq org-time-was-given t))
16480 (if (< year 100) (setq year (+ 2000 year)))
16481 (if to-time
16482 (encode-time second minute hour day month year)
16483 (if (or (nth 1 tl) (nth 2 tl))
16484 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
16485 (format "%04d-%02d-%02d" year month day)))))
16487 ;(defun org-parse-for-shift (n1 n2 given-dec default-dec)
16488 ; (cond
16489 ; ((not (nth n1 given-dec))
16490 ; (nth n1 default-dec))
16491 ; ((or (> (nth n1 given-dec) (nth n1 (default-dec)))
16492 ; (not org-read-date-prefer-future))
16493 ; (nth n1 given-dec))
16494 ; (t (1+
16495 ; (if (nth 3 given-dec)
16496 ; (nth 3 given-dec)
16497 ; (if (> (nth
16498 ; (setq given
16499 ; (if (and
16501 (defvar parse-time-weekdays)
16503 (defun org-read-date-get-relative (s today default)
16504 "Check string S for special relative date string.
16505 TODAY and DEFAULT are internal times, for today and for a default.
16506 Return shift list (N what def-flag)
16507 WHAT is \"d\", \"w\", \"m\", or \"y\" for day. week, month, year.
16508 N is the number if WHATs to shift
16509 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16510 the DEFAULT date rather than TODAY."
16511 (when (string-match
16512 (concat
16513 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
16514 "\\([0-9]+\\)?"
16515 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16516 "\\([ \t]\\|$\\)") s)
16517 (let* ((dir (if (match-end 1)
16518 (string-to-char (substring (match-string 1 s) -1))
16519 ?+))
16520 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16521 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16522 (what (if (match-end 3) (match-string 3 s) "d"))
16523 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16524 (date (if rel default today))
16525 (wday (nth 6 (decode-time date)))
16526 delta)
16527 (if wday1
16528 (progn
16529 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16530 (if (= dir ?-) (setq delta (- delta 7)))
16531 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16532 (list delta "d" rel))
16533 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16535 (defun org-eval-in-calendar (form &optional keepdate)
16536 "Eval FORM in the calendar window and return to current window.
16537 Also, store the cursor date in variable org-ans2."
16538 (let ((sw (selected-window)))
16539 (select-window (get-buffer-window "*Calendar*"))
16540 (eval form)
16541 (when (and (not keepdate) (calendar-cursor-to-date))
16542 (let* ((date (calendar-cursor-to-date))
16543 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16544 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16545 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16546 (select-window sw)
16547 ;; Update the prompt to show new default date
16548 (save-excursion
16549 (goto-char (point-min))
16550 (when (and org-ans2
16551 (re-search-forward "\\[[-0-9]+\\]" nil t)
16552 (get-text-property (match-end 0) 'field))
16553 (let ((inhibit-read-only t))
16554 (replace-match (concat "[" org-ans2 "]") t t)
16555 (add-text-properties (point-min) (1+ (match-end 0))
16556 (text-properties-at (1+ (point-min)))))))))
16558 (defun org-calendar-select ()
16559 "Return to `org-read-date' with the date currently selected.
16560 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16561 (interactive)
16562 (when (calendar-cursor-to-date)
16563 (let* ((date (calendar-cursor-to-date))
16564 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16565 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16566 (if (active-minibuffer-window) (exit-minibuffer))))
16568 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16569 "Insert a date stamp for the date given by the internal TIME.
16570 WITH-HM means, use the stamp format that includes the time of the day.
16571 INACTIVE means use square brackets instead of angular ones, so that the
16572 stamp will not contribute to the agenda.
16573 PRE and POST are optional strings to be inserted before and after the
16574 stamp.
16575 The command returns the inserted time stamp."
16576 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16577 stamp)
16578 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16579 (insert-before-markers (or pre ""))
16580 (insert-before-markers (setq stamp (format-time-string fmt time)))
16581 (when (listp extra)
16582 (setq extra (car extra))
16583 (if (and (stringp extra)
16584 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16585 (setq extra (format "-%02d:%02d"
16586 (string-to-number (match-string 1 extra))
16587 (string-to-number (match-string 2 extra))))
16588 (setq extra nil)))
16589 (when extra
16590 (backward-char 1)
16591 (insert-before-markers extra)
16592 (forward-char 1))
16593 (insert-before-markers (or post ""))
16594 stamp))
16596 (defun org-toggle-time-stamp-overlays ()
16597 "Toggle the use of custom time stamp formats."
16598 (interactive)
16599 (setq org-display-custom-times (not org-display-custom-times))
16600 (unless org-display-custom-times
16601 (let ((p (point-min)) (bmp (buffer-modified-p)))
16602 (while (setq p (next-single-property-change p 'display))
16603 (if (and (get-text-property p 'display)
16604 (eq (get-text-property p 'face) 'org-date))
16605 (remove-text-properties
16606 p (setq p (next-single-property-change p 'display))
16607 '(display t))))
16608 (set-buffer-modified-p bmp)))
16609 (if (featurep 'xemacs)
16610 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16611 (org-restart-font-lock)
16612 (setq org-table-may-need-update t)
16613 (if org-display-custom-times
16614 (message "Time stamps are overlayed with custom format")
16615 (message "Time stamp overlays removed")))
16617 (defun org-display-custom-time (beg end)
16618 "Overlay modified time stamp format over timestamp between BED and END."
16619 (let* ((ts (buffer-substring beg end))
16620 t1 w1 with-hm tf time str w2 (off 0))
16621 (save-match-data
16622 (setq t1 (org-parse-time-string ts t))
16623 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
16624 (setq off (- (match-end 0) (match-beginning 0)))))
16625 (setq end (- end off))
16626 (setq w1 (- end beg)
16627 with-hm (and (nth 1 t1) (nth 2 t1))
16628 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16629 time (org-fix-decoded-time t1)
16630 str (org-add-props
16631 (format-time-string
16632 (substring tf 1 -1) (apply 'encode-time time))
16633 nil 'mouse-face 'highlight)
16634 w2 (length str))
16635 (if (not (= w2 w1))
16636 (add-text-properties (1+ beg) (+ 2 beg)
16637 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16638 (if (featurep 'xemacs)
16639 (progn
16640 (put-text-property beg end 'invisible t)
16641 (put-text-property beg end 'end-glyph (make-glyph str)))
16642 (put-text-property beg end 'display str))))
16644 (defun org-translate-time (string)
16645 "Translate all timestamps in STRING to custom format.
16646 But do this only if the variable `org-display-custom-times' is set."
16647 (when org-display-custom-times
16648 (save-match-data
16649 (let* ((start 0)
16650 (re org-ts-regexp-both)
16651 t1 with-hm inactive tf time str beg end)
16652 (while (setq start (string-match re string start))
16653 (setq beg (match-beginning 0)
16654 end (match-end 0)
16655 t1 (save-match-data
16656 (org-parse-time-string (substring string beg end) t))
16657 with-hm (and (nth 1 t1) (nth 2 t1))
16658 inactive (equal (substring string beg (1+ beg)) "[")
16659 tf (funcall (if with-hm 'cdr 'car)
16660 org-time-stamp-custom-formats)
16661 time (org-fix-decoded-time t1)
16662 str (format-time-string
16663 (concat
16664 (if inactive "[" "<") (substring tf 1 -1)
16665 (if inactive "]" ">"))
16666 (apply 'encode-time time))
16667 string (replace-match str t t string)
16668 start (+ start (length str)))))))
16669 string)
16671 (defun org-fix-decoded-time (time)
16672 "Set 0 instead of nil for the first 6 elements of time.
16673 Don't touch the rest."
16674 (let ((n 0))
16675 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16677 (defun org-days-to-time (timestamp-string)
16678 "Difference between TIMESTAMP-STRING and now in days."
16679 (- (time-to-days (org-time-string-to-time timestamp-string))
16680 (time-to-days (current-time))))
16682 (defun org-deadline-close (timestamp-string &optional ndays)
16683 "Is the time in TIMESTAMP-STRING close to the current date?"
16684 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16685 (and (< (org-days-to-time timestamp-string) ndays)
16686 (not (org-entry-is-done-p))))
16688 (defun org-get-wdays (ts)
16689 "Get the deadline lead time appropriate for timestring TS."
16690 (cond
16691 ((<= org-deadline-warning-days 0)
16692 ;; 0 or negative, enforce this value no matter what
16693 (- org-deadline-warning-days))
16694 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
16695 ;; lead time is specified.
16696 (floor (* (string-to-number (match-string 1 ts))
16697 (cdr (assoc (match-string 2 ts)
16698 '(("d" . 1) ("w" . 7)
16699 ("m" . 30.4) ("y" . 365.25)))))))
16700 ;; go for the default.
16701 (t org-deadline-warning-days)))
16703 (defun org-calendar-select-mouse (ev)
16704 "Return to `org-read-date' with the date currently selected.
16705 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16706 (interactive "e")
16707 (mouse-set-point ev)
16708 (when (calendar-cursor-to-date)
16709 (let* ((date (calendar-cursor-to-date))
16710 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16711 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16712 (if (active-minibuffer-window) (exit-minibuffer))))
16714 (defun org-check-deadlines (ndays)
16715 "Check if there are any deadlines due or past due.
16716 A deadline is considered due if it happens within `org-deadline-warning-days'
16717 days from today's date. If the deadline appears in an entry marked DONE,
16718 it is not shown. The prefix arg NDAYS can be used to test that many
16719 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16720 (interactive "P")
16721 (let* ((org-warn-days
16722 (cond
16723 ((equal ndays '(4)) 100000)
16724 (ndays (prefix-numeric-value ndays))
16725 (t (abs org-deadline-warning-days))))
16726 (case-fold-search nil)
16727 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16728 (callback
16729 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16731 (message "%d deadlines past-due or due within %d days"
16732 (org-occur regexp nil callback)
16733 org-warn-days)))
16735 (defun org-evaluate-time-range (&optional to-buffer)
16736 "Evaluate a time range by computing the difference between start and end.
16737 Normally the result is just printed in the echo area, but with prefix arg
16738 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16739 If the time range is actually in a table, the result is inserted into the
16740 next column.
16741 For time difference computation, a year is assumed to be exactly 365
16742 days in order to avoid rounding problems."
16743 (interactive "P")
16745 (org-clock-update-time-maybe)
16746 (save-excursion
16747 (unless (org-at-date-range-p t)
16748 (goto-char (point-at-bol))
16749 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16750 (if (not (org-at-date-range-p t))
16751 (error "Not at a time-stamp range, and none found in current line")))
16752 (let* ((ts1 (match-string 1))
16753 (ts2 (match-string 2))
16754 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16755 (match-end (match-end 0))
16756 (time1 (org-time-string-to-time ts1))
16757 (time2 (org-time-string-to-time ts2))
16758 (t1 (time-to-seconds time1))
16759 (t2 (time-to-seconds time2))
16760 (diff (abs (- t2 t1)))
16761 (negative (< (- t2 t1) 0))
16762 ;; (ys (floor (* 365 24 60 60)))
16763 (ds (* 24 60 60))
16764 (hs (* 60 60))
16765 (fy "%dy %dd %02d:%02d")
16766 (fy1 "%dy %dd")
16767 (fd "%dd %02d:%02d")
16768 (fd1 "%dd")
16769 (fh "%02d:%02d")
16770 y d h m align)
16771 (if havetime
16772 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16774 d (floor (/ diff ds)) diff (mod diff ds)
16775 h (floor (/ diff hs)) diff (mod diff hs)
16776 m (floor (/ diff 60)))
16777 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16779 d (floor (+ (/ diff ds) 0.5))
16780 h 0 m 0))
16781 (if (not to-buffer)
16782 (message (org-make-tdiff-string y d h m))
16783 (when (org-at-table-p)
16784 (goto-char match-end)
16785 (setq align t)
16786 (and (looking-at " *|") (goto-char (match-end 0))))
16787 (if (looking-at
16788 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16789 (replace-match ""))
16790 (if negative (insert " -"))
16791 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16792 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16793 (insert " " (format fh h m))))
16794 (if align (org-table-align))
16795 (message "Time difference inserted")))))
16797 (defun org-make-tdiff-string (y d h m)
16798 (let ((fmt "")
16799 (l nil))
16800 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16801 l (push y l)))
16802 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16803 l (push d l)))
16804 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16805 l (push h l)))
16806 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16807 l (push m l)))
16808 (apply 'format fmt (nreverse l))))
16810 (defun org-time-string-to-time (s)
16811 (apply 'encode-time (org-parse-time-string s)))
16813 (defun org-time-string-to-absolute (s &optional daynr)
16814 "Convert a time stamp to an absolute day number.
16815 If there is a specifyer for a cyclic time stamp, get the closest date to
16816 DAYNR."
16817 (cond
16818 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16819 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16820 daynr
16821 (+ daynr 1000)))
16822 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
16823 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16824 (time-to-days (current-time))) (match-string 0 s)))
16825 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
16827 (defun org-time-from-absolute (d)
16828 "Return the time corresponding to date D.
16829 D may be an absolute day number, or a calendar-type list (month day year)."
16830 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16831 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16833 (defun org-calendar-holiday ()
16834 "List of holidays, for Diary display in Org-mode."
16835 (let ((hl (check-calendar-holidays date)))
16836 (if hl (mapconcat 'identity hl "; "))))
16838 (defun org-diary-sexp-entry (sexp entry date)
16839 "Process a SEXP diary ENTRY for DATE."
16840 (require 'diary-lib)
16841 (let ((result (if calendar-debug-sexp
16842 (let ((stack-trace-on-error t))
16843 (eval (car (read-from-string sexp))))
16844 (condition-case nil
16845 (eval (car (read-from-string sexp)))
16846 (error
16847 (beep)
16848 (message "Bad sexp at line %d in %s: %s"
16849 (org-current-line)
16850 (buffer-file-name) sexp)
16851 (sleep-for 2))))))
16852 (cond ((stringp result) result)
16853 ((and (consp result)
16854 (stringp (cdr result))) (cdr result))
16855 (result entry)
16856 (t nil))))
16858 (defun org-diary-to-ical-string (frombuf)
16859 "Get iCalendar entreis from diary entries in buffer FROMBUF.
16860 This uses the icalendar.el library."
16861 (let* ((tmpdir (if (featurep 'xemacs)
16862 (temp-directory)
16863 temporary-file-directory))
16864 (tmpfile (make-temp-name
16865 (expand-file-name "orgics" tmpdir)))
16866 buf rtn b e)
16867 (save-excursion
16868 (set-buffer frombuf)
16869 (icalendar-export-region (point-min) (point-max) tmpfile)
16870 (setq buf (find-buffer-visiting tmpfile))
16871 (set-buffer buf)
16872 (goto-char (point-min))
16873 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16874 (setq b (match-beginning 0)))
16875 (goto-char (point-max))
16876 (if (re-search-backward "^END:VEVENT" nil t)
16877 (setq e (match-end 0)))
16878 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16879 (kill-buffer buf)
16880 (kill-buffer frombuf)
16881 (delete-file tmpfile)
16882 rtn))
16884 (defun org-closest-date (start current change)
16885 "Find the date closest to CURRENT that is consistent with START and CHANGE."
16886 ;; Make the proper lists from the dates
16887 (catch 'exit
16888 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16889 dn dw sday cday n1 n2
16890 d m y y1 y2 date1 date2 nmonths nm ny m2)
16892 (setq start (org-date-to-gregorian start)
16893 current (org-date-to-gregorian
16894 (if org-agenda-repeating-timestamp-show-all
16895 current
16896 (time-to-days (current-time))))
16897 sday (calendar-absolute-from-gregorian start)
16898 cday (calendar-absolute-from-gregorian current))
16900 (if (<= cday sday) (throw 'exit sday))
16902 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
16903 (setq dn (string-to-number (match-string 1 change))
16904 dw (cdr (assoc (match-string 2 change) a1)))
16905 (error "Invalid change specifyer: %s" change))
16906 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16907 (cond
16908 ((eq dw 'day)
16909 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16910 n2 (+ n1 dn)))
16911 ((eq dw 'year)
16912 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16913 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16914 (setq date1 (list m d y1)
16915 n1 (calendar-absolute-from-gregorian date1)
16916 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16917 n2 (calendar-absolute-from-gregorian date2)))
16918 ((eq dw 'month)
16919 ;; approx number of month between the tow dates
16920 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16921 ;; How often does dn fit in there?
16922 (setq d (nth 1 start) m (car start) y (nth 2 start)
16923 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16924 m (+ m nm)
16925 ny (floor (/ m 12))
16926 y (+ y ny)
16927 m (- m (* ny 12)))
16928 (while (> m 12) (setq m (- m 12) y (1+ y)))
16929 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16930 (setq m2 (+ m dn) y2 y)
16931 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16932 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16933 (while (< n2 cday)
16934 (setq n1 n2 m m2 y y2)
16935 (setq m2 (+ m dn) y2 y)
16936 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16937 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16939 (if org-agenda-repeating-timestamp-show-all
16940 (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)
16941 (if (= cday n1) n1 n2)))))
16943 (defun org-date-to-gregorian (date)
16944 "Turn any specification of DATE into a gregorian date for the calendar."
16945 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16946 ((and (listp date) (= (length date) 3)) date)
16947 ((stringp date)
16948 (setq date (org-parse-time-string date))
16949 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16950 ((listp date)
16951 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16953 (defun org-parse-time-string (s &optional nodefault)
16954 "Parse the standard Org-mode time string.
16955 This should be a lot faster than the normal `parse-time-string'.
16956 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16957 hour and minute fields will be nil if not given."
16958 (if (string-match org-ts-regexp0 s)
16959 (list 0
16960 (if (or (match-beginning 8) (not nodefault))
16961 (string-to-number (or (match-string 8 s) "0")))
16962 (if (or (match-beginning 7) (not nodefault))
16963 (string-to-number (or (match-string 7 s) "0")))
16964 (string-to-number (match-string 4 s))
16965 (string-to-number (match-string 3 s))
16966 (string-to-number (match-string 2 s))
16967 nil nil nil)
16968 (make-list 9 0)))
16970 (defun org-timestamp-up (&optional arg)
16971 "Increase the date item at the cursor by one.
16972 If the cursor is on the year, change the year. If it is on the month or
16973 the day, change that.
16974 With prefix ARG, change by that many units."
16975 (interactive "p")
16976 (org-timestamp-change (prefix-numeric-value arg)))
16978 (defun org-timestamp-down (&optional arg)
16979 "Decrease the date item at the cursor by one.
16980 If the cursor is on the year, change the year. If it is on the month or
16981 the day, change that.
16982 With prefix ARG, change by that many units."
16983 (interactive "p")
16984 (org-timestamp-change (- (prefix-numeric-value arg))))
16986 (defun org-timestamp-up-day (&optional arg)
16987 "Increase the date in the time stamp by one day.
16988 With prefix ARG, change that many days."
16989 (interactive "p")
16990 (if (and (not (org-at-timestamp-p t))
16991 (org-on-heading-p))
16992 (org-todo 'up)
16993 (org-timestamp-change (prefix-numeric-value arg) 'day)))
16995 (defun org-timestamp-down-day (&optional arg)
16996 "Decrease the date in the time stamp by one day.
16997 With prefix ARG, change that many days."
16998 (interactive "p")
16999 (if (and (not (org-at-timestamp-p t))
17000 (org-on-heading-p))
17001 (org-todo 'down)
17002 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
17004 (defsubst org-pos-in-match-range (pos n)
17005 (and (match-beginning n)
17006 (<= (match-beginning n) pos)
17007 (>= (match-end n) pos)))
17009 (defun org-at-timestamp-p (&optional inactive-ok)
17010 "Determine if the cursor is in or at a timestamp."
17011 (interactive)
17012 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17013 (pos (point))
17014 (ans (or (looking-at tsr)
17015 (save-excursion
17016 (skip-chars-backward "^[<\n\r\t")
17017 (if (> (point) (point-min)) (backward-char 1))
17018 (and (looking-at tsr)
17019 (> (- (match-end 0) pos) -1))))))
17020 (and ans
17021 (boundp 'org-ts-what)
17022 (setq org-ts-what
17023 (cond
17024 ((= pos (match-beginning 0)) 'bracket)
17025 ((= pos (1- (match-end 0))) 'bracket)
17026 ((org-pos-in-match-range pos 2) 'year)
17027 ((org-pos-in-match-range pos 3) 'month)
17028 ((org-pos-in-match-range pos 7) 'hour)
17029 ((org-pos-in-match-range pos 8) 'minute)
17030 ((or (org-pos-in-match-range pos 4)
17031 (org-pos-in-match-range pos 5)) 'day)
17032 ((and (> pos (or (match-end 8) (match-end 5)))
17033 (< pos (match-end 0)))
17034 (- pos (or (match-end 8) (match-end 5))))
17035 (t 'day))))
17036 ans))
17038 (defun org-toggle-timestamp-type ()
17040 (interactive)
17041 (when (org-at-timestamp-p t)
17042 (save-excursion
17043 (goto-char (match-beginning 0))
17044 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
17045 (goto-char (1- (match-end 0)))
17046 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
17047 (message "Timestamp is now %sactive"
17048 (if (equal (char-before) ?>) "in" ""))))
17050 (defun org-timestamp-change (n &optional what)
17051 "Change the date in the time stamp at point.
17052 The date will be changed by N times WHAT. WHAT can be `day', `month',
17053 `year', `minute', `second'. If WHAT is not given, the cursor position
17054 in the timestamp determines what will be changed."
17055 (let ((pos (point))
17056 with-hm inactive
17057 org-ts-what
17058 extra
17059 ts time time0)
17060 (if (not (org-at-timestamp-p t))
17061 (error "Not at a timestamp"))
17062 (if (and (not what) (eq org-ts-what 'bracket))
17063 (org-toggle-timestamp-type)
17064 (if (and (not what) (not (eq org-ts-what 'day))
17065 org-display-custom-times
17066 (get-text-property (point) 'display)
17067 (not (get-text-property (1- (point)) 'display)))
17068 (setq org-ts-what 'day))
17069 (setq org-ts-what (or what org-ts-what)
17070 inactive (= (char-after (match-beginning 0)) ?\[)
17071 ts (match-string 0))
17072 (replace-match "")
17073 (if (string-match
17074 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
17076 (setq extra (match-string 1 ts)))
17077 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17078 (setq with-hm t))
17079 (setq time0 (org-parse-time-string ts))
17080 (setq time
17081 (encode-time (or (car time0) 0)
17082 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17083 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17084 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17085 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17086 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17087 (nthcdr 6 time0)))
17088 (when (integerp org-ts-what)
17089 (setq extra (org-modify-ts-extra extra org-ts-what n)))
17090 (if (eq what 'calendar)
17091 (let ((cal-date (org-get-date-from-calendar)))
17092 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17093 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17094 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17095 (setcar time0 (or (car time0) 0))
17096 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17097 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17098 (setq time (apply 'encode-time time0))))
17099 (setq org-last-changed-timestamp
17100 (org-insert-time-stamp time with-hm inactive nil nil extra))
17101 (org-clock-update-time-maybe)
17102 (goto-char pos)
17103 ;; Try to recenter the calendar window, if any
17104 (if (and org-calendar-follow-timestamp-change
17105 (get-buffer-window "*Calendar*" t)
17106 (memq org-ts-what '(day month year)))
17107 (org-recenter-calendar (time-to-days time))))))
17109 ;; FIXME: does not yet work for lead times
17110 (defun org-modify-ts-extra (s pos n)
17111 "Change the different parts of the lead-time and repeat fields in timestamp."
17112 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17113 ng h m new)
17114 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17115 (cond
17116 ((or (org-pos-in-match-range pos 2)
17117 (org-pos-in-match-range pos 3))
17118 (setq m (string-to-number (match-string 3 s))
17119 h (string-to-number (match-string 2 s)))
17120 (if (org-pos-in-match-range pos 2)
17121 (setq h (+ h n))
17122 (setq m (+ m n)))
17123 (if (< m 0) (setq m (+ m 60) h (1- h)))
17124 (if (> m 59) (setq m (- m 60) h (1+ h)))
17125 (setq h (min 24 (max 0 h)))
17126 (setq ng 1 new (format "-%02d:%02d" h m)))
17127 ((org-pos-in-match-range pos 6)
17128 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17129 ((org-pos-in-match-range pos 5)
17130 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
17132 (when ng
17133 (setq s (concat
17134 (substring s 0 (match-beginning ng))
17136 (substring s (match-end ng))))))
17139 (defun org-recenter-calendar (date)
17140 "If the calendar is visible, recenter it to DATE."
17141 (let* ((win (selected-window))
17142 (cwin (get-buffer-window "*Calendar*" t))
17143 (calendar-move-hook nil))
17144 (when cwin
17145 (select-window cwin)
17146 (calendar-goto-date (if (listp date) date
17147 (calendar-gregorian-from-absolute date)))
17148 (select-window win))))
17150 (defun org-goto-calendar (&optional arg)
17151 "Go to the Emacs calendar at the current date.
17152 If there is a time stamp in the current line, go to that date.
17153 A prefix ARG can be used to force the current date."
17154 (interactive "P")
17155 (let ((tsr org-ts-regexp) diff
17156 (calendar-move-hook nil)
17157 (view-calendar-holidays-initially nil)
17158 (view-diary-entries-initially nil))
17159 (if (or (org-at-timestamp-p)
17160 (save-excursion
17161 (beginning-of-line 1)
17162 (looking-at (concat ".*" tsr))))
17163 (let ((d1 (time-to-days (current-time)))
17164 (d2 (time-to-days
17165 (org-time-string-to-time (match-string 1)))))
17166 (setq diff (- d2 d1))))
17167 (calendar)
17168 (calendar-goto-today)
17169 (if (and diff (not arg)) (calendar-forward-day diff))))
17171 (defun org-get-date-from-calendar ()
17172 "Return a list (month day year) of date at point in calendar."
17173 (with-current-buffer "*Calendar*"
17174 (save-match-data
17175 (calendar-cursor-to-date))))
17177 (defun org-date-from-calendar ()
17178 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17179 If there is already a time stamp at the cursor position, update it."
17180 (interactive)
17181 (if (org-at-timestamp-p t)
17182 (org-timestamp-change 0 'calendar)
17183 (let ((cal-date (org-get-date-from-calendar)))
17184 (org-insert-time-stamp
17185 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17187 ;; Make appt aware of appointments from the agenda
17188 ;;;###autoload
17189 (defun org-agenda-to-appt (&optional filter)
17190 "Activate appointments found in `org-agenda-files'.
17191 When prefixed, prompt for a regular expression and use it as a
17192 filter: only add entries if they match this regular expression.
17194 FILTER can be a string. In this case, use this string as a
17195 regular expression to filter results.
17197 FILTER can also be an alist, with the car of each cell being
17198 either 'headline or 'category. For example:
17200 '((headline \"IMPORTANT\")
17201 (category \"Work\"))
17203 will only add headlines containing IMPORTANT or headlines
17204 belonging to the category \"Work\"."
17205 (interactive "P")
17206 (require 'calendar)
17207 (if (equal filter '(4))
17208 (setq filter (read-from-minibuffer "Regexp filter: ")))
17209 (let* ((cnt 0) ; count added events
17210 (today (org-date-to-gregorian
17211 (time-to-days (current-time))))
17212 (files (org-agenda-files)) entries file)
17213 ;; Get all entries which may contain an appt
17214 (while (setq file (pop files))
17215 (setq entries
17216 (append entries
17217 (org-agenda-get-day-entries
17218 file today
17219 :timestamp :scheduled :deadline))))
17220 (setq entries (delq nil entries))
17221 ;; Map thru entries and find if they pass thru the filter
17222 (mapc
17223 (lambda(x)
17224 (let* ((evt (org-trim (get-text-property 1 'txt x)))
17225 (cat (get-text-property 1 'org-category x))
17226 (tod (get-text-property 1 'time-of-day x))
17227 (ok (or (null filter)
17228 (and (stringp filter) (string-match filter evt))
17229 (and (listp filter)
17230 (or (string-match
17231 (cadr (assoc 'category filter)) cat)
17232 (string-match
17233 (cadr (assoc 'headline filter)) evt))))))
17234 ;; FIXME Shall we remove text-properties for the appt text?
17235 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
17236 (when (and ok tod)
17237 (setq tod (number-to-string tod)
17238 tod (when (string-match
17239 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
17240 (concat (match-string 1 tod) ":"
17241 (match-string 2 tod))))
17242 (appt-add tod evt)
17243 (setq cnt (1+ cnt))))) entries)
17244 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" ""))))
17246 ;;; The clock for measuring work time.
17248 (defvar org-mode-line-string "")
17249 (put 'org-mode-line-string 'risky-local-variable t)
17251 (defvar org-mode-line-timer nil)
17252 (defvar org-clock-heading "")
17253 (defvar org-clock-start-time "")
17255 (defun org-update-mode-line ()
17256 (let* ((delta (- (time-to-seconds (current-time))
17257 (time-to-seconds org-clock-start-time)))
17258 (h (floor delta 3600))
17259 (m (floor (- delta (* 3600 h)) 60)))
17260 (setq org-mode-line-string
17261 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
17262 'help-echo "Org-mode clock is running"))
17263 (force-mode-line-update)))
17265 (defvar org-clock-marker (make-marker)
17266 "Marker recording the last clock-in.")
17267 (defvar org-clock-mode-line-entry nil
17268 "Information for the modeline about the running clock.")
17270 (defun org-clock-in ()
17271 "Start the clock on the current item.
17272 If necessary, clock-out of the currently active clock."
17273 (interactive)
17274 (org-clock-out t)
17275 (let (ts)
17276 (save-excursion
17277 (org-back-to-heading t)
17278 (if (looking-at org-todo-line-regexp)
17279 (setq org-clock-heading (match-string 3))
17280 (setq org-clock-heading "???"))
17281 (setq org-clock-heading (propertize org-clock-heading 'face nil))
17282 (org-clock-find-position)
17284 (insert "\n") (backward-char 1)
17285 (indent-relative)
17286 (insert org-clock-string " ")
17287 (setq org-clock-start-time (current-time))
17288 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
17289 (move-marker org-clock-marker (point) (buffer-base-buffer))
17290 (or global-mode-string (setq global-mode-string '("")))
17291 (or (memq 'org-mode-line-string global-mode-string)
17292 (setq global-mode-string
17293 (append global-mode-string '(org-mode-line-string))))
17294 (org-update-mode-line)
17295 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
17296 (message "Clock started at %s" ts))))
17298 (defun org-clock-find-position ()
17299 "Find the location where the next clock line should be inserted."
17300 (org-back-to-heading t)
17301 (catch 'exit
17302 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
17303 (re (concat "^[ \t]*" org-clock-string))
17304 (cnt 0)
17305 first last)
17306 (goto-char beg)
17307 (when (eobp) (newline) (setq end (max (point) end)))
17308 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
17309 ;; we seem to have a CLOCK drawer, so go there.
17310 (beginning-of-line 2)
17311 (throw 'exit t))
17312 ;; Lets count the CLOCK lines
17313 (goto-char beg)
17314 (while (re-search-forward re end t)
17315 (setq first (or first (match-beginning 0))
17316 last (match-beginning 0)
17317 cnt (1+ cnt)))
17318 (when (and (integerp org-clock-into-drawer)
17319 (>= (1+ cnt) org-clock-into-drawer))
17320 ;; Wrap current entries into a new drawer
17321 (goto-char last)
17322 (beginning-of-line 2)
17323 (if (org-at-item-p) (org-end-of-item))
17324 (insert ":END:\n")
17325 (beginning-of-line 0)
17326 (org-indent-line-function)
17327 (goto-char first)
17328 (insert ":CLOCK:\n")
17329 (beginning-of-line 0)
17330 (org-indent-line-function)
17331 (org-flag-drawer t)
17332 (beginning-of-line 2)
17333 (throw 'exit nil))
17335 (goto-char beg)
17336 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
17337 (not (equal (match-string 1) org-clock-string)))
17338 ;; Planning info, skip to after it
17339 (beginning-of-line 2)
17340 (or (bolp) (newline)))
17341 (when (eq t org-clock-into-drawer)
17342 (insert ":CLOCK:\n:END:\n")
17343 (beginning-of-line -1)
17344 (org-indent-line-function)
17345 (org-flag-drawer t)
17346 (beginning-of-line 2)
17347 (org-indent-line-function)))))
17349 (defun org-clock-out (&optional fail-quietly)
17350 "Stop the currently running clock.
17351 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
17352 (interactive)
17353 (catch 'exit
17354 (if (not (marker-buffer org-clock-marker))
17355 (if fail-quietly (throw 'exit t) (error "No active clock")))
17356 (let (ts te s h m)
17357 (save-excursion
17358 (set-buffer (marker-buffer org-clock-marker))
17359 (goto-char org-clock-marker)
17360 (beginning-of-line 1)
17361 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
17362 (equal (match-string 1) org-clock-string))
17363 (setq ts (match-string 2))
17364 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
17365 (goto-char (match-end 0))
17366 (delete-region (point) (point-at-eol))
17367 (insert "--")
17368 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
17369 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
17370 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
17371 h (floor (/ s 3600))
17372 s (- s (* 3600 h))
17373 m (floor (/ s 60))
17374 s (- s (* 60 s)))
17375 (insert " => " (format "%2d:%02d" h m))
17376 (move-marker org-clock-marker nil)
17377 (let* ((logging (save-match-data (org-entry-get nil "LOGGING" t)))
17378 (org-log-done (org-parse-local-options logging 'org-log-done))
17379 (org-log-repeat (org-parse-local-options logging 'org-log-repeat)))
17380 (org-add-log-maybe 'clock-out))
17381 (when org-mode-line-timer
17382 (cancel-timer org-mode-line-timer)
17383 (setq org-mode-line-timer nil))
17384 (setq global-mode-string
17385 (delq 'org-mode-line-string global-mode-string))
17386 (force-mode-line-update)
17387 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
17389 (defun org-clock-cancel ()
17390 "Cancel the running clock be removing the start timestamp."
17391 (interactive)
17392 (if (not (marker-buffer org-clock-marker))
17393 (error "No active clock"))
17394 (save-excursion
17395 (set-buffer (marker-buffer org-clock-marker))
17396 (goto-char org-clock-marker)
17397 (delete-region (1- (point-at-bol)) (point-at-eol)))
17398 (message "Clock canceled"))
17400 (defun org-clock-goto (&optional delete-windows)
17401 "Go to the currently clocked-in entry."
17402 (interactive "P")
17403 (if (not (marker-buffer org-clock-marker))
17404 (error "No active clock"))
17405 (switch-to-buffer-other-window
17406 (marker-buffer org-clock-marker))
17407 (if delete-windows (delete-other-windows))
17408 (goto-char org-clock-marker)
17409 (org-show-entry)
17410 (org-back-to-heading)
17411 (recenter))
17413 (defvar org-clock-file-total-minutes nil
17414 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
17415 (make-variable-buffer-local 'org-clock-file-total-minutes)
17417 (defun org-clock-sum (&optional tstart tend)
17418 "Sum the times for each subtree.
17419 Puts the resulting times in minutes as a text property on each headline."
17420 (interactive)
17421 (let* ((bmp (buffer-modified-p))
17422 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
17423 org-clock-string
17424 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
17425 (lmax 30)
17426 (ltimes (make-vector lmax 0))
17427 (t1 0)
17428 (level 0)
17429 ts te dt
17430 time)
17431 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
17432 (save-excursion
17433 (goto-char (point-max))
17434 (while (re-search-backward re nil t)
17435 (cond
17436 ((match-end 2)
17437 ;; Two time stamps
17438 (setq ts (match-string 2)
17439 te (match-string 3)
17440 ts (time-to-seconds
17441 (apply 'encode-time (org-parse-time-string ts)))
17442 te (time-to-seconds
17443 (apply 'encode-time (org-parse-time-string te)))
17444 ts (if tstart (max ts tstart) ts)
17445 te (if tend (min te tend) te)
17446 dt (- te ts)
17447 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
17448 ((match-end 4)
17449 ;; A naket time
17450 (setq t1 (+ t1 (string-to-number (match-string 5))
17451 (* 60 (string-to-number (match-string 4))))))
17452 (t ;; A headline
17453 (setq level (- (match-end 1) (match-beginning 1)))
17454 (when (or (> t1 0) (> (aref ltimes level) 0))
17455 (loop for l from 0 to level do
17456 (aset ltimes l (+ (aref ltimes l) t1)))
17457 (setq t1 0 time (aref ltimes level))
17458 (loop for l from level to (1- lmax) do
17459 (aset ltimes l 0))
17460 (goto-char (match-beginning 0))
17461 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
17462 (setq org-clock-file-total-minutes (aref ltimes 0)))
17463 (set-buffer-modified-p bmp)))
17465 (defun org-clock-display (&optional total-only)
17466 "Show subtree times in the entire buffer.
17467 If TOTAL-ONLY is non-nil, only show the total time for the entire file
17468 in the echo area."
17469 (interactive)
17470 (org-remove-clock-overlays)
17471 (let (time h m p)
17472 (org-clock-sum)
17473 (unless total-only
17474 (save-excursion
17475 (goto-char (point-min))
17476 (while (or (and (equal (setq p (point)) (point-min))
17477 (get-text-property p :org-clock-minutes))
17478 (setq p (next-single-property-change
17479 (point) :org-clock-minutes)))
17480 (goto-char p)
17481 (when (setq time (get-text-property p :org-clock-minutes))
17482 (org-put-clock-overlay time (funcall outline-level))))
17483 (setq h (/ org-clock-file-total-minutes 60)
17484 m (- org-clock-file-total-minutes (* 60 h)))
17485 ;; Arrange to remove the overlays upon next change.
17486 (when org-remove-highlights-with-change
17487 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
17488 nil 'local))))
17489 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
17491 (defvar org-clock-overlays nil)
17492 (make-variable-buffer-local 'org-clock-overlays)
17494 (defun org-put-clock-overlay (time &optional level)
17495 "Put an overlays on the current line, displaying TIME.
17496 If LEVEL is given, prefix time with a corresponding number of stars.
17497 This creates a new overlay and stores it in `org-clock-overlays', so that it
17498 will be easy to remove."
17499 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
17500 (l (if level (org-get-legal-level level 0) 0))
17501 (off 0)
17502 ov tx)
17503 (move-to-column c)
17504 (unless (eolp) (skip-chars-backward "^ \t"))
17505 (skip-chars-backward " \t")
17506 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
17507 tx (concat (buffer-substring (1- (point)) (point))
17508 (make-string (+ off (max 0 (- c (current-column)))) ?.)
17509 (org-add-props (format "%s %2d:%02d%s"
17510 (make-string l ?*) h m
17511 (make-string (- 10 l) ?\ ))
17512 '(face secondary-selection))
17513 ""))
17514 (if (not (featurep 'xemacs))
17515 (org-overlay-put ov 'display tx)
17516 (org-overlay-put ov 'invisible t)
17517 (org-overlay-put ov 'end-glyph (make-glyph tx)))
17518 (push ov org-clock-overlays)))
17520 (defun org-remove-clock-overlays (&optional beg end noremove)
17521 "Remove the occur highlights from the buffer.
17522 BEG and END are ignored. If NOREMOVE is nil, remove this function
17523 from the `before-change-functions' in the current buffer."
17524 (interactive)
17525 (unless org-inhibit-highlight-removal
17526 (mapc 'org-delete-overlay org-clock-overlays)
17527 (setq org-clock-overlays nil)
17528 (unless noremove
17529 (remove-hook 'before-change-functions
17530 'org-remove-clock-overlays 'local))))
17532 (defun org-clock-out-if-current ()
17533 "Clock out if the current entry contains the running clock.
17534 This is used to stop the clock after a TODO entry is marked DONE,
17535 and is only done if the variable `org-clock-out-when-done' is not nil."
17536 (when (and org-clock-out-when-done
17537 (member state org-done-keywords)
17538 (equal (marker-buffer org-clock-marker) (current-buffer))
17539 (< (point) org-clock-marker)
17540 (> (save-excursion (outline-next-heading) (point))
17541 org-clock-marker))
17542 ;; Clock out, but don't accept a logging message for this.
17543 (let ((org-log-done (if (and (listp org-log-done)
17544 (member 'clock-out org-log-done))
17545 '(done)
17546 org-log-done)))
17547 (org-clock-out))))
17549 (add-hook 'org-after-todo-state-change-hook
17550 'org-clock-out-if-current)
17552 (defun org-check-running-clock ()
17553 "Check if the current buffer contains the running clock.
17554 If yes, offer to stop it and to save the buffer with the changes."
17555 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
17556 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
17557 (buffer-name))))
17558 (org-clock-out)
17559 (when (y-or-n-p "Save changed buffer?")
17560 (save-buffer))))
17562 (defun org-clock-report (&optional arg)
17563 "Create a table containing a report about clocked time.
17564 If the cursor is inside an existing clocktable block, then the table
17565 will be updated. If not, a new clocktable will be inserted.
17566 When called with a prefix argument, move to the first clock table in the
17567 buffer and update it."
17568 (interactive "P")
17569 (org-remove-clock-overlays)
17570 (when arg (org-find-dblock "clocktable"))
17571 (if (org-in-clocktable-p)
17572 (goto-char (org-in-clocktable-p))
17573 (org-create-dblock (list :name "clocktable"
17574 :maxlevel 2 :scope 'file)))
17575 (org-update-dblock))
17577 (defun org-in-clocktable-p ()
17578 "Check if the cursor is in a clocktable."
17579 (let ((pos (point)) start)
17580 (save-excursion
17581 (end-of-line 1)
17582 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
17583 (setq start (match-beginning 0))
17584 (re-search-forward "^#\\+END:.*" nil t)
17585 (>= (match-end 0) pos)
17586 start))))
17588 (defun org-clock-update-time-maybe ()
17589 "If this is a CLOCK line, update it and return t.
17590 Otherwise, return nil."
17591 (interactive)
17592 (save-excursion
17593 (beginning-of-line 1)
17594 (skip-chars-forward " \t")
17595 (when (looking-at org-clock-string)
17596 (let ((re (concat "[ \t]*" org-clock-string
17597 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
17598 "\\([ \t]*=>.*\\)?"))
17599 ts te h m s)
17600 (if (not (looking-at re))
17602 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
17603 (end-of-line 1)
17604 (setq ts (match-string 1)
17605 te (match-string 2))
17606 (setq s (- (time-to-seconds
17607 (apply 'encode-time (org-parse-time-string te)))
17608 (time-to-seconds
17609 (apply 'encode-time (org-parse-time-string ts))))
17610 h (floor (/ s 3600))
17611 s (- s (* 3600 h))
17612 m (floor (/ s 60))
17613 s (- s (* 60 s)))
17614 (insert " => " (format "%2d:%02d" h m))
17615 t)))))
17617 (defun org-clock-special-range (key &optional time as-strings)
17618 "Return two times bordering a special time range.
17619 Key is a symbol specifying the range and can be one of `today', `yesterday',
17620 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
17621 A week starts Monday 0:00 and ends Sunday 24:00.
17622 The range is determined relative to TIME. TIME defaults to the current time.
17623 The return value is a cons cell with two internal times like the ones
17624 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
17625 the returned times will be formatted strings."
17626 (let* ((tm (decode-time (or time (current-time))))
17627 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
17628 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
17629 (dow (nth 6 tm))
17630 s1 m1 h1 d1 month1 y1 diff ts te fm)
17631 (cond
17632 ((eq key 'today)
17633 (setq h 0 m 0 h1 24 m1 0))
17634 ((eq key 'yesterday)
17635 (setq d (1- d) h 0 m 0 h1 24 m1 0))
17636 ((eq key 'thisweek)
17637 (setq diff (if (= dow 0) 6 (1- dow))
17638 m 0 h 0 d (- d diff) d1 (+ 7 d)))
17639 ((eq key 'lastweek)
17640 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
17641 m 0 h 0 d (- d diff) d1 (+ 7 d)))
17642 ((eq key 'thismonth)
17643 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
17644 ((eq key 'lastmonth)
17645 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
17646 ((eq key 'thisyear)
17647 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
17648 ((eq key 'lastyear)
17649 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
17650 (t (error "No such time block %s" key)))
17651 (setq ts (encode-time s m h d month y)
17652 te (encode-time (or s1 s) (or m1 m) (or h1 h)
17653 (or d1 d) (or month1 month) (or y1 y)))
17654 (setq fm (cdr org-time-stamp-formats))
17655 (if as-strings
17656 (cons (format-time-string fm ts) (format-time-string fm te))
17657 (cons ts te))))
17659 (defun org-dblock-write:clocktable (params)
17660 "Write the standard clocktable."
17661 (let ((hlchars '((1 . "*") (2 . "/")))
17662 (emph nil)
17663 (ins (make-marker))
17664 (total-time nil)
17665 ipos time h m p level hlc hdl maxlevel
17666 ts te cc block beg end pos scope tbl tostring multifile)
17667 (setq scope (plist-get params :scope)
17668 tostring (plist-get params :tostring)
17669 multifile (plist-get params :multifile)
17670 maxlevel (or (plist-get params :maxlevel) 3)
17671 emph (plist-get params :emphasize)
17672 ts (plist-get params :tstart)
17673 te (plist-get params :tend)
17674 block (plist-get params :block))
17675 (when block
17676 (setq cc (org-clock-special-range block nil t)
17677 ts (car cc) te (cdr cc)))
17678 (if ts (setq ts (time-to-seconds
17679 (apply 'encode-time (org-parse-time-string ts)))))
17680 (if te (setq te (time-to-seconds
17681 (apply 'encode-time (org-parse-time-string te)))))
17682 (move-marker ins (point))
17683 (setq ipos (point))
17685 ;; Get the right scope
17686 (setq pos (point))
17687 (save-restriction
17688 (cond
17689 ((not scope))
17690 ((eq scope 'file) (widen))
17691 ((eq scope 'subtree) (org-narrow-to-subtree))
17692 ((eq scope 'tree)
17693 (while (org-up-heading-safe))
17694 (org-narrow-to-subtree))
17695 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
17696 (symbol-name scope)))
17697 (setq level (string-to-number (match-string 1 (symbol-name scope))))
17698 (catch 'exit
17699 (while (org-up-heading-safe)
17700 (looking-at outline-regexp)
17701 (if (<= (org-reduced-level (funcall outline-level)) level)
17702 (throw 'exit nil))))
17703 (org-narrow-to-subtree))
17704 ((or (listp scope) (eq scope 'agenda))
17705 (let* ((files (if (listp scope) scope (org-agenda-files)))
17706 (scope 'agenda)
17707 (p1 (copy-sequence params))
17708 file)
17709 (plist-put p1 :tostring t)
17710 (plist-put p1 :multifile t)
17711 (plist-put p1 :scope 'file)
17712 (org-prepare-agenda-buffers files)
17713 (while (setq file (pop files))
17714 (with-current-buffer (find-buffer-visiting file)
17715 (push (org-clocktable-add-file
17716 file (org-dblock-write:clocktable p1)) tbl)
17717 (setq total-time (+ (or total-time 0)
17718 org-clock-file-total-minutes)))))))
17719 (goto-char pos)
17721 (unless (eq scope 'agenda)
17722 (org-clock-sum ts te)
17723 (goto-char (point-min))
17724 (while (setq p (next-single-property-change (point) :org-clock-minutes))
17725 (goto-char p)
17726 (when (setq time (get-text-property p :org-clock-minutes))
17727 (save-excursion
17728 (beginning-of-line 1)
17729 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
17730 (setq level (org-reduced-level
17731 (- (match-end 1) (match-beginning 1))))
17732 (<= level maxlevel))
17733 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
17734 hdl (match-string 2)
17735 h (/ time 60)
17736 m (- time (* 60 h)))
17737 (if (and (not multifile) (= level 1)) (push "|-" tbl))
17738 (push (concat
17739 "| " (int-to-string level) "|" hlc hdl hlc " |"
17740 (make-string (1- level) ?|)
17741 hlc (format "%d:%02d" h m) hlc
17742 " |") tbl))))))
17743 (setq tbl (nreverse tbl))
17744 (if tostring
17745 (if tbl (mapconcat 'identity tbl "\n") nil)
17746 (goto-char ins)
17747 (insert-before-markers
17748 "Clock summary at ["
17749 (substring
17750 (format-time-string (cdr org-time-stamp-formats))
17751 1 -1)
17752 "]."
17753 (if block
17754 (format " Considered range is /%s/." block)
17756 "\n\n"
17757 (if (eq scope 'agenda) "|File" "")
17758 "|L|Headline|Time|\n")
17759 (setq total-time (or total-time org-clock-file-total-minutes)
17760 h (/ total-time 60)
17761 m (- total-time (* 60 h)))
17762 (insert-before-markers
17763 "|-\n|"
17764 (if (eq scope 'agenda) "|" "")
17766 "*Total time*| "
17767 (format "*%d:%02d*" h m)
17768 "|\n|-\n")
17769 (setq tbl (delq nil tbl))
17770 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
17771 (equal (substring (car tbl) 0 2) "|-"))
17772 (pop tbl))
17773 (insert-before-markers (mapconcat
17774 'identity (delq nil tbl)
17775 (if (eq scope 'agenda) "\n|-\n" "\n")))
17776 (backward-delete-char 1)
17777 (goto-char ipos)
17778 (skip-chars-forward "^|")
17779 (org-table-align)))))
17781 (defun org-clocktable-add-file (file table)
17782 (if table
17783 (let ((lines (org-split-string table "\n"))
17784 (ff (file-name-nondirectory file)))
17785 (mapconcat 'identity
17786 (mapcar (lambda (x)
17787 (if (string-match org-table-dataline-regexp x)
17788 (concat "|" ff x)
17790 lines)
17791 "\n"))))
17793 ;; FIXME: I don't think anybody uses this, ask David
17794 (defun org-collect-clock-time-entries ()
17795 "Return an internal list with clocking information.
17796 This list has one entry for each CLOCK interval.
17797 FIXME: describe the elements."
17798 (interactive)
17799 (let ((re (concat "^[ \t]*" org-clock-string
17800 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
17801 rtn beg end next cont level title total closedp leafp
17802 clockpos titlepos h m donep)
17803 (save-excursion
17804 (org-clock-sum)
17805 (goto-char (point-min))
17806 (while (re-search-forward re nil t)
17807 (setq clockpos (match-beginning 0)
17808 beg (match-string 1) end (match-string 2)
17809 cont (match-end 0))
17810 (setq beg (apply 'encode-time (org-parse-time-string beg))
17811 end (apply 'encode-time (org-parse-time-string end)))
17812 (org-back-to-heading t)
17813 (setq donep (org-entry-is-done-p))
17814 (setq titlepos (point)
17815 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
17816 h (/ total 60) m (- total (* 60 h))
17817 total (cons h m))
17818 (looking-at "\\(\\*+\\) +\\(.*\\)")
17819 (setq level (- (match-end 1) (match-beginning 1))
17820 title (org-match-string-no-properties 2))
17821 (save-excursion (outline-next-heading) (setq next (point)))
17822 (setq closedp (re-search-forward org-closed-time-regexp next t))
17823 (goto-char next)
17824 (setq leafp (and (looking-at "^\\*+ ")
17825 (<= (- (match-end 0) (point)) level)))
17826 (push (list beg end clockpos closedp donep
17827 total title titlepos level leafp)
17828 rtn)
17829 (goto-char cont)))
17830 (nreverse rtn)))
17832 ;;;; Agenda, and Diary Integration
17834 ;;; Define the Org-agenda-mode
17836 (defvar org-agenda-mode-map (make-sparse-keymap)
17837 "Keymap for `org-agenda-mode'.")
17839 (defvar org-agenda-menu) ; defined later in this file.
17840 (defvar org-agenda-follow-mode nil)
17841 (defvar org-agenda-show-log nil)
17842 (defvar org-agenda-redo-command nil)
17843 (defvar org-agenda-mode-hook nil)
17844 (defvar org-agenda-type nil)
17845 (defvar org-agenda-force-single-file nil)
17847 (defun org-agenda-mode ()
17848 "Mode for time-sorted view on action items in Org-mode files.
17850 The following commands are available:
17852 \\{org-agenda-mode-map}"
17853 (interactive)
17854 (kill-all-local-variables)
17855 (setq org-agenda-undo-list nil
17856 org-agenda-pending-undo-list nil)
17857 (setq major-mode 'org-agenda-mode)
17858 ;; Keep global-font-lock-mode from turning on font-lock-mode
17859 (org-set-local 'font-lock-global-modes (list 'not major-mode))
17860 (setq mode-name "Org-Agenda")
17861 (use-local-map org-agenda-mode-map)
17862 (easy-menu-add org-agenda-menu)
17863 (if org-startup-truncated (setq truncate-lines t))
17864 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
17865 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
17866 ;; Make sure properties are removed when copying text
17867 (when (boundp 'buffer-substring-filters)
17868 (org-set-local 'buffer-substring-filters
17869 (cons (lambda (x)
17870 (set-text-properties 0 (length x) nil x) x)
17871 buffer-substring-filters)))
17872 (unless org-agenda-keep-modes
17873 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
17874 org-agenda-show-log nil))
17875 (easy-menu-change
17876 '("Agenda") "Agenda Files"
17877 (append
17878 (list
17879 (vector
17880 (if (get 'org-agenda-files 'org-restrict)
17881 "Restricted to single file"
17882 "Edit File List")
17883 '(org-edit-agenda-file-list)
17884 (not (get 'org-agenda-files 'org-restrict)))
17885 "--")
17886 (mapcar 'org-file-menu-entry (org-agenda-files))))
17887 (org-agenda-set-mode-name)
17888 (apply
17889 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
17890 (list 'org-agenda-mode-hook)))
17892 (substitute-key-definition 'undo 'org-agenda-undo
17893 org-agenda-mode-map global-map)
17894 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
17895 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
17896 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
17897 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
17898 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
17899 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
17900 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
17901 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
17902 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
17903 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
17904 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
17905 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
17906 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
17907 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
17908 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
17909 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
17910 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
17911 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
17912 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
17913 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
17914 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
17915 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
17916 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
17917 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
17918 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
17919 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
17920 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
17921 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
17922 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
17924 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
17925 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
17926 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
17927 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
17928 (while l (org-defkey org-agenda-mode-map
17929 (int-to-string (pop l)) 'digit-argument)))
17931 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
17932 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
17933 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
17934 (org-defkey org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
17935 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
17936 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
17937 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
17938 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
17939 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
17940 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
17941 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
17942 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
17943 (org-defkey org-agenda-mode-map "n" 'next-line)
17944 (org-defkey org-agenda-mode-map "p" 'previous-line)
17945 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
17946 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
17947 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
17948 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
17949 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
17950 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
17951 (eval-after-load "calendar"
17952 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
17953 'org-calendar-goto-agenda))
17954 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
17955 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
17956 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
17957 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
17958 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
17959 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
17960 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
17961 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
17962 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
17963 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
17964 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
17965 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17966 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
17967 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
17968 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
17969 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
17970 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
17971 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
17972 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
17973 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
17974 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
17975 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
17977 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
17978 "Local keymap for agenda entries from Org-mode.")
17980 (org-defkey org-agenda-keymap
17981 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
17982 (org-defkey org-agenda-keymap
17983 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
17984 (when org-agenda-mouse-1-follows-link
17985 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
17986 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
17987 '("Agenda"
17988 ("Agenda Files")
17989 "--"
17990 ["Show" org-agenda-show t]
17991 ["Go To (other window)" org-agenda-goto t]
17992 ["Go To (this window)" org-agenda-switch-to t]
17993 ["Follow Mode" org-agenda-follow-mode
17994 :style toggle :selected org-agenda-follow-mode :active t]
17995 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
17996 "--"
17997 ["Cycle TODO" org-agenda-todo t]
17998 ["Archive subtree" org-agenda-archive t]
17999 ["Delete subtree" org-agenda-kill t]
18000 "--"
18001 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
18002 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
18003 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
18004 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
18005 "--"
18006 ("Tags and Properties"
18007 ["Show all Tags" org-agenda-show-tags t]
18008 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
18009 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
18010 "--"
18011 ["Column View" org-columns t])
18012 ("Date/Schedule"
18013 ["Schedule" org-agenda-schedule t]
18014 ["Set Deadline" org-agenda-deadline t]
18015 "--"
18016 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
18017 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
18018 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
18019 ("Clock"
18020 ["Clock in" org-agenda-clock-in t]
18021 ["Clock out" org-agenda-clock-out t]
18022 ["Clock cancel" org-agenda-clock-cancel t]
18023 ["Goto running clock" org-clock-goto t])
18024 ("Priority"
18025 ["Set Priority" org-agenda-priority t]
18026 ["Increase Priority" org-agenda-priority-up t]
18027 ["Decrease Priority" org-agenda-priority-down t]
18028 ["Show Priority" org-agenda-show-priority t])
18029 ("Calendar/Diary"
18030 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
18031 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
18032 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
18033 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
18034 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
18035 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
18036 "--"
18037 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
18038 "--"
18039 ("View"
18040 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
18041 :style radio :selected (equal org-agenda-ndays 1)]
18042 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
18043 :style radio :selected (equal org-agenda-ndays 7)]
18044 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
18045 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
18046 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
18047 :style radio :selected (member org-agenda-ndays '(365 366))]
18048 "--"
18049 ["Show Logbook entries" org-agenda-log-mode
18050 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
18051 ["Include Diary" org-agenda-toggle-diary
18052 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
18053 ["Use Time Grid" org-agenda-toggle-time-grid
18054 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
18055 ["Write view to file" org-write-agenda t]
18056 ["Rebuild buffer" org-agenda-redo t]
18057 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
18058 "--"
18059 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
18060 "--"
18061 ["Quit" org-agenda-quit t]
18062 ["Exit and Release Buffers" org-agenda-exit t]
18065 ;;; Agenda undo
18067 (defvar org-agenda-allow-remote-undo t
18068 "Non-nil means, allow remote undo from the agenda buffer.")
18069 (defvar org-agenda-undo-list nil
18070 "List of undoable operations in the agenda since last refresh.")
18071 (defvar org-agenda-undo-has-started-in nil
18072 "Buffers that have already seen `undo-start' in the current undo sequence.")
18073 (defvar org-agenda-pending-undo-list nil
18074 "In a series of undo commands, this is the list of remaning undo items.")
18076 (defmacro org-if-unprotected (&rest body)
18077 "Execute BODY if there is no `org-protected' text property at point."
18078 (declare (debug t))
18079 `(unless (get-text-property (point) 'org-protected)
18080 ,@body))
18082 (defmacro org-with-remote-undo (_buffer &rest _body)
18083 "Execute BODY while recording undo information in two buffers."
18084 (declare (indent 1) (debug t))
18085 `(let ((_cline (org-current-line))
18086 (_cmd this-command)
18087 (_buf1 (current-buffer))
18088 (_buf2 ,_buffer)
18089 (_undo1 buffer-undo-list)
18090 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
18091 _c1 _c2)
18092 ,@_body
18093 (when org-agenda-allow-remote-undo
18094 (setq _c1 (org-verify-change-for-undo
18095 _undo1 (with-current-buffer _buf1 buffer-undo-list))
18096 _c2 (org-verify-change-for-undo
18097 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
18098 (when (or _c1 _c2)
18099 ;; make sure there are undo boundaries
18100 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
18101 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
18102 ;; remember which buffer to undo
18103 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
18104 org-agenda-undo-list)))))
18106 (defun org-agenda-undo ()
18107 "Undo a remote editing step in the agenda.
18108 This undoes changes both in the agenda buffer and in the remote buffer
18109 that have been changed along."
18110 (interactive)
18111 (or org-agenda-allow-remote-undo
18112 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
18113 (if (not (eq this-command last-command))
18114 (setq org-agenda-undo-has-started-in nil
18115 org-agenda-pending-undo-list org-agenda-undo-list))
18116 (if (not org-agenda-pending-undo-list)
18117 (error "No further undo information"))
18118 (let* ((entry (pop org-agenda-pending-undo-list))
18119 buf line cmd rembuf)
18120 (setq cmd (pop entry) line (pop entry))
18121 (setq rembuf (nth 2 entry))
18122 (org-with-remote-undo rembuf
18123 (while (bufferp (setq buf (pop entry)))
18124 (if (pop entry)
18125 (with-current-buffer buf
18126 (let ((last-undo-buffer buf)
18127 (inhibit-read-only t))
18128 (unless (memq buf org-agenda-undo-has-started-in)
18129 (push buf org-agenda-undo-has-started-in)
18130 (make-local-variable 'pending-undo-list)
18131 (undo-start))
18132 (while (and pending-undo-list
18133 (listp pending-undo-list)
18134 (not (car pending-undo-list)))
18135 (pop pending-undo-list))
18136 (undo-more 1))))))
18137 (goto-line line)
18138 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
18140 (defun org-verify-change-for-undo (l1 l2)
18141 "Verify that a real change occurred between the undo lists L1 and L2."
18142 (while (and l1 (listp l1) (null (car l1))) (pop l1))
18143 (while (and l2 (listp l2) (null (car l2))) (pop l2))
18144 (not (eq l1 l2)))
18146 ;;; Agenda dispatch
18148 (defvar org-agenda-restrict nil)
18149 (defvar org-agenda-restrict-begin (make-marker))
18150 (defvar org-agenda-restrict-end (make-marker))
18151 (defvar org-agenda-last-dispatch-buffer nil)
18153 ;;;###autoload
18154 (defun org-agenda (arg &optional keys restriction)
18155 "Dispatch agenda commands to collect entries to the agenda buffer.
18156 Prompts for a command to execute. Any prefix arg will be passed
18157 on to the selected command. The default selections are:
18159 a Call `org-agenda-list' to display the agenda for current day or week.
18160 t Call `org-todo-list' to display the global todo list.
18161 T Call `org-todo-list' to display the global todo list, select only
18162 entries with a specific TODO keyword (the user gets a prompt).
18163 m Call `org-tags-view' to display headlines with tags matching
18164 a condition (the user is prompted for the condition).
18165 M Like `m', but select only TODO entries, no ordinary headlines.
18166 L Create a timeline for the current buffer.
18167 e Export views to associated files.
18169 More commands can be added by configuring the variable
18170 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
18171 searches can be pre-defined in this way.
18173 If the current buffer is in Org-mode and visiting a file, you can also
18174 first press `<' once to indicate that the agenda should be temporarily
18175 \(until the next use of \\[org-agenda]) restricted to the current file.
18176 Pressing `<' twice means to restrict to the current subtree or region
18177 \(if active)."
18178 (interactive "P")
18179 (catch 'exit
18180 (let* ((prefix-descriptions nil)
18181 (org-agenda-custom-commands
18182 ;; normalize different versions
18183 (delq nil
18184 (mapcar
18185 (lambda (x)
18186 (cond ((stringp (cdr x))
18187 (push x prefix-descriptions)
18188 nil)
18189 ((stringp (nth 1 x)) x)
18190 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
18191 (t (cons (car x) (cons "" (cdr x))))))
18192 org-agenda-custom-commands)))
18193 (buf (current-buffer))
18194 (bfn (buffer-file-name (buffer-base-buffer)))
18195 entry key type match lprops ans)
18196 ;; Turn off restriction
18197 (put 'org-agenda-files 'org-restrict nil)
18198 (setq org-agenda-restrict nil)
18199 (move-marker org-agenda-restrict-begin nil)
18200 (move-marker org-agenda-restrict-end nil)
18201 ;; Delete old local properties
18202 (put 'org-agenda-redo-command 'org-lprops nil)
18203 ;; Remember where this call originated
18204 (setq org-agenda-last-dispatch-buffer (current-buffer))
18205 (unless keys
18206 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
18207 keys (car ans)
18208 restriction (cdr ans)))
18209 ;; Estabish the restriction, if any
18210 (when restriction
18211 (put 'org-agenda-files 'org-restrict (list bfn))
18212 (cond
18213 ((eq restriction 'region)
18214 (setq org-agenda-restrict t)
18215 (move-marker org-agenda-restrict-begin (region-beginning))
18216 (move-marker org-agenda-restrict-end (region-end)))
18217 ((eq restriction 'subtree)
18218 (save-excursion
18219 (setq org-agenda-restrict t)
18220 (org-back-to-heading t)
18221 (move-marker org-agenda-restrict-begin (point))
18222 (move-marker org-agenda-restrict-end
18223 (progn (org-end-of-subtree t)))))))
18225 (require 'calendar) ; FIXME: can we avoid this for some commands?
18226 ;; For example the todo list should not need it (but does...)
18227 (cond
18228 ((setq entry (assoc keys org-agenda-custom-commands))
18229 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
18230 (progn
18231 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
18232 (put 'org-agenda-redo-command 'org-lprops lprops)
18233 (cond
18234 ((eq type 'agenda)
18235 (org-let lprops '(org-agenda-list current-prefix-arg)))
18236 ((eq type 'alltodo)
18237 (org-let lprops '(org-todo-list current-prefix-arg)))
18238 ((eq type 'stuck)
18239 (org-let lprops '(org-agenda-list-stuck-projects
18240 current-prefix-arg)))
18241 ((eq type 'tags)
18242 (org-let lprops '(org-tags-view current-prefix-arg match)))
18243 ((eq type 'tags-todo)
18244 (org-let lprops '(org-tags-view '(4) match)))
18245 ((eq type 'todo)
18246 (org-let lprops '(org-todo-list match)))
18247 ((eq type 'tags-tree)
18248 (org-check-for-org-mode)
18249 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
18250 ((eq type 'todo-tree)
18251 (org-check-for-org-mode)
18252 (org-let lprops
18253 '(org-occur (concat "^" outline-regexp "[ \t]*"
18254 (regexp-quote match) "\\>"))))
18255 ((eq type 'occur-tree)
18256 (org-check-for-org-mode)
18257 (org-let lprops '(org-occur match)))
18258 ((functionp type)
18259 (org-let lprops '(funcall type match)))
18260 ((fboundp type)
18261 (org-let lprops '(funcall type match)))
18262 (t (error "Invalid custom agenda command type %s" type))))
18263 (org-run-agenda-series (nth 1 entry) (cddr entry))))
18264 ((equal keys "C") (customize-variable 'org-agenda-custom-commands))
18265 ((equal keys "a") (call-interactively 'org-agenda-list))
18266 ((equal keys "t") (call-interactively 'org-todo-list))
18267 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
18268 ((equal keys "m") (call-interactively 'org-tags-view))
18269 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
18270 ((equal keys "e") (call-interactively 'org-store-agenda-views))
18271 ((equal keys "L")
18272 (unless (org-mode-p)
18273 (error "This is not an Org-mode file"))
18274 (unless restriction
18275 (put 'org-agenda-files 'org-restrict (list bfn))
18276 (org-call-with-arg 'org-timeline arg)))
18277 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
18278 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
18279 ((equal keys "!") (customize-variable 'org-stuck-projects))
18280 (t (error "Invalid agenda key"))))))
18282 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
18283 "The user interface for selecting an agenda command."
18284 (catch 'exit
18285 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
18286 (restrict-ok (and bfn (org-mode-p)))
18287 (region-p (org-region-active-p))
18288 (custom org-agenda-custom-commands)
18289 (selstring "")
18290 restriction second-time
18291 c entry key type match prefixes rmheader header-end custom1 desc)
18292 (save-window-excursion
18293 (delete-other-windows)
18294 (org-switch-to-buffer-other-window " *Agenda Commands*")
18295 (erase-buffer)
18296 (insert (eval-when-compile
18297 (let ((header
18298 "Press key for an agenda command: < Buffer,subtree/region restriction
18299 -------------------------------- C Configure custom agenda commands
18300 a Agenda for current week or day e Export agenda views
18301 t List of all TODO entries T Entries with special TODO kwd
18302 m Match a TAGS query M Like m, but only TODO entries
18303 L Timeline for current buffer # List stuck projects (!=configure)
18304 / Multi-occur
18306 (start 0))
18307 (while (string-match
18308 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
18309 header start)
18310 (setq start (match-end 0))
18311 (add-text-properties (match-beginning 2) (match-end 2)
18312 '(face bold) header))
18313 header)))
18314 (setq header-end (move-marker (make-marker) (point)))
18315 (while t
18316 (setq custom1 custom)
18317 (when (eq rmheader t)
18318 (goto-line 1)
18319 (re-search-forward ":" nil t)
18320 (delete-region (match-end 0) (line-end-position))
18321 (forward-char 1)
18322 (looking-at "-+")
18323 (delete-region (match-end 0) (line-end-position))
18324 (move-marker header-end (match-end 0)))
18325 (goto-char header-end)
18326 (delete-region (point) (point-max))
18327 (while (setq entry (pop custom1))
18328 (setq key (car entry) desc (nth 1 entry)
18329 type (nth 2 entry) match (nth 3 entry))
18330 (if (> (length key) 1)
18331 (add-to-list 'prefixes (string-to-char key))
18332 (insert
18333 (format
18334 "\n%-4s%-14s: %s"
18335 (org-add-props (copy-sequence key)
18336 '(face bold))
18337 (cond
18338 ((string-match "\\S-" desc) desc)
18339 ((eq type 'agenda) "Agenda for current week or day")
18340 ((eq type 'alltodo) "List of all TODO entries")
18341 ((eq type 'stuck) "List of stuck projects")
18342 ((eq type 'todo) "TODO keyword")
18343 ((eq type 'tags) "Tags query")
18344 ((eq type 'tags-todo) "Tags (TODO)")
18345 ((eq type 'tags-tree) "Tags tree")
18346 ((eq type 'todo-tree) "TODO kwd tree")
18347 ((eq type 'occur-tree) "Occur tree")
18348 ((functionp type) (if (symbolp type)
18349 (symbol-name type)
18350 "Lambda expression"))
18351 (t "???"))
18352 (cond
18353 ((stringp match)
18354 (org-add-props match nil 'face 'org-warning))
18355 (match
18356 (format "set of %d commands" (length match)))
18357 (t ""))))))
18358 (when prefixes
18359 (mapcar (lambda (x)
18360 (insert
18361 (format "\n%s %s"
18362 (org-add-props (char-to-string x)
18363 nil 'face 'bold)
18364 (or (cdr (assoc (concat selstring (char-to-string x))
18365 prefix-descriptions))
18366 "Prefix key"))))
18367 prefixes))
18368 (goto-char (point-min))
18369 (when (fboundp 'fit-window-to-buffer)
18370 (if second-time
18371 (if (not (pos-visible-in-window-p (point-max)))
18372 (fit-window-to-buffer))
18373 (setq second-time t)
18374 (fit-window-to-buffer)))
18375 (message "Press key for agenda command%s:"
18376 (if restrict-ok
18377 (if restriction
18378 (format " (restricted to %s)" restriction)
18379 " (unrestricted)")
18380 ""))
18381 (setq c (read-char-exclusive))
18382 (message "")
18383 (cond
18384 ((assoc (char-to-string c) custom)
18385 (setq selstring (concat selstring (char-to-string c)))
18386 (throw 'exit (cons selstring restriction)))
18387 ((memq c prefixes)
18388 (setq selstring (concat selstring (char-to-string c))
18389 prefixes nil
18390 rmheader (or rmheader t)
18391 custom (delq nil (mapcar
18392 (lambda (x)
18393 (if (or (= (length (car x)) 1)
18394 (/= (string-to-char (car x)) c))
18396 (cons (substring (car x) 1) (cdr x))))
18397 custom))))
18398 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
18399 (message "Restriction is only possible in Org-mode buffers")
18400 (ding) (sit-for 1))
18401 ((eq c ?1)
18402 (setq restriction 'buffer))
18403 ((eq c ?0)
18404 (setq restriction (if region-p 'region 'subtree)))
18405 ((eq c ?<)
18406 (setq restriction
18407 (cond
18408 ((eq restriction 'buffer)
18409 (if region-p 'region 'subtree))
18410 ((memq restriction '(subtree region))
18411 nil)
18412 (t 'buffer))))
18413 ((and (equal selstring "") (memq c '(?a ?t ?m ?L ?C ?e ?T ?M ?# ?/)))
18414 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
18415 ((equal c ?q) (error "Abort"))
18416 (t (error "Invalid key %c" c))))))))
18418 (defun org-run-agenda-series (name series)
18419 (org-prepare-agenda name)
18420 (let* ((org-agenda-multi t)
18421 (redo (list 'org-run-agenda-series name (list 'quote series)))
18422 (cmds (car series))
18423 (gprops (nth 1 series))
18424 match ;; The byte compiler incorrectly complains about this. Keep it!
18425 cmd type lprops)
18426 (while (setq cmd (pop cmds))
18427 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
18428 (cond
18429 ((eq type 'agenda)
18430 (org-let2 gprops lprops
18431 '(call-interactively 'org-agenda-list)))
18432 ((eq type 'alltodo)
18433 (org-let2 gprops lprops
18434 '(call-interactively 'org-todo-list)))
18435 ((eq type 'stuck)
18436 (org-let2 gprops lprops
18437 '(call-interactively 'org-agenda-list-stuck-projects)))
18438 ((eq type 'tags)
18439 (org-let2 gprops lprops
18440 '(org-tags-view current-prefix-arg match)))
18441 ((eq type 'tags-todo)
18442 (org-let2 gprops lprops
18443 '(org-tags-view '(4) match)))
18444 ((eq type 'todo)
18445 (org-let2 gprops lprops
18446 '(org-todo-list match)))
18447 ((fboundp type)
18448 (org-let2 gprops lprops
18449 '(funcall type match)))
18450 (t (error "Invalid type in command series"))))
18451 (widen)
18452 (setq org-agenda-redo-command redo)
18453 (goto-char (point-min)))
18454 (org-finalize-agenda))
18456 ;;;###autoload
18457 (defmacro org-batch-agenda (cmd-key &rest parameters)
18458 "Run an agenda command in batch mode and send the result to STDOUT.
18459 If CMD-KEY is a string of length 1, it is used as a key in
18460 `org-agenda-custom-commands' and triggers this command. If it is a
18461 longer string is is used as a tags/todo match string.
18462 Paramters are alternating variable names and values that will be bound
18463 before running the agenda command."
18464 (let (pars)
18465 (while parameters
18466 (push (list (pop parameters) (if parameters (pop parameters))) pars))
18467 (if (> (length cmd-key) 2)
18468 (eval (list 'let (nreverse pars)
18469 (list 'org-tags-view nil cmd-key)))
18470 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
18471 (set-buffer org-agenda-buffer-name)
18472 (princ (org-encode-for-stdout (buffer-string)))))
18474 (defun org-encode-for-stdout (string)
18475 (if (fboundp 'encode-coding-string)
18476 (encode-coding-string string buffer-file-coding-system)
18477 string))
18479 (defvar org-agenda-info nil)
18481 ;;;###autoload
18482 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
18483 "Run an agenda command in batch mode and send the result to STDOUT.
18484 If CMD-KEY is a string of length 1, it is used as a key in
18485 `org-agenda-custom-commands' and triggers this command. If it is a
18486 longer string is is used as a tags/todo match string.
18487 Paramters are alternating variable names and values that will be bound
18488 before running the agenda command.
18490 The output gives a line for each selected agenda item. Each
18491 item is a list of comma-separated values, like this:
18493 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
18495 category The category of the item
18496 head The headline, without TODO kwd, TAGS and PRIORITY
18497 type The type of the agenda entry, can be
18498 todo selected in TODO match
18499 tagsmatch selected in tags match
18500 diary imported from diary
18501 deadline a deadline on given date
18502 scheduled scheduled on given date
18503 timestamp entry has timestamp on given date
18504 closed entry was closed on given date
18505 upcoming-deadline warning about deadline
18506 past-scheduled forwarded scheduled item
18507 block entry has date block including g. date
18508 todo The todo keyword, if any
18509 tags All tags including inherited ones, separated by colons
18510 date The relevant date, like 2007-2-14
18511 time The time, like 15:00-16:50
18512 extra Sting with extra planning info
18513 priority-l The priority letter if any was given
18514 priority-n The computed numerical priority
18515 agenda-day The day in the agenda where this is listed"
18517 (let (pars)
18518 (while parameters
18519 (push (list (pop parameters) (if parameters (pop parameters))) pars))
18520 (push (list 'org-agenda-remove-tags t) pars)
18521 (if (> (length cmd-key) 2)
18522 (eval (list 'let (nreverse pars)
18523 (list 'org-tags-view nil cmd-key)))
18524 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
18525 (set-buffer org-agenda-buffer-name)
18526 (let* ((lines (org-split-string (buffer-string) "\n"))
18527 line)
18528 (while (setq line (pop lines))
18529 (catch 'next
18530 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
18531 (setq org-agenda-info
18532 (org-fix-agenda-info (text-properties-at 0 line)))
18533 (princ
18534 (org-encode-for-stdout
18535 (mapconcat 'org-agenda-export-csv-mapper
18536 '(org-category txt type todo tags date time-of-day extra
18537 priority-letter priority agenda-day)
18538 ",")))
18539 (princ "\n"))))))
18541 (defun org-fix-agenda-info (props)
18542 "Make sure all properties on an agenda item have a canonical form,
18543 so the the export commands caneasily use it."
18544 (let (tmp re)
18545 (when (setq tmp (plist-get props 'tags))
18546 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
18547 (when (setq tmp (plist-get props 'date))
18548 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
18549 (let ((calendar-date-display-form '(year "-" month "-" day)))
18550 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
18552 (setq tmp (calendar-date-string tmp)))
18553 (setq props (plist-put props 'date tmp)))
18554 (when (setq tmp (plist-get props 'day))
18555 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
18556 (let ((calendar-date-display-form '(year "-" month "-" day)))
18557 (setq tmp (calendar-date-string tmp)))
18558 (setq props (plist-put props 'day tmp))
18559 (setq props (plist-put props 'agenda-day tmp)))
18560 (when (setq tmp (plist-get props 'txt))
18561 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
18562 (plist-put props 'priority-letter (match-string 1 tmp))
18563 (setq tmp (replace-match "" t t tmp)))
18564 (when (and (setq re (plist-get props 'org-todo-regexp))
18565 (setq re (concat "\\`\\.*" re " ?"))
18566 (string-match re tmp))
18567 (plist-put props 'todo (match-string 1 tmp))
18568 (setq tmp (replace-match "" t t tmp)))
18569 (plist-put props 'txt tmp)))
18570 props)
18572 (defun org-agenda-export-csv-mapper (prop)
18573 (let ((res (plist-get org-agenda-info prop)))
18574 (setq res
18575 (cond
18576 ((not res) "")
18577 ((stringp res) res)
18578 (t (prin1-to-string res))))
18579 (while (string-match "," res)
18580 (setq res (replace-match ";" t t res)))
18581 (org-trim res)))
18584 ;;;###autoload
18585 (defun org-store-agenda-views (&rest parameters)
18586 (interactive)
18587 (eval (list 'org-batch-store-agenda-views)))
18589 ;; FIXME, why is this a macro?????
18590 ;;;###autoload
18591 (defmacro org-batch-store-agenda-views (&rest parameters)
18592 "Run all custom agenda commands that have a file argument."
18593 (let ((cmds org-agenda-custom-commands)
18594 (pop-up-frames nil)
18595 (dir default-directory)
18596 pars cmd thiscmdkey files opts)
18597 (while parameters
18598 (push (list (pop parameters) (if parameters (pop parameters))) pars))
18599 (setq pars (reverse pars))
18600 (save-window-excursion
18601 (while cmds
18602 (setq cmd (pop cmds)
18603 thiscmdkey (car cmd)
18604 opts (nth 3 cmd)
18605 files (nth 4 cmd))
18606 (if (stringp files) (setq files (list files)))
18607 (when files
18608 (eval (list 'let (append org-agenda-exporter-settings opts pars)
18609 (list 'org-agenda nil thiscmdkey)))
18610 (set-buffer org-agenda-buffer-name)
18611 (while files
18612 (eval (list 'let (append org-agenda-exporter-settings opts pars)
18613 (list 'org-write-agenda
18614 (expand-file-name (pop files) dir) t))))
18615 (and (get-buffer org-agenda-buffer-name)
18616 (kill-buffer org-agenda-buffer-name)))))))
18618 (defun org-write-agenda (file &optional nosettings)
18619 "Write the current buffer (an agenda view) as a file.
18620 Depending on the extension of the file name, plain text (.txt),
18621 HTML (.html or .htm) or Postscript (.ps) is produced.
18622 If NOSETTINGS is given, do not scope the settings of
18623 `org-agenda-exporter-settings' into the export commands. This is used when
18624 the settings have already been scoped and we do not wish to overrule other,
18625 higher priority settings."
18626 (interactive "FWrite agenda to file: ")
18627 (if (not (file-writable-p file))
18628 (error "Cannot write agenda to file %s" file))
18629 (cond
18630 ((string-match "\\.html?\\'" file) (require 'htmlize))
18631 ((string-match "\\.ps\\'" file) (require 'ps-print)))
18632 (org-let (if nosettings nil org-agenda-exporter-settings)
18633 '(save-excursion
18634 (save-window-excursion
18635 (cond
18636 ((string-match "\\.html?\\'" file)
18637 (set-buffer (htmlize-buffer (current-buffer)))
18639 (when (and org-agenda-export-html-style
18640 (string-match "<style>" org-agenda-export-html-style))
18641 ;; replace <style> section with org-agenda-export-html-style
18642 (goto-char (point-min))
18643 (kill-region (- (search-forward "<style") 6)
18644 (search-forward "</style>"))
18645 (insert org-agenda-export-html-style))
18646 (write-file file)
18647 (kill-buffer (current-buffer))
18648 (message "HTML written to %s" file))
18649 ((string-match "\\.ps\\'" file)
18650 (ps-print-buffer-with-faces file)
18651 (message "Postscript written to %s" file))
18653 (let ((bs (buffer-string)))
18654 (find-file file)
18655 (insert bs)
18656 (save-buffer 0)
18657 (kill-buffer (current-buffer))
18658 (message "Plain text written to %s" file))))))
18659 (set-buffer org-agenda-buffer-name)))
18661 (defmacro org-no-read-only (&rest body)
18662 "Inhibit read-only for BODY."
18663 `(let ((inhibit-read-only t)) ,@body))
18665 (defun org-check-for-org-mode ()
18666 "Make sure current buffer is in org-mode. Error if not."
18667 (or (org-mode-p)
18668 (error "Cannot execute org-mode agenda command on buffer in %s."
18669 major-mode)))
18671 (defun org-fit-agenda-window ()
18672 "Fit the window to the buffer size."
18673 (and (memq org-agenda-window-setup '(reorganize-frame))
18674 (fboundp 'fit-window-to-buffer)
18675 (fit-window-to-buffer
18677 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
18678 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
18680 ;;; Agenda file list
18682 (defun org-agenda-files (&optional unrestricted)
18683 "Get the list of agenda files.
18684 Optional UNRESTRICTED means return the full list even if a restriction
18685 is currently in place."
18686 (let ((files
18687 (cond
18688 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18689 ((stringp org-agenda-files) (org-read-agenda-file-list))
18690 ((listp org-agenda-files) org-agenda-files)
18691 (t (error "Invalid value of `org-agenda-files'")))))
18692 (setq files (apply 'append
18693 (mapcar (lambda (f)
18694 (if (file-directory-p f)
18695 (directory-files f t "\\.org\\'")
18696 (list f)))
18697 files)))
18698 (if org-agenda-skip-unavailable-files
18699 (delq nil
18700 (mapcar (function
18701 (lambda (file)
18702 (and (file-readable-p file) file)))
18703 files))
18704 files))) ; `org-check-agenda-file' will remove them from the list
18706 (defun org-edit-agenda-file-list ()
18707 "Edit the list of agenda files.
18708 Depending on setup, this either uses customize to edit the variable
18709 `org-agenda-files', or it visits the file that is holding the list. In the
18710 latter case, the buffer is set up in a way that saving it automatically kills
18711 the buffer and restores the previous window configuration."
18712 (interactive)
18713 (if (stringp org-agenda-files)
18714 (let ((cw (current-window-configuration)))
18715 (find-file org-agenda-files)
18716 (org-set-local 'org-window-configuration cw)
18717 (org-add-hook 'after-save-hook
18718 (lambda ()
18719 (set-window-configuration
18720 (prog1 org-window-configuration
18721 (kill-buffer (current-buffer))))
18722 (org-install-agenda-files-menu)
18723 (message "New agenda file list installed"))
18724 nil 'local)
18725 (message (substitute-command-keys
18726 "Edit list and finish with \\[save-buffer]")))
18727 (customize-variable 'org-agenda-files)))
18729 (defun org-store-new-agenda-file-list (list)
18730 "Set new value for the agenda file list and save it correcly."
18731 (if (stringp org-agenda-files)
18732 (let ((f org-agenda-files) b)
18733 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
18734 (with-temp-file f
18735 (insert (mapconcat 'identity list "\n") "\n")))
18736 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
18737 (setq org-agenda-files list)
18738 (customize-save-variable 'org-agenda-files org-agenda-files))))
18740 (defun org-read-agenda-file-list ()
18741 "Read the list of agenda files from a file."
18742 (when (stringp org-agenda-files)
18743 (with-temp-buffer
18744 (insert-file-contents org-agenda-files)
18745 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
18748 ;;;###autoload
18749 (defun org-cycle-agenda-files ()
18750 "Cycle through the files in `org-agenda-files'.
18751 If the current buffer visits an agenda file, find the next one in the list.
18752 If the current buffer does not, find the first agenda file."
18753 (interactive)
18754 (let* ((fs (org-agenda-files t))
18755 (files (append fs (list (car fs))))
18756 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18757 file)
18758 (unless files (error "No agenda files"))
18759 (catch 'exit
18760 (while (setq file (pop files))
18761 (if (equal (file-truename file) tcf)
18762 (when (car files)
18763 (find-file (car files))
18764 (throw 'exit t))))
18765 (find-file (car fs)))
18766 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
18768 (defun org-agenda-file-to-front (&optional to-end)
18769 "Move/add the current file to the top of the agenda file list.
18770 If the file is not present in the list, it is added to the front. If it is
18771 present, it is moved there. With optional argument TO-END, add/move to the
18772 end of the list."
18773 (interactive "P")
18774 (let ((org-agenda-skip-unavailable-files nil)
18775 (file-alist (mapcar (lambda (x)
18776 (cons (file-truename x) x))
18777 (org-agenda-files t)))
18778 (ctf (file-truename buffer-file-name))
18779 x had)
18780 (setq x (assoc ctf file-alist) had x)
18782 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18783 (if to-end
18784 (setq file-alist (append (delq x file-alist) (list x)))
18785 (setq file-alist (cons x (delq x file-alist))))
18786 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18787 (org-install-agenda-files-menu)
18788 (message "File %s to %s of agenda file list"
18789 (if had "moved" "added") (if to-end "end" "front"))))
18791 (defun org-remove-file (&optional file)
18792 "Remove current file from the list of files in variable `org-agenda-files'.
18793 These are the files which are being checked for agenda entries.
18794 Optional argument FILE means, use this file instead of the current."
18795 (interactive)
18796 (let* ((org-agenda-skip-unavailable-files nil)
18797 (file (or file buffer-file-name))
18798 (true-file (file-truename file))
18799 (afile (abbreviate-file-name file))
18800 (files (delq nil (mapcar
18801 (lambda (x)
18802 (if (equal true-file
18803 (file-truename x))
18804 nil x))
18805 (org-agenda-files t)))))
18806 (if (not (= (length files) (length (org-agenda-files t))))
18807 (progn
18808 (org-store-new-agenda-file-list files)
18809 (org-install-agenda-files-menu)
18810 (message "Removed file: %s" afile))
18811 (message "File was not in list: %s" afile))))
18813 (defun org-file-menu-entry (file)
18814 (vector file (list 'find-file file) t))
18816 (defun org-check-agenda-file (file)
18817 "Make sure FILE exists. If not, ask user what to do."
18818 (when (not (file-exists-p file))
18819 (message "non-existent file %s. [R]emove from list or [A]bort?"
18820 (abbreviate-file-name file))
18821 (let ((r (downcase (read-char-exclusive))))
18822 (cond
18823 ((equal r ?r)
18824 (org-remove-file file)
18825 (throw 'nextfile t))
18826 (t (error "Abort"))))))
18828 ;;; Agenda prepare and finalize
18830 (defvar org-agenda-multi nil) ; dynammically scoped
18831 (defvar org-agenda-buffer-name "*Org Agenda*")
18832 (defvar org-pre-agenda-window-conf nil)
18833 (defvar org-agenda-name nil)
18834 (defun org-prepare-agenda (&optional name)
18835 (setq org-todo-keywords-for-agenda nil)
18836 (setq org-done-keywords-for-agenda nil)
18837 (if org-agenda-multi
18838 (progn
18839 (setq buffer-read-only nil)
18840 (goto-char (point-max))
18841 (unless (or (bobp) org-agenda-compact-blocks)
18842 (insert "\n" (make-string (window-width) ?=) "\n"))
18843 (narrow-to-region (point) (point-max)))
18844 (org-agenda-maybe-reset-markers 'force)
18845 (org-prepare-agenda-buffers (org-agenda-files))
18846 (setq org-todo-keywords-for-agenda
18847 (org-uniquify org-todo-keywords-for-agenda))
18848 (setq org-done-keywords-for-agenda
18849 (org-uniquify org-done-keywords-for-agenda))
18850 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
18851 (awin (get-buffer-window abuf)))
18852 (cond
18853 ((equal (current-buffer) abuf) nil)
18854 (awin (select-window awin))
18855 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
18856 ((equal org-agenda-window-setup 'current-window)
18857 (switch-to-buffer abuf))
18858 ((equal org-agenda-window-setup 'other-window)
18859 (org-switch-to-buffer-other-window abuf))
18860 ((equal org-agenda-window-setup 'other-frame)
18861 (switch-to-buffer-other-frame abuf))
18862 ((equal org-agenda-window-setup 'reorganize-frame)
18863 (delete-other-windows)
18864 (org-switch-to-buffer-other-window abuf))))
18865 (setq buffer-read-only nil)
18866 (erase-buffer)
18867 (org-agenda-mode)
18868 (and name (not org-agenda-name)
18869 (org-set-local 'org-agenda-name name)))
18870 (setq buffer-read-only nil))
18872 (defun org-finalize-agenda ()
18873 "Finishing touch for the agenda buffer, called just before displaying it."
18874 (unless org-agenda-multi
18875 (save-excursion
18876 (let ((inhibit-read-only t))
18877 (goto-char (point-min))
18878 (while (org-activate-bracket-links (point-max))
18879 (add-text-properties (match-beginning 0) (match-end 0)
18880 '(face org-link)))
18881 (org-agenda-align-tags)
18882 (unless org-agenda-with-colors
18883 (remove-text-properties (point-min) (point-max) '(face nil))))
18884 (if (and (boundp 'org-overriding-columns-format)
18885 org-overriding-columns-format)
18886 (org-set-local 'org-overriding-columns-format
18887 org-overriding-columns-format))
18888 (if (and (boundp 'org-agenda-view-columns-initially)
18889 org-agenda-view-columns-initially)
18890 (org-agenda-columns))
18891 (when org-agenda-fontify-priorities
18892 (org-fontify-priorities))
18893 (run-hooks 'org-finalize-agenda-hook))))
18895 (defun org-fontify-priorities ()
18896 "Make highest priority lines bold, and lowest italic."
18897 (interactive)
18898 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
18899 (org-delete-overlay o)))
18900 (overlays-in (point-min) (point-max)))
18901 (save-excursion
18902 (let ((ovs (org-overlays-in (point-min) (point-max)))
18903 (inhibit-read-only t)
18904 b e p ov h l)
18905 (goto-char (point-min))
18906 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
18907 (setq h (or (get-char-property (point) 'org-highest-priority)
18908 org-highest-priority)
18909 l (or (get-char-property (point) 'org-lowest-priority)
18910 org-lowest-priority)
18911 p (string-to-char (match-string 1))
18912 b (match-beginning 0) e (line-end-position)
18913 ov (org-make-overlay b e))
18914 (org-overlay-put
18915 ov 'face
18916 (cond ((listp org-agenda-fontify-priorities)
18917 (cdr (assoc p org-agenda-fontify-priorities)))
18918 ((equal p l) 'italic)
18919 ((equal p h) 'bold)))
18920 (org-overlay-put ov 'org-type 'org-priority)))))
18922 (defun org-prepare-agenda-buffers (files)
18923 "Create buffers for all agenda files, protect archived trees and comments."
18924 (interactive)
18925 (let ((pa '(:org-archived t))
18926 (pc '(:org-comment t))
18927 (pall '(:org-archived t :org-comment t))
18928 (inhibit-read-only t)
18929 (rea (concat ":" org-archive-tag ":"))
18930 bmp file re)
18931 (save-excursion
18932 (save-restriction
18933 (while (setq file (pop files))
18934 (org-check-agenda-file file)
18935 (set-buffer (org-get-agenda-file-buffer file))
18936 (widen)
18937 (setq bmp (buffer-modified-p))
18938 (org-refresh-category-properties)
18939 (setq org-todo-keywords-for-agenda
18940 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18941 (setq org-done-keywords-for-agenda
18942 (append org-done-keywords-for-agenda org-done-keywords))
18943 (save-excursion
18944 (remove-text-properties (point-min) (point-max) pall)
18945 (when org-agenda-skip-archived-trees
18946 (goto-char (point-min))
18947 (while (re-search-forward rea nil t)
18948 (if (org-on-heading-p t)
18949 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18950 (goto-char (point-min))
18951 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
18952 (while (re-search-forward re nil t)
18953 (add-text-properties
18954 (match-beginning 0) (org-end-of-subtree t) pc)))
18955 (set-buffer-modified-p bmp))))))
18957 (defvar org-agenda-skip-function nil
18958 "Function to be called at each match during agenda construction.
18959 If this function returns nil, the current match should not be skipped.
18960 Otherwise, the function must return a position from where the search
18961 should be continued.
18962 This may also be a Lisp form, it will be evaluated.
18963 Never set this variable using `setq' or so, because then it will apply
18964 to all future agenda commands. Instead, bind it with `let' to scope
18965 it dynamically into the agenda-constructing command. A good way to set
18966 it is through options in org-agenda-custom-commands.")
18968 (defun org-agenda-skip ()
18969 "Throw to `:skip' in places that should be skipped.
18970 Also moves point to the end of the skipped region, so that search can
18971 continue from there."
18972 (let ((p (point-at-bol)) to fp)
18973 (and org-agenda-skip-archived-trees
18974 (get-text-property p :org-archived)
18975 (org-end-of-subtree t)
18976 (throw :skip t))
18977 (and (get-text-property p :org-comment)
18978 (org-end-of-subtree t)
18979 (throw :skip t))
18980 (if (equal (char-after p) ?#) (throw :skip t))
18981 (when (and (or (setq fp (functionp org-agenda-skip-function))
18982 (consp org-agenda-skip-function))
18983 (setq to (save-excursion
18984 (save-match-data
18985 (if fp
18986 (funcall org-agenda-skip-function)
18987 (eval org-agenda-skip-function))))))
18988 (goto-char to)
18989 (throw :skip t))))
18991 (defvar org-agenda-markers nil
18992 "List of all currently active markers created by `org-agenda'.")
18993 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
18994 "Creation time of the last agenda marker.")
18996 (defun org-agenda-new-marker (&optional pos)
18997 "Return a new agenda marker.
18998 Org-mode keeps a list of these markers and resets them when they are
18999 no longer in use."
19000 (let ((m (copy-marker (or pos (point)))))
19001 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
19002 (push m org-agenda-markers)
19005 (defun org-agenda-maybe-reset-markers (&optional force)
19006 "Reset markers created by `org-agenda'. But only if they are old enough."
19007 (if (or (and force (not org-agenda-multi))
19008 (> (- (time-to-seconds (current-time))
19009 org-agenda-last-marker-time)
19011 (while org-agenda-markers
19012 (move-marker (pop org-agenda-markers) nil))))
19014 (defvar org-agenda-new-buffers nil
19015 "Buffers created to visit agenda files.")
19017 (defun org-get-agenda-file-buffer (file)
19018 "Get a buffer visiting FILE. If the buffer needs to be created, add
19019 it to the list of buffers which might be released later."
19020 (let ((buf (org-find-base-buffer-visiting file)))
19021 (if buf
19022 buf ; just return it
19023 ;; Make a new buffer and remember it
19024 (setq buf (find-file-noselect file))
19025 (if buf (push buf org-agenda-new-buffers))
19026 buf)))
19028 (defun org-release-buffers (blist)
19029 "Release all buffers in list, asking the user for confirmation when needed.
19030 When a buffer is unmodified, it is just killed. When modified, it is saved
19031 \(if the user agrees) and then killed."
19032 (let (buf file)
19033 (while (setq buf (pop blist))
19034 (setq file (buffer-file-name buf))
19035 (when (and (buffer-modified-p buf)
19036 file
19037 (y-or-n-p (format "Save file %s? " file)))
19038 (with-current-buffer buf (save-buffer)))
19039 (kill-buffer buf))))
19041 (defun org-get-category (&optional pos)
19042 "Get the category applying to position POS."
19043 (get-text-property (or pos (point)) 'org-category))
19045 ;;; Agenda timeline
19047 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
19049 (defun org-timeline (&optional include-all)
19050 "Show a time-sorted view of the entries in the current org file.
19051 Only entries with a time stamp of today or later will be listed. With
19052 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
19053 under the current date.
19054 If the buffer contains an active region, only check the region for
19055 dates."
19056 (interactive "P")
19057 (require 'calendar)
19058 (org-compile-prefix-format 'timeline)
19059 (org-set-sorting-strategy 'timeline)
19060 (let* ((dopast t)
19061 (dotodo include-all)
19062 (doclosed org-agenda-show-log)
19063 (entry buffer-file-name)
19064 (date (calendar-current-date))
19065 (beg (if (org-region-active-p) (region-beginning) (point-min)))
19066 (end (if (org-region-active-p) (region-end) (point-max)))
19067 (day-numbers (org-get-all-dates beg end 'no-ranges
19068 t doclosed ; always include today
19069 org-timeline-show-empty-dates))
19070 (org-deadline-warning-days 0)
19071 (org-agenda-only-exact-dates t)
19072 (today (time-to-days (current-time)))
19073 (past t)
19074 args
19075 s e rtn d emptyp)
19076 (setq org-agenda-redo-command
19077 (list 'progn
19078 (list 'org-switch-to-buffer-other-window (current-buffer))
19079 (list 'org-timeline (list 'quote include-all))))
19080 (if (not dopast)
19081 ;; Remove past dates from the list of dates.
19082 (setq day-numbers (delq nil (mapcar (lambda(x)
19083 (if (>= x today) x nil))
19084 day-numbers))))
19085 (org-prepare-agenda (concat "Timeline "
19086 (file-name-nondirectory buffer-file-name)))
19087 (if doclosed (push :closed args))
19088 (push :timestamp args)
19089 (push :deadline args)
19090 (push :scheduled args)
19091 (push :sexp args)
19092 (if dotodo (push :todo args))
19093 (while (setq d (pop day-numbers))
19094 (if (and (listp d) (eq (car d) :omitted))
19095 (progn
19096 (setq s (point))
19097 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
19098 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
19099 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
19100 (if (and (>= d today)
19101 dopast
19102 past)
19103 (progn
19104 (setq past nil)
19105 (insert (make-string 79 ?-) "\n")))
19106 (setq date (calendar-gregorian-from-absolute d))
19107 (setq s (point))
19108 (setq rtn (and (not emptyp)
19109 (apply 'org-agenda-get-day-entries entry
19110 date args)))
19111 (if (or rtn (equal d today) org-timeline-show-empty-dates)
19112 (progn
19113 (insert
19114 (if (stringp org-agenda-format-date)
19115 (format-time-string org-agenda-format-date
19116 (org-time-from-absolute date))
19117 (funcall org-agenda-format-date date))
19118 "\n")
19119 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
19120 (put-text-property s (1- (point)) 'org-date-line t)
19121 (if (equal d today)
19122 (put-text-property s (1- (point)) 'org-today t))
19123 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
19124 (put-text-property s (1- (point)) 'day d)))))
19125 (goto-char (point-min))
19126 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
19127 (point-min)))
19128 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
19129 (org-finalize-agenda)
19130 (setq buffer-read-only t)))
19132 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
19133 "Return a list of all relevant day numbers from BEG to END buffer positions.
19134 If NO-RANGES is non-nil, include only the start and end dates of a range,
19135 not every single day in the range. If FORCE-TODAY is non-nil, make
19136 sure that TODAY is included in the list. If INACTIVE is non-nil, also
19137 inactive time stamps (those in square brackets) are included.
19138 When EMPTY is non-nil, also include days without any entries."
19139 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
19140 dates dates1 date day day1 day2 ts1 ts2)
19141 (if force-today
19142 (setq dates (list (time-to-days (current-time)))))
19143 (save-excursion
19144 (goto-char beg)
19145 (while (re-search-forward re end t)
19146 (setq day (time-to-days (org-time-string-to-time
19147 (substring (match-string 1) 0 10))))
19148 (or (memq day dates) (push day dates)))
19149 (unless no-ranges
19150 (goto-char beg)
19151 (while (re-search-forward org-tr-regexp end t)
19152 (setq ts1 (substring (match-string 1) 0 10)
19153 ts2 (substring (match-string 2) 0 10)
19154 day1 (time-to-days (org-time-string-to-time ts1))
19155 day2 (time-to-days (org-time-string-to-time ts2)))
19156 (while (< (setq day1 (1+ day1)) day2)
19157 (or (memq day1 dates) (push day1 dates)))))
19158 (setq dates (sort dates '<))
19159 (when empty
19160 (while (setq day (pop dates))
19161 (setq day2 (car dates))
19162 (push day dates1)
19163 (when (and day2 empty)
19164 (if (or (eq empty t)
19165 (and (numberp empty) (<= (- day2 day) empty)))
19166 (while (< (setq day (1+ day)) day2)
19167 (push (list day) dates1))
19168 (push (cons :omitted (- day2 day)) dates1))))
19169 (setq dates (nreverse dates1)))
19170 dates)))
19172 ;;; Agenda Daily/Weekly
19174 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
19175 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
19176 (defvar org-agenda-last-arguments nil
19177 "The arguments of the previous call to org-agenda")
19178 (defvar org-starting-day nil) ; local variable in the agenda buffer
19179 (defvar org-agenda-span nil) ; local variable in the agenda buffer
19180 (defvar org-include-all-loc nil) ; local variable
19181 (defvar org-agenda-remove-date nil) ; dynamically scoped
19183 ;;;###autoload
19184 (defun org-agenda-list (&optional include-all start-day ndays)
19185 "Produce a weekly view from all files in variable `org-agenda-files'.
19186 The view will be for the current week, but from the overview buffer you
19187 will be able to go to other weeks.
19188 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
19189 also be shown, under the current date.
19190 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
19191 on the days are also shown. See the variable `org-log-done' for how
19192 to turn on logging.
19193 START-DAY defaults to TODAY, or to the most recent match for the weekday
19194 given in `org-agenda-start-on-weekday'.
19195 NDAYS defaults to `org-agenda-ndays'."
19196 (interactive "P")
19197 (setq ndays (or ndays org-agenda-ndays)
19198 start-day (or start-day org-agenda-start-day))
19199 (if org-agenda-overriding-arguments
19200 (setq include-all (car org-agenda-overriding-arguments)
19201 start-day (nth 1 org-agenda-overriding-arguments)
19202 ndays (nth 2 org-agenda-overriding-arguments)))
19203 (if (stringp start-day)
19204 ;; Convert to an absolute day number
19205 (setq start-day (time-to-days (org-read-date nil t start-day))))
19206 (setq org-agenda-last-arguments (list include-all start-day ndays))
19207 (org-compile-prefix-format 'agenda)
19208 (org-set-sorting-strategy 'agenda)
19209 (require 'calendar)
19210 (let* ((org-agenda-start-on-weekday
19211 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
19212 org-agenda-start-on-weekday nil))
19213 (thefiles (org-agenda-files))
19214 (files thefiles)
19215 (today (time-to-days (current-time)))
19216 (sd (or start-day today))
19217 (start (if (or (null org-agenda-start-on-weekday)
19218 (< org-agenda-ndays 7))
19220 (let* ((nt (calendar-day-of-week
19221 (calendar-gregorian-from-absolute sd)))
19222 (n1 org-agenda-start-on-weekday)
19223 (d (- nt n1)))
19224 (- sd (+ (if (< d 0) 7 0) d)))))
19225 (day-numbers (list start))
19226 (day-cnt 0)
19227 (inhibit-redisplay (not debug-on-error))
19228 s e rtn rtnall file date d start-pos end-pos todayp nd)
19229 (setq org-agenda-redo-command
19230 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
19231 ;; Make the list of days
19232 (setq ndays (or ndays org-agenda-ndays)
19233 nd ndays)
19234 (while (> ndays 1)
19235 (push (1+ (car day-numbers)) day-numbers)
19236 (setq ndays (1- ndays)))
19237 (setq day-numbers (nreverse day-numbers))
19238 (org-prepare-agenda "Day/Week")
19239 (org-set-local 'org-starting-day (car day-numbers))
19240 (org-set-local 'org-include-all-loc include-all)
19241 (org-set-local 'org-agenda-span
19242 (org-agenda-ndays-to-span nd))
19243 (when (and (or include-all org-agenda-include-all-todo)
19244 (member today day-numbers))
19245 (setq files thefiles
19246 rtnall nil)
19247 (while (setq file (pop files))
19248 (catch 'nextfile
19249 (org-check-agenda-file file)
19250 (setq date (calendar-gregorian-from-absolute today)
19251 rtn (org-agenda-get-day-entries
19252 file date :todo))
19253 (setq rtnall (append rtnall rtn))))
19254 (when rtnall
19255 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
19256 (add-text-properties (point-min) (1- (point))
19257 (list 'face 'org-agenda-structure))
19258 (insert (org-finalize-agenda-entries rtnall) "\n")))
19259 (unless org-agenda-compact-blocks
19260 (setq s (point))
19261 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
19262 "-agenda:\n")
19263 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
19264 'org-date-line t)))
19265 (while (setq d (pop day-numbers))
19266 (setq date (calendar-gregorian-from-absolute d)
19267 s (point))
19268 (if (or (setq todayp (= d today))
19269 (and (not start-pos) (= d sd)))
19270 (setq start-pos (point))
19271 (if (and start-pos (not end-pos))
19272 (setq end-pos (point))))
19273 (setq files thefiles
19274 rtnall nil)
19275 (while (setq file (pop files))
19276 (catch 'nextfile
19277 (org-check-agenda-file file)
19278 (if org-agenda-show-log
19279 (setq rtn (org-agenda-get-day-entries
19280 file date
19281 :deadline :scheduled :timestamp :sexp :closed))
19282 (setq rtn (org-agenda-get-day-entries
19283 file date
19284 :deadline :scheduled :sexp :timestamp)))
19285 (setq rtnall (append rtnall rtn))))
19286 (if org-agenda-include-diary
19287 (progn
19288 (require 'diary-lib)
19289 (setq rtn (org-get-entries-from-diary date))
19290 (setq rtnall (append rtnall rtn))))
19291 (if (or rtnall org-agenda-show-all-dates)
19292 (progn
19293 (setq day-cnt (1+ day-cnt))
19294 (insert
19295 (if (stringp org-agenda-format-date)
19296 (format-time-string org-agenda-format-date
19297 (org-time-from-absolute date))
19298 (funcall org-agenda-format-date date))
19299 "\n")
19300 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
19301 (put-text-property s (1- (point)) 'org-date-line t)
19302 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
19303 (if todayp (put-text-property s (1- (point)) 'org-today t))
19304 (if rtnall (insert
19305 (org-finalize-agenda-entries
19306 (org-agenda-add-time-grid-maybe
19307 rtnall nd todayp))
19308 "\n"))
19309 (put-text-property s (1- (point)) 'day d)
19310 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
19311 (goto-char (point-min))
19312 (org-fit-agenda-window)
19313 (unless (and (pos-visible-in-window-p (point-min))
19314 (pos-visible-in-window-p (point-max)))
19315 (goto-char (1- (point-max)))
19316 (recenter -1)
19317 (if (not (pos-visible-in-window-p (or start-pos 1)))
19318 (progn
19319 (goto-char (or start-pos 1))
19320 (recenter 1))))
19321 (goto-char (or start-pos 1))
19322 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
19323 (org-finalize-agenda)
19324 (setq buffer-read-only t)
19325 (message "")))
19327 (defun org-agenda-ndays-to-span (n)
19328 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
19330 ;;; Agenda TODO list
19332 (defvar org-select-this-todo-keyword nil)
19333 (defvar org-last-arg nil)
19335 ;;;###autoload
19336 (defun org-todo-list (arg)
19337 "Show all TODO entries from all agenda file in a single list.
19338 The prefix arg can be used to select a specific TODO keyword and limit
19339 the list to these. When using \\[universal-argument], you will be prompted
19340 for a keyword. A numeric prefix directly selects the Nth keyword in
19341 `org-todo-keywords-1'."
19342 (interactive "P")
19343 (require 'calendar)
19344 (org-compile-prefix-format 'todo)
19345 (org-set-sorting-strategy 'todo)
19346 (org-prepare-agenda "TODO")
19347 (let* ((today (time-to-days (current-time)))
19348 (date (calendar-gregorian-from-absolute today))
19349 (kwds org-todo-keywords-for-agenda)
19350 (completion-ignore-case t)
19351 (org-select-this-todo-keyword
19352 (if (stringp arg) arg
19353 (and arg (integerp arg) (> arg 0)
19354 (nth (1- arg) kwds))))
19355 rtn rtnall files file pos)
19356 (when (equal arg '(4))
19357 (setq org-select-this-todo-keyword
19358 (completing-read "Keyword (or KWD1|K2D2|...): "
19359 (mapcar 'list kwds) nil nil)))
19360 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
19361 (org-set-local 'org-last-arg arg)
19362 (setq org-agenda-redo-command
19363 '(org-todo-list (or current-prefix-arg org-last-arg)))
19364 (setq files (org-agenda-files)
19365 rtnall nil)
19366 (while (setq file (pop files))
19367 (catch 'nextfile
19368 (org-check-agenda-file file)
19369 (setq rtn (org-agenda-get-day-entries file date :todo))
19370 (setq rtnall (append rtnall rtn))))
19371 (if org-agenda-overriding-header
19372 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
19373 nil 'face 'org-agenda-structure) "\n")
19374 (insert "Global list of TODO items of type: ")
19375 (add-text-properties (point-min) (1- (point))
19376 (list 'face 'org-agenda-structure))
19377 (setq pos (point))
19378 (insert (or org-select-this-todo-keyword "ALL") "\n")
19379 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
19380 (setq pos (point))
19381 (unless org-agenda-multi
19382 (insert "Available with `N r': (0)ALL")
19383 (let ((n 0) s)
19384 (mapc (lambda (x)
19385 (setq s (format "(%d)%s" (setq n (1+ n)) x))
19386 (if (> (+ (current-column) (string-width s) 1) (frame-width))
19387 (insert "\n "))
19388 (insert " " s))
19389 kwds))
19390 (insert "\n"))
19391 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
19392 (when rtnall
19393 (insert (org-finalize-agenda-entries rtnall) "\n"))
19394 (goto-char (point-min))
19395 (org-fit-agenda-window)
19396 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
19397 (org-finalize-agenda)
19398 (setq buffer-read-only t)))
19400 ;;; Agenda tags match
19402 ;;;###autoload
19403 (defun org-tags-view (&optional todo-only match)
19404 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
19405 The prefix arg TODO-ONLY limits the search to TODO entries."
19406 (interactive "P")
19407 (org-compile-prefix-format 'tags)
19408 (org-set-sorting-strategy 'tags)
19409 (let* ((org-tags-match-list-sublevels
19410 (if todo-only t org-tags-match-list-sublevels))
19411 (completion-ignore-case t)
19412 rtn rtnall files file pos matcher
19413 buffer)
19414 (setq matcher (org-make-tags-matcher match)
19415 match (car matcher) matcher (cdr matcher))
19416 (org-prepare-agenda (concat "TAGS " match))
19417 (setq org-agenda-redo-command
19418 (list 'org-tags-view (list 'quote todo-only)
19419 (list 'if 'current-prefix-arg nil match)))
19420 (setq files (org-agenda-files)
19421 rtnall nil)
19422 (while (setq file (pop files))
19423 (catch 'nextfile
19424 (org-check-agenda-file file)
19425 (setq buffer (if (file-exists-p file)
19426 (org-get-agenda-file-buffer file)
19427 (error "No such file %s" file)))
19428 (if (not buffer)
19429 ;; If file does not exist, merror message to agenda
19430 (setq rtn (list
19431 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
19432 rtnall (append rtnall rtn))
19433 (with-current-buffer buffer
19434 (unless (org-mode-p)
19435 (error "Agenda file %s is not in `org-mode'" file))
19436 (save-excursion
19437 (save-restriction
19438 (if org-agenda-restrict
19439 (narrow-to-region org-agenda-restrict-begin
19440 org-agenda-restrict-end)
19441 (widen))
19442 (setq rtn (org-scan-tags 'agenda matcher todo-only))
19443 (setq rtnall (append rtnall rtn))))))))
19444 (if org-agenda-overriding-header
19445 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
19446 nil 'face 'org-agenda-structure) "\n")
19447 (insert "Headlines with TAGS match: ")
19448 (add-text-properties (point-min) (1- (point))
19449 (list 'face 'org-agenda-structure))
19450 (setq pos (point))
19451 (insert match "\n")
19452 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
19453 (setq pos (point))
19454 (unless org-agenda-multi
19455 (insert "Press `C-u r' to search again with new search string\n"))
19456 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
19457 (when rtnall
19458 (insert (org-finalize-agenda-entries rtnall) "\n"))
19459 (goto-char (point-min))
19460 (org-fit-agenda-window)
19461 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
19462 (org-finalize-agenda)
19463 (setq buffer-read-only t)))
19465 ;;; Agenda Finding stuck projects
19467 (defvar org-agenda-skip-regexp nil
19468 "Regular expression used in skipping subtrees for the agenda.
19469 This is basically a temporary global variable that can be set and then
19470 used by user-defined selections using `org-agenda-skip-function'.")
19472 (defvar org-agenda-overriding-header nil
19473 "When this is set during todo and tags searches, will replace header.")
19475 (defun org-agenda-skip-subtree-when-regexp-matches ()
19476 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
19477 If yes, it returns the end position of this tree, causing agenda commands
19478 to skip this subtree. This is a function that can be put into
19479 `org-agenda-skip-function' for the duration of a command."
19480 (let ((end (save-excursion (org-end-of-subtree t)))
19481 skip)
19482 (save-excursion
19483 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
19484 (and skip end)))
19486 (defun org-agenda-skip-entry-if (&rest conditions)
19487 "Skip entry if any of CONDITIONS is true.
19488 See `org-agenda-skip-if for details."
19489 (org-agenda-skip-if nil conditions))
19490 (defun org-agenda-skip-subtree-if (&rest conditions)
19491 "Skip entry if any of CONDITIONS is true.
19492 See `org-agenda-skip-if for details."
19493 (org-agenda-skip-if t conditions))
19495 (defun org-agenda-skip-if (subtree conditions)
19496 "Checks current entity for CONDITIONS.
19497 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
19498 the entry, i.e. the text before the next heading is checked.
19500 CONDITIONS is a list of symbols, boolean OR is used to combine the results
19501 from different tests. Valid conditions are:
19503 scheduled Check if there is a scheduled cookie
19504 notscheduled Check if there is no scheduled cookie
19505 deadline Check if there is a deadline
19506 notdeadline Check if there is no deadline
19507 regexp Check if regexp matches
19508 notregexp Check if regexp does not match.
19510 The regexp is taken from the conditions list, it must com right after the
19511 `regexp' of `notregexp' element.
19513 If any of these conditions is met, this function returns the end point of
19514 the entity, causing the search to continue from there. This is a function
19515 that can be put into `org-agenda-skip-function' for the duration of a command."
19516 (let (beg end m r)
19517 (org-back-to-heading t)
19518 (setq beg (point)
19519 end (if subtree
19520 (progn (org-end-of-subtree t) (point))
19521 (progn (outline-next-heading) (1- (point)))))
19522 (goto-char beg)
19523 (and
19525 (and (memq 'scheduled conditions)
19526 (re-search-forward org-scheduled-time-regexp end t))
19527 (and (memq 'notscheduled conditions)
19528 (not (re-search-forward org-scheduled-time-regexp end t)))
19529 (and (memq 'deadline conditions)
19530 (re-search-forward org-deadline-time-regexp end t))
19531 (and (memq 'notdeadline conditions)
19532 (not (re-search-forward org-deadline-time-regexp end t)))
19533 (and (setq m (memq 'regexp conditions))
19534 (stringp (setq r (nth 1 m)))
19535 (re-search-forward (nth 1 m) end t))
19536 (and (setq m (memq 'notregexp conditions))
19537 (stringp (setq r (nth 1 m)))
19538 (not (re-search-forward (nth 1 m) end t))))
19539 end)))
19541 (defun org-agenda-list-stuck-projects (&rest ignore)
19542 "Create agenda view for projects that are stuck.
19543 Stuck projects are project that have no next actions. For the definitions
19544 of what a project is and how to check if it stuck, customize the variable
19545 `org-stuck-projects'.
19546 MATCH is being ignored."
19547 (interactive)
19548 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
19549 ;; FIXME: we could have used org-agenda-skip-if here.
19550 (org-agenda-overriding-header "List of stuck projects: ")
19551 (matcher (nth 0 org-stuck-projects))
19552 (todo (nth 1 org-stuck-projects))
19553 (todo-wds (if (member "*" todo)
19554 (progn
19555 (org-prepare-agenda-buffers (org-agenda-files))
19556 (org-delete-all
19557 org-done-keywords-for-agenda
19558 (copy-sequence org-todo-keywords-for-agenda)))
19559 todo))
19560 (todo-re (concat "^\\*+[ \t]+\\("
19561 (mapconcat 'identity todo-wds "\\|")
19562 "\\)\\>"))
19563 (tags (nth 2 org-stuck-projects))
19564 (tags-re (if (member "*" tags)
19565 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
19566 (concat "^\\*+ .*:\\("
19567 (mapconcat 'identity tags "\\|")
19568 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
19569 (gen-re (nth 3 org-stuck-projects))
19570 (re-list
19571 (delq nil
19572 (list
19573 (if todo todo-re)
19574 (if tags tags-re)
19575 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
19576 gen-re)))))
19577 (setq org-agenda-skip-regexp
19578 (if re-list
19579 (mapconcat 'identity re-list "\\|")
19580 (error "No information how to identify unstuck projects")))
19581 (org-tags-view nil matcher)
19582 (with-current-buffer org-agenda-buffer-name
19583 (setq org-agenda-redo-command
19584 '(org-agenda-list-stuck-projects
19585 (or current-prefix-arg org-last-arg))))))
19587 ;;; Diary integration
19589 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
19591 (defun org-get-entries-from-diary (date)
19592 "Get the (Emacs Calendar) diary entries for DATE."
19593 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
19594 (diary-display-hook '(fancy-diary-display))
19595 (pop-up-frames nil)
19596 (list-diary-entries-hook
19597 (cons 'org-diary-default-entry list-diary-entries-hook))
19598 (diary-file-name-prefix-function nil) ; turn this feature off
19599 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
19600 entries
19601 (org-disable-agenda-to-diary t))
19602 (save-excursion
19603 (save-window-excursion
19604 (funcall (if (fboundp 'diary-list-entries)
19605 'diary-list-entries 'list-diary-entries)
19606 date 1)))
19607 (if (not (get-buffer fancy-diary-buffer))
19608 (setq entries nil)
19609 (with-current-buffer fancy-diary-buffer
19610 (setq buffer-read-only nil)
19611 (if (zerop (buffer-size))
19612 ;; No entries
19613 (setq entries nil)
19614 ;; Omit the date and other unnecessary stuff
19615 (org-agenda-cleanup-fancy-diary)
19616 ;; Add prefix to each line and extend the text properties
19617 (if (zerop (buffer-size))
19618 (setq entries nil)
19619 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
19620 (set-buffer-modified-p nil)
19621 (kill-buffer fancy-diary-buffer)))
19622 (when entries
19623 (setq entries (org-split-string entries "\n"))
19624 (setq entries
19625 (mapcar
19626 (lambda (x)
19627 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
19628 ;; Extend the text properties to the beginning of the line
19629 (org-add-props x (text-properties-at (1- (length x)) x)
19630 'type "diary" 'date date))
19631 entries)))))
19633 (defun org-agenda-cleanup-fancy-diary ()
19634 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
19635 This gets rid of the date, the underline under the date, and
19636 the dummy entry installed by `org-mode' to ensure non-empty diary for each
19637 date. It also removes lines that contain only whitespace."
19638 (goto-char (point-min))
19639 (if (looking-at ".*?:[ \t]*")
19640 (progn
19641 (replace-match "")
19642 (re-search-forward "\n=+$" nil t)
19643 (replace-match "")
19644 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
19645 (re-search-forward "\n=+$" nil t)
19646 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
19647 (goto-char (point-min))
19648 (while (re-search-forward "^ +\n" nil t)
19649 (replace-match ""))
19650 (goto-char (point-min))
19651 (if (re-search-forward "^Org-mode dummy\n?" nil t)
19652 (replace-match "")))
19654 ;; Make sure entries from the diary have the right text properties.
19655 (eval-after-load "diary-lib"
19656 '(if (boundp 'diary-modify-entry-list-string-function)
19657 ;; We can rely on the hook, nothing to do
19659 ;; Hook not avaiable, must use advice to make this work
19660 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
19661 "Make the position visible."
19662 (if (and org-disable-agenda-to-diary ;; called from org-agenda
19663 (stringp string)
19664 buffer-file-name)
19665 (setq string (org-modify-diary-entry-string string))))))
19667 (defun org-modify-diary-entry-string (string)
19668 "Add text properties to string, allowing org-mode to act on it."
19669 (org-add-props string nil
19670 'mouse-face 'highlight
19671 'keymap org-agenda-keymap
19672 'help-echo (if buffer-file-name
19673 (format "mouse-2 or RET jump to diary file %s"
19674 (abbreviate-file-name buffer-file-name))
19676 'org-agenda-diary-link t
19677 'org-marker (org-agenda-new-marker (point-at-bol))))
19679 (defun org-diary-default-entry ()
19680 "Add a dummy entry to the diary.
19681 Needed to avoid empty dates which mess up holiday display."
19682 ;; Catch the error if dealing with the new add-to-diary-alist
19683 (when org-disable-agenda-to-diary
19684 (condition-case nil
19685 (add-to-diary-list original-date "Org-mode dummy" "")
19686 (error
19687 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
19689 ;;;###autoload
19690 (defun org-diary (&rest args)
19691 "Return diary information from org-files.
19692 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
19693 It accesses org files and extracts information from those files to be
19694 listed in the diary. The function accepts arguments specifying what
19695 items should be listed. The following arguments are allowed:
19697 :timestamp List the headlines of items containing a date stamp or
19698 date range matching the selected date. Deadlines will
19699 also be listed, on the expiration day.
19701 :sexp List entries resulting from diary-like sexps.
19703 :deadline List any deadlines past due, or due within
19704 `org-deadline-warning-days'. The listing occurs only
19705 in the diary for *today*, not at any other date. If
19706 an entry is marked DONE, it is no longer listed.
19708 :scheduled List all items which are scheduled for the given date.
19709 The diary for *today* also contains items which were
19710 scheduled earlier and are not yet marked DONE.
19712 :todo List all TODO items from the org-file. This may be a
19713 long list - so this is not turned on by default.
19714 Like deadlines, these entries only show up in the
19715 diary for *today*, not at any other date.
19717 The call in the diary file should look like this:
19719 &%%(org-diary) ~/path/to/some/orgfile.org
19721 Use a separate line for each org file to check. Or, if you omit the file name,
19722 all files listed in `org-agenda-files' will be checked automatically:
19724 &%%(org-diary)
19726 If you don't give any arguments (as in the example above), the default
19727 arguments (:deadline :scheduled :timestamp :sexp) are used.
19728 So the example above may also be written as
19730 &%%(org-diary :deadline :timestamp :sexp :scheduled)
19732 The function expects the lisp variables `entry' and `date' to be provided
19733 by the caller, because this is how the calendar works. Don't use this
19734 function from a program - use `org-agenda-get-day-entries' instead."
19735 (org-agenda-maybe-reset-markers)
19736 (org-compile-prefix-format 'agenda)
19737 (org-set-sorting-strategy 'agenda)
19738 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
19739 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
19740 (list entry)
19741 (org-agenda-files t)))
19742 file rtn results)
19743 (org-prepare-agenda-buffers files)
19744 ;; If this is called during org-agenda, don't return any entries to
19745 ;; the calendar. Org Agenda will list these entries itself.
19746 (if org-disable-agenda-to-diary (setq files nil))
19747 (while (setq file (pop files))
19748 (setq rtn (apply 'org-agenda-get-day-entries file date args))
19749 (setq results (append results rtn)))
19750 (if results
19751 (concat (org-finalize-agenda-entries results) "\n"))))
19753 ;;; Agenda entry finders
19755 (defun org-agenda-get-day-entries (file date &rest args)
19756 "Does the work for `org-diary' and `org-agenda'.
19757 FILE is the path to a file to be checked for entries. DATE is date like
19758 the one returned by `calendar-current-date'. ARGS are symbols indicating
19759 which kind of entries should be extracted. For details about these, see
19760 the documentation of `org-diary'."
19761 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
19762 (let* ((org-startup-folded nil)
19763 (org-startup-align-all-tables nil)
19764 (buffer (if (file-exists-p file)
19765 (org-get-agenda-file-buffer file)
19766 (error "No such file %s" file)))
19767 arg results rtn)
19768 (if (not buffer)
19769 ;; If file does not exist, make sure an error message ends up in diary
19770 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
19771 (with-current-buffer buffer
19772 (unless (org-mode-p)
19773 (error "Agenda file %s is not in `org-mode'" file))
19774 (let ((case-fold-search nil))
19775 (save-excursion
19776 (save-restriction
19777 (if org-agenda-restrict
19778 (narrow-to-region org-agenda-restrict-begin
19779 org-agenda-restrict-end)
19780 (widen))
19781 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
19782 (while (setq arg (pop args))
19783 (cond
19784 ((and (eq arg :todo)
19785 (equal date (calendar-current-date)))
19786 (setq rtn (org-agenda-get-todos))
19787 (setq results (append results rtn)))
19788 ((eq arg :timestamp)
19789 (setq rtn (org-agenda-get-blocks))
19790 (setq results (append results rtn))
19791 (setq rtn (org-agenda-get-timestamps))
19792 (setq results (append results rtn)))
19793 ((eq arg :sexp)
19794 (setq rtn (org-agenda-get-sexps))
19795 (setq results (append results rtn)))
19796 ((eq arg :scheduled)
19797 (setq rtn (org-agenda-get-scheduled))
19798 (setq results (append results rtn)))
19799 ((eq arg :closed)
19800 (setq rtn (org-agenda-get-closed))
19801 (setq results (append results rtn)))
19802 ((eq arg :deadline)
19803 (setq rtn (org-agenda-get-deadlines))
19804 (setq results (append results rtn))))))))
19805 results))))
19807 ;; FIXME: this works only if the cursor is *not* at the
19808 ;; beginning of the entry
19809 ;(defun org-entry-is-done-p ()
19810 ; "Is the current entry marked DONE?"
19811 ; (save-excursion
19812 ; (and (re-search-backward "[\r\n]\\*+ " nil t)
19813 ; (looking-at org-nl-done-regexp))))
19815 (defun org-entry-is-todo-p ()
19816 (member (org-get-todo-state) org-not-done-keywords))
19818 (defun org-entry-is-done-p ()
19819 (member (org-get-todo-state) org-done-keywords))
19821 (defun org-get-todo-state ()
19822 (save-excursion
19823 (org-back-to-heading t)
19824 (and (looking-at org-todo-line-regexp)
19825 (match-end 2)
19826 (match-string 2))))
19828 (defun org-at-date-range-p (&optional inactive-ok)
19829 "Is the cursor inside a date range?"
19830 (interactive)
19831 (save-excursion
19832 (catch 'exit
19833 (let ((pos (point)))
19834 (skip-chars-backward "^[<\r\n")
19835 (skip-chars-backward "<[")
19836 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
19837 (>= (match-end 0) pos)
19838 (throw 'exit t))
19839 (skip-chars-backward "^<[\r\n")
19840 (skip-chars-backward "<[")
19841 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
19842 (>= (match-end 0) pos)
19843 (throw 'exit t)))
19844 nil)))
19846 (defun org-agenda-get-todos ()
19847 "Return the TODO information for agenda display."
19848 (let* ((props (list 'face nil
19849 'done-face 'org-done
19850 'org-not-done-regexp org-not-done-regexp
19851 'org-todo-regexp org-todo-regexp
19852 'mouse-face 'highlight
19853 'keymap org-agenda-keymap
19854 'help-echo
19855 (format "mouse-2 or RET jump to org file %s"
19856 (abbreviate-file-name buffer-file-name))))
19857 ;; FIXME: get rid of the \n at some point but watch out
19858 (regexp (concat "^\\*+[ \t]+\\("
19859 (if org-select-this-todo-keyword
19860 (if (equal org-select-this-todo-keyword "*")
19861 org-todo-regexp
19862 (concat "\\<\\("
19863 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
19864 "\\)\\>"))
19865 org-not-done-regexp)
19866 "[^\n\r]*\\)"))
19867 marker priority category tags
19868 ee txt beg end)
19869 (goto-char (point-min))
19870 (while (re-search-forward regexp nil t)
19871 (catch :skip
19872 (save-match-data
19873 (beginning-of-line)
19874 (setq beg (point) end (progn (outline-next-heading) (point)))
19875 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
19876 (re-search-forward org-ts-regexp end t))
19877 (and org-agenda-todo-ignore-scheduled (goto-char beg)
19878 (re-search-forward org-scheduled-time-regexp end t))
19879 (and org-agenda-todo-ignore-deadlines (goto-char beg)
19880 (re-search-forward org-deadline-time-regexp end t)
19881 (org-deadline-close (match-string 1))))
19882 (goto-char (1+ beg))
19883 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
19884 (throw :skip nil)))
19885 (goto-char beg)
19886 (org-agenda-skip)
19887 (goto-char (match-beginning 1))
19888 (setq marker (org-agenda-new-marker (match-beginning 0))
19889 category (org-get-category)
19890 tags (org-get-tags-at (point))
19891 txt (org-format-agenda-item "" (match-string 1) category tags)
19892 priority (1+ (org-get-priority txt)))
19893 (org-add-props txt props
19894 'org-marker marker 'org-hd-marker marker
19895 'priority priority 'org-category category
19896 'type "todo")
19897 (push txt ee)
19898 (if org-agenda-todo-list-sublevels
19899 (goto-char (match-end 1))
19900 (org-end-of-subtree 'invisible))))
19901 (nreverse ee)))
19903 (defconst org-agenda-no-heading-message
19904 "No heading for this item in buffer or region.")
19906 (defun org-agenda-get-timestamps ()
19907 "Return the date stamp information for agenda display."
19908 (let* ((props (list 'face nil
19909 'org-not-done-regexp org-not-done-regexp
19910 'org-todo-regexp org-todo-regexp
19911 'mouse-face 'highlight
19912 'keymap org-agenda-keymap
19913 'help-echo
19914 (format "mouse-2 or RET jump to org file %s"
19915 (abbreviate-file-name buffer-file-name))))
19916 (d1 (calendar-absolute-from-gregorian date))
19917 (remove-re
19918 (concat
19919 (regexp-quote
19920 (format-time-string
19921 "<%Y-%m-%d"
19922 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
19923 ".*?>"))
19924 (regexp
19925 (concat
19926 (regexp-quote
19927 (substring
19928 (format-time-string
19929 (car org-time-stamp-formats)
19930 (apply 'encode-time ; DATE bound by calendar
19931 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
19932 0 11))
19933 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
19934 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
19935 marker hdmarker deadlinep scheduledp donep tmp priority category
19936 ee txt timestr tags b0 b3 e3)
19937 (goto-char (point-min))
19938 (while (re-search-forward regexp nil t)
19939 (setq b0 (match-beginning 0)
19940 b3 (match-beginning 3) e3 (match-end 3))
19941 (catch :skip
19942 (and (org-at-date-range-p) (throw :skip nil))
19943 (org-agenda-skip)
19944 (if (and (match-end 1)
19945 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
19946 (throw :skip nil))
19947 (if (and e3
19948 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
19949 (throw :skip nil))
19950 (setq marker (org-agenda-new-marker b0)
19951 category (org-get-category b0)
19952 tmp (buffer-substring (max (point-min)
19953 (- b0 org-ds-keyword-length))
19955 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
19956 deadlinep (string-match org-deadline-regexp tmp)
19957 scheduledp (string-match org-scheduled-regexp tmp)
19958 donep (org-entry-is-done-p))
19959 (if (or scheduledp deadlinep) (throw :skip t))
19960 (if (string-match ">" timestr)
19961 ;; substring should only run to end of time stamp
19962 (setq timestr (substring timestr 0 (match-end 0))))
19963 (save-excursion
19964 (if (re-search-backward "^\\*+ " nil t)
19965 (progn
19966 (goto-char (match-beginning 0))
19967 (setq hdmarker (org-agenda-new-marker)
19968 tags (org-get-tags-at))
19969 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
19970 (setq txt (org-format-agenda-item
19971 nil (match-string 1) category tags timestr nil
19972 remove-re)))
19973 (setq txt org-agenda-no-heading-message))
19974 (setq priority (org-get-priority txt))
19975 (org-add-props txt props
19976 'org-marker marker 'org-hd-marker hdmarker)
19977 (org-add-props txt nil 'priority priority
19978 'org-category category 'date date
19979 'type "timestamp")
19980 (push txt ee))
19981 (outline-next-heading)))
19982 (nreverse ee)))
19984 (defun org-agenda-get-sexps ()
19985 "Return the sexp information for agenda display."
19986 (require 'diary-lib)
19987 (let* ((props (list 'face nil
19988 'mouse-face 'highlight
19989 'keymap org-agenda-keymap
19990 'help-echo
19991 (format "mouse-2 or RET jump to org file %s"
19992 (abbreviate-file-name buffer-file-name))))
19993 (regexp "^&?%%(")
19994 marker category ee txt tags entry result beg b sexp sexp-entry)
19995 (goto-char (point-min))
19996 (while (re-search-forward regexp nil t)
19997 (catch :skip
19998 (org-agenda-skip)
19999 (setq beg (match-beginning 0))
20000 (goto-char (1- (match-end 0)))
20001 (setq b (point))
20002 (forward-sexp 1)
20003 (setq sexp (buffer-substring b (point)))
20004 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
20005 (org-trim (match-string 1))
20006 ""))
20007 (setq result (org-diary-sexp-entry sexp sexp-entry date))
20008 (when result
20009 (setq marker (org-agenda-new-marker beg)
20010 category (org-get-category beg))
20012 (if (string-match "\\S-" result)
20013 (setq txt result)
20014 (setq txt "SEXP entry returned empty string"))
20016 (setq txt (org-format-agenda-item
20017 "" txt category tags 'time))
20018 (org-add-props txt props 'org-marker marker)
20019 (org-add-props txt nil
20020 'org-category category 'date date
20021 'type "sexp")
20022 (push txt ee))))
20023 (nreverse ee)))
20025 (defun org-agenda-get-closed ()
20026 "Return the logged TODO entries for agenda display."
20027 (let* ((props (list 'mouse-face 'highlight
20028 'org-not-done-regexp org-not-done-regexp
20029 'org-todo-regexp org-todo-regexp
20030 'keymap org-agenda-keymap
20031 'help-echo
20032 (format "mouse-2 or RET jump to org file %s"
20033 (abbreviate-file-name buffer-file-name))))
20034 (regexp (concat
20035 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
20036 (regexp-quote
20037 (substring
20038 (format-time-string
20039 (car org-time-stamp-formats)
20040 (apply 'encode-time ; DATE bound by calendar
20041 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
20042 1 11))))
20043 marker hdmarker priority category tags closedp
20044 ee txt timestr)
20045 (goto-char (point-min))
20046 (while (re-search-forward regexp nil t)
20047 (catch :skip
20048 (org-agenda-skip)
20049 (setq marker (org-agenda-new-marker (match-beginning 0))
20050 closedp (equal (match-string 1) org-closed-string)
20051 category (org-get-category (match-beginning 0))
20052 timestr (buffer-substring (match-beginning 0) (point-at-eol))
20053 ;; donep (org-entry-is-done-p)
20055 (if (string-match "\\]" timestr)
20056 ;; substring should only run to end of time stamp
20057 (setq timestr (substring timestr 0 (match-end 0))))
20058 (save-excursion
20059 (if (re-search-backward "^\\*+ " nil t)
20060 (progn
20061 (goto-char (match-beginning 0))
20062 (setq hdmarker (org-agenda-new-marker)
20063 tags (org-get-tags-at))
20064 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
20065 (setq txt (org-format-agenda-item
20066 (if closedp "Closed: " "Clocked: ")
20067 (match-string 1) category tags timestr)))
20068 (setq txt org-agenda-no-heading-message))
20069 (setq priority 100000)
20070 (org-add-props txt props
20071 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
20072 'priority priority 'org-category category
20073 'type "closed" 'date date
20074 'undone-face 'org-warning 'done-face 'org-done)
20075 (push txt ee))
20076 (outline-next-heading)))
20077 (nreverse ee)))
20079 (defun org-agenda-get-deadlines ()
20080 "Return the deadline information for agenda display."
20081 (let* ((props (list 'mouse-face 'highlight
20082 'org-not-done-regexp org-not-done-regexp
20083 'org-todo-regexp org-todo-regexp
20084 'keymap org-agenda-keymap
20085 'help-echo
20086 (format "mouse-2 or RET jump to org file %s"
20087 (abbreviate-file-name buffer-file-name))))
20088 (regexp org-deadline-time-regexp)
20089 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
20090 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
20091 d2 diff dfrac wdays pos pos1 category tags
20092 ee txt head face s upcomingp donep timestr)
20093 (goto-char (point-min))
20094 (while (re-search-forward regexp nil t)
20095 (catch :skip
20096 (org-agenda-skip)
20097 (setq s (match-string 1)
20098 pos (1- (match-beginning 1))
20099 d2 (org-time-string-to-absolute (match-string 1) d1)
20100 diff (- d2 d1)
20101 wdays (org-get-wdays s)
20102 dfrac (/ (* 1.0 (- wdays diff)) wdays)
20103 upcomingp (and todayp (> diff 0)))
20104 ;; When to show a deadline in the calendar:
20105 ;; If the expiration is within wdays warning time.
20106 ;; Past-due deadlines are only shown on the current date
20107 (if (or (and (<= diff wdays)
20108 (and todayp (not org-agenda-only-exact-dates)))
20109 (= diff 0))
20110 (save-excursion
20111 (setq category (org-get-category))
20112 (if (re-search-backward "^\\*+[ \t]+" nil t)
20113 (progn
20114 (goto-char (match-end 0))
20115 (setq pos1 (match-beginning 0))
20116 (setq tags (org-get-tags-at pos1))
20117 (setq head (buffer-substring-no-properties
20118 (point)
20119 (progn (skip-chars-forward "^\r\n")
20120 (point))))
20121 (setq donep (string-match org-looking-at-done-regexp head))
20122 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
20123 (setq timestr
20124 (concat (substring s (match-beginning 1)) " "))
20125 (setq timestr 'time))
20126 (if (and donep
20127 (or org-agenda-skip-deadline-if-done
20128 (not (= diff 0))))
20129 (setq txt nil)
20130 (setq txt (org-format-agenda-item
20131 (if (= diff 0)
20132 (car org-agenda-deadline-leaders)
20133 (format (nth 1 org-agenda-deadline-leaders)
20134 diff))
20135 head category tags timestr))))
20136 (setq txt org-agenda-no-heading-message))
20137 (when txt
20138 (setq face (org-agenda-deadline-face dfrac))
20139 (org-add-props txt props
20140 'org-marker (org-agenda-new-marker pos)
20141 'org-hd-marker (org-agenda-new-marker pos1)
20142 'priority (+ (if upcomingp (floor (* dfrac 10.)) 100)
20143 (org-get-priority txt))
20144 'org-category category
20145 'type (if upcomingp "upcoming-deadline" "deadline")
20146 'date (if upcomingp date d2)
20147 'face (if donep 'org-done face)
20148 'undone-face face 'done-face 'org-done)
20149 (push txt ee))))))
20150 (nreverse ee)))
20152 (defun org-agenda-deadline-face (fraction)
20153 "Return the face to displaying a deadline item.
20154 FRACTION is what fraction of the head-warning time has passed."
20155 (let ((faces org-agenda-deadline-faces) f)
20156 (catch 'exit
20157 (while (setq f (pop faces))
20158 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
20160 (defun org-agenda-get-scheduled ()
20161 "Return the scheduled information for agenda display."
20162 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
20163 'org-todo-regexp org-todo-regexp
20164 'done-face 'org-done
20165 'mouse-face 'highlight
20166 'keymap org-agenda-keymap
20167 'help-echo
20168 (format "mouse-2 or RET jump to org file %s"
20169 (abbreviate-file-name buffer-file-name))))
20170 (regexp org-scheduled-time-regexp)
20171 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
20172 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
20173 d2 diff pos pos1 category tags
20174 ee txt head pastschedp donep face timestr s)
20175 (goto-char (point-min))
20176 (while (re-search-forward regexp nil t)
20177 (catch :skip
20178 (org-agenda-skip)
20179 (setq s (match-string 1)
20180 pos (1- (match-beginning 1))
20181 d2 (org-time-string-to-absolute (match-string 1) d1)
20182 diff (- d2 d1))
20183 (setq pastschedp (and todayp (< diff 0)))
20184 ;; When to show a scheduled item in the calendar:
20185 ;; If it is on or past the date.
20186 (if (or (and (< diff 0)
20187 (and todayp (not org-agenda-only-exact-dates)))
20188 (= diff 0))
20189 (save-excursion
20190 (setq category (org-get-category))
20191 (if (re-search-backward "^\\*+[ \t]+" nil t)
20192 (progn
20193 (goto-char (match-end 0))
20194 (setq pos1 (match-beginning 0))
20195 (setq tags (org-get-tags-at))
20196 (setq head (buffer-substring-no-properties
20197 (point)
20198 (progn (skip-chars-forward "^\r\n") (point))))
20199 (setq donep (string-match org-looking-at-done-regexp head))
20200 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
20201 (setq timestr
20202 (concat (substring s (match-beginning 1)) " "))
20203 (setq timestr 'time))
20204 (if (and donep
20205 (or org-agenda-skip-scheduled-if-done
20206 (not (= diff 0))))
20207 (setq txt nil)
20208 (setq txt (org-format-agenda-item
20209 (if (= diff 0)
20210 (car org-agenda-scheduled-leaders)
20211 (format (nth 1 org-agenda-scheduled-leaders)
20212 (- 1 diff)))
20213 head category tags timestr))))
20214 (setq txt org-agenda-no-heading-message))
20215 (when txt
20216 (setq face (if pastschedp
20217 'org-scheduled-previously
20218 'org-scheduled-today))
20219 (org-add-props txt props
20220 'undone-face face
20221 'face (if donep 'org-done face)
20222 'org-marker (org-agenda-new-marker pos)
20223 'org-hd-marker (org-agenda-new-marker pos1)
20224 'type (if pastschedp "past-scheduled" "scheduled")
20225 'date (if pastschedp d2 date)
20226 'priority (+ 94 (- 5 diff) (org-get-priority txt))
20227 'org-category category)
20228 (push txt ee))))))
20229 (nreverse ee)))
20231 (defun org-agenda-get-blocks ()
20232 "Return the date-range information for agenda display."
20233 (let* ((props (list 'face nil
20234 'org-not-done-regexp org-not-done-regexp
20235 'org-todo-regexp org-todo-regexp
20236 'mouse-face 'highlight
20237 'keymap org-agenda-keymap
20238 'help-echo
20239 (format "mouse-2 or RET jump to org file %s"
20240 (abbreviate-file-name buffer-file-name))))
20241 (regexp org-tr-regexp)
20242 (d0 (calendar-absolute-from-gregorian date))
20243 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos)
20244 (goto-char (point-min))
20245 (while (re-search-forward regexp nil t)
20246 (catch :skip
20247 (org-agenda-skip)
20248 (setq pos (point))
20249 (setq timestr (match-string 0)
20250 s1 (match-string 1)
20251 s2 (match-string 2)
20252 d1 (time-to-days (org-time-string-to-time s1))
20253 d2 (time-to-days (org-time-string-to-time s2)))
20254 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
20255 ;; Only allow days between the limits, because the normal
20256 ;; date stamps will catch the limits.
20257 (save-excursion
20258 (setq marker (org-agenda-new-marker (point)))
20259 (setq category (org-get-category))
20260 (if (re-search-backward "^\\*+ " nil t)
20261 (progn
20262 (goto-char (match-beginning 0))
20263 (setq hdmarker (org-agenda-new-marker (point)))
20264 (setq tags (org-get-tags-at))
20265 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
20266 (setq txt (org-format-agenda-item
20267 (format (if (= d1 d2) "" "(%d/%d): ")
20268 (1+ (- d0 d1)) (1+ (- d2 d1)))
20269 (match-string 1) category tags
20270 (if (= d0 d1) timestr))))
20271 (setq txt org-agenda-no-heading-message))
20272 (org-add-props txt props
20273 'org-marker marker 'org-hd-marker hdmarker
20274 'type "block" 'date date
20275 'priority (org-get-priority txt) 'org-category category)
20276 (push txt ee)))
20277 (goto-char pos)))
20278 ;; Sort the entries by expiration date.
20279 (nreverse ee)))
20281 ;;; Agenda presentation and sorting
20283 (defconst org-plain-time-of-day-regexp
20284 (concat
20285 "\\(\\<[012]?[0-9]"
20286 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
20287 "\\(--?"
20288 "\\(\\<[012]?[0-9]"
20289 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
20290 "\\)?")
20291 "Regular expression to match a plain time or time range.
20292 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
20293 groups carry important information:
20294 0 the full match
20295 1 the first time, range or not
20296 8 the second time, if it is a range.")
20298 (defconst org-plain-time-extension-regexp
20299 (concat
20300 "\\(\\<[012]?[0-9]"
20301 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
20302 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
20303 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
20304 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
20305 groups carry important information:
20306 0 the full match
20307 7 hours of duration
20308 9 minutes of duration")
20310 (defconst org-stamp-time-of-day-regexp
20311 (concat
20312 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
20313 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
20314 "\\(--?"
20315 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
20316 "Regular expression to match a timestamp time or time range.
20317 After a match, the following groups carry important information:
20318 0 the full match
20319 1 date plus weekday, for backreferencing to make sure both times on same day
20320 2 the first time, range or not
20321 4 the second time, if it is a range.")
20323 (defvar org-prefix-has-time nil
20324 "A flag, set by `org-compile-prefix-format'.
20325 The flag is set if the currently compiled format contains a `%t'.")
20326 (defvar org-prefix-has-tag nil
20327 "A flag, set by `org-compile-prefix-format'.
20328 The flag is set if the currently compiled format contains a `%T'.")
20330 (defun org-format-agenda-item (extra txt &optional category tags dotime
20331 noprefix remove-re)
20332 "Format TXT to be inserted into the agenda buffer.
20333 In particular, it adds the prefix and corresponding text properties. EXTRA
20334 must be a string and replaces the `%s' specifier in the prefix format.
20335 CATEGORY (string, symbol or nil) may be used to overrule the default
20336 category taken from local variable or file name. It will replace the `%c'
20337 specifier in the format. DOTIME, when non-nil, indicates that a
20338 time-of-day should be extracted from TXT for sorting of this entry, and for
20339 the `%t' specifier in the format. When DOTIME is a string, this string is
20340 searched for a time before TXT is. NOPREFIX is a flag and indicates that
20341 only the correctly processes TXT should be returned - this is used by
20342 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
20343 Any match of REMOVE-RE will be removed from TXT."
20344 (save-match-data
20345 ;; Diary entries sometimes have extra whitespace at the beginning
20346 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
20347 (let* ((category (or category
20348 org-category
20349 (if buffer-file-name
20350 (file-name-sans-extension
20351 (file-name-nondirectory buffer-file-name))
20352 "")))
20353 (tag (if tags (nth (1- (length tags)) tags) ""))
20354 time ; time and tag are needed for the eval of the prefix format
20355 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
20356 (time-of-day (and dotime (org-get-time-of-day ts)))
20357 stamp plain s0 s1 s2 rtn srp)
20358 (when (and dotime time-of-day org-prefix-has-time)
20359 ;; Extract starting and ending time and move them to prefix
20360 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
20361 (setq plain (string-match org-plain-time-of-day-regexp ts)))
20362 (setq s0 (match-string 0 ts)
20363 srp (and stamp (match-end 3))
20364 s1 (match-string (if plain 1 2) ts)
20365 s2 (match-string (if plain 8 (if srp 4 6)) ts))
20367 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
20368 ;; them, we might want to remove them there to avoid duplication.
20369 ;; The user can turn this off with a variable.
20370 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
20371 (string-match (concat (regexp-quote s0) " *") txt)
20372 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
20373 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
20374 (= (match-beginning 0) 0)
20376 (setq txt (replace-match "" nil nil txt))))
20377 ;; Normalize the time(s) to 24 hour
20378 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
20379 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
20381 (when (and s1 (not s2) org-agenda-default-appointment-duration
20382 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
20383 (let ((m (+ (string-to-number (match-string 2 s1))
20384 (* 60 (string-to-number (match-string 1 s1)))
20385 org-agenda-default-appointment-duration))
20387 (setq h (/ m 60) m (- m (* h 60)))
20388 (setq s2 (format "%02d:%02d" h m))))
20390 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
20391 txt)
20392 ;; Tags are in the string
20393 (if (or (eq org-agenda-remove-tags t)
20394 (and org-agenda-remove-tags
20395 org-prefix-has-tag))
20396 (setq txt (replace-match "" t t txt))
20397 (setq txt (replace-match
20398 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
20399 (match-string 2 txt))
20400 t t txt))))
20402 (when remove-re
20403 (while (string-match remove-re txt)
20404 (setq txt (replace-match "" t t txt))))
20406 ;; Create the final string
20407 (if noprefix
20408 (setq rtn txt)
20409 ;; Prepare the variables needed in the eval of the compiled format
20410 (setq time (cond (s2 (concat s1 "-" s2))
20411 (s1 (concat s1 "......"))
20412 (t ""))
20413 extra (or extra "")
20414 category (if (symbolp category) (symbol-name category) category))
20415 ;; Evaluate the compiled format
20416 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
20418 ;; And finally add the text properties
20419 (org-add-props rtn nil
20420 'org-category (downcase category) 'tags tags
20421 'org-highest-priority org-highest-priority
20422 'org-lowest-priority org-lowest-priority
20423 'prefix-length (- (length rtn) (length txt))
20424 'time-of-day time-of-day
20425 'txt txt
20426 'time time
20427 'extra extra
20428 'dotime dotime))))
20430 (defvar org-agenda-sorting-strategy) ;; FIXME: can be removed?
20431 (defvar org-agenda-sorting-strategy-selected nil)
20433 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
20434 (catch 'exit
20435 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
20436 ((and todayp (member 'today (car org-agenda-time-grid))))
20437 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
20438 ((member 'weekly (car org-agenda-time-grid)))
20439 (t (throw 'exit list)))
20440 (let* ((have (delq nil (mapcar
20441 (lambda (x) (get-text-property 1 'time-of-day x))
20442 list)))
20443 (string (nth 1 org-agenda-time-grid))
20444 (gridtimes (nth 2 org-agenda-time-grid))
20445 (req (car org-agenda-time-grid))
20446 (remove (member 'remove-match req))
20447 new time)
20448 (if (and (member 'require-timed req) (not have))
20449 ;; don't show empty grid
20450 (throw 'exit list))
20451 (while (setq time (pop gridtimes))
20452 (unless (and remove (member time have))
20453 (setq time (int-to-string time))
20454 (push (org-format-agenda-item
20455 nil string "" nil
20456 (concat (substring time 0 -2) ":" (substring time -2)))
20457 new)
20458 (put-text-property
20459 1 (length (car new)) 'face 'org-time-grid (car new))))
20460 (if (member 'time-up org-agenda-sorting-strategy-selected)
20461 (append new list)
20462 (append list new)))))
20464 (defun org-compile-prefix-format (key)
20465 "Compile the prefix format into a Lisp form that can be evaluated.
20466 The resulting form is returned and stored in the variable
20467 `org-prefix-format-compiled'."
20468 (setq org-prefix-has-time nil org-prefix-has-tag nil)
20469 (let ((s (cond
20470 ((stringp org-agenda-prefix-format)
20471 org-agenda-prefix-format)
20472 ((assq key org-agenda-prefix-format)
20473 (cdr (assq key org-agenda-prefix-format)))
20474 (t " %-12:c%?-12t% s")))
20475 (start 0)
20476 varform vars var e c f opt)
20477 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
20478 s start)
20479 (setq var (cdr (assoc (match-string 4 s)
20480 '(("c" . category) ("t" . time) ("s" . extra)
20481 ("T" . tag))))
20482 c (or (match-string 3 s) "")
20483 opt (match-beginning 1)
20484 start (1+ (match-beginning 0)))
20485 (if (equal var 'time) (setq org-prefix-has-time t))
20486 (if (equal var 'tag) (setq org-prefix-has-tag t))
20487 (setq f (concat "%" (match-string 2 s) "s"))
20488 (if opt
20489 (setq varform
20490 `(if (equal "" ,var)
20492 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
20493 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
20494 (setq s (replace-match "%s" t nil s))
20495 (push varform vars))
20496 (setq vars (nreverse vars))
20497 (setq org-prefix-format-compiled `(format ,s ,@vars))))
20499 (defun org-set-sorting-strategy (key)
20500 (if (symbolp (car org-agenda-sorting-strategy))
20501 ;; the old format
20502 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
20503 (setq org-agenda-sorting-strategy-selected
20504 (or (cdr (assq key org-agenda-sorting-strategy))
20505 (cdr (assq 'agenda org-agenda-sorting-strategy))
20506 '(time-up category-keep priority-down)))))
20508 (defun org-get-time-of-day (s &optional string mod24)
20509 "Check string S for a time of day.
20510 If found, return it as a military time number between 0 and 2400.
20511 If not found, return nil.
20512 The optional STRING argument forces conversion into a 5 character wide string
20513 HH:MM."
20514 (save-match-data
20515 (when
20516 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
20517 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
20518 (let* ((h (string-to-number (match-string 1 s)))
20519 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
20520 (ampm (if (match-end 4) (downcase (match-string 4 s))))
20521 (am-p (equal ampm "am"))
20522 (h1 (cond ((not ampm) h)
20523 ((= h 12) (if am-p 0 12))
20524 (t (+ h (if am-p 0 12)))))
20525 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
20526 (mod h1 24) h1))
20527 (t0 (+ (* 100 h2) m))
20528 (t1 (concat (if (>= h1 24) "+" " ")
20529 (if (< t0 100) "0" "")
20530 (if (< t0 10) "0" "")
20531 (int-to-string t0))))
20532 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
20534 (defun org-finalize-agenda-entries (list &optional nosort)
20535 "Sort and concatenate the agenda items."
20536 (setq list (mapcar 'org-agenda-highlight-todo list))
20537 (if nosort
20538 list
20539 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
20541 (defun org-agenda-highlight-todo (x)
20542 (let (re pl)
20543 (if (eq x 'line)
20544 (save-excursion
20545 (beginning-of-line 1)
20546 (setq re (get-text-property (point) 'org-todo-regexp))
20547 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
20548 (and (looking-at (concat "[ \t]*\\.*" re))
20549 (add-text-properties (match-beginning 0) (match-end 0)
20550 (list 'face (org-get-todo-face 0)))))
20551 (setq re (concat (get-text-property 0 'org-todo-regexp x))
20552 pl (get-text-property 0 'prefix-length x))
20553 (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
20554 (add-text-properties
20555 (or (match-end 1) (match-end 0)) (match-end 0)
20556 (list 'face (org-get-todo-face (match-string 2 x)))
20558 x)))
20560 (defsubst org-cmp-priority (a b)
20561 "Compare the priorities of string A and B."
20562 (let ((pa (or (get-text-property 1 'priority a) 0))
20563 (pb (or (get-text-property 1 'priority b) 0)))
20564 (cond ((> pa pb) +1)
20565 ((< pa pb) -1)
20566 (t nil))))
20568 (defsubst org-cmp-category (a b)
20569 "Compare the string values of categories of strings A and B."
20570 (let ((ca (or (get-text-property 1 'org-category a) ""))
20571 (cb (or (get-text-property 1 'org-category b) "")))
20572 (cond ((string-lessp ca cb) -1)
20573 ((string-lessp cb ca) +1)
20574 (t nil))))
20576 (defsubst org-cmp-tag (a b)
20577 "Compare the string values of categories of strings A and B."
20578 (let ((ta (car (last (get-text-property 1 'tags a))))
20579 (tb (car (last (get-text-property 1 'tags b)))))
20580 (cond ((not ta) +1)
20581 ((not tb) -1)
20582 ((string-lessp ta tb) -1)
20583 ((string-lessp tb ta) +1)
20584 (t nil))))
20586 (defsubst org-cmp-time (a b)
20587 "Compare the time-of-day values of strings A and B."
20588 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
20589 (ta (or (get-text-property 1 'time-of-day a) def))
20590 (tb (or (get-text-property 1 'time-of-day b) def)))
20591 (cond ((< ta tb) -1)
20592 ((< tb ta) +1)
20593 (t nil))))
20595 (defun org-entries-lessp (a b)
20596 "Predicate for sorting agenda entries."
20597 ;; The following variables will be used when the form is evaluated.
20598 ;; So even though the compiler complains, keep them.
20599 (let* ((time-up (org-cmp-time a b))
20600 (time-down (if time-up (- time-up) nil))
20601 (priority-up (org-cmp-priority a b))
20602 (priority-down (if priority-up (- priority-up) nil))
20603 (category-up (org-cmp-category a b))
20604 (category-down (if category-up (- category-up) nil))
20605 (category-keep (if category-up +1 nil))
20606 (tag-up (org-cmp-tag a b))
20607 (tag-down (if tag-up (- tag-up) nil)))
20608 (cdr (assoc
20609 (eval (cons 'or org-agenda-sorting-strategy-selected))
20610 '((-1 . t) (1 . nil) (nil . nil))))))
20612 ;;; Agenda commands
20614 (defun org-agenda-check-type (error &rest types)
20615 "Check if agenda buffer is of allowed type.
20616 If ERROR is non-nil, throw an error, otherwise just return nil."
20617 (if (memq org-agenda-type types)
20619 (if error
20620 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
20621 nil)))
20623 (defun org-agenda-quit ()
20624 "Exit agenda by removing the window or the buffer."
20625 (interactive)
20626 (let ((buf (current-buffer)))
20627 (if (not (one-window-p)) (delete-window))
20628 (kill-buffer buf)
20629 (org-agenda-maybe-reset-markers 'force)
20630 (org-columns-remove-overlays))
20631 ;; Maybe restore the pre-agenda window configuration.
20632 (and org-agenda-restore-windows-after-quit
20633 (not (eq org-agenda-window-setup 'other-frame))
20634 org-pre-agenda-window-conf
20635 (set-window-configuration org-pre-agenda-window-conf)))
20637 (defun org-agenda-exit ()
20638 "Exit agenda by removing the window or the buffer.
20639 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
20640 Org-mode buffers visited directly by the user will not be touched."
20641 (interactive)
20642 (org-release-buffers org-agenda-new-buffers)
20643 (setq org-agenda-new-buffers nil)
20644 (org-agenda-quit))
20646 (defun org-save-all-org-buffers ()
20647 "Save all Org-mode buffers without user confirmation."
20648 (interactive)
20649 (message "Saving all Org-mode buffers...")
20650 (save-some-buffers t 'org-mode-p)
20651 (message "Saving all Org-mode buffers... done"))
20653 (defun org-agenda-redo ()
20654 "Rebuild Agenda.
20655 When this is the global TODO list, a prefix argument will be interpreted."
20656 (interactive)
20657 (let* ((org-agenda-keep-modes t)
20658 (line (org-current-line))
20659 (window-line (- line (org-current-line (window-start))))
20660 (lprops (get 'org-agenda-redo-command 'org-lprops)))
20661 (message "Rebuilding agenda buffer...")
20662 (org-let lprops '(eval org-agenda-redo-command))
20663 (setq org-agenda-undo-list nil
20664 org-agenda-pending-undo-list nil)
20665 (message "Rebuilding agenda buffer...done")
20666 (goto-line line)
20667 (recenter window-line)))
20669 (defun org-agenda-goto-date (date)
20670 "Jump to DATE in agenda."
20671 (interactive (list (org-read-date)))
20672 (org-agenda-list nil date))
20674 (defun org-agenda-goto-today ()
20675 "Go to today."
20676 (interactive)
20677 (org-agenda-check-type t 'timeline 'agenda)
20678 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
20679 (cond
20680 (tdpos (goto-char tdpos))
20681 ((eq org-agenda-type 'agenda)
20682 (let* ((sd (time-to-days (current-time)))
20683 (comp (org-agenda-compute-time-span sd org-agenda-span))
20684 (org-agenda-overriding-arguments org-agenda-last-arguments))
20685 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
20686 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
20687 (org-agenda-redo)
20688 (org-agenda-find-same-or-today-or-agenda)))
20689 (t (error "Cannot find today")))))
20691 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
20692 (goto-char
20693 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
20694 (text-property-any (point-min) (point-max) 'org-today t)
20695 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
20696 (point-min))))
20698 (defun org-agenda-later (arg)
20699 "Go forward in time by thee current span.
20700 With prefix ARG, go forward that many times the current span."
20701 (interactive "p")
20702 (org-agenda-check-type t 'agenda)
20703 (let* ((span org-agenda-span)
20704 (sd org-starting-day)
20705 (greg (calendar-gregorian-from-absolute sd))
20706 (cnt (get-text-property (point) 'org-day-cnt))
20707 greg2 nd)
20708 (cond
20709 ((eq span 'day)
20710 (setq sd (+ arg sd) nd 1))
20711 ((eq span 'week)
20712 (setq sd (+ (* 7 arg) sd) nd 7))
20713 ((eq span 'month)
20714 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
20715 sd (calendar-absolute-from-gregorian greg2))
20716 (setcar greg2 (1+ (car greg2)))
20717 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
20718 ((eq span 'year)
20719 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
20720 sd (calendar-absolute-from-gregorian greg2))
20721 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
20722 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
20723 (let ((org-agenda-overriding-arguments
20724 (list (car org-agenda-last-arguments) sd nd t)))
20725 (org-agenda-redo)
20726 (org-agenda-find-same-or-today-or-agenda cnt))))
20728 (defun org-agenda-earlier (arg)
20729 "Go backward in time by the current span.
20730 With prefix ARG, go backward that many times the current span."
20731 (interactive "p")
20732 (org-agenda-later (- arg)))
20734 (defun org-agenda-day-view ()
20735 "Switch to daily view for agenda."
20736 (interactive)
20737 (setq org-agenda-ndays 1)
20738 (org-agenda-change-time-span 'day))
20739 (defun org-agenda-week-view ()
20740 "Switch to daily view for agenda."
20741 (interactive)
20742 (setq org-agenda-ndays 7)
20743 (org-agenda-change-time-span 'week))
20744 (defun org-agenda-month-view ()
20745 "Switch to daily view for agenda."
20746 (interactive)
20747 (org-agenda-change-time-span 'month))
20748 (defun org-agenda-year-view ()
20749 "Switch to daily view for agenda."
20750 (interactive)
20751 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
20752 (org-agenda-change-time-span 'year)
20753 (error "Abort")))
20755 (defun org-agenda-change-time-span (span)
20756 "Change the agenda view to SPAN.
20757 SPAN may be `day', `week', `month', `year'."
20758 (org-agenda-check-type t 'agenda)
20759 (if (equal org-agenda-span span)
20760 (error "Viewing span is already \"%s\"" span))
20761 (let* ((sd (or (get-text-property (point) 'day)
20762 org-starting-day))
20763 (computed (org-agenda-compute-time-span sd span))
20764 (org-agenda-overriding-arguments
20765 (list (car org-agenda-last-arguments)
20766 (car computed) (cdr computed) t)))
20767 (org-agenda-redo)
20768 (org-agenda-find-same-or-today-or-agenda))
20769 (org-agenda-set-mode-name)
20770 (message "Switched to %s view" span))
20772 (defun org-agenda-compute-time-span (sd span)
20773 "Compute starting date and number of days for agenda.
20774 SPAN may be `day', `week', `month', `year'. The return value
20775 is a cons cell with the starting date and the number of days,
20776 so that the date SD will be in that range."
20777 (let* ((greg (calendar-gregorian-from-absolute sd))
20779 (cond
20780 ((eq span 'day)
20781 (setq nd 1))
20782 ((eq span 'week)
20783 (let* ((nt (calendar-day-of-week
20784 (calendar-gregorian-from-absolute sd)))
20785 (d (if org-agenda-start-on-weekday
20786 (- nt org-agenda-start-on-weekday)
20787 0)))
20788 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
20789 (setq nd 7)))
20790 ((eq span 'month)
20791 (setq sd (calendar-absolute-from-gregorian
20792 (list (car greg) 1 (nth 2 greg)))
20793 nd (- (calendar-absolute-from-gregorian
20794 (list (1+ (car greg)) 1 (nth 2 greg)))
20795 sd)))
20796 ((eq span 'year)
20797 (setq sd (calendar-absolute-from-gregorian
20798 (list 1 1 (nth 2 greg)))
20799 nd (- (calendar-absolute-from-gregorian
20800 (list 1 1 (1+ (nth 2 greg))))
20801 sd))))
20802 (cons sd nd)))
20804 ;; FIXME: does not work if user makes date format that starts with a blank
20805 (defun org-agenda-next-date-line (&optional arg)
20806 "Jump to the next line indicating a date in agenda buffer."
20807 (interactive "p")
20808 (org-agenda-check-type t 'agenda 'timeline)
20809 (beginning-of-line 1)
20810 (if (looking-at "^\\S-") (forward-char 1))
20811 (if (not (re-search-forward "^\\S-" nil t arg))
20812 (progn
20813 (backward-char 1)
20814 (error "No next date after this line in this buffer")))
20815 (goto-char (match-beginning 0)))
20817 (defun org-agenda-previous-date-line (&optional arg)
20818 "Jump to the previous line indicating a date in agenda buffer."
20819 (interactive "p")
20820 (org-agenda-check-type t 'agenda 'timeline)
20821 (beginning-of-line 1)
20822 (if (not (re-search-backward "^\\S-" nil t arg))
20823 (error "No previous date before this line in this buffer")))
20825 ;; Initialize the highlight
20826 (defvar org-hl (org-make-overlay 1 1))
20827 (org-overlay-put org-hl 'face 'highlight)
20829 (defun org-highlight (begin end &optional buffer)
20830 "Highlight a region with overlay."
20831 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
20832 org-hl begin end (or buffer (current-buffer))))
20834 (defun org-unhighlight ()
20835 "Detach overlay INDEX."
20836 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
20838 ;; FIXME this is currently not used.
20839 (defun org-highlight-until-next-command (beg end &optional buffer)
20840 (org-highlight beg end buffer)
20841 (add-hook 'pre-command-hook 'org-unhighlight-once))
20842 (defun org-unhighlight-once ()
20843 (remove-hook 'pre-command-hook 'org-unhighlight-once)
20844 (org-unhighlight))
20846 (defun org-agenda-follow-mode ()
20847 "Toggle follow mode in an agenda buffer."
20848 (interactive)
20849 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
20850 (org-agenda-set-mode-name)
20851 (message "Follow mode is %s"
20852 (if org-agenda-follow-mode "on" "off")))
20854 (defun org-agenda-log-mode ()
20855 "Toggle log mode in an agenda buffer."
20856 (interactive)
20857 (org-agenda-check-type t 'agenda 'timeline)
20858 (setq org-agenda-show-log (not org-agenda-show-log))
20859 (org-agenda-set-mode-name)
20860 (org-agenda-redo)
20861 (message "Log mode is %s"
20862 (if org-agenda-show-log "on" "off")))
20864 (defun org-agenda-toggle-diary ()
20865 "Toggle diary inclusion in an agenda buffer."
20866 (interactive)
20867 (org-agenda-check-type t 'agenda)
20868 (setq org-agenda-include-diary (not org-agenda-include-diary))
20869 (org-agenda-redo)
20870 (org-agenda-set-mode-name)
20871 (message "Diary inclusion turned %s"
20872 (if org-agenda-include-diary "on" "off")))
20874 (defun org-agenda-toggle-time-grid ()
20875 "Toggle time grid in an agenda buffer."
20876 (interactive)
20877 (org-agenda-check-type t 'agenda)
20878 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
20879 (org-agenda-redo)
20880 (org-agenda-set-mode-name)
20881 (message "Time-grid turned %s"
20882 (if org-agenda-use-time-grid "on" "off")))
20884 (defun org-agenda-set-mode-name ()
20885 "Set the mode name to indicate all the small mode settings."
20886 (setq mode-name
20887 (concat "Org-Agenda"
20888 (if (equal org-agenda-ndays 1) " Day" "")
20889 (if (equal org-agenda-ndays 7) " Week" "")
20890 (if org-agenda-follow-mode " Follow" "")
20891 (if org-agenda-include-diary " Diary" "")
20892 (if org-agenda-use-time-grid " Grid" "")
20893 (if org-agenda-show-log " Log" "")))
20894 (force-mode-line-update))
20896 (defun org-agenda-post-command-hook ()
20897 (and (eolp) (not (bolp)) (backward-char 1))
20898 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20899 (if (and org-agenda-follow-mode
20900 (get-text-property (point) 'org-marker))
20901 (org-agenda-show)))
20903 (defun org-agenda-show-priority ()
20904 "Show the priority of the current item.
20905 This priority is composed of the main priority given with the [#A] cookies,
20906 and by additional input from the age of a schedules or deadline entry."
20907 (interactive)
20908 (let* ((pri (get-text-property (point-at-bol) 'priority)))
20909 (message "Priority is %d" (if pri pri -1000))))
20911 (defun org-agenda-show-tags ()
20912 "Show the tags applicable to the current item."
20913 (interactive)
20914 (let* ((tags (get-text-property (point-at-bol) 'tags)))
20915 (if tags
20916 (message "Tags are :%s:"
20917 (org-no-properties (mapconcat 'identity tags ":")))
20918 (message "No tags associated with this line"))))
20920 (defun org-agenda-goto (&optional highlight)
20921 "Go to the Org-mode file which contains the item at point."
20922 (interactive)
20923 (let* ((marker (or (get-text-property (point) 'org-marker)
20924 (org-agenda-error)))
20925 (buffer (marker-buffer marker))
20926 (pos (marker-position marker)))
20927 (switch-to-buffer-other-window buffer)
20928 (widen)
20929 (goto-char pos)
20930 (when (org-mode-p)
20931 (org-show-context 'agenda)
20932 (save-excursion
20933 (and (outline-next-heading)
20934 (org-flag-heading nil)))) ; show the next heading
20935 (run-hooks 'org-agenda-after-show-hook)
20936 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
20938 (defvar org-agenda-after-show-hook nil
20939 "Normal hook run after an item has been shown from the agenda.
20940 Point is in the buffer where the item originated.")
20942 (defun org-agenda-kill ()
20943 "Kill the entry or subtree belonging to the current agenda entry."
20944 (interactive)
20945 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
20946 (let* ((marker (or (get-text-property (point) 'org-marker)
20947 (org-agenda-error)))
20948 (buffer (marker-buffer marker))
20949 (pos (marker-position marker))
20950 (type (get-text-property (point) 'type))
20951 dbeg dend (n 0) conf)
20952 (org-with-remote-undo buffer
20953 (with-current-buffer buffer
20954 (save-excursion
20955 (goto-char pos)
20956 (if (and (org-mode-p) (not (member type '("sexp"))))
20957 (setq dbeg (progn (org-back-to-heading t) (point))
20958 dend (org-end-of-subtree t t))
20959 (setq dbeg (point-at-bol)
20960 dend (min (point-max) (1+ (point-at-eol)))))
20961 (goto-char dbeg)
20962 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
20963 (setq conf (or (eq t org-agenda-confirm-kill)
20964 (and (numberp org-agenda-confirm-kill)
20965 (> n org-agenda-confirm-kill))))
20966 (and conf
20967 (not (y-or-n-p
20968 (format "Delete entry with %d lines in buffer \"%s\"? "
20969 n (buffer-name buffer))))
20970 (error "Abort"))
20971 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
20972 (with-current-buffer buffer (delete-region dbeg dend))
20973 (message "Agenda item and source killed"))))
20975 (defun org-agenda-archive ()
20976 "Kill the entry or subtree belonging to the current agenda entry."
20977 (interactive)
20978 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
20979 (let* ((marker (or (get-text-property (point) 'org-marker)
20980 (org-agenda-error)))
20981 (buffer (marker-buffer marker))
20982 (pos (marker-position marker)))
20983 (org-with-remote-undo buffer
20984 (with-current-buffer buffer
20985 (if (org-mode-p)
20986 (save-excursion
20987 (goto-char pos)
20988 (org-remove-subtree-entries-from-agenda)
20989 (org-back-to-heading t)
20990 (org-archive-subtree))
20991 (error "Archiving works only in Org-mode files"))))))
20993 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
20994 "Remove all lines in the agenda that correspond to a given subtree.
20995 The subtree is the one in buffer BUF, starting at BEG and ending at END.
20996 If this information is not given, the function uses the tree at point."
20997 (let ((buf (or buf (current-buffer))) m p)
20998 (save-excursion
20999 (unless (and beg end)
21000 (org-back-to-heading t)
21001 (setq beg (point))
21002 (org-end-of-subtree t)
21003 (setq end (point)))
21004 (set-buffer (get-buffer org-agenda-buffer-name))
21005 (save-excursion
21006 (goto-char (point-max))
21007 (beginning-of-line 1)
21008 (while (not (bobp))
21009 (when (and (setq m (get-text-property (point) 'org-marker))
21010 (equal buf (marker-buffer m))
21011 (setq p (marker-position m))
21012 (>= p beg)
21013 (<= p end))
21014 (let ((inhibit-read-only t))
21015 (delete-region (point-at-bol) (1+ (point-at-eol)))))
21016 (beginning-of-line 0))))))
21018 (defun org-agenda-open-link ()
21019 "Follow the link in the current line, if any."
21020 (interactive)
21021 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
21022 (save-excursion
21023 (save-restriction
21024 (narrow-to-region (point-at-bol) (point-at-eol))
21025 (org-open-at-point))))
21027 (defun org-agenda-copy-local-variable (var)
21028 "Get a variable from a referenced buffer and install it here."
21029 (let ((m (get-text-property (point) 'org-marker)))
21030 (when (and m (buffer-live-p (marker-buffer m)))
21031 (org-set-local var (with-current-buffer (marker-buffer m)
21032 (symbol-value var))))))
21034 (defun org-agenda-switch-to (&optional delete-other-windows)
21035 "Go to the Org-mode file which contains the item at point."
21036 (interactive)
21037 (let* ((marker (or (get-text-property (point) 'org-marker)
21038 (org-agenda-error)))
21039 (buffer (marker-buffer marker))
21040 (pos (marker-position marker)))
21041 (switch-to-buffer buffer)
21042 (and delete-other-windows (delete-other-windows))
21043 (widen)
21044 (goto-char pos)
21045 (when (org-mode-p)
21046 (org-show-context 'agenda)
21047 (save-excursion
21048 (and (outline-next-heading)
21049 (org-flag-heading nil)))))) ; show the next heading
21051 (defun org-agenda-goto-mouse (ev)
21052 "Go to the Org-mode file which contains the item at the mouse click."
21053 (interactive "e")
21054 (mouse-set-point ev)
21055 (org-agenda-goto))
21057 (defun org-agenda-show ()
21058 "Display the Org-mode file which contains the item at point."
21059 (interactive)
21060 (let ((win (selected-window)))
21061 (org-agenda-goto t)
21062 (select-window win)))
21064 (defun org-agenda-recenter (arg)
21065 "Display the Org-mode file which contains the item at point and recenter."
21066 (interactive "P")
21067 (let ((win (selected-window)))
21068 (org-agenda-goto t)
21069 (recenter arg)
21070 (select-window win)))
21072 (defun org-agenda-show-mouse (ev)
21073 "Display the Org-mode file which contains the item at the mouse click."
21074 (interactive "e")
21075 (mouse-set-point ev)
21076 (org-agenda-show))
21078 (defun org-agenda-check-no-diary ()
21079 "Check if the entry is a diary link and abort if yes."
21080 (if (get-text-property (point) 'org-agenda-diary-link)
21081 (org-agenda-error)))
21083 (defun org-agenda-error ()
21084 (error "Command not allowed in this line"))
21086 (defun org-agenda-tree-to-indirect-buffer ()
21087 "Show the subtree corresponding to the current entry in an indirect buffer.
21088 This calls the command `org-tree-to-indirect-buffer' from the original
21089 Org-mode buffer.
21090 With numerical prefix arg ARG, go up to this level and then take that tree.
21091 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
21092 dedicated frame)."
21093 (interactive)
21094 (org-agenda-check-no-diary)
21095 (let* ((marker (or (get-text-property (point) 'org-marker)
21096 (org-agenda-error)))
21097 (buffer (marker-buffer marker))
21098 (pos (marker-position marker)))
21099 (with-current-buffer buffer
21100 (save-excursion
21101 (goto-char pos)
21102 (call-interactively 'org-tree-to-indirect-buffer)))))
21104 (defvar org-last-heading-marker (make-marker)
21105 "Marker pointing to the headline that last changed its TODO state
21106 by a remote command from the agenda.")
21108 (defun org-agenda-todo-nextset ()
21109 "Switch TODO entry to next sequence."
21110 (interactive)
21111 (org-agenda-todo 'nextset))
21113 (defun org-agenda-todo-previousset ()
21114 "Switch TODO entry to previous sequence."
21115 (interactive)
21116 (org-agenda-todo 'previousset))
21118 (defun org-agenda-todo (&optional arg)
21119 "Cycle TODO state of line at point, also in Org-mode file.
21120 This changes the line at point, all other lines in the agenda referring to
21121 the same tree node, and the headline of the tree node in the Org-mode file."
21122 (interactive "P")
21123 (org-agenda-check-no-diary)
21124 (let* ((col (current-column))
21125 (marker (or (get-text-property (point) 'org-marker)
21126 (org-agenda-error)))
21127 (buffer (marker-buffer marker))
21128 (pos (marker-position marker))
21129 (hdmarker (get-text-property (point) 'org-hd-marker))
21130 (inhibit-read-only t)
21131 newhead)
21132 (org-with-remote-undo buffer
21133 (with-current-buffer buffer
21134 (widen)
21135 (goto-char pos)
21136 (org-show-context 'agenda)
21137 (save-excursion
21138 (and (outline-next-heading)
21139 (org-flag-heading nil))) ; show the next heading
21140 (org-todo arg)
21141 (and (bolp) (forward-char 1))
21142 (setq newhead (org-get-heading))
21143 (save-excursion
21144 (org-back-to-heading)
21145 (move-marker org-last-heading-marker (point))))
21146 (beginning-of-line 1)
21147 (save-excursion
21148 (org-agenda-change-all-lines newhead hdmarker 'fixface))
21149 (move-to-column col))))
21151 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
21152 "Change all lines in the agenda buffer which match HDMARKER.
21153 The new content of the line will be NEWHEAD (as modified by
21154 `org-format-agenda-item'). HDMARKER is checked with
21155 `equal' against all `org-hd-marker' text properties in the file.
21156 If FIXFACE is non-nil, the face of each item is modified acording to
21157 the new TODO state."
21158 (let* ((inhibit-read-only t)
21159 props m pl undone-face done-face finish new dotime cat tags)
21160 (save-excursion
21161 (goto-char (point-max))
21162 (beginning-of-line 1)
21163 (while (not finish)
21164 (setq finish (bobp))
21165 (when (and (setq m (get-text-property (point) 'org-hd-marker))
21166 (equal m hdmarker))
21167 (setq props (text-properties-at (point))
21168 dotime (get-text-property (point) 'dotime)
21169 cat (get-text-property (point) 'org-category)
21170 tags (get-text-property (point) 'tags)
21171 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
21172 pl (get-text-property (point) 'prefix-length)
21173 undone-face (get-text-property (point) 'undone-face)
21174 done-face (get-text-property (point) 'done-face))
21175 (move-to-column pl)
21176 (cond
21177 ((equal new "")
21178 (beginning-of-line 1)
21179 (and (looking-at ".*\n?") (replace-match "")))
21180 ((looking-at ".*")
21181 (replace-match new t t)
21182 (beginning-of-line 1)
21183 (add-text-properties (point-at-bol) (point-at-eol) props)
21184 (when fixface
21185 (add-text-properties
21186 (point-at-bol) (point-at-eol)
21187 (list 'face
21188 (if org-last-todo-state-is-todo
21189 undone-face done-face))))
21190 (org-agenda-highlight-todo 'line)
21191 (beginning-of-line 1))
21192 (t (error "Line update did not work"))))
21193 (beginning-of-line 0)))
21194 (org-finalize-agenda)))
21196 (defun org-agenda-align-tags (&optional line)
21197 "Align all tags in agenda items to `org-agenda-tags-column'."
21198 (let ((inhibit-read-only t) l c)
21199 (save-excursion
21200 (goto-char (if line (point-at-bol) (point-min)))
21201 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
21202 (if line (point-at-eol) nil) t)
21203 (add-text-properties
21204 (match-beginning 2) (match-end 2)
21205 (list 'face (list 'org-tag (get-text-property
21206 (match-beginning 2) 'face))))
21207 (setq l (- (match-end 2) (match-beginning 2))
21208 c (if (< org-agenda-tags-column 0)
21209 (- (abs org-agenda-tags-column) l)
21210 org-agenda-tags-column))
21211 (delete-region (match-beginning 1) (match-end 1))
21212 (goto-char (match-beginning 1))
21213 (insert (org-add-props
21214 (make-string (max 1 (- c (current-column))) ?\ )
21215 (text-properties-at (point))))))))
21217 (defun org-agenda-priority-up ()
21218 "Increase the priority of line at point, also in Org-mode file."
21219 (interactive)
21220 (org-agenda-priority 'up))
21222 (defun org-agenda-priority-down ()
21223 "Decrease the priority of line at point, also in Org-mode file."
21224 (interactive)
21225 (org-agenda-priority 'down))
21227 (defun org-agenda-priority (&optional force-direction)
21228 "Set the priority of line at point, also in Org-mode file.
21229 This changes the line at point, all other lines in the agenda referring to
21230 the same tree node, and the headline of the tree node in the Org-mode file."
21231 (interactive)
21232 (org-agenda-check-no-diary)
21233 (let* ((marker (or (get-text-property (point) 'org-marker)
21234 (org-agenda-error)))
21235 (hdmarker (get-text-property (point) 'org-hd-marker))
21236 (buffer (marker-buffer hdmarker))
21237 (pos (marker-position hdmarker))
21238 (inhibit-read-only t)
21239 newhead)
21240 (org-with-remote-undo buffer
21241 (with-current-buffer buffer
21242 (widen)
21243 (goto-char pos)
21244 (org-show-context 'agenda)
21245 (save-excursion
21246 (and (outline-next-heading)
21247 (org-flag-heading nil))) ; show the next heading
21248 (funcall 'org-priority force-direction)
21249 (end-of-line 1)
21250 (setq newhead (org-get-heading)))
21251 (org-agenda-change-all-lines newhead hdmarker)
21252 (beginning-of-line 1))))
21254 (defun org-get-tags-at (&optional pos)
21255 "Get a list of all headline tags applicable at POS.
21256 POS defaults to point. If tags are inherited, the list contains
21257 the targets in the same sequence as the headlines appear, i.e.
21258 the tags of the current headline come last."
21259 (interactive)
21260 (let (tags lastpos)
21261 (save-excursion
21262 (save-restriction
21263 (widen)
21264 (goto-char (or pos (point)))
21265 (save-match-data
21266 (org-back-to-heading t)
21267 (condition-case nil
21268 (while (not (equal lastpos (point)))
21269 (setq lastpos (point))
21270 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
21271 (setq tags (append (org-split-string
21272 (org-match-string-no-properties 1) ":")
21273 tags)))
21274 (or org-use-tag-inheritance (error ""))
21275 (org-up-heading-all 1))
21276 (error nil))))
21277 tags)))
21279 ;; FIXME: should fix the tags property of the agenda line.
21280 (defun org-agenda-set-tags ()
21281 "Set tags for the current headline."
21282 (interactive)
21283 (org-agenda-check-no-diary)
21284 (if (and (org-region-active-p) (interactive-p))
21285 (call-interactively 'org-change-tag-in-region)
21286 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
21287 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
21288 (org-agenda-error)))
21289 (buffer (marker-buffer hdmarker))
21290 (pos (marker-position hdmarker))
21291 (inhibit-read-only t)
21292 newhead)
21293 (org-with-remote-undo buffer
21294 (with-current-buffer buffer
21295 (widen)
21296 (goto-char pos)
21297 (save-excursion
21298 (org-show-context 'agenda))
21299 (save-excursion
21300 (and (outline-next-heading)
21301 (org-flag-heading nil))) ; show the next heading
21302 (goto-char pos)
21303 (call-interactively 'org-set-tags)
21304 (end-of-line 1)
21305 (setq newhead (org-get-heading)))
21306 (org-agenda-change-all-lines newhead hdmarker)
21307 (beginning-of-line 1)))))
21309 (defun org-agenda-toggle-archive-tag ()
21310 "Toggle the archive tag for the current entry."
21311 (interactive)
21312 (org-agenda-check-no-diary)
21313 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
21314 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
21315 (org-agenda-error)))
21316 (buffer (marker-buffer hdmarker))
21317 (pos (marker-position hdmarker))
21318 (inhibit-read-only t)
21319 newhead)
21320 (org-with-remote-undo buffer
21321 (with-current-buffer buffer
21322 (widen)
21323 (goto-char pos)
21324 (org-show-context 'agenda)
21325 (save-excursion
21326 (and (outline-next-heading)
21327 (org-flag-heading nil))) ; show the next heading
21328 (call-interactively 'org-toggle-archive-tag)
21329 (end-of-line 1)
21330 (setq newhead (org-get-heading)))
21331 (org-agenda-change-all-lines newhead hdmarker)
21332 (beginning-of-line 1))))
21334 (defun org-agenda-date-later (arg &optional what)
21335 "Change the date of this item to one day later."
21336 (interactive "p")
21337 (org-agenda-check-type t 'agenda 'timeline)
21338 (org-agenda-check-no-diary)
21339 (let* ((marker (or (get-text-property (point) 'org-marker)
21340 (org-agenda-error)))
21341 (buffer (marker-buffer marker))
21342 (pos (marker-position marker)))
21343 (org-with-remote-undo buffer
21344 (with-current-buffer buffer
21345 (widen)
21346 (goto-char pos)
21347 (if (not (org-at-timestamp-p))
21348 (error "Cannot find time stamp"))
21349 (org-timestamp-change arg (or what 'day)))
21350 (org-agenda-show-new-time marker org-last-changed-timestamp))
21351 (message "Time stamp changed to %s" org-last-changed-timestamp)))
21353 (defun org-agenda-date-earlier (arg &optional what)
21354 "Change the date of this item to one day earlier."
21355 (interactive "p")
21356 (org-agenda-date-later (- arg) what))
21358 (defun org-agenda-show-new-time (marker stamp &optional prefix)
21359 "Show new date stamp via text properties."
21360 ;; We use text properties to make this undoable
21361 (let ((inhibit-read-only t))
21362 (setq stamp (concat " " prefix " => " stamp))
21363 (save-excursion
21364 (goto-char (point-max))
21365 (while (not (bobp))
21366 (when (equal marker (get-text-property (point) 'org-marker))
21367 (move-to-column (- (window-width) (length stamp)) t)
21368 (if (featurep 'xemacs)
21369 ;; Use `duplicable' property to trigger undo recording
21370 (let ((ex (make-extent nil nil))
21371 (gl (make-glyph stamp)))
21372 (set-glyph-face gl 'secondary-selection)
21373 (set-extent-properties
21374 ex (list 'invisible t 'end-glyph gl 'duplicable t))
21375 (insert-extent ex (1- (point)) (point-at-eol)))
21376 (add-text-properties
21377 (1- (point)) (point-at-eol)
21378 (list 'display (org-add-props stamp nil
21379 'face 'secondary-selection))))
21380 (beginning-of-line 1))
21381 (beginning-of-line 0)))))
21383 (defun org-agenda-date-prompt (arg)
21384 "Change the date of this item. Date is prompted for, with default today.
21385 The prefix ARG is passed to the `org-time-stamp' command and can therefore
21386 be used to request time specification in the time stamp."
21387 (interactive "P")
21388 (org-agenda-check-type t 'agenda 'timeline)
21389 (org-agenda-check-no-diary)
21390 (let* ((marker (or (get-text-property (point) 'org-marker)
21391 (org-agenda-error)))
21392 (buffer (marker-buffer marker))
21393 (pos (marker-position marker)))
21394 (org-with-remote-undo buffer
21395 (with-current-buffer buffer
21396 (widen)
21397 (goto-char pos)
21398 (if (not (org-at-timestamp-p))
21399 (error "Cannot find time stamp"))
21400 (org-time-stamp arg)
21401 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
21403 (defun org-agenda-schedule (arg)
21404 "Schedule the item at point."
21405 (interactive "P")
21406 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
21407 (org-agenda-check-no-diary)
21408 (let* ((marker (or (get-text-property (point) 'org-marker)
21409 (org-agenda-error)))
21410 (buffer (marker-buffer marker))
21411 (pos (marker-position marker))
21412 (org-insert-labeled-timestamps-at-point nil)
21414 (org-with-remote-undo buffer
21415 (with-current-buffer buffer
21416 (widen)
21417 (goto-char pos)
21418 (setq ts (org-schedule arg)))
21419 (org-agenda-show-new-time marker ts "S"))
21420 (message "Item scheduled for %s" ts)))
21422 (defun org-agenda-deadline (arg)
21423 "Schedule the item at point."
21424 (interactive "P")
21425 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
21426 (org-agenda-check-no-diary)
21427 (let* ((marker (or (get-text-property (point) 'org-marker)
21428 (org-agenda-error)))
21429 (buffer (marker-buffer marker))
21430 (pos (marker-position marker))
21431 (org-insert-labeled-timestamps-at-point nil)
21433 (org-with-remote-undo buffer
21434 (with-current-buffer buffer
21435 (widen)
21436 (goto-char pos)
21437 (setq ts (org-deadline arg)))
21438 (org-agenda-show-new-time marker ts "S"))
21439 (message "Deadline for this item set to %s" ts)))
21441 (defun org-get-heading (&optional no-tags)
21442 "Return the heading of the current entry, without the stars."
21443 (save-excursion
21444 (org-back-to-heading t)
21445 (if (looking-at
21446 (if no-tags
21447 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
21448 "\\*+[ \t]+\\([^\r\n]*\\)"))
21449 (match-string 1) "")))
21451 (defun org-agenda-clock-in (&optional arg)
21452 "Start the clock on the currently selected item."
21453 (interactive "P")
21454 (org-agenda-check-no-diary)
21455 (let* ((marker (or (get-text-property (point) 'org-marker)
21456 (org-agenda-error)))
21457 (pos (marker-position marker)))
21458 (org-with-remote-undo (marker-buffer marker)
21459 (with-current-buffer (marker-buffer marker)
21460 (widen)
21461 (goto-char pos)
21462 (org-clock-in)))))
21464 (defun org-agenda-clock-out (&optional arg)
21465 "Stop the currently running clock."
21466 (interactive "P")
21467 (unless (marker-buffer org-clock-marker)
21468 (error "No running clock"))
21469 (org-with-remote-undo (marker-buffer org-clock-marker)
21470 (org-clock-out)))
21472 (defun org-agenda-clock-cancel (&optional arg)
21473 "Cancel the currently running clock."
21474 (interactive "P")
21475 (unless (marker-buffer org-clock-marker)
21476 (error "No running clock"))
21477 (org-with-remote-undo (marker-buffer org-clock-marker)
21478 (org-clock-cancel)))
21480 (defun org-agenda-diary-entry ()
21481 "Make a diary entry, like the `i' command from the calendar.
21482 All the standard commands work: block, weekly etc."
21483 (interactive)
21484 (org-agenda-check-type t 'agenda 'timeline)
21485 (require 'diary-lib)
21486 (let* ((char (progn
21487 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
21488 (read-char-exclusive)))
21489 (cmd (cdr (assoc char
21490 '((?d . insert-diary-entry)
21491 (?w . insert-weekly-diary-entry)
21492 (?m . insert-monthly-diary-entry)
21493 (?y . insert-yearly-diary-entry)
21494 (?a . insert-anniversary-diary-entry)
21495 (?b . insert-block-diary-entry)
21496 (?c . insert-cyclic-diary-entry)))))
21497 (oldf (symbol-function 'calendar-cursor-to-date))
21498 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
21499 (point (point))
21500 (mark (or (mark t) (point))))
21501 (unless cmd
21502 (error "No command associated with <%c>" char))
21503 (unless (and (get-text-property point 'day)
21504 (or (not (equal ?b char))
21505 (get-text-property mark 'day)))
21506 (error "Don't know which date to use for diary entry"))
21507 ;; We implement this by hacking the `calendar-cursor-to-date' function
21508 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
21509 (let ((calendar-mark-ring
21510 (list (calendar-gregorian-from-absolute
21511 (or (get-text-property mark 'day)
21512 (get-text-property point 'day))))))
21513 (unwind-protect
21514 (progn
21515 (fset 'calendar-cursor-to-date
21516 (lambda (&optional error)
21517 (calendar-gregorian-from-absolute
21518 (get-text-property point 'day))))
21519 (call-interactively cmd))
21520 (fset 'calendar-cursor-to-date oldf)))))
21523 (defun org-agenda-execute-calendar-command (cmd)
21524 "Execute a calendar command from the agenda, with the date associated to
21525 the cursor position."
21526 (org-agenda-check-type t 'agenda 'timeline)
21527 (require 'diary-lib)
21528 (unless (get-text-property (point) 'day)
21529 (error "Don't know which date to use for calendar command"))
21530 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
21531 (point (point))
21532 (date (calendar-gregorian-from-absolute
21533 (get-text-property point 'day)))
21534 ;; the following 3 vars are needed in the calendar
21535 (displayed-day (extract-calendar-day date))
21536 (displayed-month (extract-calendar-month date))
21537 (displayed-year (extract-calendar-year date)))
21538 (unwind-protect
21539 (progn
21540 (fset 'calendar-cursor-to-date
21541 (lambda (&optional error)
21542 (calendar-gregorian-from-absolute
21543 (get-text-property point 'day))))
21544 (call-interactively cmd))
21545 (fset 'calendar-cursor-to-date oldf))))
21547 (defun org-agenda-phases-of-moon ()
21548 "Display the phases of the moon for the 3 months around the cursor date."
21549 (interactive)
21550 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
21552 (defun org-agenda-holidays ()
21553 "Display the holidays for the 3 months around the cursor date."
21554 (interactive)
21555 (org-agenda-execute-calendar-command 'list-calendar-holidays))
21557 (defun org-agenda-sunrise-sunset (arg)
21558 "Display sunrise and sunset for the cursor date.
21559 Latitude and longitude can be specified with the variables
21560 `calendar-latitude' and `calendar-longitude'. When called with prefix
21561 argument, latitude and longitude will be prompted for."
21562 (interactive "P")
21563 (let ((calendar-longitude (if arg nil calendar-longitude))
21564 (calendar-latitude (if arg nil calendar-latitude))
21565 (calendar-location-name
21566 (if arg "the given coordinates" calendar-location-name)))
21567 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
21569 (defun org-agenda-goto-calendar ()
21570 "Open the Emacs calendar with the date at the cursor."
21571 (interactive)
21572 (org-agenda-check-type t 'agenda 'timeline)
21573 (let* ((day (or (get-text-property (point) 'day)
21574 (error "Don't know which date to open in calendar")))
21575 (date (calendar-gregorian-from-absolute day))
21576 (calendar-move-hook nil)
21577 (view-calendar-holidays-initially nil)
21578 (view-diary-entries-initially nil))
21579 (calendar)
21580 (calendar-goto-date date)))
21582 (defun org-calendar-goto-agenda ()
21583 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
21584 This is a command that has to be installed in `calendar-mode-map'."
21585 (interactive)
21586 (org-agenda-list nil (calendar-absolute-from-gregorian
21587 (calendar-cursor-to-date))
21588 nil))
21590 (defun org-agenda-convert-date ()
21591 (interactive)
21592 (org-agenda-check-type t 'agenda 'timeline)
21593 (let ((day (get-text-property (point) 'day))
21594 date s)
21595 (unless day
21596 (error "Don't know which date to convert"))
21597 (setq date (calendar-gregorian-from-absolute day))
21598 (setq s (concat
21599 "Gregorian: " (calendar-date-string date) "\n"
21600 "ISO: " (calendar-iso-date-string date) "\n"
21601 "Day of Yr: " (calendar-day-of-year-string date) "\n"
21602 "Julian: " (calendar-julian-date-string date) "\n"
21603 "Astron. JD: " (calendar-astro-date-string date)
21604 " (Julian date number at noon UTC)\n"
21605 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
21606 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
21607 "French: " (calendar-french-date-string date) "\n"
21608 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
21609 "Mayan: " (calendar-mayan-date-string date) "\n"
21610 "Coptic: " (calendar-coptic-date-string date) "\n"
21611 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
21612 "Persian: " (calendar-persian-date-string date) "\n"
21613 "Chinese: " (calendar-chinese-date-string date) "\n"))
21614 (with-output-to-temp-buffer "*Dates*"
21615 (princ s))
21616 (if (fboundp 'fit-window-to-buffer)
21617 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
21620 ;;;; Embedded LaTeX
21622 (defvar org-cdlatex-mode-map (make-sparse-keymap)
21623 "Keymap for the minor `org-cdlatex-mode'.")
21625 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
21626 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
21627 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
21628 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
21629 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
21631 (defvar org-cdlatex-texmathp-advice-is-done nil
21632 "Flag remembering if we have applied the advice to texmathp already.")
21634 (define-minor-mode org-cdlatex-mode
21635 "Toggle the minor `org-cdlatex-mode'.
21636 This mode supports entering LaTeX environment and math in LaTeX fragments
21637 in Org-mode.
21638 \\{org-cdlatex-mode-map}"
21639 nil " OCDL" nil
21640 (when org-cdlatex-mode (require 'cdlatex))
21641 (unless org-cdlatex-texmathp-advice-is-done
21642 (setq org-cdlatex-texmathp-advice-is-done t)
21643 (defadvice texmathp (around org-math-always-on activate)
21644 "Always return t in org-mode buffers.
21645 This is because we want to insert math symbols without dollars even outside
21646 the LaTeX math segments. If Orgmode thinks that point is actually inside
21647 en embedded LaTeX fragement, let texmathp do its job.
21648 \\[org-cdlatex-mode-map]"
21649 (interactive)
21650 (let (p)
21651 (cond
21652 ((not (org-mode-p)) ad-do-it)
21653 ((eq this-command 'cdlatex-math-symbol)
21654 (setq ad-return-value t
21655 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
21657 (let ((p (org-inside-LaTeX-fragment-p)))
21658 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
21659 (setq ad-return-value t
21660 texmathp-why '("Org-mode embedded math" . 0))
21661 (if p ad-do-it)))))))))
21663 (defun turn-on-org-cdlatex ()
21664 "Unconditionally turn on `org-cdlatex-mode'."
21665 (org-cdlatex-mode 1))
21667 (defun org-inside-LaTeX-fragment-p ()
21668 "Test if point is inside a LaTeX fragment.
21669 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
21670 sequence appearing also before point.
21671 Even though the matchers for math are configurable, this function assumes
21672 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
21673 delimiters are skipped when they have been removed by customization.
21674 The return value is nil, or a cons cell with the delimiter and
21675 and the position of this delimiter.
21677 This function does a reasonably good job, but can locally be fooled by
21678 for example currency specifications. For example it will assume being in
21679 inline math after \"$22.34\". The LaTeX fragment formatter will only format
21680 fragments that are properly closed, but during editing, we have to live
21681 with the uncertainty caused by missing closing delimiters. This function
21682 looks only before point, not after."
21683 (catch 'exit
21684 (let ((pos (point))
21685 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
21686 (lim (progn
21687 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
21688 (point)))
21689 dd-on str (start 0) m re)
21690 (goto-char pos)
21691 (when dodollar
21692 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
21693 re (nth 1 (assoc "$" org-latex-regexps)))
21694 (while (string-match re str start)
21695 (cond
21696 ((= (match-end 0) (length str))
21697 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
21698 ((= (match-end 0) (- (length str) 5))
21699 (throw 'exit nil))
21700 (t (setq start (match-end 0))))))
21701 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
21702 (goto-char pos)
21703 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
21704 (and (match-beginning 2) (throw 'exit nil))
21705 ;; count $$
21706 (while (re-search-backward "\\$\\$" lim t)
21707 (setq dd-on (not dd-on)))
21708 (goto-char pos)
21709 (if dd-on (cons "$$" m))))))
21712 (defun org-try-cdlatex-tab ()
21713 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
21714 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
21715 - inside a LaTeX fragment, or
21716 - after the first word in a line, where an abbreviation expansion could
21717 insert a LaTeX environment."
21718 (when org-cdlatex-mode
21719 (cond
21720 ((save-excursion
21721 (skip-chars-backward "a-zA-Z0-9*")
21722 (skip-chars-backward " \t")
21723 (bolp))
21724 (cdlatex-tab) t)
21725 ((org-inside-LaTeX-fragment-p)
21726 (cdlatex-tab) t)
21727 (t nil))))
21729 (defun org-cdlatex-underscore-caret (&optional arg)
21730 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
21731 Revert to the normal definition outside of these fragments."
21732 (interactive "P")
21733 (if (org-inside-LaTeX-fragment-p)
21734 (call-interactively 'cdlatex-sub-superscript)
21735 (let (org-cdlatex-mode)
21736 (call-interactively (key-binding (vector last-input-event))))))
21738 (defun org-cdlatex-math-modify (&optional arg)
21739 "Execute `cdlatex-math-modify' in LaTeX fragments.
21740 Revert to the normal definition outside of these fragments."
21741 (interactive "P")
21742 (if (org-inside-LaTeX-fragment-p)
21743 (call-interactively 'cdlatex-math-modify)
21744 (let (org-cdlatex-mode)
21745 (call-interactively (key-binding (vector last-input-event))))))
21747 (defvar org-latex-fragment-image-overlays nil
21748 "List of overlays carrying the images of latex fragments.")
21749 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
21751 (defun org-remove-latex-fragment-image-overlays ()
21752 "Remove all overlays with LaTeX fragment images in current buffer."
21753 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
21754 (setq org-latex-fragment-image-overlays nil))
21756 (defun org-preview-latex-fragment (&optional subtree)
21757 "Preview the LaTeX fragment at point, or all locally or globally.
21758 If the cursor is in a LaTeX fragment, create the image and overlay
21759 it over the source code. If there is no fragment at point, display
21760 all fragments in the current text, from one headline to the next. With
21761 prefix SUBTREE, display all fragments in the current subtree. With a
21762 double prefix `C-u C-u', or when the cursor is before the first headline,
21763 display all fragments in the buffer.
21764 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
21765 (interactive "P")
21766 (org-remove-latex-fragment-image-overlays)
21767 (save-excursion
21768 (save-restriction
21769 (let (beg end at msg)
21770 (cond
21771 ((or (equal subtree '(16))
21772 (not (save-excursion
21773 (re-search-backward (concat "^" outline-regexp) nil t))))
21774 (setq beg (point-min) end (point-max)
21775 msg "Creating images for buffer...%s"))
21776 ((equal subtree '(4))
21777 (org-back-to-heading)
21778 (setq beg (point) end (org-end-of-subtree t)
21779 msg "Creating images for subtree...%s"))
21781 (if (setq at (org-inside-LaTeX-fragment-p))
21782 (goto-char (max (point-min) (- (cdr at) 2)))
21783 (org-back-to-heading))
21784 (setq beg (point) end (progn (outline-next-heading) (point))
21785 msg (if at "Creating image...%s"
21786 "Creating images for entry...%s"))))
21787 (message msg "")
21788 (narrow-to-region beg end)
21789 (goto-char beg)
21790 (org-format-latex
21791 (concat "ltxpng/" (file-name-sans-extension
21792 (file-name-nondirectory
21793 buffer-file-name)))
21794 default-directory 'overlays msg at 'forbuffer)
21795 (message msg "done. Use `C-c C-c' to remove images.")))))
21797 (defvar org-latex-regexps
21798 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
21799 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
21800 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
21801 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
21802 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
21803 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
21804 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
21805 "Regular expressions for matching embedded LaTeX.")
21807 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
21808 "Replace LaTeX fragments with links to an image, and produce images."
21809 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
21810 (let* ((prefixnodir (file-name-nondirectory prefix))
21811 (absprefix (expand-file-name prefix dir))
21812 (todir (file-name-directory absprefix))
21813 (opt org-format-latex-options)
21814 (matchers (plist-get opt :matchers))
21815 (re-list org-latex-regexps)
21816 (cnt 0) txt link beg end re e checkdir
21817 m n block linkfile movefile ov)
21818 ;; Check if there are old images files with this prefix, and remove them
21819 (when (file-directory-p todir)
21820 (mapc 'delete-file
21821 (directory-files
21822 todir 'full
21823 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
21824 ;; Check the different regular expressions
21825 (while (setq e (pop re-list))
21826 (setq m (car e) re (nth 1 e) n (nth 2 e)
21827 block (if (nth 3 e) "\n\n" ""))
21828 (when (member m matchers)
21829 (goto-char (point-min))
21830 (while (re-search-forward re nil t)
21831 (when (or (not at) (equal (cdr at) (match-beginning n)))
21832 (setq txt (match-string n)
21833 beg (match-beginning n) end (match-end n)
21834 cnt (1+ cnt)
21835 linkfile (format "%s_%04d.png" prefix cnt)
21836 movefile (format "%s_%04d.png" absprefix cnt)
21837 link (concat block "[[file:" linkfile "]]" block))
21838 (if msg (message msg cnt))
21839 (goto-char beg)
21840 (unless checkdir ; make sure the directory exists
21841 (setq checkdir t)
21842 (or (file-directory-p todir) (make-directory todir)))
21843 (org-create-formula-image
21844 txt movefile opt forbuffer)
21845 (if overlays
21846 (progn
21847 (setq ov (org-make-overlay beg end))
21848 (if (featurep 'xemacs)
21849 (progn
21850 (org-overlay-put ov 'invisible t)
21851 (org-overlay-put
21852 ov 'end-glyph
21853 (make-glyph (vector 'png :file movefile))))
21854 (org-overlay-put
21855 ov 'display
21856 (list 'image :type 'png :file movefile :ascent 'center)))
21857 (push ov org-latex-fragment-image-overlays)
21858 (goto-char end))
21859 (delete-region beg end)
21860 (insert link))))))))
21862 ;; This function borrows from Ganesh Swami's latex2png.el
21863 (defun org-create-formula-image (string tofile options buffer)
21864 (let* ((tmpdir (if (featurep 'xemacs)
21865 (temp-directory)
21866 temporary-file-directory))
21867 (texfilebase (make-temp-name
21868 (expand-file-name "orgtex" tmpdir)))
21869 (texfile (concat texfilebase ".tex"))
21870 (dvifile (concat texfilebase ".dvi"))
21871 (pngfile (concat texfilebase ".png"))
21872 (fnh (face-attribute 'default :height nil))
21873 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
21874 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
21875 (fg (or (plist-get options (if buffer :foreground :html-foreground))
21876 "Black"))
21877 (bg (or (plist-get options (if buffer :background :html-background))
21878 "Transparent")))
21879 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
21880 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
21881 (with-temp-file texfile
21882 (insert org-format-latex-header
21883 "\n\\begin{document}\n" string "\n\\end{document}\n"))
21884 (let ((dir default-directory))
21885 (condition-case nil
21886 (progn
21887 (cd tmpdir)
21888 (call-process "latex" nil nil nil texfile))
21889 (error nil))
21890 (cd dir))
21891 (if (not (file-exists-p dvifile))
21892 (progn (message "Failed to create dvi file from %s" texfile) nil)
21893 (call-process "dvipng" nil nil nil
21894 "-E" "-fg" fg "-bg" bg
21895 "-D" dpi
21896 ;;"-x" scale "-y" scale
21897 "-T" "tight"
21898 "-o" pngfile
21899 dvifile)
21900 (if (not (file-exists-p pngfile))
21901 (progn (message "Failed to create png file from %s" texfile) nil)
21902 ;; Use the requested file name and clean up
21903 (copy-file pngfile tofile 'replace)
21904 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
21905 (delete-file (concat texfilebase e)))
21906 pngfile))))
21908 (defun org-dvipng-color (attr)
21909 "Return an rgb color specification for dvipng."
21910 (apply 'format "rgb %s %s %s"
21911 (mapcar 'org-normalize-color
21912 (color-values (face-attribute 'default attr nil)))))
21914 (defun org-normalize-color (value)
21915 "Return string to be used as color value for an RGB component."
21916 (format "%g" (/ value 65535.0)))
21918 ;;;; Exporting
21920 ;;; Variables, constants, and parameter plists
21922 (defconst org-level-max 20)
21924 (defvar org-export-html-preamble nil
21925 "Preamble, to be inserted just after <body>. Set by publishing functions.")
21926 (defvar org-export-html-postamble nil
21927 "Preamble, to be inserted just before </body>. Set by publishing functions.")
21928 (defvar org-export-html-auto-preamble t
21929 "Should default preamble be inserted? Set by publishing functions.")
21930 (defvar org-export-html-auto-postamble t
21931 "Should default postamble be inserted? Set by publishing functions.")
21932 (defvar org-current-export-file nil) ; dynamically scoped parameter
21933 (defvar org-current-export-dir nil) ; dynamically scoped parameter
21936 (defconst org-export-plist-vars
21937 '((:language . org-export-default-language)
21938 (:customtime . org-display-custom-times)
21939 (:headline-levels . org-export-headline-levels)
21940 (:section-numbers . org-export-with-section-numbers)
21941 (:table-of-contents . org-export-with-toc)
21942 (:preserve-breaks . org-export-preserve-breaks)
21943 (:archived-trees . org-export-with-archived-trees)
21944 (:emphasize . org-export-with-emphasize)
21945 (:sub-superscript . org-export-with-sub-superscripts)
21946 (:footnotes . org-export-with-footnotes)
21947 (:drawers . org-export-with-drawers)
21948 (:tags . org-export-with-tags)
21949 (:TeX-macros . org-export-with-TeX-macros)
21950 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
21951 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
21952 (:fixed-width . org-export-with-fixed-width)
21953 (:timestamps . org-export-with-timestamps)
21954 (:author-info . org-export-author-info)
21955 (:time-stamp-file . org-export-time-stamp-file)
21956 (:tables . org-export-with-tables)
21957 (:table-auto-headline . org-export-highlight-first-table-line)
21958 (:style . org-export-html-style)
21959 (:agenda-style . org-agenda-export-html-style) ;; FIXME: Does this work????
21960 (:convert-org-links . org-export-html-link-org-files-as-html)
21961 (:inline-images . org-export-html-inline-images)
21962 (:html-extension . org-export-html-extension)
21963 (:expand-quoted-html . org-export-html-expand)
21964 (:timestamp . org-export-html-with-timestamp)
21965 (:publishing-directory . org-export-publishing-directory)
21966 (:preamble . org-export-html-preamble)
21967 (:postamble . org-export-html-postamble)
21968 (:auto-preamble . org-export-html-auto-preamble)
21969 (:auto-postamble . org-export-html-auto-postamble)
21970 (:author . user-full-name)
21971 (:email . user-mail-address)))
21973 (defun org-default-export-plist ()
21974 "Return the property list with default settings for the export variables."
21975 (let ((l org-export-plist-vars) rtn e)
21976 (while (setq e (pop l))
21977 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
21978 rtn))
21980 (defun org-infile-export-plist ()
21981 "Return the property list with file-local settings for export."
21982 (save-excursion
21983 (goto-char 0)
21984 (let ((re (org-make-options-regexp
21985 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
21986 p key val text options)
21987 (while (re-search-forward re nil t)
21988 (setq key (org-match-string-no-properties 1)
21989 val (org-match-string-no-properties 2))
21990 (cond
21991 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
21992 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
21993 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
21994 ((string-equal key "DATE") (setq p (plist-put p :date val)))
21995 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
21996 ((string-equal key "TEXT")
21997 (setq text (if text (concat text "\n" val) val)))
21998 ((string-equal key "OPTIONS") (setq options val))))
21999 (setq p (plist-put p :text text))
22000 (when options
22001 (let ((op '(("H" . :headline-levels)
22002 ("num" . :section-numbers)
22003 ("toc" . :table-of-contents)
22004 ("\\n" . :preserve-breaks)
22005 ("@" . :expand-quoted-html)
22006 (":" . :fixed-width)
22007 ("|" . :tables)
22008 ("^" . :sub-superscript)
22009 ("f" . :footnotes)
22010 ("d" . :drawers)
22011 ("tags" . :tags)
22012 ("*" . :emphasize)
22013 ("TeX" . :TeX-macros)
22014 ("LaTeX" . :LaTeX-fragments)
22015 ("skip" . :skip-before-1st-heading)
22016 ("author" . :author-info)
22017 ("timestamp" . :time-stamp-file)))
22019 (while (setq o (pop op))
22020 (if (string-match (concat (regexp-quote (car o))
22021 ":\\([^ \t\n\r;,.]*\\)")
22022 options)
22023 (setq p (plist-put p (cdr o)
22024 (car (read-from-string
22025 (match-string 1 options)))))))))
22026 p)))
22028 (defun org-export-directory (type plist)
22029 (let* ((val (plist-get plist :publishing-directory))
22030 (dir (if (listp val)
22031 (or (cdr (assoc type val)) ".")
22032 val)))
22033 dir))
22035 (defun org-skip-comments (lines)
22036 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
22037 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
22038 (re2 "^\\(\\*+\\)[ \t\n\r]")
22039 (case-fold-search nil)
22040 rtn line level)
22041 (while (setq line (pop lines))
22042 (cond
22043 ((and (string-match re1 line)
22044 (setq level (- (match-end 1) (match-beginning 1))))
22045 ;; Beginning of a COMMENT subtree. Skip it.
22046 (while (and (setq line (pop lines))
22047 (or (not (string-match re2 line))
22048 (> (- (match-end 1) (match-beginning 1)) level))))
22049 (setq lines (cons line lines)))
22050 ((string-match "^#" line)
22051 ;; an ordinary comment line
22053 ((and org-export-table-remove-special-lines
22054 (string-match "^[ \t]*|" line)
22055 (or (string-match "^[ \t]*| *[!_^] *|" line)
22056 (and (string-match "| *<[0-9]+> *|" line)
22057 (not (string-match "| *[^ <|]" line)))))
22058 ;; a special table line that should be removed
22060 (t (setq rtn (cons line rtn)))))
22061 (nreverse rtn)))
22063 (defun org-export (&optional arg)
22064 (interactive)
22065 (let ((help "[t] insert the export option template
22066 \[v] limit export to visible part of outline tree
22068 \[a] export as ASCII
22070 \[h] export as HTML
22071 \[H] export as HTML to temporary buffer
22072 \[R] export region as HTML
22073 \[b] export as HTML and browse immediately
22074 \[x] export as XOXO
22076 \[l] export as LaTeX
22077 \[L] export as LaTeX to temporary buffer
22079 \[i] export current file as iCalendar file
22080 \[I] export all agenda files as iCalendar files
22081 \[c] export agenda files into combined iCalendar file
22083 \[F] publish current file
22084 \[P] publish current project
22085 \[X] publish... (project will be prompted for)
22086 \[A] publish all projects")
22087 (cmds
22088 '((?t . org-insert-export-options-template)
22089 (?v . org-export-visible)
22090 (?a . org-export-as-ascii)
22091 (?h . org-export-as-html)
22092 (?b . org-export-as-html-and-open)
22093 (?H . org-export-as-html-to-buffer)
22094 (?R . org-export-region-as-html)
22095 (?x . org-export-as-xoxo)
22096 (?l . org-export-as-latex)
22097 (?L . org-export-as-latex-to-buffer)
22098 (?i . org-export-icalendar-this-file)
22099 (?I . org-export-icalendar-all-agenda-files)
22100 (?c . org-export-icalendar-combine-agenda-files)
22101 (?F . org-publish-current-file)
22102 (?P . org-publish-current-project)
22103 (?X . org-publish)
22104 (?A . org-publish-all)))
22105 r1 r2 ass)
22106 (save-window-excursion
22107 (delete-other-windows)
22108 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
22109 (princ help))
22110 (message "Select command: ")
22111 (setq r1 (read-char-exclusive)))
22112 (setq r2 (if (< r1 27) (+ r1 96) r1))
22113 (if (setq ass (assq r2 cmds))
22114 (call-interactively (cdr ass))
22115 (error "No command associated with key %c" r1))))
22117 (defconst org-html-entities
22118 '(("nbsp")
22119 ("iexcl")
22120 ("cent")
22121 ("pound")
22122 ("curren")
22123 ("yen")
22124 ("brvbar")
22125 ("vert" . "&#124;")
22126 ("sect")
22127 ("uml")
22128 ("copy")
22129 ("ordf")
22130 ("laquo")
22131 ("not")
22132 ("shy")
22133 ("reg")
22134 ("macr")
22135 ("deg")
22136 ("plusmn")
22137 ("sup2")
22138 ("sup3")
22139 ("acute")
22140 ("micro")
22141 ("para")
22142 ("middot")
22143 ("odot"."o")
22144 ("star"."*")
22145 ("cedil")
22146 ("sup1")
22147 ("ordm")
22148 ("raquo")
22149 ("frac14")
22150 ("frac12")
22151 ("frac34")
22152 ("iquest")
22153 ("Agrave")
22154 ("Aacute")
22155 ("Acirc")
22156 ("Atilde")
22157 ("Auml")
22158 ("Aring") ("AA"."&Aring;")
22159 ("AElig")
22160 ("Ccedil")
22161 ("Egrave")
22162 ("Eacute")
22163 ("Ecirc")
22164 ("Euml")
22165 ("Igrave")
22166 ("Iacute")
22167 ("Icirc")
22168 ("Iuml")
22169 ("ETH")
22170 ("Ntilde")
22171 ("Ograve")
22172 ("Oacute")
22173 ("Ocirc")
22174 ("Otilde")
22175 ("Ouml")
22176 ("times")
22177 ("Oslash")
22178 ("Ugrave")
22179 ("Uacute")
22180 ("Ucirc")
22181 ("Uuml")
22182 ("Yacute")
22183 ("THORN")
22184 ("szlig")
22185 ("agrave")
22186 ("aacute")
22187 ("acirc")
22188 ("atilde")
22189 ("auml")
22190 ("aring")
22191 ("aelig")
22192 ("ccedil")
22193 ("egrave")
22194 ("eacute")
22195 ("ecirc")
22196 ("euml")
22197 ("igrave")
22198 ("iacute")
22199 ("icirc")
22200 ("iuml")
22201 ("eth")
22202 ("ntilde")
22203 ("ograve")
22204 ("oacute")
22205 ("ocirc")
22206 ("otilde")
22207 ("ouml")
22208 ("divide")
22209 ("oslash")
22210 ("ugrave")
22211 ("uacute")
22212 ("ucirc")
22213 ("uuml")
22214 ("yacute")
22215 ("thorn")
22216 ("yuml")
22217 ("fnof")
22218 ("Alpha")
22219 ("Beta")
22220 ("Gamma")
22221 ("Delta")
22222 ("Epsilon")
22223 ("Zeta")
22224 ("Eta")
22225 ("Theta")
22226 ("Iota")
22227 ("Kappa")
22228 ("Lambda")
22229 ("Mu")
22230 ("Nu")
22231 ("Xi")
22232 ("Omicron")
22233 ("Pi")
22234 ("Rho")
22235 ("Sigma")
22236 ("Tau")
22237 ("Upsilon")
22238 ("Phi")
22239 ("Chi")
22240 ("Psi")
22241 ("Omega")
22242 ("alpha")
22243 ("beta")
22244 ("gamma")
22245 ("delta")
22246 ("epsilon")
22247 ("varepsilon"."&epsilon;")
22248 ("zeta")
22249 ("eta")
22250 ("theta")
22251 ("iota")
22252 ("kappa")
22253 ("lambda")
22254 ("mu")
22255 ("nu")
22256 ("xi")
22257 ("omicron")
22258 ("pi")
22259 ("rho")
22260 ("sigmaf") ("varsigma"."&sigmaf;")
22261 ("sigma")
22262 ("tau")
22263 ("upsilon")
22264 ("phi")
22265 ("chi")
22266 ("psi")
22267 ("omega")
22268 ("thetasym") ("vartheta"."&thetasym;")
22269 ("upsih")
22270 ("piv")
22271 ("bull") ("bullet"."&bull;")
22272 ("hellip") ("dots"."&hellip;")
22273 ("prime")
22274 ("Prime")
22275 ("oline")
22276 ("frasl")
22277 ("weierp")
22278 ("image")
22279 ("real")
22280 ("trade")
22281 ("alefsym")
22282 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
22283 ("uarr") ("uparrow"."&uarr;")
22284 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
22285 ("darr")("downarrow"."&darr;")
22286 ("harr") ("leftrightarrow"."&harr;")
22287 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
22288 ("lArr") ("Leftarrow"."&lArr;")
22289 ("uArr") ("Uparrow"."&uArr;")
22290 ("rArr") ("Rightarrow"."&rArr;")
22291 ("dArr") ("Downarrow"."&dArr;")
22292 ("hArr") ("Leftrightarrow"."&hArr;")
22293 ("forall")
22294 ("part") ("partial"."&part;")
22295 ("exist") ("exists"."&exist;")
22296 ("empty") ("emptyset"."&empty;")
22297 ("nabla")
22298 ("isin") ("in"."&isin;")
22299 ("notin")
22300 ("ni")
22301 ("prod")
22302 ("sum")
22303 ("minus")
22304 ("lowast") ("ast"."&lowast;")
22305 ("radic")
22306 ("prop") ("proptp"."&prop;")
22307 ("infin") ("infty"."&infin;")
22308 ("ang") ("angle"."&ang;")
22309 ("and") ("vee"."&and;")
22310 ("or") ("wedge"."&or;")
22311 ("cap")
22312 ("cup")
22313 ("int")
22314 ("there4")
22315 ("sim")
22316 ("cong") ("simeq"."&cong;")
22317 ("asymp")("approx"."&asymp;")
22318 ("ne") ("neq"."&ne;")
22319 ("equiv")
22320 ("le")
22321 ("ge")
22322 ("sub") ("subset"."&sub;")
22323 ("sup") ("supset"."&sup;")
22324 ("nsub")
22325 ("sube")
22326 ("supe")
22327 ("oplus")
22328 ("otimes")
22329 ("perp")
22330 ("sdot") ("cdot"."&sdot;")
22331 ("lceil")
22332 ("rceil")
22333 ("lfloor")
22334 ("rfloor")
22335 ("lang")
22336 ("rang")
22337 ("loz") ("Diamond"."&loz;")
22338 ("spades") ("spadesuit"."&spades;")
22339 ("clubs") ("clubsuit"."&clubs;")
22340 ("hearts") ("diamondsuit"."&hearts;")
22341 ("diams") ("diamondsuit"."&diams;")
22342 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
22343 ("quot")
22344 ("amp")
22345 ("lt")
22346 ("gt")
22347 ("OElig")
22348 ("oelig")
22349 ("Scaron")
22350 ("scaron")
22351 ("Yuml")
22352 ("circ")
22353 ("tilde")
22354 ("ensp")
22355 ("emsp")
22356 ("thinsp")
22357 ("zwnj")
22358 ("zwj")
22359 ("lrm")
22360 ("rlm")
22361 ("ndash")
22362 ("mdash")
22363 ("lsquo")
22364 ("rsquo")
22365 ("sbquo")
22366 ("ldquo")
22367 ("rdquo")
22368 ("bdquo")
22369 ("dagger")
22370 ("Dagger")
22371 ("permil")
22372 ("lsaquo")
22373 ("rsaquo")
22374 ("euro")
22376 ("arccos"."arccos")
22377 ("arcsin"."arcsin")
22378 ("arctan"."arctan")
22379 ("arg"."arg")
22380 ("cos"."cos")
22381 ("cosh"."cosh")
22382 ("cot"."cot")
22383 ("coth"."coth")
22384 ("csc"."csc")
22385 ("deg"."deg")
22386 ("det"."det")
22387 ("dim"."dim")
22388 ("exp"."exp")
22389 ("gcd"."gcd")
22390 ("hom"."hom")
22391 ("inf"."inf")
22392 ("ker"."ker")
22393 ("lg"."lg")
22394 ("lim"."lim")
22395 ("liminf"."liminf")
22396 ("limsup"."limsup")
22397 ("ln"."ln")
22398 ("log"."log")
22399 ("max"."max")
22400 ("min"."min")
22401 ("Pr"."Pr")
22402 ("sec"."sec")
22403 ("sin"."sin")
22404 ("sinh"."sinh")
22405 ("sup"."sup")
22406 ("tan"."tan")
22407 ("tanh"."tanh")
22409 "Entities for TeX->HTML translation.
22410 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
22411 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
22412 In that case, \"\\ent\" will be translated to \"&other;\".
22413 The list contains HTML entities for Latin-1, Greek and other symbols.
22414 It is supplemented by a number of commonly used TeX macros with appropriate
22415 translations. There is currently no way for users to extend this.")
22417 ;;; General functions for all backends
22419 (defun org-cleaned-string-for-export (string &rest parameters)
22420 "Cleanup a buffer STRING so that links can be created safely."
22421 (interactive)
22422 (let* ((re-radio (and org-target-link-regexp
22423 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
22424 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
22425 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
22426 (re-archive (concat ":" org-archive-tag ":"))
22427 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
22428 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
22429 (htmlp (plist-get parameters :for-html))
22430 (asciip (plist-get parameters :for-ascii))
22431 (latexp (plist-get parameters :for-LaTeX))
22432 (commentsp (plist-get parameters :comments))
22433 (archived-trees (plist-get parameters :archived-trees))
22434 (inhibit-read-only t)
22435 (outline-regexp "\\*+ ")
22436 a b xx
22437 rtn p)
22438 (with-current-buffer (get-buffer-create " org-mode-tmp")
22439 (erase-buffer)
22440 (insert string)
22441 ;; Remove license-to-kill stuff
22442 (while (setq p (text-property-any (point-min) (point-max)
22443 :org-license-to-kill t))
22444 (delete-region p (next-single-property-change p :org-license-to-kill)))
22446 (let ((org-inhibit-startup t)) (org-mode))
22447 (untabify (point-min) (point-max))
22449 ;; Get the correct stuff before the first headline
22450 (when (plist-get parameters :skip-before-1st-heading)
22451 (goto-char (point-min))
22452 (when (re-search-forward "^\\*+[ \t]" nil t)
22453 (delete-region (point-min) (match-beginning 0))
22454 (goto-char (point-min))
22455 (insert "\n")))
22456 (when (plist-get parameters :add-text)
22457 (goto-char (point-min))
22458 (insert (plist-get parameters :add-text) "\n"))
22460 ;; Get rid of archived trees
22461 (when (not (eq archived-trees t))
22462 (goto-char (point-min))
22463 (while (re-search-forward re-archive nil t)
22464 (if (not (org-on-heading-p t))
22465 (org-end-of-subtree t)
22466 (beginning-of-line 1)
22467 (setq a (if archived-trees
22468 (1+ (point-at-eol)) (point))
22469 b (org-end-of-subtree t))
22470 (if (> b a) (delete-region a b)))))
22472 ;; Get rid of drawers
22473 (unless (eq t org-export-with-drawers)
22474 (goto-char (point-min))
22475 (let ((re (concat "^[ \t]*:\\("
22476 (mapconcat 'identity
22477 (if (listp org-export-with-drawers)
22478 org-export-with-drawers
22479 org-drawers)
22480 "\\|")
22481 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
22482 (while (re-search-forward re nil t)
22483 (replace-match ""))))
22485 ;; Find targets in comments and move them out of comments,
22486 ;; but mark them as targets that should be invisible
22487 (goto-char (point-min))
22488 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
22489 (replace-match "\\1(INVISIBLE)"))
22491 ;; Protect backend specific stuff, throw away the others.
22492 (goto-char (point-min))
22493 (let ((formatters
22494 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
22495 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
22496 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
22497 fmt)
22498 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
22499 (add-text-properties (match-beginning 0) (match-end 0)
22500 '(org-protected t)))
22501 (while formatters
22502 (setq fmt (pop formatters))
22503 (when (car fmt)
22504 (goto-char (point-min))
22505 (while (re-search-forward (concat "^#\\+" (cadr fmt)
22506 ":[ \t]*\\(.*\\)") nil t)
22507 (replace-match "\\1" t)
22508 (add-text-properties
22509 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
22510 '(org-protected t))))
22511 (goto-char (point-min))
22512 (while (re-search-forward
22513 (concat "^#\\+"
22514 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
22515 (cadddr fmt) "\\>.*\n?") nil t)
22516 (if (car fmt)
22517 (add-text-properties (match-beginning 1) (1+ (match-end 1))
22518 '(org-protected t))
22519 (delete-region (match-beginning 0) (match-end 0))))))
22521 ;; Protect quoted subtrees
22522 (goto-char (point-min))
22523 (while (re-search-forward re-quote nil t)
22524 (goto-char (match-beginning 0))
22525 (end-of-line 1)
22526 (add-text-properties (point) (org-end-of-subtree t)
22527 '(org-protected t)))
22529 ;; Remove subtrees that are commented
22530 (goto-char (point-min))
22531 (while (re-search-forward re-commented nil t)
22532 (goto-char (match-beginning 0))
22533 (delete-region (point) (org-end-of-subtree t)))
22535 ;; Remove special table lines
22536 (when org-export-table-remove-special-lines
22537 (goto-char (point-min))
22538 (while (re-search-forward "^[ \t]*|" nil t)
22539 (beginning-of-line 1)
22540 (if (or (looking-at "[ \t]*| *[!_^] *|")
22541 (and (looking-at ".*?| *<[0-9]+> *|")
22542 (not (looking-at ".*?| *[^ <|]"))))
22543 (delete-region (max (point-min) (1- (point-at-bol)))
22544 (point-at-eol))
22545 (end-of-line 1))))
22547 ;; Specific LaTeX stuff
22548 (when latexp
22549 (require 'org-export-latex nil)
22550 (org-export-latex-cleaned-string))
22552 ;; Specific HTML stuff
22553 (when htmlp
22554 ;; Convert LaTeX fragments to images
22555 (when (plist-get parameters :LaTeX-fragments)
22556 (org-format-latex
22557 (concat "ltxpng/" (file-name-sans-extension
22558 (file-name-nondirectory
22559 org-current-export-file)))
22560 org-current-export-dir nil "Creating LaTeX image %s"))
22561 (message "Exporting..."))
22563 ;; Remove or replace comments
22564 (goto-char (point-min))
22565 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
22566 (if commentsp
22567 (progn (add-text-properties
22568 (match-beginning 0) (match-end 0) '(org-protected t))
22569 (replace-match (format commentsp (match-string 1)) t t))
22570 (replace-match "")))
22572 ;; Find matches for radio targets and turn them into internal links
22573 (goto-char (point-min))
22574 (when re-radio
22575 (while (re-search-forward re-radio nil t)
22576 (org-if-unprotected
22577 (replace-match "\\1[[\\2]]"))))
22579 ;; Find all links that contain a newline and put them into a single line
22580 (goto-char (point-min))
22581 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
22582 (org-if-unprotected
22583 (replace-match "\\1 \\3")
22584 (goto-char (match-beginning 0))))
22587 ;; Normalize links: Convert angle and plain links into bracket links
22588 ;; Expand link abbreviations
22589 (goto-char (point-min))
22590 (while (re-search-forward re-plain-link nil t)
22591 (goto-char (1- (match-end 0)))
22592 (org-if-unprotected
22593 (let* ((s (concat (match-string 1) "[[" (match-string 2)
22594 ":" (match-string 3) "]]")))
22595 ;; added 'org-link face to links
22596 (put-text-property 0 (length s) 'face 'org-link s)
22597 (replace-match s t t))))
22598 (goto-char (point-min))
22599 (while (re-search-forward re-angle-link nil t)
22600 (goto-char (1- (match-end 0)))
22601 (org-if-unprotected
22602 (let* ((s (concat (match-string 1) "[[" (match-string 2)
22603 ":" (match-string 3) "]]")))
22604 (put-text-property 0 (length s) 'face 'org-link s)
22605 (replace-match s t t))))
22606 (goto-char (point-min))
22607 (while (re-search-forward org-bracket-link-regexp nil t)
22608 (org-if-unprotected
22609 (let* ((s (concat "[[" (setq xx (save-match-data
22610 (org-link-expand-abbrev (match-string 1))))
22612 (if (match-end 3)
22613 (match-string 2)
22614 (concat "[" xx "]"))
22615 "]")))
22616 (put-text-property 0 (length s) 'face 'org-link s)
22617 (replace-match s t t))))
22619 ;; Find multiline emphasis and put them into single line
22620 (when (plist-get parameters :emph-multiline)
22621 (goto-char (point-min))
22622 (while (re-search-forward org-emph-re nil t)
22623 (if (not (= (char-after (match-beginning 3))
22624 (char-after (match-beginning 4))))
22625 (org-if-unprotected
22626 (subst-char-in-region (match-beginning 0) (match-end 0)
22627 ?\n ?\ t)
22628 (goto-char (1- (match-end 0))))
22629 (goto-char (1+ (match-beginning 0))))))
22631 (setq rtn (buffer-string)))
22632 (kill-buffer " org-mode-tmp")
22633 rtn))
22635 (defun org-export-grab-title-from-buffer ()
22636 "Get a title for the current document, from looking at the buffer."
22637 (let ((inhibit-read-only t))
22638 (save-excursion
22639 (goto-char (point-min))
22640 (let ((end (save-excursion (outline-next-heading) (point))))
22641 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
22642 ;; Mark the line so that it will not be exported as normal text.
22643 (org-unmodified
22644 (add-text-properties (match-beginning 0) (match-end 0)
22645 (list :org-license-to-kill t)))
22646 ;; Return the title string
22647 (org-trim (match-string 0)))))))
22649 (defun org-export-get-title-from-subtree ()
22650 "Return subtree title and exclude it from export."
22651 (let (title (m (mark)))
22652 (save-excursion
22653 (goto-char (region-beginning))
22654 (when (and (org-at-heading-p)
22655 (>= (org-end-of-subtree t t) (region-end)))
22656 ;; This is a subtree, we take the title from the first heading
22657 (goto-char (region-beginning))
22658 (looking-at org-todo-line-regexp)
22659 (setq title (match-string 3))
22660 (org-unmodified
22661 (add-text-properties (point) (1+ (point-at-eol))
22662 (list :org-license-to-kill t)))))
22663 title))
22665 (defun org-solidify-link-text (s &optional alist)
22666 "Take link text and make a safe target out of it."
22667 (save-match-data
22668 (let* ((rtn
22669 (mapconcat
22670 'identity
22671 (org-split-string s "[ \t\r\n]+") "--"))
22672 (a (assoc rtn alist)))
22673 (or (cdr a) rtn))))
22675 (defun org-get-min-level (lines)
22676 "Get the minimum level in LINES."
22677 (let ((re "^\\(\\*+\\) ") l min)
22678 (catch 'exit
22679 (while (setq l (pop lines))
22680 (if (string-match re l)
22681 (throw 'exit (org-tr-level (length (match-string 1 l))))))
22682 1)))
22684 ;; Variable holding the vector with section numbers
22685 (defvar org-section-numbers (make-vector org-level-max 0))
22687 (defun org-init-section-numbers ()
22688 "Initialize the vector for the section numbers."
22689 (let* ((level -1)
22690 (numbers (nreverse (org-split-string "" "\\.")))
22691 (depth (1- (length org-section-numbers)))
22692 (i depth) number-string)
22693 (while (>= i 0)
22694 (if (> i level)
22695 (aset org-section-numbers i 0)
22696 (setq number-string (or (car numbers) "0"))
22697 (if (string-match "\\`[A-Z]\\'" number-string)
22698 (aset org-section-numbers i
22699 (- (string-to-char number-string) ?A -1))
22700 (aset org-section-numbers i (string-to-number number-string)))
22701 (pop numbers))
22702 (setq i (1- i)))))
22704 (defun org-section-number (&optional level)
22705 "Return a string with the current section number.
22706 When LEVEL is non-nil, increase section numbers on that level."
22707 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
22708 (when level
22709 (when (> level -1)
22710 (aset org-section-numbers
22711 level (1+ (aref org-section-numbers level))))
22712 (setq idx (1+ level))
22713 (while (<= idx depth)
22714 (if (not (= idx 1))
22715 (aset org-section-numbers idx 0))
22716 (setq idx (1+ idx))))
22717 (setq idx 0)
22718 (while (<= idx depth)
22719 (setq n (aref org-section-numbers idx))
22720 (setq string (concat string (if (not (string= string "")) "." "")
22721 (int-to-string n)))
22722 (setq idx (1+ idx)))
22723 (save-match-data
22724 (if (string-match "\\`\\([@0]\\.\\)+" string)
22725 (setq string (replace-match "" t nil string)))
22726 (if (string-match "\\(\\.0\\)+\\'" string)
22727 (setq string (replace-match "" t nil string))))
22728 string))
22730 ;;; ASCII export
22732 (defvar org-last-level nil) ; dynamically scoped variable
22733 (defvar org-min-level nil) ; dynamically scoped variable
22734 (defvar org-levels-open nil) ; dynamically scoped parameter
22735 (defvar org-ascii-current-indentation nil) ; For communication
22737 (defun org-export-as-ascii (arg)
22738 "Export the outline as a pretty ASCII file.
22739 If there is an active region, export only the region.
22740 The prefix ARG specifies how many levels of the outline should become
22741 underlined headlines. The default is 3."
22742 (interactive "P")
22743 (setq-default org-todo-line-regexp org-todo-line-regexp)
22744 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
22745 (org-infile-export-plist)))
22746 (region-p (org-region-active-p))
22747 (subtree-p
22748 (when region-p
22749 (save-excursion
22750 (goto-char (region-beginning))
22751 (and (org-at-heading-p)
22752 (>= (org-end-of-subtree t t) (region-end))))))
22753 (custom-times org-display-custom-times)
22754 (org-ascii-current-indentation '(0 . 0))
22755 (level 0) line txt
22756 (umax nil)
22757 (umax-toc nil)
22758 (case-fold-search nil)
22759 (filename (concat (file-name-as-directory
22760 (org-export-directory :ascii opt-plist))
22761 (file-name-sans-extension
22762 (or (and subtree-p
22763 (org-entry-get (region-beginning)
22764 "EXPORT_FILE_NAME" t))
22765 (file-name-nondirectory buffer-file-name)))
22766 ".txt"))
22767 (filename (if (equal (file-truename filename)
22768 (file-truename buffer-file-name))
22769 (concat filename ".txt")
22770 filename))
22771 (buffer (find-file-noselect filename))
22772 (org-levels-open (make-vector org-level-max nil))
22773 (odd org-odd-levels-only)
22774 (date (plist-get opt-plist :date))
22775 (author (plist-get opt-plist :author))
22776 (title (or (and subtree-p (org-export-get-title-from-subtree))
22777 (plist-get opt-plist :title)
22778 (and (not
22779 (plist-get opt-plist :skip-before-1st-heading))
22780 (org-export-grab-title-from-buffer))
22781 (file-name-sans-extension
22782 (file-name-nondirectory buffer-file-name))))
22783 (email (plist-get opt-plist :email))
22784 (language (plist-get opt-plist :language))
22785 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
22786 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
22787 (todo nil)
22788 (lang-words nil)
22789 (region
22790 (buffer-substring
22791 (if (org-region-active-p) (region-beginning) (point-min))
22792 (if (org-region-active-p) (region-end) (point-max))))
22793 (lines (org-split-string
22794 (org-cleaned-string-for-export
22795 region
22796 :for-ascii t
22797 :skip-before-1st-heading
22798 (plist-get opt-plist :skip-before-1st-heading)
22799 :archived-trees
22800 (plist-get opt-plist :archived-trees)
22801 :add-text (plist-get opt-plist :text))
22802 "\n"))
22803 thetoc have-headings first-heading-pos
22804 table-open table-buffer)
22806 (let ((inhibit-read-only t))
22807 (org-unmodified
22808 (remove-text-properties (point-min) (point-max)
22809 '(:org-license-to-kill t))))
22811 (setq org-min-level (org-get-min-level lines))
22812 (setq org-last-level org-min-level)
22813 (org-init-section-numbers)
22815 (find-file-noselect filename)
22817 (setq lang-words (or (assoc language org-export-language-setup)
22818 (assoc "en" org-export-language-setup)))
22819 (switch-to-buffer-other-window buffer)
22820 (erase-buffer)
22821 (fundamental-mode)
22822 ;; create local variables for all options, to make sure all called
22823 ;; functions get the correct information
22824 (mapc (lambda (x)
22825 (set (make-local-variable (cdr x))
22826 (plist-get opt-plist (car x))))
22827 org-export-plist-vars)
22828 (org-set-local 'org-odd-levels-only odd)
22829 (setq umax (if arg (prefix-numeric-value arg)
22830 org-export-headline-levels))
22831 (setq umax-toc (if (integerp org-export-with-toc)
22832 (min org-export-with-toc umax)
22833 umax))
22835 ;; File header
22836 (if title (org-insert-centered title ?=))
22837 (insert "\n")
22838 (if (and (or author email)
22839 org-export-author-info)
22840 (insert (concat (nth 1 lang-words) ": " (or author "")
22841 (if email (concat " <" email ">") "")
22842 "\n")))
22844 (cond
22845 ((and date (string-match "%" date))
22846 (setq date (format-time-string date (current-time))))
22847 (date)
22848 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
22850 (if (and date org-export-time-stamp-file)
22851 (insert (concat (nth 2 lang-words) ": " date"\n")))
22853 (insert "\n\n")
22855 (if org-export-with-toc
22856 (progn
22857 (push (concat (nth 3 lang-words) "\n") thetoc)
22858 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
22859 (mapc '(lambda (line)
22860 (if (string-match org-todo-line-regexp
22861 line)
22862 ;; This is a headline
22863 (progn
22864 (setq have-headings t)
22865 (setq level (- (match-end 1) (match-beginning 1))
22866 level (org-tr-level level)
22867 txt (match-string 3 line)
22868 todo
22869 (or (and org-export-mark-todo-in-toc
22870 (match-beginning 2)
22871 (not (member (match-string 2 line)
22872 org-done-keywords)))
22873 ; TODO, not DONE
22874 (and org-export-mark-todo-in-toc
22875 (= level umax-toc)
22876 (org-search-todo-below
22877 line lines level))))
22878 (setq txt (org-html-expand-for-ascii txt))
22880 (while (string-match org-bracket-link-regexp txt)
22881 (setq txt
22882 (replace-match
22883 (match-string (if (match-end 2) 3 1) txt)
22884 t t txt)))
22886 (if (and (memq org-export-with-tags '(not-in-toc nil))
22887 (string-match
22888 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
22889 txt))
22890 (setq txt (replace-match "" t t txt)))
22891 (if (string-match quote-re0 txt)
22892 (setq txt (replace-match "" t t txt)))
22894 (if org-export-with-section-numbers
22895 (setq txt (concat (org-section-number level)
22896 " " txt)))
22897 (if (<= level umax-toc)
22898 (progn
22899 (push
22900 (concat
22901 (make-string
22902 (* (max 0 (- level org-min-level)) 4) ?\ )
22903 (format (if todo "%s (*)\n" "%s\n") txt))
22904 thetoc)
22905 (setq org-last-level level))
22906 ))))
22907 lines)
22908 (setq thetoc (if have-headings (nreverse thetoc) nil))))
22910 (org-init-section-numbers)
22911 (while (setq line (pop lines))
22912 ;; Remove the quoted HTML tags.
22913 (setq line (org-html-expand-for-ascii line))
22914 ;; Remove targets
22915 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
22916 (setq line (replace-match "" t t line)))
22917 ;; Replace internal links
22918 (while (string-match org-bracket-link-regexp line)
22919 (setq line (replace-match
22920 (if (match-end 3) "[\\3]" "[\\1]")
22921 t nil line)))
22922 (when custom-times
22923 (setq line (org-translate-time line)))
22924 (cond
22925 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
22926 ;; a Headline
22927 (setq first-heading-pos (or first-heading-pos (point)))
22928 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
22929 txt (match-string 2 line))
22930 (org-ascii-level-start level txt umax lines))
22932 ((and org-export-with-tables
22933 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
22934 (if (not table-open)
22935 ;; New table starts
22936 (setq table-open t table-buffer nil))
22937 ;; Accumulate lines
22938 (setq table-buffer (cons line table-buffer))
22939 (when (or (not lines)
22940 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
22941 (car lines))))
22942 (setq table-open nil
22943 table-buffer (nreverse table-buffer))
22944 (insert (mapconcat
22945 (lambda (x)
22946 (org-fix-indentation x org-ascii-current-indentation))
22947 (org-format-table-ascii table-buffer)
22948 "\n") "\n")))
22950 (setq line (org-fix-indentation line org-ascii-current-indentation))
22951 (if (and org-export-with-fixed-width
22952 (string-match "^\\([ \t]*\\)\\(:\\)" line))
22953 (setq line (replace-match "\\1" nil nil line)))
22954 (insert line "\n"))))
22956 (normal-mode)
22958 ;; insert the table of contents
22959 (when thetoc
22960 (goto-char (point-min))
22961 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
22962 (progn
22963 (goto-char (match-beginning 0))
22964 (replace-match ""))
22965 (goto-char first-heading-pos))
22966 (mapc 'insert thetoc)
22967 (or (looking-at "[ \t]*\n[ \t]*\n")
22968 (insert "\n\n")))
22970 ;; Convert whitespace place holders
22971 (goto-char (point-min))
22972 (let (beg end)
22973 (while (setq beg (next-single-property-change (point) 'org-whitespace))
22974 (setq end (next-single-property-change beg 'org-whitespace))
22975 (goto-char beg)
22976 (delete-region beg end)
22977 (insert (make-string (- end beg) ?\ ))))
22979 (save-buffer)
22980 ;; remove display and invisible chars
22981 (let (beg end)
22982 (goto-char (point-min))
22983 (while (setq beg (next-single-property-change (point) 'display))
22984 (setq end (next-single-property-change beg 'display))
22985 (delete-region beg end)
22986 (goto-char beg)
22987 (insert "=>"))
22988 (goto-char (point-min))
22989 (while (setq beg (next-single-property-change (point) 'org-cwidth))
22990 (setq end (next-single-property-change beg 'org-cwidth))
22991 (delete-region beg end)
22992 (goto-char beg)))
22993 (goto-char (point-min))))
22995 (defun org-search-todo-below (line lines level)
22996 "Search the subtree below LINE for any TODO entries."
22997 (let ((rest (cdr (memq line lines)))
22998 (re org-todo-line-regexp)
22999 line lv todo)
23000 (catch 'exit
23001 (while (setq line (pop rest))
23002 (if (string-match re line)
23003 (progn
23004 (setq lv (- (match-end 1) (match-beginning 1))
23005 todo (and (match-beginning 2)
23006 (not (member (match-string 2 line)
23007 org-done-keywords))))
23008 ; TODO, not DONE
23009 (if (<= lv level) (throw 'exit nil))
23010 (if todo (throw 'exit t))))))))
23012 (defun org-html-expand-for-ascii (line)
23013 "Handle quoted HTML for ASCII export."
23014 (if org-export-html-expand
23015 (while (string-match "@<[^<>\n]*>" line)
23016 ;; We just remove the tags for now.
23017 (setq line (replace-match "" nil nil line))))
23018 line)
23020 (defun org-insert-centered (s &optional underline)
23021 "Insert the string S centered and underline it with character UNDERLINE."
23022 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
23023 (insert (make-string ind ?\ ) s "\n")
23024 (if underline
23025 (insert (make-string ind ?\ )
23026 (make-string (string-width s) underline)
23027 "\n"))))
23029 (defun org-ascii-level-start (level title umax &optional lines)
23030 "Insert a new level in ASCII export."
23031 (let (char (n (- level umax 1)) (ind 0))
23032 (if (> level umax)
23033 (progn
23034 (insert (make-string (* 2 n) ?\ )
23035 (char-to-string (nth (% n (length org-export-ascii-bullets))
23036 org-export-ascii-bullets))
23037 " " title "\n")
23038 ;; find the indentation of the next non-empty line
23039 (catch 'stop
23040 (while lines
23041 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
23042 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
23043 (throw 'stop (setq ind (org-get-indentation (car lines)))))
23044 (pop lines)))
23045 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
23046 (if (or (not (equal (char-before) ?\n))
23047 (not (equal (char-before (1- (point))) ?\n)))
23048 (insert "\n"))
23049 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
23050 (unless org-export-with-tags
23051 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
23052 (setq title (replace-match "" t t title))))
23053 (if org-export-with-section-numbers
23054 (setq title (concat (org-section-number level) " " title)))
23055 (insert title "\n" (make-string (string-width title) char) "\n")
23056 (setq org-ascii-current-indentation '(0 . 0)))))
23058 (defun org-export-visible (type arg)
23059 "Create a copy of the visible part of the current buffer, and export it.
23060 The copy is created in a temporary buffer and removed after use.
23061 TYPE is the final key (as a string) that also select the export command in
23062 the `C-c C-e' export dispatcher.
23063 As a special case, if the you type SPC at the prompt, the temporary
23064 org-mode file will not be removed but presented to you so that you can
23065 continue to use it. The prefix arg ARG is passed through to the exporting
23066 command."
23067 (interactive
23068 (list (progn
23069 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
23070 (read-char-exclusive))
23071 current-prefix-arg))
23072 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
23073 (error "Invalid export key"))
23074 (let* ((binding (cdr (assoc type
23075 '((?a . org-export-as-ascii)
23076 (?\C-a . org-export-as-ascii)
23077 (?b . org-export-as-html-and-open)
23078 (?\C-b . org-export-as-html-and-open)
23079 (?h . org-export-as-html)
23080 (?H . org-export-as-html-to-buffer)
23081 (?R . org-export-region-as-html)
23082 (?x . org-export-as-xoxo)))))
23083 (keepp (equal type ?\ ))
23084 (file buffer-file-name)
23085 (buffer (get-buffer-create "*Org Export Visible*"))
23086 s e)
23087 ;; Need to hack the drawers here.
23088 (save-excursion
23089 (goto-char (point-min))
23090 (while (re-search-forward org-drawer-regexp nil t)
23091 (goto-char (match-beginning 1))
23092 (or (org-invisible-p) (org-flag-drawer nil))))
23093 (with-current-buffer buffer (erase-buffer))
23094 (save-excursion
23095 (setq s (goto-char (point-min)))
23096 (while (not (= (point) (point-max)))
23097 (goto-char (org-find-invisible))
23098 (append-to-buffer buffer s (point))
23099 (setq s (goto-char (org-find-visible))))
23100 (org-cycle-hide-drawers 'all)
23101 (goto-char (point-min))
23102 (unless keepp
23103 ;; Copy all comment lines to the end, to make sure #+ settings are
23104 ;; still available for the second export step. Kind of a hack, but
23105 ;; does do the trick.
23106 (if (looking-at "#[^\r\n]*")
23107 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
23108 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
23109 (append-to-buffer buffer (1+ (match-beginning 0))
23110 (min (point-max) (1+ (match-end 0))))))
23111 (set-buffer buffer)
23112 (let ((buffer-file-name file)
23113 (org-inhibit-startup t))
23114 (org-mode)
23115 (show-all)
23116 (unless keepp (funcall binding arg))))
23117 (if (not keepp)
23118 (kill-buffer buffer)
23119 (switch-to-buffer-other-window buffer)
23120 (goto-char (point-min)))))
23122 (defun org-find-visible ()
23123 (let ((s (point)))
23124 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
23125 (get-char-property s 'invisible)))
23127 (defun org-find-invisible ()
23128 (let ((s (point)))
23129 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
23130 (not (get-char-property s 'invisible))))
23133 ;;; HTML export
23135 (defun org-get-current-options ()
23136 "Return a string with current options as keyword options.
23137 Does include HTML export options as well as TODO and CATEGORY stuff."
23138 (format
23139 "#+TITLE: %s
23140 #+AUTHOR: %s
23141 #+EMAIL: %s
23142 #+LANGUAGE: %s
23143 #+TEXT: Some descriptive text to be emitted. Several lines OK.
23144 #+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
23145 #+CATEGORY: %s
23146 #+SEQ_TODO: %s
23147 #+TYP_TODO: %s
23148 #+PRIORITIES: %c %c %c
23149 #+DRAWERS: %s
23150 #+STARTUP: %s %s %s %s %s
23151 #+TAGS: %s
23152 #+ARCHIVE: %s
23153 #+LINK: %s
23155 (buffer-name) (user-full-name) user-mail-address org-export-default-language
23156 org-export-headline-levels
23157 org-export-with-section-numbers
23158 org-export-with-toc
23159 org-export-preserve-breaks
23160 org-export-html-expand
23161 org-export-with-fixed-width
23162 org-export-with-tables
23163 org-export-with-sub-superscripts
23164 org-export-with-footnotes
23165 org-export-with-emphasize
23166 org-export-with-TeX-macros
23167 org-export-with-LaTeX-fragments
23168 org-export-skip-text-before-1st-heading
23169 org-export-with-drawers
23170 org-export-with-tags
23171 (file-name-nondirectory buffer-file-name)
23172 "TODO FEEDBACK VERIFY DONE"
23173 "Me Jason Marie DONE"
23174 org-highest-priority org-lowest-priority org-default-priority
23175 (mapconcat 'identity org-drawers " ")
23176 (cdr (assoc org-startup-folded
23177 '((nil . "showall") (t . "overview") (content . "content"))))
23178 (if org-odd-levels-only "odd" "oddeven")
23179 (if org-hide-leading-stars "hidestars" "showstars")
23180 (if org-startup-align-all-tables "align" "noalign")
23181 (cond ((eq t org-log-done) "logdone")
23182 ((not org-log-done) "nologging")
23183 ((listp org-log-done)
23184 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
23185 org-log-done " ")))
23186 (or (mapconcat (lambda (x)
23187 (cond
23188 ((equal '(:startgroup) x) "{")
23189 ((equal '(:endgroup) x) "}")
23190 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
23191 (t (car x))))
23192 (or org-tag-alist (org-get-buffer-tags)) " ") "")
23193 org-archive-location
23194 "org file:~/org/%s.org"
23197 (defun org-insert-export-options-template ()
23198 "Insert into the buffer a template with information for exporting."
23199 (interactive)
23200 (if (not (bolp)) (newline))
23201 (let ((s (org-get-current-options)))
23202 (and (string-match "#\\+CATEGORY" s)
23203 (setq s (substring s 0 (match-beginning 0))))
23204 (insert s)))
23206 (defun org-toggle-fixed-width-section (arg)
23207 "Toggle the fixed-width export.
23208 If there is no active region, the QUOTE keyword at the current headline is
23209 inserted or removed. When present, it causes the text between this headline
23210 and the next to be exported as fixed-width text, and unmodified.
23211 If there is an active region, this command adds or removes a colon as the
23212 first character of this line. If the first character of a line is a colon,
23213 this line is also exported in fixed-width font."
23214 (interactive "P")
23215 (let* ((cc 0)
23216 (regionp (org-region-active-p))
23217 (beg (if regionp (region-beginning) (point)))
23218 (end (if regionp (region-end)))
23219 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
23220 (re "[ \t]*\\(:\\)")
23221 off)
23222 (if regionp
23223 (save-excursion
23224 (goto-char beg)
23225 (setq cc (current-column))
23226 (beginning-of-line 1)
23227 (setq off (looking-at re))
23228 (while (> nlines 0)
23229 (setq nlines (1- nlines))
23230 (beginning-of-line 1)
23231 (cond
23232 (arg
23233 (move-to-column cc t)
23234 (insert ":\n")
23235 (forward-line -1))
23236 ((and off (looking-at re))
23237 (replace-match "" t t nil 1))
23238 ((not off) (move-to-column cc t) (insert ":")))
23239 (forward-line 1)))
23240 (save-excursion
23241 (org-back-to-heading)
23242 (if (looking-at (concat outline-regexp
23243 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
23244 (replace-match "" t t nil 1)
23245 (if (looking-at outline-regexp)
23246 (progn
23247 (goto-char (match-end 0))
23248 (insert org-quote-string " "))))))))
23250 (defun org-export-as-html-and-open (arg)
23251 "Export the outline as HTML and immediately open it with a browser.
23252 If there is an active region, export only the region.
23253 The prefix ARG specifies how many levels of the outline should become
23254 headlines. The default is 3. Lower levels will become bulleted lists."
23255 (interactive "P")
23256 (org-export-as-html arg 'hidden)
23257 (org-open-file buffer-file-name))
23259 (defun org-export-as-html-batch ()
23260 "Call `org-export-as-html', may be used in batch processing as
23261 emacs --batch
23262 --load=$HOME/lib/emacs/org.el
23263 --eval \"(setq org-export-headline-levels 2)\"
23264 --visit=MyFile --funcall org-export-as-html-batch"
23265 (org-export-as-html org-export-headline-levels 'hidden))
23267 (defun org-export-as-html-to-buffer (arg)
23268 "Call `org-exort-as-html` with output to a temporary buffer.
23269 No file is created. The prefix ARG is passed through to `org-export-as-html'."
23270 (interactive "P")
23271 (org-export-as-html arg nil nil "*Org HTML Export*")
23272 (switch-to-buffer-other-window "*Org HTML Export*"))
23274 (defun org-replace-region-by-html (beg end)
23275 "Assume the current region has org-mode syntax, and convert it to HTML.
23276 This can be used in any buffer. For example, you could write an
23277 itemized list in org-mode syntax in an HTML buffer and then use this
23278 command to convert it."
23279 (interactive "r")
23280 (let (reg html buf pop-up-frames)
23281 (save-window-excursion
23282 (if (org-mode-p)
23283 (setq html (org-export-region-as-html
23284 beg end t 'string))
23285 (setq reg (buffer-substring beg end)
23286 buf (get-buffer-create "*Org tmp*"))
23287 (with-current-buffer buf
23288 (erase-buffer)
23289 (insert reg)
23290 (org-mode)
23291 (setq html (org-export-region-as-html
23292 (point-min) (point-max) t 'string)))
23293 (kill-buffer buf)))
23294 (delete-region beg end)
23295 (insert html)))
23297 (defun org-export-region-as-html (beg end &optional body-only buffer)
23298 "Convert region from BEG to END in org-mode buffer to HTML.
23299 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
23300 contents, and only produce the region of converted text, useful for
23301 cut-and-paste operations.
23302 If BUFFER is a buffer or a string, use/create that buffer as a target
23303 of the converted HTML. If BUFFER is the symbol `string', return the
23304 produced HTML as a string and leave not buffer behind. For example,
23305 a Lisp program could call this function in the following way:
23307 (setq html (org-export-region-as-html beg end t 'string))
23309 When called interactively, the output buffer is selected, and shown
23310 in a window. A non-interactive call will only retunr the buffer."
23311 (interactive "r\nP")
23312 (when (interactive-p)
23313 (setq buffer "*Org HTML Export*"))
23314 (let ((transient-mark-mode t) (zmacs-regions t)
23315 rtn)
23316 (goto-char end)
23317 (set-mark (point)) ;; to activate the region
23318 (goto-char beg)
23319 (setq rtn (org-export-as-html
23320 nil nil nil
23321 buffer body-only))
23322 (if (fboundp 'deactivate-mark) (deactivate-mark))
23323 (if (and (interactive-p) (bufferp rtn))
23324 (switch-to-buffer-other-window rtn)
23325 rtn)))
23327 (defun org-export-as-html (arg &optional hidden ext-plist
23328 to-buffer body-only)
23329 "Export the outline as a pretty HTML file.
23330 If there is an active region, export only the region. The prefix
23331 ARG specifies how many levels of the outline should become
23332 headlines. The default is 3. Lower levels will become bulleted
23333 lists. When HIDDEN is non-nil, don't display the HTML buffer.
23334 EXT-PLIST is a property list with external parameters overriding
23335 org-mode's default settings, but still inferior to file-local
23336 settings. When TO-BUFFER is non-nil, create a buffer with that
23337 name and export to that buffer. If TO-BUFFER is the symbol `string',
23338 don't leave any buffer behind but just return the resulting HTML as
23339 a string. When BODY-ONLY is set, don't produce the file header and footer,
23340 simply return the content of <body>...</body>, without even
23341 the body tags themselves."
23342 (interactive "P")
23344 ;; Make sure we have a file name when we need it.
23345 (when (and (not (or to-buffer body-only))
23346 (not buffer-file-name))
23347 (if (buffer-base-buffer)
23348 (org-set-local 'buffer-file-name
23349 (with-current-buffer (buffer-base-buffer)
23350 buffer-file-name))
23351 (error "Need a file name to be able to export.")))
23353 (message "Exporting...")
23354 (setq-default org-todo-line-regexp org-todo-line-regexp)
23355 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
23356 (setq-default org-done-keywords org-done-keywords)
23357 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
23358 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
23359 ext-plist
23360 (org-infile-export-plist)))
23362 (style (plist-get opt-plist :style))
23363 (link-validate (plist-get opt-plist :link-validation-function))
23364 valid thetoc have-headings first-heading-pos
23365 (odd org-odd-levels-only)
23366 (region-p (org-region-active-p))
23367 (subtree-p
23368 (when region-p
23369 (save-excursion
23370 (goto-char (region-beginning))
23371 (and (org-at-heading-p)
23372 (>= (org-end-of-subtree t t) (region-end))))))
23373 ;; The following two are dynamically scoped into other
23374 ;; routines below.
23375 (org-current-export-dir (org-export-directory :html opt-plist))
23376 (org-current-export-file buffer-file-name)
23377 (level 0) (line "") (origline "") txt todo
23378 (umax nil)
23379 (umax-toc nil)
23380 (filename (if to-buffer nil
23381 (concat (file-name-as-directory
23382 (org-export-directory :html opt-plist))
23383 (file-name-sans-extension
23384 (or (and subtree-p
23385 (org-entry-get (region-beginning)
23386 "EXPORT_FILE_NAME" t))
23387 (file-name-nondirectory buffer-file-name)))
23388 "." org-export-html-extension)))
23389 (current-dir (if buffer-file-name
23390 (file-name-directory buffer-file-name)
23391 default-directory))
23392 (buffer (if to-buffer
23393 (cond
23394 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
23395 (t (get-buffer-create to-buffer)))
23396 (find-file-noselect filename)))
23397 (org-levels-open (make-vector org-level-max nil))
23398 (date (plist-get opt-plist :date))
23399 (author (plist-get opt-plist :author))
23400 (title (or (and subtree-p (org-export-get-title-from-subtree))
23401 (plist-get opt-plist :title)
23402 (and (not
23403 (plist-get opt-plist :skip-before-1st-heading))
23404 (org-export-grab-title-from-buffer))
23405 (and buffer-file-name
23406 (file-name-sans-extension
23407 (file-name-nondirectory buffer-file-name)))
23408 "UNTITLED"))
23409 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
23410 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
23411 (inquote nil)
23412 (infixed nil)
23413 (in-local-list nil)
23414 (local-list-num nil)
23415 (local-list-indent nil)
23416 (llt org-plain-list-ordered-item-terminator)
23417 (email (plist-get opt-plist :email))
23418 (language (plist-get opt-plist :language))
23419 (lang-words nil)
23420 (target-alist nil) tg
23421 (head-count 0) cnt
23422 (start 0)
23423 (coding-system (and (boundp 'buffer-file-coding-system)
23424 buffer-file-coding-system))
23425 (coding-system-for-write (or org-export-html-coding-system
23426 coding-system))
23427 (save-buffer-coding-system (or org-export-html-coding-system
23428 coding-system))
23429 (charset (and coding-system-for-write
23430 (fboundp 'coding-system-get)
23431 (coding-system-get coding-system-for-write
23432 'mime-charset)))
23433 (region
23434 (buffer-substring
23435 (if region-p (region-beginning) (point-min))
23436 (if region-p (region-end) (point-max))))
23437 (lines
23438 (org-split-string
23439 (org-cleaned-string-for-export
23440 region
23441 :emph-multiline t
23442 :for-html t
23443 :skip-before-1st-heading
23444 (plist-get opt-plist :skip-before-1st-heading)
23445 :archived-trees
23446 (plist-get opt-plist :archived-trees)
23447 :add-text
23448 (plist-get opt-plist :text)
23449 :LaTeX-fragments
23450 (plist-get opt-plist :LaTeX-fragments))
23451 "[\r\n]"))
23452 table-open type
23453 table-buffer table-orig-buffer
23454 ind start-is-num starter didclose
23455 rpl path desc descp desc1 desc2 link
23458 (let ((inhibit-read-only t))
23459 (org-unmodified
23460 (remove-text-properties (point-min) (point-max)
23461 '(:org-license-to-kill t))))
23463 (message "Exporting...")
23465 (setq org-min-level (org-get-min-level lines))
23466 (setq org-last-level org-min-level)
23467 (org-init-section-numbers)
23469 (cond
23470 ((and date (string-match "%" date))
23471 (setq date (format-time-string date (current-time))))
23472 (date)
23473 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
23475 ;; Get the language-dependent settings
23476 (setq lang-words (or (assoc language org-export-language-setup)
23477 (assoc "en" org-export-language-setup)))
23479 ;; Switch to the output buffer
23480 (set-buffer buffer)
23481 (erase-buffer)
23482 (fundamental-mode)
23484 (and (fboundp 'set-buffer-file-coding-system)
23485 (set-buffer-file-coding-system coding-system-for-write))
23487 (let ((case-fold-search nil)
23488 (org-odd-levels-only odd))
23489 ;; create local variables for all options, to make sure all called
23490 ;; functions get the correct information
23491 (mapc (lambda (x)
23492 (set (make-local-variable (cdr x))
23493 (plist-get opt-plist (car x))))
23494 org-export-plist-vars)
23495 (setq umax (if arg (prefix-numeric-value arg)
23496 org-export-headline-levels))
23497 (setq umax-toc (if (integerp org-export-with-toc)
23498 (min org-export-with-toc umax)
23499 umax))
23500 (unless body-only
23501 ;; File header
23502 (insert (format
23503 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
23504 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
23505 <html xmlns=\"http://www.w3.org/1999/xhtml\"
23506 lang=\"%s\" xml:lang=\"%s\">
23507 <head>
23508 <title>%s</title>
23509 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
23510 <meta name=\"generator\" content=\"Org-mode\"/>
23511 <meta name=\"generated\" content=\"%s\"/>
23512 <meta name=\"author\" content=\"%s\"/>
23514 </head><body>
23516 language language (org-html-expand title)
23517 (or charset "iso-8859-1") date author style))
23519 (insert (or (plist-get opt-plist :preamble) ""))
23521 (when (plist-get opt-plist :auto-preamble)
23522 (if title (insert (format org-export-html-title-format
23523 (org-html-expand title))))))
23525 (if (and org-export-with-toc (not body-only))
23526 (progn
23527 (push (format "<h%d>%s</h%d>\n"
23528 org-export-html-toplevel-hlevel
23529 (nth 3 lang-words)
23530 org-export-html-toplevel-hlevel)
23531 thetoc)
23532 (push "<ul>\n<li>" thetoc)
23533 (setq lines
23534 (mapcar '(lambda (line)
23535 (if (string-match org-todo-line-regexp line)
23536 ;; This is a headline
23537 (progn
23538 (setq have-headings t)
23539 (setq level (- (match-end 1) (match-beginning 1))
23540 level (org-tr-level level)
23541 txt (save-match-data
23542 (org-html-expand
23543 (org-export-cleanup-toc-line
23544 (match-string 3 line))))
23545 todo
23546 (or (and org-export-mark-todo-in-toc
23547 (match-beginning 2)
23548 (not (member (match-string 2 line)
23549 org-done-keywords)))
23550 ; TODO, not DONE
23551 (and org-export-mark-todo-in-toc
23552 (= level umax-toc)
23553 (org-search-todo-below
23554 line lines level))))
23555 (if (string-match
23556 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
23557 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
23558 (if (string-match quote-re0 txt)
23559 (setq txt (replace-match "" t t txt)))
23560 (if org-export-with-section-numbers
23561 (setq txt (concat (org-section-number level)
23562 " " txt)))
23563 (if (<= level (max umax umax-toc))
23564 (setq head-count (+ head-count 1)))
23565 (if (<= level umax-toc)
23566 (progn
23567 (if (> level org-last-level)
23568 (progn
23569 (setq cnt (- level org-last-level))
23570 (while (>= (setq cnt (1- cnt)) 0)
23571 (push "\n<ul>\n<li>" thetoc))
23572 (push "\n" thetoc)))
23573 (if (< level org-last-level)
23574 (progn
23575 (setq cnt (- org-last-level level))
23576 (while (>= (setq cnt (1- cnt)) 0)
23577 (push "</li>\n</ul>" thetoc))
23578 (push "\n" thetoc)))
23579 ;; Check for targets
23580 (while (string-match org-target-regexp line)
23581 (setq tg (match-string 1 line)
23582 line (replace-match
23583 (concat "@<span class=\"target\">" tg "@</span> ")
23584 t t line))
23585 (push (cons (org-solidify-link-text tg)
23586 (format "sec-%d" head-count))
23587 target-alist))
23588 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
23589 (setq txt (replace-match "" t t txt)))
23590 (push
23591 (format
23592 (if todo
23593 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
23594 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
23595 head-count txt) thetoc)
23597 (setq org-last-level level))
23599 line)
23600 lines))
23601 (while (> org-last-level (1- org-min-level))
23602 (setq org-last-level (1- org-last-level))
23603 (push "</li>\n</ul>\n" thetoc))
23604 (setq thetoc (if have-headings (nreverse thetoc) nil))))
23606 (setq head-count 0)
23607 (org-init-section-numbers)
23609 (while (setq line (pop lines) origline line)
23610 (catch 'nextline
23612 ;; end of quote section?
23613 (when (and inquote (string-match "^\\*+ " line))
23614 (insert "</pre>\n")
23615 (setq inquote nil))
23616 ;; inside a quote section?
23617 (when inquote
23618 (insert (org-html-protect line) "\n")
23619 (throw 'nextline nil))
23621 ;; verbatim lines
23622 (when (and org-export-with-fixed-width
23623 (string-match "^[ \t]*:\\(.*\\)" line))
23624 (when (not infixed)
23625 (setq infixed t)
23626 (insert "<pre>\n"))
23627 (insert (org-html-protect (match-string 1 line)) "\n")
23628 (when (and lines
23629 (not (string-match "^[ \t]*\\(:.*\\)"
23630 (car lines))))
23631 (setq infixed nil)
23632 (insert "</pre>\n"))
23633 (throw 'nextline nil))
23635 ;; Protected HTML
23636 (when (get-text-property 0 'org-protected line)
23637 (let (par)
23638 (when (re-search-backward
23639 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
23640 (setq par (match-string 1))
23641 (replace-match "\\2\n"))
23642 (insert line "\n")
23643 (while (and lines
23644 (get-text-property 0 'org-protected (car lines)))
23645 (insert (pop lines) "\n"))
23646 (and par (insert "<p>\n")))
23647 (throw 'nextline nil))
23649 ;; Horizontal line
23650 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
23651 (insert "\n<hr/>\n")
23652 (throw 'nextline nil))
23654 ;; make targets to anchors
23655 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
23656 (cond
23657 ((match-end 2)
23658 (setq line (replace-match
23659 (concat "@<a name=\""
23660 (org-solidify-link-text (match-string 1 line))
23661 "\">\\nbsp@</a>")
23662 t t line)))
23663 ((and org-export-with-toc (equal (string-to-char line) ?*))
23664 (setq line (replace-match
23665 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
23666 ; (concat "@<i>" (match-string 1 line) "@</i> ")
23667 t t line)))
23669 (setq line (replace-match
23670 (concat "@<a name=\""
23671 (org-solidify-link-text (match-string 1 line))
23672 "\" class=\"target\">" (match-string 1 line) "@</a> ")
23673 t t line)))))
23675 (setq line (org-html-handle-time-stamps line))
23677 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
23678 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
23679 ;; Also handle sub_superscripts and checkboxes
23680 (setq line (org-html-expand line))
23682 ;; Format the links
23683 (setq start 0)
23684 (while (string-match org-bracket-link-analytic-regexp line start)
23685 (setq start (match-beginning 0))
23686 (setq type (if (match-end 2) (match-string 2 line) "internal"))
23687 (setq path (match-string 3 line))
23688 (setq desc1 (if (match-end 5) (match-string 5 line))
23689 desc2 (if (match-end 2) (concat type ":" path) path)
23690 descp (and desc1 (not (equal desc1 desc2)))
23691 desc (or desc1 desc2))
23692 ;; Make an image out of the description if that is so wanted
23693 (when (and descp (org-file-image-p desc))
23694 (save-match-data
23695 (if (string-match "^file:" desc)
23696 (setq desc (substring desc (match-end 0)))))
23697 (setq desc (concat "<img src=\"" desc "\"/>")))
23698 ;; FIXME: do we need to unescape here somewhere?
23699 (cond
23700 ((equal type "internal")
23701 (setq rpl
23702 (concat
23703 "<a href=\"#"
23704 (org-solidify-link-text
23705 (save-match-data (org-link-unescape path)) target-alist)
23706 "\">" desc "</a>")))
23707 ((member type '("http" "https"))
23708 ;; standard URL, just check if we need to inline an image
23709 (if (and (or (eq t org-export-html-inline-images)
23710 (and org-export-html-inline-images (not descp)))
23711 (org-file-image-p path))
23712 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
23713 (setq link (concat type ":" path))
23714 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
23715 ((member type '("ftp" "mailto" "news"))
23716 ;; standard URL
23717 (setq link (concat type ":" path))
23718 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
23719 ((string= type "file")
23720 ;; FILE link
23721 (let* ((filename path)
23722 (abs-p (file-name-absolute-p filename))
23723 thefile file-is-image-p search)
23724 (save-match-data
23725 (if (string-match "::\\(.*\\)" filename)
23726 (setq search (match-string 1 filename)
23727 filename (replace-match "" t nil filename)))
23728 (setq valid
23729 (if (functionp link-validate)
23730 (funcall link-validate filename current-dir)
23732 (setq file-is-image-p (org-file-image-p filename))
23733 (setq thefile (if abs-p (expand-file-name filename) filename))
23734 (when (and org-export-html-link-org-files-as-html
23735 (string-match "\\.org$" thefile))
23736 (setq thefile (concat (substring thefile 0
23737 (match-beginning 0))
23738 "." org-export-html-extension))
23739 (if (and search
23740 ;; make sure this is can be used as target search
23741 (not (string-match "^[0-9]*$" search))
23742 (not (string-match "^\\*" search))
23743 (not (string-match "^/.*/$" search)))
23744 (setq thefile (concat thefile "#"
23745 (org-solidify-link-text
23746 (org-link-unescape search)))))
23747 (when (string-match "^file:" desc)
23748 (setq desc (replace-match "" t t desc))
23749 (if (string-match "\\.org$" desc)
23750 (setq desc (replace-match "" t t desc))))))
23751 (setq rpl (if (and file-is-image-p
23752 (or (eq t org-export-html-inline-images)
23753 (and org-export-html-inline-images
23754 (not descp))))
23755 (concat "<img src=\"" thefile "\"/>")
23756 (concat "<a href=\"" thefile "\">" desc "</a>")))
23757 (if (not valid) (setq rpl desc))))
23758 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
23759 (setq rpl (concat "<i>&lt;" type ":"
23760 (save-match-data (org-link-unescape path))
23761 "&gt;</i>"))))
23762 (setq line (replace-match rpl t t line)
23763 start (+ start (length rpl))))
23765 ;; TODO items
23766 (if (and (string-match org-todo-line-regexp line)
23767 (match-beginning 2))
23769 (setq line
23770 (concat (substring line 0 (match-beginning 2))
23771 "<span class=\""
23772 (if (member (match-string 2 line)
23773 org-done-keywords)
23774 "done" "todo")
23775 "\">" (match-string 2 line)
23776 "</span>" (substring line (match-end 2)))))
23778 ;; Does this contain a reference to a footnote?
23779 (when org-export-with-footnotes
23780 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line)
23781 (let ((n (match-string 2 line)))
23782 (setq line
23783 (replace-match
23784 (format
23785 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
23786 (match-string 1 line) n n n)
23787 t t line)))))
23789 (cond
23790 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
23791 ;; This is a headline
23792 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
23793 txt (match-string 2 line))
23794 (if (string-match quote-re0 txt)
23795 (setq txt (replace-match "" t t txt)))
23796 (if (<= level (max umax umax-toc))
23797 (setq head-count (+ head-count 1)))
23798 (when in-local-list
23799 ;; Close any local lists before inserting a new header line
23800 (while local-list-num
23801 (org-close-li)
23802 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
23803 (pop local-list-num))
23804 (setq local-list-indent nil
23805 in-local-list nil))
23806 (setq first-heading-pos (or first-heading-pos (point)))
23807 (org-html-level-start level txt umax
23808 (and org-export-with-toc (<= level umax))
23809 head-count)
23810 ;; QUOTES
23811 (when (string-match quote-re line)
23812 (insert "<pre>")
23813 (setq inquote t)))
23815 ((and org-export-with-tables
23816 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
23817 (if (not table-open)
23818 ;; New table starts
23819 (setq table-open t table-buffer nil table-orig-buffer nil))
23820 ;; Accumulate lines
23821 (setq table-buffer (cons line table-buffer)
23822 table-orig-buffer (cons origline table-orig-buffer))
23823 (when (or (not lines)
23824 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
23825 (car lines))))
23826 (setq table-open nil
23827 table-buffer (nreverse table-buffer)
23828 table-orig-buffer (nreverse table-orig-buffer))
23829 (org-close-par-maybe)
23830 (insert (org-format-table-html table-buffer table-orig-buffer))))
23832 ;; Normal lines
23833 (when (string-match
23834 (cond
23835 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
23836 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
23837 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
23838 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
23839 line)
23840 (setq ind (org-get-string-indentation line)
23841 start-is-num (match-beginning 4)
23842 starter (if (match-beginning 2)
23843 (substring (match-string 2 line) 0 -1))
23844 line (substring line (match-beginning 5)))
23845 (unless (string-match "[^ \t]" line)
23846 ;; empty line. Pretend indentation is large.
23847 (setq ind (if org-empty-line-terminates-plain-lists
23849 (1+ (or (car local-list-indent) 1)))))
23850 (setq didclose nil)
23851 (while (and in-local-list
23852 (or (and (= ind (car local-list-indent))
23853 (not starter))
23854 (< ind (car local-list-indent))))
23855 (setq didclose t)
23856 (org-close-li)
23857 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
23858 (pop local-list-num) (pop local-list-indent)
23859 (setq in-local-list local-list-indent))
23860 (cond
23861 ((and starter
23862 (or (not in-local-list)
23863 (> ind (car local-list-indent))))
23864 ;; Start new (level of) list
23865 (org-close-par-maybe)
23866 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
23867 (push start-is-num local-list-num)
23868 (push ind local-list-indent)
23869 (setq in-local-list t))
23870 (starter
23871 ;; continue current list
23872 (org-close-li)
23873 (insert "<li>\n"))
23874 (didclose
23875 ;; we did close a list, normal text follows: need <p>
23876 (org-open-par)))
23877 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
23878 (setq line
23879 (replace-match
23880 (if (equal (match-string 1 line) "X")
23881 "<b>[X]</b>"
23882 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
23883 t t line))))
23885 ;; Empty lines start a new paragraph. If hand-formatted lists
23886 ;; are not fully interpreted, lines starting with "-", "+", "*"
23887 ;; also start a new paragraph.
23888 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
23890 ;; Is this the start of a footnote?
23891 (when org-export-with-footnotes
23892 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
23893 (org-close-par-maybe)
23894 (let ((n (match-string 1 line)))
23895 (setq line (replace-match
23896 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
23898 ;; Check if the line break needs to be conserved
23899 (cond
23900 ((string-match "\\\\\\\\[ \t]*$" line)
23901 (setq line (replace-match "<br/>" t t line)))
23902 (org-export-preserve-breaks
23903 (setq line (concat line "<br/>"))))
23905 (insert line "\n")))))
23907 ;; Properly close all local lists and other lists
23908 (when inquote (insert "</pre>\n"))
23909 (when in-local-list
23910 ;; Close any local lists before inserting a new header line
23911 (while local-list-num
23912 (org-close-li)
23913 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
23914 (pop local-list-num))
23915 (setq local-list-indent nil
23916 in-local-list nil))
23917 (org-html-level-start 0 nil umax
23918 (and org-export-with-toc (<= level umax))
23919 head-count)
23921 (unless body-only
23922 (when (plist-get opt-plist :auto-postamble)
23923 (insert "<div id=\"postamble\">")
23924 (when (and org-export-author-info author)
23925 (insert "<p class=\"author\"> "
23926 (nth 1 lang-words) ": " author "\n")
23927 (when email
23928 (insert "<a href=\"mailto:" email "\">&lt;"
23929 email "&gt;</a>\n"))
23930 (insert "</p>\n"))
23931 (when (and date org-export-time-stamp-file)
23932 (insert "<p class=\"date\"> "
23933 (nth 2 lang-words) ": "
23934 date "</p>\n"))
23935 (insert "</div>"))
23937 (if org-export-html-with-timestamp
23938 (insert org-export-html-html-helper-timestamp))
23939 (insert (or (plist-get opt-plist :postamble) ""))
23940 (insert "</body>\n</html>\n"))
23942 (normal-mode)
23943 (if (eq major-mode default-major-mode) (html-mode))
23945 ;; insert the table of contents
23946 (goto-char (point-min))
23947 (when thetoc
23948 (if (or (re-search-forward
23949 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
23950 (re-search-forward
23951 "\\[TABLE-OF-CONTENTS\\]" nil t))
23952 (progn
23953 (goto-char (match-beginning 0))
23954 (replace-match ""))
23955 (goto-char first-heading-pos)
23956 (when (looking-at "\\s-*</p>")
23957 (goto-char (match-end 0))
23958 (insert "\n")))
23959 (insert "<div id=\"table-of-contents\">\n")
23960 (mapc 'insert thetoc)
23961 (insert "</div>\n"))
23962 ;; remove empty paragraphs and lists
23963 (goto-char (point-min))
23964 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
23965 (replace-match ""))
23966 (goto-char (point-min))
23967 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
23968 (replace-match ""))
23969 ;; Convert whitespace place holders
23970 (goto-char (point-min))
23971 (let (beg end n)
23972 (while (setq beg (next-single-property-change (point) 'org-whitespace))
23973 (setq n (get-text-property beg 'org-whitespace)
23974 end (next-single-property-change beg 'org-whitespace))
23975 (goto-char beg)
23976 (delete-region beg end)
23977 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
23978 (make-string n ?x)))))
23980 (or to-buffer (save-buffer))
23981 (goto-char (point-min))
23982 (message "Exporting... done")
23983 (if (eq to-buffer 'string)
23984 (prog1 (buffer-substring (point-min) (point-max))
23985 (kill-buffer (current-buffer)))
23986 (current-buffer)))))
23988 (defvar org-table-colgroup-info nil)
23989 (defun org-format-table-ascii (lines)
23990 "Format a table for ascii export."
23991 (if (stringp lines)
23992 (setq lines (org-split-string lines "\n")))
23993 (if (not (string-match "^[ \t]*|" (car lines)))
23994 ;; Table made by table.el - test for spanning
23995 lines
23997 ;; A normal org table
23998 ;; Get rid of hlines at beginning and end
23999 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
24000 (setq lines (nreverse lines))
24001 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
24002 (setq lines (nreverse lines))
24003 (when org-export-table-remove-special-lines
24004 ;; Check if the table has a marking column. If yes remove the
24005 ;; column and the special lines
24006 (setq lines (org-table-clean-before-export lines)))
24007 ;; Get rid of the vertical lines except for grouping
24008 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
24009 rtn line vl1 start)
24010 (while (setq line (pop lines))
24011 (if (string-match org-table-hline-regexp line)
24012 (and (string-match "|\\(.*\\)|" line)
24013 (setq line (replace-match " \\1" t nil line)))
24014 (setq start 0 vl1 vl)
24015 (while (string-match "|" line start)
24016 (setq start (match-end 0))
24017 (or (pop vl1) (setq line (replace-match " " t t line)))))
24018 (push line rtn))
24019 (nreverse rtn))))
24021 (defun org-colgroup-info-to-vline-list (info)
24022 (let (vl new last)
24023 (while info
24024 (setq last new new (pop info))
24025 (if (or (memq last '(:end :startend))
24026 (memq new '(:start :startend)))
24027 (push t vl)
24028 (push nil vl)))
24029 (setq vl (nreverse vl))
24030 (and vl (setcar vl nil))
24031 vl))
24033 (defun org-format-table-html (lines olines)
24034 "Find out which HTML converter to use and return the HTML code."
24035 (if (stringp lines)
24036 (setq lines (org-split-string lines "\n")))
24037 (if (string-match "^[ \t]*|" (car lines))
24038 ;; A normal org table
24039 (org-format-org-table-html lines)
24040 ;; Table made by table.el - test for spanning
24041 (let* ((hlines (delq nil (mapcar
24042 (lambda (x)
24043 (if (string-match "^[ \t]*\\+-" x) x
24044 nil))
24045 lines)))
24046 (first (car hlines))
24047 (ll (and (string-match "\\S-+" first)
24048 (match-string 0 first)))
24049 (re (concat "^[ \t]*" (regexp-quote ll)))
24050 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
24051 hlines))))
24052 (if (and (not spanning)
24053 (not org-export-prefer-native-exporter-for-tables))
24054 ;; We can use my own converter with HTML conversions
24055 (org-format-table-table-html lines)
24056 ;; Need to use the code generator in table.el, with the original text.
24057 (org-format-table-table-html-using-table-generate-source olines)))))
24059 (defun org-format-org-table-html (lines &optional splice)
24060 "Format a table into HTML."
24061 ;; Get rid of hlines at beginning and end
24062 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
24063 (setq lines (nreverse lines))
24064 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
24065 (setq lines (nreverse lines))
24066 (when org-export-table-remove-special-lines
24067 ;; Check if the table has a marking column. If yes remove the
24068 ;; column and the special lines
24069 (setq lines (org-table-clean-before-export lines)))
24071 (let ((head (and org-export-highlight-first-table-line
24072 (delq nil (mapcar
24073 (lambda (x) (string-match "^[ \t]*|-" x))
24074 (cdr lines)))))
24075 (nlines 0) fnum i
24076 tbopen line fields html gr colgropen)
24077 (if splice (setq head nil))
24078 (unless splice (push (if head "<thead>" "<tbody>") html))
24079 (setq tbopen t)
24080 (while (setq line (pop lines))
24081 (catch 'next-line
24082 (if (string-match "^[ \t]*|-" line)
24083 (progn
24084 (unless splice
24085 (push (if head "</thead>" "</tbody>") html)
24086 (if lines (push "<tbody>" html) (setq tbopen nil)))
24087 (setq head nil) ;; head ends here, first time around
24088 ;; ignore this line
24089 (throw 'next-line t)))
24090 ;; Break the line into fields
24091 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
24092 (unless fnum (setq fnum (make-vector (length fields) 0)))
24093 (setq nlines (1+ nlines) i -1)
24094 (push (concat "<tr>"
24095 (mapconcat
24096 (lambda (x)
24097 (setq i (1+ i))
24098 (if (and (< i nlines)
24099 (string-match org-table-number-regexp x))
24100 (incf (aref fnum i)))
24101 (if head
24102 (concat (car org-export-table-header-tags) x
24103 (cdr org-export-table-header-tags))
24104 (concat (car org-export-table-data-tags) x
24105 (cdr org-export-table-data-tags))))
24106 fields "")
24107 "</tr>")
24108 html)))
24109 (unless splice (if tbopen (push "</tbody>" html)))
24110 (unless splice (push "</table>\n" html))
24111 (setq html (nreverse html))
24112 (unless splice
24113 ;; Put in COL tags with the alignment (unfortuntely often ignored...)
24114 (push (mapconcat
24115 (lambda (x)
24116 (setq gr (pop org-table-colgroup-info))
24117 (format "%s<COL align=\"%s\"></COL>%s"
24118 (if (memq gr '(:start :startend))
24119 (prog1
24120 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
24121 (setq colgropen t))
24123 (if (> (/ (float x) nlines) org-table-number-fraction)
24124 "right" "left")
24125 (if (memq gr '(:end :startend))
24126 (progn (setq colgropen nil) "</colgroup>")
24127 "")))
24128 fnum "")
24129 html)
24130 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
24131 (push org-export-html-table-tag html))
24132 (concat (mapconcat 'identity html "\n") "\n")))
24134 (defun org-table-clean-before-export (lines)
24135 "Check if the table has a marking column.
24136 If yes remove the column and the special lines."
24137 (setq org-table-colgroup-info nil)
24138 (if (memq nil
24139 (mapcar
24140 (lambda (x) (or (string-match "^[ \t]*|-" x)
24141 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
24142 lines))
24143 (progn
24144 (setq org-table-clean-did-remove-column nil)
24145 (delq nil
24146 (mapcar
24147 (lambda (x)
24148 (cond
24149 ((string-match "^[ \t]*| */ *|" x)
24150 (setq org-table-colgroup-info
24151 (mapcar (lambda (x)
24152 (cond ((member x '("<" "&lt;")) :start)
24153 ((member x '(">" "&gt;")) :end)
24154 ((member x '("<>" "&lt;&gt;")) :startend)
24155 (t nil)))
24156 (org-split-string x "[ \t]*|[ \t]*")))
24157 nil)
24158 (t x)))
24159 lines)))
24160 (setq org-table-clean-did-remove-column t)
24161 (delq nil
24162 (mapcar
24163 (lambda (x)
24164 (cond
24165 ((string-match "^[ \t]*| */ *|" x)
24166 (setq org-table-colgroup-info
24167 (mapcar (lambda (x)
24168 (cond ((member x '("<" "&lt;")) :start)
24169 ((member x '(">" "&gt;")) :end)
24170 ((member x '("<>" "&lt;&gt;")) :startend)
24171 (t nil)))
24172 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
24173 nil)
24174 ((string-match "^[ \t]*| *[!_^/] *|" x)
24175 nil) ; ignore this line
24176 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
24177 (string-match "^\\([ \t]*\\)|[^|]*|" x))
24178 ;; remove the first column
24179 (replace-match "\\1|" t nil x))
24180 (t (error "This should not happen"))))
24181 lines))))
24183 (defun org-format-table-table-html (lines)
24184 "Format a table generated by table.el into HTML.
24185 This conversion does *not* use `table-generate-source' from table.el.
24186 This has the advantage that Org-mode's HTML conversions can be used.
24187 But it has the disadvantage, that no cell- or row-spanning is allowed."
24188 (let (line field-buffer
24189 (head org-export-highlight-first-table-line)
24190 fields html empty)
24191 (setq html (concat org-export-html-table-tag "\n"))
24192 (while (setq line (pop lines))
24193 (setq empty "&nbsp;")
24194 (catch 'next-line
24195 (if (string-match "^[ \t]*\\+-" line)
24196 (progn
24197 (if field-buffer
24198 (progn
24199 (setq
24200 html
24201 (concat
24202 html
24203 "<tr>"
24204 (mapconcat
24205 (lambda (x)
24206 (if (equal x "") (setq x empty))
24207 (if head
24208 (concat (car org-export-table-header-tags) x
24209 (cdr org-export-table-header-tags))
24210 (concat (car org-export-table-data-tags) x
24211 (cdr org-export-table-data-tags))))
24212 field-buffer "\n")
24213 "</tr>\n"))
24214 (setq head nil)
24215 (setq field-buffer nil)))
24216 ;; Ignore this line
24217 (throw 'next-line t)))
24218 ;; Break the line into fields and store the fields
24219 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
24220 (if field-buffer
24221 (setq field-buffer (mapcar
24222 (lambda (x)
24223 (concat x "<br/>" (pop fields)))
24224 field-buffer))
24225 (setq field-buffer fields))))
24226 (setq html (concat html "</table>\n"))
24227 html))
24229 (defun org-format-table-table-html-using-table-generate-source (lines)
24230 "Format a table into html, using `table-generate-source' from table.el.
24231 This has the advantage that cell- or row-spanning is allowed.
24232 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
24233 (require 'table)
24234 (with-current-buffer (get-buffer-create " org-tmp1 ")
24235 (erase-buffer)
24236 (insert (mapconcat 'identity lines "\n"))
24237 (goto-char (point-min))
24238 (if (not (re-search-forward "|[^+]" nil t))
24239 (error "Error processing table"))
24240 (table-recognize-table)
24241 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
24242 (table-generate-source 'html " org-tmp2 ")
24243 (set-buffer " org-tmp2 ")
24244 (buffer-substring (point-min) (point-max))))
24246 (defun org-html-handle-time-stamps (s)
24247 "Format time stamps in string S, or remove them."
24248 (catch 'exit
24249 (let (r b)
24250 (while (string-match org-maybe-keyword-time-regexp s)
24251 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
24252 ;; never export CLOCK
24253 (throw 'exit ""))
24254 (or b (setq b (substring s 0 (match-beginning 0))))
24255 (if (not org-export-with-timestamps)
24256 (setq r (concat r (substring s 0 (match-beginning 0)))
24257 s (substring s (match-end 0)))
24258 (setq r (concat
24259 r (substring s 0 (match-beginning 0))
24260 (if (match-end 1)
24261 (format "@<span class=\"timestamp-kwd\">%s @</span>"
24262 (match-string 1 s)))
24263 (format " @<span class=\"timestamp\">%s@</span>"
24264 (substring
24265 (org-translate-time (match-string 3 s)) 1 -1)))
24266 s (substring s (match-end 0)))))
24267 ;; Line break if line started and ended with time stamp stuff
24268 (if (not r)
24270 (setq r (concat r s))
24271 (unless (string-match "\\S-" (concat b s))
24272 (setq r (concat r "@<br/>")))
24273 r))))
24275 (defun org-html-protect (s)
24276 ;; convert & to &amp;, < to &lt; and > to &gt;
24277 (let ((start 0))
24278 (while (string-match "&" s start)
24279 (setq s (replace-match "&amp;" t t s)
24280 start (1+ (match-beginning 0))))
24281 (while (string-match "<" s)
24282 (setq s (replace-match "&lt;" t t s)))
24283 (while (string-match ">" s)
24284 (setq s (replace-match "&gt;" t t s))))
24287 (defun org-export-cleanup-toc-line (s)
24288 "Remove tags and time staps from lines going into the toc."
24289 (when (memq org-export-with-tags '(not-in-toc nil))
24290 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
24291 (setq s (replace-match "" t t s))))
24292 (when org-export-remove-timestamps-from-toc
24293 (while (string-match org-maybe-keyword-time-regexp s)
24294 (setq s (replace-match "" t t s))))
24295 (while (string-match org-bracket-link-regexp s)
24296 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
24297 t t s)))
24300 (defun org-html-expand (string)
24301 "Prepare STRING for HTML export. Applies all active conversions.
24302 If there are links in the string, don't modify these."
24303 (let* ((re (concat org-bracket-link-regexp "\\|"
24304 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
24305 m s l res)
24306 (while (setq m (string-match re string))
24307 (setq s (substring string 0 m)
24308 l (match-string 0 string)
24309 string (substring string (match-end 0)))
24310 (push (org-html-do-expand s) res)
24311 (push l res))
24312 (push (org-html-do-expand string) res)
24313 (apply 'concat (nreverse res))))
24315 (defun org-html-do-expand (s)
24316 "Apply all active conversions to translate special ASCII to HTML."
24317 (setq s (org-html-protect s))
24318 (if org-export-html-expand
24319 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
24320 (setq s (replace-match "<\\1>" t nil s))))
24321 (if org-export-with-emphasize
24322 (setq s (org-export-html-convert-emphasize s)))
24323 (if org-export-with-sub-superscripts
24324 (setq s (org-export-html-convert-sub-super s)))
24325 (if org-export-with-TeX-macros
24326 (let ((start 0) wd ass)
24327 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
24328 (setq wd (match-string 1 s))
24329 (if (setq ass (assoc wd org-html-entities))
24330 (setq s (replace-match (or (cdr ass)
24331 (concat "&" (car ass) ";"))
24332 t t s))
24333 (setq start (+ start (length wd)))))))
24336 (defun org-create-multibrace-regexp (left right n)
24337 "Create a regular expression which will match a balanced sexp.
24338 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
24339 as single character strings.
24340 The regexp returned will match the entire expression including the
24341 delimiters. It will also define a single group which contains the
24342 match except for the outermost delimiters. The maximum depth of
24343 stacked delimiters is N. Escaping delimiters is not possible."
24344 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
24345 (or "\\|")
24346 (re nothing)
24347 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
24348 (while (> n 1)
24349 (setq n (1- n)
24350 re (concat re or next)
24351 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
24352 (concat left "\\(" re "\\)" right)))
24354 (defvar org-match-substring-regexp
24355 (concat
24356 "\\([^\\]\\)\\([_^]\\)\\("
24357 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
24358 "\\|"
24359 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
24360 "\\|"
24361 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
24362 "The regular expression matching a sub- or superscript.")
24364 ;(let ((s "a\\_b"))
24365 ; (and (string-match org-match-substring-regexp s)
24366 ; (conca t (match-string 1 s) ":::" (match-string 2 s))))
24368 (defun org-export-html-convert-sub-super (string)
24369 "Convert sub- and superscripts in STRING to HTML."
24370 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
24371 (while (string-match org-match-substring-regexp string s)
24372 (if (and requireb (match-end 8))
24373 (setq s (match-end 2))
24374 (setq s (match-end 1)
24375 key (if (string= (match-string 2 string) "_") "sub" "sup")
24376 c (or (match-string 8 string)
24377 (match-string 6 string)
24378 (match-string 5 string))
24379 string (replace-match
24380 (concat (match-string 1 string)
24381 "<" key ">" c "</" key ">")
24382 t t string))))
24383 (while (string-match "\\\\\\([_^]\\)" string)
24384 (setq string (replace-match (match-string 1 string) t t string)))
24385 string))
24387 (defun org-export-html-convert-emphasize (string)
24388 "Apply emphasis."
24389 (let ((s 0))
24390 (while (string-match org-emph-re string s)
24391 (if (not (equal
24392 (substring string (match-beginning 3) (1+ (match-beginning 3)))
24393 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
24394 (setq string (replace-match
24395 (concat "\\1" (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
24396 "\\4" (nth 3 (assoc (match-string 3 string) org-emphasis-alist))
24397 "\\5") t nil string))
24398 (setq s (1+ s))))
24399 string))
24401 (defvar org-par-open nil)
24402 (defun org-open-par ()
24403 "Insert <p>, but first close previous paragraph if any."
24404 (org-close-par-maybe)
24405 (insert "\n<p>")
24406 (setq org-par-open t))
24407 (defun org-close-par-maybe ()
24408 "Close paragraph if there is one open."
24409 (when org-par-open
24410 (insert "</p>")
24411 (setq org-par-open nil)))
24412 (defun org-close-li ()
24413 "Close <li> if necessary."
24414 (org-close-par-maybe)
24415 (insert "</li>\n"))
24417 (defvar body-only) ; dynamically scoped into this.
24418 (defun org-html-level-start (level title umax with-toc head-count)
24419 "Insert a new level in HTML export.
24420 When TITLE is nil, just close all open levels."
24421 (org-close-par-maybe)
24422 (let ((l org-level-max))
24423 (while (>= l (1+ level))
24424 (if (aref org-levels-open (1- l))
24425 (progn
24426 (org-html-level-close l umax)
24427 (aset org-levels-open (1- l) nil)))
24428 (setq l (1- l)))
24429 (when title
24430 ;; If title is nil, this means this function is called to close
24431 ;; all levels, so the rest is done only if title is given
24432 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
24433 (setq title (replace-match
24434 (if org-export-with-tags
24435 (save-match-data
24436 (concat
24437 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
24438 (mapconcat 'identity (org-split-string
24439 (match-string 1 title) ":")
24440 "&nbsp;")
24441 "</span>"))
24443 t t title)))
24444 (if (> level umax)
24445 (progn
24446 (if (aref org-levels-open (1- level))
24447 (progn
24448 (org-close-li)
24449 (insert "<li>" title "<br/>\n"))
24450 (aset org-levels-open (1- level) t)
24451 (org-close-par-maybe)
24452 (insert "<ul>\n<li>" title "<br/>\n")))
24453 (aset org-levels-open (1- level) t)
24454 (if (and org-export-with-section-numbers (not body-only))
24455 (setq title (concat (org-section-number level) " " title)))
24456 (setq level (+ level org-export-html-toplevel-hlevel -1))
24457 (if with-toc
24458 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
24459 level level head-count title level))
24460 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
24461 (org-open-par)))))
24463 (defun org-html-level-close (level max-outline-level)
24464 "Terminate one level in HTML export."
24465 (if (<= level max-outline-level)
24466 (insert "</div>\n")
24467 (org-close-li)
24468 (insert "</ul>\n")))
24470 ;;; iCalendar export
24472 ;;;###autoload
24473 (defun org-export-icalendar-this-file ()
24474 "Export current file as an iCalendar file.
24475 The iCalendar file will be located in the same directory as the Org-mode
24476 file, but with extension `.ics'."
24477 (interactive)
24478 (org-export-icalendar nil buffer-file-name))
24480 ;;;###autoload
24481 (defun org-export-icalendar-all-agenda-files ()
24482 "Export all files in `org-agenda-files' to iCalendar .ics files.
24483 Each iCalendar file will be located in the same directory as the Org-mode
24484 file, but with extension `.ics'."
24485 (interactive)
24486 (apply 'org-export-icalendar nil (org-agenda-files t)))
24488 ;;;###autoload
24489 (defun org-export-icalendar-combine-agenda-files ()
24490 "Export all files in `org-agenda-files' to a single combined iCalendar file.
24491 The file is stored under the name `org-combined-agenda-icalendar-file'."
24492 (interactive)
24493 (apply 'org-export-icalendar t (org-agenda-files t)))
24495 (defun org-export-icalendar (combine &rest files)
24496 "Create iCalendar files for all elements of FILES.
24497 If COMBINE is non-nil, combine all calendar entries into a single large
24498 file and store it under the name `org-combined-agenda-icalendar-file'."
24499 (save-excursion
24500 (org-prepare-agenda-buffers files)
24501 (let* ((dir (org-export-directory
24502 :ical (list :publishing-directory
24503 org-export-publishing-directory)))
24504 file ical-file ical-buffer category started org-agenda-new-buffers)
24506 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
24507 (when combine
24508 (setq ical-file
24509 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
24510 org-combined-agenda-icalendar-file
24511 (expand-file-name org-combined-agenda-icalendar-file dir))
24512 ical-buffer (org-get-agenda-file-buffer ical-file))
24513 (set-buffer ical-buffer) (erase-buffer))
24514 (while (setq file (pop files))
24515 (catch 'nextfile
24516 (org-check-agenda-file file)
24517 (set-buffer (org-get-agenda-file-buffer file))
24518 (unless combine
24519 (setq ical-file (concat (file-name-as-directory dir)
24520 (file-name-sans-extension
24521 (file-name-nondirectory buffer-file-name))
24522 ".ics"))
24523 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
24524 (with-current-buffer ical-buffer (erase-buffer)))
24525 (setq category (or org-category
24526 (file-name-sans-extension
24527 (file-name-nondirectory buffer-file-name))))
24528 (if (symbolp category) (setq category (symbol-name category)))
24529 (let ((standard-output ical-buffer))
24530 (if combine
24531 (and (not started) (setq started t)
24532 (org-start-icalendar-file org-icalendar-combined-name))
24533 (org-start-icalendar-file category))
24534 (org-print-icalendar-entries combine)
24535 (when (or (and combine (not files)) (not combine))
24536 (org-finish-icalendar-file)
24537 (set-buffer ical-buffer)
24538 (save-buffer)
24539 (run-hooks 'org-after-save-iCalendar-file-hook)))))
24540 (org-release-buffers org-agenda-new-buffers))))
24542 (defvar org-after-save-iCalendar-file-hook nil
24543 "Hook run after an iCalendar file has been saved.
24544 The iCalendar buffer is still current when this hook is run.
24545 A good way to use this is to tell a desktop calenndar application to re-read
24546 the iCalendar file.")
24548 (defun org-print-icalendar-entries (&optional combine)
24549 "Print iCalendar entries for the current Org-mode file to `standard-output'.
24550 When COMBINE is non nil, add the category to each line."
24551 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
24552 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
24553 (dts (org-ical-ts-to-string
24554 (format-time-string (cdr org-time-stamp-formats) (current-time))
24555 "DTSTART"))
24556 hd ts ts2 state status (inc t) pos b sexp rrule
24557 scheduledp deadlinep tmp pri category entry location summary desc
24558 (sexp-buffer (get-buffer-create "*ical-tmp*")))
24559 (org-refresh-category-properties)
24560 (save-excursion
24561 (goto-char (point-min))
24562 (while (re-search-forward re1 nil t)
24563 (catch :skip
24564 (org-agenda-skip)
24565 (setq pos (match-beginning 0)
24566 ts (match-string 0)
24567 inc t
24568 hd (org-get-heading)
24569 summary (org-entry-get nil "SUMMARY")
24570 desc (or (org-entry-get nil "DESCRIPTION")
24571 (org-get-cleaned-entry org-icalendar-include-body))
24572 location (org-entry-get nil "LOCATION")
24573 category (org-get-category))
24574 (if (looking-at re2)
24575 (progn
24576 (goto-char (match-end 0))
24577 (setq ts2 (match-string 1) inc nil))
24578 (setq tmp (buffer-substring (max (point-min)
24579 (- pos org-ds-keyword-length))
24580 pos)
24581 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
24582 (progn
24583 (setq inc nil)
24584 (replace-match "\\1" t nil ts))
24586 deadlinep (string-match org-deadline-regexp tmp)
24587 scheduledp (string-match org-scheduled-regexp tmp)
24588 ;; donep (org-entry-is-done-p)
24590 (if (or (string-match org-tr-regexp hd)
24591 (string-match org-ts-regexp hd))
24592 (setq hd (replace-match "" t t hd)))
24593 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
24594 (setq rrule
24595 (concat "\nRRULE:FREQ="
24596 (cdr (assoc
24597 (match-string 2 ts)
24598 '(("d" . "DAILY")("w" . "WEEKLY")
24599 ("m" . "MONTHLY")("y" . "YEARLY"))))
24600 ";INTERVAL=" (match-string 1 ts)))
24601 (setq rrule ""))
24602 (setq summary (or summary hd))
24603 (if (string-match org-bracket-link-regexp summary)
24604 (setq summary
24605 (replace-match (if (match-end 3)
24606 (match-string 3 summary)
24607 (match-string 1 summary))
24608 t t summary)))
24609 (if deadlinep (setq summary (concat "DL: " summary)))
24610 (if scheduledp (setq summary (concat "S: " summary)))
24611 (if (string-match "\\`<%%" ts)
24612 (with-current-buffer sexp-buffer
24613 (insert (substring ts 1 -1) " " summary "\n"))
24614 (princ (format "BEGIN:VEVENT
24616 %s%s
24617 SUMMARY:%s%s%s
24618 CATEGORIES:%s
24619 END:VEVENT\n"
24620 (org-ical-ts-to-string ts "DTSTART")
24621 (org-ical-ts-to-string ts2 "DTEND" inc)
24622 rrule summary
24623 (if (and desc (string-match "\\S-" desc))
24624 (concat "\nDESCRIPTION: " desc) "")
24625 (if (and location (string-match "\\S-" location))
24626 (concat "\nLOCATION: " location) "")
24627 category)))))
24629 (when (and org-icalendar-include-sexps
24630 (condition-case nil (require 'icalendar) (error nil))
24631 (fboundp 'icalendar-export-region))
24632 ;; Get all the literal sexps
24633 (goto-char (point-min))
24634 (while (re-search-forward "^&?%%(" nil t)
24635 (catch :skip
24636 (org-agenda-skip)
24637 (setq b (match-beginning 0))
24638 (goto-char (1- (match-end 0)))
24639 (forward-sexp 1)
24640 (end-of-line 1)
24641 (setq sexp (buffer-substring b (point)))
24642 (with-current-buffer sexp-buffer
24643 (insert sexp "\n"))
24644 (princ (org-diary-to-ical-string sexp-buffer)))))
24646 (when org-icalendar-include-todo
24647 (goto-char (point-min))
24648 (while (re-search-forward org-todo-line-regexp nil t)
24649 (catch :skip
24650 (org-agenda-skip)
24651 (setq state (match-string 2))
24652 (setq status (if (member state org-done-keywords)
24653 "COMPLETED" "NEEDS-ACTION"))
24654 (when (and state
24655 (or (not (member state org-done-keywords))
24656 (eq org-icalendar-include-todo 'all))
24657 (not (member org-archive-tag (org-get-tags-at)))
24659 (setq hd (match-string 3)
24660 summary (org-entry-get nil "SUMMARY")
24661 desc (or (org-entry-get nil "DESCRIPTION")
24662 (org-get-cleaned-entry org-icalendar-include-body))
24663 location (org-entry-get nil "LOCATION"))
24664 (if (string-match org-bracket-link-regexp hd)
24665 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
24666 (match-string 1 hd))
24667 t t hd)))
24668 (if (string-match org-priority-regexp hd)
24669 (setq pri (string-to-char (match-string 2 hd))
24670 hd (concat (substring hd 0 (match-beginning 1))
24671 (substring hd (match-end 1))))
24672 (setq pri org-default-priority))
24673 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
24674 (- org-lowest-priority org-highest-priority))))))
24676 (princ (format "BEGIN:VTODO
24678 SUMMARY:%s%s%s
24679 CATEGORIES:%s
24680 SEQUENCE:1
24681 PRIORITY:%d
24682 STATUS:%s
24683 END:VTODO\n"
24685 (or summary hd)
24686 (if (and location (string-match "\\S-" location))
24687 (concat "\nLOCATION: " location) "")
24688 (if (and desc (string-match "\\S-" desc))
24689 (concat "\nDESCRIPTION: " desc) "")
24690 category pri status)))))))))
24692 (defun org-get-cleaned-entry (what)
24693 "Clean-up description string."
24694 (when what
24695 (save-excursion
24696 (org-back-to-heading t)
24697 (let ((s (buffer-substring (point-at-bol 2) (org-end-of-subtree t)))
24698 (re (concat org-drawer-regexp "[^\000]*?:END:.*\n?"))
24699 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
24700 (while (string-match re s) (setq s (replace-match "" t t s)))
24701 (while (string-match re2 s) (setq s (replace-match "" t t s)))
24702 (if (string-match "[ \t\r\n]+\\'" s) (setq s (replace-match "" t t s)))
24703 (while (string-match "[ \t]*\n[ \t]*" s)
24704 (setq s (replace-match "\\n" t t s)))
24705 (setq s (org-trim s))
24706 (if (and (numberp what)
24707 (> (length s) what))
24708 (substring s 0 what)
24709 s)))))
24711 (defun org-start-icalendar-file (name)
24712 "Start an iCalendar file by inserting the header."
24713 (let ((user user-full-name)
24714 (name (or name "unknown"))
24715 (timezone (cadr (current-time-zone))))
24716 (princ
24717 (format "BEGIN:VCALENDAR
24718 VERSION:2.0
24719 X-WR-CALNAME:%s
24720 PRODID:-//%s//Emacs with Org-mode//EN
24721 X-WR-TIMEZONE:%s
24722 CALSCALE:GREGORIAN\n" name user timezone))))
24724 (defun org-finish-icalendar-file ()
24725 "Finish an iCalendar file by inserting the END statement."
24726 (princ "END:VCALENDAR\n"))
24728 (defun org-ical-ts-to-string (s keyword &optional inc)
24729 "Take a time string S and convert it to iCalendar format.
24730 KEYWORD is added in front, to make a complete line like DTSTART....
24731 When INC is non-nil, increase the hour by two (if time string contains
24732 a time), or the day by one (if it does not contain a time)."
24733 (let ((t1 (org-parse-time-string s 'nodefault))
24734 t2 fmt have-time time)
24735 (if (and (car t1) (nth 1 t1) (nth 2 t1))
24736 (setq t2 t1 have-time t)
24737 (setq t2 (org-parse-time-string s)))
24738 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
24739 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
24740 (when inc
24741 (if have-time
24742 (if org-agenda-default-appointment-duration
24743 (setq mi (+ org-agenda-default-appointment-duration mi))
24744 (setq h (+ 2 h)))
24745 (setq d (1+ d))))
24746 (setq time (encode-time s mi h d m y)))
24747 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
24748 (concat keyword (format-time-string fmt time))))
24750 ;;; XOXO export
24752 (defun org-export-as-xoxo-insert-into (buffer &rest output)
24753 (with-current-buffer buffer
24754 (apply 'insert output)))
24755 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
24757 (defun org-export-as-xoxo (&optional buffer)
24758 "Export the org buffer as XOXO.
24759 The XOXO buffer is named *xoxo-<source buffer name>*"
24760 (interactive (list (current-buffer)))
24761 ;; A quickie abstraction
24763 ;; Output everything as XOXO
24764 (with-current-buffer (get-buffer buffer)
24765 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
24766 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24767 (org-infile-export-plist)))
24768 (filename (concat (file-name-as-directory
24769 (org-export-directory :xoxo opt-plist))
24770 (file-name-sans-extension
24771 (file-name-nondirectory buffer-file-name))
24772 ".html"))
24773 (out (find-file-noselect filename))
24774 (last-level 1)
24775 (hanging-li nil))
24776 ;; Check the output buffer is empty.
24777 (with-current-buffer out (erase-buffer))
24778 ;; Kick off the output
24779 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
24780 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
24781 (let* ((hd (match-string-no-properties 1))
24782 (level (length hd))
24783 (text (concat
24784 (match-string-no-properties 2)
24785 (save-excursion
24786 (goto-char (match-end 0))
24787 (let ((str ""))
24788 (catch 'loop
24789 (while 't
24790 (forward-line)
24791 (if (looking-at "^[ \t]\\(.*\\)")
24792 (setq str (concat str (match-string-no-properties 1)))
24793 (throw 'loop str)))))))))
24795 ;; Handle level rendering
24796 (cond
24797 ((> level last-level)
24798 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
24800 ((< level last-level)
24801 (dotimes (- (- last-level level) 1)
24802 (if hanging-li
24803 (org-export-as-xoxo-insert-into out "</li>\n"))
24804 (org-export-as-xoxo-insert-into out "</ol>\n"))
24805 (when hanging-li
24806 (org-export-as-xoxo-insert-into out "</li>\n")
24807 (setq hanging-li nil)))
24809 ((equal level last-level)
24810 (if hanging-li
24811 (org-export-as-xoxo-insert-into out "</li>\n")))
24814 (setq last-level level)
24816 ;; And output the new li
24817 (setq hanging-li 't)
24818 (if (equal ?+ (elt text 0))
24819 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
24820 (org-export-as-xoxo-insert-into out "<li>" text))))
24822 ;; Finally finish off the ol
24823 (dotimes (- last-level 1)
24824 (if hanging-li
24825 (org-export-as-xoxo-insert-into out "</li>\n"))
24826 (org-export-as-xoxo-insert-into out "</ol>\n"))
24828 ;; Finish the buffer off and clean it up.
24829 (switch-to-buffer-other-window out)
24830 (indent-region (point-min) (point-max) nil)
24831 (save-buffer)
24832 (goto-char (point-min))
24836 ;;;; Key bindings
24838 ;; Make `C-c C-x' a prefix key
24839 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
24841 ;; TAB key with modifiers
24842 (org-defkey org-mode-map "\C-i" 'org-cycle)
24843 (org-defkey org-mode-map [(tab)] 'org-cycle)
24844 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
24845 (org-defkey org-mode-map [(meta tab)] 'org-complete)
24846 (org-defkey org-mode-map "\M-\t" 'org-complete)
24847 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
24848 ;; The following line is necessary under Suse GNU/Linux
24849 (unless (featurep 'xemacs)
24850 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
24851 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
24852 (define-key org-mode-map [backtab] 'org-shifttab)
24854 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
24855 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
24856 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
24858 ;; Cursor keys with modifiers
24859 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
24860 (org-defkey org-mode-map [(meta right)] 'org-metaright)
24861 (org-defkey org-mode-map [(meta up)] 'org-metaup)
24862 (org-defkey org-mode-map [(meta down)] 'org-metadown)
24864 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
24865 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
24866 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
24867 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
24869 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
24870 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
24871 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
24872 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
24874 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
24875 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
24877 ;;; Extra keys for tty access.
24878 ;; We only set them when really needed because otherwise the
24879 ;; menus don't show the simple keys
24881 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
24882 (not window-system))
24883 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
24884 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
24885 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
24886 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
24887 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
24888 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
24889 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
24890 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
24891 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
24892 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
24893 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
24894 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
24895 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
24896 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
24897 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
24898 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
24899 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
24900 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
24901 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
24902 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
24903 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
24904 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
24906 ;; All the other keys
24908 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
24909 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
24910 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
24911 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
24912 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
24913 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
24914 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
24915 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
24916 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
24917 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
24918 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
24919 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
24920 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
24921 (org-defkey org-mode-map "\C-c\C-w" 'org-check-deadlines)
24922 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
24923 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
24924 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
24925 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
24926 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
24927 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
24928 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
24929 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
24930 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
24931 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
24932 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
24933 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
24934 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
24935 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
24936 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
24937 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
24938 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
24939 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
24940 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
24941 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
24942 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
24943 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
24944 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
24945 (org-defkey org-mode-map "\C-c^" 'org-sort)
24946 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
24947 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
24948 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
24949 (org-defkey org-mode-map "\C-m" 'org-return)
24950 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
24951 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
24952 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
24953 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
24954 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
24955 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
24956 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
24957 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
24958 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
24959 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
24960 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
24961 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
24962 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
24963 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
24964 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
24965 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
24967 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
24968 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
24969 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
24970 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
24972 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
24973 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
24974 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
24975 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
24976 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
24977 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
24978 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
24979 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
24980 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
24981 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
24982 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
24983 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
24985 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
24987 (when (featurep 'xemacs)
24988 (org-defkey org-mode-map 'button3 'popup-mode-menu))
24990 (defsubst org-table-p () (org-at-table-p))
24992 (defun org-self-insert-command (N)
24993 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
24994 If the cursor is in a table looking at whitespace, the whitespace is
24995 overwritten, and the table is not marked as requiring realignment."
24996 (interactive "p")
24997 (if (and (org-table-p)
24998 (progn
24999 ;; check if we blank the field, and if that triggers align
25000 (and org-table-auto-blank-field
25001 (member last-command
25002 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
25003 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
25004 ;; got extra space, this field does not determine column width
25005 (let (org-table-may-need-update) (org-table-blank-field))
25006 ;; no extra space, this field may determine column width
25007 (org-table-blank-field)))
25009 (eq N 1)
25010 (looking-at "[^|\n]* |"))
25011 (let (org-table-may-need-update)
25012 (goto-char (1- (match-end 0)))
25013 (delete-backward-char 1)
25014 (goto-char (match-beginning 0))
25015 (self-insert-command N))
25016 (setq org-table-may-need-update t)
25017 (self-insert-command N)
25018 (org-fix-tags-on-the-fly)))
25020 (defun org-fix-tags-on-the-fly ()
25021 (when (and (equal (char-after (point-at-bol)) ?*)
25022 (org-on-heading-p))
25023 (org-align-tags-here org-tags-column)))
25025 (defun org-delete-backward-char (N)
25026 "Like `delete-backward-char', insert whitespace at field end in tables.
25027 When deleting backwards, in tables this function will insert whitespace in
25028 front of the next \"|\" separator, to keep the table aligned. The table will
25029 still be marked for re-alignment if the field did fill the entire column,
25030 because, in this case the deletion might narrow the column."
25031 (interactive "p")
25032 (if (and (org-table-p)
25033 (eq N 1)
25034 (string-match "|" (buffer-substring (point-at-bol) (point)))
25035 (looking-at ".*?|"))
25036 (let ((pos (point))
25037 (noalign (looking-at "[^|\n\r]* |"))
25038 (c org-table-may-need-update))
25039 (backward-delete-char N)
25040 (skip-chars-forward "^|")
25041 (insert " ")
25042 (goto-char (1- pos))
25043 ;; noalign: if there were two spaces at the end, this field
25044 ;; does not determine the width of the column.
25045 (if noalign (setq org-table-may-need-update c)))
25046 (backward-delete-char N)
25047 (org-fix-tags-on-the-fly)))
25049 (defun org-delete-char (N)
25050 "Like `delete-char', but insert whitespace at field end in tables.
25051 When deleting characters, in tables this function will insert whitespace in
25052 front of the next \"|\" separator, to keep the table aligned. The table will
25053 still be marked for re-alignment if the field did fill the entire column,
25054 because, in this case the deletion might narrow the column."
25055 (interactive "p")
25056 (if (and (org-table-p)
25057 (not (bolp))
25058 (not (= (char-after) ?|))
25059 (eq N 1))
25060 (if (looking-at ".*?|")
25061 (let ((pos (point))
25062 (noalign (looking-at "[^|\n\r]* |"))
25063 (c org-table-may-need-update))
25064 (replace-match (concat
25065 (substring (match-string 0) 1 -1)
25066 " |"))
25067 (goto-char pos)
25068 ;; noalign: if there were two spaces at the end, this field
25069 ;; does not determine the width of the column.
25070 (if noalign (setq org-table-may-need-update c)))
25071 (delete-char N))
25072 (delete-char N)
25073 (org-fix-tags-on-the-fly)))
25075 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
25076 (put 'org-self-insert-command 'delete-selection t)
25077 (put 'orgtbl-self-insert-command 'delete-selection t)
25078 (put 'org-delete-char 'delete-selection 'supersede)
25079 (put 'org-delete-backward-char 'delete-selection 'supersede)
25081 ;; Make `flyspell-mode' delay after some commands
25082 (put 'org-self-insert-command 'flyspell-delayed t)
25083 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
25084 (put 'org-delete-char 'flyspell-delayed t)
25085 (put 'org-delete-backward-char 'flyspell-delayed t)
25087 (eval-after-load "pabbrev"
25088 '(progn
25089 (add-to-list 'pabbrev-expand-after-command-list
25090 'orgtbl-self-insert-command t)
25091 (add-to-list 'pabbrev-expand-after-command-list
25092 'org-self-insert-command t)))
25094 ;; How to do this: Measure non-white length of current string
25095 ;; If equal to column width, we should realign.
25097 (defun org-remap (map &rest commands)
25098 "In MAP, remap the functions given in COMMANDS.
25099 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
25100 (let (new old)
25101 (while commands
25102 (setq old (pop commands) new (pop commands))
25103 (if (fboundp 'command-remapping)
25104 (org-defkey map (vector 'remap old) new)
25105 (substitute-key-definition old new map global-map)))))
25107 (when (eq org-enable-table-editor 'optimized)
25108 ;; If the user wants maximum table support, we need to hijack
25109 ;; some standard editing functions
25110 (org-remap org-mode-map
25111 'self-insert-command 'org-self-insert-command
25112 'delete-char 'org-delete-char
25113 'delete-backward-char 'org-delete-backward-char)
25114 (org-defkey org-mode-map "|" 'org-force-self-insert))
25116 (defun org-shiftcursor-error ()
25117 "Throw an error because Shift-Cursor command was applied in wrong context."
25118 (error "This command is active in special context like tables, headlines or timestamps"))
25120 (defun org-shifttab (&optional arg)
25121 "Global visibility cycling or move to previous table field.
25122 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
25123 on context.
25124 See the individual commands for more information."
25125 (interactive "P")
25126 (cond
25127 ((org-at-table-p) (call-interactively 'org-table-previous-field))
25128 (arg (message "Content view to level: ")
25129 (org-content (prefix-numeric-value arg))
25130 (setq org-cycle-global-status 'overview))
25131 (t (call-interactively 'org-global-cycle))))
25133 (defun org-shiftmetaleft ()
25134 "Promote subtree or delete table column.
25135 Calls `org-promote-subtree', `org-outdent-item',
25136 or `org-table-delete-column', depending on context.
25137 See the individual commands for more information."
25138 (interactive)
25139 (cond
25140 ((org-at-table-p) (call-interactively 'org-table-delete-column))
25141 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
25142 ((org-at-item-p) (call-interactively 'org-outdent-item))
25143 (t (org-shiftcursor-error))))
25145 (defun org-shiftmetaright ()
25146 "Demote subtree or insert table column.
25147 Calls `org-demote-subtree', `org-indent-item',
25148 or `org-table-insert-column', depending on context.
25149 See the individual commands for more information."
25150 (interactive)
25151 (cond
25152 ((org-at-table-p) (call-interactively 'org-table-insert-column))
25153 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
25154 ((org-at-item-p) (call-interactively 'org-indent-item))
25155 (t (org-shiftcursor-error))))
25157 (defun org-shiftmetaup (&optional arg)
25158 "Move subtree up or kill table row.
25159 Calls `org-move-subtree-up' or `org-table-kill-row' or
25160 `org-move-item-up' depending on context. See the individual commands
25161 for more information."
25162 (interactive "P")
25163 (cond
25164 ((org-at-table-p) (call-interactively 'org-table-kill-row))
25165 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
25166 ((org-at-item-p) (call-interactively 'org-move-item-up))
25167 (t (org-shiftcursor-error))))
25168 (defun org-shiftmetadown (&optional arg)
25169 "Move subtree down or insert table row.
25170 Calls `org-move-subtree-down' or `org-table-insert-row' or
25171 `org-move-item-down', depending on context. See the individual
25172 commands for more information."
25173 (interactive "P")
25174 (cond
25175 ((org-at-table-p) (call-interactively 'org-table-insert-row))
25176 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
25177 ((org-at-item-p) (call-interactively 'org-move-item-down))
25178 (t (org-shiftcursor-error))))
25180 (defun org-metaleft (&optional arg)
25181 "Promote heading or move table column to left.
25182 Calls `org-do-promote' or `org-table-move-column', depending on context.
25183 With no specific context, calls the Emacs default `backward-word'.
25184 See the individual commands for more information."
25185 (interactive "P")
25186 (cond
25187 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
25188 ((or (org-on-heading-p) (org-region-active-p))
25189 (call-interactively 'org-do-promote))
25190 ((org-at-item-p) (call-interactively 'org-outdent-item))
25191 (t (call-interactively 'backward-word))))
25193 (defun org-metaright (&optional arg)
25194 "Demote subtree or move table column to right.
25195 Calls `org-do-demote' or `org-table-move-column', depending on context.
25196 With no specific context, calls the Emacs default `forward-word'.
25197 See the individual commands for more information."
25198 (interactive "P")
25199 (cond
25200 ((org-at-table-p) (call-interactively 'org-table-move-column))
25201 ((or (org-on-heading-p) (org-region-active-p))
25202 (call-interactively 'org-do-demote))
25203 ((org-at-item-p) (call-interactively 'org-indent-item))
25204 (t (call-interactively 'forward-word))))
25206 (defun org-metaup (&optional arg)
25207 "Move subtree up or move table row up.
25208 Calls `org-move-subtree-up' or `org-table-move-row' or
25209 `org-move-item-up', depending on context. See the individual commands
25210 for more information."
25211 (interactive "P")
25212 (cond
25213 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
25214 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
25215 ((org-at-item-p) (call-interactively 'org-move-item-up))
25216 (t (transpose-lines 1) (beginning-of-line -1))))
25218 (defun org-metadown (&optional arg)
25219 "Move subtree down or move table row down.
25220 Calls `org-move-subtree-down' or `org-table-move-row' or
25221 `org-move-item-down', depending on context. See the individual
25222 commands for more information."
25223 (interactive "P")
25224 (cond
25225 ((org-at-table-p) (call-interactively 'org-table-move-row))
25226 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
25227 ((org-at-item-p) (call-interactively 'org-move-item-down))
25228 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
25230 (defun org-shiftup (&optional arg)
25231 "Increase item in timestamp or increase priority of current headline.
25232 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
25233 depending on context. See the individual commands for more information."
25234 (interactive "P")
25235 (cond
25236 ((org-at-timestamp-p t)
25237 (call-interactively (if org-edit-timestamp-down-means-later
25238 'org-timestamp-down 'org-timestamp-up)))
25239 ((org-on-heading-p) (call-interactively 'org-priority-up))
25240 ((org-at-item-p) (call-interactively 'org-previous-item))
25241 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
25243 (defun org-shiftdown (&optional arg)
25244 "Decrease item in timestamp or decrease priority of current headline.
25245 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
25246 depending on context. See the individual commands for more information."
25247 (interactive "P")
25248 (cond
25249 ((org-at-timestamp-p t)
25250 (call-interactively (if org-edit-timestamp-down-means-later
25251 'org-timestamp-up 'org-timestamp-down)))
25252 ((org-on-heading-p) (call-interactively 'org-priority-down))
25253 (t (call-interactively 'org-next-item))))
25255 (defun org-shiftright ()
25256 "Next TODO keyword or timestamp one day later, depending on context."
25257 (interactive)
25258 (cond
25259 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
25260 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
25261 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
25262 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
25263 (t (org-shiftcursor-error))))
25265 (defun org-shiftleft ()
25266 "Previous TODO keyword or timestamp one day earlier, depending on context."
25267 (interactive)
25268 (cond
25269 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
25270 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
25271 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
25272 ((org-at-property-p)
25273 (call-interactively 'org-property-previous-allowed-value))
25274 (t (org-shiftcursor-error))))
25276 (defun org-shiftcontrolright ()
25277 "Switch to next TODO set."
25278 (interactive)
25279 (cond
25280 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
25281 (t (org-shiftcursor-error))))
25283 (defun org-shiftcontrolleft ()
25284 "Switch to previous TODO set."
25285 (interactive)
25286 (cond
25287 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
25288 (t (org-shiftcursor-error))))
25290 (defun org-ctrl-c-ret ()
25291 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
25292 (interactive)
25293 (cond
25294 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
25295 (t (call-interactively 'org-insert-heading))))
25297 (defun org-copy-special ()
25298 "Copy region in table or copy current subtree.
25299 Calls `org-table-copy' or `org-copy-subtree', depending on context.
25300 See the individual commands for more information."
25301 (interactive)
25302 (call-interactively
25303 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
25305 (defun org-cut-special ()
25306 "Cut region in table or cut current subtree.
25307 Calls `org-table-copy' or `org-cut-subtree', depending on context.
25308 See the individual commands for more information."
25309 (interactive)
25310 (call-interactively
25311 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
25313 (defun org-paste-special (arg)
25314 "Paste rectangular region into table, or past subtree relative to level.
25315 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
25316 See the individual commands for more information."
25317 (interactive "P")
25318 (if (org-at-table-p)
25319 (org-table-paste-rectangle)
25320 (org-paste-subtree arg)))
25322 (defun org-ctrl-c-ctrl-c (&optional arg)
25323 "Set tags in headline, or update according to changed information at point.
25325 This command does many different things, depending on context:
25327 - If the cursor is in a headline, prompt for tags and insert them
25328 into the current line, aligned to `org-tags-column'. When called
25329 with prefix arg, realign all tags in the current buffer.
25331 - If the cursor is in one of the special #+KEYWORD lines, this
25332 triggers scanning the buffer for these lines and updating the
25333 information.
25335 - If the cursor is inside a table, realign the table. This command
25336 works even if the automatic table editor has been turned off.
25338 - If the cursor is on a #+TBLFM line, re-apply the formulas to
25339 the entire table.
25341 - If the cursor is a the beginning of a dynamic block, update it.
25343 - If the cursor is inside a table created by the table.el package,
25344 activate that table.
25346 - If the current buffer is a remember buffer, close note and file it.
25347 with a prefix argument, file it without further interaction to the default
25348 location.
25350 - If the cursor is on a <<<target>>>, update radio targets and corresponding
25351 links in this buffer.
25353 - If the cursor is on a numbered item in a plain list, renumber the
25354 ordered list."
25355 (interactive "P")
25356 (let ((org-enable-table-editor t))
25357 (cond
25358 ((or org-clock-overlays
25359 org-occur-highlights
25360 org-latex-fragment-image-overlays)
25361 (org-remove-clock-overlays)
25362 (org-remove-occur-highlights)
25363 (org-remove-latex-fragment-image-overlays)
25364 (message "Temporary highlights/overlays removed from current buffer"))
25365 ((and (local-variable-p 'org-finish-function (current-buffer))
25366 (fboundp org-finish-function))
25367 (funcall org-finish-function))
25368 ((org-at-property-p)
25369 (call-interactively 'org-property-action))
25370 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
25371 ((org-on-heading-p) (call-interactively 'org-set-tags))
25372 ((org-at-table.el-p)
25373 (require 'table)
25374 (beginning-of-line 1)
25375 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
25376 (call-interactively 'table-recognize-table))
25377 ((org-at-table-p)
25378 (org-table-maybe-eval-formula)
25379 (if arg
25380 (call-interactively 'org-table-recalculate)
25381 (org-table-maybe-recalculate-line))
25382 (call-interactively 'org-table-align))
25383 ((org-at-item-checkbox-p)
25384 (call-interactively 'org-toggle-checkbox))
25385 ((org-at-item-p)
25386 (call-interactively 'org-maybe-renumber-ordered-list))
25387 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
25388 ;; Dynamic block
25389 (beginning-of-line 1)
25390 (org-update-dblock))
25391 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
25392 (cond
25393 ((equal (match-string 1) "TBLFM")
25394 ;; Recalculate the table before this line
25395 (save-excursion
25396 (beginning-of-line 1)
25397 (skip-chars-backward " \r\n\t")
25398 (if (org-at-table-p)
25399 (org-call-with-arg 'org-table-recalculate t))))
25401 (call-interactively 'org-mode-restart))))
25402 (t (error "C-c C-c can do nothing useful at this location.")))))
25404 (defun org-mode-restart ()
25405 "Restart Org-mode, to scan again for special lines.
25406 Also updates the keyword regular expressions."
25407 (interactive)
25408 (let ((org-inhibit-startup t)) (org-mode))
25409 (message "Org-mode restarted to refresh keyword and special line setup"))
25411 (defun org-kill-note-or-show-branches ()
25412 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
25413 (interactive)
25414 (if (not org-finish-function)
25415 (call-interactively 'show-branches)
25416 (let ((org-note-abort t))
25417 (funcall org-finish-function))))
25419 (defun org-return ()
25420 "Goto next table row or insert a newline.
25421 Calls `org-table-next-row' or `newline', depending on context.
25422 See the individual commands for more information."
25423 (interactive)
25424 (cond
25425 ((bobp) (newline))
25426 ((org-at-table-p)
25427 (org-table-justify-field-maybe)
25428 (call-interactively 'org-table-next-row))
25429 (t (newline))))
25432 (defun org-ctrl-c-minus ()
25433 "Insert separator line in table or modify bullet type in list.
25434 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
25435 depending on context."
25436 (interactive)
25437 (cond
25438 ((org-at-table-p)
25439 (call-interactively 'org-table-insert-hline))
25440 ((org-on-heading-p)
25441 ;; Convert to item
25442 (save-excursion
25443 (beginning-of-line 1)
25444 (if (looking-at "\\*+ ")
25445 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
25446 ((org-in-item-p)
25447 (call-interactively 'org-cycle-list-bullet))
25448 (t (error "`C-c -' does have no function here."))))
25450 (defun org-meta-return (&optional arg)
25451 "Insert a new heading or wrap a region in a table.
25452 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
25453 See the individual commands for more information."
25454 (interactive "P")
25455 (cond
25456 ((org-at-table-p)
25457 (call-interactively 'org-table-wrap-region))
25458 (t (call-interactively 'org-insert-heading))))
25460 ;;; Menu entries
25462 ;; Define the Org-mode menus
25463 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
25464 '("Tbl"
25465 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
25466 ["Next Field" org-cycle (org-at-table-p)]
25467 ["Previous Field" org-shifttab (org-at-table-p)]
25468 ["Next Row" org-return (org-at-table-p)]
25469 "--"
25470 ["Blank Field" org-table-blank-field (org-at-table-p)]
25471 ["Edit Field" org-table-edit-field (org-at-table-p)]
25472 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
25473 "--"
25474 ("Column"
25475 ["Move Column Left" org-metaleft (org-at-table-p)]
25476 ["Move Column Right" org-metaright (org-at-table-p)]
25477 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
25478 ["Insert Column" org-shiftmetaright (org-at-table-p)])
25479 ("Row"
25480 ["Move Row Up" org-metaup (org-at-table-p)]
25481 ["Move Row Down" org-metadown (org-at-table-p)]
25482 ["Delete Row" org-shiftmetaup (org-at-table-p)]
25483 ["Insert Row" org-shiftmetadown (org-at-table-p)]
25484 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
25485 "--"
25486 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
25487 ("Rectangle"
25488 ["Copy Rectangle" org-copy-special (org-at-table-p)]
25489 ["Cut Rectangle" org-cut-special (org-at-table-p)]
25490 ["Paste Rectangle" org-paste-special (org-at-table-p)]
25491 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
25492 "--"
25493 ("Calculate"
25494 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
25495 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
25496 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
25497 "--"
25498 ["Recalculate line" org-table-recalculate (org-at-table-p)]
25499 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
25500 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
25501 "--"
25502 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
25503 "--"
25504 ["Sum Column/Rectangle" org-table-sum
25505 (or (org-at-table-p) (org-region-active-p))]
25506 ["Which Column?" org-table-current-column (org-at-table-p)])
25507 ["Debug Formulas"
25508 org-table-toggle-formula-debugger
25509 :style toggle :selected org-table-formula-debug]
25510 ["Show Col/Row Numbers"
25511 org-table-toggle-coordinate-overlays
25512 :style toggle :selected org-table-overlay-coordinates]
25513 "--"
25514 ["Create" org-table-create (and (not (org-at-table-p))
25515 org-enable-table-editor)]
25516 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
25517 ["Import from File" org-table-import (not (org-at-table-p))]
25518 ["Export to File" org-table-export (org-at-table-p)]
25519 "--"
25520 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
25522 (easy-menu-define org-org-menu org-mode-map "Org menu"
25523 '("Org"
25524 ("Show/Hide"
25525 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
25526 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
25527 ["Sparse Tree" org-occur t]
25528 ["Reveal Context" org-reveal t]
25529 ["Show All" show-all t]
25530 "--"
25531 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
25532 "--"
25533 ["New Heading" org-insert-heading t]
25534 ("Navigate Headings"
25535 ["Up" outline-up-heading t]
25536 ["Next" outline-next-visible-heading t]
25537 ["Previous" outline-previous-visible-heading t]
25538 ["Next Same Level" outline-forward-same-level t]
25539 ["Previous Same Level" outline-backward-same-level t]
25540 "--"
25541 ["Jump" org-goto t])
25542 ("Edit Structure"
25543 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
25544 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
25545 "--"
25546 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
25547 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
25548 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
25549 "--"
25550 ["Promote Heading" org-metaleft (not (org-at-table-p))]
25551 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
25552 ["Demote Heading" org-metaright (not (org-at-table-p))]
25553 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
25554 "--"
25555 ["Sort Region/Children" org-sort (not (org-at-table-p))]
25556 "--"
25557 ["Convert to odd levels" org-convert-to-odd-levels t]
25558 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
25559 ("Editing"
25560 ["Emphasis..." org-emphasize t])
25561 ("Archive"
25562 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
25563 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
25564 ; :active t :keys "C-u C-c C-x C-a"]
25565 ["Sparse trees open ARCHIVE trees"
25566 (setq org-sparse-tree-open-archived-trees
25567 (not org-sparse-tree-open-archived-trees))
25568 :style toggle :selected org-sparse-tree-open-archived-trees]
25569 ["Cycling opens ARCHIVE trees"
25570 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
25571 :style toggle :selected org-cycle-open-archived-trees]
25572 ["Agenda includes ARCHIVE trees"
25573 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
25574 :style toggle :selected (not org-agenda-skip-archived-trees)]
25575 "--"
25576 ["Move Subtree to Archive" org-advertized-archive-subtree t]
25577 ; ["Check and Move Children" (org-archive-subtree '(4))
25578 ; :active t :keys "C-u C-c C-x C-s"]
25580 "--"
25581 ("TODO Lists"
25582 ["TODO/DONE/-" org-todo t]
25583 ("Select keyword"
25584 ["Next keyword" org-shiftright (org-on-heading-p)]
25585 ["Previous keyword" org-shiftleft (org-on-heading-p)]
25586 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
25587 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
25588 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
25589 ["Show TODO Tree" org-show-todo-tree t]
25590 ["Global TODO list" org-todo-list t]
25591 "--"
25592 ["Set Priority" org-priority t]
25593 ["Priority Up" org-shiftup t]
25594 ["Priority Down" org-shiftdown t])
25595 ("TAGS and Properties"
25596 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
25597 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
25598 "--"
25599 ["Set property" 'org-set-property t]
25600 ["Column view of properties" org-columns t]
25601 ["Insert Column View DBlock" org-insert-columns-dblock t])
25602 ("Dates and Scheduling"
25603 ["Timestamp" org-time-stamp t]
25604 ["Timestamp (inactive)" org-time-stamp-inactive t]
25605 ("Change Date"
25606 ["1 Day Later" org-shiftright t]
25607 ["1 Day Earlier" org-shiftleft t]
25608 ["1 ... Later" org-shiftup t]
25609 ["1 ... Earlier" org-shiftdown t])
25610 ["Compute Time Range" org-evaluate-time-range t]
25611 ["Schedule Item" org-schedule t]
25612 ["Deadline" org-deadline t]
25613 "--"
25614 ["Custom time format" org-toggle-time-stamp-overlays
25615 :style radio :selected org-display-custom-times]
25616 "--"
25617 ["Goto Calendar" org-goto-calendar t]
25618 ["Date from Calendar" org-date-from-calendar t])
25619 ("Logging work"
25620 ["Clock in" org-clock-in t]
25621 ["Clock out" org-clock-out t]
25622 ["Clock cancel" org-clock-cancel t]
25623 ["Goto running clock" org-clock-goto t]
25624 ["Display times" org-clock-display t]
25625 ["Create clock table" org-clock-report t]
25626 "--"
25627 ["Record DONE time"
25628 (progn (setq org-log-done (not org-log-done))
25629 (message "Switching to %s will %s record a timestamp"
25630 (car org-done-keywords)
25631 (if org-log-done "automatically" "not")))
25632 :style toggle :selected org-log-done])
25633 "--"
25634 ["Agenda Command..." org-agenda t]
25635 ("File List for Agenda")
25636 ("Special views current file"
25637 ["TODO Tree" org-show-todo-tree t]
25638 ["Check Deadlines" org-check-deadlines t]
25639 ["Timeline" org-timeline t]
25640 ["Tags Tree" org-tags-sparse-tree t])
25641 "--"
25642 ("Hyperlinks"
25643 ["Store Link (Global)" org-store-link t]
25644 ["Insert Link" org-insert-link t]
25645 ["Follow Link" org-open-at-point t]
25646 "--"
25647 ["Next link" org-next-link t]
25648 ["Previous link" org-previous-link t]
25649 "--"
25650 ["Descriptive Links"
25651 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
25652 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
25653 ["Literal Links"
25654 (progn
25655 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
25656 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
25657 "--"
25658 ["Export/Publish..." org-export t]
25659 ("LaTeX"
25660 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
25661 :selected org-cdlatex-mode]
25662 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
25663 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
25664 ["Modify math symbol" org-cdlatex-math-modify
25665 (org-inside-LaTeX-fragment-p)]
25666 ["Export LaTeX fragments as images"
25667 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
25668 :style toggle :selected org-export-with-LaTeX-fragments])
25669 "--"
25670 ("Documentation"
25671 ["Show Version" org-version t]
25672 ["Info Documentation" org-info t])
25673 ("Customize"
25674 ["Browse Org Group" org-customize t]
25675 "--"
25676 ["Expand This Menu" org-create-customize-menu
25677 (fboundp 'customize-menu-create)])
25678 "--"
25679 ["Refresh setup" org-mode-restart t]
25682 (defun org-info (&optional node)
25683 "Read documentation for Org-mode in the info system.
25684 With optional NODE, go directly to that node."
25685 (interactive)
25686 (require 'info)
25687 (Info-goto-node (format "(org)%s" (or node ""))))
25689 (defun org-install-agenda-files-menu ()
25690 (let ((bl (buffer-list)))
25691 (save-excursion
25692 (while bl
25693 (set-buffer (pop bl))
25694 (if (org-mode-p) (setq bl nil)))
25695 (when (org-mode-p)
25696 (easy-menu-change
25697 '("Org") "File List for Agenda"
25698 (append
25699 (list
25700 ["Edit File List" (org-edit-agenda-file-list) t]
25701 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
25702 ["Remove Current File from List" org-remove-file t]
25703 ["Cycle through agenda files" org-cycle-agenda-files t]
25704 ["Occur in all agenda files" org-occur-in-agenda-files t]
25705 "--")
25706 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
25708 ;;;; Documentation
25710 (defun org-customize ()
25711 "Call the customize function with org as argument."
25712 (interactive)
25713 (customize-browse 'org))
25715 (defun org-create-customize-menu ()
25716 "Create a full customization menu for Org-mode, insert it into the menu."
25717 (interactive)
25718 (if (fboundp 'customize-menu-create)
25719 (progn
25720 (easy-menu-change
25721 '("Org") "Customize"
25722 `(["Browse Org group" org-customize t]
25723 "--"
25724 ,(customize-menu-create 'org)
25725 ["Set" Custom-set t]
25726 ["Save" Custom-save t]
25727 ["Reset to Current" Custom-reset-current t]
25728 ["Reset to Saved" Custom-reset-saved t]
25729 ["Reset to Standard Settings" Custom-reset-standard t]))
25730 (message "\"Org\"-menu now contains full customization menu"))
25731 (error "Cannot expand menu (outdated version of cus-edit.el)")))
25733 ;;;; Miscellaneous stuff
25736 ;;; Generally useful functions
25738 (defun org-context ()
25739 "Return a list of contexts of the current cursor position.
25740 If several contexts apply, all are returned.
25741 Each context entry is a list with a symbol naming the context, and
25742 two positions indicating start and end of the context. Possible
25743 contexts are:
25745 :headline anywhere in a headline
25746 :headline-stars on the leading stars in a headline
25747 :todo-keyword on a TODO keyword (including DONE) in a headline
25748 :tags on the TAGS in a headline
25749 :priority on the priority cookie in a headline
25750 :item on the first line of a plain list item
25751 :item-bullet on the bullet/number of a plain list item
25752 :checkbox on the checkbox in a plain list item
25753 :table in an org-mode table
25754 :table-special on a special filed in a table
25755 :table-table in a table.el table
25756 :link on a hyperlink
25757 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
25758 :target on a <<target>>
25759 :radio-target on a <<<radio-target>>>
25760 :latex-fragment on a LaTeX fragment
25761 :latex-preview on a LaTeX fragment with overlayed preview image
25763 This function expects the position to be visible because it uses font-lock
25764 faces as a help to recognize the following contexts: :table-special, :link,
25765 and :keyword."
25766 (let* ((f (get-text-property (point) 'face))
25767 (faces (if (listp f) f (list f)))
25768 (p (point)) clist o)
25769 ;; First the large context
25770 (cond
25771 ((org-on-heading-p t)
25772 (push (list :headline (point-at-bol) (point-at-eol)) clist)
25773 (when (progn
25774 (beginning-of-line 1)
25775 (looking-at org-todo-line-tags-regexp))
25776 (push (org-point-in-group p 1 :headline-stars) clist)
25777 (push (org-point-in-group p 2 :todo-keyword) clist)
25778 (push (org-point-in-group p 4 :tags) clist))
25779 (goto-char p)
25780 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
25781 (if (looking-at "\\[#[A-Z0-9]\\]")
25782 (push (org-point-in-group p 0 :priority) clist)))
25784 ((org-at-item-p)
25785 (push (org-point-in-group p 2 :item-bullet) clist)
25786 (push (list :item (point-at-bol)
25787 (save-excursion (org-end-of-item) (point)))
25788 clist)
25789 (and (org-at-item-checkbox-p)
25790 (push (org-point-in-group p 0 :checkbox) clist)))
25792 ((org-at-table-p)
25793 (push (list :table (org-table-begin) (org-table-end)) clist)
25794 (if (memq 'org-formula faces)
25795 (push (list :table-special
25796 (previous-single-property-change p 'face)
25797 (next-single-property-change p 'face)) clist)))
25798 ((org-at-table-p 'any)
25799 (push (list :table-table) clist)))
25800 (goto-char p)
25802 ;; Now the small context
25803 (cond
25804 ((org-at-timestamp-p)
25805 (push (org-point-in-group p 0 :timestamp) clist))
25806 ((memq 'org-link faces)
25807 (push (list :link
25808 (previous-single-property-change p 'face)
25809 (next-single-property-change p 'face)) clist))
25810 ((memq 'org-special-keyword faces)
25811 (push (list :keyword
25812 (previous-single-property-change p 'face)
25813 (next-single-property-change p 'face)) clist))
25814 ((org-on-target-p)
25815 (push (org-point-in-group p 0 :target) clist)
25816 (goto-char (1- (match-beginning 0)))
25817 (if (looking-at org-radio-target-regexp)
25818 (push (org-point-in-group p 0 :radio-target) clist))
25819 (goto-char p))
25820 ((setq o (car (delq nil
25821 (mapcar
25822 (lambda (x)
25823 (if (memq x org-latex-fragment-image-overlays) x))
25824 (org-overlays-at (point))))))
25825 (push (list :latex-fragment
25826 (org-overlay-start o) (org-overlay-end o)) clist)
25827 (push (list :latex-preview
25828 (org-overlay-start o) (org-overlay-end o)) clist))
25829 ((org-inside-LaTeX-fragment-p)
25830 ;; FIXME: positions wrong.
25831 (push (list :latex-fragment (point) (point)) clist)))
25833 (setq clist (nreverse (delq nil clist)))
25834 clist))
25836 ;; FIXME: Compare with at-regexp-p Do we need both?
25837 (defun org-in-regexp (re &optional nlines visually)
25838 "Check if point is inside a match of regexp.
25839 Normally only the current line is checked, but you can include NLINES extra
25840 lines both before and after point into the search.
25841 If VISUALLY is set, require that the cursor is not after the match but
25842 really on, so that the block visually is on the match."
25843 (catch 'exit
25844 (let ((pos (point))
25845 (eol (point-at-eol (+ 1 (or nlines 0))))
25846 (inc (if visually 1 0)))
25847 (save-excursion
25848 (beginning-of-line (- 1 (or nlines 0)))
25849 (while (re-search-forward re eol t)
25850 (if (and (<= (match-beginning 0) pos)
25851 (>= (+ inc (match-end 0)) pos))
25852 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
25854 (defun org-at-regexp-p (regexp)
25855 "Is point inside a match of REGEXP in the current line?"
25856 (catch 'exit
25857 (save-excursion
25858 (let ((pos (point)) (end (point-at-eol)))
25859 (beginning-of-line 1)
25860 (while (re-search-forward regexp end t)
25861 (if (and (<= (match-beginning 0) pos)
25862 (>= (match-end 0) pos))
25863 (throw 'exit t)))
25864 nil))))
25866 (defun org-occur-in-agenda-files (regexp &optional nlines)
25867 "Call `multi-occur' with buffers for all agenda files."
25868 (interactive "sOrg-files matching: \np")
25869 (let* ((files (org-agenda-files))
25870 (tnames (mapcar 'file-truename files))
25871 (extra org-agenda-multi-occur-extra-files)
25873 (while (setq f (pop extra))
25874 (unless (member (file-truename f) tnames)
25875 (add-to-list 'files f 'append)
25876 (add-to-list 'tnames (file-truename f) 'append)))
25877 (multi-occur
25878 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
25879 regexp)))
25881 (defun org-uniquify (list)
25882 "Remove duplicate elements from LIST."
25883 (let (res)
25884 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
25885 res))
25887 (defun org-delete-all (elts list)
25888 "Remove all elements in ELTS from LIST."
25889 (while elts
25890 (setq list (delete (pop elts) list)))
25891 list)
25893 (defun org-point-in-group (point group &optional context)
25894 "Check if POINT is in match-group GROUP.
25895 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
25896 match. If the match group does ot exist or point is not inside it,
25897 return nil."
25898 (and (match-beginning group)
25899 (>= point (match-beginning group))
25900 (<= point (match-end group))
25901 (if context
25902 (list context (match-beginning group) (match-end group))
25903 t)))
25905 (defun org-switch-to-buffer-other-window (&rest args)
25906 "Switch to buffer in a second window on the current frame.
25907 In particular, do not allow pop-up frames."
25908 (let (pop-up-frames special-display-buffer-names special-display-regexps
25909 special-display-function)
25910 (apply 'switch-to-buffer-other-window args)))
25912 (defun org-combine-plists (&rest plists)
25913 "Create a single property list from all plists in PLISTS.
25914 The process starts by copying the first list, and then setting properties
25915 from the other lists. Settings in the last list are the most significant
25916 ones and overrule settings in the other lists."
25917 (let ((rtn (copy-sequence (pop plists)))
25918 p v ls)
25919 (while plists
25920 (setq ls (pop plists))
25921 (while ls
25922 (setq p (pop ls) v (pop ls))
25923 (setq rtn (plist-put rtn p v))))
25924 rtn))
25926 (defun org-move-line-down (arg)
25927 "Move the current line down. With prefix argument, move it past ARG lines."
25928 (interactive "p")
25929 (let ((col (current-column))
25930 beg end pos)
25931 (beginning-of-line 1) (setq beg (point))
25932 (beginning-of-line 2) (setq end (point))
25933 (beginning-of-line (+ 1 arg))
25934 (setq pos (move-marker (make-marker) (point)))
25935 (insert (delete-and-extract-region beg end))
25936 (goto-char pos)
25937 (move-to-column col)))
25939 (defun org-move-line-up (arg)
25940 "Move the current line up. With prefix argument, move it past ARG lines."
25941 (interactive "p")
25942 (let ((col (current-column))
25943 beg end pos)
25944 (beginning-of-line 1) (setq beg (point))
25945 (beginning-of-line 2) (setq end (point))
25946 (beginning-of-line (- arg))
25947 (setq pos (move-marker (make-marker) (point)))
25948 (insert (delete-and-extract-region beg end))
25949 (goto-char pos)
25950 (move-to-column col)))
25952 (defun org-replace-escapes (string table)
25953 "Replace %-escapes in STRING with values in TABLE.
25954 TABLE is an association list with keys like \"%a\" and string values.
25955 The sequences in STRING may contain normal field width and padding information,
25956 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
25957 so values can contain further %-escapes if they are define later in TABLE."
25958 (let ((case-fold-search nil)
25959 e re rpl)
25960 (while (setq e (pop table))
25961 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
25962 (while (string-match re string)
25963 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
25964 (cdr e)))
25965 (setq string (replace-match rpl t t string))))
25966 string))
25969 (defun org-sublist (list start end)
25970 "Return a section of LIST, from START to END.
25971 Counting starts at 1."
25972 (let (rtn (c start))
25973 (setq list (nthcdr (1- start) list))
25974 (while (and list (<= c end))
25975 (push (pop list) rtn)
25976 (setq c (1+ c)))
25977 (nreverse rtn)))
25979 (defun org-find-base-buffer-visiting (file)
25980 "Like `find-buffer-visiting' but alway return the base buffer and
25981 not an indirect buffer"
25982 (let ((buf (find-buffer-visiting file)))
25983 (if buf
25984 (or (buffer-base-buffer buf) buf)
25985 nil)))
25987 (defun org-image-file-name-regexp ()
25988 "Return regexp matching the file names of images."
25989 (if (fboundp 'image-file-name-regexp)
25990 (image-file-name-regexp)
25991 (let ((image-file-name-extensions
25992 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
25993 "xbm" "xpm" "pbm" "pgm" "ppm")))
25994 (concat "\\."
25995 (regexp-opt (nconc (mapcar 'upcase
25996 image-file-name-extensions)
25997 image-file-name-extensions)
25999 "\\'"))))
26001 (defun org-file-image-p (file)
26002 "Return non-nil if FILE is an image."
26003 (save-match-data
26004 (string-match (org-image-file-name-regexp) file)))
26006 ;;; Paragraph filling stuff.
26007 ;; We want this to be just right, so use the full arsenal.
26009 (defun org-indent-line-function ()
26010 "Indent line like previous, but further if previous was headline or item."
26011 (interactive)
26012 (let* ((pos (point))
26013 (itemp (org-at-item-p))
26014 column bpos bcol tpos tcol bullet btype bullet-type)
26015 ;; Find the previous relevant line
26016 (beginning-of-line 1)
26017 (cond
26018 ((looking-at "#") (setq column 0))
26019 ((looking-at "\\*+ ") (setq column 0))
26021 (beginning-of-line 0)
26022 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
26023 (beginning-of-line 0))
26024 (cond
26025 ((looking-at "\\*+[ \t]+")
26026 (goto-char (match-end 0))
26027 (setq column (current-column)))
26028 ((org-in-item-p)
26029 (org-beginning-of-item)
26030 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
26031 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
26032 (setq bpos (match-beginning 1) tpos (match-end 0)
26033 bcol (progn (goto-char bpos) (current-column))
26034 tcol (progn (goto-char tpos) (current-column))
26035 bullet (match-string 1)
26036 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
26037 (if (not itemp)
26038 (setq column tcol)
26039 (goto-char pos)
26040 (beginning-of-line 1)
26041 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
26042 (setq bullet (match-string 1)
26043 btype (if (string-match "[0-9]" bullet) "n" bullet))
26044 (setq column (if (equal btype bullet-type) bcol tcol))))
26045 (t (setq column (org-get-indentation))))))
26046 (goto-char pos)
26047 (if (<= (current-column) (current-indentation))
26048 (indent-line-to column)
26049 (save-excursion (indent-line-to column)))
26050 (setq column (current-column))
26051 (beginning-of-line 1)
26052 (if (looking-at
26053 "\\([ \t]+\\)\\(:[0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
26054 (replace-match (concat "\\1" (format org-property-format
26055 (match-string 2) (match-string 3)))
26056 t nil))
26057 (move-to-column column)))
26059 (defun org-set-autofill-regexps ()
26060 (interactive)
26061 ;; In the paragraph separator we include headlines, because filling
26062 ;; text in a line directly attached to a headline would otherwise
26063 ;; fill the headline as well.
26064 (org-set-local 'comment-start-skip "^#+[ \t]*")
26065 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
26066 ;; The paragraph starter includes hand-formatted lists.
26067 (org-set-local 'paragraph-start
26068 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
26069 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
26070 ;; But only if the user has not turned off tables or fixed-width regions
26071 (org-set-local
26072 'auto-fill-inhibit-regexp
26073 (concat "\\*+ \\|#\\+"
26074 "\\|[ \t]*" org-keyword-time-regexp
26075 (if (or org-enable-table-editor org-enable-fixed-width-editor)
26076 (concat
26077 "\\|[ \t]*["
26078 (if org-enable-table-editor "|" "")
26079 (if org-enable-fixed-width-editor ":" "")
26080 "]"))))
26081 ;; We use our own fill-paragraph function, to make sure that tables
26082 ;; and fixed-width regions are not wrapped. That function will pass
26083 ;; through to `fill-paragraph' when appropriate.
26084 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
26085 ; Adaptive filling: To get full control, first make sure that
26086 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
26087 (org-set-local 'adaptive-fill-regexp "\000")
26088 (org-set-local 'adaptive-fill-function
26089 'org-adaptive-fill-function))
26091 (defun org-fill-paragraph (&optional justify)
26092 "Re-align a table, pass through to fill-paragraph if no table."
26093 (let ((table-p (org-at-table-p))
26094 (table.el-p (org-at-table.el-p)))
26095 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
26096 (table.el-p t) ; skip table.el tables
26097 (table-p (org-table-align) t) ; align org-mode tables
26098 (t nil)))) ; call paragraph-fill
26100 ;; For reference, this is the default value of adaptive-fill-regexp
26101 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
26103 (defun org-adaptive-fill-function ()
26104 "Return a fill prefix for org-mode files.
26105 In particular, this makes sure hanging paragraphs for hand-formatted lists
26106 work correctly."
26107 (cond ((looking-at "#[ \t]+")
26108 (match-string 0))
26109 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
26110 (save-excursion
26111 (goto-char (match-end 0))
26112 (make-string (current-column) ?\ )))
26113 (t nil)))
26115 ;;;; Functions extending outline functionality
26117 (defun org-beginning-of-line (&optional arg)
26118 "Go to the beginning of the current line. If that is invisible, continue
26119 to a visible line beginning. This makes the function of C-a more intuitive.
26120 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
26121 first attempt, and only move to after the tags when the cursor is already
26122 beyond the end of the headline."
26123 (interactive "P")
26124 (let ((pos (point)))
26125 (beginning-of-line 1)
26126 (if (bobp)
26128 (backward-char 1)
26129 (if (org-invisible-p)
26130 (while (and (not (bobp)) (org-invisible-p))
26131 (backward-char 1)
26132 (beginning-of-line 1))
26133 (forward-char 1)))
26134 (when org-special-ctrl-a/e
26135 (cond
26136 ((and (looking-at org-todo-line-regexp)
26137 (= (char-after (match-end 1)) ?\ ))
26138 (goto-char
26139 (if (eq org-special-ctrl-a/e t)
26140 (cond ((> pos (match-beginning 3)) (match-beginning 3))
26141 ((= pos (point)) (match-beginning 3))
26142 (t (point)))
26143 (cond ((> pos (point)) (point))
26144 ((not (eq last-command this-command)) (point))
26145 (t (match-beginning 3))))))
26146 ((org-at-item-p)
26147 (goto-char
26148 (if (eq org-special-ctrl-a/e t)
26149 (cond ((> pos (match-end 4)) (match-end 4))
26150 ((= pos (point)) (match-end 4))
26151 (t (point)))
26152 (cond ((> pos (point)) (point))
26153 ((not (eq last-command this-command)) (point))
26154 (t (match-end 4))))))))))
26156 (defun org-end-of-line (&optional arg)
26157 "Go to the end of the line.
26158 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
26159 first attempt, and only move to after the tags when the cursor is already
26160 beyond the end of the headline."
26161 (interactive "P")
26162 (if (or (not org-special-ctrl-a/e)
26163 (not (org-on-heading-p)))
26164 (end-of-line arg)
26165 (let ((pos (point)))
26166 (beginning-of-line 1)
26167 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
26168 (if (eq org-special-ctrl-a/e t)
26169 (if (or (< pos (match-beginning 1))
26170 (= pos (match-end 0)))
26171 (goto-char (match-beginning 1))
26172 (goto-char (match-end 0)))
26173 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
26174 (goto-char (match-end 0))
26175 (goto-char (match-beginning 1))))
26176 (end-of-line arg)))))
26178 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
26179 (define-key org-mode-map "\C-e" 'org-end-of-line)
26181 (defun org-invisible-p ()
26182 "Check if point is at a character currently not visible."
26183 ;; Early versions of noutline don't have `outline-invisible-p'.
26184 (if (fboundp 'outline-invisible-p)
26185 (outline-invisible-p)
26186 (get-char-property (point) 'invisible)))
26188 (defun org-invisible-p2 ()
26189 "Check if point is at a character currently not visible."
26190 (save-excursion
26191 (if (and (eolp) (not (bobp))) (backward-char 1))
26192 ;; Early versions of noutline don't have `outline-invisible-p'.
26193 (if (fboundp 'outline-invisible-p)
26194 (outline-invisible-p)
26195 (get-char-property (point) 'invisible))))
26197 (defalias 'org-back-to-heading 'outline-back-to-heading)
26198 (defalias 'org-on-heading-p 'outline-on-heading-p)
26199 (defalias 'org-at-heading-p 'outline-on-heading-p)
26200 (defun org-at-heading-or-item-p ()
26201 (or (org-on-heading-p) (org-at-item-p)))
26203 (defun org-on-target-p ()
26204 (or (org-in-regexp org-radio-target-regexp)
26205 (org-in-regexp org-target-regexp)))
26207 (defun org-up-heading-all (arg)
26208 "Move to the heading line of which the present line is a subheading.
26209 This function considers both visible and invisible heading lines.
26210 With argument, move up ARG levels."
26211 (if (fboundp 'outline-up-heading-all)
26212 (outline-up-heading-all arg) ; emacs 21 version of outline.el
26213 (outline-up-heading arg t))) ; emacs 22 version of outline.el
26215 (defun org-up-heading-safe ()
26216 "Move to the heading line of which the present line is a subheading.
26217 This version will not throw an error. It will return the level of the
26218 headline found, or nil if no higher level is found."
26219 (let ((pos (point)) start-level level
26220 (re (concat "^" outline-regexp)))
26221 (catch 'exit
26222 (outline-back-to-heading t)
26223 (setq start-level (funcall outline-level))
26224 (if (equal start-level 1) (throw 'exit nil))
26225 (while (re-search-backward re nil t)
26226 (setq level (funcall outline-level))
26227 (if (< level start-level) (throw 'exit level)))
26228 nil)))
26230 (defun org-goto-sibling (&optional previous)
26231 "Goto the next sibling, even if it is invisible.
26232 When PREVIOUS is set, go to the previous sibling instead. Returns t
26233 when a sibling was found. When none is found, return nil and don't
26234 move point."
26235 (let ((fun (if previous 're-search-backward 're-search-forward))
26236 (pos (point))
26237 (re (concat "^" outline-regexp))
26238 level l)
26239 (when (condition-case nil (org-back-to-heading t) (error nil))
26240 (setq level (funcall outline-level))
26241 (catch 'exit
26242 (or previous (forward-char 1))
26243 (while (funcall fun re nil t)
26244 (setq l (funcall outline-level))
26245 (when (< l level) (goto-char pos) (throw 'exit nil))
26246 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
26247 (goto-char pos)
26248 nil))))
26250 (defun org-show-siblings ()
26251 "Show all siblings of the current headline."
26252 (save-excursion
26253 (while (org-goto-sibling) (org-flag-heading nil)))
26254 (save-excursion
26255 (while (org-goto-sibling 'previous)
26256 (org-flag-heading nil))))
26258 (defun org-show-hidden-entry ()
26259 "Show an entry where even the heading is hidden."
26260 (save-excursion
26261 (org-show-entry)))
26263 (defun org-flag-heading (flag &optional entry)
26264 "Flag the current heading. FLAG non-nil means make invisible.
26265 When ENTRY is non-nil, show the entire entry."
26266 (save-excursion
26267 (org-back-to-heading t)
26268 ;; Check if we should show the entire entry
26269 (if entry
26270 (progn
26271 (org-show-entry)
26272 (save-excursion
26273 (and (outline-next-heading)
26274 (org-flag-heading nil))))
26275 (outline-flag-region (max (point-min) (1- (point)))
26276 (save-excursion (outline-end-of-heading) (point))
26277 flag))))
26279 (defun org-end-of-subtree (&optional invisible-OK to-heading)
26280 ;; This is an exact copy of the original function, but it uses
26281 ;; `org-back-to-heading', to make it work also in invisible
26282 ;; trees. And is uses an invisible-OK argument.
26283 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
26284 (org-back-to-heading invisible-OK)
26285 (let ((first t)
26286 (level (funcall outline-level)))
26287 (while (and (not (eobp))
26288 (or first (> (funcall outline-level) level)))
26289 (setq first nil)
26290 (outline-next-heading))
26291 (unless to-heading
26292 (if (memq (preceding-char) '(?\n ?\^M))
26293 (progn
26294 ;; Go to end of line before heading
26295 (forward-char -1)
26296 (if (memq (preceding-char) '(?\n ?\^M))
26297 ;; leave blank line before heading
26298 (forward-char -1))))))
26299 (point))
26301 (defun org-show-subtree ()
26302 "Show everything after this heading at deeper levels."
26303 (outline-flag-region
26304 (point)
26305 (save-excursion
26306 (outline-end-of-subtree) (outline-next-heading) (point))
26307 nil))
26309 (defun org-show-entry ()
26310 "Show the body directly following this heading.
26311 Show the heading too, if it is currently invisible."
26312 (interactive)
26313 (save-excursion
26314 (condition-case nil
26315 (progn
26316 (org-back-to-heading t)
26317 (outline-flag-region
26318 (max (point-min) (1- (point)))
26319 (save-excursion
26320 (re-search-forward
26321 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
26322 (or (match-beginning 1) (point-max)))
26323 nil))
26324 (error nil))))
26326 (defun org-make-options-regexp (kwds)
26327 "Make a regular expression for keyword lines."
26328 (concat
26330 "#?[ \t]*\\+\\("
26331 (mapconcat 'regexp-quote kwds "\\|")
26332 "\\):[ \t]*"
26333 "\\(.+\\)"))
26335 ;; Make isearch reveal the necessary context
26336 (defun org-isearch-end ()
26337 "Reveal context after isearch exits."
26338 (when isearch-success ; only if search was successful
26339 (if (featurep 'xemacs)
26340 ;; Under XEmacs, the hook is run in the correct place,
26341 ;; we directly show the context.
26342 (org-show-context 'isearch)
26343 ;; In Emacs the hook runs *before* restoring the overlays.
26344 ;; So we have to use a one-time post-command-hook to do this.
26345 ;; (Emacs 22 has a special variable, see function `org-mode')
26346 (unless (and (boundp 'isearch-mode-end-hook-quit)
26347 isearch-mode-end-hook-quit)
26348 ;; Only when the isearch was not quitted.
26349 (org-add-hook 'post-command-hook 'org-isearch-post-command
26350 'append 'local)))))
26352 (defun org-isearch-post-command ()
26353 "Remove self from hook, and show context."
26354 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
26355 (org-show-context 'isearch))
26358 ;;;; Address problems with some other packages
26360 ;; Make flyspell not check words in links, to not mess up our keymap
26361 (defun org-mode-flyspell-verify ()
26362 "Don't let flyspell put overlays at active buttons."
26363 (not (get-text-property (point) 'keymap)))
26365 ;; Make `bookmark-jump' show the jump location if it was hidden.
26366 (eval-after-load "bookmark"
26367 '(if (boundp 'bookmark-after-jump-hook)
26368 ;; We can use the hook
26369 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
26370 ;; Hook not available, use advice
26371 (defadvice bookmark-jump (after org-make-visible activate)
26372 "Make the position visible."
26373 (org-bookmark-jump-unhide))))
26375 (defun org-bookmark-jump-unhide ()
26376 "Unhide the current position, to show the bookmark location."
26377 (and (org-mode-p)
26378 (or (org-invisible-p)
26379 (save-excursion (goto-char (max (point-min) (1- (point))))
26380 (org-invisible-p)))
26381 (org-show-context 'bookmark-jump)))
26383 ;; Make session.el ignore our circular variable
26384 (eval-after-load "session"
26385 '(add-to-list 'session-globals-exclude 'org-mark-ring))
26387 ;;;; Experimental code
26389 (defun org-closed-in-range ()
26390 "Sparse tree of items closed in a certain time range.
26391 Still experimental, may disappear in the furture."
26392 (interactive)
26393 ;; Get the time interval from the user.
26394 (let* ((time1 (time-to-seconds
26395 (org-read-date nil 'to-time nil "Starting date: ")))
26396 (time2 (time-to-seconds
26397 (org-read-date nil 'to-time nil "End date:")))
26398 ;; callback function
26399 (callback (lambda ()
26400 (let ((time
26401 (time-to-seconds
26402 (apply 'encode-time
26403 (org-parse-time-string
26404 (match-string 1))))))
26405 ;; check if time in interval
26406 (and (>= time time1) (<= time time2))))))
26407 ;; make tree, check each match with the callback
26408 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
26410 (defun org-fill-paragraph-experimental (&optional justify)
26411 "Re-align a table, pass through to fill-paragraph if no table."
26412 (let ((table-p (org-at-table-p))
26413 (table.el-p (org-at-table.el-p)))
26414 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
26415 (table.el-p t) ; skip table.el tables
26416 (table-p (org-table-align) t) ; align org-mode tables
26417 ((save-excursion
26418 (let ((pos (1+ (point-at-eol))))
26419 (backward-paragraph 1)
26420 (re-search-forward "\\\\\\\\[ \t]*$" pos t)))
26421 (save-excursion
26422 (save-restriction
26423 (narrow-to-region (1+ (match-end 0)) (point-max))
26424 (fill-paragraph nil)
26425 t)))
26426 (t nil)))) ; call paragraph-fill
26428 ;; FIXME: this needs a much better algorithm
26429 (defun org-assign-fast-keys (alist)
26430 "Assign fast keys to a keyword-key alist.
26431 Respect keys that are already there."
26432 (let (new e k c c1 c2 (char ?a))
26433 (while (setq e (pop alist))
26434 (cond
26435 ((equal e '(:startgroup)) (push e new))
26436 ((equal e '(:endgroup)) (push e new))
26438 (setq k (car e) c2 nil)
26439 (if (cdr e)
26440 (setq c (cdr e))
26441 ;; automatically assign a character.
26442 (setq c1 (string-to-char
26443 (downcase (substring
26444 k (if (= (string-to-char k) ?@) 1 0)))))
26445 (if (or (rassoc c1 new) (rassoc c1 alist))
26446 (while (or (rassoc char new) (rassoc char alist))
26447 (setq char (1+ char)))
26448 (setq c2 c1))
26449 (setq c (or c2 char)))
26450 (push (cons k c) new))))
26451 (nreverse new)))
26453 ;(defcustom org-read-date-prefer-future nil
26454 ; "Non-nil means, when reading an incomplete date from the user, assume future.
26455 ;This affects the following situations:
26456 ;1. The user give a day, but no month.
26457 ; In this case, if the day number if after today, the current month will
26458 ; be used, otherwise the next month.
26459 ;2. The user gives a month but not a year.
26460 ; In this case, the the given month is after the current month, the current
26461 ; year will be used. Otherwise the next year will be used.;
26463 ;When nil, always the current month and year will be used."
26464 ; :group 'org-time ;????
26465 ; :type 'boolean)
26468 ;;;; Finish up
26470 (provide 'org)
26472 (run-hooks 'org-load-hook)
26474 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
26475 ;;; org.el ends here