Updated the ChangeLog against latest changes.
[org-mode.git] / org.el
blobb10fb418e7bd2676863188abea68ca2079e4d39c
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, 2008 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.22a+
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 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
81 (require 'easymenu)
83 ;;;; Customization variables
85 ;;; Version
87 (defconst org-version "5.22a+"
88 "The version number of the file org.el.")
90 (defun org-version (&optional here)
91 "Show the org-mode version in the echo area.
92 With prefix arg HERE, insert it at point."
93 (interactive "P")
94 (let ((version (format "Org-mode version %s" org-version)))
95 (message version)
96 (if here
97 (insert version))))
99 ;;; Compatibility constants
100 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
101 (defconst org-format-transports-properties-p
102 (let ((x "a"))
103 (add-text-properties 0 1 '(test t) x)
104 (get-text-property 0 'test (format "%s" x)))
105 "Does format transport text properties?")
107 (defmacro org-bound-and-true-p (var)
108 "Return the value of symbol VAR if it is bound, else nil."
109 `(and (boundp (quote ,var)) ,var))
111 (defmacro org-unmodified (&rest body)
112 "Execute body without changing `buffer-modified-p'."
113 `(set-buffer-modified-p
114 (prog1 (buffer-modified-p) ,@body)))
116 (defmacro org-re (s)
117 "Replace posix classes in regular expression."
118 (if (featurep 'xemacs)
119 (let ((ss s))
120 (save-match-data
121 (while (string-match "\\[:alnum:\\]" ss)
122 (setq ss (replace-match "a-zA-Z0-9" t t ss)))
123 (while (string-match "\\[:alpha:\\]" ss)
124 (setq ss (replace-match "a-zA-Z" t t ss)))
125 ss))
128 (defmacro org-preserve-lc (&rest body)
129 `(let ((_line (org-current-line))
130 (_col (current-column)))
131 (unwind-protect
132 (progn ,@body)
133 (goto-line _line)
134 (move-to-column _col))))
136 (defmacro org-without-partial-completion (&rest body)
137 `(let ((pc-mode (and (boundp 'partial-completion-mode)
138 partial-completion-mode)))
139 (unwind-protect
140 (progn
141 (if pc-mode (partial-completion-mode -1))
142 ,@body)
143 (if pc-mode (partial-completion-mode 1)))))
145 ;;; The custom variables
147 (defgroup org nil
148 "Outline-based notes management and organizer."
149 :tag "Org"
150 :group 'outlines
151 :group 'hypermedia
152 :group 'calendar)
154 ;; FIXME: Needs a separate group...
155 (defcustom org-completion-fallback-command 'hippie-expand
156 "The expansion command called by \\[org-complete] in normal context.
157 Normal means, no org-mode-specific context."
158 :group 'org
159 :type 'function)
161 (defgroup org-startup nil
162 "Options concerning startup of Org-mode."
163 :tag "Org Startup"
164 :group 'org)
166 (defcustom org-startup-folded t
167 "Non-nil means, entering Org-mode will switch to OVERVIEW.
168 This can also be configured on a per-file basis by adding one of
169 the following lines anywhere in the buffer:
171 #+STARTUP: fold
172 #+STARTUP: nofold
173 #+STARTUP: content"
174 :group 'org-startup
175 :type '(choice
176 (const :tag "nofold: show all" nil)
177 (const :tag "fold: overview" t)
178 (const :tag "content: all headlines" content)))
180 (defcustom org-startup-truncated t
181 "Non-nil means, entering Org-mode will set `truncate-lines'.
182 This is useful since some lines containing links can be very long and
183 uninteresting. Also tables look terrible when wrapped."
184 :group 'org-startup
185 :type 'boolean)
187 (defcustom org-startup-align-all-tables nil
188 "Non-nil means, align all tables when visiting a file.
189 This is useful when the column width in tables is forced with <N> cookies
190 in table fields. Such tables will look correct only after the first re-align.
191 This can also be configured on a per-file basis by adding one of
192 the following lines anywhere in the buffer:
193 #+STARTUP: align
194 #+STARTUP: noalign"
195 :group 'org-startup
196 :type 'boolean)
198 (defcustom org-insert-mode-line-in-empty-file nil
199 "Non-nil means insert the first line setting Org-mode in empty files.
200 When the function `org-mode' is called interactively in an empty file, this
201 normally means that the file name does not automatically trigger Org-mode.
202 To ensure that the file will always be in Org-mode in the future, a
203 line enforcing Org-mode will be inserted into the buffer, if this option
204 has been set."
205 :group 'org-startup
206 :type 'boolean)
208 (defcustom org-replace-disputed-keys nil
209 "Non-nil means use alternative key bindings for some keys.
210 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
211 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
212 If you want to use Org-mode together with one of these other modes,
213 or more generally if you would like to move some Org-mode commands to
214 other keys, set this variable and configure the keys with the variable
215 `org-disputed-keys'.
217 This option is only relevant at load-time of Org-mode, and must be set
218 *before* org.el is loaded. Changing it requires a restart of Emacs to
219 become effective."
220 :group 'org-startup
221 :type 'boolean)
223 (if (fboundp 'defvaralias)
224 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
226 (defcustom org-disputed-keys
227 '(([(shift up)] . [(meta p)])
228 ([(shift down)] . [(meta n)])
229 ([(shift left)] . [(meta -)])
230 ([(shift right)] . [(meta +)])
231 ([(control shift right)] . [(meta shift +)])
232 ([(control shift left)] . [(meta shift -)]))
233 "Keys for which Org-mode and other modes compete.
234 This is an alist, cars are the default keys, second element specifies
235 the alternative to use when `org-replace-disputed-keys' is t.
237 Keys can be specified in any syntax supported by `define-key'.
238 The value of this option takes effect only at Org-mode's startup,
239 therefore you'll have to restart Emacs to apply it after changing."
240 :group 'org-startup
241 :type 'alist)
243 (defun org-key (key)
244 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
245 Or return the original if not disputed."
246 (if org-replace-disputed-keys
247 (let* ((nkey (key-description key))
248 (x (org-find-if (lambda (x)
249 (equal (key-description (car x)) nkey))
250 org-disputed-keys)))
251 (if x (cdr x) key))
252 key))
254 (defun org-find-if (predicate seq)
255 (catch 'exit
256 (while seq
257 (if (funcall predicate (car seq))
258 (throw 'exit (car seq))
259 (pop seq)))))
261 (defun org-defkey (keymap key def)
262 "Define a key, possibly translated, as returned by `org-key'."
263 (define-key keymap (org-key key) def))
265 (defcustom org-ellipsis nil
266 "The ellipsis to use in the Org-mode outline.
267 When nil, just use the standard three dots. When a string, use that instead,
268 When a face, use the standart 3 dots, but with the specified face.
269 The change affects only Org-mode (which will then use its own display table).
270 Changing this requires executing `M-x org-mode' in a buffer to become
271 effective."
272 :group 'org-startup
273 :type '(choice (const :tag "Default" nil)
274 (face :tag "Face" :value org-warning)
275 (string :tag "String" :value "...#")))
277 (defvar org-display-table nil
278 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
280 (defgroup org-keywords nil
281 "Keywords in Org-mode."
282 :tag "Org Keywords"
283 :group 'org)
285 (defcustom org-deadline-string "DEADLINE:"
286 "String to mark deadline entries.
287 A deadline is this string, followed by a time stamp. Should be a word,
288 terminated by a colon. You can insert a schedule keyword and
289 a timestamp with \\[org-deadline].
290 Changes become only effective after restarting Emacs."
291 :group 'org-keywords
292 :type 'string)
294 (defcustom org-scheduled-string "SCHEDULED:"
295 "String to mark scheduled TODO entries.
296 A schedule is this string, followed by a time stamp. Should be a word,
297 terminated by a colon. You can insert a schedule keyword and
298 a timestamp with \\[org-schedule].
299 Changes become only effective after restarting Emacs."
300 :group 'org-keywords
301 :type 'string)
303 (defcustom org-closed-string "CLOSED:"
304 "String used as the prefix for timestamps logging closing a TODO entry."
305 :group 'org-keywords
306 :type 'string)
308 (defcustom org-clock-string "CLOCK:"
309 "String used as prefix for timestamps clocking work hours on an item."
310 :group 'org-keywords
311 :type 'string)
313 (defcustom org-comment-string "COMMENT"
314 "Entries starting with this keyword will never be exported.
315 An entry can be toggled between COMMENT and normal with
316 \\[org-toggle-comment].
317 Changes become only effective after restarting Emacs."
318 :group 'org-keywords
319 :type 'string)
321 (defcustom org-quote-string "QUOTE"
322 "Entries starting with this keyword will be exported in fixed-width font.
323 Quoting applies only to the text in the entry following the headline, and does
324 not extend beyond the next headline, even if that is lower level.
325 An entry can be toggled between QUOTE and normal with
326 \\[org-toggle-fixed-width-section]."
327 :group 'org-keywords
328 :type 'string)
330 (defconst org-repeat-re
331 ; (concat "\\(?:\\<\\(?:" org-scheduled-string "\\|" org-deadline-string "\\)"
332 ; " +<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\)\\(\\+[0-9]+[dwmy]\\)")
333 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\(\\+[0-9]+[dwmy]\\)"
334 "Regular expression for specifying repeated events.
335 After a match, group 1 contains the repeat expression.")
337 (defgroup org-structure nil
338 "Options concerning the general structure of Org-mode files."
339 :tag "Org Structure"
340 :group 'org)
342 (defgroup org-reveal-location nil
343 "Options about how to make context of a location visible."
344 :tag "Org Reveal Location"
345 :group 'org-structure)
347 (defconst org-context-choice
348 '(choice
349 (const :tag "Always" t)
350 (const :tag "Never" nil)
351 (repeat :greedy t :tag "Individual contexts"
352 (cons
353 (choice :tag "Context"
354 (const agenda)
355 (const org-goto)
356 (const occur-tree)
357 (const tags-tree)
358 (const link-search)
359 (const mark-goto)
360 (const bookmark-jump)
361 (const isearch)
362 (const default))
363 (boolean))))
364 "Contexts for the reveal options.")
366 (defcustom org-show-hierarchy-above '((default . t))
367 "Non-nil means, show full hierarchy when revealing a location.
368 Org-mode often shows locations in an org-mode file which might have
369 been invisible before. When this is set, the hierarchy of headings
370 above the exposed location is shown.
371 Turning this off for example for sparse trees makes them very compact.
372 Instead of t, this can also be an alist specifying this option for different
373 contexts. Valid contexts are
374 agenda when exposing an entry from the agenda
375 org-goto when using the command `org-goto' on key C-c C-j
376 occur-tree when using the command `org-occur' on key C-c /
377 tags-tree when constructing a sparse tree based on tags matches
378 link-search when exposing search matches associated with a link
379 mark-goto when exposing the jump goal of a mark
380 bookmark-jump when exposing a bookmark location
381 isearch when exiting from an incremental search
382 default default for all contexts not set explicitly"
383 :group 'org-reveal-location
384 :type org-context-choice)
386 (defcustom org-show-following-heading '((default . nil))
387 "Non-nil means, show following heading when revealing a location.
388 Org-mode often shows locations in an org-mode file which might have
389 been invisible before. When this is set, the heading following the
390 match is shown.
391 Turning this off for example for sparse trees makes them very compact,
392 but makes it harder to edit the location of the match. In such a case,
393 use the command \\[org-reveal] to show more context.
394 Instead of t, this can also be an alist specifying this option for different
395 contexts. See `org-show-hierarchy-above' for valid contexts."
396 :group 'org-reveal-location
397 :type org-context-choice)
399 (defcustom org-show-siblings '((default . nil) (isearch t))
400 "Non-nil means, show all sibling heading when revealing a location.
401 Org-mode often shows locations in an org-mode file which might have
402 been invisible before. When this is set, the sibling of the current entry
403 heading are all made visible. If `org-show-hierarchy-above' is t,
404 the same happens on each level of the hierarchy above the current entry.
406 By default this is on for the isearch context, off for all other contexts.
407 Turning this off for example for sparse trees makes them very compact,
408 but makes it harder to edit the location of the match. In such a case,
409 use the command \\[org-reveal] to show more context.
410 Instead of t, this can also be an alist specifying this option for different
411 contexts. See `org-show-hierarchy-above' for valid contexts."
412 :group 'org-reveal-location
413 :type org-context-choice)
415 (defcustom org-show-entry-below '((default . nil))
416 "Non-nil means, show the entry below a headline when revealing a location.
417 Org-mode often shows locations in an org-mode file which might have
418 been invisible before. When this is set, the text below the headline that is
419 exposed is also shown.
421 By default this is off for all contexts.
422 Instead of t, this can also be an alist specifying this option for different
423 contexts. See `org-show-hierarchy-above' for valid contexts."
424 :group 'org-reveal-location
425 :type org-context-choice)
427 (defgroup org-cycle nil
428 "Options concerning visibility cycling in Org-mode."
429 :tag "Org Cycle"
430 :group 'org-structure)
432 (defcustom org-drawers '("PROPERTIES" "CLOCK")
433 "Names of drawers. Drawers are not opened by cycling on the headline above.
434 Drawers only open with a TAB on the drawer line itself. A drawer looks like
435 this:
436 :DRAWERNAME:
437 .....
438 :END:
439 The drawer \"PROPERTIES\" is special for capturing properties through
440 the property API.
442 Drawers can be defined on the per-file basis with a line like:
444 #+DRAWERS: HIDDEN STATE PROPERTIES"
445 :group 'org-structure
446 :type '(repeat (string :tag "Drawer Name")))
448 (defcustom org-cycle-global-at-bob nil
449 "Cycle globally if cursor is at beginning of buffer and not at a headline.
450 This makes it possible to do global cycling without having to use S-TAB or
451 C-u TAB. For this special case to work, the first line of the buffer
452 must not be a headline - it may be empty ot some other text. When used in
453 this way, `org-cycle-hook' is disables temporarily, to make sure the
454 cursor stays at the beginning of the buffer.
455 When this option is nil, don't do anything special at the beginning
456 of the buffer."
457 :group 'org-cycle
458 :type 'boolean)
460 (defcustom org-cycle-emulate-tab t
461 "Where should `org-cycle' emulate TAB.
462 nil Never
463 white Only in completely white lines
464 whitestart Only at the beginning of lines, before the first non-white char
465 t Everywhere except in headlines
466 exc-hl-bol Everywhere except at the start of a headline
467 If TAB is used in a place where it does not emulate TAB, the current subtree
468 visibility is cycled."
469 :group 'org-cycle
470 :type '(choice (const :tag "Never" nil)
471 (const :tag "Only in completely white lines" white)
472 (const :tag "Before first char in a line" whitestart)
473 (const :tag "Everywhere except in headlines" t)
474 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
477 (defcustom org-cycle-separator-lines 2
478 "Number of empty lines needed to keep an empty line between collapsed trees.
479 If you leave an empty line between the end of a subtree and the following
480 headline, this empty line is hidden when the subtree is folded.
481 Org-mode will leave (exactly) one empty line visible if the number of
482 empty lines is equal or larger to the number given in this variable.
483 So the default 2 means, at least 2 empty lines after the end of a subtree
484 are needed to produce free space between a collapsed subtree and the
485 following headline.
487 Special case: when 0, never leave empty lines in collapsed view."
488 :group 'org-cycle
489 :type 'integer)
491 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
492 org-cycle-hide-drawers
493 org-cycle-show-empty-lines
494 org-optimize-window-after-visibility-change)
495 "Hook that is run after `org-cycle' has changed the buffer visibility.
496 The function(s) in this hook must accept a single argument which indicates
497 the new state that was set by the most recent `org-cycle' command. The
498 argument is a symbol. After a global state change, it can have the values
499 `overview', `content', or `all'. After a local state change, it can have
500 the values `folded', `children', or `subtree'."
501 :group 'org-cycle
502 :type 'hook)
504 (defgroup org-edit-structure nil
505 "Options concerning structure editing in Org-mode."
506 :tag "Org Edit Structure"
507 :group 'org-structure)
509 (defcustom org-odd-levels-only nil
510 "Non-nil means, skip even levels and only use odd levels for the outline.
511 This has the effect that two stars are being added/taken away in
512 promotion/demotion commands. It also influences how levels are
513 handled by the exporters.
514 Changing it requires restart of `font-lock-mode' to become effective
515 for fontification also in regions already fontified.
516 You may also set this on a per-file basis by adding one of the following
517 lines to the buffer:
519 #+STARTUP: odd
520 #+STARTUP: oddeven"
521 :group 'org-edit-structure
522 :group 'org-font-lock
523 :type 'boolean)
525 (defcustom org-adapt-indentation t
526 "Non-nil means, adapt indentation when promoting and demoting.
527 When this is set and the *entire* text in an entry is indented, the
528 indentation is increased by one space in a demotion command, and
529 decreased by one in a promotion command. If any line in the entry
530 body starts at column 0, indentation is not changed at all."
531 :group 'org-edit-structure
532 :type 'boolean)
534 (defcustom org-special-ctrl-a/e nil
535 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
536 When t, `C-a' will bring back the cursor to the beginning of the
537 headline text, i.e. after the stars and after a possible TODO keyword.
538 In an item, this will be the position after the bullet.
539 When the cursor is already at that position, another `C-a' will bring
540 it to the beginning of the line.
541 `C-e' will jump to the end of the headline, ignoring the presence of tags
542 in the headline. A second `C-e' will then jump to the true end of the
543 line, after any tags.
544 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
545 and only a directly following, identical keypress will bring the cursor
546 to the special positions."
547 :group 'org-edit-structure
548 :type '(choice
549 (const :tag "off" nil)
550 (const :tag "after bullet first" t)
551 (const :tag "border first" reversed)))
553 (if (fboundp 'defvaralias)
554 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
556 (defcustom org-special-ctrl-k nil
557 "Non-nil means `C-k' will behave specially in headlines.
558 When nil, `C-k' will call the default `kill-line' command.
559 When t, the following will happen while the cursor is in the headline:
561 - When the cursor is at the beginning of a headline, kill the entire
562 line and possible the folded subtree below the line.
563 - When in the middle of the headline text, kill the headline up to the tags.
564 - When after the headline text, kill the tags."
565 :group 'org-edit-structure
566 :type 'boolean)
568 (defcustom org-M-RET-may-split-line '((default . t))
569 "Non-nil means, M-RET will split the line at the cursor position.
570 When nil, it will go to the end of the line before making a
571 new line.
572 You may also set this option in a different way for different
573 contexts. Valid contexts are:
575 headline when creating a new headline
576 item when creating a new item
577 table in a table field
578 default the value to be used for all contexts not explicitly
579 customized"
580 :group 'org-structure
581 :group 'org-table
582 :type '(choice
583 (const :tag "Always" t)
584 (const :tag "Never" nil)
585 (repeat :greedy t :tag "Individual contexts"
586 (cons
587 (choice :tag "Context"
588 (const headline)
589 (const item)
590 (const table)
591 (const default))
592 (boolean)))))
595 (defcustom org-blank-before-new-entry '((heading . nil)
596 (plain-list-item . nil))
597 "Should `org-insert-heading' leave a blank line before new heading/item?
598 The value is an alist, with `heading' and `plain-list-item' as car,
599 and a boolean flag as cdr."
600 :group 'org-edit-structure
601 :type '(list
602 (cons (const heading) (boolean))
603 (cons (const plain-list-item) (boolean))))
605 (defcustom org-insert-heading-hook nil
606 "Hook being run after inserting a new heading."
607 :group 'org-edit-structure
608 :type 'hook)
610 (defcustom org-enable-fixed-width-editor t
611 "Non-nil means, lines starting with \":\" are treated as fixed-width.
612 This currently only means, they are never auto-wrapped.
613 When nil, such lines will be treated like ordinary lines.
614 See also the QUOTE keyword."
615 :group 'org-edit-structure
616 :type 'boolean)
618 (defcustom org-goto-auto-isearch t
619 "Non-nil means, typing characters in org-goto starts incremental search."
620 :group 'org-edit-structure
621 :type 'boolean)
623 (defgroup org-sparse-trees nil
624 "Options concerning sparse trees in Org-mode."
625 :tag "Org Sparse Trees"
626 :group 'org-structure)
628 (defcustom org-highlight-sparse-tree-matches t
629 "Non-nil means, highlight all matches that define a sparse tree.
630 The highlights will automatically disappear the next time the buffer is
631 changed by an edit command."
632 :group 'org-sparse-trees
633 :type 'boolean)
635 (defcustom org-remove-highlights-with-change t
636 "Non-nil means, any change to the buffer will remove temporary highlights.
637 Such highlights are created by `org-occur' and `org-clock-display'.
638 When nil, `C-c C-c needs to be used to get rid of the highlights.
639 The highlights created by `org-preview-latex-fragment' always need
640 `C-c C-c' to be removed."
641 :group 'org-sparse-trees
642 :group 'org-time
643 :type 'boolean)
646 (defcustom org-occur-hook '(org-first-headline-recenter)
647 "Hook that is run after `org-occur' has constructed a sparse tree.
648 This can be used to recenter the window to show as much of the structure
649 as possible."
650 :group 'org-sparse-trees
651 :type 'hook)
653 (defgroup org-plain-lists nil
654 "Options concerning plain lists in Org-mode."
655 :tag "Org Plain lists"
656 :group 'org-structure)
658 (defcustom org-cycle-include-plain-lists nil
659 "Non-nil means, include plain lists into visibility cycling.
660 This means that during cycling, plain list items will *temporarily* be
661 interpreted as outline headlines with a level given by 1000+i where i is the
662 indentation of the bullet. In all other operations, plain list items are
663 not seen as headlines. For example, you cannot assign a TODO keyword to
664 such an item."
665 :group 'org-plain-lists
666 :type 'boolean)
668 (defcustom org-plain-list-ordered-item-terminator t
669 "The character that makes a line with leading number an ordered list item.
670 Valid values are ?. and ?\). To get both terminators, use t. While
671 ?. may look nicer, it creates the danger that a line with leading
672 number may be incorrectly interpreted as an item. ?\) therefore is
673 the safe choice."
674 :group 'org-plain-lists
675 :type '(choice (const :tag "dot like in \"2.\"" ?.)
676 (const :tag "paren like in \"2)\"" ?\))
677 (const :tab "both" t)))
679 (defcustom org-auto-renumber-ordered-lists t
680 "Non-nil means, automatically renumber ordered plain lists.
681 Renumbering happens when the sequence have been changed with
682 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
683 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
684 :group 'org-plain-lists
685 :type 'boolean)
687 (defcustom org-provide-checkbox-statistics t
688 "Non-nil means, update checkbox statistics after insert and toggle.
689 When this is set, checkbox statistics is updated each time you either insert
690 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
691 with \\[org-ctrl-c-ctrl-c\\]."
692 :group 'org-plain-lists
693 :type 'boolean)
695 (defgroup org-archive nil
696 "Options concerning archiving in Org-mode."
697 :tag "Org Archive"
698 :group 'org-structure)
700 (defcustom org-archive-tag "ARCHIVE"
701 "The tag that marks a subtree as archived.
702 An archived subtree does not open during visibility cycling, and does
703 not contribute to the agenda listings.
704 After changing this, font-lock must be restarted in the relevant buffers to
705 get the proper fontification."
706 :group 'org-archive
707 :group 'org-keywords
708 :type 'string)
710 (defcustom org-agenda-skip-archived-trees t
711 "Non-nil means, the agenda will skip any items located in archived trees.
712 An archived tree is a tree marked with the tag ARCHIVE."
713 :group 'org-archive
714 :group 'org-agenda-skip
715 :type 'boolean)
717 (defcustom org-cycle-open-archived-trees nil
718 "Non-nil means, `org-cycle' will open archived trees.
719 An archived tree is a tree marked with the tag ARCHIVE.
720 When nil, archived trees will stay folded. You can still open them with
721 normal outline commands like `show-all', but not with the cycling commands."
722 :group 'org-archive
723 :group 'org-cycle
724 :type 'boolean)
726 (defcustom org-sparse-tree-open-archived-trees nil
727 "Non-nil means sparse tree construction shows matches in archived trees.
728 When nil, matches in these trees are highlighted, but the trees are kept in
729 collapsed state."
730 :group 'org-archive
731 :group 'org-sparse-trees
732 :type 'boolean)
734 (defcustom org-archive-location "%s_archive::"
735 "The location where subtrees should be archived.
736 This string consists of two parts, separated by a double-colon.
738 The first part is a file name - when omitted, archiving happens in the same
739 file. %s will be replaced by the current file name (without directory part).
740 Archiving to a different file is useful to keep archived entries from
741 contributing to the Org-mode Agenda.
743 The part after the double colon is a headline. The archived entries will be
744 filed under that headline. When omitted, the subtrees are simply filed away
745 at the end of the file, as top-level entries.
747 Here are a few examples:
748 \"%s_archive::\"
749 If the current file is Projects.org, archive in file
750 Projects.org_archive, as top-level trees. This is the default.
752 \"::* Archived Tasks\"
753 Archive in the current file, under the top-level headline
754 \"* Archived Tasks\".
756 \"~/org/archive.org::\"
757 Archive in file ~/org/archive.org (absolute path), as top-level trees.
759 \"basement::** Finished Tasks\"
760 Archive in file ./basement (relative path), as level 3 trees
761 below the level 2 heading \"** Finished Tasks\".
763 You may set this option on a per-file basis by adding to the buffer a
764 line like
766 #+ARCHIVE: basement::** Finished Tasks"
767 :group 'org-archive
768 :type 'string)
770 (defcustom org-archive-mark-done t
771 "Non-nil means, mark entries as DONE when they are moved to the archive file.
772 This can be a string to set the keyword to use. When t, Org-mode will
773 use the first keyword in its list that means done."
774 :group 'org-archive
775 :type '(choice
776 (const :tag "No" nil)
777 (const :tag "Yes" t)
778 (string :tag "Use this keyword")))
780 (defcustom org-archive-stamp-time t
781 "Non-nil means, add a time stamp to entries moved to an archive file.
782 This variable is obsolete and has no effect anymore, instead add ot remove
783 `time' from the variablle `org-archive-save-context-info'."
784 :group 'org-archive
785 :type 'boolean)
787 (defcustom org-archive-save-context-info '(time file olpath category todo itags)
788 "Parts of context info that should be stored as properties when archiving.
789 When a subtree is moved to an archive file, it looses information given by
790 context, like inherited tags, the category, and possibly also the TODO
791 state (depending on the variable `org-archive-mark-done').
792 This variable can be a list of any of the following symbols:
794 time The time of archiving.
795 file The file where the entry originates.
796 itags The local tags, in the headline of the subtree.
797 ltags The tags the subtree inherits from further up the hierarchy.
798 todo The pre-archive TODO state.
799 category The category, taken from file name or #+CATEGORY lines.
800 olpath The outline path to the item. These are all headlines above
801 the current item, separated by /, like a file path.
803 For each symbol present in the list, a property will be created in
804 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
805 information."
806 :group 'org-archive
807 :type '(set :greedy t
808 (const :tag "Time" time)
809 (const :tag "File" file)
810 (const :tag "Category" category)
811 (const :tag "TODO state" todo)
812 (const :tag "TODO state" priority)
813 (const :tag "Inherited tags" itags)
814 (const :tag "Outline path" olpath)
815 (const :tag "Local tags" ltags)))
817 (defgroup org-imenu-and-speedbar nil
818 "Options concerning imenu and speedbar in Org-mode."
819 :tag "Org Imenu and Speedbar"
820 :group 'org-structure)
822 (defcustom org-imenu-depth 2
823 "The maximum level for Imenu access to Org-mode headlines.
824 This also applied for speedbar access."
825 :group 'org-imenu-and-speedbar
826 :type 'number)
828 (defgroup org-table nil
829 "Options concerning tables in Org-mode."
830 :tag "Org Table"
831 :group 'org)
833 (defcustom org-enable-table-editor 'optimized
834 "Non-nil means, lines starting with \"|\" are handled by the table editor.
835 When nil, such lines will be treated like ordinary lines.
837 When equal to the symbol `optimized', the table editor will be optimized to
838 do the following:
839 - Automatic overwrite mode in front of whitespace in table fields.
840 This makes the structure of the table stay in tact as long as the edited
841 field does not exceed the column width.
842 - Minimize the number of realigns. Normally, the table is aligned each time
843 TAB or RET are pressed to move to another field. With optimization this
844 happens only if changes to a field might have changed the column width.
845 Optimization requires replacing the functions `self-insert-command',
846 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
847 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
848 very good at guessing when a re-align will be necessary, but you can always
849 force one with \\[org-ctrl-c-ctrl-c].
851 If you would like to use the optimized version in Org-mode, but the
852 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
854 This variable can be used to turn on and off the table editor during a session,
855 but in order to toggle optimization, a restart is required.
857 See also the variable `org-table-auto-blank-field'."
858 :group 'org-table
859 :type '(choice
860 (const :tag "off" nil)
861 (const :tag "on" t)
862 (const :tag "on, optimized" optimized)))
864 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
865 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
866 In the optimized version, the table editor takes over all simple keys that
867 normally just insert a character. In tables, the characters are inserted
868 in a way to minimize disturbing the table structure (i.e. in overwrite mode
869 for empty fields). Outside tables, the correct binding of the keys is
870 restored.
872 The default for this option is t if the optimized version is also used in
873 Org-mode. See the variable `org-enable-table-editor' for details. Changing
874 this variable requires a restart of Emacs to become effective."
875 :group 'org-table
876 :type 'boolean)
878 (defcustom orgtbl-radio-table-templates
879 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
880 % END RECEIVE ORGTBL %n
881 \\begin{comment}
882 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
883 | | |
884 \\end{comment}\n")
885 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
886 @c END RECEIVE ORGTBL %n
887 @ignore
888 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
889 | | |
890 @end ignore\n")
891 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
892 <!-- END RECEIVE ORGTBL %n -->
893 <!--
894 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
895 | | |
896 -->\n"))
897 "Templates for radio tables in different major modes.
898 All occurrences of %n in a template will be replaced with the name of the
899 table, obtained by prompting the user."
900 :group 'org-table
901 :type '(repeat
902 (list (symbol :tag "Major mode")
903 (string :tag "Format"))))
905 (defgroup org-table-settings nil
906 "Settings for tables in Org-mode."
907 :tag "Org Table Settings"
908 :group 'org-table)
910 (defcustom org-table-default-size "5x2"
911 "The default size for newly created tables, Columns x Rows."
912 :group 'org-table-settings
913 :type 'string)
915 (defcustom org-table-number-regexp
916 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
917 "Regular expression for recognizing numbers in table columns.
918 If a table column contains mostly numbers, it will be aligned to the
919 right. If not, it will be aligned to the left.
921 The default value of this option is a regular expression which allows
922 anything which looks remotely like a number as used in scientific
923 context. For example, all of the following will be considered a
924 number:
925 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
927 Other options offered by the customize interface are more restrictive."
928 :group 'org-table-settings
929 :type '(choice
930 (const :tag "Positive Integers"
931 "^[0-9]+$")
932 (const :tag "Integers"
933 "^[-+]?[0-9]+$")
934 (const :tag "Floating Point Numbers"
935 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
936 (const :tag "Floating Point Number or Integer"
937 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
938 (const :tag "Exponential, Floating point, Integer"
939 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
940 (const :tag "Very General Number-Like, including hex"
941 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
942 (string :tag "Regexp:")))
944 (defcustom org-table-number-fraction 0.5
945 "Fraction of numbers in a column required to make the column align right.
946 In a column all non-white fields are considered. If at least this
947 fraction of fields is matched by `org-table-number-fraction',
948 alignment to the right border applies."
949 :group 'org-table-settings
950 :type 'number)
952 (defgroup org-table-editing nil
953 "Behavior of tables during editing in Org-mode."
954 :tag "Org Table Editing"
955 :group 'org-table)
957 (defcustom org-table-automatic-realign t
958 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
959 When nil, aligning is only done with \\[org-table-align], or after column
960 removal/insertion."
961 :group 'org-table-editing
962 :type 'boolean)
964 (defcustom org-table-auto-blank-field t
965 "Non-nil means, automatically blank table field when starting to type into it.
966 This only happens when typing immediately after a field motion
967 command (TAB, S-TAB or RET).
968 Only relevant when `org-enable-table-editor' is equal to `optimized'."
969 :group 'org-table-editing
970 :type 'boolean)
972 (defcustom org-table-tab-jumps-over-hlines t
973 "Non-nil means, tab in the last column of a table with jump over a hline.
974 If a horizontal separator line is following the current line,
975 `org-table-next-field' can either create a new row before that line, or jump
976 over the line. When this option is nil, a new line will be created before
977 this line."
978 :group 'org-table-editing
979 :type 'boolean)
981 (defcustom org-table-tab-recognizes-table.el t
982 "Non-nil means, TAB will automatically notice a table.el table.
983 When it sees such a table, it moves point into it and - if necessary -
984 calls `table-recognize-table'."
985 :group 'org-table-editing
986 :type 'boolean)
988 (defgroup org-table-calculation nil
989 "Options concerning tables in Org-mode."
990 :tag "Org Table Calculation"
991 :group 'org-table)
993 (defcustom org-table-use-standard-references t
994 "Should org-mode work with table refrences like B3 instead of @3$2?
995 Possible values are:
996 nil never use them
997 from accept as input, do not present for editing
998 t: accept as input and present for editing"
999 :group 'org-table-calculation
1000 :type '(choice
1001 (const :tag "Never, don't even check unser input for them" nil)
1002 (const :tag "Always, both as user input, and when editing" t)
1003 (const :tag "Convert user input, don't offer during editing" 'from)))
1005 (defcustom org-table-copy-increment t
1006 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1007 :group 'org-table-calculation
1008 :type 'boolean)
1010 (defcustom org-calc-default-modes
1011 '(calc-internal-prec 12
1012 calc-float-format (float 5)
1013 calc-angle-mode deg
1014 calc-prefer-frac nil
1015 calc-symbolic-mode nil
1016 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1017 calc-display-working-message t
1019 "List with Calc mode settings for use in calc-eval for table formulas.
1020 The list must contain alternating symbols (Calc modes variables and values).
1021 Don't remove any of the default settings, just change the values. Org-mode
1022 relies on the variables to be present in the list."
1023 :group 'org-table-calculation
1024 :type 'plist)
1026 (defcustom org-table-formula-evaluate-inline t
1027 "Non-nil means, TAB and RET evaluate a formula in current table field.
1028 If the current field starts with an equal sign, it is assumed to be a formula
1029 which should be evaluated as described in the manual and in the documentation
1030 string of the command `org-table-eval-formula'. This feature requires the
1031 Emacs calc package.
1032 When this variable is nil, formula calculation is only available through
1033 the command \\[org-table-eval-formula]."
1034 :group 'org-table-calculation
1035 :type 'boolean)
1037 (defcustom org-table-formula-use-constants t
1038 "Non-nil means, interpret constants in formulas in tables.
1039 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1040 by the value given in `org-table-formula-constants', or by a value obtained
1041 from the `constants.el' package."
1042 :group 'org-table-calculation
1043 :type 'boolean)
1045 (defcustom org-table-formula-constants nil
1046 "Alist with constant names and values, for use in table formulas.
1047 The car of each element is a name of a constant, without the `$' before it.
1048 The cdr is the value as a string. For example, if you'd like to use the
1049 speed of light in a formula, you would configure
1051 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1053 and then use it in an equation like `$1*$c'.
1055 Constants can also be defined on a per-file basis using a line like
1057 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
1058 :group 'org-table-calculation
1059 :type '(repeat
1060 (cons (string :tag "name")
1061 (string :tag "value"))))
1063 (defvar org-table-formula-constants-local nil
1064 "Local version of `org-table-formula-constants'.")
1065 (make-variable-buffer-local 'org-table-formula-constants-local)
1067 (defcustom org-table-allow-automatic-line-recalculation t
1068 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1069 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1070 :group 'org-table-calculation
1071 :type 'boolean)
1073 (defgroup org-link nil
1074 "Options concerning links in Org-mode."
1075 :tag "Org Link"
1076 :group 'org)
1078 (defvar org-link-abbrev-alist-local nil
1079 "Buffer-local version of `org-link-abbrev-alist', which see.
1080 The value of this is taken from the #+LINK lines.")
1081 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1083 (defcustom org-link-abbrev-alist nil
1084 "Alist of link abbreviations.
1085 The car of each element is a string, to be replaced at the start of a link.
1086 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1087 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1089 [[linkkey:tag][description]]
1091 If REPLACE is a string, the tag will simply be appended to create the link.
1092 If the string contains \"%s\", the tag will be inserted there.
1094 REPLACE may also be a function that will be called with the tag as the
1095 only argument to create the link, which should be returned as a string.
1097 See the manual for examples."
1098 :group 'org-link
1099 :type 'alist)
1101 (defcustom org-descriptive-links t
1102 "Non-nil means, hide link part and only show description of bracket links.
1103 Bracket links are like [[link][descritpion]]. This variable sets the initial
1104 state in new org-mode buffers. The setting can then be toggled on a
1105 per-buffer basis from the Org->Hyperlinks menu."
1106 :group 'org-link
1107 :type 'boolean)
1109 (defcustom org-link-file-path-type 'adaptive
1110 "How the path name in file links should be stored.
1111 Valid values are:
1113 relative Relative to the current directory, i.e. the directory of the file
1114 into which the link is being inserted.
1115 absolute Absolute path, if possible with ~ for home directory.
1116 noabbrev Absolute path, no abbreviation of home directory.
1117 adaptive Use relative path for files in the current directory and sub-
1118 directories of it. For other files, use an absolute path."
1119 :group 'org-link
1120 :type '(choice
1121 (const relative)
1122 (const absolute)
1123 (const noabbrev)
1124 (const adaptive)))
1126 (defcustom org-activate-links '(bracket angle plain radio tag date)
1127 "Types of links that should be activated in Org-mode files.
1128 This is a list of symbols, each leading to the activation of a certain link
1129 type. In principle, it does not hurt to turn on most link types - there may
1130 be a small gain when turning off unused link types. The types are:
1132 bracket The recommended [[link][description]] or [[link]] links with hiding.
1133 angular Links in angular brackes that may contain whitespace like
1134 <bbdb:Carsten Dominik>.
1135 plain Plain links in normal text, no whitespace, like http://google.com.
1136 radio Text that is matched by a radio target, see manual for details.
1137 tag Tag settings in a headline (link to tag search).
1138 date Time stamps (link to calendar).
1140 Changing this variable requires a restart of Emacs to become effective."
1141 :group 'org-link
1142 :type '(set (const :tag "Double bracket links (new style)" bracket)
1143 (const :tag "Angular bracket links (old style)" angular)
1144 (const :tag "plain text links" plain)
1145 (const :tag "Radio target matches" radio)
1146 (const :tag "Tags" tag)
1147 (const :tag "Tags" target)
1148 (const :tag "Timestamps" date)))
1150 (defgroup org-link-store nil
1151 "Options concerning storing links in Org-mode"
1152 :tag "Org Store Link"
1153 :group 'org-link)
1155 (defcustom org-email-link-description-format "Email %c: %.30s"
1156 "Format of the description part of a link to an email or usenet message.
1157 The following %-excapes will be replaced by corresponding information:
1159 %F full \"From\" field
1160 %f name, taken from \"From\" field, address if no name
1161 %T full \"To\" field
1162 %t first name in \"To\" field, address if no name
1163 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1164 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1165 %s subject
1166 %m message-id.
1168 You may use normal field width specification between the % and the letter.
1169 This is for example useful to limit the length of the subject.
1171 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1172 :group 'org-link-store
1173 :type 'string)
1175 (defcustom org-from-is-user-regexp
1176 (let (r1 r2)
1177 (when (and user-mail-address (not (string= user-mail-address "")))
1178 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1179 (when (and user-full-name (not (string= user-full-name "")))
1180 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1181 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1182 "Regexp mached against the \"From:\" header of an email or usenet message.
1183 It should match if the message is from the user him/herself."
1184 :group 'org-link-store
1185 :type 'regexp)
1187 (defcustom org-context-in-file-links t
1188 "Non-nil means, file links from `org-store-link' contain context.
1189 A search string will be added to the file name with :: as separator and
1190 used to find the context when the link is activated by the command
1191 `org-open-at-point'.
1192 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1193 negates this setting for the duration of the command."
1194 :group 'org-link-store
1195 :type 'boolean)
1197 (defcustom org-keep-stored-link-after-insertion nil
1198 "Non-nil means, keep link in list for entire session.
1200 The command `org-store-link' adds a link pointing to the current
1201 location to an internal list. These links accumulate during a session.
1202 The command `org-insert-link' can be used to insert links into any
1203 Org-mode file (offering completion for all stored links). When this
1204 option is nil, every link which has been inserted once using \\[org-insert-link]
1205 will be removed from the list, to make completing the unused links
1206 more efficient."
1207 :group 'org-link-store
1208 :type 'boolean)
1210 (defcustom org-usenet-links-prefer-google nil
1211 "Non-nil means, `org-store-link' will create web links to Google groups.
1212 When nil, Gnus will be used for such links.
1213 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1214 negates this setting for the duration of the command."
1215 :group 'org-link-store
1216 :type 'boolean)
1218 (defgroup org-link-follow nil
1219 "Options concerning following links in Org-mode"
1220 :tag "Org Follow Link"
1221 :group 'org-link)
1223 (defcustom org-tab-follows-link nil
1224 "Non-nil means, on links TAB will follow the link.
1225 Needs to be set before org.el is loaded."
1226 :group 'org-link-follow
1227 :type 'boolean)
1229 (defcustom org-return-follows-link nil
1230 "Non-nil means, on links RET will follow the link.
1231 Needs to be set before org.el is loaded."
1232 :group 'org-link-follow
1233 :type 'boolean)
1235 (defcustom org-mouse-1-follows-link t
1236 "Non-nil means, mouse-1 on a link will follow the link.
1237 A longer mouse click will still set point. Does not wortk on XEmacs.
1238 Needs to be set before org.el is loaded."
1239 :group 'org-link-follow
1240 :type 'boolean)
1242 (defcustom org-mark-ring-length 4
1243 "Number of different positions to be recorded in the ring
1244 Changing this requires a restart of Emacs to work correctly."
1245 :group 'org-link-follow
1246 :type 'interger)
1248 (defcustom org-link-frame-setup
1249 '((vm . vm-visit-folder-other-frame)
1250 (gnus . gnus-other-frame)
1251 (file . find-file-other-window))
1252 "Setup the frame configuration for following links.
1253 When following a link with Emacs, it may often be useful to display
1254 this link in another window or frame. This variable can be used to
1255 set this up for the different types of links.
1256 For VM, use any of
1257 `vm-visit-folder'
1258 `vm-visit-folder-other-frame'
1259 For Gnus, use any of
1260 `gnus'
1261 `gnus-other-frame'
1262 For FILE, use any of
1263 `find-file'
1264 `find-file-other-window'
1265 `find-file-other-frame'
1266 For the calendar, use the variable `calendar-setup'.
1267 For BBDB, it is currently only possible to display the matches in
1268 another window."
1269 :group 'org-link-follow
1270 :type '(list
1271 (cons (const vm)
1272 (choice
1273 (const vm-visit-folder)
1274 (const vm-visit-folder-other-window)
1275 (const vm-visit-folder-other-frame)))
1276 (cons (const gnus)
1277 (choice
1278 (const gnus)
1279 (const gnus-other-frame)))
1280 (cons (const file)
1281 (choice
1282 (const find-file)
1283 (const find-file-other-window)
1284 (const find-file-other-frame)))))
1286 (defcustom org-display-internal-link-with-indirect-buffer nil
1287 "Non-nil means, use indirect buffer to display infile links.
1288 Activating internal links (from one location in a file to another location
1289 in the same file) normally just jumps to the location. When the link is
1290 activated with a C-u prefix (or with mouse-3), the link is displayed in
1291 another window. When this option is set, the other window actually displays
1292 an indirect buffer clone of the current buffer, to avoid any visibility
1293 changes to the current buffer."
1294 :group 'org-link-follow
1295 :type 'boolean)
1297 (defcustom org-open-non-existing-files nil
1298 "Non-nil means, `org-open-file' will open non-existing files.
1299 When nil, an error will be generated."
1300 :group 'org-link-follow
1301 :type 'boolean)
1303 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1304 "Function and arguments to call for following mailto links.
1305 This is a list with the first element being a lisp function, and the
1306 remaining elements being arguments to the function. In string arguments,
1307 %a will be replaced by the address, and %s will be replaced by the subject
1308 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1309 :group 'org-link-follow
1310 :type '(choice
1311 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1312 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1313 (const :tag "message-mail" (message-mail "%a" "%s"))
1314 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1316 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1317 "Non-nil means, ask for confirmation before executing shell links.
1318 Shell links can be dangerous: just think about a link
1320 [[shell:rm -rf ~/*][Google Search]]
1322 This link would show up in your Org-mode document as \"Google Search\",
1323 but really it would remove your entire home directory.
1324 Therefore we advise against setting this variable to nil.
1325 Just change it to `y-or-n-p' of you want to confirm with a
1326 single keystroke rather than having to type \"yes\"."
1327 :group 'org-link-follow
1328 :type '(choice
1329 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1330 (const :tag "with y-or-n (faster)" y-or-n-p)
1331 (const :tag "no confirmation (dangerous)" nil)))
1333 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1334 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1335 Elisp links can be dangerous: just think about a link
1337 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1339 This link would show up in your Org-mode document as \"Google Search\",
1340 but really it would remove your entire home directory.
1341 Therefore we advise against setting this variable to nil.
1342 Just change it to `y-or-n-p' of you want to confirm with a
1343 single keystroke rather than having to type \"yes\"."
1344 :group 'org-link-follow
1345 :type '(choice
1346 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1347 (const :tag "with y-or-n (faster)" y-or-n-p)
1348 (const :tag "no confirmation (dangerous)" nil)))
1350 (defconst org-file-apps-defaults-gnu
1351 '((remote . emacs)
1352 (t . mailcap))
1353 "Default file applications on a UNIX or GNU/Linux system.
1354 See `org-file-apps'.")
1356 (defconst org-file-apps-defaults-macosx
1357 '((remote . emacs)
1358 (t . "open %s")
1359 ("ps" . "gv %s")
1360 ("ps.gz" . "gv %s")
1361 ("eps" . "gv %s")
1362 ("eps.gz" . "gv %s")
1363 ("dvi" . "xdvi %s")
1364 ("fig" . "xfig %s"))
1365 "Default file applications on a MacOS X system.
1366 The system \"open\" is known as a default, but we use X11 applications
1367 for some files for which the OS does not have a good default.
1368 See `org-file-apps'.")
1370 (defconst org-file-apps-defaults-windowsnt
1371 (list
1372 '(remote . emacs)
1373 (cons t
1374 (list (if (featurep 'xemacs)
1375 'mswindows-shell-execute
1376 'w32-shell-execute)
1377 "open" 'file)))
1378 "Default file applications on a Windows NT system.
1379 The system \"open\" is used for most files.
1380 See `org-file-apps'.")
1382 (defcustom org-file-apps
1384 ("txt" . emacs)
1385 ("tex" . emacs)
1386 ("ltx" . emacs)
1387 ("org" . emacs)
1388 ("el" . emacs)
1389 ("bib" . emacs)
1391 "External applications for opening `file:path' items in a document.
1392 Org-mode uses system defaults for different file types, but
1393 you can use this variable to set the application for a given file
1394 extension. The entries in this list are cons cells where the car identifies
1395 files and the cdr the corresponding command. Possible values for the
1396 file identifier are
1397 \"ext\" A string identifying an extension
1398 `directory' Matches a directory
1399 `remote' Matches a remote file, accessible through tramp or efs.
1400 Remote files most likely should be visited through Emacs
1401 because external applications cannot handle such paths.
1402 t Default for all remaining files
1404 Possible values for the command are:
1405 `emacs' The file will be visited by the current Emacs process.
1406 `default' Use the default application for this file type.
1407 string A command to be executed by a shell; %s will be replaced
1408 by the path to the file.
1409 sexp A Lisp form which will be evaluated. The file path will
1410 be available in the Lisp variable `file'.
1411 For more examples, see the system specific constants
1412 `org-file-apps-defaults-macosx'
1413 `org-file-apps-defaults-windowsnt'
1414 `org-file-apps-defaults-gnu'."
1415 :group 'org-link-follow
1416 :type '(repeat
1417 (cons (choice :value ""
1418 (string :tag "Extension")
1419 (const :tag "Default for unrecognized files" t)
1420 (const :tag "Remote file" remote)
1421 (const :tag "Links to a directory" directory))
1422 (choice :value ""
1423 (const :tag "Visit with Emacs" emacs)
1424 (const :tag "Use system default" default)
1425 (string :tag "Command")
1426 (sexp :tag "Lisp form")))))
1428 (defcustom org-mhe-search-all-folders nil
1429 "Non-nil means, that the search for the mh-message will be extended to
1430 all folders if the message cannot be found in the folder given in the link.
1431 Searching all folders is very efficient with one of the search engines
1432 supported by MH-E, but will be slow with pick."
1433 :group 'org-link-follow
1434 :type 'boolean)
1436 (defgroup org-remember nil
1437 "Options concerning interaction with remember.el."
1438 :tag "Org Remember"
1439 :group 'org)
1441 (defcustom org-directory "~/org"
1442 "Directory with org files.
1443 This directory will be used as default to prompt for org files.
1444 Used by the hooks for remember.el."
1445 :group 'org-remember
1446 :type 'directory)
1448 (defcustom org-default-notes-file "~/.notes"
1449 "Default target for storing notes.
1450 Used by the hooks for remember.el. This can be a string, or nil to mean
1451 the value of `remember-data-file'.
1452 You can set this on a per-template basis with the variable
1453 `org-remember-templates'."
1454 :group 'org-remember
1455 :type '(choice
1456 (const :tag "Default from remember-data-file" nil)
1457 file))
1459 (defcustom org-remember-store-without-prompt t
1460 "Non-nil means, `C-c C-c' stores remember note without further promts.
1461 In this case, you need `C-u C-c C-c' to get the prompts for
1462 note file and headline.
1463 When this variable is nil, `C-c C-c' give you the prompts, and
1464 `C-u C-c C-c' trigger the fasttrack."
1465 :group 'org-remember
1466 :type 'boolean)
1468 (defcustom org-remember-interactive-interface 'refile
1469 "The interface to be used for interactive filing of remember notes.
1470 This is only used when the interactive mode for selecting a filing
1471 location is used (see the variable `org-remember-store-without-prompt').
1472 Allowed vaues are:
1473 outline The interface shows an outline of the relevant file
1474 and the correct heading is found by moving through
1475 the outline or by searching with incremental search.
1476 outline-path-completion Headlines in the current buffer are offered via
1477 completion.
1478 refile Use the refile interface, and offer headlines,
1479 possibly from different buffers."
1480 :group 'org-remember
1481 :type '(choice
1482 (const :tag "Refile" refile)
1483 (const :tag "Outline" outline)
1484 (const :tag "Outline-path-completion" outline-path-completion)))
1486 (defcustom org-goto-interface 'outline
1487 "The default interface to be used for `org-goto'.
1488 Allowed vaues are:
1489 outline The interface shows an outline of the relevant file
1490 and the correct heading is found by moving through
1491 the outline or by searching with incremental search.
1492 outline-path-completion Headlines in the current buffer are offered via
1493 completion."
1494 :group 'org-remember ; FIXME: different group for org-goto and org-refile
1495 :type '(choice
1496 (const :tag "Outline" outline)
1497 (const :tag "Outline-path-completion" outline-path-completion)))
1499 (defcustom org-remember-default-headline ""
1500 "The headline that should be the default location in the notes file.
1501 When filing remember notes, the cursor will start at that position.
1502 You can set this on a per-template basis with the variable
1503 `org-remember-templates'."
1504 :group 'org-remember
1505 :type 'string)
1507 (defcustom org-remember-templates nil
1508 "Templates for the creation of remember buffers.
1509 When nil, just let remember make the buffer.
1510 When not nil, this is a list of 5-element lists. In each entry, the first
1511 element is the name of the template, which should be a single short word.
1512 The second element is a character, a unique key to select this template.
1513 The third element is the template. The fourth element is optional and can
1514 specify a destination file for remember items created with this template.
1515 The default file is given by `org-default-notes-file'. An optional fifth
1516 element can specify the headline in that file that should be offered
1517 first when the user is asked to file the entry. The default headline is
1518 given in the variable `org-remember-default-headline'.
1520 The template specifies the structure of the remember buffer. It should have
1521 a first line starting with a star, to act as the org-mode headline.
1522 Furthermore, the following %-escapes will be replaced with content:
1524 %^{prompt} Prompt the user for a string and replace this sequence with it.
1525 A default value and a completion table ca be specified like this:
1526 %^{prompt|default|completion2|completion3|...}
1527 %t time stamp, date only
1528 %T time stamp with date and time
1529 %u, %U like the above, but inactive time stamps
1530 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1531 You may define a prompt like %^{Please specify birthday}t
1532 %n user name (taken from `user-full-name')
1533 %a annotation, normally the link created with org-store-link
1534 %i initial content, the region active. If %i is indented,
1535 the entire inserted text will be indented as well.
1536 %c content of the clipboard, or current kill ring head
1537 %^g prompt for tags, with completion on tags in target file
1538 %^G prompt for tags, with completion all tags in all agenda files
1539 %:keyword specific information for certain link types, see below
1540 %[pathname] insert the contents of the file given by `pathname'
1541 %(sexp) evaluate elisp `(sexp)' and replace with the result
1542 %! Store this note immediately after filling the template
1544 %? After completing the template, position cursor here.
1546 Apart from these general escapes, you can access information specific to the
1547 link type that is created. For example, calling `remember' in emails or gnus
1548 will record the author and the subject of the message, which you can access
1549 with %:author and %:subject, respectively. Here is a complete list of what
1550 is recorded for each link type.
1552 Link type | Available information
1553 -------------------+------------------------------------------------------
1554 bbdb | %:type %:name %:company
1555 vm, wl, mh, rmail | %:type %:subject %:message-id
1556 | %:from %:fromname %:fromaddress
1557 | %:to %:toname %:toaddress
1558 | %:fromto (either \"to NAME\" or \"from NAME\")
1559 gnus | %:group, for messages also all email fields
1560 w3, w3m | %:type %:url
1561 info | %:type %:file %:node
1562 calendar | %:type %:date"
1563 :group 'org-remember
1564 :get (lambda (var) ; Make sure all entries have 5 elements
1565 (mapcar (lambda (x)
1566 (if (not (stringp (car x))) (setq x (cons "" x)))
1567 (cond ((= (length x) 4) (append x '("")))
1568 ((= (length x) 3) (append x '("" "")))
1569 (t x)))
1570 (default-value var)))
1571 :type '(repeat
1572 :tag "enabled"
1573 (list :value ("" ?a "\n" nil nil)
1574 (string :tag "Name")
1575 (character :tag "Selection Key")
1576 (string :tag "Template")
1577 (choice
1578 (file :tag "Destination file")
1579 (const :tag "Prompt for file" nil))
1580 (choice
1581 (string :tag "Destination headline")
1582 (const :tag "Selection interface for heading")))))
1584 (defcustom org-reverse-note-order nil
1585 "Non-nil means, store new notes at the beginning of a file or entry.
1586 When nil, new notes will be filed to the end of a file or entry.
1587 This can also be a list with cons cells of regular expressions that
1588 are matched against file names, and values."
1589 :group 'org-remember
1590 :type '(choice
1591 (const :tag "Reverse always" t)
1592 (const :tag "Reverse never" nil)
1593 (repeat :tag "By file name regexp"
1594 (cons regexp boolean))))
1596 (defcustom org-refile-targets nil
1597 "Targets for refiling entries with \\[org-refile].
1598 This is list of cons cells. Each cell contains:
1599 - a specification of the files to be considered, either a list of files,
1600 or a symbol whose function or value fields will be used to retrieve
1601 a file name or a list of file names. Nil means, refile to a different
1602 heading in the current buffer.
1603 - A specification of how to find candidate refile targets. This may be
1604 any of
1605 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1606 This tag has to be present in all target headlines, inheritance will
1607 not be considered.
1608 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1609 todo keyword.
1610 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1611 headlines that are refiling targets.
1612 - a cons cell (:level . N). Any headline of level N is considered a target.
1613 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1614 ;; FIXME: what if there are a var and func with same name???
1615 :group 'org-remember
1616 :type '(repeat
1617 (cons
1618 (choice :value org-agenda-files
1619 (const :tag "All agenda files" org-agenda-files)
1620 (const :tag "Current buffer" nil)
1621 (function) (variable) (file))
1622 (choice :tag "Identify target headline by"
1623 (cons :tag "Specific tag" (const :tag) (string))
1624 (cons :tag "TODO keyword" (const :todo) (string))
1625 (cons :tag "Regular expression" (const :regexp) (regexp))
1626 (cons :tag "Level number" (const :level) (integer))
1627 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1629 (defcustom org-refile-use-outline-path nil
1630 "Non-nil means, provide refile targets as paths.
1631 So a level 3 headline will be available as level1/level2/level3.
1632 When the value is `file', also include the file name (without directory)
1633 into the path. When `full-file-path', include the full file path."
1634 :group 'org-remember
1635 :type '(choice
1636 (const :tag "Not" nil)
1637 (const :tag "Yes" t)
1638 (const :tag "Start with file name" file)
1639 (const :tag "Start with full file path" full-file-path)))
1641 (defgroup org-todo nil
1642 "Options concerning TODO items in Org-mode."
1643 :tag "Org TODO"
1644 :group 'org)
1646 (defgroup org-progress nil
1647 "Options concerning Progress logging in Org-mode."
1648 :tag "Org Progress"
1649 :group 'org-time)
1651 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1652 "List of TODO entry keyword sequences and their interpretation.
1653 \\<org-mode-map>This is a list of sequences.
1655 Each sequence starts with a symbol, either `sequence' or `type',
1656 indicating if the keywords should be interpreted as a sequence of
1657 action steps, or as different types of TODO items. The first
1658 keywords are states requiring action - these states will select a headline
1659 for inclusion into the global TODO list Org-mode produces. If one of
1660 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1661 signify that no further action is necessary. If \"|\" is not found,
1662 the last keyword is treated as the only DONE state of the sequence.
1664 The command \\[org-todo] cycles an entry through these states, and one
1665 additional state where no keyword is present. For details about this
1666 cycling, see the manual.
1668 TODO keywords and interpretation can also be set on a per-file basis with
1669 the special #+SEQ_TODO and #+TYP_TODO lines.
1671 Each keyword can optionally specify a character for fast state selection
1672 \(in combination with the variable `org-use-fast-todo-selection')
1673 and specifiers for state change logging, using the same syntax
1674 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1675 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1676 indicates to record a time stamp each time this state is selected.
1677 \"WAIT(w@)\" says that the user should in addition be prompted for a
1678 note, and \"WAIT(w@/@)\" says that a note should be taken both when
1679 entering and when leaving this state.
1681 For backward compatibility, this variable may also be just a list
1682 of keywords - in this case the interptetation (sequence or type) will be
1683 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1684 :group 'org-todo
1685 :group 'org-keywords
1686 :type '(choice
1687 (repeat :tag "Old syntax, just keywords"
1688 (string :tag "Keyword"))
1689 (repeat :tag "New syntax"
1690 (cons
1691 (choice
1692 :tag "Interpretation"
1693 (const :tag "Sequence (cycling hits every state)" sequence)
1694 (const :tag "Type (cycling directly to DONE)" type))
1695 (repeat
1696 (string :tag "Keyword"))))))
1698 (defvar org-todo-keywords-1 nil
1699 "All TODO and DONE keywords active in a buffer.")
1700 (make-variable-buffer-local 'org-todo-keywords-1)
1701 (defvar org-todo-keywords-for-agenda nil)
1702 (defvar org-done-keywords-for-agenda nil)
1703 (defvar org-not-done-keywords nil)
1704 (make-variable-buffer-local 'org-not-done-keywords)
1705 (defvar org-done-keywords nil)
1706 (make-variable-buffer-local 'org-done-keywords)
1707 (defvar org-todo-heads nil)
1708 (make-variable-buffer-local 'org-todo-heads)
1709 (defvar org-todo-sets nil)
1710 (make-variable-buffer-local 'org-todo-sets)
1711 (defvar org-todo-log-states nil)
1712 (make-variable-buffer-local 'org-todo-log-states)
1713 (defvar org-todo-kwd-alist nil)
1714 (make-variable-buffer-local 'org-todo-kwd-alist)
1715 (defvar org-todo-key-alist nil)
1716 (make-variable-buffer-local 'org-todo-key-alist)
1717 (defvar org-todo-key-trigger nil)
1718 (make-variable-buffer-local 'org-todo-key-trigger)
1720 (defcustom org-todo-interpretation 'sequence
1721 "Controls how TODO keywords are interpreted.
1722 This variable is in principle obsolete and is only used for
1723 backward compatibility, if the interpretation of todo keywords is
1724 not given already in `org-todo-keywords'. See that variable for
1725 more information."
1726 :group 'org-todo
1727 :group 'org-keywords
1728 :type '(choice (const sequence)
1729 (const type)))
1731 (defcustom org-use-fast-todo-selection 'prefix
1732 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1733 This variable describes if and under what circumstances the cycling
1734 mechanism for TODO keywords will be replaced by a single-key, direct
1735 selection scheme.
1737 When nil, fast selection is never used.
1739 When the symbol `prefix', it will be used when `org-todo' is called with
1740 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1741 in an agenda buffer.
1743 When t, fast selection is used by default. In this case, the prefix
1744 argument forces cycling instead.
1746 In all cases, the special interface is only used if access keys have actually
1747 been assigned by the user, i.e. if keywords in the configuration are followed
1748 by a letter in parenthesis, like TODO(t)."
1749 :group 'org-todo
1750 :type '(choice
1751 (const :tag "Never" nil)
1752 (const :tag "By default" t)
1753 (const :tag "Only with C-u C-c C-t" prefix)))
1755 (defcustom org-after-todo-state-change-hook nil
1756 "Hook which is run after the state of a TODO item was changed.
1757 The new state (a string with a TODO keyword, or nil) is available in the
1758 Lisp variable `state'."
1759 :group 'org-todo
1760 :type 'hook)
1762 (defcustom org-log-done nil
1763 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1764 When equal to the list (done), also prompt for a closing note.
1765 This can also be configured on a per-file basis by adding one of
1766 the following lines anywhere in the buffer:
1768 #+STARTUP: logdone
1769 #+STARTUP: lognotedone
1770 #+STARTUP: nologdone"
1771 :group 'org-todo
1772 :group 'org-progress
1773 :type '(choice
1774 (const :tag "No logging" nil)
1775 (const :tag "Record CLOSED timestamp" time)
1776 (const :tag "Record CLOSED timestamp with closing note." note)))
1778 ;; Normalize old uses of org-log-done.
1779 (cond
1780 ((eq org-log-done t) (setq org-log-done 'time))
1781 ((and (listp org-log-done) (memq 'done org-log-done))
1782 (setq org-log-done 'note)))
1784 ;; FIXME: document
1785 (defcustom org-log-note-clock-out nil
1786 "Non-nil means, recored a note when clocking out of an item.
1787 This can also be configured on a per-file basis by adding one of
1788 the following lines anywhere in the buffer:
1790 #+STARTUP: lognoteclock-out
1791 #+STARTUP: nolognoteclock-out"
1792 :group 'org-todo
1793 :group 'org-progress
1794 :type 'boolean)
1796 (defcustom org-log-done-with-time t
1797 "Non-nil means, the CLOSED time stamp will contain date and time.
1798 When nil, only the date will be recorded."
1799 :group 'org-progress
1800 :type 'boolean)
1802 (defcustom org-log-note-headings
1803 '((done . "CLOSING NOTE %t")
1804 (state . "State %-12s %t")
1805 (clock-out . ""))
1806 "Headings for notes added when clocking out or closing TODO items.
1807 The value is an alist, with the car being a symbol indicating the note
1808 context, and the cdr is the heading to be used. The heading may also be the
1809 empty string.
1810 %t in the heading will be replaced by a time stamp.
1811 %s will be replaced by the new TODO state, in double quotes.
1812 %u will be replaced by the user name.
1813 %U will be replaced by the full user name."
1814 :group 'org-todo
1815 :group 'org-progress
1816 :type '(list :greedy t
1817 (cons (const :tag "Heading when closing an item" done) string)
1818 (cons (const :tag
1819 "Heading when changing todo state (todo sequence only)"
1820 state) string)
1821 (cons (const :tag "Heading when clocking out" clock-out) string)))
1823 (defcustom org-log-states-order-reversed t
1824 "Non-nil means, the latest state change note will be directly after heading.
1825 When nil, the notes will be orderer according to time."
1826 :group 'org-todo
1827 :group 'org-progress
1828 :type 'boolean)
1830 (defcustom org-log-repeat 'time
1831 "Non-nil means, record moving through the DONE state when triggering repeat.
1832 An auto-repeating tasks is immediately switched back to TODO when marked
1833 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1834 the TODO keyword definition, or recording a cloing note by setting
1835 `org-log-done', there will be no record of the task moving trhough DONE.
1836 This variable forces taking a note anyway. Possible values are:
1838 nil Don't force a record
1839 time Record a time stamp
1840 note Record a note
1842 This option can also be set with on a per-file-basis with
1844 #+STARTUP: logrepeat
1845 #+STARTUP: lognoterepeat
1846 #+STARTUP: nologrepeat
1848 You can have local logging settings for a subtree by setting the LOGGING
1849 property to one or more of these keywords."
1850 :group 'org-todo
1851 :group 'org-progress
1852 :type '(choice
1853 (const :tag "Don't force a record" nil)
1854 (const :tag "Force recording the DONE state" time)
1855 (const :tag "Force recording a note with the DONE state" note)))
1857 (defcustom org-clock-into-drawer 2
1858 "Should clocking info be wrapped into a drawer?
1859 When t, clocking info will always be inserted into a :CLOCK: drawer.
1860 If necessary, the drawer will be created.
1861 When nil, the drawer will not be created, but used when present.
1862 When an integer and the number of clocking entries in an item
1863 reaches or exceeds this number, a drawer will be created."
1864 :group 'org-todo
1865 :group 'org-progress
1866 :type '(choice
1867 (const :tag "Always" t)
1868 (const :tag "Only when drawer exists" nil)
1869 (integer :tag "When at least N clock entries")))
1871 (defcustom org-clock-out-when-done t
1872 "When t, the clock will be stopped when the relevant entry is marked DONE.
1873 Nil means, clock will keep running until stopped explicitly with
1874 `C-c C-x C-o', or until the clock is started in a different item."
1875 :group 'org-progress
1876 :type 'boolean)
1878 (defcustom org-clock-in-switch-to-state nil
1879 "Set task to a special todo state while clocking it.
1880 The value should be the state to which the entry should be switched."
1881 :group 'org-progress
1882 :group 'org-todo
1883 :type '(choice
1884 (const :tag "Don't force a state" nil)
1885 (string :tag "State")))
1887 (defgroup org-priorities nil
1888 "Priorities in Org-mode."
1889 :tag "Org Priorities"
1890 :group 'org-todo)
1892 (defcustom org-highest-priority ?A
1893 "The highest priority of TODO items. A character like ?A, ?B etc.
1894 Must have a smaller ASCII number than `org-lowest-priority'."
1895 :group 'org-priorities
1896 :type 'character)
1898 (defcustom org-lowest-priority ?C
1899 "The lowest priority of TODO items. A character like ?A, ?B etc.
1900 Must have a larger ASCII number than `org-highest-priority'."
1901 :group 'org-priorities
1902 :type 'character)
1904 (defcustom org-default-priority ?B
1905 "The default priority of TODO items.
1906 This is the priority an item get if no explicit priority is given."
1907 :group 'org-priorities
1908 :type 'character)
1910 (defcustom org-priority-start-cycle-with-default t
1911 "Non-nil means, start with default priority when starting to cycle.
1912 When this is nil, the first step in the cycle will be (depending on the
1913 command used) one higher or lower that the default priority."
1914 :group 'org-priorities
1915 :type 'boolean)
1917 (defgroup org-time nil
1918 "Options concerning time stamps and deadlines in Org-mode."
1919 :tag "Org Time"
1920 :group 'org)
1922 (defcustom org-insert-labeled-timestamps-at-point nil
1923 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1924 When nil, these labeled time stamps are forces into the second line of an
1925 entry, just after the headline. When scheduling from the global TODO list,
1926 the time stamp will always be forced into the second line."
1927 :group 'org-time
1928 :type 'boolean)
1930 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1931 "Formats for `format-time-string' which are used for time stamps.
1932 It is not recommended to change this constant.")
1934 (defcustom org-time-stamp-rounding-minutes 0
1935 "Number of minutes to round time stamps to upon insertion.
1936 When zero, insert the time unmodified. Useful rounding numbers
1937 should be factors of 60, so for example 5, 10, 15.
1938 When this is not zero, you can still force an exact time-stamp by using
1939 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1940 :group 'org-time
1941 :type 'integer)
1943 (defcustom org-display-custom-times nil
1944 "Non-nil means, overlay custom formats over all time stamps.
1945 The formats are defined through the variable `org-time-stamp-custom-formats'.
1946 To turn this on on a per-file basis, insert anywhere in the file:
1947 #+STARTUP: customtime"
1948 :group 'org-time
1949 :set 'set-default
1950 :type 'sexp)
1951 (make-variable-buffer-local 'org-display-custom-times)
1953 (defcustom org-time-stamp-custom-formats
1954 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1955 "Custom formats for time stamps. See `format-time-string' for the syntax.
1956 These are overlayed over the default ISO format if the variable
1957 `org-display-custom-times' is set. Time like %H:%M should be at the
1958 end of the second format."
1959 :group 'org-time
1960 :type 'sexp)
1962 (defun org-time-stamp-format (&optional long inactive)
1963 "Get the right format for a time string."
1964 (let ((f (if long (cdr org-time-stamp-formats)
1965 (car org-time-stamp-formats))))
1966 (if inactive
1967 (concat "[" (substring f 1 -1) "]")
1968 f)))
1970 (defcustom org-read-date-prefer-future t
1971 "Non-nil means, assume future for incomplete date input from user.
1972 This affects the following situations:
1973 1. The user gives a day, but no month.
1974 For example, if today is the 15th, and you enter \"3\", Org-mode will
1975 read this as the third of *next* month. However, if you enter \"17\",
1976 it will be considered as *this* month.
1977 2. The user gives a month but not a year.
1978 For example, if it is april and you enter \"feb 2\", this will be read
1979 as feb 2, *next* year. \"May 5\", however, will be this year.
1981 When this option is nil, the current month and year will always be used
1982 as defaults."
1983 :group 'org-time
1984 :type 'boolean)
1986 (defcustom org-read-date-display-live t
1987 "Non-nil means, display current interpretation of date prompt live.
1988 This display will be in an overlay, in the minibuffer."
1989 :group 'org-time
1990 :type 'boolean)
1992 (defcustom org-read-date-popup-calendar t
1993 "Non-nil means, pop up a calendar when prompting for a date.
1994 In the calendar, the date can be selected with mouse-1. However, the
1995 minibuffer will also be active, and you can simply enter the date as well.
1996 When nil, only the minibuffer will be available."
1997 :group 'org-time
1998 :type 'boolean)
1999 (if (fboundp 'defvaralias)
2000 (defvaralias 'org-popup-calendar-for-date-prompt
2001 'org-read-date-popup-calendar))
2003 (defcustom org-extend-today-until 0
2004 "The hour when your day really ends.
2005 This has influence for the following applications:
2006 - When switching the agenda to \"today\". It it is still earlier than
2007 the time given here, the day recognized as TODAY is actually yesterday.
2008 - When a date is read from the user and it is still before the time given
2009 here, the current date and time will be assumed to be yesterday, 23:59.
2011 FIXME:
2012 IMPORTANT: This is still a very experimental feature, it may disappear
2013 again or it may be extended to mean more things."
2014 :group 'org-time
2015 :type 'number)
2017 (defcustom org-edit-timestamp-down-means-later nil
2018 "Non-nil means, S-down will increase the time in a time stamp.
2019 When nil, S-up will increase."
2020 :group 'org-time
2021 :type 'boolean)
2023 (defcustom org-calendar-follow-timestamp-change t
2024 "Non-nil means, make the calendar window follow timestamp changes.
2025 When a timestamp is modified and the calendar window is visible, it will be
2026 moved to the new date."
2027 :group 'org-time
2028 :type 'boolean)
2030 (defcustom org-clock-heading-function nil
2031 "When non-nil, should be a function to create `org-clock-heading'.
2032 This is the string shown in the mode line when a clock is running.
2033 The function is called with point at the beginning of the headline."
2034 :group 'org-time ; FIXME: Should we have a separate group????
2035 :type 'function)
2037 (defgroup org-tags nil
2038 "Options concerning tags in Org-mode."
2039 :tag "Org Tags"
2040 :group 'org)
2042 (defcustom org-tag-alist nil
2043 "List of tags allowed in Org-mode files.
2044 When this list is nil, Org-mode will base TAG input on what is already in the
2045 buffer.
2046 The value of this variable is an alist, the car of each entry must be a
2047 keyword as a string, the cdr may be a character that is used to select
2048 that tag through the fast-tag-selection interface.
2049 See the manual for details."
2050 :group 'org-tags
2051 :type '(repeat
2052 (choice
2053 (cons (string :tag "Tag name")
2054 (character :tag "Access char"))
2055 (const :tag "Start radio group" (:startgroup))
2056 (const :tag "End radio group" (:endgroup)))))
2058 (defcustom org-use-fast-tag-selection 'auto
2059 "Non-nil means, use fast tag selection scheme.
2060 This is a special interface to select and deselect tags with single keys.
2061 When nil, fast selection is never used.
2062 When the symbol `auto', fast selection is used if and only if selection
2063 characters for tags have been configured, either through the variable
2064 `org-tag-alist' or through a #+TAGS line in the buffer.
2065 When t, fast selection is always used and selection keys are assigned
2066 automatically if necessary."
2067 :group 'org-tags
2068 :type '(choice
2069 (const :tag "Always" t)
2070 (const :tag "Never" nil)
2071 (const :tag "When selection characters are configured" 'auto)))
2073 (defcustom org-fast-tag-selection-single-key nil
2074 "Non-nil means, fast tag selection exits after first change.
2075 When nil, you have to press RET to exit it.
2076 During fast tag selection, you can toggle this flag with `C-c'.
2077 This variable can also have the value `expert'. In this case, the window
2078 displaying the tags menu is not even shown, until you press C-c again."
2079 :group 'org-tags
2080 :type '(choice
2081 (const :tag "No" nil)
2082 (const :tag "Yes" t)
2083 (const :tag "Expert" expert)))
2085 (defvar org-fast-tag-selection-include-todo nil
2086 "Non-nil means, fast tags selection interface will also offer TODO states.
2087 This is an undocumented feature, you should not rely on it.")
2089 (defcustom org-tags-column -80
2090 "The column to which tags should be indented in a headline.
2091 If this number is positive, it specifies the column. If it is negative,
2092 it means that the tags should be flushright to that column. For example,
2093 -80 works well for a normal 80 character screen."
2094 :group 'org-tags
2095 :type 'integer)
2097 (defcustom org-auto-align-tags t
2098 "Non-nil means, realign tags after pro/demotion of TODO state change.
2099 These operations change the length of a headline and therefore shift
2100 the tags around. With this options turned on, after each such operation
2101 the tags are again aligned to `org-tags-column'."
2102 :group 'org-tags
2103 :type 'boolean)
2105 (defcustom org-use-tag-inheritance t
2106 "Non-nil means, tags in levels apply also for sublevels.
2107 When nil, only the tags directly given in a specific line apply there.
2108 If you turn off this option, you very likely want to turn on the
2109 companion option `org-tags-match-list-sublevels'."
2110 :group 'org-tags
2111 :type 'boolean)
2113 (defcustom org-tags-match-list-sublevels nil
2114 "Non-nil means list also sublevels of headlines matching tag search.
2115 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2116 the sublevels of a headline matching a tag search often also match
2117 the same search. Listing all of them can create very long lists.
2118 Setting this variable to nil causes subtrees of a match to be skipped.
2119 This option is off by default, because inheritance in on. If you turn
2120 inheritance off, you very likely want to turn this option on.
2122 As a special case, if the tag search is restricted to TODO items, the
2123 value of this variable is ignored and sublevels are always checked, to
2124 make sure all corresponding TODO items find their way into the list."
2125 :group 'org-tags
2126 :type 'boolean)
2128 (defvar org-tags-history nil
2129 "History of minibuffer reads for tags.")
2130 (defvar org-last-tags-completion-table nil
2131 "The last used completion table for tags.")
2132 (defvar org-after-tags-change-hook nil
2133 "Hook that is run after the tags in a line have changed.")
2135 (defgroup org-properties nil
2136 "Options concerning properties in Org-mode."
2137 :tag "Org Properties"
2138 :group 'org)
2140 (defcustom org-property-format "%-10s %s"
2141 "How property key/value pairs should be formatted by `indent-line'.
2142 When `indent-line' hits a property definition, it will format the line
2143 according to this format, mainly to make sure that the values are
2144 lined-up with respect to each other."
2145 :group 'org-properties
2146 :type 'string)
2148 (defcustom org-use-property-inheritance nil
2149 "Non-nil means, properties apply also for sublevels.
2150 This setting is only relevant during property searches, not when querying
2151 an entry with `org-entry-get'. To retrieve a property with inheritance,
2152 you need to call `org-entry-get' with the inheritance flag.
2153 Turning this on can cause significant overhead when doing a search, so
2154 this is turned off by default.
2155 When nil, only the properties directly given in the current entry count.
2156 The value may also be a list of properties that shouldhave inheritance.
2158 However, note that some special properties use inheritance under special
2159 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2160 and the properties ending in \"_ALL\" when they are used as descriptor
2161 for valid values of a property."
2162 :group 'org-properties
2163 :type '(choice
2164 (const :tag "Not" nil)
2165 (const :tag "Always" nil)
2166 (repeat :tag "Specific properties" (string :tag "Property"))))
2168 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2169 "The default column format, if no other format has been defined.
2170 This variable can be set on the per-file basis by inserting a line
2172 #+COLUMNS: %25ITEM ....."
2173 :group 'org-properties
2174 :type 'string)
2176 (defcustom org-global-properties nil
2177 "List of property/value pairs that can be inherited by any entry.
2178 You can set buffer-local values for this by adding lines like
2180 #+PROPERTY: NAME VALUE"
2181 :group 'org-properties
2182 :type '(repeat
2183 (cons (string :tag "Property")
2184 (string :tag "Value"))))
2186 (defvar org-local-properties nil
2187 "List of property/value pairs that can be inherited by any entry.
2188 Valid for the current buffer.
2189 This variable is populated from #+PROPERTY lines.")
2191 (defgroup org-agenda nil
2192 "Options concerning agenda views in Org-mode."
2193 :tag "Org Agenda"
2194 :group 'org)
2196 (defvar org-category nil
2197 "Variable used by org files to set a category for agenda display.
2198 Such files should use a file variable to set it, for example
2200 # -*- mode: org; org-category: \"ELisp\"
2202 or contain a special line
2204 #+CATEGORY: ELisp
2206 If the file does not specify a category, then file's base name
2207 is used instead.")
2208 (make-variable-buffer-local 'org-category)
2210 (defcustom org-agenda-files nil
2211 "The files to be used for agenda display.
2212 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2213 \\[org-remove-file]. You can also use customize to edit the list.
2215 If an entry is a directory, all files in that directory that are matched by
2216 `org-agenda-file-regexp' will be part of the file list.
2218 If the value of the variable is not a list but a single file name, then
2219 the list of agenda files is actually stored and maintained in that file, one
2220 agenda file per line."
2221 :group 'org-agenda
2222 :type '(choice
2223 (repeat :tag "List of files and directories" file)
2224 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2226 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2227 "Regular expression to match files for `org-agenda-files'.
2228 If any element in the list in that variable contains a directory instead
2229 of a normal file, all files in that directory that are matched by this
2230 regular expression will be included."
2231 :group 'org-agenda
2232 :type 'regexp)
2234 (defcustom org-agenda-skip-unavailable-files nil
2235 "t means to just skip non-reachable files in `org-agenda-files'.
2236 Nil means to remove them, after a query, from the list."
2237 :group 'org-agenda
2238 :type 'boolean)
2240 (defcustom org-agenda-multi-occur-extra-files nil
2241 "List of extra files to be searched by `org-occur-in-agenda-files'.
2242 The files in `org-agenda-files' are always searched."
2243 :group 'org-agenda
2244 :type '(repeat file))
2246 (defcustom org-agenda-confirm-kill 1
2247 "When set, remote killing from the agenda buffer needs confirmation.
2248 When t, a confirmation is always needed. When a number N, confirmation is
2249 only needed when the text to be killed contains more than N non-white lines."
2250 :group 'org-agenda
2251 :type '(choice
2252 (const :tag "Never" nil)
2253 (const :tag "Always" t)
2254 (number :tag "When more than N lines")))
2256 (defcustom org-calendar-to-agenda-key [?c]
2257 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2258 The command `org-calendar-goto-agenda' will be bound to this key. The
2259 default is the character `c' because then `c' can be used to switch back and
2260 forth between agenda and calendar."
2261 :group 'org-agenda
2262 :type 'sexp)
2264 (defcustom org-agenda-compact-blocks nil
2265 "Non-nil means, make the block agenda more compact.
2266 This is done by leaving out unnecessary lines."
2267 :group 'org-agenda
2268 :type nil)
2270 (defgroup org-agenda-export nil
2271 "Options concerning exporting agenda views in Org-mode."
2272 :tag "Org Agenda Export"
2273 :group 'org-agenda)
2275 (defcustom org-agenda-with-colors t
2276 "Non-nil means, use colors in agenda views."
2277 :group 'org-agenda-export
2278 :type 'boolean)
2280 (defcustom org-agenda-exporter-settings nil
2281 "Alist of variable/value pairs that should be active during agenda export.
2282 This is a good place to set uptions for ps-print and for htmlize."
2283 :group 'org-agenda-export
2284 :type '(repeat
2285 (list
2286 (variable)
2287 (sexp :tag "Value"))))
2289 (defcustom org-agenda-export-html-style ""
2290 "The style specification for exported HTML Agenda files.
2291 If this variable contains a string, it will replace the default <style>
2292 section as produced by `htmlize'.
2293 Since there are different ways of setting style information, this variable
2294 needs to contain the full HTML structure to provide a style, including the
2295 surrounding HTML tags. The style specifications should include definitions
2296 the fonts used by the agenda, here is an example:
2298 <style type=\"text/css\">
2299 p { font-weight: normal; color: gray; }
2300 .org-agenda-structure {
2301 font-size: 110%;
2302 color: #003399;
2303 font-weight: 600;
2305 .org-todo {
2306 color: #cc6666;Week-agenda:
2307 font-weight: bold;
2309 .org-done {
2310 color: #339933;
2312 .title { text-align: center; }
2313 .todo, .deadline { color: red; }
2314 .done { color: green; }
2315 </style>
2317 or, if you want to keep the style in a file,
2319 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2321 As the value of this option simply gets inserted into the HTML <head> header,
2322 you can \"misuse\" it to also add other text to the header. However,
2323 <style>...</style> is required, if not present the variable will be ignored."
2324 :group 'org-agenda-export
2325 :group 'org-export-html
2326 :type 'string)
2328 (defgroup org-agenda-custom-commands nil
2329 "Options concerning agenda views in Org-mode."
2330 :tag "Org Agenda Custom Commands"
2331 :group 'org-agenda)
2333 (defcustom org-agenda-custom-commands nil
2334 "Custom commands for the agenda.
2335 These commands will be offered on the splash screen displayed by the
2336 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2338 (key desc type match options files)
2340 key The key (one or more characters as a string) to be associated
2341 with the command.
2342 desc A description of the commend, when omitted or nil, a default
2343 description is built using MATCH.
2344 type The command type, any of the following symbols:
2345 todo Entries with a specific TODO keyword, in all agenda files.
2346 tags Tags match in all agenda files.
2347 tags-todo Tags match in all agenda files, TODO entries only.
2348 todo-tree Sparse tree of specific TODO keyword in *current* file.
2349 tags-tree Sparse tree with all tags matches in *current* file.
2350 occur-tree Occur sparse tree for *current* file.
2351 ... A user-defined function.
2352 match What to search for:
2353 - a single keyword for TODO keyword searches
2354 - a tags match expression for tags searches
2355 - a regular expression for occur searches
2356 options A list of option settings, similar to that in a let form, so like
2357 this: ((opt1 val1) (opt2 val2) ...)
2358 files A list of files file to write the produced agenda buffer to
2359 with the command `org-store-agenda-views'.
2360 If a file name ends in \".html\", an HTML version of the buffer
2361 is written out. If it ends in \".ps\", a postscript version is
2362 produced. Otherwide, only the plain text is written to the file.
2364 You can also define a set of commands, to create a composite agenda buffer.
2365 In this case, an entry looks like this:
2367 (key desc (cmd1 cmd2 ...) general-options file)
2369 where
2371 desc A description string to be displayed in the dispatcher menu.
2372 cmd An agenda command, similar to the above. However, tree commands
2373 are no allowed, but instead you can get agenda and global todo list.
2374 So valid commands for a set are:
2375 (agenda)
2376 (alltodo)
2377 (stuck)
2378 (todo \"match\" options files)
2379 (tags \"match\" options files)
2380 (tags-todo \"match\" options files)
2382 Each command can carry a list of options, and another set of options can be
2383 given for the whole set of commands. Individual command options take
2384 precedence over the general options.
2386 When using several characters as key to a command, the first characters
2387 are prefix commands. For the dispatcher to display useful information, you
2388 should provide a description for the prefix, like
2390 (setq org-agenda-custom-commands
2391 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2392 (\"hl\" tags \"+HOME+Lisa\")
2393 (\"hp\" tags \"+HOME+Peter\")
2394 (\"hk\" tags \"+HOME+Kim\")))"
2395 :group 'org-agenda-custom-commands
2396 :type '(repeat
2397 (choice :value ("a" "" tags "" nil)
2398 (list :tag "Single command"
2399 (string :tag "Access Key(s) ")
2400 (option (string :tag "Description"))
2401 (choice
2402 (const :tag "Agenda" agenda)
2403 (const :tag "TODO list" alltodo)
2404 (const :tag "Stuck projects" stuck)
2405 (const :tag "Tags search (all agenda files)" tags)
2406 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2407 (const :tag "TODO keyword search (all agenda files)" todo)
2408 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2409 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2410 (const :tag "Occur tree (current buffer)" occur-tree)
2411 (sexp :tag "Other, user-defined function"))
2412 (string :tag "Match")
2413 (repeat :tag "Local options"
2414 (list (variable :tag "Option") (sexp :tag "Value")))
2415 (option (repeat :tag "Export" (file :tag "Export to"))))
2416 (list :tag "Command series, all agenda files"
2417 (string :tag "Access Key(s)")
2418 (string :tag "Description ")
2419 (repeat
2420 (choice
2421 (const :tag "Agenda" (agenda))
2422 (const :tag "TODO list" (alltodo))
2423 (const :tag "Stuck projects" (stuck))
2424 (list :tag "Tags search"
2425 (const :format "" tags)
2426 (string :tag "Match")
2427 (repeat :tag "Local options"
2428 (list (variable :tag "Option")
2429 (sexp :tag "Value"))))
2431 (list :tag "Tags search, TODO entries only"
2432 (const :format "" tags-todo)
2433 (string :tag "Match")
2434 (repeat :tag "Local options"
2435 (list (variable :tag "Option")
2436 (sexp :tag "Value"))))
2438 (list :tag "TODO keyword search"
2439 (const :format "" todo)
2440 (string :tag "Match")
2441 (repeat :tag "Local options"
2442 (list (variable :tag "Option")
2443 (sexp :tag "Value"))))
2445 (list :tag "Other, user-defined function"
2446 (symbol :tag "function")
2447 (string :tag "Match")
2448 (repeat :tag "Local options"
2449 (list (variable :tag "Option")
2450 (sexp :tag "Value"))))))
2452 (repeat :tag "General options"
2453 (list (variable :tag "Option")
2454 (sexp :tag "Value")))
2455 (option (repeat :tag "Export" (file :tag "Export to"))))
2456 (cons :tag "Prefix key documentation"
2457 (string :tag "Access Key(s)")
2458 (string :tag "Description ")))))
2460 (defcustom org-stuck-projects
2461 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2462 "How to identify stuck projects.
2463 This is a list of four items:
2464 1. A tags/todo matcher string that is used to identify a project.
2465 The entire tree below a headline matched by this is considered one project.
2466 2. A list of TODO keywords identifying non-stuck projects.
2467 If the project subtree contains any headline with one of these todo
2468 keywords, the project is considered to be not stuck. If you specify
2469 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2470 3. A list of tags identifying non-stuck projects.
2471 If the project subtree contains any headline with one of these tags,
2472 the project is considered to be not stuck. If you specify \"*\" as
2473 a tag, any tag will mark the project unstuck.
2474 4. An arbitrary regular expression matching non-stuck projects.
2476 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2477 or `C-c a #' to produce the list."
2478 :group 'org-agenda-custom-commands
2479 :type '(list
2480 (string :tag "Tags/TODO match to identify a project")
2481 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2482 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2483 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2486 (defgroup org-agenda-skip nil
2487 "Options concerning skipping parts of agenda files."
2488 :tag "Org Agenda Skip"
2489 :group 'org-agenda)
2491 (defcustom org-agenda-todo-list-sublevels t
2492 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2493 When nil, the sublevels of a TODO entry are not checked, resulting in
2494 potentially much shorter TODO lists."
2495 :group 'org-agenda-skip
2496 :group 'org-todo
2497 :type 'boolean)
2499 (defcustom org-agenda-todo-ignore-with-date nil
2500 "Non-nil means, don't show entries with a date in the global todo list.
2501 You can use this if you prefer to mark mere appointments with a TODO keyword,
2502 but don't want them to show up in the TODO list.
2503 When this is set, it also covers deadlines and scheduled items, the settings
2504 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2505 will be ignored."
2506 :group 'org-agenda-skip
2507 :group 'org-todo
2508 :type 'boolean)
2510 (defcustom org-agenda-todo-ignore-scheduled nil
2511 "Non-nil means, don't show scheduled entries in the global todo list.
2512 The idea behind this is that by scheduling it, you have already taken care
2513 of this item.
2514 See also `org-agenda-todo-ignore-with-date'."
2515 :group 'org-agenda-skip
2516 :group 'org-todo
2517 :type 'boolean)
2519 (defcustom org-agenda-todo-ignore-deadlines nil
2520 "Non-nil means, don't show near deadline entries in the global todo list.
2521 Near means closer than `org-deadline-warning-days' days.
2522 The idea behind this is that such items will appear in the agenda anyway.
2523 See also `org-agenda-todo-ignore-with-date'."
2524 :group 'org-agenda-skip
2525 :group 'org-todo
2526 :type 'boolean)
2528 (defcustom org-agenda-skip-scheduled-if-done nil
2529 "Non-nil means don't show scheduled items in agenda when they are done.
2530 This is relevant for the daily/weekly agenda, not for the TODO list. And
2531 it applies only to the actual date of the scheduling. Warnings about
2532 an item with a past scheduling dates are always turned off when the item
2533 is DONE."
2534 :group 'org-agenda-skip
2535 :type 'boolean)
2537 (defcustom org-agenda-skip-deadline-if-done nil
2538 "Non-nil means don't show deadines when the corresponding item is done.
2539 When nil, the deadline is still shown and should give you a happy feeling.
2540 This is relevant for the daily/weekly agenda. And it applied only to the
2541 actualy date of the deadline. Warnings about approching and past-due
2542 deadlines are always turned off when the item is DONE."
2543 :group 'org-agenda-skip
2544 :type 'boolean)
2546 (defcustom org-agenda-skip-timestamp-if-done nil
2547 "Non-nil means don't select item by timestamp or -range if it is DONE."
2548 :group 'org-agenda-skip
2549 :type 'boolean)
2551 (defcustom org-timeline-show-empty-dates 3
2552 "Non-nil means, `org-timeline' also shows dates without an entry.
2553 When nil, only the days which actually have entries are shown.
2554 When t, all days between the first and the last date are shown.
2555 When an integer, show also empty dates, but if there is a gap of more than
2556 N days, just insert a special line indicating the size of the gap."
2557 :group 'org-agenda-skip
2558 :type '(choice
2559 (const :tag "None" nil)
2560 (const :tag "All" t)
2561 (number :tag "at most")))
2564 (defgroup org-agenda-startup nil
2565 "Options concerning initial settings in the Agenda in Org Mode."
2566 :tag "Org Agenda Startup"
2567 :group 'org-agenda)
2569 (defcustom org-finalize-agenda-hook nil
2570 "Hook run just before displaying an agenda buffer."
2571 :group 'org-agenda-startup
2572 :type 'hook)
2574 (defcustom org-agenda-mouse-1-follows-link nil
2575 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2576 A longer mouse click will still set point. Does not wortk on XEmacs.
2577 Needs to be set before org.el is loaded."
2578 :group 'org-agenda-startup
2579 :type 'boolean)
2581 (defcustom org-agenda-start-with-follow-mode nil
2582 "The initial value of follow-mode in a newly created agenda window."
2583 :group 'org-agenda-startup
2584 :type 'boolean)
2586 (defgroup org-agenda-windows nil
2587 "Options concerning the windows used by the Agenda in Org Mode."
2588 :tag "Org Agenda Windows"
2589 :group 'org-agenda)
2591 (defcustom org-agenda-window-setup 'reorganize-frame
2592 "How the agenda buffer should be displayed.
2593 Possible values for this option are:
2595 current-window Show agenda in the current window, keeping all other windows.
2596 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2597 other-window Use `switch-to-buffer-other-window' to display agenda.
2598 reorganize-frame Show only two windows on the current frame, the current
2599 window and the agenda.
2600 See also the variable `org-agenda-restore-windows-after-quit'."
2601 :group 'org-agenda-windows
2602 :type '(choice
2603 (const current-window)
2604 (const other-frame)
2605 (const other-window)
2606 (const reorganize-frame)))
2608 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2609 "The min and max height of the agenda window as a fraction of frame height.
2610 The value of the variable is a cons cell with two numbers between 0 and 1.
2611 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2612 :group 'org-agenda-windows
2613 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2615 (defcustom org-agenda-restore-windows-after-quit nil
2616 "Non-nil means, restore window configuration open exiting agenda.
2617 Before the window configuration is changed for displaying the agenda,
2618 the current status is recorded. When the agenda is exited with
2619 `q' or `x' and this option is set, the old state is restored. If
2620 `org-agenda-window-setup' is `other-frame', the value of this
2621 option will be ignored.."
2622 :group 'org-agenda-windows
2623 :type 'boolean)
2625 (defcustom org-indirect-buffer-display 'other-window
2626 "How should indirect tree buffers be displayed?
2627 This applies to indirect buffers created with the commands
2628 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2629 Valid values are:
2630 current-window Display in the current window
2631 other-window Just display in another window.
2632 dedicated-frame Create one new frame, and re-use it each time.
2633 new-frame Make a new frame each time. Note that in this case
2634 previously-made indirect buffers are kept, and you need to
2635 kill these buffers yourself."
2636 :group 'org-structure
2637 :group 'org-agenda-windows
2638 :type '(choice
2639 (const :tag "In current window" current-window)
2640 (const :tag "In current frame, other window" other-window)
2641 (const :tag "Each time a new frame" new-frame)
2642 (const :tag "One dedicated frame" dedicated-frame)))
2644 (defgroup org-agenda-daily/weekly nil
2645 "Options concerning the daily/weekly agenda."
2646 :tag "Org Agenda Daily/Weekly"
2647 :group 'org-agenda)
2649 (defcustom org-agenda-ndays 7
2650 "Number of days to include in overview display.
2651 Should be 1 or 7."
2652 :group 'org-agenda-daily/weekly
2653 :type 'number)
2655 (defcustom org-agenda-start-on-weekday 1
2656 "Non-nil means, start the overview always on the specified weekday.
2657 0 denotes Sunday, 1 denotes Monday etc.
2658 When nil, always start on the current day."
2659 :group 'org-agenda-daily/weekly
2660 :type '(choice (const :tag "Today" nil)
2661 (number :tag "Weekday No.")))
2663 (defcustom org-agenda-show-all-dates t
2664 "Non-nil means, `org-agenda' shows every day in the selected range.
2665 When nil, only the days which actually have entries are shown."
2666 :group 'org-agenda-daily/weekly
2667 :type 'boolean)
2669 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2670 "Format string for displaying dates in the agenda.
2671 Used by the daily/weekly agenda and by the timeline. This should be
2672 a format string understood by `format-time-string', or a function returning
2673 the formatted date as a string. The function must take a single argument,
2674 a calendar-style date list like (month day year)."
2675 :group 'org-agenda-daily/weekly
2676 :type '(choice
2677 (string :tag "Format string")
2678 (function :tag "Function")))
2680 (defun org-agenda-format-date-aligned (date)
2681 "Format a date string for display in the daily/weekly agenda, or timeline.
2682 This function makes sure that dates are aligned for easy reading."
2683 (format "%-9s %2d %s %4d"
2684 (calendar-day-name date)
2685 (extract-calendar-day date)
2686 (calendar-month-name (extract-calendar-month date))
2687 (extract-calendar-year date)))
2689 (defcustom org-agenda-include-diary nil
2690 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2691 :group 'org-agenda-daily/weekly
2692 :type 'boolean)
2694 (defcustom org-agenda-include-all-todo nil
2695 "Set means weekly/daily agenda will always contain all TODO entries.
2696 The TODO entries will be listed at the top of the agenda, before
2697 the entries for specific days."
2698 :group 'org-agenda-daily/weekly
2699 :type 'boolean)
2701 (defcustom org-agenda-repeating-timestamp-show-all t
2702 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2703 When nil, only one occurence is shown, either today or the
2704 nearest into the future."
2705 :group 'org-agenda-daily/weekly
2706 :type 'boolean)
2708 (defcustom org-deadline-warning-days 14
2709 "No. of days before expiration during which a deadline becomes active.
2710 This variable governs the display in sparse trees and in the agenda.
2711 When negative or null, it means use the absolute value of this number
2712 even if a deadline has a different individual lead time specified."
2713 :group 'org-time
2714 :group 'org-agenda-daily/weekly
2715 :type 'number)
2717 (defcustom org-scheduled-past-days 10000
2718 "No. of days to continue listing scheduled items that are not marked DONE.
2719 When an item is scheduled on a date, it shows up in the agenda on this
2720 day and will be listed until it is marked done for the number of days
2721 given here."
2722 :group 'org-agenda-daily/weekly
2723 :type 'number)
2725 (defgroup org-agenda-time-grid nil
2726 "Options concerning the time grid in the Org-mode Agenda."
2727 :tag "Org Agenda Time Grid"
2728 :group 'org-agenda)
2730 (defcustom org-agenda-use-time-grid t
2731 "Non-nil means, show a time grid in the agenda schedule.
2732 A time grid is a set of lines for specific times (like every two hours between
2733 8:00 and 20:00). The items scheduled for a day at specific times are
2734 sorted in between these lines.
2735 For details about when the grid will be shown, and what it will look like, see
2736 the variable `org-agenda-time-grid'."
2737 :group 'org-agenda-time-grid
2738 :type 'boolean)
2740 (defcustom org-agenda-time-grid
2741 '((daily today require-timed)
2742 "----------------"
2743 (800 1000 1200 1400 1600 1800 2000))
2745 "The settings for time grid for agenda display.
2746 This is a list of three items. The first item is again a list. It contains
2747 symbols specifying conditions when the grid should be displayed:
2749 daily if the agenda shows a single day
2750 weekly if the agenda shows an entire week
2751 today show grid on current date, independent of daily/weekly display
2752 require-timed show grid only if at least one item has a time specification
2754 The second item is a string which will be places behing the grid time.
2756 The third item is a list of integers, indicating the times that should have
2757 a grid line."
2758 :group 'org-agenda-time-grid
2759 :type
2760 '(list
2761 (set :greedy t :tag "Grid Display Options"
2762 (const :tag "Show grid in single day agenda display" daily)
2763 (const :tag "Show grid in weekly agenda display" weekly)
2764 (const :tag "Always show grid for today" today)
2765 (const :tag "Show grid only if any timed entries are present"
2766 require-timed)
2767 (const :tag "Skip grid times already present in an entry"
2768 remove-match))
2769 (string :tag "Grid String")
2770 (repeat :tag "Grid Times" (integer :tag "Time"))))
2772 (defgroup org-agenda-sorting nil
2773 "Options concerning sorting in the Org-mode Agenda."
2774 :tag "Org Agenda Sorting"
2775 :group 'org-agenda)
2777 (defconst org-sorting-choice
2778 '(choice
2779 (const time-up) (const time-down)
2780 (const category-keep) (const category-up) (const category-down)
2781 (const tag-down) (const tag-up)
2782 (const priority-up) (const priority-down))
2783 "Sorting choices.")
2785 (defcustom org-agenda-sorting-strategy
2786 '((agenda time-up category-keep priority-down)
2787 (todo category-keep priority-down)
2788 (tags category-keep priority-down))
2789 "Sorting structure for the agenda items of a single day.
2790 This is a list of symbols which will be used in sequence to determine
2791 if an entry should be listed before another entry. The following
2792 symbols are recognized:
2794 time-up Put entries with time-of-day indications first, early first
2795 time-down Put entries with time-of-day indications first, late first
2796 category-keep Keep the default order of categories, corresponding to the
2797 sequence in `org-agenda-files'.
2798 category-up Sort alphabetically by category, A-Z.
2799 category-down Sort alphabetically by category, Z-A.
2800 tag-up Sort alphabetically by last tag, A-Z.
2801 tag-down Sort alphabetically by last tag, Z-A.
2802 priority-up Sort numerically by priority, high priority last.
2803 priority-down Sort numerically by priority, high priority first.
2805 The different possibilities will be tried in sequence, and testing stops
2806 if one comparison returns a \"not-equal\". For example, the default
2807 '(time-up category-keep priority-down)
2808 means: Pull out all entries having a specified time of day and sort them,
2809 in order to make a time schedule for the current day the first thing in the
2810 agenda listing for the day. Of the entries without a time indication, keep
2811 the grouped in categories, don't sort the categories, but keep them in
2812 the sequence given in `org-agenda-files'. Within each category sort by
2813 priority.
2815 Leaving out `category-keep' would mean that items will be sorted across
2816 categories by priority.
2818 Instead of a single list, this can also be a set of list for specific
2819 contents, with a context symbol in the car of the list, any of
2820 `agenda', `todo', `tags' for the corresponding agenda views."
2821 :group 'org-agenda-sorting
2822 :type `(choice
2823 (repeat :tag "General" ,org-sorting-choice)
2824 (list :tag "Individually"
2825 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2826 (repeat ,org-sorting-choice))
2827 (cons (const :tag "Strategy for TODO lists" todo)
2828 (repeat ,org-sorting-choice))
2829 (cons (const :tag "Strategy for Tags matches" tags)
2830 (repeat ,org-sorting-choice)))))
2832 (defcustom org-sort-agenda-notime-is-late t
2833 "Non-nil means, items without time are considered late.
2834 This is only relevant for sorting. When t, items which have no explicit
2835 time like 15:30 will be considered as 99:01, i.e. later than any items which
2836 do have a time. When nil, the default time is before 0:00. You can use this
2837 option to decide if the schedule for today should come before or after timeless
2838 agenda entries."
2839 :group 'org-agenda-sorting
2840 :type 'boolean)
2842 (defgroup org-agenda-line-format nil
2843 "Options concerning the entry prefix in the Org-mode agenda display."
2844 :tag "Org Agenda Line Format"
2845 :group 'org-agenda)
2847 (defcustom org-agenda-prefix-format
2848 '((agenda . " %-12:c%?-12t% s")
2849 (timeline . " % s")
2850 (todo . " %-12:c")
2851 (tags . " %-12:c"))
2852 "Format specifications for the prefix of items in the agenda views.
2853 An alist with four entries, for the different agenda types. The keys to the
2854 sublists are `agenda', `timeline', `todo', and `tags'. The values
2855 are format strings.
2856 This format works similar to a printf format, with the following meaning:
2858 %c the category of the item, \"Diary\" for entries from the diary, or
2859 as given by the CATEGORY keyword or derived from the file name.
2860 %T the *last* tag of the item. Last because inherited tags come
2861 first in the list.
2862 %t the time-of-day specification if one applies to the entry, in the
2863 format HH:MM
2864 %s Scheduling/Deadline information, a short string
2866 All specifiers work basically like the standard `%s' of printf, but may
2867 contain two additional characters: A question mark just after the `%' and
2868 a whitespace/punctuation character just before the final letter.
2870 If the first character after `%' is a question mark, the entire field
2871 will only be included if the corresponding value applies to the
2872 current entry. This is useful for fields which should have fixed
2873 width when present, but zero width when absent. For example,
2874 \"%?-12t\" will result in a 12 character time field if a time of the
2875 day is specified, but will completely disappear in entries which do
2876 not contain a time.
2878 If there is punctuation or whitespace character just before the final
2879 format letter, this character will be appended to the field value if
2880 the value is not empty. For example, the format \"%-12:c\" leads to
2881 \"Diary: \" if the category is \"Diary\". If the category were be
2882 empty, no additional colon would be interted.
2884 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2885 - Indent the line with two space characters
2886 - Give the category in a 12 chars wide field, padded with whitespace on
2887 the right (because of `-'). Append a colon if there is a category
2888 (because of `:').
2889 - If there is a time-of-day, put it into a 12 chars wide field. If no
2890 time, don't put in an empty field, just skip it (because of '?').
2891 - Finally, put the scheduling information and append a whitespace.
2893 As another example, if you don't want the time-of-day of entries in
2894 the prefix, you could use:
2896 (setq org-agenda-prefix-format \" %-11:c% s\")
2898 See also the variables `org-agenda-remove-times-when-in-prefix' and
2899 `org-agenda-remove-tags'."
2900 :type '(choice
2901 (string :tag "General format")
2902 (list :greedy t :tag "View dependent"
2903 (cons (const agenda) (string :tag "Format"))
2904 (cons (const timeline) (string :tag "Format"))
2905 (cons (const todo) (string :tag "Format"))
2906 (cons (const tags) (string :tag "Format"))))
2907 :group 'org-agenda-line-format)
2909 (defvar org-prefix-format-compiled nil
2910 "The compiled version of the most recently used prefix format.
2911 See the variable `org-agenda-prefix-format'.")
2913 (defcustom org-agenda-todo-keyword-format "%-1s"
2914 "Format for the TODO keyword in agenda lines.
2915 Set this to something like \"%-12s\" if you want all TODO keywords
2916 to occupy a fixed space in the agenda display."
2917 :group 'org-agenda-line-format
2918 :type 'string)
2920 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
2921 "Text preceeding scheduled items in the agenda view.
2922 This is a list with two strings. The first applies when the item is
2923 scheduled on the current day. The second applies when it has been scheduled
2924 previously, it may contain a %d to capture how many days ago the item was
2925 scheduled."
2926 :group 'org-agenda-line-format
2927 :type '(list
2928 (string :tag "Scheduled today ")
2929 (string :tag "Scheduled previously")))
2931 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
2932 "Text preceeding deadline items in the agenda view.
2933 This is a list with two strings. The first applies when the item has its
2934 deadline on the current day. The second applies when it is in the past or
2935 in the future, it may contain %d to capture how many days away the deadline
2936 is (was)."
2937 :group 'org-agenda-line-format
2938 :type '(list
2939 (string :tag "Deadline today ")
2940 (string :tag "Deadline relative")))
2942 (defcustom org-agenda-remove-times-when-in-prefix t
2943 "Non-nil means, remove duplicate time specifications in agenda items.
2944 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2945 time-of-day specification in a headline or diary entry is extracted and
2946 placed into the prefix. If this option is non-nil, the original specification
2947 \(a timestamp or -range, or just a plain time(range) specification like
2948 11:30-4pm) will be removed for agenda display. This makes the agenda less
2949 cluttered.
2950 The option can be t or nil. It may also be the symbol `beg', indicating
2951 that the time should only be removed what it is located at the beginning of
2952 the headline/diary entry."
2953 :group 'org-agenda-line-format
2954 :type '(choice
2955 (const :tag "Always" t)
2956 (const :tag "Never" nil)
2957 (const :tag "When at beginning of entry" beg)))
2960 (defcustom org-agenda-default-appointment-duration nil
2961 "Default duration for appointments that only have a starting time.
2962 When nil, no duration is specified in such cases.
2963 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
2964 :group 'org-agenda-line-format
2965 :type '(choice
2966 (integer :tag "Minutes")
2967 (const :tag "No default duration")))
2970 (defcustom org-agenda-remove-tags nil
2971 "Non-nil means, remove the tags from the headline copy in the agenda.
2972 When this is the symbol `prefix', only remove tags when
2973 `org-agenda-prefix-format' contains a `%T' specifier."
2974 :group 'org-agenda-line-format
2975 :type '(choice
2976 (const :tag "Always" t)
2977 (const :tag "Never" nil)
2978 (const :tag "When prefix format contains %T" prefix)))
2980 (if (fboundp 'defvaralias)
2981 (defvaralias 'org-agenda-remove-tags-when-in-prefix
2982 'org-agenda-remove-tags))
2984 (defcustom org-agenda-tags-column -80
2985 "Shift tags in agenda items to this column.
2986 If this number is positive, it specifies the column. If it is negative,
2987 it means that the tags should be flushright to that column. For example,
2988 -80 works well for a normal 80 character screen."
2989 :group 'org-agenda-line-format
2990 :type 'integer)
2992 (if (fboundp 'defvaralias)
2993 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
2995 (defcustom org-agenda-fontify-priorities t
2996 "Non-nil means, highlight low and high priorities in agenda.
2997 When t, the highest priority entries are bold, lowest priority italic.
2998 This may also be an association list of priority faces. The face may be
2999 a names face, or a list like `(:background \"Red\")'."
3000 :group 'org-agenda-line-format
3001 :type '(choice
3002 (const :tag "Never" nil)
3003 (const :tag "Defaults" t)
3004 (repeat :tag "Specify"
3005 (list (character :tag "Priority" :value ?A)
3006 (sexp :tag "face")))))
3008 (defgroup org-latex nil
3009 "Options for embedding LaTeX code into Org-mode"
3010 :tag "Org LaTeX"
3011 :group 'org)
3013 (defcustom org-format-latex-options
3014 '(:foreground default :background default :scale 1.0
3015 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
3016 :matchers ("begin" "$" "$$" "\\(" "\\["))
3017 "Options for creating images from LaTeX fragments.
3018 This is a property list with the following properties:
3019 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
3020 `default' means use the forground of the default face.
3021 :background the background color, or \"Transparent\".
3022 `default' means use the background of the default face.
3023 :scale a scaling factor for the size of the images
3024 :html-foreground, :html-background, :html-scale
3025 The same numbers for HTML export.
3026 :matchers a list indicating which matchers should be used to
3027 find LaTeX fragments. Valid members of this list are:
3028 \"begin\" find environments
3029 \"$\" find math expressions surrounded by $...$
3030 \"$$\" find math expressions surrounded by $$....$$
3031 \"\\(\" find math expressions surrounded by \\(...\\)
3032 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3033 :group 'org-latex
3034 :type 'plist)
3036 (defcustom org-format-latex-header "\\documentclass{article}
3037 \\usepackage{fullpage} % do not remove
3038 \\usepackage{amssymb}
3039 \\usepackage[usenames]{color}
3040 \\usepackage{amsmath}
3041 \\usepackage{latexsym}
3042 \\usepackage[mathscr]{eucal}
3043 \\pagestyle{empty} % do not remove"
3044 "The document header used for processing LaTeX fragments."
3045 :group 'org-latex
3046 :type 'string)
3048 (defgroup org-export nil
3049 "Options for exporting org-listings."
3050 :tag "Org Export"
3051 :group 'org)
3053 (defgroup org-export-general nil
3054 "General options for exporting Org-mode files."
3055 :tag "Org Export General"
3056 :group 'org-export)
3058 ;; FIXME
3059 (defvar org-export-publishing-directory nil)
3061 (defcustom org-export-with-special-strings t
3062 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3063 When this option is turned on, these strings will be exported as:
3065 Org HTML LaTeX
3066 -----+----------+--------
3067 \\- &shy; \\-
3068 -- &ndash; --
3069 --- &mdash; ---
3070 ... &hellip; \ldots
3072 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3073 :group 'org-export-translation
3074 :type 'boolean)
3076 (defcustom org-export-language-setup
3077 '(("en" "Author" "Date" "Table of Contents")
3078 ("cs" "Autor" "Datum" "Obsah")
3079 ("da" "Ophavsmand" "Dato" "Indhold")
3080 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
3081 ("es" "Autor" "Fecha" "\xcdndice")
3082 ("fr" "Auteur" "Date" "Table des mati\xe8res")
3083 ("it" "Autore" "Data" "Indice")
3084 ("nl" "Auteur" "Datum" "Inhoudsopgave")
3085 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
3086 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
3087 "Terms used in export text, translated to different languages.
3088 Use the variable `org-export-default-language' to set the language,
3089 or use the +OPTION lines for a per-file setting."
3090 :group 'org-export-general
3091 :type '(repeat
3092 (list
3093 (string :tag "HTML language tag")
3094 (string :tag "Author")
3095 (string :tag "Date")
3096 (string :tag "Table of Contents"))))
3098 (defcustom org-export-default-language "en"
3099 "The default language of HTML export, as a string.
3100 This should have an association in `org-export-language-setup'."
3101 :group 'org-export-general
3102 :type 'string)
3104 (defcustom org-export-skip-text-before-1st-heading t
3105 "Non-nil means, skip all text before the first headline when exporting.
3106 When nil, that text is exported as well."
3107 :group 'org-export-general
3108 :type 'boolean)
3110 (defcustom org-export-headline-levels 3
3111 "The last level which is still exported as a headline.
3112 Inferior levels will produce itemize lists when exported.
3113 Note that a numeric prefix argument to an exporter function overrides
3114 this setting.
3116 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
3117 :group 'org-export-general
3118 :type 'number)
3120 (defcustom org-export-with-section-numbers t
3121 "Non-nil means, add section numbers to headlines when exporting.
3123 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
3124 :group 'org-export-general
3125 :type 'boolean)
3127 (defcustom org-export-with-toc t
3128 "Non-nil means, create a table of contents in exported files.
3129 The TOC contains headlines with levels up to`org-export-headline-levels'.
3130 When an integer, include levels up to N in the toc, this may then be
3131 different from `org-export-headline-levels', but it will not be allowed
3132 to be larger than the number of headline levels.
3133 When nil, no table of contents is made.
3135 Headlines which contain any TODO items will be marked with \"(*)\" in
3136 ASCII export, and with red color in HTML output, if the option
3137 `org-export-mark-todo-in-toc' is set.
3139 In HTML output, the TOC will be clickable.
3141 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
3142 or \"toc:3\"."
3143 :group 'org-export-general
3144 :type '(choice
3145 (const :tag "No Table of Contents" nil)
3146 (const :tag "Full Table of Contents" t)
3147 (integer :tag "TOC to level")))
3149 (defcustom org-export-mark-todo-in-toc nil
3150 "Non-nil means, mark TOC lines that contain any open TODO items."
3151 :group 'org-export-general
3152 :type 'boolean)
3154 (defcustom org-export-preserve-breaks nil
3155 "Non-nil means, preserve all line breaks when exporting.
3156 Normally, in HTML output paragraphs will be reformatted. In ASCII
3157 export, line breaks will always be preserved, regardless of this variable.
3159 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3160 :group 'org-export-general
3161 :type 'boolean)
3163 (defcustom org-export-with-archived-trees 'headline
3164 "Whether subtrees with the ARCHIVE tag should be exported.
3165 This can have three different values
3166 nil Do not export, pretend this tree is not present
3167 t Do export the entire tree
3168 headline Only export the headline, but skip the tree below it."
3169 :group 'org-export-general
3170 :group 'org-archive
3171 :type '(choice
3172 (const :tag "not at all" nil)
3173 (const :tag "headline only" 'headline)
3174 (const :tag "entirely" t)))
3176 (defcustom org-export-author-info t
3177 "Non-nil means, insert author name and email into the exported file.
3179 This option can also be set with the +OPTIONS line,
3180 e.g. \"author-info:nil\"."
3181 :group 'org-export-general
3182 :type 'boolean)
3184 (defcustom org-export-time-stamp-file t
3185 "Non-nil means, insert a time stamp into the exported file.
3186 The time stamp shows when the file was created.
3188 This option can also be set with the +OPTIONS line,
3189 e.g. \"timestamp:nil\"."
3190 :group 'org-export-general
3191 :type 'boolean)
3193 (defcustom org-export-with-timestamps t
3194 "If nil, do not export time stamps and associated keywords."
3195 :group 'org-export-general
3196 :type 'boolean)
3198 (defcustom org-export-remove-timestamps-from-toc t
3199 "If nil, remove timestamps from the table of contents entries."
3200 :group 'org-export-general
3201 :type 'boolean)
3203 (defcustom org-export-with-tags 'not-in-toc
3204 "If nil, do not export tags, just remove them from headlines.
3205 If this is the symbol `not-in-toc', tags will be removed from table of
3206 contents entries, but still be shown in the headlines of the document.
3208 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3209 :group 'org-export-general
3210 :type '(choice
3211 (const :tag "Off" nil)
3212 (const :tag "Not in TOC" not-in-toc)
3213 (const :tag "On" t)))
3215 (defcustom org-export-with-drawers nil
3216 "Non-nil means, export with drawers like the property drawer.
3217 When t, all drawers are exported. This may also be a list of
3218 drawer names to export."
3219 :group 'org-export-general
3220 :type '(choice
3221 (const :tag "All drawers" t)
3222 (const :tag "None" nil)
3223 (repeat :tag "Selected drawers"
3224 (string :tag "Drawer name"))))
3226 (defgroup org-export-translation nil
3227 "Options for translating special ascii sequences for the export backends."
3228 :tag "Org Export Translation"
3229 :group 'org-export)
3231 (defcustom org-export-with-emphasize t
3232 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3233 If the export target supports emphasizing text, the word will be
3234 typeset in bold, italic, or underlined, respectively. Works only for
3235 single words, but you can say: I *really* *mean* *this*.
3236 Not all export backends support this.
3238 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3239 :group 'org-export-translation
3240 :type 'boolean)
3242 (defcustom org-export-with-footnotes t
3243 "If nil, export [1] as a footnote marker.
3244 Lines starting with [1] will be formatted as footnotes.
3246 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3247 :group 'org-export-translation
3248 :type 'boolean)
3250 (defcustom org-export-with-sub-superscripts t
3251 "Non-nil means, interpret \"_\" and \"^\" for export.
3252 When this option is turned on, you can use TeX-like syntax for sub- and
3253 superscripts. Several characters after \"_\" or \"^\" will be
3254 considered as a single item - so grouping with {} is normally not
3255 needed. For example, the following things will be parsed as single
3256 sub- or superscripts.
3258 10^24 or 10^tau several digits will be considered 1 item.
3259 10^-12 or 10^-tau a leading sign with digits or a word
3260 x^2-y^3 will be read as x^2 - y^3, because items are
3261 terminated by almost any nonword/nondigit char.
3262 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3264 Still, ambiguity is possible - so when in doubt use {} to enclose the
3265 sub/superscript. If you set this variable to the symbol `{}',
3266 the braces are *required* in order to trigger interpretations as
3267 sub/superscript. This can be helpful in documents that need \"_\"
3268 frequently in plain text.
3270 Not all export backends support this, but HTML does.
3272 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3273 :group 'org-export-translation
3274 :type '(choice
3275 (const :tag "Always interpret" t)
3276 (const :tag "Only with braces" {})
3277 (const :tag "Never interpret" nil)))
3279 (defcustom org-export-with-special-strings t
3280 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3281 When this option is turned on, these strings will be exported as:
3283 \\- : &shy;
3284 -- : &ndash;
3285 --- : &mdash;
3287 Not all export backends support this, but HTML does.
3289 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3290 :group 'org-export-translation
3291 :type 'boolean)
3293 (defcustom org-export-with-TeX-macros t
3294 "Non-nil means, interpret simple TeX-like macros when exporting.
3295 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3296 No only real TeX macros will work here, but the standard HTML entities
3297 for math can be used as macro names as well. For a list of supported
3298 names in HTML export, see the constant `org-html-entities'.
3299 Not all export backends support this.
3301 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3302 :group 'org-export-translation
3303 :group 'org-export-latex
3304 :type 'boolean)
3306 (defcustom org-export-with-LaTeX-fragments nil
3307 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3308 When set, the exporter will find LaTeX environments if the \\begin line is
3309 the first non-white thing on a line. It will also find the math delimiters
3310 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3311 display math.
3313 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3314 :group 'org-export-translation
3315 :group 'org-export-latex
3316 :type 'boolean)
3318 (defcustom org-export-with-fixed-width t
3319 "Non-nil means, lines starting with \":\" will be in fixed width font.
3320 This can be used to have pre-formatted text, fragments of code etc. For
3321 example:
3322 : ;; Some Lisp examples
3323 : (while (defc cnt)
3324 : (ding))
3325 will be looking just like this in also HTML. See also the QUOTE keyword.
3326 Not all export backends support this.
3328 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3329 :group 'org-export-translation
3330 :type 'boolean)
3332 (defcustom org-match-sexp-depth 3
3333 "Number of stacked braces for sub/superscript matching.
3334 This has to be set before loading org.el to be effective."
3335 :group 'org-export-translation
3336 :type 'integer)
3338 (defgroup org-export-tables nil
3339 "Options for exporting tables in Org-mode."
3340 :tag "Org Export Tables"
3341 :group 'org-export)
3343 (defcustom org-export-with-tables t
3344 "If non-nil, lines starting with \"|\" define a table.
3345 For example:
3347 | Name | Address | Birthday |
3348 |-------------+----------+-----------|
3349 | Arthur Dent | England | 29.2.2100 |
3351 Not all export backends support this.
3353 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3354 :group 'org-export-tables
3355 :type 'boolean)
3357 (defcustom org-export-highlight-first-table-line t
3358 "Non-nil means, highlight the first table line.
3359 In HTML export, this means use <th> instead of <td>.
3360 In tables created with table.el, this applies to the first table line.
3361 In Org-mode tables, all lines before the first horizontal separator
3362 line will be formatted with <th> tags."
3363 :group 'org-export-tables
3364 :type 'boolean)
3366 (defcustom org-export-table-remove-special-lines t
3367 "Remove special lines and marking characters in calculating tables.
3368 This removes the special marking character column from tables that are set
3369 up for spreadsheet calculations. It also removes the entire lines
3370 marked with `!', `_', or `^'. The lines with `$' are kept, because
3371 the values of constants may be useful to have."
3372 :group 'org-export-tables
3373 :type 'boolean)
3375 (defcustom org-export-prefer-native-exporter-for-tables nil
3376 "Non-nil means, always export tables created with table.el natively.
3377 Natively means, use the HTML code generator in table.el.
3378 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3379 the table does not use row- or column-spanning). This has the
3380 advantage, that the automatic HTML conversions for math symbols and
3381 sub/superscripts can be applied. Org-mode's HTML generator is also
3382 much faster."
3383 :group 'org-export-tables
3384 :type 'boolean)
3386 (defgroup org-export-ascii nil
3387 "Options specific for ASCII export of Org-mode files."
3388 :tag "Org Export ASCII"
3389 :group 'org-export)
3391 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3392 "Characters for underlining headings in ASCII export.
3393 In the given sequence, these characters will be used for level 1, 2, ..."
3394 :group 'org-export-ascii
3395 :type '(repeat character))
3397 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3398 "Bullet characters for headlines converted to lists in ASCII export.
3399 The first character is used for the first lest level generated in this
3400 way, and so on. If there are more levels than characters given here,
3401 the list will be repeated.
3402 Note that plain lists will keep the same bullets as the have in the
3403 Org-mode file."
3404 :group 'org-export-ascii
3405 :type '(repeat character))
3407 (defgroup org-export-xml nil
3408 "Options specific for XML export of Org-mode files."
3409 :tag "Org Export XML"
3410 :group 'org-export)
3412 (defgroup org-export-html nil
3413 "Options specific for HTML export of Org-mode files."
3414 :tag "Org Export HTML"
3415 :group 'org-export)
3417 (defcustom org-export-html-coding-system nil
3419 :group 'org-export-html
3420 :type 'coding-system)
3422 (defcustom org-export-html-extension "html"
3423 "The extension for exported HTML files."
3424 :group 'org-export-html
3425 :type 'string)
3427 (defcustom org-export-html-style
3428 "<style type=\"text/css\">
3429 html {
3430 font-family: Times, serif;
3431 font-size: 12pt;
3433 .title { text-align: center; }
3434 .todo { color: red; }
3435 .done { color: green; }
3436 .timestamp { color: grey }
3437 .timestamp-kwd { color: CadetBlue }
3438 .tag { background-color:lightblue; font-weight:normal }
3439 .target { background-color: lavender; }
3440 pre {
3441 border: 1pt solid #AEBDCC;
3442 background-color: #F3F5F7;
3443 padding: 5pt;
3444 font-family: courier, monospace;
3446 table { border-collapse: collapse; }
3447 td, th {
3448 vertical-align: top;
3449 <!--border: 1pt solid #ADB9CC;-->
3451 </style>"
3452 "The default style specification for exported HTML files.
3453 Since there are different ways of setting style information, this variable
3454 needs to contain the full HTML structure to provide a style, including the
3455 surrounding HTML tags. The style specifications should include definitions
3456 for new classes todo, done, title, and deadline. For example, legal values
3457 would be:
3459 <style type=\"text/css\">
3460 p { font-weight: normal; color: gray; }
3461 h1 { color: black; }
3462 .title { text-align: center; }
3463 .todo, .deadline { color: red; }
3464 .done { color: green; }
3465 </style>
3467 or, if you want to keep the style in a file,
3469 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3471 As the value of this option simply gets inserted into the HTML <head> header,
3472 you can \"misuse\" it to add arbitrary text to the header."
3473 :group 'org-export-html
3474 :type 'string)
3477 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3478 "Format for typesetting the document title in HTML export."
3479 :group 'org-export-html
3480 :type 'string)
3482 (defcustom org-export-html-toplevel-hlevel 2
3483 "The <H> level for level 1 headings in HTML export."
3484 :group 'org-export-html
3485 :type 'string)
3487 (defcustom org-export-html-link-org-files-as-html t
3488 "Non-nil means, make file links to `file.org' point to `file.html'.
3489 When org-mode is exporting an org-mode file to HTML, links to
3490 non-html files are directly put into a href tag in HTML.
3491 However, links to other Org-mode files (recognized by the
3492 extension `.org.) should become links to the corresponding html
3493 file, assuming that the linked org-mode file will also be
3494 converted to HTML.
3495 When nil, the links still point to the plain `.org' file."
3496 :group 'org-export-html
3497 :type 'boolean)
3499 (defcustom org-export-html-inline-images 'maybe
3500 "Non-nil means, inline images into exported HTML pages.
3501 This is done using an <img> tag. When nil, an anchor with href is used to
3502 link to the image. If this option is `maybe', then images in links with
3503 an empty description will be inlined, while images with a description will
3504 be linked only."
3505 :group 'org-export-html
3506 :type '(choice (const :tag "Never" nil)
3507 (const :tag "Always" t)
3508 (const :tag "When there is no description" maybe)))
3510 ;; FIXME: rename
3511 (defcustom org-export-html-expand t
3512 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3513 When nil, these tags will be exported as plain text and therefore
3514 not be interpreted by a browser.
3516 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3517 :group 'org-export-html
3518 :type 'boolean)
3520 (defcustom org-export-html-table-tag
3521 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3522 "The HTML tag that is used to start a table.
3523 This must be a <table> tag, but you may change the options like
3524 borders and spacing."
3525 :group 'org-export-html
3526 :type 'string)
3528 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3529 "The opening tag for table header fields.
3530 This is customizable so that alignment options can be specified."
3531 :group 'org-export-tables
3532 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3534 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3535 "The opening tag for table data fields.
3536 This is customizable so that alignment options can be specified."
3537 :group 'org-export-tables
3538 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3540 (defcustom org-export-html-with-timestamp nil
3541 "If non-nil, write `org-export-html-html-helper-timestamp'
3542 into the exported HTML text. Otherwise, the buffer will just be saved
3543 to a file."
3544 :group 'org-export-html
3545 :type 'boolean)
3547 (defcustom org-export-html-html-helper-timestamp
3548 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3549 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3550 :group 'org-export-html
3551 :type 'string)
3553 (defgroup org-export-icalendar nil
3554 "Options specific for iCalendar export of Org-mode files."
3555 :tag "Org Export iCalendar"
3556 :group 'org-export)
3558 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3559 "The file name for the iCalendar file covering all agenda files.
3560 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3561 The file name should be absolute, the file will be overwritten without warning."
3562 :group 'org-export-icalendar
3563 :type 'file)
3565 (defcustom org-icalendar-include-todo nil
3566 "Non-nil means, export to iCalendar files should also cover TODO items."
3567 :group 'org-export-icalendar
3568 :type '(choice
3569 (const :tag "None" nil)
3570 (const :tag "Unfinished" t)
3571 (const :tag "All" all)))
3573 (defcustom org-icalendar-include-sexps t
3574 "Non-nil means, export to iCalendar files should also cover sexp entries.
3575 These are entries like in the diary, but directly in an Org-mode file."
3576 :group 'org-export-icalendar
3577 :type 'boolean)
3579 (defcustom org-icalendar-include-body 100
3580 "Amount of text below headline to be included in iCalendar export.
3581 This is a number of characters that should maximally be included.
3582 Properties, scheduling and clocking lines will always be removed.
3583 The text will be inserted into the DESCRIPTION field."
3584 :group 'org-export-icalendar
3585 :type '(choice
3586 (const :tag "Nothing" nil)
3587 (const :tag "Everything" t)
3588 (integer :tag "Max characters")))
3590 (defcustom org-icalendar-combined-name "OrgMode"
3591 "Calendar name for the combined iCalendar representing all agenda files."
3592 :group 'org-export-icalendar
3593 :type 'string)
3595 (defgroup org-font-lock nil
3596 "Font-lock settings for highlighting in Org-mode."
3597 :tag "Org Font Lock"
3598 :group 'org)
3600 (defcustom org-level-color-stars-only nil
3601 "Non-nil means fontify only the stars in each headline.
3602 When nil, the entire headline is fontified.
3603 Changing it requires restart of `font-lock-mode' to become effective
3604 also in regions already fontified."
3605 :group 'org-font-lock
3606 :type 'boolean)
3608 (defcustom org-hide-leading-stars nil
3609 "Non-nil means, hide the first N-1 stars in a headline.
3610 This works by using the face `org-hide' for these stars. This
3611 face is white for a light background, and black for a dark
3612 background. You may have to customize the face `org-hide' to
3613 make this work.
3614 Changing it requires restart of `font-lock-mode' to become effective
3615 also in regions already fontified.
3616 You may also set this on a per-file basis by adding one of the following
3617 lines to the buffer:
3619 #+STARTUP: hidestars
3620 #+STARTUP: showstars"
3621 :group 'org-font-lock
3622 :type 'boolean)
3624 (defcustom org-fontify-done-headline nil
3625 "Non-nil means, change the face of a headline if it is marked DONE.
3626 Normally, only the TODO/DONE keyword indicates the state of a headline.
3627 When this is non-nil, the headline after the keyword is set to the
3628 `org-headline-done' as an additional indication."
3629 :group 'org-font-lock
3630 :type 'boolean)
3632 (defcustom org-fontify-emphasized-text t
3633 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3634 Changing this variable requires a restart of Emacs to take effect."
3635 :group 'org-font-lock
3636 :type 'boolean)
3638 (defcustom org-highlight-latex-fragments-and-specials nil
3639 "Non-nil means, fontify what is treated specially by the exporters."
3640 :group 'org-font-lock
3641 :type 'boolean)
3643 (defcustom org-hide-emphasis-markers nil
3644 "Non-nil mean font-lock should hide the emphasis marker characters."
3645 :group 'org-font-lock
3646 :type 'boolean)
3648 (defvar org-emph-re nil
3649 "Regular expression for matching emphasis.")
3650 (defvar org-verbatim-re nil
3651 "Regular expression for matching verbatim text.")
3652 (defvar org-emphasis-regexp-components) ; defined just below
3653 (defvar org-emphasis-alist) ; defined just below
3654 (defun org-set-emph-re (var val)
3655 "Set variable and compute the emphasis regular expression."
3656 (set var val)
3657 (when (and (boundp 'org-emphasis-alist)
3658 (boundp 'org-emphasis-regexp-components)
3659 org-emphasis-alist org-emphasis-regexp-components)
3660 (let* ((e org-emphasis-regexp-components)
3661 (pre (car e))
3662 (post (nth 1 e))
3663 (border (nth 2 e))
3664 (body (nth 3 e))
3665 (nl (nth 4 e))
3666 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3667 (body1 (concat body "*?"))
3668 (markers (mapconcat 'car org-emphasis-alist ""))
3669 (vmarkers (mapconcat
3670 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3671 org-emphasis-alist "")))
3672 ;; make sure special characters appear at the right position in the class
3673 (if (string-match "\\^" markers)
3674 (setq markers (concat (replace-match "" t t markers) "^")))
3675 (if (string-match "-" markers)
3676 (setq markers (concat (replace-match "" t t markers) "-")))
3677 (if (string-match "\\^" vmarkers)
3678 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3679 (if (string-match "-" vmarkers)
3680 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3681 (if (> nl 0)
3682 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3683 (int-to-string nl) "\\}")))
3684 ;; Make the regexp
3685 (setq org-emph-re
3686 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3687 "\\("
3688 "\\([" markers "]\\)"
3689 "\\("
3690 "[^" border "]\\|"
3691 "[^" border (if (and nil stacked) markers) "]"
3692 body1
3693 "[^" border (if (and nil stacked) markers) "]"
3694 "\\)"
3695 "\\3\\)"
3696 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3697 (setq org-verbatim-re
3698 (concat "\\([" pre "]\\|^\\)"
3699 "\\("
3700 "\\([" vmarkers "]\\)"
3701 "\\("
3702 "[^" border "]\\|"
3703 "[^" border "]"
3704 body1
3705 "[^" border "]"
3706 "\\)"
3707 "\\3\\)"
3708 "\\([" post "]\\|$\\)")))))
3710 (defcustom org-emphasis-regexp-components
3711 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3712 "Components used to build the regular expression for emphasis.
3713 This is a list with 6 entries. Terminology: In an emphasis string
3714 like \" *strong word* \", we call the initial space PREMATCH, the final
3715 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3716 and \"trong wor\" is the body. The different components in this variable
3717 specify what is allowed/forbidden in each part:
3719 pre Chars allowed as prematch. Beginning of line will be allowed too.
3720 post Chars allowed as postmatch. End of line will be allowed too.
3721 border The chars *forbidden* as border characters.
3722 body-regexp A regexp like \".\" to match a body character. Don't use
3723 non-shy groups here, and don't allow newline here.
3724 newline The maximum number of newlines allowed in an emphasis exp.
3726 Use customize to modify this, or restart Emacs after changing it."
3727 :group 'org-font-lock
3728 :set 'org-set-emph-re
3729 :type '(list
3730 (sexp :tag "Allowed chars in pre ")
3731 (sexp :tag "Allowed chars in post ")
3732 (sexp :tag "Forbidden chars in border ")
3733 (sexp :tag "Regexp for body ")
3734 (integer :tag "number of newlines allowed")
3735 (option (boolean :tag "Stacking (DISABLED) "))))
3737 (defcustom org-emphasis-alist
3738 '(("*" bold "<b>" "</b>")
3739 ("/" italic "<i>" "</i>")
3740 ("_" underline "<u>" "</u>")
3741 ("=" org-code "<code>" "</code>" verbatim)
3742 ("~" org-verbatim "" "" verbatim)
3743 ("+" (:strike-through t) "<del>" "</del>")
3745 "Special syntax for emphasized text.
3746 Text starting and ending with a special character will be emphasized, for
3747 example *bold*, _underlined_ and /italic/. This variable sets the marker
3748 characters, the face to be used by font-lock for highlighting in Org-mode
3749 Emacs buffers, and the HTML tags to be used for this.
3750 Use customize to modify this, or restart Emacs after changing it."
3751 :group 'org-font-lock
3752 :set 'org-set-emph-re
3753 :type '(repeat
3754 (list
3755 (string :tag "Marker character")
3756 (choice
3757 (face :tag "Font-lock-face")
3758 (plist :tag "Face property list"))
3759 (string :tag "HTML start tag")
3760 (string :tag "HTML end tag")
3761 (option (const verbatim)))))
3763 ;;; The faces
3765 (defgroup org-faces nil
3766 "Faces in Org-mode."
3767 :tag "Org Faces"
3768 :group 'org-font-lock)
3770 (defun org-compatible-face (inherits specs)
3771 "Make a compatible face specification.
3772 If INHERITS is an existing face and if the Emacs version supports it,
3773 just inherit the face. If not, use SPECS to define the face.
3774 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3775 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3776 to the top of the list. The `min-colors' attribute will be removed from
3777 any other entries, and any resulting duplicates will be removed entirely."
3778 (cond
3779 ((and inherits (facep inherits)
3780 (not (featurep 'xemacs)) (> emacs-major-version 22))
3781 ;; In Emacs 23, we use inheritance where possible.
3782 ;; We only do this in Emacs 23, because only there the outline
3783 ;; faces have been changed to the original org-mode-level-faces.
3784 (list (list t :inherit inherits)))
3785 ((or (featurep 'xemacs) (< emacs-major-version 22))
3786 ;; These do not understand the `min-colors' attribute.
3787 (let (r e a)
3788 (while (setq e (pop specs))
3789 (cond
3790 ((memq (car e) '(t default)) (push e r))
3791 ((setq a (member '(min-colors 8) (car e)))
3792 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3793 (cdr e)))))
3794 ((setq a (assq 'min-colors (car e)))
3795 (setq e (cons (delq a (car e)) (cdr e)))
3796 (or (assoc (car e) r) (push e r)))
3797 (t (or (assoc (car e) r) (push e r)))))
3798 (nreverse r)))
3799 (t specs)))
3800 (put 'org-compatible-face 'lisp-indent-function 1)
3802 (defface org-hide
3803 '((((background light)) (:foreground "white"))
3804 (((background dark)) (:foreground "black")))
3805 "Face used to hide leading stars in headlines.
3806 The forground color of this face should be equal to the background
3807 color of the frame."
3808 :group 'org-faces)
3810 (defface org-level-1 ;; font-lock-function-name-face
3811 (org-compatible-face 'outline-1
3812 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3813 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3814 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3815 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3816 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3817 (t (:bold t))))
3818 "Face used for level 1 headlines."
3819 :group 'org-faces)
3821 (defface org-level-2 ;; font-lock-variable-name-face
3822 (org-compatible-face 'outline-2
3823 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3824 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3825 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3826 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3827 (t (:bold t))))
3828 "Face used for level 2 headlines."
3829 :group 'org-faces)
3831 (defface org-level-3 ;; font-lock-keyword-face
3832 (org-compatible-face 'outline-3
3833 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3834 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3835 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3836 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3837 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3838 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3839 (t (:bold t))))
3840 "Face used for level 3 headlines."
3841 :group 'org-faces)
3843 (defface org-level-4 ;; font-lock-comment-face
3844 (org-compatible-face 'outline-4
3845 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3846 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3847 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3848 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3849 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3850 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3851 (t (:bold t))))
3852 "Face used for level 4 headlines."
3853 :group 'org-faces)
3855 (defface org-level-5 ;; font-lock-type-face
3856 (org-compatible-face 'outline-5
3857 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3858 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3859 (((class color) (min-colors 8)) (:foreground "green"))))
3860 "Face used for level 5 headlines."
3861 :group 'org-faces)
3863 (defface org-level-6 ;; font-lock-constant-face
3864 (org-compatible-face 'outline-6
3865 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3866 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3867 (((class color) (min-colors 8)) (:foreground "magenta"))))
3868 "Face used for level 6 headlines."
3869 :group 'org-faces)
3871 (defface org-level-7 ;; font-lock-builtin-face
3872 (org-compatible-face 'outline-7
3873 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3874 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3875 (((class color) (min-colors 8)) (:foreground "blue"))))
3876 "Face used for level 7 headlines."
3877 :group 'org-faces)
3879 (defface org-level-8 ;; font-lock-string-face
3880 (org-compatible-face 'outline-8
3881 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3882 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3883 (((class color) (min-colors 8)) (:foreground "green"))))
3884 "Face used for level 8 headlines."
3885 :group 'org-faces)
3887 (defface org-special-keyword ;; font-lock-string-face
3888 (org-compatible-face nil
3889 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3890 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3891 (t (:italic t))))
3892 "Face used for special keywords."
3893 :group 'org-faces)
3895 (defface org-drawer ;; font-lock-function-name-face
3896 (org-compatible-face nil
3897 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3898 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3899 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3900 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3901 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3902 (t (:bold t))))
3903 "Face used for drawers."
3904 :group 'org-faces)
3906 (defface org-property-value nil
3907 "Face used for the value of a property."
3908 :group 'org-faces)
3910 (defface org-column
3911 (org-compatible-face nil
3912 '((((class color) (min-colors 16) (background light))
3913 (:background "grey90"))
3914 (((class color) (min-colors 16) (background dark))
3915 (:background "grey30"))
3916 (((class color) (min-colors 8))
3917 (:background "cyan" :foreground "black"))
3918 (t (:inverse-video t))))
3919 "Face for column display of entry properties."
3920 :group 'org-faces)
3922 (when (fboundp 'set-face-attribute)
3923 ;; Make sure that a fixed-width face is used when we have a column table.
3924 (set-face-attribute 'org-column nil
3925 :height (face-attribute 'default :height)
3926 :family (face-attribute 'default :family)))
3928 (defface org-warning
3929 (org-compatible-face 'font-lock-warning-face
3930 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3931 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3932 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3933 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3934 (t (:bold t))))
3935 "Face for deadlines and TODO keywords."
3936 :group 'org-faces)
3938 (defface org-archived ; similar to shadow
3939 (org-compatible-face 'shadow
3940 '((((class color grayscale) (min-colors 88) (background light))
3941 (:foreground "grey50"))
3942 (((class color grayscale) (min-colors 88) (background dark))
3943 (:foreground "grey70"))
3944 (((class color) (min-colors 8) (background light))
3945 (:foreground "green"))
3946 (((class color) (min-colors 8) (background dark))
3947 (:foreground "yellow"))))
3948 "Face for headline with the ARCHIVE tag."
3949 :group 'org-faces)
3951 (defface org-link
3952 '((((class color) (background light)) (:foreground "Purple" :underline t))
3953 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3954 (t (:underline t)))
3955 "Face for links."
3956 :group 'org-faces)
3958 (defface org-ellipsis
3959 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
3960 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
3961 (t (:strike-through t)))
3962 "Face for the ellipsis in folded text."
3963 :group 'org-faces)
3965 (defface org-target
3966 '((((class color) (background light)) (:underline t))
3967 (((class color) (background dark)) (:underline t))
3968 (t (:underline t)))
3969 "Face for links."
3970 :group 'org-faces)
3972 (defface org-date
3973 '((((class color) (background light)) (:foreground "Purple" :underline t))
3974 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3975 (t (:underline t)))
3976 "Face for links."
3977 :group 'org-faces)
3979 (defface org-sexp-date
3980 '((((class color) (background light)) (:foreground "Purple"))
3981 (((class color) (background dark)) (:foreground "Cyan"))
3982 (t (:underline t)))
3983 "Face for links."
3984 :group 'org-faces)
3986 (defface org-tag
3987 '((t (:bold t)))
3988 "Face for tags."
3989 :group 'org-faces)
3991 (defface org-todo ; font-lock-warning-face
3992 (org-compatible-face nil
3993 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3994 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3995 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3996 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3997 (t (:inverse-video t :bold t))))
3998 "Face for TODO keywords."
3999 :group 'org-faces)
4001 (defface org-done ;; font-lock-type-face
4002 (org-compatible-face nil
4003 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
4004 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
4005 (((class color) (min-colors 8)) (:foreground "green"))
4006 (t (:bold t))))
4007 "Face used for todo keywords that indicate DONE items."
4008 :group 'org-faces)
4010 (defface org-headline-done ;; font-lock-string-face
4011 (org-compatible-face nil
4012 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4013 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4014 (((class color) (min-colors 8) (background light)) (:bold nil))))
4015 "Face used to indicate that a headline is DONE.
4016 This face is only used if `org-fontify-done-headline' is set. If applies
4017 to the part of the headline after the DONE keyword."
4018 :group 'org-faces)
4020 (defcustom org-todo-keyword-faces nil
4021 "Faces for specific TODO keywords.
4022 This is a list of cons cells, with TODO keywords in the car
4023 and faces in the cdr. The face can be a symbol, or a property
4024 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
4025 :group 'org-faces
4026 :group 'org-todo
4027 :type '(repeat
4028 (cons
4029 (string :tag "keyword")
4030 (sexp :tag "face"))))
4032 (defface org-table ;; font-lock-function-name-face
4033 (org-compatible-face nil
4034 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4035 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4036 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4037 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4038 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
4039 (((class color) (min-colors 8) (background dark)))))
4040 "Face used for tables."
4041 :group 'org-faces)
4043 (defface org-formula
4044 (org-compatible-face nil
4045 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4046 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4047 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4048 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
4049 (t (:bold t :italic t))))
4050 "Face for formulas."
4051 :group 'org-faces)
4053 (defface org-code
4054 (org-compatible-face nil
4055 '((((class color grayscale) (min-colors 88) (background light))
4056 (:foreground "grey50"))
4057 (((class color grayscale) (min-colors 88) (background dark))
4058 (:foreground "grey70"))
4059 (((class color) (min-colors 8) (background light))
4060 (:foreground "green"))
4061 (((class color) (min-colors 8) (background dark))
4062 (:foreground "yellow"))))
4063 "Face for fixed-with text like code snippets."
4064 :group 'org-faces
4065 :version "22.1")
4067 (defface org-verbatim
4068 (org-compatible-face nil
4069 '((((class color grayscale) (min-colors 88) (background light))
4070 (:foreground "grey50" :underline t))
4071 (((class color grayscale) (min-colors 88) (background dark))
4072 (:foreground "grey70" :underline t))
4073 (((class color) (min-colors 8) (background light))
4074 (:foreground "green" :underline t))
4075 (((class color) (min-colors 8) (background dark))
4076 (:foreground "yellow" :underline t))))
4077 "Face for fixed-with text like code snippets."
4078 :group 'org-faces
4079 :version "22.1")
4081 (defface org-agenda-structure ;; font-lock-function-name-face
4082 (org-compatible-face nil
4083 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4084 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4085 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4086 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4087 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4088 (t (:bold t))))
4089 "Face used in agenda for captions and dates."
4090 :group 'org-faces)
4092 (defface org-scheduled-today
4093 (org-compatible-face nil
4094 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
4095 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
4096 (((class color) (min-colors 8)) (:foreground "green"))
4097 (t (:bold t :italic t))))
4098 "Face for items scheduled for a certain day."
4099 :group 'org-faces)
4101 (defface org-scheduled-previously
4102 (org-compatible-face nil
4103 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4104 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4105 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4106 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4107 (t (:bold t))))
4108 "Face for items scheduled previously, and not yet done."
4109 :group 'org-faces)
4111 (defface org-upcoming-deadline
4112 (org-compatible-face nil
4113 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4114 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4115 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4116 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4117 (t (:bold t))))
4118 "Face for items scheduled previously, and not yet done."
4119 :group 'org-faces)
4121 (defcustom org-agenda-deadline-faces
4122 '((1.0 . org-warning)
4123 (0.5 . org-upcoming-deadline)
4124 (0.0 . default))
4125 "Faces for showing deadlines in the agenda.
4126 This is a list of cons cells. The cdr of each cell is a face to be used,
4127 and it can also just be like '(:foreground \"yellow\").
4128 Each car is a fraction of the head-warning time that must have passed for
4129 this the face in the cdr to be used for display. The numbers must be
4130 given in descending order. The head-warning time is normally taken
4131 from `org-deadline-warning-days', but can also be specified in the deadline
4132 timestamp itself, like this:
4134 DEADLINE: <2007-08-13 Mon -8d>
4136 You may use d for days, w for weeks, m for months and y for years. Months
4137 and years will only be treated in an approximate fashion (30.4 days for a
4138 month and 365.24 days for a year)."
4139 :group 'org-faces
4140 :group 'org-agenda-daily/weekly
4141 :type '(repeat
4142 (cons
4143 (number :tag "Fraction of head-warning time passed")
4144 (sexp :tag "Face"))))
4146 ;; FIXME: this is not a good face yet.
4147 (defface org-agenda-restriction-lock
4148 (org-compatible-face nil
4149 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
4150 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
4151 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
4152 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
4153 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
4154 (t (:inverse-video t))))
4155 "Face for showing the agenda restriction lock."
4156 :group 'org-faces)
4158 (defface org-time-grid ;; font-lock-variable-name-face
4159 (org-compatible-face nil
4160 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4161 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4162 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4163 "Face used for time grids."
4164 :group 'org-faces)
4166 (defconst org-level-faces
4167 '(org-level-1 org-level-2 org-level-3 org-level-4
4168 org-level-5 org-level-6 org-level-7 org-level-8
4171 (defcustom org-n-level-faces (length org-level-faces)
4172 "The number different faces to be used for headlines.
4173 Org-mode defines 8 different headline faces, so this can be at most 8.
4174 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4175 :type 'number
4176 :group 'org-faces)
4178 ;;; Functions and variables from ther packages
4179 ;; Declared here to avoid compiler warnings
4181 (eval-and-compile
4182 (unless (fboundp 'declare-function)
4183 (defmacro declare-function (fn file &optional arglist fileonly))))
4185 ;; XEmacs only
4186 (defvar outline-mode-menu-heading)
4187 (defvar outline-mode-menu-show)
4188 (defvar outline-mode-menu-hide)
4189 (defvar zmacs-regions) ; XEmacs regions
4191 ;; Emacs only
4192 (defvar mark-active)
4194 ;; Various packages
4195 ;; FIXME: get the argument lists for the UNKNOWN stuff
4196 (declare-function add-to-diary-list "diary-lib"
4197 (date string specifier &optional marker globcolor literal))
4198 (defvar appt-time-msg-list)
4199 (declare-function appt-check "appt" (&optional force))
4200 (declare-function table--at-cell-p "table" (position &optional object at-column))
4201 (declare-function Info-find-node "info" (filename nodename &optional no-going-back))
4202 (declare-function Info-goto-node "info" (nodename &optional fork))
4203 (declare-function bbdb "ext:bbdb-com" (string elidep))
4204 (declare-function bbdb-company "ext:bbdb-com" (string elidep))
4205 (declare-function bbdb-current-record "ext:bbdb-com" (&optional planning-on-modifying))
4206 (declare-function bbdb-name "ext:bbdb-com" (string elidep))
4207 (declare-function bbdb-record-getprop "ext:bbdb" (record property))
4208 (declare-function bbdb-record-name "ext:bbdb" (record))
4209 (declare-function bibtex-beginning-of-entry "bibtex" ())
4210 (declare-function bibtex-generate-autokey "bibtex" ())
4211 (declare-function bibtex-parse-entry "bibtex" (&optional content))
4212 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
4213 (defvar calc-embedded-close-formula)
4214 (defvar calc-embedded-open-formula)
4215 (declare-function calendar-astro-date-string "cal-julian" (&optional date))
4216 (declare-function calendar-bahai-date-string "cal-bahai" (&optional date))
4217 (declare-function calendar-check-holidays "holidays" (date))
4218 (declare-function calendar-chinese-date-string "cal-china" (&optional date))
4219 (declare-function calendar-coptic-date-string "cal-coptic" (&optional date))
4220 (declare-function calendar-ethiopic-date-string "cal-coptic" (&optional date))
4221 (declare-function calendar-forward-day "cal-move" (arg))
4222 (declare-function calendar-french-date-string "cal-french" (&optional date))
4223 (declare-function calendar-goto-date "cal-move" (date))
4224 (declare-function calendar-goto-today "cal-move" ())
4225 (declare-function calendar-hebrew-date-string "cal-hebrew" (&optional date))
4226 (declare-function calendar-islamic-date-string "cal-islam" (&optional date))
4227 (declare-function calendar-iso-date-string "cal-iso" (&optional date))
4228 (declare-function calendar-julian-date-string "cal-julian" (&optional date))
4229 (declare-function calendar-mayan-date-string "cal-mayan" (&optional date))
4230 (declare-function calendar-persian-date-string "cal-persia" (&optional date))
4231 (defvar calendar-mode-map)
4232 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4233 (declare-function cdlatex-tab "ext:cdlatex" ())
4234 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4235 (declare-function elmo-folder-exists-p "ext:elmo" (folder) t)
4236 (declare-function elmo-message-entity-field "ext:elmo-msgdb" (entity field &optional type))
4237 (declare-function elmo-message-field "ext:elmo" (folder number field &optional type) t)
4238 (declare-function elmo-msgdb-overview-get-entity "ext:elmo" (&rest unknown) t)
4239 (defvar font-lock-unfontify-region-function)
4240 (declare-function gnus-article-show-summary "gnus-art" ())
4241 (declare-function gnus-summary-last-subject "gnus-sum" ())
4242 (defvar gnus-other-frame-object)
4243 (defvar gnus-group-name)
4244 (defvar gnus-article-current)
4245 (defvar Info-current-file)
4246 (defvar Info-current-node)
4247 (declare-function mh-display-msg "mh-show" (msg-num folder-name))
4248 (declare-function mh-find-path "mh-utils" ())
4249 (declare-function mh-get-header-field "mh-utils" (field))
4250 (declare-function mh-get-msg-num "mh-utils" (error-if-no-message))
4251 (declare-function mh-header-display "mh-show" ())
4252 (declare-function mh-index-previous-folder "mh-search" ())
4253 (declare-function mh-normalize-folder-name "mh-utils" (folder &optional empty-string-okay dont-remove-trailing-slash return-nil-if-folder-empty))
4254 (declare-function mh-search "mh-search" (folder search-regexp &optional redo-search-flag window-config))
4255 (declare-function mh-search-choose "mh-search" (&optional searcher))
4256 (declare-function mh-show "mh-show" (&optional message redisplay-flag))
4257 (declare-function mh-show-buffer-message-number "mh-comp" (&optional buffer))
4258 (declare-function mh-show-header-display "mh-show" t t)
4259 (declare-function mh-show-msg "mh-show" (msg))
4260 (declare-function mh-show-show "mh-show" t t)
4261 (declare-function mh-visit-folder "mh-folder" (folder &optional range index-data))
4262 (defvar mh-progs)
4263 (defvar mh-current-folder)
4264 (defvar mh-show-folder-buffer)
4265 (defvar mh-index-folder)
4266 (defvar mh-searcher)
4267 (declare-function org-export-latex-cleaned-string "org-export-latex" ())
4268 (declare-function parse-time-string "parse-time" (string))
4269 (declare-function remember "remember" (&optional initial))
4270 (declare-function remember-buffer-desc "remember" ())
4271 (declare-function remember-finalize "remember" ())
4272 (defvar remember-save-after-remembering)
4273 (defvar remember-data-file)
4274 (defvar remember-register)
4275 (defvar remember-buffer)
4276 (defvar remember-handler-functions)
4277 (defvar remember-annotation-functions)
4278 (declare-function rmail-narrow-to-non-pruned-header "rmail" ())
4279 (declare-function rmail-show-message "rmail" (&optional n no-summary))
4280 (declare-function rmail-what-message "rmail" ())
4281 (defvar rmail-current-message)
4282 (defvar texmathp-why)
4283 (declare-function vm-beginning-of-message "ext:vm-page" ())
4284 (declare-function vm-follow-summary-cursor "ext:vm-motion" ())
4285 (declare-function vm-get-header-contents "ext:vm-summary" (message header-name-regexp &optional clump-sep))
4286 (declare-function vm-isearch-narrow "ext:vm-search" ())
4287 (declare-function vm-isearch-update "ext:vm-search" ())
4288 (declare-function vm-select-folder-buffer "ext:vm-macro" ())
4289 (declare-function vm-su-message-id "ext:vm-summary" (m))
4290 (declare-function vm-su-subject "ext:vm-summary" (m))
4291 (declare-function vm-summarize "ext:vm-summary" (&optional display raise))
4292 (defvar vm-message-pointer)
4293 (defvar vm-folder-directory)
4294 (defvar w3m-current-url)
4295 (defvar w3m-current-title)
4296 ;; backward compatibility to old version of wl
4297 (declare-function wl-summary-buffer-msgdb "ext:wl-folder" (&rest unknown) t)
4298 (declare-function wl-folder-get-elmo-folder "ext:wl-folder" (entity &optional no-cache))
4299 (declare-function wl-summary-goto-folder-subr "ext:wl-summary" (&optional name scan-type other-window sticky interactive scoring force-exit))
4300 (declare-function wl-summary-jump-to-msg-by-message-id "ext:wl-summary" (&optional id))
4301 (declare-function wl-summary-line-from "ext:wl-summary" ())
4302 (declare-function wl-summary-line-subject "ext:wl-summary" ())
4303 (declare-function wl-summary-message-number "ext:wl-summary" ())
4304 (declare-function wl-summary-redisplay "ext:wl-summary" (&optional arg))
4305 (defvar wl-summary-buffer-elmo-folder)
4306 (defvar wl-summary-buffer-folder-name)
4307 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4309 (defvar org-latex-regexps)
4310 (defvar constants-unit-system)
4312 ;;; Variables for pre-computed regular expressions, all buffer local
4314 (defvar org-drawer-regexp nil
4315 "Matches first line of a hidden block.")
4316 (make-variable-buffer-local 'org-drawer-regexp)
4317 (defvar org-todo-regexp nil
4318 "Matches any of the TODO state keywords.")
4319 (make-variable-buffer-local 'org-todo-regexp)
4320 (defvar org-not-done-regexp nil
4321 "Matches any of the TODO state keywords except the last one.")
4322 (make-variable-buffer-local 'org-not-done-regexp)
4323 (defvar org-todo-line-regexp nil
4324 "Matches a headline and puts TODO state into group 2 if present.")
4325 (make-variable-buffer-local 'org-todo-line-regexp)
4326 (defvar org-complex-heading-regexp nil
4327 "Matches a headline and puts everything into groups:
4328 group 1: the stars
4329 group 2: The todo keyword, maybe
4330 group 3: Priority cookie
4331 group 4: True headline
4332 group 5: Tags")
4333 (make-variable-buffer-local 'org-complex-heading-regexp)
4334 (defvar org-todo-line-tags-regexp nil
4335 "Matches a headline and puts TODO state into group 2 if present.
4336 Also put tags into group 4 if tags are present.")
4337 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4338 (defvar org-nl-done-regexp nil
4339 "Matches newline followed by a headline with the DONE keyword.")
4340 (make-variable-buffer-local 'org-nl-done-regexp)
4341 (defvar org-looking-at-done-regexp nil
4342 "Matches the DONE keyword a point.")
4343 (make-variable-buffer-local 'org-looking-at-done-regexp)
4344 (defvar org-ds-keyword-length 12
4345 "Maximum length of the Deadline and SCHEDULED keywords.")
4346 (make-variable-buffer-local 'org-ds-keyword-length)
4347 (defvar org-deadline-regexp nil
4348 "Matches the DEADLINE keyword.")
4349 (make-variable-buffer-local 'org-deadline-regexp)
4350 (defvar org-deadline-time-regexp nil
4351 "Matches the DEADLINE keyword together with a time stamp.")
4352 (make-variable-buffer-local 'org-deadline-time-regexp)
4353 (defvar org-deadline-line-regexp nil
4354 "Matches the DEADLINE keyword and the rest of the line.")
4355 (make-variable-buffer-local 'org-deadline-line-regexp)
4356 (defvar org-scheduled-regexp nil
4357 "Matches the SCHEDULED keyword.")
4358 (make-variable-buffer-local 'org-scheduled-regexp)
4359 (defvar org-scheduled-time-regexp nil
4360 "Matches the SCHEDULED keyword together with a time stamp.")
4361 (make-variable-buffer-local 'org-scheduled-time-regexp)
4362 (defvar org-closed-time-regexp nil
4363 "Matches the CLOSED keyword together with a time stamp.")
4364 (make-variable-buffer-local 'org-closed-time-regexp)
4366 (defvar org-keyword-time-regexp nil
4367 "Matches any of the 4 keywords, together with the time stamp.")
4368 (make-variable-buffer-local 'org-keyword-time-regexp)
4369 (defvar org-keyword-time-not-clock-regexp nil
4370 "Matches any of the 3 keywords, together with the time stamp.")
4371 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4372 (defvar org-maybe-keyword-time-regexp nil
4373 "Matches a timestamp, possibly preceeded by a keyword.")
4374 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4375 (defvar org-planning-or-clock-line-re nil
4376 "Matches a line with planning or clock info.")
4377 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4379 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4380 rear-nonsticky t mouse-map t fontified t)
4381 "Properties to remove when a string without properties is wanted.")
4383 (defsubst org-match-string-no-properties (num &optional string)
4384 (if (featurep 'xemacs)
4385 (let ((s (match-string num string)))
4386 (remove-text-properties 0 (length s) org-rm-props s)
4388 (match-string-no-properties num string)))
4390 (defsubst org-no-properties (s)
4391 (if (fboundp 'set-text-properties)
4392 (set-text-properties 0 (length s) nil s)
4393 (remove-text-properties 0 (length s) org-rm-props s))
4396 (defsubst org-get-alist-option (option key)
4397 (cond ((eq key t) t)
4398 ((eq option t) t)
4399 ((assoc key option) (cdr (assoc key option)))
4400 (t (cdr (assq 'default option)))))
4402 (defsubst org-inhibit-invisibility ()
4403 "Modified `buffer-invisibility-spec' for Emacs 21.
4404 Some ops with invisible text do not work correctly on Emacs 21. For these
4405 we turn off invisibility temporarily. Use this in a `let' form."
4406 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4408 (defsubst org-set-local (var value)
4409 "Make VAR local in current buffer and set it to VALUE."
4410 (set (make-variable-buffer-local var) value))
4412 (defsubst org-mode-p ()
4413 "Check if the current buffer is in Org-mode."
4414 (eq major-mode 'org-mode))
4416 (defsubst org-last (list)
4417 "Return the last element of LIST."
4418 (car (last list)))
4420 (defun org-let (list &rest body)
4421 (eval (cons 'let (cons list body))))
4422 (put 'org-let 'lisp-indent-function 1)
4424 (defun org-let2 (list1 list2 &rest body)
4425 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4426 (put 'org-let2 'lisp-indent-function 2)
4427 (defconst org-startup-options
4428 '(("fold" org-startup-folded t)
4429 ("overview" org-startup-folded t)
4430 ("nofold" org-startup-folded nil)
4431 ("showall" org-startup-folded nil)
4432 ("content" org-startup-folded content)
4433 ("hidestars" org-hide-leading-stars t)
4434 ("showstars" org-hide-leading-stars nil)
4435 ("odd" org-odd-levels-only t)
4436 ("oddeven" org-odd-levels-only nil)
4437 ("align" org-startup-align-all-tables t)
4438 ("noalign" org-startup-align-all-tables nil)
4439 ("customtime" org-display-custom-times t)
4440 ("logdone" org-log-done time)
4441 ("lognotedone" org-log-done note)
4442 ("nologdone" org-log-done nil)
4443 ("lognoteclock-out" org-log-note-clock-out t)
4444 ("nolognoteclock-out" org-log-note-clock-out nil)
4445 ("logrepeat" org-log-repeat state)
4446 ("lognoterepeat" org-log-repeat note)
4447 ("nologrepeat" org-log-repeat nil)
4448 ("constcgs" constants-unit-system cgs)
4449 ("constSI" constants-unit-system SI))
4450 "Variable associated with STARTUP options for org-mode.
4451 Each element is a list of three items: The startup options as written
4452 in the #+STARTUP line, the corresponding variable, and the value to
4453 set this variable to if the option is found. An optional forth element PUSH
4454 means to push this value onto the list in the variable.")
4456 (defun org-set-regexps-and-options ()
4457 "Precompute regular expressions for current buffer."
4458 (when (org-mode-p)
4459 (org-set-local 'org-todo-kwd-alist nil)
4460 (org-set-local 'org-todo-key-alist nil)
4461 (org-set-local 'org-todo-key-trigger nil)
4462 (org-set-local 'org-todo-keywords-1 nil)
4463 (org-set-local 'org-done-keywords nil)
4464 (org-set-local 'org-todo-heads nil)
4465 (org-set-local 'org-todo-sets nil)
4466 (org-set-local 'org-todo-log-states nil)
4467 (let ((re (org-make-options-regexp
4468 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4469 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4470 "CONSTANTS" "PROPERTY" "DRAWERS")))
4471 (splitre "[ \t]+")
4472 kwds kws0 kwsa key log value cat arch tags const links hw dws
4473 tail sep kws1 prio props drawers)
4474 (save-excursion
4475 (save-restriction
4476 (widen)
4477 (goto-char (point-min))
4478 (while (re-search-forward re nil t)
4479 (setq key (match-string 1) value (org-match-string-no-properties 2))
4480 (cond
4481 ((equal key "CATEGORY")
4482 (if (string-match "[ \t]+$" value)
4483 (setq value (replace-match "" t t value)))
4484 (setq cat value))
4485 ((member key '("SEQ_TODO" "TODO"))
4486 (push (cons 'sequence (org-split-string value splitre)) kwds))
4487 ((equal key "TYP_TODO")
4488 (push (cons 'type (org-split-string value splitre)) kwds))
4489 ((equal key "TAGS")
4490 (setq tags (append tags (org-split-string value splitre))))
4491 ((equal key "COLUMNS")
4492 (org-set-local 'org-columns-default-format value))
4493 ((equal key "LINK")
4494 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4495 (push (cons (match-string 1 value)
4496 (org-trim (match-string 2 value)))
4497 links)))
4498 ((equal key "PRIORITIES")
4499 (setq prio (org-split-string value " +")))
4500 ((equal key "PROPERTY")
4501 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4502 (push (cons (match-string 1 value) (match-string 2 value))
4503 props)))
4504 ((equal key "DRAWERS")
4505 (setq drawers (org-split-string value splitre)))
4506 ((equal key "CONSTANTS")
4507 (setq const (append const (org-split-string value splitre))))
4508 ((equal key "STARTUP")
4509 (let ((opts (org-split-string value splitre))
4510 l var val)
4511 (while (setq l (pop opts))
4512 (when (setq l (assoc l org-startup-options))
4513 (setq var (nth 1 l) val (nth 2 l))
4514 (if (not (nth 3 l))
4515 (set (make-local-variable var) val)
4516 (if (not (listp (symbol-value var)))
4517 (set (make-local-variable var) nil))
4518 (set (make-local-variable var) (symbol-value var))
4519 (add-to-list var val))))))
4520 ((equal key "ARCHIVE")
4521 (string-match " *$" value)
4522 (setq arch (replace-match "" t t value))
4523 (remove-text-properties 0 (length arch)
4524 '(face t fontified t) arch)))
4526 (when cat
4527 (org-set-local 'org-category (intern cat))
4528 (push (cons "CATEGORY" cat) props))
4529 (when prio
4530 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4531 (setq prio (mapcar 'string-to-char prio))
4532 (org-set-local 'org-highest-priority (nth 0 prio))
4533 (org-set-local 'org-lowest-priority (nth 1 prio))
4534 (org-set-local 'org-default-priority (nth 2 prio)))
4535 (and props (org-set-local 'org-local-properties (nreverse props)))
4536 (and drawers (org-set-local 'org-drawers drawers))
4537 (and arch (org-set-local 'org-archive-location arch))
4538 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4539 ;; Process the TODO keywords
4540 (unless kwds
4541 ;; Use the global values as if they had been given locally.
4542 (setq kwds (default-value 'org-todo-keywords))
4543 (if (stringp (car kwds))
4544 (setq kwds (list (cons org-todo-interpretation
4545 (default-value 'org-todo-keywords)))))
4546 (setq kwds (reverse kwds)))
4547 (setq kwds (nreverse kwds))
4548 (let (inter kws kw)
4549 (while (setq kws (pop kwds))
4550 (setq inter (pop kws) sep (member "|" kws)
4551 kws0 (delete "|" (copy-sequence kws))
4552 kwsa nil
4553 kws1 (mapcar
4554 (lambda (x)
4555 ;; 1 2
4556 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4557 (progn
4558 (setq kw (match-string 1 x)
4559 key (and (match-end 2) (match-string 2 x))
4560 log (org-extract-log-state-settings x))
4561 (push (cons kw (and key (string-to-char key))) kwsa)
4562 (and log (push log org-todo-log-states))
4564 (error "Invalid TODO keyword %s" x)))
4565 kws0)
4566 kwsa (if kwsa (append '((:startgroup))
4567 (nreverse kwsa)
4568 '((:endgroup))))
4569 hw (car kws1)
4570 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4571 tail (list inter hw (car dws) (org-last dws)))
4572 (add-to-list 'org-todo-heads hw 'append)
4573 (push kws1 org-todo-sets)
4574 (setq org-done-keywords (append org-done-keywords dws nil))
4575 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4576 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4577 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4578 (setq org-todo-sets (nreverse org-todo-sets)
4579 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4580 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4581 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4582 ;; Process the constants
4583 (when const
4584 (let (e cst)
4585 (while (setq e (pop const))
4586 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4587 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4588 (setq org-table-formula-constants-local cst)))
4590 ;; Process the tags.
4591 (when tags
4592 (let (e tgs)
4593 (while (setq e (pop tags))
4594 (cond
4595 ((equal e "{") (push '(:startgroup) tgs))
4596 ((equal e "}") (push '(:endgroup) tgs))
4597 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4598 (push (cons (match-string 1 e)
4599 (string-to-char (match-string 2 e)))
4600 tgs))
4601 (t (push (list e) tgs))))
4602 (org-set-local 'org-tag-alist nil)
4603 (while (setq e (pop tgs))
4604 (or (and (stringp (car e))
4605 (assoc (car e) org-tag-alist))
4606 (push e org-tag-alist))))))
4608 ;; Compute the regular expressions and other local variables
4609 (if (not org-done-keywords)
4610 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4611 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4612 (length org-scheduled-string)))
4613 org-drawer-regexp
4614 (concat "^[ \t]*:\\("
4615 (mapconcat 'regexp-quote org-drawers "\\|")
4616 "\\):[ \t]*$")
4617 org-not-done-keywords
4618 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4619 org-todo-regexp
4620 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4621 "\\|") "\\)\\>")
4622 org-not-done-regexp
4623 (concat "\\<\\("
4624 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4625 "\\)\\>")
4626 org-todo-line-regexp
4627 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4628 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4629 "\\)\\>\\)?[ \t]*\\(.*\\)")
4630 org-complex-heading-regexp
4631 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4632 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4633 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4634 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4635 org-nl-done-regexp
4636 (concat "\n\\*+[ \t]+"
4637 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4638 "\\)" "\\>")
4639 org-todo-line-tags-regexp
4640 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4641 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4642 (org-re
4643 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4644 org-looking-at-done-regexp
4645 (concat "^" "\\(?:"
4646 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4647 "\\>")
4648 org-deadline-regexp (concat "\\<" org-deadline-string)
4649 org-deadline-time-regexp
4650 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4651 org-deadline-line-regexp
4652 (concat "\\<\\(" org-deadline-string "\\).*")
4653 org-scheduled-regexp
4654 (concat "\\<" org-scheduled-string)
4655 org-scheduled-time-regexp
4656 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4657 org-closed-time-regexp
4658 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4659 org-keyword-time-regexp
4660 (concat "\\<\\(" org-scheduled-string
4661 "\\|" org-deadline-string
4662 "\\|" org-closed-string
4663 "\\|" org-clock-string "\\)"
4664 " *[[<]\\([^]>]+\\)[]>]")
4665 org-keyword-time-not-clock-regexp
4666 (concat "\\<\\(" org-scheduled-string
4667 "\\|" org-deadline-string
4668 "\\|" org-closed-string
4669 "\\)"
4670 " *[[<]\\([^]>]+\\)[]>]")
4671 org-maybe-keyword-time-regexp
4672 (concat "\\(\\<\\(" org-scheduled-string
4673 "\\|" org-deadline-string
4674 "\\|" org-closed-string
4675 "\\|" org-clock-string "\\)\\)?"
4676 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4677 org-planning-or-clock-line-re
4678 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4679 "\\|" org-deadline-string
4680 "\\|" org-closed-string "\\|" org-clock-string
4681 "\\)\\>\\)")
4683 (org-compute-latex-and-specials-regexp)
4684 (org-set-font-lock-defaults)))
4686 (defun org-extract-log-state-settings (x)
4687 "Extract the log state setting from a TODO keyword string.
4688 This will extract info from a string like \"WAIT(w@/!)\"."
4689 (let (kw key log1 log2)
4690 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4691 (setq kw (match-string 1 x)
4692 key (and (match-end 2) (match-string 2 x))
4693 log1 (and (match-end 3) (match-string 3 x))
4694 log2 (and (match-end 4) (match-string 4 x)))
4695 (and (or log1 log2)
4696 (list kw
4697 (and log1 (if (equal log1 "!") 'time 'note))
4698 (and log2 (if (equal log2 "!") 'time 'note)))))))
4700 (defun org-remove-keyword-keys (list)
4701 "Remove a pair of parenthesis at the end of each string in LIST."
4702 (mapcar (lambda (x)
4703 (if (string-match "(.*)$" x)
4704 (substring x 0 (match-beginning 0))
4706 list))
4708 ;; FIXME: this could be done much better, using second characters etc.
4709 (defun org-assign-fast-keys (alist)
4710 "Assign fast keys to a keyword-key alist.
4711 Respect keys that are already there."
4712 (let (new e k c c1 c2 (char ?a))
4713 (while (setq e (pop alist))
4714 (cond
4715 ((equal e '(:startgroup)) (push e new))
4716 ((equal e '(:endgroup)) (push e new))
4718 (setq k (car e) c2 nil)
4719 (if (cdr e)
4720 (setq c (cdr e))
4721 ;; automatically assign a character.
4722 (setq c1 (string-to-char
4723 (downcase (substring
4724 k (if (= (string-to-char k) ?@) 1 0)))))
4725 (if (or (rassoc c1 new) (rassoc c1 alist))
4726 (while (or (rassoc char new) (rassoc char alist))
4727 (setq char (1+ char)))
4728 (setq c2 c1))
4729 (setq c (or c2 char)))
4730 (push (cons k c) new))))
4731 (nreverse new)))
4733 ;;; Some variables ujsed in various places
4735 (defvar org-window-configuration nil
4736 "Used in various places to store a window configuration.")
4737 (defvar org-finish-function nil
4738 "Function to be called when `C-c C-c' is used.
4739 This is for getting out of special buffers like remember.")
4742 ;; FIXME: Occasionally check by commenting these, to make sure
4743 ;; no other functions uses these, forgetting to let-bind them.
4744 (defvar entry)
4745 (defvar state)
4746 (defvar last-state)
4747 (defvar date)
4748 (defvar description)
4750 ;; Defined somewhere in this file, but used before definition.
4751 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4752 (defvar org-agenda-buffer-name)
4753 (defvar org-agenda-undo-list)
4754 (defvar org-agenda-pending-undo-list)
4755 (defvar org-agenda-overriding-header)
4756 (defvar orgtbl-mode)
4757 (defvar org-html-entities)
4758 (defvar org-struct-menu)
4759 (defvar org-org-menu)
4760 (defvar org-tbl-menu)
4761 (defvar org-agenda-keymap)
4763 ;;;; Emacs/XEmacs compatibility
4765 ;; Overlay compatibility functions
4766 (defun org-make-overlay (beg end &optional buffer)
4767 (if (featurep 'xemacs)
4768 (make-extent beg end buffer)
4769 (make-overlay beg end buffer)))
4770 (defun org-delete-overlay (ovl)
4771 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4772 (defun org-detach-overlay (ovl)
4773 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4774 (defun org-move-overlay (ovl beg end &optional buffer)
4775 (if (featurep 'xemacs)
4776 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4777 (move-overlay ovl beg end buffer)))
4778 (defun org-overlay-put (ovl prop value)
4779 (if (featurep 'xemacs)
4780 (set-extent-property ovl prop value)
4781 (overlay-put ovl prop value)))
4782 (defun org-overlay-display (ovl text &optional face evap)
4783 "Make overlay OVL display TEXT with face FACE."
4784 (if (featurep 'xemacs)
4785 (let ((gl (make-glyph text)))
4786 (and face (set-glyph-face gl face))
4787 (set-extent-property ovl 'invisible t)
4788 (set-extent-property ovl 'end-glyph gl))
4789 (overlay-put ovl 'display text)
4790 (if face (overlay-put ovl 'face face))
4791 (if evap (overlay-put ovl 'evaporate t))))
4792 (defun org-overlay-before-string (ovl text &optional face evap)
4793 "Make overlay OVL display TEXT with face FACE."
4794 (if (featurep 'xemacs)
4795 (let ((gl (make-glyph text)))
4796 (and face (set-glyph-face gl face))
4797 (set-extent-property ovl 'begin-glyph gl))
4798 (if face (org-add-props text nil 'face face))
4799 (overlay-put ovl 'before-string text)
4800 (if evap (overlay-put ovl 'evaporate t))))
4801 (defun org-overlay-get (ovl prop)
4802 (if (featurep 'xemacs)
4803 (extent-property ovl prop)
4804 (overlay-get ovl prop)))
4805 (defun org-overlays-at (pos)
4806 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4807 (defun org-overlays-in (&optional start end)
4808 (if (featurep 'xemacs)
4809 (extent-list nil start end)
4810 (overlays-in start end)))
4811 (defun org-overlay-start (o)
4812 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4813 (defun org-overlay-end (o)
4814 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4815 (defun org-find-overlays (prop &optional pos delete)
4816 "Find all overlays specifying PROP at POS or point.
4817 If DELETE is non-nil, delete all those overlays."
4818 (let ((overlays (org-overlays-at (or pos (point))))
4819 ov found)
4820 (while (setq ov (pop overlays))
4821 (if (org-overlay-get ov prop)
4822 (if delete (org-delete-overlay ov) (push ov found))))
4823 found))
4825 ;; Region compatibility
4827 (defun org-add-hook (hook function &optional append local)
4828 "Add-hook, compatible with both Emacsen."
4829 (if (and local (featurep 'xemacs))
4830 (add-local-hook hook function append)
4831 (add-hook hook function append local)))
4833 (defvar org-ignore-region nil
4834 "To temporarily disable the active region.")
4836 (defun org-region-active-p ()
4837 "Is `transient-mark-mode' on and the region active?
4838 Works on both Emacs and XEmacs."
4839 (if org-ignore-region
4841 (if (featurep 'xemacs)
4842 (and zmacs-regions (region-active-p))
4843 (if (fboundp 'use-region-p)
4844 (use-region-p)
4845 (and transient-mark-mode mark-active))))) ; Emacs 22 and before
4847 ;; Invisibility compatibility
4849 (defun org-add-to-invisibility-spec (arg)
4850 "Add elements to `buffer-invisibility-spec'.
4851 See documentation for `buffer-invisibility-spec' for the kind of elements
4852 that can be added."
4853 (cond
4854 ((fboundp 'add-to-invisibility-spec)
4855 (add-to-invisibility-spec arg))
4856 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4857 (setq buffer-invisibility-spec (list arg)))
4859 (setq buffer-invisibility-spec
4860 (cons arg buffer-invisibility-spec)))))
4862 (defun org-remove-from-invisibility-spec (arg)
4863 "Remove elements from `buffer-invisibility-spec'."
4864 (if (fboundp 'remove-from-invisibility-spec)
4865 (remove-from-invisibility-spec arg)
4866 (if (consp buffer-invisibility-spec)
4867 (setq buffer-invisibility-spec
4868 (delete arg buffer-invisibility-spec)))))
4870 (defun org-in-invisibility-spec-p (arg)
4871 "Is ARG a member of `buffer-invisibility-spec'?"
4872 (if (consp buffer-invisibility-spec)
4873 (member arg buffer-invisibility-spec)
4874 nil))
4876 ;;;; Define the Org-mode
4878 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4879 (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."))
4882 ;; We use a before-change function to check if a table might need
4883 ;; an update.
4884 (defvar org-table-may-need-update t
4885 "Indicates that a table might need an update.
4886 This variable is set by `org-before-change-function'.
4887 `org-table-align' sets it back to nil.")
4888 (defvar org-mode-map)
4889 (defvar org-mode-hook nil)
4890 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4891 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4892 (defvar org-table-buffer-is-an nil)
4893 (defconst org-outline-regexp "\\*+ ")
4895 ;;;###autoload
4896 (define-derived-mode org-mode outline-mode "Org"
4897 "Outline-based notes management and organizer, alias
4898 \"Carsten's outline-mode for keeping track of everything.\"
4900 Org-mode develops organizational tasks around a NOTES file which
4901 contains information about projects as plain text. Org-mode is
4902 implemented on top of outline-mode, which is ideal to keep the content
4903 of large files well structured. It supports ToDo items, deadlines and
4904 time stamps, which magically appear in the diary listing of the Emacs
4905 calendar. Tables are easily created with a built-in table editor.
4906 Plain text URL-like links connect to websites, emails (VM), Usenet
4907 messages (Gnus), BBDB entries, and any files related to the project.
4908 For printing and sharing of notes, an Org-mode file (or a part of it)
4909 can be exported as a structured ASCII or HTML file.
4911 The following commands are available:
4913 \\{org-mode-map}"
4915 ;; Get rid of Outline menus, they are not needed
4916 ;; Need to do this here because define-derived-mode sets up
4917 ;; the keymap so late. Still, it is a waste to call this each time
4918 ;; we switch another buffer into org-mode.
4919 (if (featurep 'xemacs)
4920 (when (boundp 'outline-mode-menu-heading)
4921 ;; Assume this is Greg's port, it used easymenu
4922 (easy-menu-remove outline-mode-menu-heading)
4923 (easy-menu-remove outline-mode-menu-show)
4924 (easy-menu-remove outline-mode-menu-hide))
4925 (define-key org-mode-map [menu-bar headings] 'undefined)
4926 (define-key org-mode-map [menu-bar hide] 'undefined)
4927 (define-key org-mode-map [menu-bar show] 'undefined))
4929 (easy-menu-add org-org-menu)
4930 (easy-menu-add org-tbl-menu)
4931 (org-install-agenda-files-menu)
4932 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4933 (org-add-to-invisibility-spec '(org-cwidth))
4934 (when (featurep 'xemacs)
4935 (org-set-local 'line-move-ignore-invisible t))
4936 (org-set-local 'outline-regexp org-outline-regexp)
4937 (org-set-local 'outline-level 'org-outline-level)
4938 (when (and org-ellipsis
4939 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4940 (fboundp 'make-glyph-code))
4941 (unless org-display-table
4942 (setq org-display-table (make-display-table)))
4943 (set-display-table-slot
4944 org-display-table 4
4945 (vconcat (mapcar
4946 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4947 org-ellipsis)))
4948 (if (stringp org-ellipsis) org-ellipsis "..."))))
4949 (setq buffer-display-table org-display-table))
4950 (org-set-regexps-and-options)
4951 ;; Calc embedded
4952 (org-set-local 'calc-embedded-open-mode "# ")
4953 (modify-syntax-entry ?# "<")
4954 (modify-syntax-entry ?@ "w")
4955 (if org-startup-truncated (setq truncate-lines t))
4956 (org-set-local 'font-lock-unfontify-region-function
4957 'org-unfontify-region)
4958 ;; Activate before-change-function
4959 (org-set-local 'org-table-may-need-update t)
4960 (org-add-hook 'before-change-functions 'org-before-change-function nil
4961 'local)
4962 ;; Check for running clock before killing a buffer
4963 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4964 ;; Paragraphs and auto-filling
4965 (org-set-autofill-regexps)
4966 (setq indent-line-function 'org-indent-line-function)
4967 (org-update-radio-target-regexp)
4969 ;; Comment characters
4970 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4971 (org-set-local 'comment-padding " ")
4973 ;; Align options lines
4974 (org-set-local
4975 'align-mode-rules-list
4976 '((org-in-buffer-settings
4977 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4978 (modes . '(org-mode)))))
4980 ;; Imenu
4981 (org-set-local 'imenu-create-index-function
4982 'org-imenu-get-tree)
4984 ;; Make isearch reveal context
4985 (if (or (featurep 'xemacs)
4986 (not (boundp 'outline-isearch-open-invisible-function)))
4987 ;; Emacs 21 and XEmacs make use of the hook
4988 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4989 ;; Emacs 22 deals with this through a special variable
4990 (org-set-local 'outline-isearch-open-invisible-function
4991 (lambda (&rest ignore) (org-show-context 'isearch))))
4993 ;; If empty file that did not turn on org-mode automatically, make it to.
4994 (if (and org-insert-mode-line-in-empty-file
4995 (interactive-p)
4996 (= (point-min) (point-max)))
4997 (insert "# -*- mode: org -*-\n\n"))
4999 (unless org-inhibit-startup
5000 (when org-startup-align-all-tables
5001 (let ((bmp (buffer-modified-p)))
5002 (org-table-map-tables 'org-table-align)
5003 (set-buffer-modified-p bmp)))
5004 (org-cycle-hide-drawers 'all)
5005 (cond
5006 ((eq org-startup-folded t)
5007 (org-cycle '(4)))
5008 ((eq org-startup-folded 'content)
5009 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5010 (org-cycle '(4)) (org-cycle '(4)))))))
5012 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5014 (defsubst org-call-with-arg (command arg)
5015 "Call COMMAND interactively, but pretend prefix are was ARG."
5016 (let ((current-prefix-arg arg)) (call-interactively command)))
5018 (defsubst org-current-line (&optional pos)
5019 (save-excursion
5020 (and pos (goto-char pos))
5021 ;; works also in narrowed buffer, because we start at 1, not point-min
5022 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
5024 (defun org-current-time ()
5025 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5026 (if (> org-time-stamp-rounding-minutes 0)
5027 (let ((r org-time-stamp-rounding-minutes)
5028 (time (decode-time)))
5029 (apply 'encode-time
5030 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5031 (nthcdr 2 time))))
5032 (current-time)))
5034 (defun org-add-props (string plist &rest props)
5035 "Add text properties to entire string, from beginning to end.
5036 PLIST may be a list of properties, PROPS are individual properties and values
5037 that will be added to PLIST. Returns the string that was modified."
5038 (add-text-properties
5039 0 (length string) (if props (append plist props) plist) string)
5040 string)
5041 (put 'org-add-props 'lisp-indent-function 2)
5044 ;;;; Font-Lock stuff, including the activators
5046 (defvar org-mouse-map (make-sparse-keymap))
5047 (org-defkey org-mouse-map
5048 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
5049 (org-defkey org-mouse-map
5050 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
5051 (when org-mouse-1-follows-link
5052 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5053 (when org-tab-follows-link
5054 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5055 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5056 (when org-return-follows-link
5057 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
5058 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
5060 (require 'font-lock)
5062 (defconst org-non-link-chars "]\t\n\r<>")
5063 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
5064 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp" "message"))
5065 (defvar org-link-re-with-space nil
5066 "Matches a link with spaces, optional angular brackets around it.")
5067 (defvar org-link-re-with-space2 nil
5068 "Matches a link with spaces, optional angular brackets around it.")
5069 (defvar org-angle-link-re nil
5070 "Matches link with angular brackets, spaces are allowed.")
5071 (defvar org-plain-link-re nil
5072 "Matches plain link, without spaces.")
5073 (defvar org-bracket-link-regexp nil
5074 "Matches a link in double brackets.")
5075 (defvar org-bracket-link-analytic-regexp nil
5076 "Regular expression used to analyze links.
5077 Here is what the match groups contain after a match:
5078 1: http:
5079 2: http
5080 3: path
5081 4: [desc]
5082 5: desc")
5083 (defvar org-any-link-re nil
5084 "Regular expression matching any link.")
5086 (defun org-make-link-regexps ()
5087 "Update the link regular expressions.
5088 This should be called after the variable `org-link-types' has changed."
5089 (setq org-link-re-with-space
5090 (concat
5091 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5092 "\\([^" org-non-link-chars " ]"
5093 "[^" org-non-link-chars "]*"
5094 "[^" org-non-link-chars " ]\\)>?")
5095 org-link-re-with-space2
5096 (concat
5097 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5098 "\\([^" org-non-link-chars " ]"
5099 "[^]\t\n\r]*"
5100 "[^" org-non-link-chars " ]\\)>?")
5101 org-angle-link-re
5102 (concat
5103 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5104 "\\([^" org-non-link-chars " ]"
5105 "[^" org-non-link-chars "]*"
5106 "\\)>")
5107 org-plain-link-re
5108 (concat
5109 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5110 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5111 org-bracket-link-regexp
5112 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5113 org-bracket-link-analytic-regexp
5114 (concat
5115 "\\[\\["
5116 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
5117 "\\([^]]+\\)"
5118 "\\]"
5119 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5120 "\\]")
5121 org-any-link-re
5122 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5123 org-angle-link-re "\\)\\|\\("
5124 org-plain-link-re "\\)")))
5126 (org-make-link-regexps)
5128 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5129 "Regular expression for fast time stamp matching.")
5130 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
5131 "Regular expression for fast time stamp matching.")
5132 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5133 "Regular expression matching time strings for analysis.
5134 This one does not require the space after the date.")
5135 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5136 "Regular expression matching time strings for analysis.")
5137 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5138 "Regular expression matching time stamps, with groups.")
5139 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5140 "Regular expression matching time stamps (also [..]), with groups.")
5141 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5142 "Regular expression matching a time stamp range.")
5143 (defconst org-tr-regexp-both
5144 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5145 "Regular expression matching a time stamp range.")
5146 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5147 org-ts-regexp "\\)?")
5148 "Regular expression matching a time stamp or time stamp range.")
5149 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5150 org-ts-regexp-both "\\)?")
5151 "Regular expression matching a time stamp or time stamp range.
5152 The time stamps may be either active or inactive.")
5154 (defvar org-emph-face nil)
5156 (defun org-do-emphasis-faces (limit)
5157 "Run through the buffer and add overlays to links."
5158 (let (rtn)
5159 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5160 (if (not (= (char-after (match-beginning 3))
5161 (char-after (match-beginning 4))))
5162 (progn
5163 (setq rtn t)
5164 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5165 'face
5166 (nth 1 (assoc (match-string 3)
5167 org-emphasis-alist)))
5168 (add-text-properties (match-beginning 2) (match-end 2)
5169 '(font-lock-multiline t))
5170 (when org-hide-emphasis-markers
5171 (add-text-properties (match-end 4) (match-beginning 5)
5172 '(invisible org-link))
5173 (add-text-properties (match-beginning 3) (match-end 3)
5174 '(invisible org-link)))))
5175 (backward-char 1))
5176 rtn))
5178 (defun org-emphasize (&optional char)
5179 "Insert or change an emphasis, i.e. a font like bold or italic.
5180 If there is an active region, change that region to a new emphasis.
5181 If there is no region, just insert the marker characters and position
5182 the cursor between them.
5183 CHAR should be either the marker character, or the first character of the
5184 HTML tag associated with that emphasis. If CHAR is a space, the means
5185 to remove the emphasis of the selected region.
5186 If char is not given (for example in an interactive call) it
5187 will be prompted for."
5188 (interactive)
5189 (let ((eal org-emphasis-alist) e det
5190 (erc org-emphasis-regexp-components)
5191 (prompt "")
5192 (string "") beg end move tag c s)
5193 (if (org-region-active-p)
5194 (setq beg (region-beginning) end (region-end)
5195 string (buffer-substring beg end))
5196 (setq move t))
5198 (while (setq e (pop eal))
5199 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5200 c (aref tag 0))
5201 (push (cons c (string-to-char (car e))) det)
5202 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5203 (substring tag 1)))))
5204 (unless char
5205 (message "%s" (concat "Emphasis marker or tag:" prompt))
5206 (setq char (read-char-exclusive)))
5207 (setq char (or (cdr (assoc char det)) char))
5208 (if (equal char ?\ )
5209 (setq s "" move nil)
5210 (unless (assoc (char-to-string char) org-emphasis-alist)
5211 (error "No such emphasis marker: \"%c\"" char))
5212 (setq s (char-to-string char)))
5213 (while (and (> (length string) 1)
5214 (equal (substring string 0 1) (substring string -1))
5215 (assoc (substring string 0 1) org-emphasis-alist))
5216 (setq string (substring string 1 -1)))
5217 (setq string (concat s string s))
5218 (if beg (delete-region beg end))
5219 (unless (or (bolp)
5220 (string-match (concat "[" (nth 0 erc) "\n]")
5221 (char-to-string (char-before (point)))))
5222 (insert " "))
5223 (unless (string-match (concat "[" (nth 1 erc) "\n]")
5224 (char-to-string (char-after (point))))
5225 (insert " ") (backward-char 1))
5226 (insert string)
5227 (and move (backward-char 1))))
5229 (defconst org-nonsticky-props
5230 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5233 (defun org-activate-plain-links (limit)
5234 "Run through the buffer and add overlays to links."
5235 (catch 'exit
5236 (let (f)
5237 (while (re-search-forward org-plain-link-re limit t)
5238 (setq f (get-text-property (match-beginning 0) 'face))
5239 (if (or (eq f 'org-tag)
5240 (and (listp f) (memq 'org-tag f)))
5242 (add-text-properties (match-beginning 0) (match-end 0)
5243 (list 'mouse-face 'highlight
5244 'rear-nonsticky org-nonsticky-props
5245 'keymap org-mouse-map
5247 (throw 'exit t))))))
5249 (defun org-activate-code (limit)
5250 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
5251 (unless (get-text-property (match-beginning 1) 'face)
5252 (remove-text-properties (match-beginning 0) (match-end 0)
5253 '(display t invisible t intangible t))
5254 t)))
5256 (defun org-activate-angle-links (limit)
5257 "Run through the buffer and add overlays to links."
5258 (if (re-search-forward org-angle-link-re limit t)
5259 (progn
5260 (add-text-properties (match-beginning 0) (match-end 0)
5261 (list 'mouse-face 'highlight
5262 'rear-nonsticky org-nonsticky-props
5263 'keymap org-mouse-map
5265 t)))
5267 (defmacro org-maybe-intangible (props)
5268 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
5269 In emacs 21, invisible text is not avoided by the command loop, so the
5270 intangible property is needed to make sure point skips this text.
5271 In Emacs 22, this is not necessary. The intangible text property has
5272 led to problems with flyspell. These problems are fixed in flyspell.el,
5273 but we still avoid setting the property in Emacs 22 and later.
5274 We use a macro so that the test can happen at compilation time."
5275 (if (< emacs-major-version 22)
5276 `(append '(intangible t) ,props)
5277 props))
5279 (defun org-activate-bracket-links (limit)
5280 "Run through the buffer and add overlays to bracketed links."
5281 (if (re-search-forward org-bracket-link-regexp limit t)
5282 (let* ((help (concat "LINK: "
5283 (org-match-string-no-properties 1)))
5284 ;; FIXME: above we should remove the escapes.
5285 ;; but that requires another match, protecting match data,
5286 ;; a lot of overhead for font-lock.
5287 (ip (org-maybe-intangible
5288 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5289 'keymap org-mouse-map 'mouse-face 'highlight
5290 'font-lock-multiline t 'help-echo help)))
5291 (vp (list 'rear-nonsticky org-nonsticky-props
5292 'keymap org-mouse-map 'mouse-face 'highlight
5293 ' font-lock-multiline t 'help-echo help)))
5294 ;; We need to remove the invisible property here. Table narrowing
5295 ;; may have made some of this invisible.
5296 (remove-text-properties (match-beginning 0) (match-end 0)
5297 '(invisible nil))
5298 (if (match-end 3)
5299 (progn
5300 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5301 (add-text-properties (match-beginning 3) (match-end 3) vp)
5302 (add-text-properties (match-end 3) (match-end 0) ip))
5303 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5304 (add-text-properties (match-beginning 1) (match-end 1) vp)
5305 (add-text-properties (match-end 1) (match-end 0) ip))
5306 t)))
5308 (defun org-activate-dates (limit)
5309 "Run through the buffer and add overlays to dates."
5310 (if (re-search-forward org-tsr-regexp-both limit t)
5311 (progn
5312 (add-text-properties (match-beginning 0) (match-end 0)
5313 (list 'mouse-face 'highlight
5314 'rear-nonsticky org-nonsticky-props
5315 'keymap org-mouse-map))
5316 (when org-display-custom-times
5317 (if (match-end 3)
5318 (org-display-custom-time (match-beginning 3) (match-end 3)))
5319 (org-display-custom-time (match-beginning 1) (match-end 1)))
5320 t)))
5322 (defvar org-target-link-regexp nil
5323 "Regular expression matching radio targets in plain text.")
5324 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5325 "Regular expression matching a link target.")
5326 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5327 "Regular expression matching a radio target.")
5328 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5329 "Regular expression matching any target.")
5331 (defun org-activate-target-links (limit)
5332 "Run through the buffer and add overlays to target matches."
5333 (when org-target-link-regexp
5334 (let ((case-fold-search t))
5335 (if (re-search-forward org-target-link-regexp limit t)
5336 (progn
5337 (add-text-properties (match-beginning 0) (match-end 0)
5338 (list 'mouse-face 'highlight
5339 'rear-nonsticky org-nonsticky-props
5340 'keymap org-mouse-map
5341 'help-echo "Radio target link"
5342 'org-linked-text t))
5343 t)))))
5345 (defun org-update-radio-target-regexp ()
5346 "Find all radio targets in this file and update the regular expression."
5347 (interactive)
5348 (when (memq 'radio org-activate-links)
5349 (setq org-target-link-regexp
5350 (org-make-target-link-regexp (org-all-targets 'radio)))
5351 (org-restart-font-lock)))
5353 (defun org-hide-wide-columns (limit)
5354 (let (s e)
5355 (setq s (text-property-any (point) (or limit (point-max))
5356 'org-cwidth t))
5357 (when s
5358 (setq e (next-single-property-change s 'org-cwidth))
5359 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5360 (goto-char e)
5361 t)))
5363 (defvar org-latex-and-specials-regexp nil
5364 "Regular expression for highlighting export special stuff.")
5365 (defvar org-match-substring-regexp)
5366 (defvar org-match-substring-with-braces-regexp)
5367 (defvar org-export-html-special-string-regexps)
5369 (defun org-compute-latex-and-specials-regexp ()
5370 "Compute regular expression for stuff treated specially by exporters."
5371 (if (not org-highlight-latex-fragments-and-specials)
5372 (org-set-local 'org-latex-and-specials-regexp nil)
5373 (let*
5374 ((matchers (plist-get org-format-latex-options :matchers))
5375 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5376 org-latex-regexps)))
5377 (options (org-combine-plists (org-default-export-plist)
5378 (org-infile-export-plist)))
5379 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5380 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5381 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5382 (org-export-html-expand (plist-get options :expand-quoted-html))
5383 (org-export-with-special-strings (plist-get options :special-strings))
5384 (re-sub
5385 (cond
5386 ((equal org-export-with-sub-superscripts '{})
5387 (list org-match-substring-with-braces-regexp))
5388 (org-export-with-sub-superscripts
5389 (list org-match-substring-regexp))
5390 (t nil)))
5391 (re-latex
5392 (if org-export-with-LaTeX-fragments
5393 (mapcar (lambda (x) (nth 1 x)) latexs)))
5394 (re-macros
5395 (if org-export-with-TeX-macros
5396 (list (concat "\\\\"
5397 (regexp-opt
5398 (append (mapcar 'car org-html-entities)
5399 (if (boundp 'org-latex-entities)
5400 org-latex-entities nil))
5401 'words))) ; FIXME
5403 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5404 (re-special (if org-export-with-special-strings
5405 (mapcar (lambda (x) (car x))
5406 org-export-html-special-string-regexps)))
5407 (re-rest
5408 (delq nil
5409 (list
5410 (if org-export-html-expand "@<[^>\n]+>")
5411 ))))
5412 (org-set-local
5413 'org-latex-and-specials-regexp
5414 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5415 re-rest) "\\|")))))
5417 (defface org-latex-and-export-specials
5418 (let ((font (cond ((assq :inherit custom-face-attributes)
5419 '(:inherit underline))
5420 (t '(:underline t)))))
5421 `((((class grayscale) (background light))
5422 (:foreground "DimGray" ,@font))
5423 (((class grayscale) (background dark))
5424 (:foreground "LightGray" ,@font))
5425 (((class color) (background light))
5426 (:foreground "SaddleBrown"))
5427 (((class color) (background dark))
5428 (:foreground "burlywood"))
5429 (t (,@font))))
5430 "Face used to highlight math latex and other special exporter stuff."
5431 :group 'org-faces)
5433 (defun org-do-latex-and-special-faces (limit)
5434 "Run through the buffer and add overlays to links."
5435 (when org-latex-and-specials-regexp
5436 (let (rtn d)
5437 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5438 limit t))
5439 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5440 'face))
5441 '(org-code org-verbatim underline)))
5442 (progn
5443 (setq rtn t
5444 d (cond ((member (char-after (1+ (match-beginning 0)))
5445 '(?_ ?^)) 1)
5446 (t 0)))
5447 (font-lock-prepend-text-property
5448 (+ d (match-beginning 0)) (match-end 0)
5449 'face 'org-latex-and-export-specials)
5450 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5451 '(font-lock-multiline t)))))
5452 rtn)))
5454 (defun org-restart-font-lock ()
5455 "Restart font-lock-mode, to force refontification."
5456 (when (and (boundp 'font-lock-mode) font-lock-mode)
5457 (font-lock-mode -1)
5458 (font-lock-mode 1)))
5460 (defun org-all-targets (&optional radio)
5461 "Return a list of all targets in this file.
5462 With optional argument RADIO, only find radio targets."
5463 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5464 rtn)
5465 (save-excursion
5466 (goto-char (point-min))
5467 (while (re-search-forward re nil t)
5468 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5469 rtn)))
5471 (defun org-make-target-link-regexp (targets)
5472 "Make regular expression matching all strings in TARGETS.
5473 The regular expression finds the targets also if there is a line break
5474 between words."
5475 (and targets
5476 (concat
5477 "\\<\\("
5478 (mapconcat
5479 (lambda (x)
5480 (while (string-match " +" x)
5481 (setq x (replace-match "\\s-+" t t x)))
5483 targets
5484 "\\|")
5485 "\\)\\>")))
5487 (defun org-activate-tags (limit)
5488 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5489 (progn
5490 (add-text-properties (match-beginning 1) (match-end 1)
5491 (list 'mouse-face 'highlight
5492 'rear-nonsticky org-nonsticky-props
5493 'keymap org-mouse-map))
5494 t)))
5496 (defun org-outline-level ()
5497 (save-excursion
5498 (looking-at outline-regexp)
5499 (if (match-beginning 1)
5500 (+ (org-get-string-indentation (match-string 1)) 1000)
5501 (1- (- (match-end 0) (match-beginning 0))))))
5503 (defvar org-font-lock-keywords nil)
5505 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5506 "Regular expression matching a property line.")
5508 (defun org-set-font-lock-defaults ()
5509 (let* ((em org-fontify-emphasized-text)
5510 (lk org-activate-links)
5511 (org-font-lock-extra-keywords
5512 (list
5513 ;; Headlines
5514 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5515 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5516 ;; Table lines
5517 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5518 (1 'org-table t))
5519 ;; Table internals
5520 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5521 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5522 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5523 ;; Drawers
5524 (list org-drawer-regexp '(0 'org-special-keyword t))
5525 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5526 ;; Properties
5527 (list org-property-re
5528 '(1 'org-special-keyword t)
5529 '(3 'org-property-value t))
5530 (if org-format-transports-properties-p
5531 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5532 ;; Links
5533 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5534 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5535 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5536 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5537 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5538 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5539 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5540 '(org-hide-wide-columns (0 nil append))
5541 ;; TODO lines
5542 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5543 '(1 (org-get-todo-face 1) t))
5544 ;; DONE
5545 (if org-fontify-done-headline
5546 (list (concat "^[*]+ +\\<\\("
5547 (mapconcat 'regexp-quote org-done-keywords "\\|")
5548 "\\)\\(.*\\)")
5549 '(2 'org-headline-done t))
5550 nil)
5551 ;; Priorities
5552 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5553 ;; Special keywords
5554 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5555 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5556 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5557 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5558 ;; Emphasis
5559 (if em
5560 (if (featurep 'xemacs)
5561 '(org-do-emphasis-faces (0 nil append))
5562 '(org-do-emphasis-faces)))
5563 ;; Checkboxes
5564 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5565 2 'bold prepend)
5566 (if org-provide-checkbox-statistics
5567 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5568 (0 (org-get-checkbox-statistics-face) t)))
5569 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5570 '(1 'org-archived prepend))
5571 ;; Specials
5572 '(org-do-latex-and-special-faces)
5573 ;; Code
5574 '(org-activate-code (1 'org-code t))
5575 ;; COMMENT
5576 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5577 "\\|" org-quote-string "\\)\\>")
5578 '(1 'org-special-keyword t))
5579 '("^#.*" (0 'font-lock-comment-face t))
5581 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5582 ;; Now set the full font-lock-keywords
5583 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5584 (org-set-local 'font-lock-defaults
5585 '(org-font-lock-keywords t nil nil backward-paragraph))
5586 (kill-local-variable 'font-lock-keywords) nil))
5588 (defvar org-m nil)
5589 (defvar org-l nil)
5590 (defvar org-f nil)
5591 (defun org-get-level-face (n)
5592 "Get the right face for match N in font-lock matching of healdines."
5593 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5594 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5595 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5596 (cond
5597 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5598 ((eq n 2) org-f)
5599 (t (if org-level-color-stars-only nil org-f))))
5601 (defun org-get-todo-face (kwd)
5602 "Get the right face for a TODO keyword KWD.
5603 If KWD is a number, get the corresponding match group."
5604 (if (numberp kwd) (setq kwd (match-string kwd)))
5605 (or (cdr (assoc kwd org-todo-keyword-faces))
5606 (and (member kwd org-done-keywords) 'org-done)
5607 'org-todo))
5609 (defun org-unfontify-region (beg end &optional maybe_loudly)
5610 "Remove fontification and activation overlays from links."
5611 (font-lock-default-unfontify-region beg end)
5612 (let* ((buffer-undo-list t)
5613 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5614 (inhibit-modification-hooks t)
5615 deactivate-mark buffer-file-name buffer-file-truename)
5616 (remove-text-properties beg end
5617 '(mouse-face t keymap t org-linked-text t
5618 invisible t intangible t))))
5620 ;;;; Visibility cycling, including org-goto and indirect buffer
5622 ;;; Cycling
5624 (defvar org-cycle-global-status nil)
5625 (make-variable-buffer-local 'org-cycle-global-status)
5626 (defvar org-cycle-subtree-status nil)
5627 (make-variable-buffer-local 'org-cycle-subtree-status)
5629 ;;;###autoload
5630 (defun org-cycle (&optional arg)
5631 "Visibility cycling for Org-mode.
5633 - When this function is called with a prefix argument, rotate the entire
5634 buffer through 3 states (global cycling)
5635 1. OVERVIEW: Show only top-level headlines.
5636 2. CONTENTS: Show all headlines of all levels, but no body text.
5637 3. SHOW ALL: Show everything.
5639 - When point is at the beginning of a headline, rotate the subtree started
5640 by this line through 3 different states (local cycling)
5641 1. FOLDED: Only the main headline is shown.
5642 2. CHILDREN: The main headline and the direct children are shown.
5643 From this state, you can move to one of the children
5644 and zoom in further.
5645 3. SUBTREE: Show the entire subtree, including body text.
5647 - When there is a numeric prefix, go up to a heading with level ARG, do
5648 a `show-subtree' and return to the previous cursor position. If ARG
5649 is negative, go up that many levels.
5651 - When point is not at the beginning of a headline, execute
5652 `indent-relative', like TAB normally does. See the option
5653 `org-cycle-emulate-tab' for details.
5655 - Special case: if point is at the beginning of the buffer and there is
5656 no headline in line 1, this function will act as if called with prefix arg.
5657 But only if also the variable `org-cycle-global-at-bob' is t."
5658 (interactive "P")
5659 (let* ((outline-regexp
5660 (if (and (org-mode-p) org-cycle-include-plain-lists)
5661 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5662 outline-regexp))
5663 (bob-special (and org-cycle-global-at-bob (bobp)
5664 (not (looking-at outline-regexp))))
5665 (org-cycle-hook
5666 (if bob-special
5667 (delq 'org-optimize-window-after-visibility-change
5668 (copy-sequence org-cycle-hook))
5669 org-cycle-hook))
5670 (pos (point)))
5672 (if (or bob-special (equal arg '(4)))
5673 ;; special case: use global cycling
5674 (setq arg t))
5676 (cond
5678 ((org-at-table-p 'any)
5679 ;; Enter the table or move to the next field in the table
5680 (or (org-table-recognize-table.el)
5681 (progn
5682 (if arg (org-table-edit-field t)
5683 (org-table-justify-field-maybe)
5684 (call-interactively 'org-table-next-field)))))
5686 ((eq arg t) ;; Global cycling
5688 (cond
5689 ((and (eq last-command this-command)
5690 (eq org-cycle-global-status 'overview))
5691 ;; We just created the overview - now do table of contents
5692 ;; This can be slow in very large buffers, so indicate action
5693 (message "CONTENTS...")
5694 (org-content)
5695 (message "CONTENTS...done")
5696 (setq org-cycle-global-status 'contents)
5697 (run-hook-with-args 'org-cycle-hook 'contents))
5699 ((and (eq last-command this-command)
5700 (eq org-cycle-global-status 'contents))
5701 ;; We just showed the table of contents - now show everything
5702 (show-all)
5703 (message "SHOW ALL")
5704 (setq org-cycle-global-status 'all)
5705 (run-hook-with-args 'org-cycle-hook 'all))
5708 ;; Default action: go to overview
5709 (org-overview)
5710 (message "OVERVIEW")
5711 (setq org-cycle-global-status 'overview)
5712 (run-hook-with-args 'org-cycle-hook 'overview))))
5714 ((and org-drawers org-drawer-regexp
5715 (save-excursion
5716 (beginning-of-line 1)
5717 (looking-at org-drawer-regexp)))
5718 ;; Toggle block visibility
5719 (org-flag-drawer
5720 (not (get-char-property (match-end 0) 'invisible))))
5722 ((integerp arg)
5723 ;; Show-subtree, ARG levels up from here.
5724 (save-excursion
5725 (org-back-to-heading)
5726 (outline-up-heading (if (< arg 0) (- arg)
5727 (- (funcall outline-level) arg)))
5728 (org-show-subtree)))
5730 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5731 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5732 ;; At a heading: rotate between three different views
5733 (org-back-to-heading)
5734 (let ((goal-column 0) eoh eol eos)
5735 ;; First, some boundaries
5736 (save-excursion
5737 (org-back-to-heading)
5738 (save-excursion
5739 (beginning-of-line 2)
5740 (while (and (not (eobp)) ;; this is like `next-line'
5741 (get-char-property (1- (point)) 'invisible))
5742 (beginning-of-line 2)) (setq eol (point)))
5743 (outline-end-of-heading) (setq eoh (point))
5744 (org-end-of-subtree t)
5745 (unless (eobp)
5746 (skip-chars-forward " \t\n")
5747 (beginning-of-line 1) ; in case this is an item
5749 (setq eos (1- (point))))
5750 ;; Find out what to do next and set `this-command'
5751 (cond
5752 ((= eos eoh)
5753 ;; Nothing is hidden behind this heading
5754 (message "EMPTY ENTRY")
5755 (setq org-cycle-subtree-status nil)
5756 (save-excursion
5757 (goto-char eos)
5758 (outline-next-heading)
5759 (if (org-invisible-p) (org-flag-heading nil))))
5760 ((or (>= eol eos)
5761 (not (string-match "\\S-" (buffer-substring eol eos))))
5762 ;; Entire subtree is hidden in one line: open it
5763 (org-show-entry)
5764 (show-children)
5765 (message "CHILDREN")
5766 (save-excursion
5767 (goto-char eos)
5768 (outline-next-heading)
5769 (if (org-invisible-p) (org-flag-heading nil)))
5770 (setq org-cycle-subtree-status 'children)
5771 (run-hook-with-args 'org-cycle-hook 'children))
5772 ((and (eq last-command this-command)
5773 (eq org-cycle-subtree-status 'children))
5774 ;; We just showed the children, now show everything.
5775 (org-show-subtree)
5776 (message "SUBTREE")
5777 (setq org-cycle-subtree-status 'subtree)
5778 (run-hook-with-args 'org-cycle-hook 'subtree))
5780 ;; Default action: hide the subtree.
5781 (hide-subtree)
5782 (message "FOLDED")
5783 (setq org-cycle-subtree-status 'folded)
5784 (run-hook-with-args 'org-cycle-hook 'folded)))))
5786 ;; TAB emulation
5787 (buffer-read-only (org-back-to-heading))
5789 ((org-try-cdlatex-tab))
5791 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5792 (or (not (bolp))
5793 (not (looking-at outline-regexp))))
5794 (call-interactively (global-key-binding "\t")))
5796 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5797 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5798 (or (and (eq org-cycle-emulate-tab 'white)
5799 (= (match-end 0) (point-at-eol)))
5800 (and (eq org-cycle-emulate-tab 'whitestart)
5801 (>= (match-end 0) pos))))
5803 (eq org-cycle-emulate-tab t))
5804 ; (if (and (looking-at "[ \n\r\t]")
5805 ; (string-match "^[ \t]*$" (buffer-substring
5806 ; (point-at-bol) (point))))
5807 ; (progn
5808 ; (beginning-of-line 1)
5809 ; (and (looking-at "[ \t]+") (replace-match ""))))
5810 (call-interactively (global-key-binding "\t")))
5812 (t (save-excursion
5813 (org-back-to-heading)
5814 (org-cycle))))))
5816 ;;;###autoload
5817 (defun org-global-cycle (&optional arg)
5818 "Cycle the global visibility. For details see `org-cycle'."
5819 (interactive "P")
5820 (let ((org-cycle-include-plain-lists
5821 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5822 (if (integerp arg)
5823 (progn
5824 (show-all)
5825 (hide-sublevels arg)
5826 (setq org-cycle-global-status 'contents))
5827 (org-cycle '(4)))))
5829 (defun org-overview ()
5830 "Switch to overview mode, shoing only top-level headlines.
5831 Really, this shows all headlines with level equal or greater than the level
5832 of the first headline in the buffer. This is important, because if the
5833 first headline is not level one, then (hide-sublevels 1) gives confusing
5834 results."
5835 (interactive)
5836 (let ((level (save-excursion
5837 (goto-char (point-min))
5838 (if (re-search-forward (concat "^" outline-regexp) nil t)
5839 (progn
5840 (goto-char (match-beginning 0))
5841 (funcall outline-level))))))
5842 (and level (hide-sublevels level))))
5844 (defun org-content (&optional arg)
5845 "Show all headlines in the buffer, like a table of contents.
5846 With numerical argument N, show content up to level N."
5847 (interactive "P")
5848 (save-excursion
5849 ;; Visit all headings and show their offspring
5850 (and (integerp arg) (org-overview))
5851 (goto-char (point-max))
5852 (catch 'exit
5853 (while (and (progn (condition-case nil
5854 (outline-previous-visible-heading 1)
5855 (error (goto-char (point-min))))
5857 (looking-at outline-regexp))
5858 (if (integerp arg)
5859 (show-children (1- arg))
5860 (show-branches))
5861 (if (bobp) (throw 'exit nil))))))
5864 (defun org-optimize-window-after-visibility-change (state)
5865 "Adjust the window after a change in outline visibility.
5866 This function is the default value of the hook `org-cycle-hook'."
5867 (when (get-buffer-window (current-buffer))
5868 (cond
5869 ; ((eq state 'overview) (org-first-headline-recenter 1))
5870 ; ((eq state 'overview) (org-beginning-of-line))
5871 ((eq state 'content) nil)
5872 ((eq state 'all) nil)
5873 ((eq state 'folded) nil)
5874 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5875 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5877 (defun org-compact-display-after-subtree-move ()
5878 (let (beg end)
5879 (save-excursion
5880 (if (org-up-heading-safe)
5881 (progn
5882 (hide-subtree)
5883 (show-entry)
5884 (show-children)
5885 (org-cycle-show-empty-lines 'children)
5886 (org-cycle-hide-drawers 'children))
5887 (org-overview)))))
5889 (defun org-cycle-show-empty-lines (state)
5890 "Show empty lines above all visible headlines.
5891 The region to be covered depends on STATE when called through
5892 `org-cycle-hook'. Lisp program can use t for STATE to get the
5893 entire buffer covered. Note that an empty line is only shown if there
5894 are at least `org-cycle-separator-lines' empty lines before the headeline."
5895 (when (> org-cycle-separator-lines 0)
5896 (save-excursion
5897 (let* ((n org-cycle-separator-lines)
5898 (re (cond
5899 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5900 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5901 (t (let ((ns (number-to-string (- n 2))))
5902 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5903 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5904 beg end)
5905 (cond
5906 ((memq state '(overview contents t))
5907 (setq beg (point-min) end (point-max)))
5908 ((memq state '(children folded))
5909 (setq beg (point) end (progn (org-end-of-subtree t t)
5910 (beginning-of-line 2)
5911 (point)))))
5912 (when beg
5913 (goto-char beg)
5914 (while (re-search-forward re end t)
5915 (if (not (get-char-property (match-end 1) 'invisible))
5916 (outline-flag-region
5917 (match-beginning 1) (match-end 1) nil)))))))
5918 ;; Never hide empty lines at the end of the file.
5919 (save-excursion
5920 (goto-char (point-max))
5921 (outline-previous-heading)
5922 (outline-end-of-heading)
5923 (if (and (looking-at "[ \t\n]+")
5924 (= (match-end 0) (point-max)))
5925 (outline-flag-region (point) (match-end 0) nil))))
5927 (defun org-subtree-end-visible-p ()
5928 "Is the end of the current subtree visible?"
5929 (pos-visible-in-window-p
5930 (save-excursion (org-end-of-subtree t) (point))))
5932 (defun org-first-headline-recenter (&optional N)
5933 "Move cursor to the first headline and recenter the headline.
5934 Optional argument N means, put the headline into the Nth line of the window."
5935 (goto-char (point-min))
5936 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5937 (beginning-of-line)
5938 (recenter (prefix-numeric-value N))))
5940 ;;; Org-goto
5942 (defvar org-goto-window-configuration nil)
5943 (defvar org-goto-marker nil)
5944 (defvar org-goto-map
5945 (let ((map (make-sparse-keymap)))
5946 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5947 (while (setq cmd (pop cmds))
5948 (substitute-key-definition cmd cmd map global-map)))
5949 (suppress-keymap map)
5950 (org-defkey map "\C-m" 'org-goto-ret)
5951 (org-defkey map [(return)] 'org-goto-ret)
5952 (org-defkey map [(left)] 'org-goto-left)
5953 (org-defkey map [(right)] 'org-goto-right)
5954 (org-defkey map [(control ?g)] 'org-goto-quit)
5955 (org-defkey map "\C-i" 'org-cycle)
5956 (org-defkey map [(tab)] 'org-cycle)
5957 (org-defkey map [(down)] 'outline-next-visible-heading)
5958 (org-defkey map [(up)] 'outline-previous-visible-heading)
5959 (if org-goto-auto-isearch
5960 (if (fboundp 'define-key-after)
5961 (define-key-after map [t] 'org-goto-local-auto-isearch)
5962 nil)
5963 (org-defkey map "q" 'org-goto-quit)
5964 (org-defkey map "n" 'outline-next-visible-heading)
5965 (org-defkey map "p" 'outline-previous-visible-heading)
5966 (org-defkey map "f" 'outline-forward-same-level)
5967 (org-defkey map "b" 'outline-backward-same-level)
5968 (org-defkey map "u" 'outline-up-heading))
5969 (org-defkey map "/" 'org-occur)
5970 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5971 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5972 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5973 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5974 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5975 map))
5977 (defconst org-goto-help
5978 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5979 RET=jump to location [Q]uit and return to previous location
5980 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5982 (defvar org-goto-start-pos) ; dynamically scoped parameter
5984 (defun org-goto (&optional alternative-interface)
5985 "Look up a different location in the current file, keeping current visibility.
5987 When you want look-up or go to a different location in a document, the
5988 fastest way is often to fold the entire buffer and then dive into the tree.
5989 This method has the disadvantage, that the previous location will be folded,
5990 which may not be what you want.
5992 This command works around this by showing a copy of the current buffer
5993 in an indirect buffer, in overview mode. You can dive into the tree in
5994 that copy, use org-occur and incremental search to find a location.
5995 When pressing RET or `Q', the command returns to the original buffer in
5996 which the visibility is still unchanged. After RET is will also jump to
5997 the location selected in the indirect buffer and expose the
5998 the headline hierarchy above."
5999 (interactive "P")
6000 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
6001 (org-refile-use-outline-path t)
6002 (interface
6003 (if (not alternative-interface)
6004 org-goto-interface
6005 (if (eq org-goto-interface 'outline)
6006 'outline-path-completion
6007 'outline)))
6008 (org-goto-start-pos (point))
6009 (selected-point
6010 (if (eq interface 'outline)
6011 (car (org-get-location (current-buffer) org-goto-help))
6012 (nth 3 (org-refile-get-location "Goto: ")))))
6013 (if selected-point
6014 (progn
6015 (org-mark-ring-push org-goto-start-pos)
6016 (goto-char selected-point)
6017 (if (or (org-invisible-p) (org-invisible-p2))
6018 (org-show-context 'org-goto)))
6019 (message "Quit"))))
6021 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6022 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6023 (defvar org-goto-local-auto-isearch-map) ; defined below
6025 (defun org-get-location (buf help)
6026 "Let the user select a location in the Org-mode buffer BUF.
6027 This function uses a recursive edit. It returns the selected position
6028 or nil."
6029 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6030 (isearch-hide-immediately nil)
6031 (isearch-search-fun-function
6032 (lambda () 'org-goto-local-search-forward-headings))
6033 (org-goto-selected-point org-goto-exit-command))
6034 (save-excursion
6035 (save-window-excursion
6036 (delete-other-windows)
6037 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6038 (switch-to-buffer
6039 (condition-case nil
6040 (make-indirect-buffer (current-buffer) "*org-goto*")
6041 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6042 (with-output-to-temp-buffer "*Help*"
6043 (princ help))
6044 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
6045 (setq buffer-read-only nil)
6046 (let ((org-startup-truncated t)
6047 (org-startup-folded nil)
6048 (org-startup-align-all-tables nil))
6049 (org-mode)
6050 (org-overview))
6051 (setq buffer-read-only t)
6052 (if (and (boundp 'org-goto-start-pos)
6053 (integer-or-marker-p org-goto-start-pos))
6054 (let ((org-show-hierarchy-above t)
6055 (org-show-siblings t)
6056 (org-show-following-heading t))
6057 (goto-char org-goto-start-pos)
6058 (and (org-invisible-p) (org-show-context)))
6059 (goto-char (point-min)))
6060 (org-beginning-of-line)
6061 (message "Select location and press RET")
6062 (use-local-map org-goto-map)
6063 (recursive-edit)
6065 (kill-buffer "*org-goto*")
6066 (cons org-goto-selected-point org-goto-exit-command)))
6068 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6069 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6070 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6071 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6073 (defun org-goto-local-search-forward-headings (string bound noerror)
6074 "Search and make sure that anu matches are in headlines."
6075 (catch 'return
6076 (while (search-forward string bound noerror)
6077 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6078 (and (member :headline context)
6079 (not (member :tags context))))
6080 (throw 'return (point))))))
6082 (defun org-goto-local-auto-isearch ()
6083 "Start isearch."
6084 (interactive)
6085 (goto-char (point-min))
6086 (let ((keys (this-command-keys)))
6087 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6088 (isearch-mode t)
6089 (isearch-process-search-char (string-to-char keys)))))
6091 (defun org-goto-ret (&optional arg)
6092 "Finish `org-goto' by going to the new location."
6093 (interactive "P")
6094 (setq org-goto-selected-point (point)
6095 org-goto-exit-command 'return)
6096 (throw 'exit nil))
6098 (defun org-goto-left ()
6099 "Finish `org-goto' by going to the new location."
6100 (interactive)
6101 (if (org-on-heading-p)
6102 (progn
6103 (beginning-of-line 1)
6104 (setq org-goto-selected-point (point)
6105 org-goto-exit-command 'left)
6106 (throw 'exit nil))
6107 (error "Not on a heading")))
6109 (defun org-goto-right ()
6110 "Finish `org-goto' by going to the new location."
6111 (interactive)
6112 (if (org-on-heading-p)
6113 (progn
6114 (setq org-goto-selected-point (point)
6115 org-goto-exit-command 'right)
6116 (throw 'exit nil))
6117 (error "Not on a heading")))
6119 (defun org-goto-quit ()
6120 "Finish `org-goto' without cursor motion."
6121 (interactive)
6122 (setq org-goto-selected-point nil)
6123 (setq org-goto-exit-command 'quit)
6124 (throw 'exit nil))
6126 ;;; Indirect buffer display of subtrees
6128 (defvar org-indirect-dedicated-frame nil
6129 "This is the frame being used for indirect tree display.")
6130 (defvar org-last-indirect-buffer nil)
6132 (defun org-tree-to-indirect-buffer (&optional arg)
6133 "Create indirect buffer and narrow it to current subtree.
6134 With numerical prefix ARG, go up to this level and then take that tree.
6135 If ARG is negative, go up that many levels.
6136 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6137 indirect buffer previously made with this command, to avoid proliferation of
6138 indirect buffers. However, when you call the command with a `C-u' prefix, or
6139 when `org-indirect-buffer-display' is `new-frame', the last buffer
6140 is kept so that you can work with several indirect buffers at the same time.
6141 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6142 requests that a new frame be made for the new buffer, so that the dedicated
6143 frame is not changed."
6144 (interactive "P")
6145 (let ((cbuf (current-buffer))
6146 (cwin (selected-window))
6147 (pos (point))
6148 beg end level heading ibuf)
6149 (save-excursion
6150 (org-back-to-heading t)
6151 (when (numberp arg)
6152 (setq level (org-outline-level))
6153 (if (< arg 0) (setq arg (+ level arg)))
6154 (while (> (setq level (org-outline-level)) arg)
6155 (outline-up-heading 1 t)))
6156 (setq beg (point)
6157 heading (org-get-heading))
6158 (org-end-of-subtree t) (setq end (point)))
6159 (if (and (buffer-live-p org-last-indirect-buffer)
6160 (not (eq org-indirect-buffer-display 'new-frame))
6161 (not arg))
6162 (kill-buffer org-last-indirect-buffer))
6163 (setq ibuf (org-get-indirect-buffer cbuf)
6164 org-last-indirect-buffer ibuf)
6165 (cond
6166 ((or (eq org-indirect-buffer-display 'new-frame)
6167 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6168 (select-frame (make-frame))
6169 (delete-other-windows)
6170 (switch-to-buffer ibuf)
6171 (org-set-frame-title heading))
6172 ((eq org-indirect-buffer-display 'dedicated-frame)
6173 (raise-frame
6174 (select-frame (or (and org-indirect-dedicated-frame
6175 (frame-live-p org-indirect-dedicated-frame)
6176 org-indirect-dedicated-frame)
6177 (setq org-indirect-dedicated-frame (make-frame)))))
6178 (delete-other-windows)
6179 (switch-to-buffer ibuf)
6180 (org-set-frame-title (concat "Indirect: " heading)))
6181 ((eq org-indirect-buffer-display 'current-window)
6182 (switch-to-buffer ibuf))
6183 ((eq org-indirect-buffer-display 'other-window)
6184 (pop-to-buffer ibuf))
6185 (t (error "Invalid value.")))
6186 (if (featurep 'xemacs)
6187 (save-excursion (org-mode) (turn-on-font-lock)))
6188 (narrow-to-region beg end)
6189 (show-all)
6190 (goto-char pos)
6191 (and (window-live-p cwin) (select-window cwin))))
6193 (defun org-get-indirect-buffer (&optional buffer)
6194 (setq buffer (or buffer (current-buffer)))
6195 (let ((n 1) (base (buffer-name buffer)) bname)
6196 (while (buffer-live-p
6197 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6198 (setq n (1+ n)))
6199 (condition-case nil
6200 (make-indirect-buffer buffer bname 'clone)
6201 (error (make-indirect-buffer buffer bname)))))
6203 (defun org-set-frame-title (title)
6204 "Set the title of the current frame to the string TITLE."
6205 ;; FIXME: how to name a single frame in XEmacs???
6206 (unless (featurep 'xemacs)
6207 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6209 ;;;; Structure editing
6211 ;;; Inserting headlines
6213 (defun org-insert-heading (&optional force-heading)
6214 "Insert a new heading or item with same depth at point.
6215 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6216 If point is at the beginning of a headline, insert a sibling before the
6217 current headline. If point is not at the beginning, do not split the line,
6218 but create the new hedline after the current line."
6219 (interactive "P")
6220 (if (= (buffer-size) 0)
6221 (insert "\n* ")
6222 (when (or force-heading (not (org-insert-item)))
6223 (let* ((head (save-excursion
6224 (condition-case nil
6225 (progn
6226 (org-back-to-heading)
6227 (match-string 0))
6228 (error "*"))))
6229 (blank (cdr (assq 'heading org-blank-before-new-entry)))
6230 pos)
6231 (cond
6232 ((and (org-on-heading-p) (bolp)
6233 (or (bobp)
6234 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6235 ;; insert before the current line
6236 (open-line (if blank 2 1)))
6237 ((and (bolp)
6238 (or (bobp)
6239 (save-excursion
6240 (backward-char 1) (not (org-invisible-p)))))
6241 ;; insert right here
6242 nil)
6244 ; ;; in the middle of the line
6245 ; (org-show-entry)
6246 ; (if (org-get-alist-option org-M-RET-may-split-line 'headline)
6247 ; (if (and
6248 ; (org-on-heading-p)
6249 ; (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \r\n]"))
6250 ; ;; protect the tags
6251 ;; (let ((tags (match-string 2)) pos)
6252 ; (delete-region (match-beginning 1) (match-end 1))
6253 ; (setq pos (point-at-bol))
6254 ; (newline (if blank 2 1))
6255 ; (save-excursion
6256 ; (goto-char pos)
6257 ; (end-of-line 1)
6258 ; (insert " " tags)
6259 ; (org-set-tags nil 'align)))
6260 ; (newline (if blank 2 1)))
6261 ; (newline (if blank 2 1))))
6264 ;; in the middle of the line
6265 (org-show-entry)
6266 (let ((split
6267 (org-get-alist-option org-M-RET-may-split-line 'headline))
6268 tags pos)
6269 (if (org-on-heading-p)
6270 (progn
6271 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6272 (setq tags (and (match-end 2) (match-string 2)))
6273 (and (match-end 1)
6274 (delete-region (match-beginning 1) (match-end 1)))
6275 (setq pos (point-at-bol))
6276 (or split (end-of-line 1))
6277 (delete-horizontal-space)
6278 (newline (if blank 2 1))
6279 (when tags
6280 (save-excursion
6281 (goto-char pos)
6282 (end-of-line 1)
6283 (insert " " tags)
6284 (org-set-tags nil 'align))))
6285 (or split (end-of-line 1))
6286 (newline (if blank 2 1))))))
6287 (insert head) (just-one-space)
6288 (setq pos (point))
6289 (end-of-line 1)
6290 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6291 (run-hooks 'org-insert-heading-hook)))))
6293 (defun org-insert-heading-after-current ()
6294 "Insert a new heading with same level as current, after current subtree."
6295 (interactive)
6296 (org-back-to-heading)
6297 (org-insert-heading)
6298 (org-move-subtree-down)
6299 (end-of-line 1))
6301 (defun org-insert-todo-heading (arg)
6302 "Insert a new heading with the same level and TODO state as current heading.
6303 If the heading has no TODO state, or if the state is DONE, use the first
6304 state (TODO by default). Also with prefix arg, force first state."
6305 (interactive "P")
6306 (when (not (org-insert-item 'checkbox))
6307 (org-insert-heading)
6308 (save-excursion
6309 (org-back-to-heading)
6310 (outline-previous-heading)
6311 (looking-at org-todo-line-regexp))
6312 (if (or arg
6313 (not (match-beginning 2))
6314 (member (match-string 2) org-done-keywords))
6315 (insert (car org-todo-keywords-1) " ")
6316 (insert (match-string 2) " "))))
6318 (defun org-insert-subheading (arg)
6319 "Insert a new subheading and demote it.
6320 Works for outline headings and for plain lists alike."
6321 (interactive "P")
6322 (org-insert-heading arg)
6323 (cond
6324 ((org-on-heading-p) (org-do-demote))
6325 ((org-at-item-p) (org-indent-item 1))))
6327 (defun org-insert-todo-subheading (arg)
6328 "Insert a new subheading with TODO keyword or checkbox and demote it.
6329 Works for outline headings and for plain lists alike."
6330 (interactive "P")
6331 (org-insert-todo-heading arg)
6332 (cond
6333 ((org-on-heading-p) (org-do-demote))
6334 ((org-at-item-p) (org-indent-item 1))))
6336 ;;; Promotion and Demotion
6338 (defun org-promote-subtree ()
6339 "Promote the entire subtree.
6340 See also `org-promote'."
6341 (interactive)
6342 (save-excursion
6343 (org-map-tree 'org-promote))
6344 (org-fix-position-after-promote))
6346 (defun org-demote-subtree ()
6347 "Demote the entire subtree. See `org-demote'.
6348 See also `org-promote'."
6349 (interactive)
6350 (save-excursion
6351 (org-map-tree 'org-demote))
6352 (org-fix-position-after-promote))
6355 (defun org-do-promote ()
6356 "Promote the current heading higher up the tree.
6357 If the region is active in `transient-mark-mode', promote all headings
6358 in the region."
6359 (interactive)
6360 (save-excursion
6361 (if (org-region-active-p)
6362 (org-map-region 'org-promote (region-beginning) (region-end))
6363 (org-promote)))
6364 (org-fix-position-after-promote))
6366 (defun org-do-demote ()
6367 "Demote the current heading lower down the tree.
6368 If the region is active in `transient-mark-mode', demote all headings
6369 in the region."
6370 (interactive)
6371 (save-excursion
6372 (if (org-region-active-p)
6373 (org-map-region 'org-demote (region-beginning) (region-end))
6374 (org-demote)))
6375 (org-fix-position-after-promote))
6377 (defun org-fix-position-after-promote ()
6378 "Make sure that after pro/demotion cursor position is right."
6379 (let ((pos (point)))
6380 (when (save-excursion
6381 (beginning-of-line 1)
6382 (looking-at org-todo-line-regexp)
6383 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6384 (cond ((eobp) (insert " "))
6385 ((eolp) (insert " "))
6386 ((equal (char-after) ?\ ) (forward-char 1))))))
6388 (defun org-reduced-level (l)
6389 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6391 (defun org-get-legal-level (level &optional change)
6392 "Rectify a level change under the influence of `org-odd-levels-only'
6393 LEVEL is a current level, CHANGE is by how much the level should be
6394 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6395 even level numbers will become the next higher odd number."
6396 (if org-odd-levels-only
6397 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6398 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6399 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6400 (max 1 (+ level change))))
6402 (defun org-promote ()
6403 "Promote the current heading higher up the tree.
6404 If the region is active in `transient-mark-mode', promote all headings
6405 in the region."
6406 (org-back-to-heading t)
6407 (let* ((level (save-match-data (funcall outline-level)))
6408 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
6409 (diff (abs (- level (length up-head) -1))))
6410 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6411 (replace-match up-head nil t)
6412 ;; Fixup tag positioning
6413 (and org-auto-align-tags (org-set-tags nil t))
6414 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
6416 (defun org-demote ()
6417 "Demote the current heading lower down the tree.
6418 If the region is active in `transient-mark-mode', demote all headings
6419 in the region."
6420 (org-back-to-heading t)
6421 (let* ((level (save-match-data (funcall outline-level)))
6422 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
6423 (diff (abs (- level (length down-head) -1))))
6424 (replace-match down-head nil t)
6425 ;; Fixup tag positioning
6426 (and org-auto-align-tags (org-set-tags nil t))
6427 (if org-adapt-indentation (org-fixup-indentation diff))))
6429 (defun org-map-tree (fun)
6430 "Call FUN for every heading underneath the current one."
6431 (org-back-to-heading)
6432 (let ((level (funcall outline-level)))
6433 (save-excursion
6434 (funcall fun)
6435 (while (and (progn
6436 (outline-next-heading)
6437 (> (funcall outline-level) level))
6438 (not (eobp)))
6439 (funcall fun)))))
6441 (defun org-map-region (fun beg end)
6442 "Call FUN for every heading between BEG and END."
6443 (let ((org-ignore-region t))
6444 (save-excursion
6445 (setq end (copy-marker end))
6446 (goto-char beg)
6447 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6448 (< (point) end))
6449 (funcall fun))
6450 (while (and (progn
6451 (outline-next-heading)
6452 (< (point) end))
6453 (not (eobp)))
6454 (funcall fun)))))
6456 (defun org-fixup-indentation (diff)
6457 "Change the indentation in the current entry by DIFF
6458 However, if any line in the current entry has no indentation, or if it
6459 would end up with no indentation after the change, nothing at all is done."
6460 (save-excursion
6461 (let ((end (save-excursion (outline-next-heading)
6462 (point-marker)))
6463 (prohibit (if (> diff 0)
6464 "^\\S-"
6465 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6466 col)
6467 (unless (save-excursion (end-of-line 1)
6468 (re-search-forward prohibit end t))
6469 (while (and (< (point) end)
6470 (re-search-forward "^[ \t]+" end t))
6471 (goto-char (match-end 0))
6472 (setq col (current-column))
6473 (if (< diff 0) (replace-match ""))
6474 (indent-to (+ diff col))))
6475 (move-marker end nil))))
6477 (defun org-convert-to-odd-levels ()
6478 "Convert an org-mode file with all levels allowed to one with odd levels.
6479 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6480 level 5 etc."
6481 (interactive)
6482 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6483 (let ((org-odd-levels-only nil) n)
6484 (save-excursion
6485 (goto-char (point-min))
6486 (while (re-search-forward "^\\*\\*+ " nil t)
6487 (setq n (- (length (match-string 0)) 2))
6488 (while (>= (setq n (1- n)) 0)
6489 (org-demote))
6490 (end-of-line 1))))))
6493 (defun org-convert-to-oddeven-levels ()
6494 "Convert an org-mode file with only odd levels to one with odd and even levels.
6495 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6496 section with an even level, conversion would destroy the structure of the file. An error
6497 is signaled in this case."
6498 (interactive)
6499 (goto-char (point-min))
6500 ;; First check if there are no even levels
6501 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6502 (org-show-context t)
6503 (error "Not all levels are odd in this file. Conversion not possible."))
6504 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6505 (let ((org-odd-levels-only nil) n)
6506 (save-excursion
6507 (goto-char (point-min))
6508 (while (re-search-forward "^\\*\\*+ " nil t)
6509 (setq n (/ (1- (length (match-string 0))) 2))
6510 (while (>= (setq n (1- n)) 0)
6511 (org-promote))
6512 (end-of-line 1))))))
6514 (defun org-tr-level (n)
6515 "Make N odd if required."
6516 (if org-odd-levels-only (1+ (/ n 2)) n))
6518 ;;; Vertical tree motion, cutting and pasting of subtrees
6520 (defun org-move-subtree-up (&optional arg)
6521 "Move the current subtree up past ARG headlines of the same level."
6522 (interactive "p")
6523 (org-move-subtree-down (- (prefix-numeric-value arg))))
6525 (defun org-move-subtree-down (&optional arg)
6526 "Move the current subtree down past ARG headlines of the same level."
6527 (interactive "p")
6528 (setq arg (prefix-numeric-value arg))
6529 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6530 'outline-get-last-sibling))
6531 (ins-point (make-marker))
6532 (cnt (abs arg))
6533 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6534 ;; Select the tree
6535 (org-back-to-heading)
6536 (setq beg0 (point))
6537 (save-excursion
6538 (setq ne-beg (org-back-over-empty-lines))
6539 (setq beg (point)))
6540 (save-match-data
6541 (save-excursion (outline-end-of-heading)
6542 (setq folded (org-invisible-p)))
6543 (outline-end-of-subtree))
6544 (outline-next-heading)
6545 (setq ne-end (org-back-over-empty-lines))
6546 (setq end (point))
6547 (goto-char beg0)
6548 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6549 ;; include less whitespace
6550 (save-excursion
6551 (goto-char beg)
6552 (forward-line (- ne-beg ne-end))
6553 (setq beg (point))))
6554 ;; Find insertion point, with error handling
6555 (while (> cnt 0)
6556 (or (and (funcall movfunc) (looking-at outline-regexp))
6557 (progn (goto-char beg0)
6558 (error "Cannot move past superior level or buffer limit")))
6559 (setq cnt (1- cnt)))
6560 (if (> arg 0)
6561 ;; Moving forward - still need to move over subtree
6562 (progn (org-end-of-subtree t t)
6563 (save-excursion
6564 (org-back-over-empty-lines)
6565 (or (bolp) (newline)))))
6566 (setq ne-ins (org-back-over-empty-lines))
6567 (move-marker ins-point (point))
6568 (setq txt (buffer-substring beg end))
6569 (delete-region beg end)
6570 (outline-flag-region (1- beg) beg nil)
6571 (outline-flag-region (1- (point)) (point) nil)
6572 (insert txt)
6573 (or (bolp) (insert "\n"))
6574 (setq ins-end (point))
6575 (goto-char ins-point)
6576 (org-skip-whitespace)
6577 (when (and (< arg 0)
6578 (org-first-sibling-p)
6579 (> ne-ins ne-beg))
6580 ;; Move whitespace back to beginning
6581 (save-excursion
6582 (goto-char ins-end)
6583 (let ((kill-whole-line t))
6584 (kill-line (- ne-ins ne-beg)) (point)))
6585 (insert (make-string (- ne-ins ne-beg) ?\n)))
6586 (move-marker ins-point nil)
6587 (org-compact-display-after-subtree-move)
6588 (unless folded
6589 (org-show-entry)
6590 (show-children)
6591 (org-cycle-hide-drawers 'children))))
6593 (defvar org-subtree-clip ""
6594 "Clipboard for cut and paste of subtrees.
6595 This is actually only a copy of the kill, because we use the normal kill
6596 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6598 (defvar org-subtree-clip-folded nil
6599 "Was the last copied subtree folded?
6600 This is used to fold the tree back after pasting.")
6602 (defun org-cut-subtree (&optional n)
6603 "Cut the current subtree into the clipboard.
6604 With prefix arg N, cut this many sequential subtrees.
6605 This is a short-hand for marking the subtree and then cutting it."
6606 (interactive "p")
6607 (org-copy-subtree n 'cut))
6609 (defun org-copy-subtree (&optional n cut)
6610 "Cut the current subtree into the clipboard.
6611 With prefix arg N, cut this many sequential subtrees.
6612 This is a short-hand for marking the subtree and then copying it.
6613 If CUT is non-nil, actually cut the subtree."
6614 (interactive "p")
6615 (let (beg end folded (beg0 (point)))
6616 (if (interactive-p)
6617 (org-back-to-heading nil) ; take what looks like a subtree
6618 (org-back-to-heading t)) ; take what is really there
6619 (org-back-over-empty-lines)
6620 (setq beg (point))
6621 (skip-chars-forward " \t\r\n")
6622 (save-match-data
6623 (save-excursion (outline-end-of-heading)
6624 (setq folded (org-invisible-p)))
6625 (condition-case nil
6626 (outline-forward-same-level (1- n))
6627 (error nil))
6628 (org-end-of-subtree t t))
6629 (org-back-over-empty-lines)
6630 (setq end (point))
6631 (goto-char beg0)
6632 (when (> end beg)
6633 (setq org-subtree-clip-folded folded)
6634 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6635 (setq org-subtree-clip (current-kill 0))
6636 (message "%s: Subtree(s) with %d characters"
6637 (if cut "Cut" "Copied")
6638 (length org-subtree-clip)))))
6640 (defun org-paste-subtree (&optional level tree)
6641 "Paste the clipboard as a subtree, with modification of headline level.
6642 The entire subtree is promoted or demoted in order to match a new headline
6643 level. By default, the new level is derived from the visible headings
6644 before and after the insertion point, and taken to be the inferior headline
6645 level of the two. So if the previous visible heading is level 3 and the
6646 next is level 4 (or vice versa), level 4 will be used for insertion.
6647 This makes sure that the subtree remains an independent subtree and does
6648 not swallow low level entries.
6650 You can also force a different level, either by using a numeric prefix
6651 argument, or by inserting the heading marker by hand. For example, if the
6652 cursor is after \"*****\", then the tree will be shifted to level 5.
6654 If you want to insert the tree as is, just use \\[yank].
6656 If optional TREE is given, use this text instead of the kill ring."
6657 (interactive "P")
6658 (unless (org-kill-is-subtree-p tree)
6659 (error "%s"
6660 (substitute-command-keys
6661 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6662 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6663 (^re (concat "^\\(" outline-regexp "\\)"))
6664 (re (concat "\\(" outline-regexp "\\)"))
6665 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6667 (old-level (if (string-match ^re txt)
6668 (- (match-end 0) (match-beginning 0) 1)
6669 -1))
6670 (force-level (cond (level (prefix-numeric-value level))
6671 ((string-match
6672 ^re_ (buffer-substring (point-at-bol) (point)))
6673 (- (match-end 1) (match-beginning 1)))
6674 (t nil)))
6675 (previous-level (save-excursion
6676 (condition-case nil
6677 (progn
6678 (outline-previous-visible-heading 1)
6679 (if (looking-at re)
6680 (- (match-end 0) (match-beginning 0) 1)
6682 (error 1))))
6683 (next-level (save-excursion
6684 (condition-case nil
6685 (progn
6686 (or (looking-at outline-regexp)
6687 (outline-next-visible-heading 1))
6688 (if (looking-at re)
6689 (- (match-end 0) (match-beginning 0) 1)
6691 (error 1))))
6692 (new-level (or force-level (max previous-level next-level)))
6693 (shift (if (or (= old-level -1)
6694 (= new-level -1)
6695 (= old-level new-level))
6697 (- new-level old-level)))
6698 (delta (if (> shift 0) -1 1))
6699 (func (if (> shift 0) 'org-demote 'org-promote))
6700 (org-odd-levels-only nil)
6701 beg end)
6702 ;; Remove the forced level indicator
6703 (if force-level
6704 (delete-region (point-at-bol) (point)))
6705 ;; Paste
6706 (beginning-of-line 1)
6707 (org-back-over-empty-lines) ;; FIXME: correct fix????
6708 (setq beg (point))
6709 (insert-before-markers txt) ;; FIXME: correct fix????
6710 (unless (string-match "\n\\'" txt) (insert "\n"))
6711 (setq end (point))
6712 (goto-char beg)
6713 (skip-chars-forward " \t\n\r")
6714 (setq beg (point))
6715 ;; Shift if necessary
6716 (unless (= shift 0)
6717 (save-restriction
6718 (narrow-to-region beg end)
6719 (while (not (= shift 0))
6720 (org-map-region func (point-min) (point-max))
6721 (setq shift (+ delta shift)))
6722 (goto-char (point-min))))
6723 (when (interactive-p)
6724 (message "Clipboard pasted as level %d subtree" new-level))
6725 (if (and kill-ring
6726 (eq org-subtree-clip (current-kill 0))
6727 org-subtree-clip-folded)
6728 ;; The tree was folded before it was killed/copied
6729 (hide-subtree))))
6731 (defun org-kill-is-subtree-p (&optional txt)
6732 "Check if the current kill is an outline subtree, or a set of trees.
6733 Returns nil if kill does not start with a headline, or if the first
6734 headline level is not the largest headline level in the tree.
6735 So this will actually accept several entries of equal levels as well,
6736 which is OK for `org-paste-subtree'.
6737 If optional TXT is given, check this string instead of the current kill."
6738 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6739 (start-level (and kill
6740 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6741 org-outline-regexp "\\)")
6742 kill)
6743 (- (match-end 2) (match-beginning 2) 1)))
6744 (re (concat "^" org-outline-regexp))
6745 (start (1+ (match-beginning 2))))
6746 (if (not start-level)
6747 (progn
6748 nil) ;; does not even start with a heading
6749 (catch 'exit
6750 (while (setq start (string-match re kill (1+ start)))
6751 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6752 (throw 'exit nil)))
6753 t))))
6755 (defun org-narrow-to-subtree ()
6756 "Narrow buffer to the current subtree."
6757 (interactive)
6758 (save-excursion
6759 (save-match-data
6760 (narrow-to-region
6761 (progn (org-back-to-heading) (point))
6762 (progn (org-end-of-subtree t t) (point))))))
6765 ;;; Outline Sorting
6767 (defun org-sort (with-case)
6768 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6769 Optional argument WITH-CASE means sort case-sensitively."
6770 (interactive "P")
6771 (if (org-at-table-p)
6772 (org-call-with-arg 'org-table-sort-lines with-case)
6773 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6775 (defvar org-priority-regexp) ; defined later in the file
6777 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6778 "Sort entries on a certain level of an outline tree.
6779 If there is an active region, the entries in the region are sorted.
6780 Else, if the cursor is before the first entry, sort the top-level items.
6781 Else, the children of the entry at point are sorted.
6783 Sorting can be alphabetically, numerically, and by date/time as given by
6784 the first time stamp in the entry. The command prompts for the sorting
6785 type unless it has been given to the function through the SORTING-TYPE
6786 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6787 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6788 called with point at the beginning of the record. It must return either
6789 a string or a number that should serve as the sorting key for that record.
6791 Comparing entries ignores case by default. However, with an optional argument
6792 WITH-CASE, the sorting considers case as well."
6793 (interactive "P")
6794 (let ((case-func (if with-case 'identity 'downcase))
6795 start beg end stars re re2
6796 txt what tmp plain-list-p)
6797 ;; Find beginning and end of region to sort
6798 (cond
6799 ((org-region-active-p)
6800 ;; we will sort the region
6801 (setq end (region-end)
6802 what "region")
6803 (goto-char (region-beginning))
6804 (if (not (org-on-heading-p)) (outline-next-heading))
6805 (setq start (point)))
6806 ((org-at-item-p)
6807 ;; we will sort this plain list
6808 (org-beginning-of-item-list) (setq start (point))
6809 (org-end-of-item-list) (setq end (point))
6810 (goto-char start)
6811 (setq plain-list-p t
6812 what "plain list"))
6813 ((or (org-on-heading-p)
6814 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6815 ;; we will sort the children of the current headline
6816 (org-back-to-heading)
6817 (setq start (point)
6818 end (progn (org-end-of-subtree t t)
6819 (org-back-over-empty-lines)
6820 (point))
6821 what "children")
6822 (goto-char start)
6823 (show-subtree)
6824 (outline-next-heading))
6826 ;; we will sort the top-level entries in this file
6827 (goto-char (point-min))
6828 (or (org-on-heading-p) (outline-next-heading))
6829 (setq start (point) end (point-max) what "top-level")
6830 (goto-char start)
6831 (show-all)))
6833 (setq beg (point))
6834 (if (>= beg end) (error "Nothing to sort"))
6836 (unless plain-list-p
6837 (looking-at "\\(\\*+\\)")
6838 (setq stars (match-string 1)
6839 re (concat "^" (regexp-quote stars) " +")
6840 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6841 txt (buffer-substring beg end))
6842 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6843 (if (and (not (equal stars "*")) (string-match re2 txt))
6844 (error "Region to sort contains a level above the first entry")))
6846 (unless sorting-type
6847 (message
6848 (if plain-list-p
6849 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6850 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
6851 what)
6852 (setq sorting-type (read-char-exclusive))
6854 (and (= (downcase sorting-type) ?f)
6855 (setq getkey-func
6856 (completing-read "Sort using function: "
6857 obarray 'fboundp t nil nil))
6858 (setq getkey-func (intern getkey-func)))
6860 (and (= (downcase sorting-type) ?r)
6861 (setq property
6862 (completing-read "Property: "
6863 (mapcar 'list (org-buffer-property-keys t))
6864 nil t))))
6866 (message "Sorting entries...")
6868 (save-restriction
6869 (narrow-to-region start end)
6871 (let ((dcst (downcase sorting-type))
6872 (now (current-time)))
6873 (sort-subr
6874 (/= dcst sorting-type)
6875 ;; This function moves to the beginning character of the "record" to
6876 ;; be sorted.
6877 (if plain-list-p
6878 (lambda nil
6879 (if (org-at-item-p) t (goto-char (point-max))))
6880 (lambda nil
6881 (if (re-search-forward re nil t)
6882 (goto-char (match-beginning 0))
6883 (goto-char (point-max)))))
6884 ;; This function moves to the last character of the "record" being
6885 ;; sorted.
6886 (if plain-list-p
6887 'org-end-of-item
6888 (lambda nil
6889 (save-match-data
6890 (condition-case nil
6891 (outline-forward-same-level 1)
6892 (error
6893 (goto-char (point-max)))))))
6895 ;; This function returns the value that gets sorted against.
6896 (if plain-list-p
6897 (lambda nil
6898 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6899 (cond
6900 ((= dcst ?n)
6901 (string-to-number (buffer-substring (match-end 0)
6902 (point-at-eol))))
6903 ((= dcst ?a)
6904 (buffer-substring (match-end 0) (point-at-eol)))
6905 ((= dcst ?t)
6906 (if (re-search-forward org-ts-regexp
6907 (point-at-eol) t)
6908 (org-time-string-to-time (match-string 0))
6909 now))
6910 ((= dcst ?f)
6911 (if getkey-func
6912 (progn
6913 (setq tmp (funcall getkey-func))
6914 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6915 tmp)
6916 (error "Invalid key function `%s'" getkey-func)))
6917 (t (error "Invalid sorting type `%c'" sorting-type)))))
6918 (lambda nil
6919 (cond
6920 ((= dcst ?n)
6921 (if (looking-at outline-regexp)
6922 (string-to-number (buffer-substring (match-end 0)
6923 (point-at-eol)))
6924 nil))
6925 ((= dcst ?a)
6926 (funcall case-func (buffer-substring (point-at-bol)
6927 (point-at-eol))))
6928 ((= dcst ?t)
6929 (if (re-search-forward org-ts-regexp
6930 (save-excursion
6931 (forward-line 2)
6932 (point)) t)
6933 (org-time-string-to-time (match-string 0))
6934 now))
6935 ((= dcst ?p)
6936 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6937 (string-to-char (match-string 2))
6938 org-default-priority))
6939 ((= dcst ?r)
6940 (or (org-entry-get nil property) ""))
6941 ((= dcst ?f)
6942 (if getkey-func
6943 (progn
6944 (setq tmp (funcall getkey-func))
6945 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6946 tmp)
6947 (error "Invalid key function `%s'" getkey-func)))
6948 (t (error "Invalid sorting type `%c'" sorting-type)))))
6950 (cond
6951 ((= dcst ?a) 'string<)
6952 ((= dcst ?t) 'time-less-p)
6953 (t nil)))))
6954 (message "Sorting entries...done")))
6956 (defun org-do-sort (table what &optional with-case sorting-type)
6957 "Sort TABLE of WHAT according to SORTING-TYPE.
6958 The user will be prompted for the SORTING-TYPE if the call to this
6959 function does not specify it. WHAT is only for the prompt, to indicate
6960 what is being sorted. The sorting key will be extracted from
6961 the car of the elements of the table.
6962 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6963 (unless sorting-type
6964 (message
6965 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6966 what)
6967 (setq sorting-type (read-char-exclusive)))
6968 (let ((dcst (downcase sorting-type))
6969 extractfun comparefun)
6970 ;; Define the appropriate functions
6971 (cond
6972 ((= dcst ?n)
6973 (setq extractfun 'string-to-number
6974 comparefun (if (= dcst sorting-type) '< '>)))
6975 ((= dcst ?a)
6976 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6977 (lambda(x) (downcase (org-sort-remove-invisible x))))
6978 comparefun (if (= dcst sorting-type)
6979 'string<
6980 (lambda (a b) (and (not (string< a b))
6981 (not (string= a b)))))))
6982 ((= dcst ?t)
6983 (setq extractfun
6984 (lambda (x)
6985 (if (string-match org-ts-regexp x)
6986 (time-to-seconds
6987 (org-time-string-to-time (match-string 0 x)))
6989 comparefun (if (= dcst sorting-type) '< '>)))
6990 (t (error "Invalid sorting type `%c'" sorting-type)))
6992 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6993 table)
6994 (lambda (a b) (funcall comparefun (car a) (car b))))))
6996 ;;;; Plain list items, including checkboxes
6998 ;;; Plain list items
7000 (defun org-at-item-p ()
7001 "Is point in a line starting a hand-formatted item?"
7002 (let ((llt org-plain-list-ordered-item-terminator))
7003 (save-excursion
7004 (goto-char (point-at-bol))
7005 (looking-at
7006 (cond
7007 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7008 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7009 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7010 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
7012 (defun org-in-item-p ()
7013 "It the cursor inside a plain list item.
7014 Does not have to be the first line."
7015 (save-excursion
7016 (condition-case nil
7017 (progn
7018 (org-beginning-of-item)
7019 (org-at-item-p)
7021 (error nil))))
7023 (defun org-insert-item (&optional checkbox)
7024 "Insert a new item at the current level.
7025 Return t when things worked, nil when we are not in an item."
7026 (when (save-excursion
7027 (condition-case nil
7028 (progn
7029 (org-beginning-of-item)
7030 (org-at-item-p)
7031 (if (org-invisible-p) (error "Invisible item"))
7033 (error nil)))
7034 (let* ((bul (match-string 0))
7035 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
7036 (match-end 0)))
7037 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
7038 pos)
7039 (cond
7040 ((and (org-at-item-p) (<= (point) eow))
7041 ;; before the bullet
7042 (beginning-of-line 1)
7043 (open-line (if blank 2 1)))
7044 ((<= (point) eow)
7045 (beginning-of-line 1))
7047 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
7048 (end-of-line 1)
7049 (delete-horizontal-space))
7050 (newline (if blank 2 1))))
7051 (insert bul (if checkbox "[ ]" ""))
7052 (just-one-space)
7053 (setq pos (point))
7054 (end-of-line 1)
7055 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
7056 (org-maybe-renumber-ordered-list)
7057 (and checkbox (org-update-checkbox-count-maybe))
7060 ;;; Checkboxes
7062 (defun org-at-item-checkbox-p ()
7063 "Is point at a line starting a plain-list item with a checklet?"
7064 (and (org-at-item-p)
7065 (save-excursion
7066 (goto-char (match-end 0))
7067 (skip-chars-forward " \t")
7068 (looking-at "\\[[- X]\\]"))))
7070 (defun org-toggle-checkbox (&optional arg)
7071 "Toggle the checkbox in the current line."
7072 (interactive "P")
7073 (catch 'exit
7074 (let (beg end status (firstnew 'unknown))
7075 (cond
7076 ((org-region-active-p)
7077 (setq beg (region-beginning) end (region-end)))
7078 ((org-on-heading-p)
7079 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
7080 ((org-at-item-checkbox-p)
7081 (let ((pos (point)))
7082 (replace-match
7083 (cond (arg "[-]")
7084 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
7085 (t "[ ]"))
7086 t t)
7087 (goto-char pos))
7088 (throw 'exit t))
7089 (t (error "Not at a checkbox or heading, and no active region")))
7090 (save-excursion
7091 (goto-char beg)
7092 (while (< (point) end)
7093 (when (org-at-item-checkbox-p)
7094 (setq status (equal (match-string 0) "[X]"))
7095 (when (eq firstnew 'unknown)
7096 (setq firstnew (not status)))
7097 (replace-match
7098 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
7099 (beginning-of-line 2)))))
7100 (org-update-checkbox-count-maybe))
7102 (defun org-update-checkbox-count-maybe ()
7103 "Update checkbox statistics unless turned off by user."
7104 (when org-provide-checkbox-statistics
7105 (org-update-checkbox-count)))
7107 (defun org-update-checkbox-count (&optional all)
7108 "Update the checkbox statistics in the current section.
7109 This will find all statistic cookies like [57%] and [6/12] and update them
7110 with the current numbers. With optional prefix argument ALL, do this for
7111 the whole buffer."
7112 (interactive "P")
7113 (save-excursion
7114 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
7115 (beg (condition-case nil
7116 (progn (outline-back-to-heading) (point))
7117 (error (point-min))))
7118 (end (move-marker (make-marker)
7119 (progn (outline-next-heading) (point))))
7120 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
7121 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
7122 (re-find (concat re "\\|" re-box))
7123 beg-cookie end-cookie is-percent c-on c-off lim
7124 eline curr-ind next-ind continue-from startsearch
7125 (cstat 0)
7127 (when all
7128 (goto-char (point-min))
7129 (outline-next-heading)
7130 (setq beg (point) end (point-max)))
7131 (goto-char end)
7132 ;; find each statistic cookie
7133 (while (re-search-backward re-find beg t)
7134 (setq beg-cookie (match-beginning 1)
7135 end-cookie (match-end 1)
7136 cstat (+ cstat (if end-cookie 1 0))
7137 startsearch (point-at-eol)
7138 continue-from (point-at-bol)
7139 is-percent (match-beginning 2)
7140 lim (cond
7141 ((org-on-heading-p) (outline-next-heading) (point))
7142 ((org-at-item-p) (org-end-of-item) (point))
7143 (t nil))
7144 c-on 0
7145 c-off 0)
7146 (when lim
7147 ;; find first checkbox for this cookie and gather
7148 ;; statistics from all that are at this indentation level
7149 (goto-char startsearch)
7150 (if (re-search-forward re-box lim t)
7151 (progn
7152 (org-beginning-of-item)
7153 (setq curr-ind (org-get-indentation))
7154 (setq next-ind curr-ind)
7155 (while (= curr-ind next-ind)
7156 (save-excursion (end-of-line) (setq eline (point)))
7157 (if (re-search-forward re-box eline t)
7158 (if (member (match-string 2) '("[ ]" "[-]"))
7159 (setq c-off (1+ c-off))
7160 (setq c-on (1+ c-on))
7163 (org-end-of-item)
7164 (setq next-ind (org-get-indentation))
7166 (goto-char continue-from)
7167 ;; update cookie
7168 (when end-cookie
7169 (delete-region beg-cookie end-cookie)
7170 (goto-char beg-cookie)
7171 (insert
7172 (if is-percent
7173 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
7174 (format "[%d/%d]" c-on (+ c-on c-off)))))
7175 ;; update items checkbox if it has one
7176 (when (org-at-item-p)
7177 (org-beginning-of-item)
7178 (when (and (> (+ c-on c-off) 0)
7179 (re-search-forward re-box (point-at-eol) t))
7180 (setq beg-cookie (match-beginning 2)
7181 end-cookie (match-end 2))
7182 (delete-region beg-cookie end-cookie)
7183 (goto-char beg-cookie)
7184 (cond ((= c-off 0) (insert "[X]"))
7185 ((= c-on 0) (insert "[ ]"))
7186 (t (insert "[-]")))
7188 (goto-char continue-from))
7189 (when (interactive-p)
7190 (message "Checkbox satistics updated %s (%d places)"
7191 (if all "in entire file" "in current outline entry") cstat)))))
7193 (defun org-get-checkbox-statistics-face ()
7194 "Select the face for checkbox statistics.
7195 The face will be `org-done' when all relevant boxes are checked. Otherwise
7196 it will be `org-todo'."
7197 (if (match-end 1)
7198 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
7199 (if (and (> (match-end 2) (match-beginning 2))
7200 (equal (match-string 2) (match-string 3)))
7201 'org-done
7202 'org-todo)))
7204 (defun org-get-indentation (&optional line)
7205 "Get the indentation of the current line, interpreting tabs.
7206 When LINE is given, assume it represents a line and compute its indentation."
7207 (if line
7208 (if (string-match "^ *" (org-remove-tabs line))
7209 (match-end 0))
7210 (save-excursion
7211 (beginning-of-line 1)
7212 (skip-chars-forward " \t")
7213 (current-column))))
7215 (defun org-remove-tabs (s &optional width)
7216 "Replace tabulators in S with spaces.
7217 Assumes that s is a single line, starting in column 0."
7218 (setq width (or width tab-width))
7219 (while (string-match "\t" s)
7220 (setq s (replace-match
7221 (make-string
7222 (- (* width (/ (+ (match-beginning 0) width) width))
7223 (match-beginning 0)) ?\ )
7224 t t s)))
7227 (defun org-fix-indentation (line ind)
7228 "Fix indentation in LINE.
7229 IND is a cons cell with target and minimum indentation.
7230 If the current indenation in LINE is smaller than the minimum,
7231 leave it alone. If it is larger than ind, set it to the target."
7232 (let* ((l (org-remove-tabs line))
7233 (i (org-get-indentation l))
7234 (i1 (car ind)) (i2 (cdr ind)))
7235 (if (>= i i2) (setq l (substring line i2)))
7236 (if (> i1 0)
7237 (concat (make-string i1 ?\ ) l)
7238 l)))
7240 (defcustom org-empty-line-terminates-plain-lists nil
7241 "Non-nil means, an empty line ends all plain list levels.
7242 When nil, empty lines are part of the preceeding item."
7243 :group 'org-plain-lists
7244 :type 'boolean)
7246 (defun org-beginning-of-item ()
7247 "Go to the beginning of the current hand-formatted item.
7248 If the cursor is not in an item, throw an error."
7249 (interactive)
7250 (let ((pos (point))
7251 (limit (save-excursion
7252 (condition-case nil
7253 (progn
7254 (org-back-to-heading)
7255 (beginning-of-line 2) (point))
7256 (error (point-min)))))
7257 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7258 ind ind1)
7259 (if (org-at-item-p)
7260 (beginning-of-line 1)
7261 (beginning-of-line 1)
7262 (skip-chars-forward " \t")
7263 (setq ind (current-column))
7264 (if (catch 'exit
7265 (while t
7266 (beginning-of-line 0)
7267 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
7269 (if (looking-at "[ \t]*$")
7270 (setq ind1 ind-empty)
7271 (skip-chars-forward " \t")
7272 (setq ind1 (current-column)))
7273 (if (< ind1 ind)
7274 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
7276 (goto-char pos)
7277 (error "Not in an item")))))
7279 (defun org-end-of-item ()
7280 "Go to the end of the current hand-formatted item.
7281 If the cursor is not in an item, throw an error."
7282 (interactive)
7283 (let* ((pos (point))
7284 ind1
7285 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7286 (limit (save-excursion (outline-next-heading) (point)))
7287 (ind (save-excursion
7288 (org-beginning-of-item)
7289 (skip-chars-forward " \t")
7290 (current-column)))
7291 (end (catch 'exit
7292 (while t
7293 (beginning-of-line 2)
7294 (if (eobp) (throw 'exit (point)))
7295 (if (>= (point) limit) (throw 'exit (point-at-bol)))
7296 (if (looking-at "[ \t]*$")
7297 (setq ind1 ind-empty)
7298 (skip-chars-forward " \t")
7299 (setq ind1 (current-column)))
7300 (if (<= ind1 ind)
7301 (throw 'exit (point-at-bol)))))))
7302 (if end
7303 (goto-char end)
7304 (goto-char pos)
7305 (error "Not in an item"))))
7307 (defun org-next-item ()
7308 "Move to the beginning of the next item in the current plain list.
7309 Error if not at a plain list, or if this is the last item in the list."
7310 (interactive)
7311 (let (ind ind1 (pos (point)))
7312 (org-beginning-of-item)
7313 (setq ind (org-get-indentation))
7314 (org-end-of-item)
7315 (setq ind1 (org-get-indentation))
7316 (unless (and (org-at-item-p) (= ind ind1))
7317 (goto-char pos)
7318 (error "On last item"))))
7320 (defun org-previous-item ()
7321 "Move to the beginning of the previous item in the current plain list.
7322 Error if not at a plain list, or if this is the first item in the list."
7323 (interactive)
7324 (let (beg ind ind1 (pos (point)))
7325 (org-beginning-of-item)
7326 (setq beg (point))
7327 (setq ind (org-get-indentation))
7328 (goto-char beg)
7329 (catch 'exit
7330 (while t
7331 (beginning-of-line 0)
7332 (if (looking-at "[ \t]*$")
7334 (if (<= (setq ind1 (org-get-indentation)) ind)
7335 (throw 'exit t)))))
7336 (condition-case nil
7337 (if (or (not (org-at-item-p))
7338 (< ind1 (1- ind)))
7339 (error "")
7340 (org-beginning-of-item))
7341 (error (goto-char pos)
7342 (error "On first item")))))
7344 (defun org-first-list-item-p ()
7345 "Is this heading the item in a plain list?"
7346 (unless (org-at-item-p)
7347 (error "Not at a plain list item"))
7348 (org-beginning-of-item)
7349 (= (point) (save-excursion (org-beginning-of-item-list))))
7351 (defun org-move-item-down ()
7352 "Move the plain list item at point down, i.e. swap with following item.
7353 Subitems (items with larger indentation) are considered part of the item,
7354 so this really moves item trees."
7355 (interactive)
7356 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
7357 (org-beginning-of-item)
7358 (setq beg0 (point))
7359 (save-excursion
7360 (setq ne-beg (org-back-over-empty-lines))
7361 (setq beg (point)))
7362 (goto-char beg0)
7363 (setq ind (org-get-indentation))
7364 (org-end-of-item)
7365 (setq end0 (point))
7366 (setq ind1 (org-get-indentation))
7367 (setq ne-end (org-back-over-empty-lines))
7368 (setq end (point))
7369 (goto-char beg0)
7370 (when (and (org-first-list-item-p) (< ne-end ne-beg))
7371 ;; include less whitespace
7372 (save-excursion
7373 (goto-char beg)
7374 (forward-line (- ne-beg ne-end))
7375 (setq beg (point))))
7376 (goto-char end0)
7377 (if (and (org-at-item-p) (= ind ind1))
7378 (progn
7379 (org-end-of-item)
7380 (org-back-over-empty-lines)
7381 (setq txt (buffer-substring beg end))
7382 (save-excursion
7383 (delete-region beg end))
7384 (setq pos (point))
7385 (insert txt)
7386 (goto-char pos) (org-skip-whitespace)
7387 (org-maybe-renumber-ordered-list))
7388 (goto-char pos)
7389 (error "Cannot move this item further down"))))
7391 (defun org-move-item-up (arg)
7392 "Move the plain list item at point up, i.e. swap with previous item.
7393 Subitems (items with larger indentation) are considered part of the item,
7394 so this really moves item trees."
7395 (interactive "p")
7396 (let (beg beg0 end ind ind1 (pos (point)) txt
7397 ne-beg ne-ins ins-end)
7398 (org-beginning-of-item)
7399 (setq beg0 (point))
7400 (setq ind (org-get-indentation))
7401 (save-excursion
7402 (setq ne-beg (org-back-over-empty-lines))
7403 (setq beg (point)))
7404 (goto-char beg0)
7405 (org-end-of-item)
7406 (setq end (point))
7407 (goto-char beg0)
7408 (catch 'exit
7409 (while t
7410 (beginning-of-line 0)
7411 (if (looking-at "[ \t]*$")
7412 (if org-empty-line-terminates-plain-lists
7413 (progn
7414 (goto-char pos)
7415 (error "Cannot move this item further up"))
7416 nil)
7417 (if (<= (setq ind1 (org-get-indentation)) ind)
7418 (throw 'exit t)))))
7419 (condition-case nil
7420 (org-beginning-of-item)
7421 (error (goto-char beg)
7422 (error "Cannot move this item further up")))
7423 (setq ind1 (org-get-indentation))
7424 (if (and (org-at-item-p) (= ind ind1))
7425 (progn
7426 (setq ne-ins (org-back-over-empty-lines))
7427 (setq txt (buffer-substring beg end))
7428 (save-excursion
7429 (delete-region beg end))
7430 (setq pos (point))
7431 (insert txt)
7432 (setq ins-end (point))
7433 (goto-char pos) (org-skip-whitespace)
7435 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
7436 ;; Move whitespace back to beginning
7437 (save-excursion
7438 (goto-char ins-end)
7439 (let ((kill-whole-line t))
7440 (kill-line (- ne-ins ne-beg)) (point)))
7441 (insert (make-string (- ne-ins ne-beg) ?\n)))
7443 (org-maybe-renumber-ordered-list))
7444 (goto-char pos)
7445 (error "Cannot move this item further up"))))
7447 (defun org-maybe-renumber-ordered-list ()
7448 "Renumber the ordered list at point if setup allows it.
7449 This tests the user option `org-auto-renumber-ordered-lists' before
7450 doing the renumbering."
7451 (interactive)
7452 (when (and org-auto-renumber-ordered-lists
7453 (org-at-item-p))
7454 (if (match-beginning 3)
7455 (org-renumber-ordered-list 1)
7456 (org-fix-bullet-type))))
7458 (defun org-maybe-renumber-ordered-list-safe ()
7459 (condition-case nil
7460 (save-excursion
7461 (org-maybe-renumber-ordered-list))
7462 (error nil)))
7464 (defun org-cycle-list-bullet (&optional which)
7465 "Cycle through the different itemize/enumerate bullets.
7466 This cycle the entire list level through the sequence:
7468 `-' -> `+' -> `*' -> `1.' -> `1)'
7470 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7471 0 meand `-', 1 means `+' etc."
7472 (interactive "P")
7473 (org-preserve-lc
7474 (org-beginning-of-item-list)
7475 (org-at-item-p)
7476 (beginning-of-line 1)
7477 (let ((current (match-string 0))
7478 (prevp (eq which 'previous))
7479 new)
7480 (setq new (cond
7481 ((and (numberp which)
7482 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7483 ((string-match "-" current) (if prevp "1)" "+"))
7484 ((string-match "\\+" current)
7485 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7486 ((string-match "\\*" current) (if prevp "+" "1."))
7487 ((string-match "\\." current) (if prevp "*" "1)"))
7488 ((string-match ")" current) (if prevp "1." "-"))
7489 (t (error "This should not happen"))))
7490 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7491 (org-fix-bullet-type)
7492 (org-maybe-renumber-ordered-list))))
7494 (defun org-get-string-indentation (s)
7495 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7496 (let ((n -1) (i 0) (w tab-width) c)
7497 (catch 'exit
7498 (while (< (setq n (1+ n)) (length s))
7499 (setq c (aref s n))
7500 (cond ((= c ?\ ) (setq i (1+ i)))
7501 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7502 (t (throw 'exit t)))))
7505 (defun org-renumber-ordered-list (arg)
7506 "Renumber an ordered plain list.
7507 Cursor needs to be in the first line of an item, the line that starts
7508 with something like \"1.\" or \"2)\"."
7509 (interactive "p")
7510 (unless (and (org-at-item-p)
7511 (match-beginning 3))
7512 (error "This is not an ordered list"))
7513 (let ((line (org-current-line))
7514 (col (current-column))
7515 (ind (org-get-string-indentation
7516 (buffer-substring (point-at-bol) (match-beginning 3))))
7517 ;; (term (substring (match-string 3) -1))
7518 ind1 (n (1- arg))
7519 fmt)
7520 ;; find where this list begins
7521 (org-beginning-of-item-list)
7522 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7523 (setq fmt (concat "%d" (match-string 1)))
7524 (beginning-of-line 0)
7525 ;; walk forward and replace these numbers
7526 (catch 'exit
7527 (while t
7528 (catch 'next
7529 (beginning-of-line 2)
7530 (if (eobp) (throw 'exit nil))
7531 (if (looking-at "[ \t]*$") (throw 'next nil))
7532 (skip-chars-forward " \t") (setq ind1 (current-column))
7533 (if (> ind1 ind) (throw 'next t))
7534 (if (< ind1 ind) (throw 'exit t))
7535 (if (not (org-at-item-p)) (throw 'exit nil))
7536 (delete-region (match-beginning 2) (match-end 2))
7537 (goto-char (match-beginning 2))
7538 (insert (format fmt (setq n (1+ n)))))))
7539 (goto-line line)
7540 (move-to-column col)))
7542 (defun org-fix-bullet-type ()
7543 "Make sure all items in this list have the same bullet as the firsst item."
7544 (interactive)
7545 (unless (org-at-item-p) (error "This is not a list"))
7546 (let ((line (org-current-line))
7547 (col (current-column))
7548 (ind (current-indentation))
7549 ind1 bullet)
7550 ;; find where this list begins
7551 (org-beginning-of-item-list)
7552 (beginning-of-line 1)
7553 ;; find out what the bullet type is
7554 (looking-at "[ \t]*\\(\\S-+\\)")
7555 (setq bullet (match-string 1))
7556 ;; walk forward and replace these numbers
7557 (beginning-of-line 0)
7558 (catch 'exit
7559 (while t
7560 (catch 'next
7561 (beginning-of-line 2)
7562 (if (eobp) (throw 'exit nil))
7563 (if (looking-at "[ \t]*$") (throw 'next nil))
7564 (skip-chars-forward " \t") (setq ind1 (current-column))
7565 (if (> ind1 ind) (throw 'next t))
7566 (if (< ind1 ind) (throw 'exit t))
7567 (if (not (org-at-item-p)) (throw 'exit nil))
7568 (skip-chars-forward " \t")
7569 (looking-at "\\S-+")
7570 (replace-match bullet))))
7571 (goto-line line)
7572 (move-to-column col)
7573 (if (string-match "[0-9]" bullet)
7574 (org-renumber-ordered-list 1))))
7576 (defun org-beginning-of-item-list ()
7577 "Go to the beginning of the current item list.
7578 I.e. to the first item in this list."
7579 (interactive)
7580 (org-beginning-of-item)
7581 (let ((pos (point-at-bol))
7582 (ind (org-get-indentation))
7583 ind1)
7584 ;; find where this list begins
7585 (catch 'exit
7586 (while t
7587 (catch 'next
7588 (beginning-of-line 0)
7589 (if (looking-at "[ \t]*$")
7590 (throw (if (bobp) 'exit 'next) t))
7591 (skip-chars-forward " \t") (setq ind1 (current-column))
7592 (if (or (< ind1 ind)
7593 (and (= ind1 ind)
7594 (not (org-at-item-p)))
7595 (bobp))
7596 (throw 'exit t)
7597 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7598 (goto-char pos)))
7601 (defun org-end-of-item-list ()
7602 "Go to the end of the current item list.
7603 I.e. to the text after the last item."
7604 (interactive)
7605 (org-beginning-of-item)
7606 (let ((pos (point-at-bol))
7607 (ind (org-get-indentation))
7608 ind1)
7609 ;; find where this list begins
7610 (catch 'exit
7611 (while t
7612 (catch 'next
7613 (beginning-of-line 2)
7614 (if (looking-at "[ \t]*$")
7615 (throw (if (eobp) 'exit 'next) t))
7616 (skip-chars-forward " \t") (setq ind1 (current-column))
7617 (if (or (< ind1 ind)
7618 (and (= ind1 ind)
7619 (not (org-at-item-p)))
7620 (eobp))
7621 (progn
7622 (setq pos (point-at-bol))
7623 (throw 'exit t))))))
7624 (goto-char pos)))
7627 (defvar org-last-indent-begin-marker (make-marker))
7628 (defvar org-last-indent-end-marker (make-marker))
7630 (defun org-outdent-item (arg)
7631 "Outdent a local list item."
7632 (interactive "p")
7633 (org-indent-item (- arg)))
7635 (defun org-indent-item (arg)
7636 "Indent a local list item."
7637 (interactive "p")
7638 (unless (org-at-item-p)
7639 (error "Not on an item"))
7640 (save-excursion
7641 (let (beg end ind ind1 tmp delta ind-down ind-up)
7642 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7643 (setq beg org-last-indent-begin-marker
7644 end org-last-indent-end-marker)
7645 (org-beginning-of-item)
7646 (setq beg (move-marker org-last-indent-begin-marker (point)))
7647 (org-end-of-item)
7648 (setq end (move-marker org-last-indent-end-marker (point))))
7649 (goto-char beg)
7650 (setq tmp (org-item-indent-positions)
7651 ind (car tmp)
7652 ind-down (nth 2 tmp)
7653 ind-up (nth 1 tmp)
7654 delta (if (> arg 0)
7655 (if ind-down (- ind-down ind) 2)
7656 (if ind-up (- ind-up ind) -2)))
7657 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7658 (while (< (point) end)
7659 (beginning-of-line 1)
7660 (skip-chars-forward " \t") (setq ind1 (current-column))
7661 (delete-region (point-at-bol) (point))
7662 (or (eolp) (indent-to-column (+ ind1 delta)))
7663 (beginning-of-line 2))))
7664 (org-fix-bullet-type)
7665 (org-maybe-renumber-ordered-list-safe)
7666 (save-excursion
7667 (beginning-of-line 0)
7668 (condition-case nil (org-beginning-of-item) (error nil))
7669 (org-maybe-renumber-ordered-list-safe)))
7671 (defun org-item-indent-positions ()
7672 "Return indentation for plain list items.
7673 This returns a list with three values: The current indentation, the
7674 parent indentation and the indentation a child should habe.
7675 Assumes cursor in item line."
7676 (let* ((bolpos (point-at-bol))
7677 (ind (org-get-indentation))
7678 ind-down ind-up pos)
7679 (save-excursion
7680 (org-beginning-of-item-list)
7681 (skip-chars-backward "\n\r \t")
7682 (when (org-in-item-p)
7683 (org-beginning-of-item)
7684 (setq ind-up (org-get-indentation))))
7685 (setq pos (point))
7686 (save-excursion
7687 (cond
7688 ((and (condition-case nil (progn (org-previous-item) t)
7689 (error nil))
7690 (or (forward-char 1) t)
7691 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7692 (setq ind-down (org-get-indentation)))
7693 ((and (goto-char pos)
7694 (org-at-item-p))
7695 (goto-char (match-end 0))
7696 (skip-chars-forward " \t")
7697 (setq ind-down (current-column)))))
7698 (list ind ind-up ind-down)))
7700 ;;; The orgstruct minor mode
7702 ;; Define a minor mode which can be used in other modes in order to
7703 ;; integrate the org-mode structure editing commands.
7705 ;; This is really a hack, because the org-mode structure commands use
7706 ;; keys which normally belong to the major mode. Here is how it
7707 ;; works: The minor mode defines all the keys necessary to operate the
7708 ;; structure commands, but wraps the commands into a function which
7709 ;; tests if the cursor is currently at a headline or a plain list
7710 ;; item. If that is the case, the structure command is used,
7711 ;; temporarily setting many Org-mode variables like regular
7712 ;; expressions for filling etc. However, when any of those keys is
7713 ;; used at a different location, function uses `key-binding' to look
7714 ;; up if the key has an associated command in another currently active
7715 ;; keymap (minor modes, major mode, global), and executes that
7716 ;; command. There might be problems if any of the keys is otherwise
7717 ;; used as a prefix key.
7719 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7720 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7721 ;; addresses this by checking explicitly for both bindings.
7723 (defvar orgstruct-mode-map (make-sparse-keymap)
7724 "Keymap for the minor `orgstruct-mode'.")
7726 (defvar org-local-vars nil
7727 "List of local variables, for use by `orgstruct-mode'")
7729 ;;;###autoload
7730 (define-minor-mode orgstruct-mode
7731 "Toggle the minor more `orgstruct-mode'.
7732 This mode is for using Org-mode structure commands in other modes.
7733 The following key behave as if Org-mode was active, if the cursor
7734 is on a headline, or on a plain list item (both in the definition
7735 of Org-mode).
7737 M-up Move entry/item up
7738 M-down Move entry/item down
7739 M-left Promote
7740 M-right Demote
7741 M-S-up Move entry/item up
7742 M-S-down Move entry/item down
7743 M-S-left Promote subtree
7744 M-S-right Demote subtree
7745 M-q Fill paragraph and items like in Org-mode
7746 C-c ^ Sort entries
7747 C-c - Cycle list bullet
7748 TAB Cycle item visibility
7749 M-RET Insert new heading/item
7750 S-M-RET Insert new TODO heading / Chekbox item
7751 C-c C-c Set tags / toggle checkbox"
7752 nil " OrgStruct" nil
7753 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7755 ;;;###autoload
7756 (defun turn-on-orgstruct ()
7757 "Unconditionally turn on `orgstruct-mode'."
7758 (orgstruct-mode 1))
7760 ;;;###autoload
7761 (defun turn-on-orgstruct++ ()
7762 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7763 In addition to setting orgstruct-mode, this also exports all indentation and
7764 autofilling variables from org-mode into the buffer. Note that turning
7765 off orgstruct-mode will *not* remove these additional settings."
7766 (orgstruct-mode 1)
7767 (let (var val)
7768 (mapc
7769 (lambda (x)
7770 (when (string-match
7771 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7772 (symbol-name (car x)))
7773 (setq var (car x) val (nth 1 x))
7774 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7775 org-local-vars)))
7777 (defun orgstruct-error ()
7778 "Error when there is no default binding for a structure key."
7779 (interactive)
7780 (error "This key has no function outside structure elements"))
7782 (defun orgstruct-setup ()
7783 "Setup orgstruct keymaps."
7784 (let ((nfunc 0)
7785 (bindings
7786 (list
7787 '([(meta up)] org-metaup)
7788 '([(meta down)] org-metadown)
7789 '([(meta left)] org-metaleft)
7790 '([(meta right)] org-metaright)
7791 '([(meta shift up)] org-shiftmetaup)
7792 '([(meta shift down)] org-shiftmetadown)
7793 '([(meta shift left)] org-shiftmetaleft)
7794 '([(meta shift right)] org-shiftmetaright)
7795 '([(shift up)] org-shiftup)
7796 '([(shift down)] org-shiftdown)
7797 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7798 '("\M-q" fill-paragraph)
7799 '("\C-c^" org-sort)
7800 '("\C-c-" org-cycle-list-bullet)))
7801 elt key fun cmd)
7802 (while (setq elt (pop bindings))
7803 (setq nfunc (1+ nfunc))
7804 (setq key (org-key (car elt))
7805 fun (nth 1 elt)
7806 cmd (orgstruct-make-binding fun nfunc key))
7807 (org-defkey orgstruct-mode-map key cmd))
7809 ;; Special treatment needed for TAB and RET
7810 (org-defkey orgstruct-mode-map [(tab)]
7811 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7812 (org-defkey orgstruct-mode-map "\C-i"
7813 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7815 (org-defkey orgstruct-mode-map "\M-\C-m"
7816 (orgstruct-make-binding 'org-insert-heading 105
7817 "\M-\C-m" [(meta return)]))
7818 (org-defkey orgstruct-mode-map [(meta return)]
7819 (orgstruct-make-binding 'org-insert-heading 106
7820 [(meta return)] "\M-\C-m"))
7822 (org-defkey orgstruct-mode-map [(shift meta return)]
7823 (orgstruct-make-binding 'org-insert-todo-heading 107
7824 [(meta return)] "\M-\C-m"))
7826 (unless org-local-vars
7827 (setq org-local-vars (org-get-local-variables)))
7831 (defun orgstruct-make-binding (fun n &rest keys)
7832 "Create a function for binding in the structure minor mode.
7833 FUN is the command to call inside a table. N is used to create a unique
7834 command name. KEYS are keys that should be checked in for a command
7835 to execute outside of tables."
7836 (eval
7837 (list 'defun
7838 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7839 '(arg)
7840 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7841 "Outside of structure, run the binding of `"
7842 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7843 "'.")
7844 '(interactive "p")
7845 (list 'if
7846 '(org-context-p 'headline 'item)
7847 (list 'org-run-like-in-org-mode (list 'quote fun))
7848 (list 'let '(orgstruct-mode)
7849 (list 'call-interactively
7850 (append '(or)
7851 (mapcar (lambda (k)
7852 (list 'key-binding k))
7853 keys)
7854 '('orgstruct-error))))))))
7856 (defun org-context-p (&rest contexts)
7857 "Check if local context is and of CONTEXTS.
7858 Possible values in the list of contexts are `table', `headline', and `item'."
7859 (let ((pos (point)))
7860 (goto-char (point-at-bol))
7861 (prog1 (or (and (memq 'table contexts)
7862 (looking-at "[ \t]*|"))
7863 (and (memq 'headline contexts)
7864 (looking-at "\\*+"))
7865 (and (memq 'item contexts)
7866 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
7867 (goto-char pos))))
7869 (defun org-get-local-variables ()
7870 "Return a list of all local variables in an org-mode buffer."
7871 (let (varlist)
7872 (with-current-buffer (get-buffer-create "*Org tmp*")
7873 (erase-buffer)
7874 (org-mode)
7875 (setq varlist (buffer-local-variables)))
7876 (kill-buffer "*Org tmp*")
7877 (delq nil
7878 (mapcar
7879 (lambda (x)
7880 (setq x
7881 (if (symbolp x)
7882 (list x)
7883 (list (car x) (list 'quote (cdr x)))))
7884 (if (string-match
7885 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7886 (symbol-name (car x)))
7887 x nil))
7888 varlist))))
7890 ;;;###autoload
7891 (defun org-run-like-in-org-mode (cmd)
7892 (unless org-local-vars
7893 (setq org-local-vars (org-get-local-variables)))
7894 (eval (list 'let org-local-vars
7895 (list 'call-interactively (list 'quote cmd)))))
7897 ;;;; Archiving
7899 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
7901 (defun org-archive-subtree (&optional find-done)
7902 "Move the current subtree to the archive.
7903 The archive can be a certain top-level heading in the current file, or in
7904 a different file. The tree will be moved to that location, the subtree
7905 heading be marked DONE, and the current time will be added.
7907 When called with prefix argument FIND-DONE, find whole trees without any
7908 open TODO items and archive them (after getting confirmation from the user).
7909 If the cursor is not at a headline when this comand is called, try all level
7910 1 trees. If the cursor is on a headline, only try the direct children of
7911 this heading."
7912 (interactive "P")
7913 (if find-done
7914 (org-archive-all-done)
7915 ;; Save all relevant TODO keyword-relatex variables
7917 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
7918 (tr-org-todo-keywords-1 org-todo-keywords-1)
7919 (tr-org-todo-kwd-alist org-todo-kwd-alist)
7920 (tr-org-done-keywords org-done-keywords)
7921 (tr-org-todo-regexp org-todo-regexp)
7922 (tr-org-todo-line-regexp org-todo-line-regexp)
7923 (tr-org-odd-levels-only org-odd-levels-only)
7924 (this-buffer (current-buffer))
7925 (org-archive-location org-archive-location)
7926 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
7927 ;; start of variables that will be used for saving context
7928 ;; The compiler complains about them - keep them anyway!
7929 (file (abbreviate-file-name (buffer-file-name)))
7930 (olpath (mapconcat 'identity (org-get-outline-path) "/"))
7931 (time (format-time-string
7932 (substring (cdr org-time-stamp-formats) 1 -1)
7933 (current-time)))
7934 afile heading buffer level newfile-p
7935 category todo priority
7936 ;; start of variables that will be used for savind context
7937 ltags itags prop)
7939 ;; Try to find a local archive location
7940 (save-excursion
7941 (save-restriction
7942 (widen)
7943 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
7944 (if (and prop (string-match "\\S-" prop))
7945 (setq org-archive-location prop)
7946 (if (or (re-search-backward re nil t)
7947 (re-search-forward re nil t))
7948 (setq org-archive-location (match-string 1))))))
7950 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
7951 (progn
7952 (setq afile (format (match-string 1 org-archive-location)
7953 (file-name-nondirectory buffer-file-name))
7954 heading (match-string 2 org-archive-location)))
7955 (error "Invalid `org-archive-location'"))
7956 (if (> (length afile) 0)
7957 (setq newfile-p (not (file-exists-p afile))
7958 buffer (find-file-noselect afile))
7959 (setq buffer (current-buffer)))
7960 (unless buffer
7961 (error "Cannot access file \"%s\"" afile))
7962 (if (and (> (length heading) 0)
7963 (string-match "^\\*+" heading))
7964 (setq level (match-end 0))
7965 (setq heading nil level 0))
7966 (save-excursion
7967 (org-back-to-heading t)
7968 ;; Get context information that will be lost by moving the tree
7969 (org-refresh-category-properties)
7970 (setq category (org-get-category)
7971 todo (and (looking-at org-todo-line-regexp)
7972 (match-string 2))
7973 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
7974 ltags (org-get-tags)
7975 itags (org-delete-all ltags (org-get-tags-at)))
7976 (setq ltags (mapconcat 'identity ltags " ")
7977 itags (mapconcat 'identity itags " "))
7978 ;; We first only copy, in case something goes wrong
7979 ;; we need to protect this-command, to avoid kill-region sets it,
7980 ;; which would lead to duplication of subtrees
7981 (let (this-command) (org-copy-subtree))
7982 (set-buffer buffer)
7983 ;; Enforce org-mode for the archive buffer
7984 (if (not (org-mode-p))
7985 ;; Force the mode for future visits.
7986 (let ((org-insert-mode-line-in-empty-file t)
7987 (org-inhibit-startup t))
7988 (call-interactively 'org-mode)))
7989 (when newfile-p
7990 (goto-char (point-max))
7991 (insert (format "\nArchived entries from file %s\n\n"
7992 (buffer-file-name this-buffer))))
7993 ;; Force the TODO keywords of the original buffer
7994 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
7995 (org-todo-keywords-1 tr-org-todo-keywords-1)
7996 (org-todo-kwd-alist tr-org-todo-kwd-alist)
7997 (org-done-keywords tr-org-done-keywords)
7998 (org-todo-regexp tr-org-todo-regexp)
7999 (org-todo-line-regexp tr-org-todo-line-regexp)
8000 (org-odd-levels-only
8001 (if (local-variable-p 'org-odd-levels-only (current-buffer))
8002 org-odd-levels-only
8003 tr-org-odd-levels-only)))
8004 (goto-char (point-min))
8005 (if heading
8006 (progn
8007 (if (re-search-forward
8008 (concat "^" (regexp-quote heading)
8009 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
8010 nil t)
8011 (goto-char (match-end 0))
8012 ;; Heading not found, just insert it at the end
8013 (goto-char (point-max))
8014 (or (bolp) (insert "\n"))
8015 (insert "\n" heading "\n")
8016 (end-of-line 0))
8017 ;; Make the subtree visible
8018 (show-subtree)
8019 (org-end-of-subtree t)
8020 (skip-chars-backward " \t\r\n")
8021 (and (looking-at "[ \t\r\n]*")
8022 (replace-match "\n\n")))
8023 ;; No specific heading, just go to end of file.
8024 (goto-char (point-max)) (insert "\n"))
8025 ;; Paste
8026 (org-paste-subtree (org-get-legal-level level 1))
8028 ;; Mark the entry as done
8029 (when (and org-archive-mark-done
8030 (looking-at org-todo-line-regexp)
8031 (or (not (match-end 2))
8032 (not (member (match-string 2) org-done-keywords))))
8033 (let (org-log-done org-todo-log-states)
8034 (org-todo
8035 (car (or (member org-archive-mark-done org-done-keywords)
8036 org-done-keywords)))))
8038 ;; Add the context info
8039 (when org-archive-save-context-info
8040 (let ((l org-archive-save-context-info) e n v)
8041 (while (setq e (pop l))
8042 (when (and (setq v (symbol-value e))
8043 (stringp v) (string-match "\\S-" v))
8044 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
8045 (org-entry-put (point) n v)))))
8047 ;; Save the buffer, if it is not the same buffer.
8048 (if (not (eq this-buffer buffer)) (save-buffer))))
8049 ;; Here we are back in the original buffer. Everything seems to have
8050 ;; worked. So now cut the tree and finish up.
8051 (let (this-command) (org-cut-subtree))
8052 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
8053 (message "Subtree archived %s"
8054 (if (eq this-buffer buffer)
8055 (concat "under heading: " heading)
8056 (concat "in file: " (abbreviate-file-name afile)))))))
8058 (defun org-refresh-category-properties ()
8059 "Refresh category text properties in teh buffer."
8060 (let ((def-cat (cond
8061 ((null org-category)
8062 (if buffer-file-name
8063 (file-name-sans-extension
8064 (file-name-nondirectory buffer-file-name))
8065 "???"))
8066 ((symbolp org-category) (symbol-name org-category))
8067 (t org-category)))
8068 beg end cat pos optionp)
8069 (org-unmodified
8070 (save-excursion
8071 (save-restriction
8072 (widen)
8073 (goto-char (point-min))
8074 (put-text-property (point) (point-max) 'org-category def-cat)
8075 (while (re-search-forward
8076 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8077 (setq pos (match-end 0)
8078 optionp (equal (char-after (match-beginning 0)) ?#)
8079 cat (org-trim (match-string 2)))
8080 (if optionp
8081 (setq beg (point-at-bol) end (point-max))
8082 (org-back-to-heading t)
8083 (setq beg (point) end (org-end-of-subtree t t)))
8084 (put-text-property beg end 'org-category cat)
8085 (goto-char pos)))))))
8087 (defun org-archive-all-done (&optional tag)
8088 "Archive sublevels of the current tree without open TODO items.
8089 If the cursor is not on a headline, try all level 1 trees. If
8090 it is on a headline, try all direct children.
8091 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
8092 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
8093 (rea (concat ".*:" org-archive-tag ":"))
8094 (begm (make-marker))
8095 (endm (make-marker))
8096 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
8097 "Move subtree to archive (no open TODO items)? "))
8098 beg end (cntarch 0))
8099 (if (org-on-heading-p)
8100 (progn
8101 (setq re1 (concat "^" (regexp-quote
8102 (make-string
8103 (1+ (- (match-end 0) (match-beginning 0) 1))
8104 ?*))
8105 " "))
8106 (move-marker begm (point))
8107 (move-marker endm (org-end-of-subtree t)))
8108 (setq re1 "^* ")
8109 (move-marker begm (point-min))
8110 (move-marker endm (point-max)))
8111 (save-excursion
8112 (goto-char begm)
8113 (while (re-search-forward re1 endm t)
8114 (setq beg (match-beginning 0)
8115 end (save-excursion (org-end-of-subtree t) (point)))
8116 (goto-char beg)
8117 (if (re-search-forward re end t)
8118 (goto-char end)
8119 (goto-char beg)
8120 (if (and (or (not tag) (not (looking-at rea)))
8121 (y-or-n-p question))
8122 (progn
8123 (if tag
8124 (org-toggle-tag org-archive-tag 'on)
8125 (org-archive-subtree))
8126 (setq cntarch (1+ cntarch)))
8127 (goto-char end)))))
8128 (message "%d trees archived" cntarch)))
8130 (defun org-cycle-hide-drawers (state)
8131 "Re-hide all drawers after a visibility state change."
8132 (when (and (org-mode-p)
8133 (not (memq state '(overview folded))))
8134 (save-excursion
8135 (let* ((globalp (memq state '(contents all)))
8136 (beg (if globalp (point-min) (point)))
8137 (end (if globalp (point-max) (org-end-of-subtree t))))
8138 (goto-char beg)
8139 (while (re-search-forward org-drawer-regexp end t)
8140 (org-flag-drawer t))))))
8142 (defun org-flag-drawer (flag)
8143 (save-excursion
8144 (beginning-of-line 1)
8145 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
8146 (let ((b (match-end 0))
8147 (outline-regexp org-outline-regexp))
8148 (if (re-search-forward
8149 "^[ \t]*:END:"
8150 (save-excursion (outline-next-heading) (point)) t)
8151 (outline-flag-region b (point-at-eol) flag)
8152 (error ":END: line missing"))))))
8154 (defun org-cycle-hide-archived-subtrees (state)
8155 "Re-hide all archived subtrees after a visibility state change."
8156 (when (and (not org-cycle-open-archived-trees)
8157 (not (memq state '(overview folded))))
8158 (save-excursion
8159 (let* ((globalp (memq state '(contents all)))
8160 (beg (if globalp (point-min) (point)))
8161 (end (if globalp (point-max) (org-end-of-subtree t))))
8162 (org-hide-archived-subtrees beg end)
8163 (goto-char beg)
8164 (if (looking-at (concat ".*:" org-archive-tag ":"))
8165 (message "%s" (substitute-command-keys
8166 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
8168 (defun org-force-cycle-archived ()
8169 "Cycle subtree even if it is archived."
8170 (interactive)
8171 (setq this-command 'org-cycle)
8172 (let ((org-cycle-open-archived-trees t))
8173 (call-interactively 'org-cycle)))
8175 (defun org-hide-archived-subtrees (beg end)
8176 "Re-hide all archived subtrees after a visibility state change."
8177 (save-excursion
8178 (let* ((re (concat ":" org-archive-tag ":")))
8179 (goto-char beg)
8180 (while (re-search-forward re end t)
8181 (and (org-on-heading-p) (hide-subtree))
8182 (org-end-of-subtree t)))))
8184 (defun org-toggle-tag (tag &optional onoff)
8185 "Toggle the tag TAG for the current line.
8186 If ONOFF is `on' or `off', don't toggle but set to this state."
8187 (unless (org-on-heading-p t) (error "Not on headling"))
8188 (let (res current)
8189 (save-excursion
8190 (beginning-of-line)
8191 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8192 (point-at-eol) t)
8193 (progn
8194 (setq current (match-string 1))
8195 (replace-match ""))
8196 (setq current ""))
8197 (setq current (nreverse (org-split-string current ":")))
8198 (cond
8199 ((eq onoff 'on)
8200 (setq res t)
8201 (or (member tag current) (push tag current)))
8202 ((eq onoff 'off)
8203 (or (not (member tag current)) (setq current (delete tag current))))
8204 (t (if (member tag current)
8205 (setq current (delete tag current))
8206 (setq res t)
8207 (push tag current))))
8208 (end-of-line 1)
8209 (if current
8210 (progn
8211 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8212 (org-set-tags nil t))
8213 (delete-horizontal-space))
8214 (run-hooks 'org-after-tags-change-hook))
8215 res))
8217 (defun org-toggle-archive-tag (&optional arg)
8218 "Toggle the archive tag for the current headline.
8219 With prefix ARG, check all children of current headline and offer tagging
8220 the children that do not contain any open TODO items."
8221 (interactive "P")
8222 (if arg
8223 (org-archive-all-done 'tag)
8224 (let (set)
8225 (save-excursion
8226 (org-back-to-heading t)
8227 (setq set (org-toggle-tag org-archive-tag))
8228 (when set (hide-subtree)))
8229 (and set (beginning-of-line 1))
8230 (message "Subtree %s" (if set "archived" "unarchived")))))
8233 ;;;; Tables
8235 ;;; The table editor
8237 ;; Watch out: Here we are talking about two different kind of tables.
8238 ;; Most of the code is for the tables created with the Org-mode table editor.
8239 ;; Sometimes, we talk about tables created and edited with the table.el
8240 ;; Emacs package. We call the former org-type tables, and the latter
8241 ;; table.el-type tables.
8243 (defun org-before-change-function (beg end)
8244 "Every change indicates that a table might need an update."
8245 (setq org-table-may-need-update t))
8247 (defconst org-table-line-regexp "^[ \t]*|"
8248 "Detects an org-type table line.")
8249 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8250 "Detects an org-type table line.")
8251 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8252 "Detects a table line marked for automatic recalculation.")
8253 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8254 "Detects a table line marked for automatic recalculation.")
8255 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8256 "Detects a table line marked for automatic recalculation.")
8257 (defconst org-table-hline-regexp "^[ \t]*|-"
8258 "Detects an org-type table hline.")
8259 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8260 "Detects a table-type table hline.")
8261 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8262 "Detects an org-type or table-type table.")
8263 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8264 "Searching from within a table (any type) this finds the first line
8265 outside the table.")
8266 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8267 "Searching from within a table (any type) this finds the first line
8268 outside the table.")
8270 (defvar org-table-last-highlighted-reference nil)
8271 (defvar org-table-formula-history nil)
8273 (defvar org-table-column-names nil
8274 "Alist with column names, derived from the `!' line.")
8275 (defvar org-table-column-name-regexp nil
8276 "Regular expression matching the current column names.")
8277 (defvar org-table-local-parameters nil
8278 "Alist with parameter names, derived from the `$' line.")
8279 (defvar org-table-named-field-locations nil
8280 "Alist with locations of named fields.")
8282 (defvar org-table-current-line-types nil
8283 "Table row types, non-nil only for the duration of a comand.")
8284 (defvar org-table-current-begin-line nil
8285 "Table begin line, non-nil only for the duration of a comand.")
8286 (defvar org-table-current-begin-pos nil
8287 "Table begin position, non-nil only for the duration of a comand.")
8288 (defvar org-table-dlines nil
8289 "Vector of data line line numbers in the current table.")
8290 (defvar org-table-hlines nil
8291 "Vector of hline line numbers in the current table.")
8293 (defconst org-table-range-regexp
8294 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
8295 ;; 1 2 3 4 5
8296 "Regular expression for matching ranges in formulas.")
8298 (defconst org-table-range-regexp2
8299 (concat
8300 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
8301 "\\.\\."
8302 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8303 "Match a range for reference display.")
8305 (defconst org-table-translate-regexp
8306 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8307 "Match a reference that needs translation, for reference display.")
8309 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8311 (defun org-table-create-with-table.el ()
8312 "Use the table.el package to insert a new table.
8313 If there is already a table at point, convert between Org-mode tables
8314 and table.el tables."
8315 (interactive)
8316 (require 'table)
8317 (cond
8318 ((org-at-table.el-p)
8319 (if (y-or-n-p "Convert table to Org-mode table? ")
8320 (org-table-convert)))
8321 ((org-at-table-p)
8322 (if (y-or-n-p "Convert table to table.el table? ")
8323 (org-table-convert)))
8324 (t (call-interactively 'table-insert))))
8326 (defun org-table-create-or-convert-from-region (arg)
8327 "Convert region to table, or create an empty table.
8328 If there is an active region, convert it to a table, using the function
8329 `org-table-convert-region'. See the documentation of that function
8330 to learn how the prefix argument is interpreted to determine the field
8331 separator.
8332 If there is no such region, create an empty table with `org-table-create'."
8333 (interactive "P")
8334 (if (org-region-active-p)
8335 (org-table-convert-region (region-beginning) (region-end) arg)
8336 (org-table-create arg)))
8338 (defun org-table-create (&optional size)
8339 "Query for a size and insert a table skeleton.
8340 SIZE is a string Columns x Rows like for example \"3x2\"."
8341 (interactive "P")
8342 (unless size
8343 (setq size (read-string
8344 (concat "Table size Columns x Rows [e.g. "
8345 org-table-default-size "]: ")
8346 "" nil org-table-default-size)))
8348 (let* ((pos (point))
8349 (indent (make-string (current-column) ?\ ))
8350 (split (org-split-string size " *x *"))
8351 (rows (string-to-number (nth 1 split)))
8352 (columns (string-to-number (car split)))
8353 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8354 "\n")))
8355 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8356 (point-at-bol) (point)))
8357 (beginning-of-line 1)
8358 (newline))
8359 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8360 (dotimes (i rows) (insert line))
8361 (goto-char pos)
8362 (if (> rows 1)
8363 ;; Insert a hline after the first row.
8364 (progn
8365 (end-of-line 1)
8366 (insert "\n|-")
8367 (goto-char pos)))
8368 (org-table-align)))
8370 (defun org-table-convert-region (beg0 end0 &optional separator)
8371 "Convert region to a table.
8372 The region goes from BEG0 to END0, but these borders will be moved
8373 slightly, to make sure a beginning of line in the first line is included.
8375 SEPARATOR specifies the field separator in the lines. It can have the
8376 following values:
8378 '(4) Use the comma as a field separator
8379 '(16) Use a TAB as field separator
8380 integer When a number, use that many spaces as field separator
8381 nil When nil, the command tries to be smart and figure out the
8382 separator in the following way:
8383 - when each line contains a TAB, assume TAB-separated material
8384 - when each line contains a comme, assume CSV material
8385 - else, assume one or more SPACE charcters as separator."
8386 (interactive "rP")
8387 (let* ((beg (min beg0 end0))
8388 (end (max beg0 end0))
8390 (goto-char beg)
8391 (beginning-of-line 1)
8392 (setq beg (move-marker (make-marker) (point)))
8393 (goto-char end)
8394 (if (bolp) (backward-char 1) (end-of-line 1))
8395 (setq end (move-marker (make-marker) (point)))
8396 ;; Get the right field separator
8397 (unless separator
8398 (goto-char beg)
8399 (setq separator
8400 (cond
8401 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8402 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8403 (t 1))))
8404 (setq re (cond
8405 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8406 ((equal separator '(16)) "^\\|\t")
8407 ((integerp separator)
8408 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8409 (t (error "This should not happen"))))
8410 (goto-char beg)
8411 (while (re-search-forward re end t)
8412 (replace-match "| " t t))
8413 (goto-char beg)
8414 (insert " ")
8415 (org-table-align)))
8417 (defun org-table-import (file arg)
8418 "Import FILE as a table.
8419 The file is assumed to be tab-separated. Such files can be produced by most
8420 spreadsheet and database applications. If no tabs (at least one per line)
8421 are found, lines will be split on whitespace into fields."
8422 (interactive "f\nP")
8423 (or (bolp) (newline))
8424 (let ((beg (point))
8425 (pm (point-max)))
8426 (insert-file-contents file)
8427 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8429 (defun org-table-export ()
8430 "Export table as a tab-separated file.
8431 Such a file can be imported into a spreadsheet program like Excel."
8432 (interactive)
8433 (let* ((beg (org-table-begin))
8434 (end (org-table-end))
8435 (table (buffer-substring beg end))
8436 (file (read-file-name "Export table to: "))
8437 buf)
8438 (unless (or (not (file-exists-p file))
8439 (y-or-n-p (format "Overwrite file %s? " file)))
8440 (error "Abort"))
8441 (with-current-buffer (find-file-noselect file)
8442 (setq buf (current-buffer))
8443 (erase-buffer)
8444 (fundamental-mode)
8445 (insert table)
8446 (goto-char (point-min))
8447 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8448 (replace-match "" t t)
8449 (end-of-line 1))
8450 (goto-char (point-min))
8451 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8452 (replace-match "" t t)
8453 (goto-char (min (1+ (point)) (point-max))))
8454 (goto-char (point-min))
8455 (while (re-search-forward "^-[-+]*$" nil t)
8456 (replace-match "")
8457 (if (looking-at "\n")
8458 (delete-char 1)))
8459 (goto-char (point-min))
8460 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8461 (replace-match "\t" t t))
8462 (save-buffer))
8463 (kill-buffer buf)))
8465 (defvar org-table-aligned-begin-marker (make-marker)
8466 "Marker at the beginning of the table last aligned.
8467 Used to check if cursor still is in that table, to minimize realignment.")
8468 (defvar org-table-aligned-end-marker (make-marker)
8469 "Marker at the end of the table last aligned.
8470 Used to check if cursor still is in that table, to minimize realignment.")
8471 (defvar org-table-last-alignment nil
8472 "List of flags for flushright alignment, from the last re-alignment.
8473 This is being used to correctly align a single field after TAB or RET.")
8474 (defvar org-table-last-column-widths nil
8475 "List of max width of fields in each column.
8476 This is being used to correctly align a single field after TAB or RET.")
8477 (defvar org-table-overlay-coordinates nil
8478 "Overlay coordinates after each align of a table.")
8479 (make-variable-buffer-local 'org-table-overlay-coordinates)
8481 (defvar org-last-recalc-line nil)
8482 (defconst org-narrow-column-arrow "=>"
8483 "Used as display property in narrowed table columns.")
8485 (defun org-table-align ()
8486 "Align the table at point by aligning all vertical bars."
8487 (interactive)
8488 (let* (
8489 ;; Limits of table
8490 (beg (org-table-begin))
8491 (end (org-table-end))
8492 ;; Current cursor position
8493 (linepos (org-current-line))
8494 (colpos (org-table-current-column))
8495 (winstart (window-start))
8496 (winstartline (org-current-line (min winstart (1- (point-max)))))
8497 lines (new "") lengths l typenums ty fields maxfields i
8498 column
8499 (indent "") cnt frac
8500 rfmt hfmt
8501 (spaces '(1 . 1))
8502 (sp1 (car spaces))
8503 (sp2 (cdr spaces))
8504 (rfmt1 (concat
8505 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8506 (hfmt1 (concat
8507 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8508 emptystrings links dates emph narrow fmax f1 len c e)
8509 (untabify beg end)
8510 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8511 ;; Check if we have links or dates
8512 (goto-char beg)
8513 (setq links (re-search-forward org-bracket-link-regexp end t))
8514 (goto-char beg)
8515 (setq emph (and org-hide-emphasis-markers
8516 (re-search-forward org-emph-re end t)))
8517 (goto-char beg)
8518 (setq dates (and org-display-custom-times
8519 (re-search-forward org-ts-regexp-both end t)))
8520 ;; Make sure the link properties are right
8521 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8522 ;; Make sure the date properties are right
8523 (when dates (goto-char beg) (while (org-activate-dates end)))
8524 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8526 ;; Check if we are narrowing any columns
8527 (goto-char beg)
8528 (setq narrow (and org-format-transports-properties-p
8529 (re-search-forward "<[0-9]+>" end t)))
8530 ;; Get the rows
8531 (setq lines (org-split-string
8532 (buffer-substring beg end) "\n"))
8533 ;; Store the indentation of the first line
8534 (if (string-match "^ *" (car lines))
8535 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8536 ;; Mark the hlines by setting the corresponding element to nil
8537 ;; At the same time, we remove trailing space.
8538 (setq lines (mapcar (lambda (l)
8539 (if (string-match "^ *|-" l)
8541 (if (string-match "[ \t]+$" l)
8542 (substring l 0 (match-beginning 0))
8543 l)))
8544 lines))
8545 ;; Get the data fields by splitting the lines.
8546 (setq fields (mapcar
8547 (lambda (l)
8548 (org-split-string l " *| *"))
8549 (delq nil (copy-sequence lines))))
8550 ;; How many fields in the longest line?
8551 (condition-case nil
8552 (setq maxfields (apply 'max (mapcar 'length fields)))
8553 (error
8554 (kill-region beg end)
8555 (org-table-create org-table-default-size)
8556 (error "Empty table - created default table")))
8557 ;; A list of empty strings to fill any short rows on output
8558 (setq emptystrings (make-list maxfields ""))
8559 ;; Check for special formatting.
8560 (setq i -1)
8561 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8562 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8563 ;; Check if there is an explicit width specified
8564 (when narrow
8565 (setq c column fmax nil)
8566 (while c
8567 (setq e (pop c))
8568 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8569 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8570 ;; Find fields that are wider than fmax, and shorten them
8571 (when fmax
8572 (loop for xx in column do
8573 (when (and (stringp xx)
8574 (> (org-string-width xx) fmax))
8575 (org-add-props xx nil
8576 'help-echo
8577 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8578 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8579 (unless (> f1 1)
8580 (error "Cannot narrow field starting with wide link \"%s\""
8581 (match-string 0 xx)))
8582 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8583 (add-text-properties (- f1 2) f1
8584 (list 'display org-narrow-column-arrow)
8585 xx)))))
8586 ;; Get the maximum width for each column
8587 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8588 ;; Get the fraction of numbers, to decide about alignment of the column
8589 (setq cnt 0 frac 0.0)
8590 (loop for x in column do
8591 (if (equal x "")
8593 (setq frac ( / (+ (* frac cnt)
8594 (if (string-match org-table-number-regexp x) 1 0))
8595 (setq cnt (1+ cnt))))))
8596 (push (>= frac org-table-number-fraction) typenums))
8597 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8599 ;; Store the alignment of this table, for later editing of single fields
8600 (setq org-table-last-alignment typenums
8601 org-table-last-column-widths lengths)
8603 ;; With invisible characters, `format' does not get the field width right
8604 ;; So we need to make these fields wide by hand.
8605 (when (or links emph)
8606 (loop for i from 0 upto (1- maxfields) do
8607 (setq len (nth i lengths))
8608 (loop for j from 0 upto (1- (length fields)) do
8609 (setq c (nthcdr i (car (nthcdr j fields))))
8610 (if (and (stringp (car c))
8611 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8612 ; (string-match org-bracket-link-regexp (car c))
8613 (< (org-string-width (car c)) len))
8614 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8616 ;; Compute the formats needed for output of the table
8617 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8618 (while (setq l (pop lengths))
8619 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8620 (setq rfmt (concat rfmt (format rfmt1 ty l))
8621 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8622 (setq rfmt (concat rfmt "\n")
8623 hfmt (concat (substring hfmt 0 -1) "|\n"))
8625 (setq new (mapconcat
8626 (lambda (l)
8627 (if l (apply 'format rfmt
8628 (append (pop fields) emptystrings))
8629 hfmt))
8630 lines ""))
8631 ;; Replace the old one
8632 (delete-region beg end)
8633 (move-marker end nil)
8634 (move-marker org-table-aligned-begin-marker (point))
8635 (insert new)
8636 (move-marker org-table-aligned-end-marker (point))
8637 (when (and orgtbl-mode (not (org-mode-p)))
8638 (goto-char org-table-aligned-begin-marker)
8639 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8640 ;; Try to move to the old location
8641 (goto-line winstartline)
8642 (setq winstart (point-at-bol))
8643 (goto-line linepos)
8644 (set-window-start (selected-window) winstart 'noforce)
8645 (org-table-goto-column colpos)
8646 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8647 (setq org-table-may-need-update nil)
8650 (defun org-string-width (s)
8651 "Compute width of string, ignoring invisible characters.
8652 This ignores character with invisibility property `org-link', and also
8653 characters with property `org-cwidth', because these will become invisible
8654 upon the next fontification round."
8655 (let (b l)
8656 (when (or (eq t buffer-invisibility-spec)
8657 (assq 'org-link buffer-invisibility-spec))
8658 (while (setq b (text-property-any 0 (length s)
8659 'invisible 'org-link s))
8660 (setq s (concat (substring s 0 b)
8661 (substring s (or (next-single-property-change
8662 b 'invisible s) (length s)))))))
8663 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8664 (setq s (concat (substring s 0 b)
8665 (substring s (or (next-single-property-change
8666 b 'org-cwidth s) (length s))))))
8667 (setq l (string-width s) b -1)
8668 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8669 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8672 (defun org-table-begin (&optional table-type)
8673 "Find the beginning of the table and return its position.
8674 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8675 (save-excursion
8676 (if (not (re-search-backward
8677 (if table-type org-table-any-border-regexp
8678 org-table-border-regexp)
8679 nil t))
8680 (progn (goto-char (point-min)) (point))
8681 (goto-char (match-beginning 0))
8682 (beginning-of-line 2)
8683 (point))))
8685 (defun org-table-end (&optional table-type)
8686 "Find the end of the table and return its position.
8687 With argument TABLE-TYPE, go to the end of a table.el-type table."
8688 (save-excursion
8689 (if (not (re-search-forward
8690 (if table-type org-table-any-border-regexp
8691 org-table-border-regexp)
8692 nil t))
8693 (goto-char (point-max))
8694 (goto-char (match-beginning 0)))
8695 (point-marker)))
8697 (defun org-table-justify-field-maybe (&optional new)
8698 "Justify the current field, text to left, number to right.
8699 Optional argument NEW may specify text to replace the current field content."
8700 (cond
8701 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8702 ((org-at-table-hline-p))
8703 ((and (not new)
8704 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8705 (current-buffer)))
8706 (< (point) org-table-aligned-begin-marker)
8707 (>= (point) org-table-aligned-end-marker)))
8708 ;; This is not the same table, force a full re-align
8709 (setq org-table-may-need-update t))
8710 (t ;; realign the current field, based on previous full realign
8711 (let* ((pos (point)) s
8712 (col (org-table-current-column))
8713 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8714 l f n o e)
8715 (when (> col 0)
8716 (skip-chars-backward "^|\n")
8717 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8718 (progn
8719 (setq s (match-string 1)
8720 o (match-string 0)
8721 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8722 e (not (= (match-beginning 2) (match-end 2))))
8723 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8724 l (if e "|" (setq org-table-may-need-update t) ""))
8725 n (format f s))
8726 (if new
8727 (if (<= (length new) l) ;; FIXME: length -> str-width?
8728 (setq n (format f new))
8729 (setq n (concat new "|") org-table-may-need-update t)))
8730 (or (equal n o)
8731 (let (org-table-may-need-update)
8732 (replace-match n t t))))
8733 (setq org-table-may-need-update t))
8734 (goto-char pos))))))
8736 (defun org-table-next-field ()
8737 "Go to the next field in the current table, creating new lines as needed.
8738 Before doing so, re-align the table if necessary."
8739 (interactive)
8740 (org-table-maybe-eval-formula)
8741 (org-table-maybe-recalculate-line)
8742 (if (and org-table-automatic-realign
8743 org-table-may-need-update)
8744 (org-table-align))
8745 (let ((end (org-table-end)))
8746 (if (org-at-table-hline-p)
8747 (end-of-line 1))
8748 (condition-case nil
8749 (progn
8750 (re-search-forward "|" end)
8751 (if (looking-at "[ \t]*$")
8752 (re-search-forward "|" end))
8753 (if (and (looking-at "-")
8754 org-table-tab-jumps-over-hlines
8755 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8756 (goto-char (match-beginning 1)))
8757 (if (looking-at "-")
8758 (progn
8759 (beginning-of-line 0)
8760 (org-table-insert-row 'below))
8761 (if (looking-at " ") (forward-char 1))))
8762 (error
8763 (org-table-insert-row 'below)))))
8765 (defun org-table-previous-field ()
8766 "Go to the previous field in the table.
8767 Before doing so, re-align the table if necessary."
8768 (interactive)
8769 (org-table-justify-field-maybe)
8770 (org-table-maybe-recalculate-line)
8771 (if (and org-table-automatic-realign
8772 org-table-may-need-update)
8773 (org-table-align))
8774 (if (org-at-table-hline-p)
8775 (end-of-line 1))
8776 (re-search-backward "|" (org-table-begin))
8777 (re-search-backward "|" (org-table-begin))
8778 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8779 (re-search-backward "|" (org-table-begin)))
8780 (if (looking-at "| ?")
8781 (goto-char (match-end 0))))
8783 (defun org-table-next-row ()
8784 "Go to the next row (same column) in the current table.
8785 Before doing so, re-align the table if necessary."
8786 (interactive)
8787 (org-table-maybe-eval-formula)
8788 (org-table-maybe-recalculate-line)
8789 (if (or (looking-at "[ \t]*$")
8790 (save-excursion (skip-chars-backward " \t") (bolp)))
8791 (newline)
8792 (if (and org-table-automatic-realign
8793 org-table-may-need-update)
8794 (org-table-align))
8795 (let ((col (org-table-current-column)))
8796 (beginning-of-line 2)
8797 (if (or (not (org-at-table-p))
8798 (org-at-table-hline-p))
8799 (progn
8800 (beginning-of-line 0)
8801 (org-table-insert-row 'below)))
8802 (org-table-goto-column col)
8803 (skip-chars-backward "^|\n\r")
8804 (if (looking-at " ") (forward-char 1)))))
8806 (defun org-table-copy-down (n)
8807 "Copy a field down in the current column.
8808 If the field at the cursor is empty, copy into it the content of the nearest
8809 non-empty field above. With argument N, use the Nth non-empty field.
8810 If the current field is not empty, it is copied down to the next row, and
8811 the cursor is moved with it. Therefore, repeating this command causes the
8812 column to be filled row-by-row.
8813 If the variable `org-table-copy-increment' is non-nil and the field is an
8814 integer or a timestamp, it will be incremented while copying. In the case of
8815 a timestamp, if the cursor is on the year, change the year. If it is on the
8816 month or the day, change that. Point will stay on the current date field
8817 in order to easily repeat the interval."
8818 (interactive "p")
8819 (let* ((colpos (org-table-current-column))
8820 (col (current-column))
8821 (field (org-table-get-field))
8822 (non-empty (string-match "[^ \t]" field))
8823 (beg (org-table-begin))
8824 txt)
8825 (org-table-check-inside-data-field)
8826 (if non-empty
8827 (progn
8828 (setq txt (org-trim field))
8829 (org-table-next-row)
8830 (org-table-blank-field))
8831 (save-excursion
8832 (setq txt
8833 (catch 'exit
8834 (while (progn (beginning-of-line 1)
8835 (re-search-backward org-table-dataline-regexp
8836 beg t))
8837 (org-table-goto-column colpos t)
8838 (if (and (looking-at
8839 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8840 (= (setq n (1- n)) 0))
8841 (throw 'exit (match-string 1))))))))
8842 (if txt
8843 (progn
8844 (if (and org-table-copy-increment
8845 (string-match "^[0-9]+$" txt))
8846 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8847 (insert txt)
8848 (move-to-column col)
8849 (if (and org-table-copy-increment (org-at-timestamp-p t))
8850 (org-timestamp-up 1)
8851 (org-table-maybe-recalculate-line))
8852 (org-table-align)
8853 (move-to-column col))
8854 (error "No non-empty field found"))))
8856 (defun org-table-check-inside-data-field ()
8857 "Is point inside a table data field?
8858 I.e. not on a hline or before the first or after the last column?
8859 This actually throws an error, so it aborts the current command."
8860 (if (or (not (org-at-table-p))
8861 (= (org-table-current-column) 0)
8862 (org-at-table-hline-p)
8863 (looking-at "[ \t]*$"))
8864 (error "Not in table data field")))
8866 (defvar org-table-clip nil
8867 "Clipboard for table regions.")
8869 (defun org-table-blank-field ()
8870 "Blank the current table field or active region."
8871 (interactive)
8872 (org-table-check-inside-data-field)
8873 (if (and (interactive-p) (org-region-active-p))
8874 (let (org-table-clip)
8875 (org-table-cut-region (region-beginning) (region-end)))
8876 (skip-chars-backward "^|")
8877 (backward-char 1)
8878 (if (looking-at "|[^|\n]+")
8879 (let* ((pos (match-beginning 0))
8880 (match (match-string 0))
8881 (len (org-string-width match)))
8882 (replace-match (concat "|" (make-string (1- len) ?\ )))
8883 (goto-char (+ 2 pos))
8884 (substring match 1)))))
8886 (defun org-table-get-field (&optional n replace)
8887 "Return the value of the field in column N of current row.
8888 N defaults to current field.
8889 If REPLACE is a string, replace field with this value. The return value
8890 is always the old value."
8891 (and n (org-table-goto-column n))
8892 (skip-chars-backward "^|\n")
8893 (backward-char 1)
8894 (if (looking-at "|[^|\r\n]*")
8895 (let* ((pos (match-beginning 0))
8896 (val (buffer-substring (1+ pos) (match-end 0))))
8897 (if replace
8898 (replace-match (concat "|" replace) t t))
8899 (goto-char (min (point-at-eol) (+ 2 pos)))
8900 val)
8901 (forward-char 1) ""))
8903 (defun org-table-field-info (arg)
8904 "Show info about the current field, and highlight any reference at point."
8905 (interactive "P")
8906 (org-table-get-specials)
8907 (save-excursion
8908 (let* ((pos (point))
8909 (col (org-table-current-column))
8910 (cname (car (rassoc (int-to-string col) org-table-column-names)))
8911 (name (car (rassoc (list (org-current-line) col)
8912 org-table-named-field-locations)))
8913 (eql (org-table-get-stored-formulas))
8914 (dline (org-table-current-dline))
8915 (ref (format "@%d$%d" dline col))
8916 (ref1 (org-table-convert-refs-to-an ref))
8917 (fequation (or (assoc name eql) (assoc ref eql)))
8918 (cequation (assoc (int-to-string col) eql))
8919 (eqn (or fequation cequation)))
8920 (goto-char pos)
8921 (condition-case nil
8922 (org-table-show-reference 'local)
8923 (error nil))
8924 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
8925 dline col
8926 (if cname (concat " or $" cname) "")
8927 dline col ref1
8928 (if name (concat " or $" name) "")
8929 ;; FIXME: formula info not correct if special table line
8930 (if eqn
8931 (concat ", formula: "
8932 (org-table-formula-to-user
8933 (concat
8934 (if (string-match "^[$@]"(car eqn)) "" "$")
8935 (car eqn) "=" (cdr eqn))))
8936 "")))))
8938 (defun org-table-current-column ()
8939 "Find out which column we are in.
8940 When called interactively, column is also displayed in echo area."
8941 (interactive)
8942 (if (interactive-p) (org-table-check-inside-data-field))
8943 (save-excursion
8944 (let ((cnt 0) (pos (point)))
8945 (beginning-of-line 1)
8946 (while (search-forward "|" pos t)
8947 (setq cnt (1+ cnt)))
8948 (if (interactive-p) (message "This is table column %d" cnt))
8949 cnt)))
8951 (defun org-table-current-dline ()
8952 "Find out what table data line we are in.
8953 Only datalins count for this."
8954 (interactive)
8955 (if (interactive-p) (org-table-check-inside-data-field))
8956 (save-excursion
8957 (let ((cnt 0) (pos (point)))
8958 (goto-char (org-table-begin))
8959 (while (<= (point) pos)
8960 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
8961 (beginning-of-line 2))
8962 (if (interactive-p) (message "This is table line %d" cnt))
8963 cnt)))
8965 (defun org-table-goto-column (n &optional on-delim force)
8966 "Move the cursor to the Nth column in the current table line.
8967 With optional argument ON-DELIM, stop with point before the left delimiter
8968 of the field.
8969 If there are less than N fields, just go to after the last delimiter.
8970 However, when FORCE is non-nil, create new columns if necessary."
8971 (interactive "p")
8972 (let ((pos (point-at-eol)))
8973 (beginning-of-line 1)
8974 (when (> n 0)
8975 (while (and (> (setq n (1- n)) -1)
8976 (or (search-forward "|" pos t)
8977 (and force
8978 (progn (end-of-line 1)
8979 (skip-chars-backward "^|")
8980 (insert " | "))))))
8981 ; (backward-char 2) t)))))
8982 (when (and force (not (looking-at ".*|")))
8983 (save-excursion (end-of-line 1) (insert " | ")))
8984 (if on-delim
8985 (backward-char 1)
8986 (if (looking-at " ") (forward-char 1))))))
8988 (defun org-at-table-p (&optional table-type)
8989 "Return t if the cursor is inside an org-type table.
8990 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8991 (if org-enable-table-editor
8992 (save-excursion
8993 (beginning-of-line 1)
8994 (looking-at (if table-type org-table-any-line-regexp
8995 org-table-line-regexp)))
8996 nil))
8998 (defun org-at-table.el-p ()
8999 "Return t if and only if we are at a table.el table."
9000 (and (org-at-table-p 'any)
9001 (save-excursion
9002 (goto-char (org-table-begin 'any))
9003 (looking-at org-table1-hline-regexp))))
9005 (defun org-table-recognize-table.el ()
9006 "If there is a table.el table nearby, recognize it and move into it."
9007 (if org-table-tab-recognizes-table.el
9008 (if (org-at-table.el-p)
9009 (progn
9010 (beginning-of-line 1)
9011 (if (looking-at org-table-dataline-regexp)
9013 (if (looking-at org-table1-hline-regexp)
9014 (progn
9015 (beginning-of-line 2)
9016 (if (looking-at org-table-any-border-regexp)
9017 (beginning-of-line -1)))))
9018 (if (re-search-forward "|" (org-table-end t) t)
9019 (progn
9020 (require 'table)
9021 (if (table--at-cell-p (point))
9023 (message "recognizing table.el table...")
9024 (table-recognize-table)
9025 (message "recognizing table.el table...done")))
9026 (error "This should not happen..."))
9028 nil)
9029 nil))
9031 (defun org-at-table-hline-p ()
9032 "Return t if the cursor is inside a hline in a table."
9033 (if org-enable-table-editor
9034 (save-excursion
9035 (beginning-of-line 1)
9036 (looking-at org-table-hline-regexp))
9037 nil))
9039 (defun org-table-insert-column ()
9040 "Insert a new column into the table."
9041 (interactive)
9042 (if (not (org-at-table-p))
9043 (error "Not at a table"))
9044 (org-table-find-dataline)
9045 (let* ((col (max 1 (org-table-current-column)))
9046 (beg (org-table-begin))
9047 (end (org-table-end))
9048 ;; Current cursor position
9049 (linepos (org-current-line))
9050 (colpos col))
9051 (goto-char beg)
9052 (while (< (point) end)
9053 (if (org-at-table-hline-p)
9055 (org-table-goto-column col t)
9056 (insert "| "))
9057 (beginning-of-line 2))
9058 (move-marker end nil)
9059 (goto-line linepos)
9060 (org-table-goto-column colpos)
9061 (org-table-align)
9062 (org-table-fix-formulas "$" nil (1- col) 1)))
9064 (defun org-table-find-dataline ()
9065 "Find a dataline in the current table, which is needed for column commands."
9066 (if (and (org-at-table-p)
9067 (not (org-at-table-hline-p)))
9069 (let ((col (current-column))
9070 (end (org-table-end)))
9071 (move-to-column col)
9072 (while (and (< (point) end)
9073 (or (not (= (current-column) col))
9074 (org-at-table-hline-p)))
9075 (beginning-of-line 2)
9076 (move-to-column col))
9077 (if (and (org-at-table-p)
9078 (not (org-at-table-hline-p)))
9080 (error
9081 "Please position cursor in a data line for column operations")))))
9083 (defun org-table-delete-column ()
9084 "Delete a column from the table."
9085 (interactive)
9086 (if (not (org-at-table-p))
9087 (error "Not at a table"))
9088 (org-table-find-dataline)
9089 (org-table-check-inside-data-field)
9090 (let* ((col (org-table-current-column))
9091 (beg (org-table-begin))
9092 (end (org-table-end))
9093 ;; Current cursor position
9094 (linepos (org-current-line))
9095 (colpos col))
9096 (goto-char beg)
9097 (while (< (point) end)
9098 (if (org-at-table-hline-p)
9100 (org-table-goto-column col t)
9101 (and (looking-at "|[^|\n]+|")
9102 (replace-match "|")))
9103 (beginning-of-line 2))
9104 (move-marker end nil)
9105 (goto-line linepos)
9106 (org-table-goto-column colpos)
9107 (org-table-align)
9108 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
9109 col -1 col)))
9111 (defun org-table-move-column-right ()
9112 "Move column to the right."
9113 (interactive)
9114 (org-table-move-column nil))
9115 (defun org-table-move-column-left ()
9116 "Move column to the left."
9117 (interactive)
9118 (org-table-move-column 'left))
9120 (defun org-table-move-column (&optional left)
9121 "Move the current column to the right. With arg LEFT, move to the left."
9122 (interactive "P")
9123 (if (not (org-at-table-p))
9124 (error "Not at a table"))
9125 (org-table-find-dataline)
9126 (org-table-check-inside-data-field)
9127 (let* ((col (org-table-current-column))
9128 (col1 (if left (1- col) col))
9129 (beg (org-table-begin))
9130 (end (org-table-end))
9131 ;; Current cursor position
9132 (linepos (org-current-line))
9133 (colpos (if left (1- col) (1+ col))))
9134 (if (and left (= col 1))
9135 (error "Cannot move column further left"))
9136 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9137 (error "Cannot move column further right"))
9138 (goto-char beg)
9139 (while (< (point) end)
9140 (if (org-at-table-hline-p)
9142 (org-table-goto-column col1 t)
9143 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9144 (replace-match "|\\2|\\1|")))
9145 (beginning-of-line 2))
9146 (move-marker end nil)
9147 (goto-line linepos)
9148 (org-table-goto-column colpos)
9149 (org-table-align)
9150 (org-table-fix-formulas
9151 "$" (list (cons (number-to-string col) (number-to-string colpos))
9152 (cons (number-to-string colpos) (number-to-string col))))))
9154 (defun org-table-move-row-down ()
9155 "Move table row down."
9156 (interactive)
9157 (org-table-move-row nil))
9158 (defun org-table-move-row-up ()
9159 "Move table row up."
9160 (interactive)
9161 (org-table-move-row 'up))
9163 (defun org-table-move-row (&optional up)
9164 "Move the current table line down. With arg UP, move it up."
9165 (interactive "P")
9166 (let* ((col (current-column))
9167 (pos (point))
9168 (hline1p (save-excursion (beginning-of-line 1)
9169 (looking-at org-table-hline-regexp)))
9170 (dline1 (org-table-current-dline))
9171 (dline2 (+ dline1 (if up -1 1)))
9172 (tonew (if up 0 2))
9173 txt hline2p)
9174 (beginning-of-line tonew)
9175 (unless (org-at-table-p)
9176 (goto-char pos)
9177 (error "Cannot move row further"))
9178 (setq hline2p (looking-at org-table-hline-regexp))
9179 (goto-char pos)
9180 (beginning-of-line 1)
9181 (setq pos (point))
9182 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9183 (delete-region (point) (1+ (point-at-eol)))
9184 (beginning-of-line tonew)
9185 (insert txt)
9186 (beginning-of-line 0)
9187 (move-to-column col)
9188 (unless (or hline1p hline2p)
9189 (org-table-fix-formulas
9190 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
9191 (cons (number-to-string dline2) (number-to-string dline1)))))))
9193 (defun org-table-insert-row (&optional arg)
9194 "Insert a new row above the current line into the table.
9195 With prefix ARG, insert below the current line."
9196 (interactive "P")
9197 (if (not (org-at-table-p))
9198 (error "Not at a table"))
9199 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9200 (new (org-table-clean-line line)))
9201 ;; Fix the first field if necessary
9202 (if (string-match "^[ \t]*| *[#$] *|" line)
9203 (setq new (replace-match (match-string 0 line) t t new)))
9204 (beginning-of-line (if arg 2 1))
9205 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9206 (beginning-of-line 0)
9207 (re-search-forward "| ?" (point-at-eol) t)
9208 (and (or org-table-may-need-update org-table-overlay-coordinates)
9209 (org-table-align))
9210 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
9212 (defun org-table-insert-hline (&optional above)
9213 "Insert a horizontal-line below the current line into the table.
9214 With prefix ABOVE, insert above the current line."
9215 (interactive "P")
9216 (if (not (org-at-table-p))
9217 (error "Not at a table"))
9218 (let ((line (org-table-clean-line
9219 (buffer-substring (point-at-bol) (point-at-eol))))
9220 (col (current-column)))
9221 (while (string-match "|\\( +\\)|" line)
9222 (setq line (replace-match
9223 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9224 ?-) "|") t t line)))
9225 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9226 (beginning-of-line (if above 1 2))
9227 (insert line "\n")
9228 (beginning-of-line (if above 1 -1))
9229 (move-to-column col)
9230 (and org-table-overlay-coordinates (org-table-align))))
9232 (defun org-table-hline-and-move (&optional same-column)
9233 "Insert a hline and move to the row below that line."
9234 (interactive "P")
9235 (let ((col (org-table-current-column)))
9236 (org-table-maybe-eval-formula)
9237 (org-table-maybe-recalculate-line)
9238 (org-table-insert-hline)
9239 (end-of-line 2)
9240 (if (looking-at "\n[ \t]*|-")
9241 (progn (insert "\n|") (org-table-align))
9242 (org-table-next-field))
9243 (if same-column (org-table-goto-column col))))
9245 (defun org-table-clean-line (s)
9246 "Convert a table line S into a string with only \"|\" and space.
9247 In particular, this does handle wide and invisible characters."
9248 (if (string-match "^[ \t]*|-" s)
9249 ;; It's a hline, just map the characters
9250 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
9251 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9252 (setq s (replace-match
9253 (concat "|" (make-string (org-string-width (match-string 1 s))
9254 ?\ ) "|")
9255 t t s)))
9258 (defun org-table-kill-row ()
9259 "Delete the current row or horizontal line from the table."
9260 (interactive)
9261 (if (not (org-at-table-p))
9262 (error "Not at a table"))
9263 (let ((col (current-column))
9264 (dline (org-table-current-dline)))
9265 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9266 (if (not (org-at-table-p)) (beginning-of-line 0))
9267 (move-to-column col)
9268 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
9269 dline -1 dline)))
9271 (defun org-table-sort-lines (with-case &optional sorting-type)
9272 "Sort table lines according to the column at point.
9274 The position of point indicates the column to be used for
9275 sorting, and the range of lines is the range between the nearest
9276 horizontal separator lines, or the entire table of no such lines
9277 exist. If point is before the first column, you will be prompted
9278 for the sorting column. If there is an active region, the mark
9279 specifies the first line and the sorting column, while point
9280 should be in the last line to be included into the sorting.
9282 The command then prompts for the sorting type which can be
9283 alphabetically, numerically, or by time (as given in a time stamp
9284 in the field). Sorting in reverse order is also possible.
9286 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
9288 If SORTING-TYPE is specified when this function is called from a Lisp
9289 program, no prompting will take place. SORTING-TYPE must be a character,
9290 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
9291 should be done in reverse order."
9292 (interactive "P")
9293 (let* ((thisline (org-current-line))
9294 (thiscol (org-table-current-column))
9295 beg end bcol ecol tend tbeg column lns pos)
9296 (when (equal thiscol 0)
9297 (if (interactive-p)
9298 (setq thiscol
9299 (string-to-number
9300 (read-string "Use column N for sorting: ")))
9301 (setq thiscol 1))
9302 (org-table-goto-column thiscol))
9303 (org-table-check-inside-data-field)
9304 (if (org-region-active-p)
9305 (progn
9306 (setq beg (region-beginning) end (region-end))
9307 (goto-char beg)
9308 (setq column (org-table-current-column)
9309 beg (point-at-bol))
9310 (goto-char end)
9311 (setq end (point-at-bol 2)))
9312 (setq column (org-table-current-column)
9313 pos (point)
9314 tbeg (org-table-begin)
9315 tend (org-table-end))
9316 (if (re-search-backward org-table-hline-regexp tbeg t)
9317 (setq beg (point-at-bol 2))
9318 (goto-char tbeg)
9319 (setq beg (point-at-bol 1)))
9320 (goto-char pos)
9321 (if (re-search-forward org-table-hline-regexp tend t)
9322 (setq end (point-at-bol 1))
9323 (goto-char tend)
9324 (setq end (point-at-bol))))
9325 (setq beg (move-marker (make-marker) beg)
9326 end (move-marker (make-marker) end))
9327 (untabify beg end)
9328 (goto-char beg)
9329 (org-table-goto-column column)
9330 (skip-chars-backward "^|")
9331 (setq bcol (current-column))
9332 (org-table-goto-column (1+ column))
9333 (skip-chars-backward "^|")
9334 (setq ecol (1- (current-column)))
9335 (org-table-goto-column column)
9336 (setq lns (mapcar (lambda(x) (cons
9337 (org-sort-remove-invisible
9338 (nth (1- column)
9339 (org-split-string x "[ \t]*|[ \t]*")))
9341 (org-split-string (buffer-substring beg end) "\n")))
9342 (setq lns (org-do-sort lns "Table" with-case sorting-type))
9343 (delete-region beg end)
9344 (move-marker beg nil)
9345 (move-marker end nil)
9346 (insert (mapconcat 'cdr lns "\n") "\n")
9347 (goto-line thisline)
9348 (org-table-goto-column thiscol)
9349 (message "%d lines sorted, based on column %d" (length lns) column)))
9351 ;; FIXME: maybe we will not need this? Table sorting is broken....
9352 (defun org-sort-remove-invisible (s)
9353 (remove-text-properties 0 (length s) org-rm-props s)
9354 (while (string-match org-bracket-link-regexp s)
9355 (setq s (replace-match (if (match-end 2)
9356 (match-string 3 s)
9357 (match-string 1 s)) t t s)))
9360 (defun org-table-cut-region (beg end)
9361 "Copy region in table to the clipboard and blank all relevant fields."
9362 (interactive "r")
9363 (org-table-copy-region beg end 'cut))
9365 (defun org-table-copy-region (beg end &optional cut)
9366 "Copy rectangular region in table to clipboard.
9367 A special clipboard is used which can only be accessed
9368 with `org-table-paste-rectangle'."
9369 (interactive "rP")
9370 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9371 region cols
9372 (rpl (if cut " " nil)))
9373 (goto-char beg)
9374 (org-table-check-inside-data-field)
9375 (setq l01 (org-current-line)
9376 c01 (org-table-current-column))
9377 (goto-char end)
9378 (org-table-check-inside-data-field)
9379 (setq l02 (org-current-line)
9380 c02 (org-table-current-column))
9381 (setq l1 (min l01 l02) l2 (max l01 l02)
9382 c1 (min c01 c02) c2 (max c01 c02))
9383 (catch 'exit
9384 (while t
9385 (catch 'nextline
9386 (if (> l1 l2) (throw 'exit t))
9387 (goto-line l1)
9388 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9389 (setq cols nil ic1 c1 ic2 c2)
9390 (while (< ic1 (1+ ic2))
9391 (push (org-table-get-field ic1 rpl) cols)
9392 (setq ic1 (1+ ic1)))
9393 (push (nreverse cols) region)
9394 (setq l1 (1+ l1)))))
9395 (setq org-table-clip (nreverse region))
9396 (if cut (org-table-align))
9397 org-table-clip))
9399 (defun org-table-paste-rectangle ()
9400 "Paste a rectangular region into a table.
9401 The upper right corner ends up in the current field. All involved fields
9402 will be overwritten. If the rectangle does not fit into the present table,
9403 the table is enlarged as needed. The process ignores horizontal separator
9404 lines."
9405 (interactive)
9406 (unless (and org-table-clip (listp org-table-clip))
9407 (error "First cut/copy a region to paste!"))
9408 (org-table-check-inside-data-field)
9409 (let* ((clip org-table-clip)
9410 (line (org-current-line))
9411 (col (org-table-current-column))
9412 (org-enable-table-editor t)
9413 (org-table-automatic-realign nil)
9414 c cols field)
9415 (while (setq cols (pop clip))
9416 (while (org-at-table-hline-p) (beginning-of-line 2))
9417 (if (not (org-at-table-p))
9418 (progn (end-of-line 0) (org-table-next-field)))
9419 (setq c col)
9420 (while (setq field (pop cols))
9421 (org-table-goto-column c nil 'force)
9422 (org-table-get-field nil field)
9423 (setq c (1+ c)))
9424 (beginning-of-line 2))
9425 (goto-line line)
9426 (org-table-goto-column col)
9427 (org-table-align)))
9429 (defun org-table-convert ()
9430 "Convert from `org-mode' table to table.el and back.
9431 Obviously, this only works within limits. When an Org-mode table is
9432 converted to table.el, all horizontal separator lines get lost, because
9433 table.el uses these as cell boundaries and has no notion of horizontal lines.
9434 A table.el table can be converted to an Org-mode table only if it does not
9435 do row or column spanning. Multiline cells will become multiple cells.
9436 Beware, Org-mode does not test if the table can be successfully converted - it
9437 blindly applies a recipe that works for simple tables."
9438 (interactive)
9439 (require 'table)
9440 (if (org-at-table.el-p)
9441 ;; convert to Org-mode table
9442 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9443 (end (move-marker (make-marker) (org-table-end t))))
9444 (table-unrecognize-region beg end)
9445 (goto-char beg)
9446 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9447 (replace-match ""))
9448 (goto-char beg))
9449 (if (org-at-table-p)
9450 ;; convert to table.el table
9451 (let ((beg (move-marker (make-marker) (org-table-begin)))
9452 (end (move-marker (make-marker) (org-table-end))))
9453 ;; first, get rid of all horizontal lines
9454 (goto-char beg)
9455 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9456 (replace-match ""))
9457 ;; insert a hline before first
9458 (goto-char beg)
9459 (org-table-insert-hline 'above)
9460 (beginning-of-line -1)
9461 ;; insert a hline after each line
9462 (while (progn (beginning-of-line 3) (< (point) end))
9463 (org-table-insert-hline))
9464 (goto-char beg)
9465 (setq end (move-marker end (org-table-end)))
9466 ;; replace "+" at beginning and ending of hlines
9467 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9468 (replace-match "\\1+-"))
9469 (goto-char beg)
9470 (while (re-search-forward "-|[ \t]*$" end t)
9471 (replace-match "-+"))
9472 (goto-char beg)))))
9474 (defun org-table-wrap-region (arg)
9475 "Wrap several fields in a column like a paragraph.
9476 This is useful if you'd like to spread the contents of a field over several
9477 lines, in order to keep the table compact.
9479 If there is an active region, and both point and mark are in the same column,
9480 the text in the column is wrapped to minimum width for the given number of
9481 lines. Generally, this makes the table more compact. A prefix ARG may be
9482 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9483 formats the selected text to two lines. If the region was longer than two
9484 lines, the remaining lines remain empty. A negative prefix argument reduces
9485 the current number of lines by that amount. The wrapped text is pasted back
9486 into the table. If you formatted it to more lines than it was before, fields
9487 further down in the table get overwritten - so you might need to make space in
9488 the table first.
9490 If there is no region, the current field is split at the cursor position and
9491 the text fragment to the right of the cursor is prepended to the field one
9492 line down.
9494 If there is no region, but you specify a prefix ARG, the current field gets
9495 blank, and the content is appended to the field above."
9496 (interactive "P")
9497 (org-table-check-inside-data-field)
9498 (if (org-region-active-p)
9499 ;; There is a region: fill as a paragraph
9500 (let* ((beg (region-beginning))
9501 (cline (save-excursion (goto-char beg) (org-current-line)))
9502 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9503 nlines)
9504 (org-table-cut-region (region-beginning) (region-end))
9505 (if (> (length (car org-table-clip)) 1)
9506 (error "Region must be limited to single column"))
9507 (setq nlines (if arg
9508 (if (< arg 1)
9509 (+ (length org-table-clip) arg)
9510 arg)
9511 (length org-table-clip)))
9512 (setq org-table-clip
9513 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9514 nil nlines)))
9515 (goto-line cline)
9516 (org-table-goto-column ccol)
9517 (org-table-paste-rectangle))
9518 ;; No region, split the current field at point
9519 (unless (org-get-alist-option org-M-RET-may-split-line 'table)
9520 (skip-chars-forward "^\r\n|"))
9521 (if arg
9522 ;; combine with field above
9523 (let ((s (org-table-blank-field))
9524 (col (org-table-current-column)))
9525 (beginning-of-line 0)
9526 (while (org-at-table-hline-p) (beginning-of-line 0))
9527 (org-table-goto-column col)
9528 (skip-chars-forward "^|")
9529 (skip-chars-backward " ")
9530 (insert " " (org-trim s))
9531 (org-table-align))
9532 ;; split field
9533 (if (looking-at "\\([^|]+\\)+|")
9534 (let ((s (match-string 1)))
9535 (replace-match " |")
9536 (goto-char (match-beginning 0))
9537 (org-table-next-row)
9538 (insert (org-trim s) " ")
9539 (org-table-align))
9540 (org-table-next-row)))))
9542 (defvar org-field-marker nil)
9544 (defun org-table-edit-field (arg)
9545 "Edit table field in a different window.
9546 This is mainly useful for fields that contain hidden parts.
9547 When called with a \\[universal-argument] prefix, just make the full field visible so that
9548 it can be edited in place."
9549 (interactive "P")
9550 (if arg
9551 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9552 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9553 (remove-text-properties b e '(org-cwidth t invisible t
9554 display t intangible t))
9555 (if (and (boundp 'font-lock-mode) font-lock-mode)
9556 (font-lock-fontify-block)))
9557 (let ((pos (move-marker (make-marker) (point)))
9558 (field (org-table-get-field))
9559 (cw (current-window-configuration))
9561 (org-switch-to-buffer-other-window "*Org tmp*")
9562 (erase-buffer)
9563 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9564 (let ((org-inhibit-startup t)) (org-mode))
9565 (goto-char (setq p (point-max)))
9566 (insert (org-trim field))
9567 (remove-text-properties p (point-max)
9568 '(invisible t org-cwidth t display t
9569 intangible t))
9570 (goto-char p)
9571 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9572 (org-set-local 'org-window-configuration cw)
9573 (org-set-local 'org-field-marker pos)
9574 (message "Edit and finish with C-c C-c"))))
9576 (defun org-table-finish-edit-field ()
9577 "Finish editing a table data field.
9578 Remove all newline characters, insert the result into the table, realign
9579 the table and kill the editing buffer."
9580 (let ((pos org-field-marker)
9581 (cw org-window-configuration)
9582 (cb (current-buffer))
9583 text)
9584 (goto-char (point-min))
9585 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9586 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9587 (replace-match " "))
9588 (setq text (org-trim (buffer-string)))
9589 (set-window-configuration cw)
9590 (kill-buffer cb)
9591 (select-window (get-buffer-window (marker-buffer pos)))
9592 (goto-char pos)
9593 (move-marker pos nil)
9594 (org-table-check-inside-data-field)
9595 (org-table-get-field nil text)
9596 (org-table-align)
9597 (message "New field value inserted")))
9599 (defun org-trim (s)
9600 "Remove whitespace at beginning and end of string."
9601 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9602 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9605 (defun org-wrap (string &optional width lines)
9606 "Wrap string to either a number of lines, or a width in characters.
9607 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9608 that costs. If there is a word longer than WIDTH, the text is actually
9609 wrapped to the length of that word.
9610 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9611 many lines, whatever width that takes.
9612 The return value is a list of lines, without newlines at the end."
9613 (let* ((words (org-split-string string "[ \t\n]+"))
9614 (maxword (apply 'max (mapcar 'org-string-width words)))
9615 w ll)
9616 (cond (width
9617 (org-do-wrap words (max maxword width)))
9618 (lines
9619 (setq w maxword)
9620 (setq ll (org-do-wrap words maxword))
9621 (if (<= (length ll) lines)
9623 (setq ll words)
9624 (while (> (length ll) lines)
9625 (setq w (1+ w))
9626 (setq ll (org-do-wrap words w)))
9627 ll))
9628 (t (error "Cannot wrap this")))))
9631 (defun org-do-wrap (words width)
9632 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9633 (let (lines line)
9634 (while words
9635 (setq line (pop words))
9636 (while (and words (< (+ (length line) (length (car words))) width))
9637 (setq line (concat line " " (pop words))))
9638 (setq lines (push line lines)))
9639 (nreverse lines)))
9641 (defun org-split-string (string &optional separators)
9642 "Splits STRING into substrings at SEPARATORS.
9643 No empty strings are returned if there are matches at the beginning
9644 and end of string."
9645 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9646 (start 0)
9647 notfirst
9648 (list nil))
9649 (while (and (string-match rexp string
9650 (if (and notfirst
9651 (= start (match-beginning 0))
9652 (< start (length string)))
9653 (1+ start) start))
9654 (< (match-beginning 0) (length string)))
9655 (setq notfirst t)
9656 (or (eq (match-beginning 0) 0)
9657 (and (eq (match-beginning 0) (match-end 0))
9658 (eq (match-beginning 0) start))
9659 (setq list
9660 (cons (substring string start (match-beginning 0))
9661 list)))
9662 (setq start (match-end 0)))
9663 (or (eq start (length string))
9664 (setq list
9665 (cons (substring string start)
9666 list)))
9667 (nreverse list)))
9669 (defun org-table-map-tables (function)
9670 "Apply FUNCTION to the start of all tables in the buffer."
9671 (save-excursion
9672 (save-restriction
9673 (widen)
9674 (goto-char (point-min))
9675 (while (re-search-forward org-table-any-line-regexp nil t)
9676 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9677 (beginning-of-line 1)
9678 (if (looking-at org-table-line-regexp)
9679 (save-excursion (funcall function)))
9680 (re-search-forward org-table-any-border-regexp nil 1))))
9681 (message "Mapping tables: done"))
9683 (defvar org-timecnt) ; dynamically scoped parameter
9685 (defun org-table-sum (&optional beg end nlast)
9686 "Sum numbers in region of current table column.
9687 The result will be displayed in the echo area, and will be available
9688 as kill to be inserted with \\[yank].
9690 If there is an active region, it is interpreted as a rectangle and all
9691 numbers in that rectangle will be summed. If there is no active
9692 region and point is located in a table column, sum all numbers in that
9693 column.
9695 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9696 numbers are assumed to be times as well (in decimal hours) and the
9697 numbers are added as such.
9699 If NLAST is a number, only the NLAST fields will actually be summed."
9700 (interactive)
9701 (save-excursion
9702 (let (col (org-timecnt 0) diff h m s org-table-clip)
9703 (cond
9704 ((and beg end)) ; beg and end given explicitly
9705 ((org-region-active-p)
9706 (setq beg (region-beginning) end (region-end)))
9708 (setq col (org-table-current-column))
9709 (goto-char (org-table-begin))
9710 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9711 (error "No table data"))
9712 (org-table-goto-column col)
9713 (setq beg (point))
9714 (goto-char (org-table-end))
9715 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9716 (error "No table data"))
9717 (org-table-goto-column col)
9718 (setq end (point))))
9719 (let* ((items (apply 'append (org-table-copy-region beg end)))
9720 (items1 (cond ((not nlast) items)
9721 ((>= nlast (length items)) items)
9722 (t (setq items (reverse items))
9723 (setcdr (nthcdr (1- nlast) items) nil)
9724 (nreverse items))))
9725 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9726 items1)))
9727 (res (apply '+ numbers))
9728 (sres (if (= org-timecnt 0)
9729 (format "%g" res)
9730 (setq diff (* 3600 res)
9731 h (floor (/ diff 3600)) diff (mod diff 3600)
9732 m (floor (/ diff 60)) diff (mod diff 60)
9733 s diff)
9734 (format "%d:%02d:%02d" h m s))))
9735 (kill-new sres)
9736 (if (interactive-p)
9737 (message "%s"
9738 (substitute-command-keys
9739 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9740 (length numbers) sres))))
9741 sres))))
9743 (defun org-table-get-number-for-summing (s)
9744 (let (n)
9745 (if (string-match "^ *|? *" s)
9746 (setq s (replace-match "" nil nil s)))
9747 (if (string-match " *|? *$" s)
9748 (setq s (replace-match "" nil nil s)))
9749 (setq n (string-to-number s))
9750 (cond
9751 ((and (string-match "0" s)
9752 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9753 ((string-match "\\`[ \t]+\\'" s) nil)
9754 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9755 (let ((h (string-to-number (or (match-string 1 s) "0")))
9756 (m (string-to-number (or (match-string 2 s) "0")))
9757 (s (string-to-number (or (match-string 4 s) "0"))))
9758 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9759 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9760 ((equal n 0) nil)
9761 (t n))))
9763 (defun org-table-current-field-formula (&optional key noerror)
9764 "Return the formula active for the current field.
9765 Assumes that specials are in place.
9766 If KEY is given, return the key to this formula.
9767 Otherwise return the formula preceeded with \"=\" or \":=\"."
9768 (let* ((name (car (rassoc (list (org-current-line)
9769 (org-table-current-column))
9770 org-table-named-field-locations)))
9771 (col (org-table-current-column))
9772 (scol (int-to-string col))
9773 (ref (format "@%d$%d" (org-table-current-dline) col))
9774 (stored-list (org-table-get-stored-formulas noerror))
9775 (ass (or (assoc name stored-list)
9776 (assoc ref stored-list)
9777 (assoc scol stored-list))))
9778 (if key
9779 (car ass)
9780 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9781 (cdr ass))))))
9783 (defun org-table-get-formula (&optional equation named)
9784 "Read a formula from the minibuffer, offer stored formula as default.
9785 When NAMED is non-nil, look for a named equation."
9786 (let* ((stored-list (org-table-get-stored-formulas))
9787 (name (car (rassoc (list (org-current-line)
9788 (org-table-current-column))
9789 org-table-named-field-locations)))
9790 (ref (format "@%d$%d" (org-table-current-dline)
9791 (org-table-current-column)))
9792 (refass (assoc ref stored-list))
9793 (scol (if named
9794 (if name name ref)
9795 (int-to-string (org-table-current-column))))
9796 (dummy (and (or name refass) (not named)
9797 (not (y-or-n-p "Replace field formula with column formula? " ))
9798 (error "Abort")))
9799 (name (or name ref))
9800 (org-table-may-need-update nil)
9801 (stored (cdr (assoc scol stored-list)))
9802 (eq (cond
9803 ((and stored equation (string-match "^ *=? *$" equation))
9804 stored)
9805 ((stringp equation)
9806 equation)
9807 (t (org-table-formula-from-user
9808 (read-string
9809 (org-table-formula-to-user
9810 (format "%s formula %s%s="
9811 (if named "Field" "Column")
9812 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9813 scol))
9814 (if stored (org-table-formula-to-user stored) "")
9815 'org-table-formula-history
9816 )))))
9817 mustsave)
9818 (when (not (string-match "\\S-" eq))
9819 ;; remove formula
9820 (setq stored-list (delq (assoc scol stored-list) stored-list))
9821 (org-table-store-formulas stored-list)
9822 (error "Formula removed"))
9823 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9824 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9825 (if (and name (not named))
9826 ;; We set the column equation, delete the named one.
9827 (setq stored-list (delq (assoc name stored-list) stored-list)
9828 mustsave t))
9829 (if stored
9830 (setcdr (assoc scol stored-list) eq)
9831 (setq stored-list (cons (cons scol eq) stored-list)))
9832 (if (or mustsave (not (equal stored eq)))
9833 (org-table-store-formulas stored-list))
9834 eq))
9836 (defun org-table-store-formulas (alist)
9837 "Store the list of formulas below the current table."
9838 (setq alist (sort alist 'org-table-formula-less-p))
9839 (save-excursion
9840 (goto-char (org-table-end))
9841 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9842 (progn
9843 ;; don't overwrite TBLFM, we might use text properties to store stuff
9844 (goto-char (match-beginning 2))
9845 (delete-region (match-beginning 2) (match-end 0)))
9846 (insert "#+TBLFM:"))
9847 (insert " "
9848 (mapconcat (lambda (x)
9849 (concat
9850 (if (equal (string-to-char (car x)) ?@) "" "$")
9851 (car x) "=" (cdr x)))
9852 alist "::")
9853 "\n")))
9855 (defsubst org-table-formula-make-cmp-string (a)
9856 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9857 (concat
9858 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9859 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9860 (if (match-end 5) (concat "@@" (match-string 5 a))))))
9862 (defun org-table-formula-less-p (a b)
9863 "Compare two formulas for sorting."
9864 (let ((as (org-table-formula-make-cmp-string (car a)))
9865 (bs (org-table-formula-make-cmp-string (car b))))
9866 (and as bs (string< as bs))))
9868 (defun org-table-get-stored-formulas (&optional noerror)
9869 "Return an alist with the stored formulas directly after current table."
9870 (interactive)
9871 (let (scol eq eq-alist strings string seen)
9872 (save-excursion
9873 (goto-char (org-table-end))
9874 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9875 (setq strings (org-split-string (match-string 2) " *:: *"))
9876 (while (setq string (pop strings))
9877 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
9878 (setq scol (if (match-end 2)
9879 (match-string 2 string)
9880 (match-string 1 string))
9881 eq (match-string 3 string)
9882 eq-alist (cons (cons scol eq) eq-alist))
9883 (if (member scol seen)
9884 (if noerror
9885 (progn
9886 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9887 (ding)
9888 (sit-for 2))
9889 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
9890 (push scol seen))))))
9891 (nreverse eq-alist)))
9893 (defun org-table-fix-formulas (key replace &optional limit delta remove)
9894 "Modify the equations after the table structure has been edited.
9895 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
9896 For all numbers larger than LIMIT, shift them by DELTA."
9897 (save-excursion
9898 (goto-char (org-table-end))
9899 (when (looking-at "#\\+TBLFM:")
9900 (let ((re (concat key "\\([0-9]+\\)"))
9901 (re2
9902 (when remove
9903 (if (equal key "$")
9904 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
9905 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
9906 s n a)
9907 (when remove
9908 (while (re-search-forward re2 (point-at-eol) t)
9909 (replace-match "")))
9910 (while (re-search-forward re (point-at-eol) t)
9911 (setq s (match-string 1) n (string-to-number s))
9912 (cond
9913 ((setq a (assoc s replace))
9914 (replace-match (concat key (cdr a)) t t))
9915 ((and limit (> n limit))
9916 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
9918 (defun org-table-get-specials ()
9919 "Get the column names and local parameters for this table."
9920 (save-excursion
9921 (let ((beg (org-table-begin)) (end (org-table-end))
9922 names name fields fields1 field cnt
9923 c v l line col types dlines hlines)
9924 (setq org-table-column-names nil
9925 org-table-local-parameters nil
9926 org-table-named-field-locations nil
9927 org-table-current-begin-line nil
9928 org-table-current-begin-pos nil
9929 org-table-current-line-types nil)
9930 (goto-char beg)
9931 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9932 (setq names (org-split-string (match-string 1) " *| *")
9933 cnt 1)
9934 (while (setq name (pop names))
9935 (setq cnt (1+ cnt))
9936 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9937 (push (cons name (int-to-string cnt)) org-table-column-names))))
9938 (setq org-table-column-names (nreverse org-table-column-names))
9939 (setq org-table-column-name-regexp
9940 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9941 (goto-char beg)
9942 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9943 (setq fields (org-split-string (match-string 1) " *| *"))
9944 (while (setq field (pop fields))
9945 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9946 (push (cons (match-string 1 field) (match-string 2 field))
9947 org-table-local-parameters))))
9948 (goto-char beg)
9949 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9950 (setq c (match-string 1)
9951 fields (org-split-string (match-string 2) " *| *"))
9952 (save-excursion
9953 (beginning-of-line (if (equal c "_") 2 0))
9954 (setq line (org-current-line) col 1)
9955 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9956 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9957 (while (and fields1 (setq field (pop fields)))
9958 (setq v (pop fields1) col (1+ col))
9959 (when (and (stringp field) (stringp v)
9960 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9961 (push (cons field v) org-table-local-parameters)
9962 (push (list field line col) org-table-named-field-locations))))
9963 ;; Analyse the line types
9964 (goto-char beg)
9965 (setq org-table-current-begin-line (org-current-line)
9966 org-table-current-begin-pos (point)
9967 l org-table-current-begin-line)
9968 (while (looking-at "[ \t]*|\\(-\\)?")
9969 (push (if (match-end 1) 'hline 'dline) types)
9970 (if (match-end 1) (push l hlines) (push l dlines))
9971 (beginning-of-line 2)
9972 (setq l (1+ l)))
9973 (setq org-table-current-line-types (apply 'vector (nreverse types))
9974 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
9975 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
9977 (defun org-table-maybe-eval-formula ()
9978 "Check if the current field starts with \"=\" or \":=\".
9979 If yes, store the formula and apply it."
9980 ;; We already know we are in a table. Get field will only return a formula
9981 ;; when appropriate. It might return a separator line, but no problem.
9982 (when org-table-formula-evaluate-inline
9983 (let* ((field (org-trim (or (org-table-get-field) "")))
9984 named eq)
9985 (when (string-match "^:?=\\(.*\\)" field)
9986 (setq named (equal (string-to-char field) ?:)
9987 eq (match-string 1 field))
9988 (if (or (fboundp 'calc-eval)
9989 (equal (substring eq 0 (min 2 (length eq))) "'("))
9990 (org-table-eval-formula (if named '(4) nil)
9991 (org-table-formula-from-user eq))
9992 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
9994 (defvar org-recalc-commands nil
9995 "List of commands triggering the recalculation of a line.
9996 Will be filled automatically during use.")
9998 (defvar org-recalc-marks
9999 '((" " . "Unmarked: no special line, no automatic recalculation")
10000 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
10001 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
10002 ("!" . "Column name definition line. Reference in formula as $name.")
10003 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
10004 ("_" . "Names for values in row below this one.")
10005 ("^" . "Names for values in row above this one.")))
10007 (defun org-table-rotate-recalc-marks (&optional newchar)
10008 "Rotate the recalculation mark in the first column.
10009 If in any row, the first field is not consistent with a mark,
10010 insert a new column for the markers.
10011 When there is an active region, change all the lines in the region,
10012 after prompting for the marking character.
10013 After each change, a message will be displayed indicating the meaning
10014 of the new mark."
10015 (interactive)
10016 (unless (org-at-table-p) (error "Not at a table"))
10017 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
10018 (beg (org-table-begin))
10019 (end (org-table-end))
10020 (l (org-current-line))
10021 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
10022 (l2 (if (org-region-active-p) (org-current-line (region-end))))
10023 (have-col
10024 (save-excursion
10025 (goto-char beg)
10026 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
10027 (col (org-table-current-column))
10028 (forcenew (car (assoc newchar org-recalc-marks)))
10029 epos new)
10030 (when l1
10031 (message "Change region to what mark? Type # * ! $ or SPC: ")
10032 (setq newchar (char-to-string (read-char-exclusive))
10033 forcenew (car (assoc newchar org-recalc-marks))))
10034 (if (and newchar (not forcenew))
10035 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
10036 newchar))
10037 (if l1 (goto-line l1))
10038 (save-excursion
10039 (beginning-of-line 1)
10040 (unless (looking-at org-table-dataline-regexp)
10041 (error "Not at a table data line")))
10042 (unless have-col
10043 (org-table-goto-column 1)
10044 (org-table-insert-column)
10045 (org-table-goto-column (1+ col)))
10046 (setq epos (point-at-eol))
10047 (save-excursion
10048 (beginning-of-line 1)
10049 (org-table-get-field
10050 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
10051 (concat " "
10052 (setq new (or forcenew
10053 (cadr (member (match-string 1) marks))))
10054 " ")
10055 " # ")))
10056 (if (and l1 l2)
10057 (progn
10058 (goto-line l1)
10059 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
10060 (and (looking-at org-table-dataline-regexp)
10061 (org-table-get-field 1 (concat " " new " "))))
10062 (goto-line l1)))
10063 (if (not (= epos (point-at-eol))) (org-table-align))
10064 (goto-line l)
10065 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
10067 (defun org-table-maybe-recalculate-line ()
10068 "Recompute the current line if marked for it, and if we haven't just done it."
10069 (interactive)
10070 (and org-table-allow-automatic-line-recalculation
10071 (not (and (memq last-command org-recalc-commands)
10072 (equal org-last-recalc-line (org-current-line))))
10073 (save-excursion (beginning-of-line 1)
10074 (looking-at org-table-auto-recalculate-regexp))
10075 (org-table-recalculate) t))
10077 (defvar org-table-formula-debug nil
10078 "Non-nil means, debug table formulas.
10079 When nil, simply write \"#ERROR\" in corrupted fields.")
10080 (make-variable-buffer-local 'org-table-formula-debug)
10082 (defvar modes)
10083 (defsubst org-set-calc-mode (var &optional value)
10084 (if (stringp var)
10085 (setq var (assoc var '(("D" calc-angle-mode deg)
10086 ("R" calc-angle-mode rad)
10087 ("F" calc-prefer-frac t)
10088 ("S" calc-symbolic-mode t)))
10089 value (nth 2 var) var (nth 1 var)))
10090 (if (memq var modes)
10091 (setcar (cdr (memq var modes)) value)
10092 (cons var (cons value modes)))
10093 modes)
10095 (defun org-table-eval-formula (&optional arg equation
10096 suppress-align suppress-const
10097 suppress-store suppress-analysis)
10098 "Replace the table field value at the cursor by the result of a calculation.
10100 This function makes use of Dave Gillespie's Calc package, in my view the
10101 most exciting program ever written for GNU Emacs. So you need to have Calc
10102 installed in order to use this function.
10104 In a table, this command replaces the value in the current field with the
10105 result of a formula. It also installs the formula as the \"current\" column
10106 formula, by storing it in a special line below the table. When called
10107 with a `C-u' prefix, the current field must ba a named field, and the
10108 formula is installed as valid in only this specific field.
10110 When called with two `C-u' prefixes, insert the active equation
10111 for the field back into the current field, so that it can be
10112 edited there. This is useful in order to use \\[org-table-show-reference]
10113 to check the referenced fields.
10115 When called, the command first prompts for a formula, which is read in
10116 the minibuffer. Previously entered formulas are available through the
10117 history list, and the last used formula is offered as a default.
10118 These stored formulas are adapted correctly when moving, inserting, or
10119 deleting columns with the corresponding commands.
10121 The formula can be any algebraic expression understood by the Calc package.
10122 For details, see the Org-mode manual.
10124 This function can also be called from Lisp programs and offers
10125 additional arguments: EQUATION can be the formula to apply. If this
10126 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10127 used to speed-up recursive calls by by-passing unnecessary aligns.
10128 SUPPRESS-CONST suppresses the interpretation of constants in the
10129 formula, assuming that this has been done already outside the function.
10130 SUPPRESS-STORE means the formula should not be stored, either because
10131 it is already stored, or because it is a modified equation that should
10132 not overwrite the stored one."
10133 (interactive "P")
10134 (org-table-check-inside-data-field)
10135 (or suppress-analysis (org-table-get-specials))
10136 (if (equal arg '(16))
10137 (let ((eq (org-table-current-field-formula)))
10138 (or eq (error "No equation active for current field"))
10139 (org-table-get-field nil eq)
10140 (org-table-align)
10141 (setq org-table-may-need-update t))
10142 (let* (fields
10143 (ndown (if (integerp arg) arg 1))
10144 (org-table-automatic-realign nil)
10145 (case-fold-search nil)
10146 (down (> ndown 1))
10147 (formula (if (and equation suppress-store)
10148 equation
10149 (org-table-get-formula equation (equal arg '(4)))))
10150 (n0 (org-table-current-column))
10151 (modes (copy-sequence org-calc-default-modes))
10152 (numbers nil) ; was a variable, now fixed default
10153 (keep-empty nil)
10154 n form form0 bw fmt x ev orig c lispp literal)
10155 ;; Parse the format string. Since we have a lot of modes, this is
10156 ;; a lot of work. However, I think calc still uses most of the time.
10157 (if (string-match ";" formula)
10158 (let ((tmp (org-split-string formula ";")))
10159 (setq formula (car tmp)
10160 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10161 (nth 1 tmp)))
10162 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
10163 (setq c (string-to-char (match-string 1 fmt))
10164 n (string-to-number (match-string 2 fmt)))
10165 (if (= c ?p)
10166 (setq modes (org-set-calc-mode 'calc-internal-prec n))
10167 (setq modes (org-set-calc-mode
10168 'calc-float-format
10169 (list (cdr (assoc c '((?n . float) (?f . fix)
10170 (?s . sci) (?e . eng))))
10171 n))))
10172 (setq fmt (replace-match "" t t fmt)))
10173 (if (string-match "[NT]" fmt)
10174 (setq numbers (equal (match-string 0 fmt) "N")
10175 fmt (replace-match "" t t fmt)))
10176 (if (string-match "L" fmt)
10177 (setq literal t
10178 fmt (replace-match "" t t fmt)))
10179 (if (string-match "E" fmt)
10180 (setq keep-empty t
10181 fmt (replace-match "" t t fmt)))
10182 (while (string-match "[DRFS]" fmt)
10183 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10184 (setq fmt (replace-match "" t t fmt)))
10185 (unless (string-match "\\S-" fmt)
10186 (setq fmt nil))))
10187 (if (and (not suppress-const) org-table-formula-use-constants)
10188 (setq formula (org-table-formula-substitute-names formula)))
10189 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10190 (while (> ndown 0)
10191 (setq fields (org-split-string
10192 (org-no-properties
10193 (buffer-substring (point-at-bol) (point-at-eol)))
10194 " *| *"))
10195 (if (eq numbers t)
10196 (setq fields (mapcar
10197 (lambda (x) (number-to-string (string-to-number x)))
10198 fields)))
10199 (setq ndown (1- ndown))
10200 (setq form (copy-sequence formula)
10201 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
10202 (if (and lispp literal) (setq lispp 'literal))
10203 ;; Check for old vertical references
10204 (setq form (org-rewrite-old-row-references form))
10205 ;; Insert complex ranges
10206 (while (string-match org-table-range-regexp form)
10207 (setq form
10208 (replace-match
10209 (save-match-data
10210 (org-table-make-reference
10211 (org-table-get-range (match-string 0 form) nil n0)
10212 keep-empty numbers lispp))
10213 t t form)))
10214 ;; Insert simple ranges
10215 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
10216 (setq form
10217 (replace-match
10218 (save-match-data
10219 (org-table-make-reference
10220 (org-sublist
10221 fields (string-to-number (match-string 1 form))
10222 (string-to-number (match-string 2 form)))
10223 keep-empty numbers lispp))
10224 t t form)))
10225 (setq form0 form)
10226 ;; Insert the references to fields in same row
10227 (while (string-match "\\$\\([0-9]+\\)" form)
10228 (setq n (string-to-number (match-string 1 form))
10229 x (nth (1- (if (= n 0) n0 n)) fields))
10230 (unless x (error "Invalid field specifier \"%s\""
10231 (match-string 0 form)))
10232 (setq form (replace-match
10233 (save-match-data
10234 (org-table-make-reference x nil numbers lispp))
10235 t t form)))
10237 (if lispp
10238 (setq ev (condition-case nil
10239 (eval (eval (read form)))
10240 (error "#ERROR"))
10241 ev (if (numberp ev) (number-to-string ev) ev))
10242 (or (fboundp 'calc-eval)
10243 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
10244 (setq ev (calc-eval (cons form modes)
10245 (if numbers 'num))))
10247 (when org-table-formula-debug
10248 (with-output-to-temp-buffer "*Substitution History*"
10249 (princ (format "Substitution history of formula
10250 Orig: %s
10251 $xyz-> %s
10252 @r$c-> %s
10253 $1-> %s\n" orig formula form0 form))
10254 (if (listp ev)
10255 (princ (format " %s^\nError: %s"
10256 (make-string (car ev) ?\-) (nth 1 ev)))
10257 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10258 ev (or fmt "NONE")
10259 (if fmt (format fmt (string-to-number ev)) ev)))))
10260 (setq bw (get-buffer-window "*Substitution History*"))
10261 (shrink-window-if-larger-than-buffer bw)
10262 (unless (and (interactive-p) (not ndown))
10263 (unless (let (inhibit-redisplay)
10264 (y-or-n-p "Debugging Formula. Continue to next? "))
10265 (org-table-align)
10266 (error "Abort"))
10267 (delete-window bw)
10268 (message "")))
10269 (if (listp ev) (setq fmt nil ev "#ERROR"))
10270 (org-table-justify-field-maybe
10271 (if fmt (format fmt (string-to-number ev)) ev))
10272 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10273 (call-interactively 'org-return)
10274 (setq ndown 0)))
10275 (and down (org-table-maybe-recalculate-line))
10276 (or suppress-align (and org-table-may-need-update
10277 (org-table-align))))))
10279 (defun org-table-put-field-property (prop value)
10280 (save-excursion
10281 (put-text-property (progn (skip-chars-backward "^|") (point))
10282 (progn (skip-chars-forward "^|") (point))
10283 prop value)))
10285 (defun org-table-get-range (desc &optional tbeg col highlight)
10286 "Get a calc vector from a column, accorting to descriptor DESC.
10287 Optional arguments TBEG and COL can give the beginning of the table and
10288 the current column, to avoid unnecessary parsing.
10289 HIGHLIGHT means, just highlight the range."
10290 (if (not (equal (string-to-char desc) ?@))
10291 (setq desc (concat "@" desc)))
10292 (save-excursion
10293 (or tbeg (setq tbeg (org-table-begin)))
10294 (or col (setq col (org-table-current-column)))
10295 (let ((thisline (org-current-line))
10296 beg end c1 c2 r1 r2 rangep tmp)
10297 (unless (string-match org-table-range-regexp desc)
10298 (error "Invalid table range specifier `%s'" desc))
10299 (setq rangep (match-end 3)
10300 r1 (and (match-end 1) (match-string 1 desc))
10301 r2 (and (match-end 4) (match-string 4 desc))
10302 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
10303 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
10305 (and c1 (setq c1 (+ (string-to-number c1)
10306 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
10307 (and c2 (setq c2 (+ (string-to-number c2)
10308 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
10309 (if (equal r1 "") (setq r1 nil))
10310 (if (equal r2 "") (setq r2 nil))
10311 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10312 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10313 ; (setq r2 (or r2 r1) c2 (or c2 c1))
10314 (if (not r1) (setq r1 thisline))
10315 (if (not r2) (setq r2 thisline))
10316 (if (not c1) (setq c1 col))
10317 (if (not c2) (setq c2 col))
10318 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10319 ;; just one field
10320 (progn
10321 (goto-line r1)
10322 (while (not (looking-at org-table-dataline-regexp))
10323 (beginning-of-line 2))
10324 (prog1 (org-trim (org-table-get-field c1))
10325 (if highlight (org-table-highlight-rectangle (point) (point)))))
10326 ;; A range, return a vector
10327 ;; First sort the numbers to get a regular ractangle
10328 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10329 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10330 (goto-line r1)
10331 (while (not (looking-at org-table-dataline-regexp))
10332 (beginning-of-line 2))
10333 (org-table-goto-column c1)
10334 (setq beg (point))
10335 (goto-line r2)
10336 (while (not (looking-at org-table-dataline-regexp))
10337 (beginning-of-line 0))
10338 (org-table-goto-column c2)
10339 (setq end (point))
10340 (if highlight
10341 (org-table-highlight-rectangle
10342 beg (progn (skip-chars-forward "^|\n") (point))))
10343 ;; return string representation of calc vector
10344 (mapcar 'org-trim
10345 (apply 'append (org-table-copy-region beg end)))))))
10347 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10348 "Analyze descriptor DESC and retrieve the corresponding line number.
10349 The cursor is currently in line CLINE, the table begins in line BLINE,
10350 and TABLE is a vector with line types."
10351 (if (string-match "^[0-9]+$" desc)
10352 (aref org-table-dlines (string-to-number desc))
10353 (setq cline (or cline (org-current-line))
10354 bline (or bline org-table-current-begin-line)
10355 table (or table org-table-current-line-types))
10356 (if (or
10357 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10358 ;; 1 2 3 4 5 6
10359 (and (not (match-end 3)) (not (match-end 6)))
10360 (and (match-end 3) (match-end 6) (not (match-end 5))))
10361 (error "invalid row descriptor `%s'" desc))
10362 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10363 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10364 (odir (and (match-end 5) (match-string 5 desc)))
10365 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10366 (i (- cline bline))
10367 (rel (and (match-end 6)
10368 (or (and (match-end 1) (not (match-end 3)))
10369 (match-end 5)))))
10370 (if (and hn (not hdir))
10371 (progn
10372 (setq i 0 hdir "+")
10373 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10374 (if (and (not hn) on (not odir))
10375 (error "should never happen");;(aref org-table-dlines on)
10376 (if (and hn (> hn 0))
10377 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10378 (if on
10379 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10380 (+ bline i)))))
10382 (defun org-find-row-type (table i type backwards relative n)
10383 (let ((l (length table)))
10384 (while (> n 0)
10385 (while (and (setq i (+ i (if backwards -1 1)))
10386 (>= i 0) (< i l)
10387 (not (eq (aref table i) type))
10388 (if (and relative (eq (aref table i) 'hline))
10389 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10390 t)))
10391 (setq n (1- n)))
10392 (if (or (< i 0) (>= i l))
10393 (error "Row descriptior leads outside table")
10394 i)))
10396 (defun org-rewrite-old-row-references (s)
10397 (if (string-match "&[-+0-9I]" s)
10398 (error "Formula contains old &row reference, please rewrite using @-syntax")
10401 (defun org-table-make-reference (elements keep-empty numbers lispp)
10402 "Convert list ELEMENTS to something appropriate to insert into formula.
10403 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10404 NUMBERS indicates that everything should be converted to numbers.
10405 LISPP means to return something appropriate for a Lisp list."
10406 (if (stringp elements) ; just a single val
10407 (if lispp
10408 (if (eq lispp 'literal)
10409 elements
10410 (prin1-to-string (if numbers (string-to-number elements) elements)))
10411 (if (equal elements "") (setq elements "0"))
10412 (if numbers (number-to-string (string-to-number elements)) elements))
10413 (unless keep-empty
10414 (setq elements
10415 (delq nil
10416 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10417 elements))))
10418 (setq elements (or elements '("0")))
10419 (if lispp
10420 (mapconcat
10421 (lambda (x)
10422 (if (eq lispp 'literal)
10424 (prin1-to-string (if numbers (string-to-number x) x))))
10425 elements " ")
10426 (concat "[" (mapconcat
10427 (lambda (x)
10428 (if numbers (number-to-string (string-to-number x)) x))
10429 elements
10430 ",") "]"))))
10432 (defun org-table-recalculate (&optional all noalign)
10433 "Recalculate the current table line by applying all stored formulas.
10434 With prefix arg ALL, do this for all lines in the table."
10435 (interactive "P")
10436 (or (memq this-command org-recalc-commands)
10437 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10438 (unless (org-at-table-p) (error "Not at a table"))
10439 (if (equal all '(16))
10440 (org-table-iterate)
10441 (org-table-get-specials)
10442 (let* ((eqlist (sort (org-table-get-stored-formulas)
10443 (lambda (a b) (string< (car a) (car b)))))
10444 (inhibit-redisplay (not debug-on-error))
10445 (line-re org-table-dataline-regexp)
10446 (thisline (org-current-line))
10447 (thiscol (org-table-current-column))
10448 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10449 ;; Insert constants in all formulas
10450 (setq eqlist
10451 (mapcar (lambda (x)
10452 (setcdr x (org-table-formula-substitute-names (cdr x)))
10454 eqlist))
10455 ;; Split the equation list
10456 (while (setq eq (pop eqlist))
10457 (if (<= (string-to-char (car eq)) ?9)
10458 (push eq eqlnum)
10459 (push eq eqlname)))
10460 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10461 (if all
10462 (progn
10463 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10464 (goto-char (setq beg (org-table-begin)))
10465 (if (re-search-forward org-table-calculate-mark-regexp end t)
10466 ;; This is a table with marked lines, compute selected lines
10467 (setq line-re org-table-recalculate-regexp)
10468 ;; Move forward to the first non-header line
10469 (if (and (re-search-forward org-table-dataline-regexp end t)
10470 (re-search-forward org-table-hline-regexp end t)
10471 (re-search-forward org-table-dataline-regexp end t))
10472 (setq beg (match-beginning 0))
10473 nil))) ;; just leave beg where it is
10474 (setq beg (point-at-bol)
10475 end (move-marker (make-marker) (1+ (point-at-eol)))))
10476 (goto-char beg)
10477 (and all (message "Re-applying formulas to full table..."))
10479 ;; First find the named fields, and mark them untouchanble
10480 (remove-text-properties beg end '(org-untouchable t))
10481 (while (setq eq (pop eqlname))
10482 (setq name (car eq)
10483 a (assoc name org-table-named-field-locations))
10484 (and (not a)
10485 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10486 (setq a (list name
10487 (aref org-table-dlines
10488 (string-to-number (match-string 1 name)))
10489 (string-to-number (match-string 2 name)))))
10490 (when (and a (or all (equal (nth 1 a) thisline)))
10491 (message "Re-applying formula to field: %s" name)
10492 (goto-line (nth 1 a))
10493 (org-table-goto-column (nth 2 a))
10494 (push (append a (list (cdr eq))) eqlname1)
10495 (org-table-put-field-property :org-untouchable t)))
10497 ;; Now evauluate the column formulas, but skip fields covered by
10498 ;; field formulas
10499 (goto-char beg)
10500 (while (re-search-forward line-re end t)
10501 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10502 ;; Unprotected line, recalculate
10503 (and all (message "Re-applying formulas to full table...(line %d)"
10504 (setq cnt (1+ cnt))))
10505 (setq org-last-recalc-line (org-current-line))
10506 (setq eql eqlnum)
10507 (while (setq entry (pop eql))
10508 (goto-line org-last-recalc-line)
10509 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10510 (unless (get-text-property (point) :org-untouchable)
10511 (org-table-eval-formula nil (cdr entry)
10512 'noalign 'nocst 'nostore 'noanalysis)))))
10514 ;; Now evaluate the field formulas
10515 (while (setq eq (pop eqlname1))
10516 (message "Re-applying formula to field: %s" (car eq))
10517 (goto-line (nth 1 eq))
10518 (org-table-goto-column (nth 2 eq))
10519 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10520 'nostore 'noanalysis))
10522 (goto-line thisline)
10523 (org-table-goto-column thiscol)
10524 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10525 (or noalign (and org-table-may-need-update (org-table-align))
10526 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10528 ;; back to initial position
10529 (message "Re-applying formulas...done")
10530 (goto-line thisline)
10531 (org-table-goto-column thiscol)
10532 (or noalign (and org-table-may-need-update (org-table-align))
10533 (and all (message "Re-applying formulas...done"))))))
10535 (defun org-table-iterate (&optional arg)
10536 "Recalculate the table until it does not change anymore."
10537 (interactive "P")
10538 (let ((imax (if arg (prefix-numeric-value arg) 10))
10539 (i 0)
10540 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10541 thistbl)
10542 (catch 'exit
10543 (while (< i imax)
10544 (setq i (1+ i))
10545 (org-table-recalculate 'all)
10546 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10547 (if (not (string= lasttbl thistbl))
10548 (setq lasttbl thistbl)
10549 (if (> i 1)
10550 (message "Convergence after %d iterations" i)
10551 (message "Table was already stable"))
10552 (throw 'exit t)))
10553 (error "No convergence after %d iterations" i))))
10555 (defun org-table-formula-substitute-names (f)
10556 "Replace $const with values in string F."
10557 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10558 ;; First, check for column names
10559 (while (setq start (string-match org-table-column-name-regexp f start))
10560 (setq start (1+ start))
10561 (setq a (assoc (match-string 1 f) org-table-column-names))
10562 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10563 ;; Parameters and constants
10564 (setq start 0)
10565 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10566 (setq start (1+ start))
10567 (if (setq a (save-match-data
10568 (org-table-get-constant (match-string 1 f))))
10569 (setq f (replace-match
10570 (concat (if pp "(") a (if pp ")")) t t f))))
10571 (if org-table-formula-debug
10572 (put-text-property 0 (length f) :orig-formula f1 f))
10575 (defun org-table-get-constant (const)
10576 "Find the value for a parameter or constant in a formula.
10577 Parameters get priority."
10578 (or (cdr (assoc const org-table-local-parameters))
10579 (cdr (assoc const org-table-formula-constants-local))
10580 (cdr (assoc const org-table-formula-constants))
10581 (and (fboundp 'constants-get) (constants-get const))
10582 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10583 (org-entry-get nil (substring const 5) 'inherit))
10584 "#UNDEFINED_NAME"))
10586 (defvar org-table-fedit-map
10587 (let ((map (make-sparse-keymap)))
10588 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10589 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10590 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10591 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10592 (org-defkey map "\C-c?" 'org-table-show-reference)
10593 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10594 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10595 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10596 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10597 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10598 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10599 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10600 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10601 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10602 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10603 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10604 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10605 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10606 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10607 map))
10609 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10610 '("Edit-Formulas"
10611 ["Finish and Install" org-table-fedit-finish t]
10612 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10613 ["Abort" org-table-fedit-abort t]
10614 "--"
10615 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10616 ["Complete Lisp Symbol" lisp-complete-symbol t]
10617 "--"
10618 "Shift Reference at Point"
10619 ["Up" org-table-fedit-ref-up t]
10620 ["Down" org-table-fedit-ref-down t]
10621 ["Left" org-table-fedit-ref-left t]
10622 ["Right" org-table-fedit-ref-right t]
10624 "Change Test Row for Column Formulas"
10625 ["Up" org-table-fedit-line-up t]
10626 ["Down" org-table-fedit-line-down t]
10627 "--"
10628 ["Scroll Table Window" org-table-fedit-scroll t]
10629 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10630 ["Show Table Grid" org-table-fedit-toggle-coordinates
10631 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10632 org-table-overlay-coordinates)]
10633 "--"
10634 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10635 :style toggle :selected org-table-buffer-is-an]))
10637 (defvar org-pos)
10639 (defun org-table-edit-formulas ()
10640 "Edit the formulas of the current table in a separate buffer."
10641 (interactive)
10642 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10643 (beginning-of-line 0))
10644 (unless (org-at-table-p) (error "Not at a table"))
10645 (org-table-get-specials)
10646 (let ((key (org-table-current-field-formula 'key 'noerror))
10647 (eql (sort (org-table-get-stored-formulas 'noerror)
10648 'org-table-formula-less-p))
10649 (pos (move-marker (make-marker) (point)))
10650 (startline 1)
10651 (wc (current-window-configuration))
10652 (titles '((column . "# Column Formulas\n")
10653 (field . "# Field Formulas\n")
10654 (named . "# Named Field Formulas\n")))
10655 entry s type title)
10656 (org-switch-to-buffer-other-window "*Edit Formulas*")
10657 (erase-buffer)
10658 ;; Keep global-font-lock-mode from turning on font-lock-mode
10659 (let ((font-lock-global-modes '(not fundamental-mode)))
10660 (fundamental-mode))
10661 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10662 (org-set-local 'org-pos pos)
10663 (org-set-local 'org-window-configuration wc)
10664 (use-local-map org-table-fedit-map)
10665 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10666 (easy-menu-add org-table-fedit-menu)
10667 (setq startline (org-current-line))
10668 (while (setq entry (pop eql))
10669 (setq type (cond
10670 ((equal (string-to-char (car entry)) ?@) 'field)
10671 ((string-match "^[0-9]" (car entry)) 'column)
10672 (t 'named)))
10673 (when (setq title (assq type titles))
10674 (or (bobp) (insert "\n"))
10675 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10676 (setq titles (delq title titles)))
10677 (if (equal key (car entry)) (setq startline (org-current-line)))
10678 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10679 (car entry) " = " (cdr entry) "\n"))
10680 (remove-text-properties 0 (length s) '(face nil) s)
10681 (insert s))
10682 (if (eq org-table-use-standard-references t)
10683 (org-table-fedit-toggle-ref-type))
10684 (goto-line startline)
10685 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10687 (defun org-table-fedit-post-command ()
10688 (when (not (memq this-command '(lisp-complete-symbol)))
10689 (let ((win (selected-window)))
10690 (save-excursion
10691 (condition-case nil
10692 (org-table-show-reference)
10693 (error nil))
10694 (select-window win)))))
10696 (defun org-table-formula-to-user (s)
10697 "Convert a formula from internal to user representation."
10698 (if (eq org-table-use-standard-references t)
10699 (org-table-convert-refs-to-an s)
10702 (defun org-table-formula-from-user (s)
10703 "Convert a formula from user to internal representation."
10704 (if org-table-use-standard-references
10705 (org-table-convert-refs-to-rc s)
10708 (defun org-table-convert-refs-to-rc (s)
10709 "Convert spreadsheet references from AB7 to @7$28.
10710 Works for single references, but also for entire formulas and even the
10711 full TBLFM line."
10712 (let ((start 0))
10713 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10714 (cond
10715 ((match-end 3)
10716 ;; format match, just advance
10717 (setq start (match-end 0)))
10718 ((and (> (match-beginning 0) 0)
10719 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10720 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10721 ;; 3.e5 or something like this.
10722 (setq start (match-end 0)))
10724 (setq start (match-beginning 0)
10725 s (replace-match
10726 (if (equal (match-string 2 s) "&")
10727 (format "$%d" (org-letters-to-number (match-string 1 s)))
10728 (format "@%d$%d"
10729 (string-to-number (match-string 2 s))
10730 (org-letters-to-number (match-string 1 s))))
10731 t t s)))))
10734 (defun org-table-convert-refs-to-an (s)
10735 "Convert spreadsheet references from to @7$28 to AB7.
10736 Works for single references, but also for entire formulas and even the
10737 full TBLFM line."
10738 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10739 (setq s (replace-match
10740 (format "%s%d"
10741 (org-number-to-letters
10742 (string-to-number (match-string 2 s)))
10743 (string-to-number (match-string 1 s)))
10744 t t s)))
10745 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10746 (setq s (replace-match (concat "\\1"
10747 (org-number-to-letters
10748 (string-to-number (match-string 2 s))) "&")
10749 t nil s)))
10752 (defun org-letters-to-number (s)
10753 "Convert a base 26 number represented by letters into an integer.
10754 For example: AB -> 28."
10755 (let ((n 0))
10756 (setq s (upcase s))
10757 (while (> (length s) 0)
10758 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10759 s (substring s 1)))
10762 (defun org-number-to-letters (n)
10763 "Convert an integer into a base 26 number represented by letters.
10764 For example: 28 -> AB."
10765 (let ((s ""))
10766 (while (> n 0)
10767 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10768 n (/ (1- n) 26)))
10771 (defun org-table-fedit-convert-buffer (function)
10772 "Convert all references in this buffer, using FUNTION."
10773 (let ((line (org-current-line)))
10774 (goto-char (point-min))
10775 (while (not (eobp))
10776 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10777 (delete-region (point) (point-at-eol))
10778 (or (eobp) (forward-char 1)))
10779 (goto-line line)))
10781 (defun org-table-fedit-toggle-ref-type ()
10782 "Convert all references in the buffer from B3 to @3$2 and back."
10783 (interactive)
10784 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10785 (org-table-fedit-convert-buffer
10786 (if org-table-buffer-is-an
10787 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10788 (message "Reference type switched to %s"
10789 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10791 (defun org-table-fedit-ref-up ()
10792 "Shift the reference at point one row/hline up."
10793 (interactive)
10794 (org-table-fedit-shift-reference 'up))
10795 (defun org-table-fedit-ref-down ()
10796 "Shift the reference at point one row/hline down."
10797 (interactive)
10798 (org-table-fedit-shift-reference 'down))
10799 (defun org-table-fedit-ref-left ()
10800 "Shift the reference at point one field to the left."
10801 (interactive)
10802 (org-table-fedit-shift-reference 'left))
10803 (defun org-table-fedit-ref-right ()
10804 "Shift the reference at point one field to the right."
10805 (interactive)
10806 (org-table-fedit-shift-reference 'right))
10808 (defun org-table-fedit-shift-reference (dir)
10809 (cond
10810 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10811 (if (memq dir '(left right))
10812 (org-rematch-and-replace 1 (eq dir 'left))
10813 (error "Cannot shift reference in this direction")))
10814 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10815 ;; A B3-like reference
10816 (if (memq dir '(up down))
10817 (org-rematch-and-replace 2 (eq dir 'up))
10818 (org-rematch-and-replace 1 (eq dir 'left))))
10819 ((org-at-regexp-p
10820 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10821 ;; An internal reference
10822 (if (memq dir '(up down))
10823 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10824 (org-rematch-and-replace 5 (eq dir 'left))))))
10826 (defun org-rematch-and-replace (n &optional decr hline)
10827 "Re-match the group N, and replace it with the shifted refrence."
10828 (or (match-end n) (error "Cannot shift reference in this direction"))
10829 (goto-char (match-beginning n))
10830 (and (looking-at (regexp-quote (match-string n)))
10831 (replace-match (org-shift-refpart (match-string 0) decr hline)
10832 t t)))
10834 (defun org-shift-refpart (ref &optional decr hline)
10835 "Shift a refrence part REF.
10836 If DECR is set, decrease the references row/column, else increase.
10837 If HLINE is set, this may be a hline reference, it certainly is not
10838 a translation reference."
10839 (save-match-data
10840 (let* ((sign (string-match "^[-+]" ref)) n)
10842 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10843 (cond
10844 ((and hline (string-match "^I+" ref))
10845 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10846 (setq n (+ n (if decr -1 1)))
10847 (if (= n 0) (setq n (+ n (if decr -1 1))))
10848 (if sign
10849 (setq sign (if (< n 0) "-" "+") n (abs n))
10850 (setq n (max 1 n)))
10851 (concat sign (make-string n ?I)))
10853 ((string-match "^[0-9]+" ref)
10854 (setq n (string-to-number (concat sign ref)))
10855 (setq n (+ n (if decr -1 1)))
10856 (if sign
10857 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10858 (number-to-string (max 1 n))))
10860 ((string-match "^[a-zA-Z]+" ref)
10861 (org-number-to-letters
10862 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10864 (t (error "Cannot shift reference"))))))
10866 (defun org-table-fedit-toggle-coordinates ()
10867 "Toggle the display of coordinates in the refrenced table."
10868 (interactive)
10869 (let ((pos (marker-position org-pos)))
10870 (with-current-buffer (marker-buffer org-pos)
10871 (save-excursion
10872 (goto-char pos)
10873 (org-table-toggle-coordinate-overlays)))))
10875 (defun org-table-fedit-finish (&optional arg)
10876 "Parse the buffer for formula definitions and install them.
10877 With prefix ARG, apply the new formulas to the table."
10878 (interactive "P")
10879 (org-table-remove-rectangle-highlight)
10880 (if org-table-use-standard-references
10881 (progn
10882 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
10883 (setq org-table-buffer-is-an nil)))
10884 (let ((pos org-pos) eql var form)
10885 (goto-char (point-min))
10886 (while (re-search-forward
10887 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
10888 nil t)
10889 (setq var (if (match-end 2) (match-string 2) (match-string 1))
10890 form (match-string 3))
10891 (setq form (org-trim form))
10892 (when (not (equal form ""))
10893 (while (string-match "[ \t]*\n[ \t]*" form)
10894 (setq form (replace-match " " t t form)))
10895 (when (assoc var eql)
10896 (error "Double formulas for %s" var))
10897 (push (cons var form) eql)))
10898 (setq org-pos nil)
10899 (set-window-configuration org-window-configuration)
10900 (select-window (get-buffer-window (marker-buffer pos)))
10901 (goto-char pos)
10902 (unless (org-at-table-p)
10903 (error "Lost table position - cannot install formulae"))
10904 (org-table-store-formulas eql)
10905 (move-marker pos nil)
10906 (kill-buffer "*Edit Formulas*")
10907 (if arg
10908 (org-table-recalculate 'all)
10909 (message "New formulas installed - press C-u C-c C-c to apply."))))
10911 (defun org-table-fedit-abort ()
10912 "Abort editing formulas, without installing the changes."
10913 (interactive)
10914 (org-table-remove-rectangle-highlight)
10915 (let ((pos org-pos))
10916 (set-window-configuration org-window-configuration)
10917 (select-window (get-buffer-window (marker-buffer pos)))
10918 (goto-char pos)
10919 (move-marker pos nil)
10920 (message "Formula editing aborted without installing changes")))
10922 (defun org-table-fedit-lisp-indent ()
10923 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
10924 (interactive)
10925 (let ((pos (point)) beg end ind)
10926 (beginning-of-line 1)
10927 (cond
10928 ((looking-at "[ \t]")
10929 (goto-char pos)
10930 (call-interactively 'lisp-indent-line))
10931 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
10932 ((not (fboundp 'pp-buffer))
10933 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
10934 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
10935 (goto-char (- (match-end 0) 2))
10936 (setq beg (point))
10937 (setq ind (make-string (current-column) ?\ ))
10938 (condition-case nil (forward-sexp 1)
10939 (error
10940 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
10941 (setq end (point))
10942 (save-restriction
10943 (narrow-to-region beg end)
10944 (if (eq last-command this-command)
10945 (progn
10946 (goto-char (point-min))
10947 (setq this-command nil)
10948 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
10949 (replace-match " ")))
10950 (pp-buffer)
10951 (untabify (point-min) (point-max))
10952 (goto-char (1+ (point-min)))
10953 (while (re-search-forward "^." nil t)
10954 (beginning-of-line 1)
10955 (insert ind))
10956 (goto-char (point-max))
10957 (backward-delete-char 1)))
10958 (goto-char beg))
10959 (t nil))))
10961 (defvar org-show-positions nil)
10963 (defun org-table-show-reference (&optional local)
10964 "Show the location/value of the $ expression at point."
10965 (interactive)
10966 (org-table-remove-rectangle-highlight)
10967 (catch 'exit
10968 (let ((pos (if local (point) org-pos))
10969 (face2 'highlight)
10970 (org-inhibit-highlight-removal t)
10971 (win (selected-window))
10972 (org-show-positions nil)
10973 var name e what match dest)
10974 (if local (org-table-get-specials))
10975 (setq what (cond
10976 ((or (org-at-regexp-p org-table-range-regexp2)
10977 (org-at-regexp-p org-table-translate-regexp)
10978 (org-at-regexp-p org-table-range-regexp))
10979 (setq match
10980 (save-match-data
10981 (org-table-convert-refs-to-rc (match-string 0))))
10982 'range)
10983 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
10984 ((org-at-regexp-p "\\$[0-9]+") 'column)
10985 ((not local) nil)
10986 (t (error "No reference at point")))
10987 match (and what (or match (match-string 0))))
10988 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
10989 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
10990 'secondary-selection))
10991 (org-add-hook 'before-change-functions
10992 'org-table-remove-rectangle-highlight)
10993 (if (eq what 'name) (setq var (substring match 1)))
10994 (when (eq what 'range)
10995 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
10996 (setq match (org-table-formula-substitute-names match)))
10997 (unless local
10998 (save-excursion
10999 (end-of-line 1)
11000 (re-search-backward "^\\S-" nil t)
11001 (beginning-of-line 1)
11002 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
11003 (setq dest
11004 (save-match-data
11005 (org-table-convert-refs-to-rc (match-string 1))))
11006 (org-table-add-rectangle-overlay
11007 (match-beginning 1) (match-end 1) face2))))
11008 (if (and (markerp pos) (marker-buffer pos))
11009 (if (get-buffer-window (marker-buffer pos))
11010 (select-window (get-buffer-window (marker-buffer pos)))
11011 (org-switch-to-buffer-other-window (get-buffer-window
11012 (marker-buffer pos)))))
11013 (goto-char pos)
11014 (org-table-force-dataline)
11015 (when dest
11016 (setq name (substring dest 1))
11017 (cond
11018 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
11019 (setq e (assoc name org-table-named-field-locations))
11020 (goto-line (nth 1 e))
11021 (org-table-goto-column (nth 2 e)))
11022 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
11023 (let ((l (string-to-number (match-string 1 dest)))
11024 (c (string-to-number (match-string 2 dest))))
11025 (goto-line (aref org-table-dlines l))
11026 (org-table-goto-column c)))
11027 (t (org-table-goto-column (string-to-number name))))
11028 (move-marker pos (point))
11029 (org-table-highlight-rectangle nil nil face2))
11030 (cond
11031 ((equal dest match))
11032 ((not match))
11033 ((eq what 'range)
11034 (condition-case nil
11035 (save-excursion
11036 (org-table-get-range match nil nil 'highlight))
11037 (error nil)))
11038 ((setq e (assoc var org-table-named-field-locations))
11039 (goto-line (nth 1 e))
11040 (org-table-goto-column (nth 2 e))
11041 (org-table-highlight-rectangle (point) (point))
11042 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
11043 ((setq e (assoc var org-table-column-names))
11044 (org-table-goto-column (string-to-number (cdr e)))
11045 (org-table-highlight-rectangle (point) (point))
11046 (goto-char (org-table-begin))
11047 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
11048 (org-table-end) t)
11049 (progn
11050 (goto-char (match-beginning 1))
11051 (org-table-highlight-rectangle)
11052 (message "Named column (column %s)" (cdr e)))
11053 (error "Column name not found")))
11054 ((eq what 'column)
11055 ;; column number
11056 (org-table-goto-column (string-to-number (substring match 1)))
11057 (org-table-highlight-rectangle (point) (point))
11058 (message "Column %s" (substring match 1)))
11059 ((setq e (assoc var org-table-local-parameters))
11060 (goto-char (org-table-begin))
11061 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
11062 (progn
11063 (goto-char (match-beginning 1))
11064 (org-table-highlight-rectangle)
11065 (message "Local parameter."))
11066 (error "Parameter not found")))
11068 (cond
11069 ((not var) (error "No reference at point"))
11070 ((setq e (assoc var org-table-formula-constants-local))
11071 (message "Local Constant: $%s=%s in #+CONSTANTS line."
11072 var (cdr e)))
11073 ((setq e (assoc var org-table-formula-constants))
11074 (message "Constant: $%s=%s in `org-table-formula-constants'."
11075 var (cdr e)))
11076 ((setq e (and (fboundp 'constants-get) (constants-get var)))
11077 (message "Constant: $%s=%s, from `constants.el'%s."
11078 var e (format " (%s units)" constants-unit-system)))
11079 (t (error "Undefined name $%s" var)))))
11080 (goto-char pos)
11081 (when (and org-show-positions
11082 (not (memq this-command '(org-table-fedit-scroll
11083 org-table-fedit-scroll-down))))
11084 (push pos org-show-positions)
11085 (push org-table-current-begin-pos org-show-positions)
11086 (let ((min (apply 'min org-show-positions))
11087 (max (apply 'max org-show-positions)))
11088 (goto-char min) (recenter 0)
11089 (goto-char max)
11090 (or (pos-visible-in-window-p max) (recenter -1))))
11091 (select-window win))))
11093 (defun org-table-force-dataline ()
11094 "Make sure the cursor is in a dataline in a table."
11095 (unless (save-excursion
11096 (beginning-of-line 1)
11097 (looking-at org-table-dataline-regexp))
11098 (let* ((re org-table-dataline-regexp)
11099 (p1 (save-excursion (re-search-forward re nil 'move)))
11100 (p2 (save-excursion (re-search-backward re nil 'move))))
11101 (cond ((and p1 p2)
11102 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
11103 p1 p2)))
11104 ((or p1 p2) (goto-char (or p1 p2)))
11105 (t (error "No table dataline around here"))))))
11107 (defun org-table-fedit-line-up ()
11108 "Move cursor one line up in the window showing the table."
11109 (interactive)
11110 (org-table-fedit-move 'previous-line))
11112 (defun org-table-fedit-line-down ()
11113 "Move cursor one line down in the window showing the table."
11114 (interactive)
11115 (org-table-fedit-move 'next-line))
11117 (defun org-table-fedit-move (command)
11118 "Move the cursor in the window shoinw the table.
11119 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
11120 (let ((org-table-allow-automatic-line-recalculation nil)
11121 (pos org-pos) (win (selected-window)) p)
11122 (select-window (get-buffer-window (marker-buffer org-pos)))
11123 (setq p (point))
11124 (call-interactively command)
11125 (while (and (org-at-table-p)
11126 (org-at-table-hline-p))
11127 (call-interactively command))
11128 (or (org-at-table-p) (goto-char p))
11129 (move-marker pos (point))
11130 (select-window win)))
11132 (defun org-table-fedit-scroll (N)
11133 (interactive "p")
11134 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
11135 (scroll-other-window N)))
11137 (defun org-table-fedit-scroll-down (N)
11138 (interactive "p")
11139 (org-table-fedit-scroll (- N)))
11141 (defvar org-table-rectangle-overlays nil)
11143 (defun org-table-add-rectangle-overlay (beg end &optional face)
11144 "Add a new overlay."
11145 (let ((ov (org-make-overlay beg end)))
11146 (org-overlay-put ov 'face (or face 'secondary-selection))
11147 (push ov org-table-rectangle-overlays)))
11149 (defun org-table-highlight-rectangle (&optional beg end face)
11150 "Highlight rectangular region in a table."
11151 (setq beg (or beg (point)) end (or end (point)))
11152 (let ((b (min beg end))
11153 (e (max beg end))
11154 l1 c1 l2 c2 tmp)
11155 (and (boundp 'org-show-positions)
11156 (setq org-show-positions (cons b (cons e org-show-positions))))
11157 (goto-char (min beg end))
11158 (setq l1 (org-current-line)
11159 c1 (org-table-current-column))
11160 (goto-char (max beg end))
11161 (setq l2 (org-current-line)
11162 c2 (org-table-current-column))
11163 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
11164 (goto-line l1)
11165 (beginning-of-line 1)
11166 (loop for line from l1 to l2 do
11167 (when (looking-at org-table-dataline-regexp)
11168 (org-table-goto-column c1)
11169 (skip-chars-backward "^|\n") (setq beg (point))
11170 (org-table-goto-column c2)
11171 (skip-chars-forward "^|\n") (setq end (point))
11172 (org-table-add-rectangle-overlay beg end face))
11173 (beginning-of-line 2))
11174 (goto-char b))
11175 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
11177 (defun org-table-remove-rectangle-highlight (&rest ignore)
11178 "Remove the rectangle overlays."
11179 (unless org-inhibit-highlight-removal
11180 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
11181 (mapc 'org-delete-overlay org-table-rectangle-overlays)
11182 (setq org-table-rectangle-overlays nil)))
11184 (defvar org-table-coordinate-overlays nil
11185 "Collects the cooordinate grid overlays, so that they can be removed.")
11186 (make-variable-buffer-local 'org-table-coordinate-overlays)
11188 (defun org-table-overlay-coordinates ()
11189 "Add overlays to the table at point, to show row/column coordinates."
11190 (interactive)
11191 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11192 (setq org-table-coordinate-overlays nil)
11193 (save-excursion
11194 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
11195 (goto-char (org-table-begin))
11196 (while (org-at-table-p)
11197 (setq eol (point-at-eol))
11198 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
11199 (push ov org-table-coordinate-overlays)
11200 (setq hline (looking-at org-table-hline-regexp))
11201 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
11202 (format "%4d" (setq id (1+ id)))))
11203 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
11204 (when hline
11205 (setq ic 0)
11206 (while (re-search-forward "[+|]\\(-+\\)" eol t)
11207 (setq beg (1+ (match-beginning 0))
11208 ic (1+ ic)
11209 s1 (concat "$" (int-to-string ic))
11210 s2 (org-number-to-letters ic)
11211 str (if (eq org-table-use-standard-references t) s2 s1))
11212 (setq ov (org-make-overlay beg (+ beg (length str))))
11213 (push ov org-table-coordinate-overlays)
11214 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
11215 (beginning-of-line 2)))))
11217 (defun org-table-toggle-coordinate-overlays ()
11218 "Toggle the display of Row/Column numbers in tables."
11219 (interactive)
11220 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
11221 (message "Row/Column number display turned %s"
11222 (if org-table-overlay-coordinates "on" "off"))
11223 (if (and (org-at-table-p) org-table-overlay-coordinates)
11224 (org-table-align))
11225 (unless org-table-overlay-coordinates
11226 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11227 (setq org-table-coordinate-overlays nil)))
11229 (defun org-table-toggle-formula-debugger ()
11230 "Toggle the formula debugger in tables."
11231 (interactive)
11232 (setq org-table-formula-debug (not org-table-formula-debug))
11233 (message "Formula debugging has been turned %s"
11234 (if org-table-formula-debug "on" "off")))
11236 ;;; The orgtbl minor mode
11238 ;; Define a minor mode which can be used in other modes in order to
11239 ;; integrate the org-mode table editor.
11241 ;; This is really a hack, because the org-mode table editor uses several
11242 ;; keys which normally belong to the major mode, for example the TAB and
11243 ;; RET keys. Here is how it works: The minor mode defines all the keys
11244 ;; necessary to operate the table editor, but wraps the commands into a
11245 ;; function which tests if the cursor is currently inside a table. If that
11246 ;; is the case, the table editor command is executed. However, when any of
11247 ;; those keys is used outside a table, the function uses `key-binding' to
11248 ;; look up if the key has an associated command in another currently active
11249 ;; keymap (minor modes, major mode, global), and executes that command.
11250 ;; There might be problems if any of the keys used by the table editor is
11251 ;; otherwise used as a prefix key.
11253 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11254 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11255 ;; addresses this by checking explicitly for both bindings.
11257 ;; The optimized version (see variable `orgtbl-optimized') takes over
11258 ;; all keys which are bound to `self-insert-command' in the *global map*.
11259 ;; Some modes bind other commands to simple characters, for example
11260 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11261 ;; active, this binding is ignored inside tables and replaced with a
11262 ;; modified self-insert.
11264 (defvar orgtbl-mode nil
11265 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11266 table editor in arbitrary modes.")
11267 (make-variable-buffer-local 'orgtbl-mode)
11269 (defvar orgtbl-mode-map (make-keymap)
11270 "Keymap for `orgtbl-mode'.")
11272 ;;;###autoload
11273 (defun turn-on-orgtbl ()
11274 "Unconditionally turn on `orgtbl-mode'."
11275 (orgtbl-mode 1))
11277 (defvar org-old-auto-fill-inhibit-regexp nil
11278 "Local variable used by `orgtbl-mode'")
11280 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
11281 "Matches a line belonging to an orgtbl.")
11283 (defconst orgtbl-extra-font-lock-keywords
11284 (list (list (concat "^" orgtbl-line-start-regexp ".*")
11285 0 (quote 'org-table) 'prepend))
11286 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
11288 ;;;###autoload
11289 (defun orgtbl-mode (&optional arg)
11290 "The `org-mode' table editor as a minor mode for use in other modes."
11291 (interactive)
11292 (if (org-mode-p)
11293 ;; Exit without error, in case some hook functions calls this
11294 ;; by accident in org-mode.
11295 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11296 (setq orgtbl-mode
11297 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11298 (if orgtbl-mode
11299 (progn
11300 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11301 ;; Make sure we are first in minor-mode-map-alist
11302 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11303 (and c (setq minor-mode-map-alist
11304 (cons c (delq c minor-mode-map-alist)))))
11305 (org-set-local (quote org-table-may-need-update) t)
11306 (org-add-hook 'before-change-functions 'org-before-change-function
11307 nil 'local)
11308 (org-set-local 'org-old-auto-fill-inhibit-regexp
11309 auto-fill-inhibit-regexp)
11310 (org-set-local 'auto-fill-inhibit-regexp
11311 (if auto-fill-inhibit-regexp
11312 (concat orgtbl-line-start-regexp "\\|"
11313 auto-fill-inhibit-regexp)
11314 orgtbl-line-start-regexp))
11315 (org-add-to-invisibility-spec '(org-cwidth))
11316 (when (fboundp 'font-lock-add-keywords)
11317 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11318 (org-restart-font-lock))
11319 (easy-menu-add orgtbl-mode-menu)
11320 (run-hooks 'orgtbl-mode-hook))
11321 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11322 (org-cleanup-narrow-column-properties)
11323 (org-remove-from-invisibility-spec '(org-cwidth))
11324 (remove-hook 'before-change-functions 'org-before-change-function t)
11325 (when (fboundp 'font-lock-remove-keywords)
11326 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11327 (org-restart-font-lock))
11328 (easy-menu-remove orgtbl-mode-menu)
11329 (force-mode-line-update 'all))))
11331 (defun org-cleanup-narrow-column-properties ()
11332 "Remove all properties related to narrow-column invisibility."
11333 (let ((s 1))
11334 (while (setq s (text-property-any s (point-max)
11335 'display org-narrow-column-arrow))
11336 (remove-text-properties s (1+ s) '(display t)))
11337 (setq s 1)
11338 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11339 (remove-text-properties s (1+ s) '(org-cwidth t)))
11340 (setq s 1)
11341 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11342 (remove-text-properties s (1+ s) '(invisible t)))))
11344 ;; Install it as a minor mode.
11345 (put 'orgtbl-mode :included t)
11346 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11347 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11349 (defun orgtbl-make-binding (fun n &rest keys)
11350 "Create a function for binding in the table minor mode.
11351 FUN is the command to call inside a table. N is used to create a unique
11352 command name. KEYS are keys that should be checked in for a command
11353 to execute outside of tables."
11354 (eval
11355 (list 'defun
11356 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11357 '(arg)
11358 (concat "In tables, run `" (symbol-name fun) "'.\n"
11359 "Outside of tables, run the binding of `"
11360 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11361 "'.")
11362 '(interactive "p")
11363 (list 'if
11364 '(org-at-table-p)
11365 (list 'call-interactively (list 'quote fun))
11366 (list 'let '(orgtbl-mode)
11367 (list 'call-interactively
11368 (append '(or)
11369 (mapcar (lambda (k)
11370 (list 'key-binding k))
11371 keys)
11372 '('orgtbl-error))))))))
11374 (defun orgtbl-error ()
11375 "Error when there is no default binding for a table key."
11376 (interactive)
11377 (error "This key has no function outside tables"))
11379 (defun orgtbl-setup ()
11380 "Setup orgtbl keymaps."
11381 (let ((nfunc 0)
11382 (bindings
11383 (list
11384 '([(meta shift left)] org-table-delete-column)
11385 '([(meta left)] org-table-move-column-left)
11386 '([(meta right)] org-table-move-column-right)
11387 '([(meta shift right)] org-table-insert-column)
11388 '([(meta shift up)] org-table-kill-row)
11389 '([(meta shift down)] org-table-insert-row)
11390 '([(meta up)] org-table-move-row-up)
11391 '([(meta down)] org-table-move-row-down)
11392 '("\C-c\C-w" org-table-cut-region)
11393 '("\C-c\M-w" org-table-copy-region)
11394 '("\C-c\C-y" org-table-paste-rectangle)
11395 '("\C-c-" org-table-insert-hline)
11396 '("\C-c}" org-table-toggle-coordinate-overlays)
11397 '("\C-c{" org-table-toggle-formula-debugger)
11398 '("\C-m" org-table-next-row)
11399 '([(shift return)] org-table-copy-down)
11400 '("\C-c\C-q" org-table-wrap-region)
11401 '("\C-c?" org-table-field-info)
11402 '("\C-c " org-table-blank-field)
11403 '("\C-c+" org-table-sum)
11404 '("\C-c=" org-table-eval-formula)
11405 '("\C-c'" org-table-edit-formulas)
11406 '("\C-c`" org-table-edit-field)
11407 '("\C-c*" org-table-recalculate)
11408 '("\C-c|" org-table-create-or-convert-from-region)
11409 '("\C-c^" org-table-sort-lines)
11410 '([(control ?#)] org-table-rotate-recalc-marks)))
11411 elt key fun cmd)
11412 (while (setq elt (pop bindings))
11413 (setq nfunc (1+ nfunc))
11414 (setq key (org-key (car elt))
11415 fun (nth 1 elt)
11416 cmd (orgtbl-make-binding fun nfunc key))
11417 (org-defkey orgtbl-mode-map key cmd))
11419 ;; Special treatment needed for TAB and RET
11420 (org-defkey orgtbl-mode-map [(return)]
11421 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11422 (org-defkey orgtbl-mode-map "\C-m"
11423 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11425 (org-defkey orgtbl-mode-map [(tab)]
11426 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11427 (org-defkey orgtbl-mode-map "\C-i"
11428 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11430 (org-defkey orgtbl-mode-map [(shift tab)]
11431 (orgtbl-make-binding 'org-table-previous-field 104
11432 [(shift tab)] [(tab)] "\C-i"))
11434 (org-defkey orgtbl-mode-map "\M-\C-m"
11435 (orgtbl-make-binding 'org-table-wrap-region 105
11436 "\M-\C-m" [(meta return)]))
11437 (org-defkey orgtbl-mode-map [(meta return)]
11438 (orgtbl-make-binding 'org-table-wrap-region 106
11439 [(meta return)] "\M-\C-m"))
11441 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11442 (when orgtbl-optimized
11443 ;; If the user wants maximum table support, we need to hijack
11444 ;; some standard editing functions
11445 (org-remap orgtbl-mode-map
11446 'self-insert-command 'orgtbl-self-insert-command
11447 'delete-char 'org-delete-char
11448 'delete-backward-char 'org-delete-backward-char)
11449 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11450 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11451 '("OrgTbl"
11452 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11453 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11454 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11455 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11456 "--"
11457 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11458 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11459 ["Copy Field from Above"
11460 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11461 "--"
11462 ("Column"
11463 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11464 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11465 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11466 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11467 ("Row"
11468 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11469 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11470 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11471 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11472 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
11473 "--"
11474 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11475 ("Rectangle"
11476 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11477 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11478 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11479 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11480 "--"
11481 ("Radio tables"
11482 ["Insert table template" orgtbl-insert-radio-table
11483 (assq major-mode orgtbl-radio-table-templates)]
11484 ["Comment/uncomment table" orgtbl-toggle-comment t])
11485 "--"
11486 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11487 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11488 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11489 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11490 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11491 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11492 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11493 ["Sum Column/Rectangle" org-table-sum
11494 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11495 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11496 ["Debug Formulas"
11497 org-table-toggle-formula-debugger :active (org-at-table-p)
11498 :keys "C-c {"
11499 :style toggle :selected org-table-formula-debug]
11500 ["Show Col/Row Numbers"
11501 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11502 :keys "C-c }"
11503 :style toggle :selected org-table-overlay-coordinates]
11507 (defun orgtbl-ctrl-c-ctrl-c (arg)
11508 "If the cursor is inside a table, realign the table.
11509 It it is a table to be sent away to a receiver, do it.
11510 With prefix arg, also recompute table."
11511 (interactive "P")
11512 (let ((pos (point)) action)
11513 (save-excursion
11514 (beginning-of-line 1)
11515 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11516 ((looking-at "[ \t]*|") pos)
11517 ((looking-at "#\\+TBLFM:") 'recalc))))
11518 (cond
11519 ((integerp action)
11520 (goto-char action)
11521 (org-table-maybe-eval-formula)
11522 (if arg
11523 (call-interactively 'org-table-recalculate)
11524 (org-table-maybe-recalculate-line))
11525 (call-interactively 'org-table-align)
11526 (orgtbl-send-table 'maybe))
11527 ((eq action 'recalc)
11528 (save-excursion
11529 (beginning-of-line 1)
11530 (skip-chars-backward " \r\n\t")
11531 (if (org-at-table-p)
11532 (org-call-with-arg 'org-table-recalculate t))))
11533 (t (let (orgtbl-mode)
11534 (call-interactively (key-binding "\C-c\C-c")))))))
11536 (defun orgtbl-tab (arg)
11537 "Justification and field motion for `orgtbl-mode'."
11538 (interactive "P")
11539 (if arg (org-table-edit-field t)
11540 (org-table-justify-field-maybe)
11541 (org-table-next-field)))
11543 (defun orgtbl-ret ()
11544 "Justification and field motion for `orgtbl-mode'."
11545 (interactive)
11546 (org-table-justify-field-maybe)
11547 (org-table-next-row))
11549 (defun orgtbl-self-insert-command (N)
11550 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11551 If the cursor is in a table looking at whitespace, the whitespace is
11552 overwritten, and the table is not marked as requiring realignment."
11553 (interactive "p")
11554 (if (and (org-at-table-p)
11556 (and org-table-auto-blank-field
11557 (member last-command
11558 '(orgtbl-hijacker-command-100
11559 orgtbl-hijacker-command-101
11560 orgtbl-hijacker-command-102
11561 orgtbl-hijacker-command-103
11562 orgtbl-hijacker-command-104
11563 orgtbl-hijacker-command-105))
11564 (org-table-blank-field))
11566 (eq N 1)
11567 (looking-at "[^|\n]* +|"))
11568 (let (org-table-may-need-update)
11569 (goto-char (1- (match-end 0)))
11570 (delete-backward-char 1)
11571 (goto-char (match-beginning 0))
11572 (self-insert-command N))
11573 (setq org-table-may-need-update t)
11574 (let (orgtbl-mode)
11575 (call-interactively (key-binding (vector last-input-event))))))
11577 (defun org-force-self-insert (N)
11578 "Needed to enforce self-insert under remapping."
11579 (interactive "p")
11580 (self-insert-command N))
11582 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11583 "Regula expression matching exponentials as produced by calc.")
11585 (defvar org-table-clean-did-remove-column nil)
11587 (defun orgtbl-export (table target)
11588 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11589 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11590 org-table-last-alignment org-table-last-column-widths
11591 maxcol column)
11592 (if (not (fboundp func))
11593 (error "Cannot export orgtbl table to %s" target))
11594 (setq lines (org-table-clean-before-export lines))
11595 (setq table
11596 (mapcar
11597 (lambda (x)
11598 (if (string-match org-table-hline-regexp x)
11599 'hline
11600 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11601 lines))
11602 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11603 table)))
11604 (loop for i from (1- maxcol) downto 0 do
11605 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11606 (setq column (delq nil column))
11607 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11608 (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))
11609 (funcall func table nil)))
11611 (defun orgtbl-send-table (&optional maybe)
11612 "Send a tranformed version of this table to the receiver position.
11613 With argument MAYBE, fail quietly if no transformation is defined for
11614 this table."
11615 (interactive)
11616 (catch 'exit
11617 (unless (org-at-table-p) (error "Not at a table"))
11618 ;; when non-interactive, we assume align has just happened.
11619 (when (interactive-p) (org-table-align))
11620 (save-excursion
11621 (goto-char (org-table-begin))
11622 (beginning-of-line 0)
11623 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11624 (if maybe
11625 (throw 'exit nil)
11626 (error "Don't know how to transform this table."))))
11627 (let* ((name (match-string 1))
11629 (transform (intern (match-string 2)))
11630 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11631 (skip (plist-get params :skip))
11632 (skipcols (plist-get params :skipcols))
11633 (txt (buffer-substring-no-properties
11634 (org-table-begin) (org-table-end)))
11635 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11636 (lines (org-table-clean-before-export lines))
11637 (i0 (if org-table-clean-did-remove-column 2 1))
11638 (table (mapcar
11639 (lambda (x)
11640 (if (string-match org-table-hline-regexp x)
11641 'hline
11642 (org-remove-by-index
11643 (org-split-string (org-trim x) "\\s-*|\\s-*")
11644 skipcols i0)))
11645 lines))
11646 (fun (if (= i0 2) 'cdr 'identity))
11647 (org-table-last-alignment
11648 (org-remove-by-index (funcall fun org-table-last-alignment)
11649 skipcols i0))
11650 (org-table-last-column-widths
11651 (org-remove-by-index (funcall fun org-table-last-column-widths)
11652 skipcols i0)))
11654 (unless (fboundp transform)
11655 (error "No such transformation function %s" transform))
11656 (setq txt (funcall transform table params))
11657 ;; Find the insertion place
11658 (save-excursion
11659 (goto-char (point-min))
11660 (unless (re-search-forward
11661 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11662 (error "Don't know where to insert translated table"))
11663 (goto-char (match-beginning 0))
11664 (beginning-of-line 2)
11665 (setq beg (point))
11666 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11667 (error "Cannot find end of insertion region"))
11668 (beginning-of-line 1)
11669 (delete-region beg (point))
11670 (goto-char beg)
11671 (insert txt "\n"))
11672 (message "Table converted and installed at receiver location"))))
11674 (defun org-remove-by-index (list indices &optional i0)
11675 "Remove the elements in LIST with indices in INDICES.
11676 First element has index 0, or I0 if given."
11677 (if (not indices)
11678 list
11679 (if (integerp indices) (setq indices (list indices)))
11680 (setq i0 (1- (or i0 0)))
11681 (delq :rm (mapcar (lambda (x)
11682 (setq i0 (1+ i0))
11683 (if (memq i0 indices) :rm x))
11684 list))))
11686 (defun orgtbl-toggle-comment ()
11687 "Comment or uncomment the orgtbl at point."
11688 (interactive)
11689 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11690 (re2 (concat "^" orgtbl-line-start-regexp))
11691 (commented (save-excursion (beginning-of-line 1)
11692 (cond ((looking-at re1) t)
11693 ((looking-at re2) nil)
11694 (t (error "Not at an org table")))))
11695 (re (if commented re1 re2))
11696 beg end)
11697 (save-excursion
11698 (beginning-of-line 1)
11699 (while (looking-at re) (beginning-of-line 0))
11700 (beginning-of-line 2)
11701 (setq beg (point))
11702 (while (looking-at re) (beginning-of-line 2))
11703 (setq end (point)))
11704 (comment-region beg end (if commented '(4) nil))))
11706 (defun orgtbl-insert-radio-table ()
11707 "Insert a radio table template appropriate for this major mode."
11708 (interactive)
11709 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11710 (txt (nth 1 e))
11711 name pos)
11712 (unless e (error "No radio table setup defined for %s" major-mode))
11713 (setq name (read-string "Table name: "))
11714 (while (string-match "%n" txt)
11715 (setq txt (replace-match name t t txt)))
11716 (or (bolp) (insert "\n"))
11717 (setq pos (point))
11718 (insert txt)
11719 (goto-char pos)))
11721 (defun org-get-param (params header i sym &optional hsym)
11722 "Get parameter value for symbol SYM.
11723 If this is a header line, actually get the value for the symbol with an
11724 additional \"h\" inserted after the colon.
11725 If the value is a protperty list, get the element for the current column.
11726 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11727 (let ((val (plist-get params sym)))
11728 (and hsym header (setq val (or (plist-get params hsym) val)))
11729 (if (consp val) (plist-get val i) val)))
11731 (defun orgtbl-to-generic (table params)
11732 "Convert the orgtbl-mode TABLE to some other format.
11733 This generic routine can be used for many standard cases.
11734 TABLE is a list, each entry either the symbol `hline' for a horizontal
11735 separator line, or a list of fields for that line.
11736 PARAMS is a property list of parameters that can influence the conversion.
11737 For the generic converter, some parameters are obligatory: You need to
11738 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11739 :splice, you must have :tstart and :tend.
11741 Valid parameters are
11743 :tstart String to start the table. Ignored when :splice is t.
11744 :tend String to end the table. Ignored when :splice is t.
11746 :splice When set to t, return only table body lines, don't wrap
11747 them into :tstart and :tend. Default is nil.
11749 :hline String to be inserted on horizontal separation lines.
11750 May be nil to ignore hlines.
11752 :lstart String to start a new table line.
11753 :lend String to end a table line
11754 :sep Separator between two fields
11755 :lfmt Format for entire line, with enough %s to capture all fields.
11756 If this is present, :lstart, :lend, and :sep are ignored.
11757 :fmt A format to be used to wrap the field, should contain
11758 %s for the original field value. For example, to wrap
11759 everything in dollars, you could use :fmt \"$%s$\".
11760 This may also be a property list with column numbers and
11761 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11763 :hlstart :hlend :hlsep :hlfmt :hfmt
11764 Same as above, specific for the header lines in the table.
11765 All lines before the first hline are treated as header.
11766 If any of these is not present, the data line value is used.
11768 :efmt Use this format to print numbers with exponentials.
11769 The format should have %s twice for inserting mantissa
11770 and exponent, for example \"%s\\\\times10^{%s}\". This
11771 may also be a property list with column numbers and
11772 formats. :fmt will still be applied after :efmt.
11774 In addition to this, the parameters :skip and :skipcols are always handled
11775 directly by `orgtbl-send-table'. See manual."
11776 (interactive)
11777 (let* ((p params)
11778 (splicep (plist-get p :splice))
11779 (hline (plist-get p :hline))
11780 rtn line i fm efm lfmt h)
11782 ;; Do we have a header?
11783 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11784 (setq h t))
11786 ;; Put header
11787 (unless splicep
11788 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11790 ;; Now loop over all lines
11791 (while (setq line (pop table))
11792 (if (eq line 'hline)
11793 ;; A horizontal separator line
11794 (progn (if hline (push hline rtn))
11795 (setq h nil)) ; no longer in header
11796 ;; A normal line. Convert the fields, push line onto the result list
11797 (setq i 0)
11798 (setq line
11799 (mapcar
11800 (lambda (f)
11801 (setq i (1+ i)
11802 fm (org-get-param p h i :fmt :hfmt)
11803 efm (org-get-param p h i :efmt))
11804 (if (and efm (string-match orgtbl-exp-regexp f))
11805 (setq f (format
11806 efm (match-string 1 f) (match-string 2 f))))
11807 (if fm (setq f (format fm f)))
11809 line))
11810 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11811 (push (apply 'format lfmt line) rtn)
11812 (push (concat
11813 (org-get-param p h i :lstart :hlstart)
11814 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11815 (org-get-param p h i :lend :hlend))
11816 rtn))))
11818 (unless splicep
11819 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11821 (mapconcat 'identity (nreverse rtn) "\n")))
11823 (defun orgtbl-to-latex (table params)
11824 "Convert the orgtbl-mode TABLE to LaTeX.
11825 TABLE is a list, each entry either the symbol `hline' for a horizontal
11826 separator line, or a list of fields for that line.
11827 PARAMS is a property list of parameters that can influence the conversion.
11828 Supports all parameters from `orgtbl-to-generic'. Most important for
11829 LaTeX are:
11831 :splice When set to t, return only table body lines, don't wrap
11832 them into a tabular environment. Default is nil.
11834 :fmt A format to be used to wrap the field, should contain %s for the
11835 original field value. For example, to wrap everything in dollars,
11836 use :fmt \"$%s$\". This may also be a property list with column
11837 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11839 :efmt Format for transforming numbers with exponentials. The format
11840 should have %s twice for inserting mantissa and exponent, for
11841 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11842 This may also be a property list with column numbers and formats.
11844 The general parameters :skip and :skipcols have already been applied when
11845 this function is called."
11846 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11847 org-table-last-alignment ""))
11848 (params2
11849 (list
11850 :tstart (concat "\\begin{tabular}{" alignment "}")
11851 :tend "\\end{tabular}"
11852 :lstart "" :lend " \\\\" :sep " & "
11853 :efmt "%s\\,(%s)" :hline "\\hline")))
11854 (orgtbl-to-generic table (org-combine-plists params2 params))))
11856 (defun orgtbl-to-html (table params)
11857 "Convert the orgtbl-mode TABLE to LaTeX.
11858 TABLE is a list, each entry either the symbol `hline' for a horizontal
11859 separator line, or a list of fields for that line.
11860 PARAMS is a property list of parameters that can influence the conversion.
11861 Currently this function recognizes the following parameters:
11863 :splice When set to t, return only table body lines, don't wrap
11864 them into a <table> environment. Default is nil.
11866 The general parameters :skip and :skipcols have already been applied when
11867 this function is called. The function does *not* use `orgtbl-to-generic',
11868 so you cannot specify parameters for it."
11869 (let* ((splicep (plist-get params :splice))
11870 html)
11871 ;; Just call the formatter we already have
11872 ;; We need to make text lines for it, so put the fields back together.
11873 (setq html (org-format-org-table-html
11874 (mapcar
11875 (lambda (x)
11876 (if (eq x 'hline)
11877 "|----+----|"
11878 (concat "| " (mapconcat 'identity x " | ") " |")))
11879 table)
11880 splicep))
11881 (if (string-match "\n+\\'" html)
11882 (setq html (replace-match "" t t html)))
11883 html))
11885 (defun orgtbl-to-texinfo (table params)
11886 "Convert the orgtbl-mode TABLE to TeXInfo.
11887 TABLE is a list, each entry either the symbol `hline' for a horizontal
11888 separator line, or a list of fields for that line.
11889 PARAMS is a property list of parameters that can influence the conversion.
11890 Supports all parameters from `orgtbl-to-generic'. Most important for
11891 TeXInfo are:
11893 :splice nil/t When set to t, return only table body lines, don't wrap
11894 them into a multitable environment. Default is nil.
11896 :fmt fmt A format to be used to wrap the field, should contain
11897 %s for the original field value. For example, to wrap
11898 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
11899 This may also be a property list with column numbers and
11900 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
11902 :cf \"f1 f2..\" The column fractions for the table. By default these
11903 are computed automatically from the width of the columns
11904 under org-mode.
11906 The general parameters :skip and :skipcols have already been applied when
11907 this function is called."
11908 (let* ((total (float (apply '+ org-table-last-column-widths)))
11909 (colfrac (or (plist-get params :cf)
11910 (mapconcat
11911 (lambda (x) (format "%.3f" (/ (float x) total)))
11912 org-table-last-column-widths " ")))
11913 (params2
11914 (list
11915 :tstart (concat "@multitable @columnfractions " colfrac)
11916 :tend "@end multitable"
11917 :lstart "@item " :lend "" :sep " @tab "
11918 :hlstart "@headitem ")))
11919 (orgtbl-to-generic table (org-combine-plists params2 params))))
11921 ;;;; Link Stuff
11923 ;;; Link abbreviations
11925 (defun org-link-expand-abbrev (link)
11926 "Apply replacements as defined in `org-link-abbrev-alist."
11927 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
11928 (let* ((key (match-string 1 link))
11929 (as (or (assoc key org-link-abbrev-alist-local)
11930 (assoc key org-link-abbrev-alist)))
11931 (tag (and (match-end 2) (match-string 3 link)))
11932 rpl)
11933 (if (not as)
11934 link
11935 (setq rpl (cdr as))
11936 (cond
11937 ((symbolp rpl) (funcall rpl tag))
11938 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
11939 (t (concat rpl tag)))))
11940 link))
11942 ;;; Storing and inserting links
11944 (defvar org-insert-link-history nil
11945 "Minibuffer history for links inserted with `org-insert-link'.")
11947 (defvar org-stored-links nil
11948 "Contains the links stored with `org-store-link'.")
11950 (defvar org-store-link-plist nil
11951 "Plist with info about the most recently link created with `org-store-link'.")
11953 (defvar org-link-protocols nil
11954 "Link protocols added to Org-mode using `org-add-link-type'.")
11956 (defvar org-store-link-functions nil
11957 "List of functions that are called to create and store a link.
11958 Each function will be called in turn until one returns a non-nil
11959 value. Each function should check if it is responsible for creating
11960 this link (for example by looking at the major mode).
11961 If not, it must exit and return nil.
11962 If yes, it should return a non-nil value after a calling
11963 `org-store-link-props' with a list of properties and values.
11964 Special properties are:
11966 :type The link prefix. like \"http\". This must be given.
11967 :link The link, like \"http://www.astro.uva.nl/~dominik\".
11968 This is obligatory as well.
11969 :description Optional default description for the second pair
11970 of brackets in an Org-mode link. The user can still change
11971 this when inserting this link into an Org-mode buffer.
11973 In addition to these, any additional properties can be specified
11974 and then used in remember templates.")
11976 (defun org-add-link-type (type &optional follow publish)
11977 "Add TYPE to the list of `org-link-types'.
11978 Re-compute all regular expressions depending on `org-link-types'
11979 FOLLOW and PUBLISH are two functions. Both take the link path as
11980 an argument.
11981 FOLLOW should do whatever is necessary to follow the link, for example
11982 to find a file or display a mail message.
11984 PUBLISH takes the path and retuns the string that should be used when
11985 this document is published. FIMXE: This is actually not yet implemented."
11986 (add-to-list 'org-link-types type t)
11987 (org-make-link-regexps)
11988 (add-to-list 'org-link-protocols
11989 (list type follow publish)))
11991 (defun org-add-agenda-custom-command (entry)
11992 "Replace or add a command in `org-agenda-custom-commands'.
11993 This is mostly for hacking and trying a new command - once the command
11994 works you probably want to add it to `org-agenda-custom-commands' for good."
11995 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
11996 (if ass
11997 (setcdr ass (cdr entry))
11998 (push entry org-agenda-custom-commands))))
12000 ;;;###autoload
12001 (defun org-store-link (arg)
12002 "\\<org-mode-map>Store an org-link to the current location.
12003 This link is added to `org-stored-links' and can later be inserted
12004 into an org-buffer with \\[org-insert-link].
12006 For some link types, a prefix arg is interpreted:
12007 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
12008 For file links, arg negates `org-context-in-file-links'."
12009 (interactive "P")
12010 (setq org-store-link-plist nil) ; reset
12011 (require 'org-irc)
12012 (let (link cpltxt desc description search txt)
12013 (cond
12015 ((run-hook-with-args-until-success 'org-store-link-functions)
12016 (setq link (plist-get org-store-link-plist :link)
12017 desc (or (plist-get org-store-link-plist :description) link)))
12019 ((eq major-mode 'bbdb-mode)
12020 (let ((name (bbdb-record-name (bbdb-current-record)))
12021 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
12022 (setq cpltxt (concat "bbdb:" (or name company))
12023 link (org-make-link cpltxt))
12024 (org-store-link-props :type "bbdb" :name name :company company)))
12026 ((eq major-mode 'Info-mode)
12027 (setq link (org-make-link "info:"
12028 (file-name-nondirectory Info-current-file)
12029 ":" Info-current-node))
12030 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
12031 ":" Info-current-node))
12032 (org-store-link-props :type "info" :file Info-current-file
12033 :node Info-current-node))
12035 ((eq major-mode 'calendar-mode)
12036 (let ((cd (calendar-cursor-to-date)))
12037 (setq link
12038 (format-time-string
12039 (car org-time-stamp-formats)
12040 (apply 'encode-time
12041 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
12042 nil nil nil))))
12043 (org-store-link-props :type "calendar" :date cd)))
12045 ((or (eq major-mode 'vm-summary-mode)
12046 (eq major-mode 'vm-presentation-mode))
12047 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
12048 (vm-follow-summary-cursor)
12049 (save-excursion
12050 (vm-select-folder-buffer)
12051 (let* ((message (car vm-message-pointer))
12052 (folder buffer-file-name)
12053 (subject (vm-su-subject message))
12054 (to (vm-get-header-contents message "To"))
12055 (from (vm-get-header-contents message "From"))
12056 (message-id (vm-su-message-id message)))
12057 (org-store-link-props :type "vm" :from from :to to :subject subject
12058 :message-id message-id)
12059 (setq message-id (org-remove-angle-brackets message-id))
12060 (setq folder (abbreviate-file-name folder))
12061 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
12062 folder)
12063 (setq folder (replace-match "" t t folder)))
12064 (setq cpltxt (org-email-link-description))
12065 (setq link (org-make-link "vm:" folder "#" message-id)))))
12067 ((eq major-mode 'wl-summary-mode)
12068 (let* ((msgnum (wl-summary-message-number))
12069 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
12070 msgnum 'message-id))
12071 (wl-message-entity
12072 (if (fboundp 'elmo-message-entity)
12073 (elmo-message-entity
12074 wl-summary-buffer-elmo-folder msgnum)
12075 (elmo-msgdb-overview-get-entity
12076 msgnum (wl-summary-buffer-msgdb))))
12077 (from (wl-summary-line-from))
12078 (to (car (elmo-message-entity-field wl-message-entity 'to)))
12079 (subject (let (wl-thr-indent-string wl-parent-message-entity)
12080 (wl-summary-line-subject))))
12081 (org-store-link-props :type "wl" :from from :to to
12082 :subject subject :message-id message-id)
12083 (setq message-id (org-remove-angle-brackets message-id))
12084 (setq cpltxt (org-email-link-description))
12085 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
12086 "#" message-id))))
12088 ((or (equal major-mode 'mh-folder-mode)
12089 (equal major-mode 'mh-show-mode))
12090 (let ((from (org-mhe-get-header "From:"))
12091 (to (org-mhe-get-header "To:"))
12092 (message-id (org-mhe-get-header "Message-Id:"))
12093 (subject (org-mhe-get-header "Subject:")))
12094 (org-store-link-props :type "mh" :from from :to to
12095 :subject subject :message-id message-id)
12096 (setq cpltxt (org-email-link-description))
12097 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
12098 (org-remove-angle-brackets message-id)))))
12100 ((or (eq major-mode 'rmail-mode)
12101 (eq major-mode 'rmail-summary-mode))
12102 (save-window-excursion
12103 (save-restriction
12104 (when (eq major-mode 'rmail-summary-mode)
12105 (rmail-show-message rmail-current-message))
12106 (rmail-narrow-to-non-pruned-header)
12107 (let ((folder buffer-file-name)
12108 (message-id (mail-fetch-field "message-id"))
12109 (from (mail-fetch-field "from"))
12110 (to (mail-fetch-field "to"))
12111 (subject (mail-fetch-field "subject")))
12112 (org-store-link-props
12113 :type "rmail" :from from :to to
12114 :subject subject :message-id message-id)
12115 (setq message-id (org-remove-angle-brackets message-id))
12116 (setq cpltxt (org-email-link-description))
12117 (setq link (org-make-link "rmail:" folder "#" message-id)))
12118 (rmail-show-message rmail-current-message))))
12120 ((eq major-mode 'gnus-group-mode)
12121 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
12122 (gnus-group-group-name)) ; version
12123 ((fboundp 'gnus-group-name)
12124 (gnus-group-name))
12125 (t "???"))))
12126 (unless group (error "Not on a group"))
12127 (org-store-link-props :type "gnus" :group group)
12128 (setq cpltxt (concat
12129 (if (org-xor arg org-usenet-links-prefer-google)
12130 "http://groups.google.com/groups?group="
12131 "gnus:")
12132 group)
12133 link (org-make-link cpltxt))))
12135 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
12136 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
12137 (let* ((group gnus-newsgroup-name)
12138 (article (gnus-summary-article-number))
12139 (header (gnus-summary-article-header article))
12140 (from (mail-header-from header))
12141 (message-id (mail-header-id header))
12142 (date (mail-header-date header))
12143 (subject (gnus-summary-subject-string)))
12144 (org-store-link-props :type "gnus" :from from :subject subject
12145 :message-id message-id :group group)
12146 (setq cpltxt (org-email-link-description))
12147 (if (org-xor arg org-usenet-links-prefer-google)
12148 (setq link
12149 (concat
12150 cpltxt "\n "
12151 (format "http://groups.google.com/groups?as_umsgid=%s"
12152 (org-fixup-message-id-for-http message-id))))
12153 (setq link (org-make-link "gnus:" group
12154 "#" (number-to-string article))))))
12156 ((eq major-mode 'w3-mode)
12157 (setq cpltxt (url-view-url t)
12158 link (org-make-link cpltxt))
12159 (org-store-link-props :type "w3" :url (url-view-url t)))
12161 ((eq major-mode 'w3m-mode)
12162 (setq cpltxt (or w3m-current-title w3m-current-url)
12163 link (org-make-link w3m-current-url))
12164 (org-store-link-props :type "w3m" :url (url-view-url t)))
12166 ((setq search (run-hook-with-args-until-success
12167 'org-create-file-search-functions))
12168 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
12169 "::" search))
12170 (setq cpltxt (or description link)))
12172 ((eq major-mode 'image-mode)
12173 (setq cpltxt (concat "file:"
12174 (abbreviate-file-name buffer-file-name))
12175 link (org-make-link cpltxt))
12176 (org-store-link-props :type "image" :file buffer-file-name))
12178 ((eq major-mode 'dired-mode)
12179 ;; link to the file in the current line
12180 (setq cpltxt (concat "file:"
12181 (abbreviate-file-name
12182 (expand-file-name
12183 (dired-get-filename nil t))))
12184 link (org-make-link cpltxt)))
12186 ((and buffer-file-name (org-mode-p))
12187 ;; Just link to current headline
12188 (setq cpltxt (concat "file:"
12189 (abbreviate-file-name buffer-file-name)))
12190 ;; Add a context search string
12191 (when (org-xor org-context-in-file-links arg)
12192 ;; Check if we are on a target
12193 (if (org-in-regexp "<<\\(.*?\\)>>")
12194 (setq cpltxt (concat cpltxt "::" (match-string 1)))
12195 (setq txt (cond
12196 ((org-on-heading-p) nil)
12197 ((org-region-active-p)
12198 (buffer-substring (region-beginning) (region-end)))
12199 (t (buffer-substring (point-at-bol) (point-at-eol)))))
12200 (when (or (null txt) (string-match "\\S-" txt))
12201 (setq cpltxt
12202 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12203 desc "NONE"))))
12204 (if (string-match "::\\'" cpltxt)
12205 (setq cpltxt (substring cpltxt 0 -2)))
12206 (setq link (org-make-link cpltxt)))
12208 ((buffer-file-name (buffer-base-buffer))
12209 ;; Just link to this file here.
12210 (setq cpltxt (concat "file:"
12211 (abbreviate-file-name
12212 (buffer-file-name (buffer-base-buffer)))))
12213 ;; Add a context string
12214 (when (org-xor org-context-in-file-links arg)
12215 (setq txt (if (org-region-active-p)
12216 (buffer-substring (region-beginning) (region-end))
12217 (buffer-substring (point-at-bol) (point-at-eol))))
12218 ;; Only use search option if there is some text.
12219 (when (string-match "\\S-" txt)
12220 (setq cpltxt
12221 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12222 desc "NONE")))
12223 (setq link (org-make-link cpltxt)))
12225 ((interactive-p)
12226 (error "Cannot link to a buffer which is not visiting a file"))
12228 (t (setq link nil)))
12230 (if (consp link) (setq cpltxt (car link) link (cdr link)))
12231 (setq link (or link cpltxt)
12232 desc (or desc cpltxt))
12233 (if (equal desc "NONE") (setq desc nil))
12235 (if (and (interactive-p) link)
12236 (progn
12237 (setq org-stored-links
12238 (cons (list link desc) org-stored-links))
12239 (message "Stored: %s" (or desc link)))
12240 (and link (org-make-link-string link desc)))))
12242 (defun org-store-link-props (&rest plist)
12243 "Store link properties, extract names and addresses."
12244 (let (x adr)
12245 (when (setq x (plist-get plist :from))
12246 (setq adr (mail-extract-address-components x))
12247 (plist-put plist :fromname (car adr))
12248 (plist-put plist :fromaddress (nth 1 adr)))
12249 (when (setq x (plist-get plist :to))
12250 (setq adr (mail-extract-address-components x))
12251 (plist-put plist :toname (car adr))
12252 (plist-put plist :toaddress (nth 1 adr))))
12253 (let ((from (plist-get plist :from))
12254 (to (plist-get plist :to)))
12255 (when (and from to org-from-is-user-regexp)
12256 (plist-put plist :fromto
12257 (if (string-match org-from-is-user-regexp from)
12258 (concat "to %t")
12259 (concat "from %f")))))
12260 (setq org-store-link-plist plist))
12262 (defun org-email-link-description (&optional fmt)
12263 "Return the description part of an email link.
12264 This takes information from `org-store-link-plist' and formats it
12265 according to FMT (default from `org-email-link-description-format')."
12266 (setq fmt (or fmt org-email-link-description-format))
12267 (let* ((p org-store-link-plist)
12268 (to (plist-get p :toaddress))
12269 (from (plist-get p :fromaddress))
12270 (table
12271 (list
12272 (cons "%c" (plist-get p :fromto))
12273 (cons "%F" (plist-get p :from))
12274 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12275 (cons "%T" (plist-get p :to))
12276 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12277 (cons "%s" (plist-get p :subject))
12278 (cons "%m" (plist-get p :message-id)))))
12279 (when (string-match "%c" fmt)
12280 ;; Check if the user wrote this message
12281 (if (and org-from-is-user-regexp from to
12282 (save-match-data (string-match org-from-is-user-regexp from)))
12283 (setq fmt (replace-match "to %t" t t fmt))
12284 (setq fmt (replace-match "from %f" t t fmt))))
12285 (org-replace-escapes fmt table)))
12287 (defun org-make-org-heading-search-string (&optional string heading)
12288 "Make search string for STRING or current headline."
12289 (interactive)
12290 (let ((s (or string (org-get-heading))))
12291 (unless (and string (not heading))
12292 ;; We are using a headline, clean up garbage in there.
12293 (if (string-match org-todo-regexp s)
12294 (setq s (replace-match "" t t s)))
12295 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12296 (setq s (replace-match "" t t s)))
12297 (setq s (org-trim s))
12298 (if (string-match (concat "^\\(" org-quote-string "\\|"
12299 org-comment-string "\\)") s)
12300 (setq s (replace-match "" t t s)))
12301 (while (string-match org-ts-regexp s)
12302 (setq s (replace-match "" t t s))))
12303 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12304 (setq s (replace-match " " t t s)))
12305 (or string (setq s (concat "*" s))) ; Add * for headlines
12306 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12308 (defun org-make-link (&rest strings)
12309 "Concatenate STRINGS."
12310 (apply 'concat strings))
12312 (defun org-make-link-string (link &optional description)
12313 "Make a link with brackets, consisting of LINK and DESCRIPTION."
12314 (unless (string-match "\\S-" link)
12315 (error "Empty link"))
12316 (when (stringp description)
12317 ;; Remove brackets from the description, they are fatal.
12318 (while (string-match "\\[" description)
12319 (setq description (replace-match "{" t t description)))
12320 (while (string-match "\\]" description)
12321 (setq description (replace-match "}" t t description))))
12322 (when (equal (org-link-escape link) description)
12323 ;; No description needed, it is identical
12324 (setq description nil))
12325 (when (and (not description)
12326 (not (equal link (org-link-escape link))))
12327 (setq description link))
12328 (concat "[[" (org-link-escape link) "]"
12329 (if description (concat "[" description "]") "")
12330 "]"))
12332 (defconst org-link-escape-chars
12333 '((?\ . "%20")
12334 (?\[ . "%5B")
12335 (?\] . "%5D")
12336 (?\340 . "%E0") ; `a
12337 (?\342 . "%E2") ; ^a
12338 (?\347 . "%E7") ; ,c
12339 (?\350 . "%E8") ; `e
12340 (?\351 . "%E9") ; 'e
12341 (?\352 . "%EA") ; ^e
12342 (?\356 . "%EE") ; ^i
12343 (?\364 . "%F4") ; ^o
12344 (?\371 . "%F9") ; `u
12345 (?\373 . "%FB") ; ^u
12346 (?\; . "%3B")
12347 (?? . "%3F")
12348 (?= . "%3D")
12349 (?+ . "%2B")
12351 "Association list of escapes for some characters problematic in links.
12352 This is the list that is used for internal purposes.")
12354 (defconst org-link-escape-chars-browser
12355 '((?\ . "%20")) ; 32 for the SPC char
12356 "Association list of escapes for some characters problematic in links.
12357 This is the list that is used before handing over to the browser.")
12359 (defun org-link-escape (text &optional table)
12360 "Escape charaters in TEXT that are problematic for links."
12361 (setq table (or table org-link-escape-chars))
12362 (when text
12363 (let ((re (mapconcat (lambda (x) (regexp-quote
12364 (char-to-string (car x))))
12365 table "\\|")))
12366 (while (string-match re text)
12367 (setq text
12368 (replace-match
12369 (cdr (assoc (string-to-char (match-string 0 text))
12370 table))
12371 t t text)))
12372 text)))
12374 (defun org-link-unescape (text &optional table)
12375 "Reverse the action of `org-link-escape'."
12376 (setq table (or table org-link-escape-chars))
12377 (when text
12378 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12379 table "\\|")))
12380 (while (string-match re text)
12381 (setq text
12382 (replace-match
12383 (char-to-string (car (rassoc (match-string 0 text) table)))
12384 t t text)))
12385 text)))
12387 (defun org-xor (a b)
12388 "Exclusive or."
12389 (if a (not b) b))
12391 (defun org-get-header (header)
12392 "Find a header field in the current buffer."
12393 (save-excursion
12394 (goto-char (point-min))
12395 (let ((case-fold-search t) s)
12396 (cond
12397 ((eq header 'from)
12398 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12399 (setq s (match-string 1)))
12400 (while (string-match "\"" s)
12401 (setq s (replace-match "" t t s)))
12402 (if (string-match "[<(].*" s)
12403 (setq s (replace-match "" t t s))))
12404 ((eq header 'message-id)
12405 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12406 (setq s (match-string 1))))
12407 ((eq header 'subject)
12408 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12409 (setq s (match-string 1)))))
12410 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12411 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12412 s)))
12415 (defun org-fixup-message-id-for-http (s)
12416 "Replace special characters in a message id, so it can be used in an http query."
12417 (while (string-match "<" s)
12418 (setq s (replace-match "%3C" t t s)))
12419 (while (string-match ">" s)
12420 (setq s (replace-match "%3E" t t s)))
12421 (while (string-match "@" s)
12422 (setq s (replace-match "%40" t t s)))
12425 ;;;###autoload
12426 (defun org-insert-link-global ()
12427 "Insert a link like Org-mode does.
12428 This command can be called in any mode to insert a link in Org-mode syntax."
12429 (interactive)
12430 (org-run-like-in-org-mode 'org-insert-link))
12432 (defun org-insert-link (&optional complete-file)
12433 "Insert a link. At the prompt, enter the link.
12435 Completion can be used to select a link previously stored with
12436 `org-store-link'. When the empty string is entered (i.e. if you just
12437 press RET at the prompt), the link defaults to the most recently
12438 stored link. As SPC triggers completion in the minibuffer, you need to
12439 use M-SPC or C-q SPC to force the insertion of a space character.
12441 You will also be prompted for a description, and if one is given, it will
12442 be displayed in the buffer instead of the link.
12444 If there is already a link at point, this command will allow you to edit link
12445 and description parts.
12447 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12448 selected using completion. The path to the file will be relative to
12449 the current directory if the file is in the current directory or a
12450 subdirectory. Otherwise, the link will be the absolute path as
12451 completed in the minibuffer (i.e. normally ~/path/to/file).
12453 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12454 is in the current directory or below.
12455 With three \\[universal-argument] prefixes, negate the meaning of
12456 `org-keep-stored-link-after-insertion'."
12457 (interactive "P")
12458 (let* ((wcf (current-window-configuration))
12459 (region (if (org-region-active-p)
12460 (buffer-substring (region-beginning) (region-end))))
12461 (remove (and region (list (region-beginning) (region-end))))
12462 (desc region)
12463 tmphist ; byte-compile incorrectly complains about this
12464 link entry file)
12465 (cond
12466 ((org-in-regexp org-bracket-link-regexp 1)
12467 ;; We do have a link at point, and we are going to edit it.
12468 (setq remove (list (match-beginning 0) (match-end 0)))
12469 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12470 (setq link (read-string "Link: "
12471 (org-link-unescape
12472 (org-match-string-no-properties 1)))))
12473 ((or (org-in-regexp org-angle-link-re)
12474 (org-in-regexp org-plain-link-re))
12475 ;; Convert to bracket link
12476 (setq remove (list (match-beginning 0) (match-end 0))
12477 link (read-string "Link: "
12478 (org-remove-angle-brackets (match-string 0)))))
12479 ((equal complete-file '(4))
12480 ;; Completing read for file names.
12481 (setq file (read-file-name "File: "))
12482 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12483 (pwd1 (file-name-as-directory (abbreviate-file-name
12484 (expand-file-name ".")))))
12485 (cond
12486 ((equal complete-file '(16))
12487 (setq link (org-make-link
12488 "file:"
12489 (abbreviate-file-name (expand-file-name file)))))
12490 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12491 (setq link (org-make-link "file:" (match-string 1 file))))
12492 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12493 (expand-file-name file))
12494 (setq link (org-make-link
12495 "file:" (match-string 1 (expand-file-name file)))))
12496 (t (setq link (org-make-link "file:" file))))))
12498 ;; Read link, with completion for stored links.
12499 (with-output-to-temp-buffer "*Org Links*"
12500 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12501 (when org-stored-links
12502 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12503 (princ (mapconcat
12504 (lambda (x)
12505 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12506 (reverse org-stored-links) "\n"))))
12507 (let ((cw (selected-window)))
12508 (select-window (get-buffer-window "*Org Links*"))
12509 (shrink-window-if-larger-than-buffer)
12510 (setq truncate-lines t)
12511 (select-window cw))
12512 ;; Fake a link history, containing the stored links.
12513 (setq tmphist (append (mapcar 'car org-stored-links)
12514 org-insert-link-history))
12515 (unwind-protect
12516 (setq link (org-completing-read
12517 "Link: "
12518 (append
12519 (mapcar (lambda (x) (list (concat (car x) ":")))
12520 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12521 (mapcar (lambda (x) (list (concat x ":")))
12522 org-link-types))
12523 nil nil nil
12524 'tmphist
12525 (or (car (car org-stored-links)))))
12526 (set-window-configuration wcf)
12527 (kill-buffer "*Org Links*"))
12528 (setq entry (assoc link org-stored-links))
12529 (or entry (push link org-insert-link-history))
12530 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12531 (not org-keep-stored-link-after-insertion))
12532 (setq org-stored-links (delq (assoc link org-stored-links)
12533 org-stored-links)))
12534 (setq desc (or desc (nth 1 entry)))))
12536 (if (string-match org-plain-link-re link)
12537 ;; URL-like link, normalize the use of angular brackets.
12538 (setq link (org-make-link (org-remove-angle-brackets link))))
12540 ;; Check if we are linking to the current file with a search option
12541 ;; If yes, simplify the link by using only the search option.
12542 (when (and buffer-file-name
12543 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12544 (let* ((path (match-string 1 link))
12545 (case-fold-search nil)
12546 (search (match-string 2 link)))
12547 (save-match-data
12548 (if (equal (file-truename buffer-file-name) (file-truename path))
12549 ;; We are linking to this same file, with a search option
12550 (setq link search)))))
12552 ;; Check if we can/should use a relative path. If yes, simplify the link
12553 (when (string-match "\\<file:\\(.*\\)" link)
12554 (let* ((path (match-string 1 link))
12555 (origpath path)
12556 (case-fold-search nil))
12557 (cond
12558 ((eq org-link-file-path-type 'absolute)
12559 (setq path (abbreviate-file-name (expand-file-name path))))
12560 ((eq org-link-file-path-type 'noabbrev)
12561 (setq path (expand-file-name path)))
12562 ((eq org-link-file-path-type 'relative)
12563 (setq path (file-relative-name path)))
12565 (save-match-data
12566 (if (string-match (concat "^" (regexp-quote
12567 (file-name-as-directory
12568 (expand-file-name "."))))
12569 (expand-file-name path))
12570 ;; We are linking a file with relative path name.
12571 (setq path (substring (expand-file-name path)
12572 (match-end 0)))))))
12573 (setq link (concat "file:" path))
12574 (if (equal desc origpath)
12575 (setq desc path))))
12577 (setq desc (read-string "Description: " desc))
12578 (unless (string-match "\\S-" desc) (setq desc nil))
12579 (if remove (apply 'delete-region remove))
12580 (insert (org-make-link-string link desc))))
12582 (defun org-completing-read (&rest args)
12583 (let ((minibuffer-local-completion-map
12584 (copy-keymap minibuffer-local-completion-map)))
12585 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12586 (apply 'completing-read args)))
12588 ;;; Opening/following a link
12589 (defvar org-link-search-failed nil)
12591 (defun org-next-link ()
12592 "Move forward to the next link.
12593 If the link is in hidden text, expose it."
12594 (interactive)
12595 (when (and org-link-search-failed (eq this-command last-command))
12596 (goto-char (point-min))
12597 (message "Link search wrapped back to beginning of buffer"))
12598 (setq org-link-search-failed nil)
12599 (let* ((pos (point))
12600 (ct (org-context))
12601 (a (assoc :link ct)))
12602 (if a (goto-char (nth 2 a)))
12603 (if (re-search-forward org-any-link-re nil t)
12604 (progn
12605 (goto-char (match-beginning 0))
12606 (if (org-invisible-p) (org-show-context)))
12607 (goto-char pos)
12608 (setq org-link-search-failed t)
12609 (error "No further link found"))))
12611 (defun org-previous-link ()
12612 "Move backward to the previous link.
12613 If the link is in hidden text, expose it."
12614 (interactive)
12615 (when (and org-link-search-failed (eq this-command last-command))
12616 (goto-char (point-max))
12617 (message "Link search wrapped back to end of buffer"))
12618 (setq org-link-search-failed nil)
12619 (let* ((pos (point))
12620 (ct (org-context))
12621 (a (assoc :link ct)))
12622 (if a (goto-char (nth 1 a)))
12623 (if (re-search-backward org-any-link-re nil t)
12624 (progn
12625 (goto-char (match-beginning 0))
12626 (if (org-invisible-p) (org-show-context)))
12627 (goto-char pos)
12628 (setq org-link-search-failed t)
12629 (error "No further link found"))))
12631 (defun org-find-file-at-mouse (ev)
12632 "Open file link or URL at mouse."
12633 (interactive "e")
12634 (mouse-set-point ev)
12635 (org-open-at-point 'in-emacs))
12637 (defun org-open-at-mouse (ev)
12638 "Open file link or URL at mouse."
12639 (interactive "e")
12640 (mouse-set-point ev)
12641 (org-open-at-point))
12643 (defvar org-window-config-before-follow-link nil
12644 "The window configuration before following a link.
12645 This is saved in case the need arises to restore it.")
12647 (defvar org-open-link-marker (make-marker)
12648 "Marker pointing to the location where `org-open-at-point; was called.")
12650 ;;;###autoload
12651 (defun org-open-at-point-global ()
12652 "Follow a link like Org-mode does.
12653 This command can be called in any mode to follow a link that has
12654 Org-mode syntax."
12655 (interactive)
12656 (org-run-like-in-org-mode 'org-open-at-point))
12658 (defun org-open-at-point (&optional in-emacs)
12659 "Open link at or after point.
12660 If there is no link at point, this function will search forward up to
12661 the end of the current subtree.
12662 Normally, files will be opened by an appropriate application. If the
12663 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12664 (interactive "P")
12665 (catch 'abort
12666 (move-marker org-open-link-marker (point))
12667 (setq org-window-config-before-follow-link (current-window-configuration))
12668 (org-remove-occur-highlights nil nil t)
12669 (if (org-at-timestamp-p t)
12670 (org-follow-timestamp-link)
12671 (let (type path link line search (pos (point)))
12672 (catch 'match
12673 (save-excursion
12674 (skip-chars-forward "^]\n\r")
12675 (when (org-in-regexp org-bracket-link-regexp)
12676 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12677 (while (string-match " *\n *" link)
12678 (setq link (replace-match " " t t link)))
12679 (setq link (org-link-expand-abbrev link))
12680 (if (string-match org-link-re-with-space2 link)
12681 (setq type (match-string 1 link) path (match-string 2 link))
12682 (setq type "thisfile" path link))
12683 (throw 'match t)))
12685 (when (get-text-property (point) 'org-linked-text)
12686 (setq type "thisfile"
12687 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12688 (1+ (point)) (point))
12689 path (buffer-substring
12690 (previous-single-property-change pos 'org-linked-text)
12691 (next-single-property-change pos 'org-linked-text)))
12692 (throw 'match t))
12694 (save-excursion
12695 (when (or (org-in-regexp org-angle-link-re)
12696 (org-in-regexp org-plain-link-re))
12697 (setq type (match-string 1) path (match-string 2))
12698 (throw 'match t)))
12699 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12700 (setq type "tree-match"
12701 path (match-string 1))
12702 (throw 'match t))
12703 (save-excursion
12704 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12705 (setq type "tags"
12706 path (match-string 1))
12707 (while (string-match ":" path)
12708 (setq path (replace-match "+" t t path)))
12709 (throw 'match t))))
12710 (unless path
12711 (error "No link found"))
12712 ;; Remove any trailing spaces in path
12713 (if (string-match " +\\'" path)
12714 (setq path (replace-match "" t t path)))
12716 (cond
12718 ((assoc type org-link-protocols)
12719 (funcall (nth 1 (assoc type org-link-protocols)) path))
12721 ((equal type "mailto")
12722 (let ((cmd (car org-link-mailto-program))
12723 (args (cdr org-link-mailto-program)) args1
12724 (address path) (subject "") a)
12725 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12726 (setq address (match-string 1 path)
12727 subject (org-link-escape (match-string 2 path))))
12728 (while args
12729 (cond
12730 ((not (stringp (car args))) (push (pop args) args1))
12731 (t (setq a (pop args))
12732 (if (string-match "%a" a)
12733 (setq a (replace-match address t t a)))
12734 (if (string-match "%s" a)
12735 (setq a (replace-match subject t t a)))
12736 (push a args1))))
12737 (apply cmd (nreverse args1))))
12739 ((member type '("http" "https" "ftp" "news"))
12740 (browse-url (concat type ":" (org-link-escape
12741 path org-link-escape-chars-browser))))
12743 ((member type '("message"))
12744 (browse-url (concat type ":" path)))
12746 ((string= type "tags")
12747 (org-tags-view in-emacs path))
12748 ((string= type "thisfile")
12749 (if in-emacs
12750 (switch-to-buffer-other-window
12751 (org-get-buffer-for-internal-link (current-buffer)))
12752 (org-mark-ring-push))
12753 (let ((cmd `(org-link-search
12754 ,path
12755 ,(cond ((equal in-emacs '(4)) 'occur)
12756 ((equal in-emacs '(16)) 'org-occur)
12757 (t nil))
12758 ,pos)))
12759 (condition-case nil (eval cmd)
12760 (error (progn (widen) (eval cmd))))))
12762 ((string= type "tree-match")
12763 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12765 ((string= type "file")
12766 (if (string-match "::\\([0-9]+\\)\\'" path)
12767 (setq line (string-to-number (match-string 1 path))
12768 path (substring path 0 (match-beginning 0)))
12769 (if (string-match "::\\(.+\\)\\'" path)
12770 (setq search (match-string 1 path)
12771 path (substring path 0 (match-beginning 0)))))
12772 (if (string-match "[*?{]" (file-name-nondirectory path))
12773 (dired path)
12774 (org-open-file path in-emacs line search)))
12776 ((string= type "news")
12777 (org-follow-gnus-link path))
12779 ((string= type "bbdb")
12780 (org-follow-bbdb-link path))
12782 ((string= type "info")
12783 (org-follow-info-link path))
12785 ((string= type "gnus")
12786 (let (group article)
12787 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12788 (error "Error in Gnus link"))
12789 (setq group (match-string 1 path)
12790 article (match-string 3 path))
12791 (org-follow-gnus-link group article)))
12793 ((string= type "vm")
12794 (let (folder article)
12795 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12796 (error "Error in VM link"))
12797 (setq folder (match-string 1 path)
12798 article (match-string 3 path))
12799 ;; in-emacs is the prefix arg, will be interpreted as read-only
12800 (org-follow-vm-link folder article in-emacs)))
12802 ((string= type "wl")
12803 (let (folder article)
12804 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12805 (error "Error in Wanderlust link"))
12806 (setq folder (match-string 1 path)
12807 article (match-string 3 path))
12808 (org-follow-wl-link folder article)))
12810 ((string= type "mhe")
12811 (let (folder article)
12812 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12813 (error "Error in MHE link"))
12814 (setq folder (match-string 1 path)
12815 article (match-string 3 path))
12816 (org-follow-mhe-link folder article)))
12818 ((string= type "rmail")
12819 (let (folder article)
12820 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12821 (error "Error in RMAIL link"))
12822 (setq folder (match-string 1 path)
12823 article (match-string 3 path))
12824 (org-follow-rmail-link folder article)))
12826 ((string= type "shell")
12827 (let ((cmd path))
12828 (if (or (not org-confirm-shell-link-function)
12829 (funcall org-confirm-shell-link-function
12830 (format "Execute \"%s\" in shell? "
12831 (org-add-props cmd nil
12832 'face 'org-warning))))
12833 (progn
12834 (message "Executing %s" cmd)
12835 (shell-command cmd))
12836 (error "Abort"))))
12838 ((string= type "elisp")
12839 (let ((cmd path))
12840 (if (or (not org-confirm-elisp-link-function)
12841 (funcall org-confirm-elisp-link-function
12842 (format "Execute \"%s\" as elisp? "
12843 (org-add-props cmd nil
12844 'face 'org-warning))))
12845 (message "%s => %s" cmd (eval (read cmd)))
12846 (error "Abort"))))
12849 (browse-url-at-point)))))
12850 (move-marker org-open-link-marker nil)))
12852 ;;; File search
12854 (defvar org-create-file-search-functions nil
12855 "List of functions to construct the right search string for a file link.
12856 These functions are called in turn with point at the location to
12857 which the link should point.
12859 A function in the hook should first test if it would like to
12860 handle this file type, for example by checking the major-mode or
12861 the file extension. If it decides not to handle this file, it
12862 should just return nil to give other functions a chance. If it
12863 does handle the file, it must return the search string to be used
12864 when following the link. The search string will be part of the
12865 file link, given after a double colon, and `org-open-at-point'
12866 will automatically search for it. If special measures must be
12867 taken to make the search successful, another function should be
12868 added to the companion hook `org-execute-file-search-functions',
12869 which see.
12871 A function in this hook may also use `setq' to set the variable
12872 `description' to provide a suggestion for the descriptive text to
12873 be used for this link when it gets inserted into an Org-mode
12874 buffer with \\[org-insert-link].")
12876 (defvar org-execute-file-search-functions nil
12877 "List of functions to execute a file search triggered by a link.
12879 Functions added to this hook must accept a single argument, the
12880 search string that was part of the file link, the part after the
12881 double colon. The function must first check if it would like to
12882 handle this search, for example by checking the major-mode or the
12883 file extension. If it decides not to handle this search, it
12884 should just return nil to give other functions a chance. If it
12885 does handle the search, it must return a non-nil value to keep
12886 other functions from trying.
12888 Each function can access the current prefix argument through the
12889 variable `current-prefix-argument'. Note that a single prefix is
12890 used to force opening a link in Emacs, so it may be good to only
12891 use a numeric or double prefix to guide the search function.
12893 In case this is needed, a function in this hook can also restore
12894 the window configuration before `org-open-at-point' was called using:
12896 (set-window-configuration org-window-config-before-follow-link)")
12898 (defun org-link-search (s &optional type avoid-pos)
12899 "Search for a link search option.
12900 If S is surrounded by forward slashes, it is interpreted as a
12901 regular expression. In org-mode files, this will create an `org-occur'
12902 sparse tree. In ordinary files, `occur' will be used to list matches.
12903 If the current buffer is in `dired-mode', grep will be used to search
12904 in all files. If AVOID-POS is given, ignore matches near that position."
12905 (let ((case-fold-search t)
12906 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12907 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12908 (append '(("") (" ") ("\t") ("\n"))
12909 org-emphasis-alist)
12910 "\\|") "\\)"))
12911 (pos (point))
12912 (pre "") (post "")
12913 words re0 re1 re2 re3 re4 re5 re2a reall)
12914 (cond
12915 ;; First check if there are any special
12916 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12917 ;; Now try the builtin stuff
12918 ((save-excursion
12919 (goto-char (point-min))
12920 (and
12921 (re-search-forward
12922 (concat "<<" (regexp-quote s0) ">>") nil t)
12923 (setq pos (match-beginning 0))))
12924 ;; There is an exact target for this
12925 (goto-char pos))
12926 ((string-match "^/\\(.*\\)/$" s)
12927 ;; A regular expression
12928 (cond
12929 ((org-mode-p)
12930 (org-occur (match-string 1 s)))
12931 ;;((eq major-mode 'dired-mode)
12932 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12933 (t (org-do-occur (match-string 1 s)))))
12935 ;; A normal search strings
12936 (when (equal (string-to-char s) ?*)
12937 ;; Anchor on headlines, post may include tags.
12938 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
12939 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
12940 s (substring s 1)))
12941 (remove-text-properties
12942 0 (length s)
12943 '(face nil mouse-face nil keymap nil fontified nil) s)
12944 ;; Make a series of regular expressions to find a match
12945 (setq words (org-split-string s "[ \n\r\t]+")
12946 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
12947 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
12948 "\\)" markers)
12949 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
12950 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
12951 re1 (concat pre re2 post)
12952 re3 (concat pre re4 post)
12953 re5 (concat pre ".*" re4)
12954 re2 (concat pre re2)
12955 re2a (concat pre re2a)
12956 re4 (concat pre re4)
12957 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
12958 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
12959 re5 "\\)"
12961 (cond
12962 ((eq type 'org-occur) (org-occur reall))
12963 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
12964 (t (goto-char (point-min))
12965 (if (or (org-search-not-self 1 re0 nil t)
12966 (org-search-not-self 1 re1 nil t)
12967 (org-search-not-self 1 re2 nil t)
12968 (org-search-not-self 1 re2a nil t)
12969 (org-search-not-self 1 re3 nil t)
12970 (org-search-not-self 1 re4 nil t)
12971 (org-search-not-self 1 re5 nil t)
12973 (goto-char (match-beginning 1))
12974 (goto-char pos)
12975 (error "No match")))))
12977 ;; Normal string-search
12978 (goto-char (point-min))
12979 (if (search-forward s nil t)
12980 (goto-char (match-beginning 0))
12981 (error "No match"))))
12982 (and (org-mode-p) (org-show-context 'link-search))))
12984 (defun org-search-not-self (group &rest args)
12985 "Execute `re-search-forward', but only accept matches that do not
12986 enclose the position of `org-open-link-marker'."
12987 (let ((m org-open-link-marker))
12988 (catch 'exit
12989 (while (apply 're-search-forward args)
12990 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
12991 (goto-char (match-end group))
12992 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
12993 (> (match-beginning 0) (marker-position m))
12994 (< (match-end 0) (marker-position m)))
12995 (save-match-data
12996 (or (not (org-in-regexp
12997 org-bracket-link-analytic-regexp 1))
12998 (not (match-end 4)) ; no description
12999 (and (<= (match-beginning 4) (point))
13000 (>= (match-end 4) (point))))))
13001 (throw 'exit (point))))))))
13003 (defun org-get-buffer-for-internal-link (buffer)
13004 "Return a buffer to be used for displaying the link target of internal links."
13005 (cond
13006 ((not org-display-internal-link-with-indirect-buffer)
13007 buffer)
13008 ((string-match "(Clone)$" (buffer-name buffer))
13009 (message "Buffer is already a clone, not making another one")
13010 ;; we also do not modify visibility in this case
13011 buffer)
13012 (t ; make a new indirect buffer for displaying the link
13013 (let* ((bn (buffer-name buffer))
13014 (ibn (concat bn "(Clone)"))
13015 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
13016 (with-current-buffer ib (org-overview))
13017 ib))))
13019 (defun org-do-occur (regexp &optional cleanup)
13020 "Call the Emacs command `occur'.
13021 If CLEANUP is non-nil, remove the printout of the regular expression
13022 in the *Occur* buffer. This is useful if the regex is long and not useful
13023 to read."
13024 (occur regexp)
13025 (when cleanup
13026 (let ((cwin (selected-window)) win beg end)
13027 (when (setq win (get-buffer-window "*Occur*"))
13028 (select-window win))
13029 (goto-char (point-min))
13030 (when (re-search-forward "match[a-z]+" nil t)
13031 (setq beg (match-end 0))
13032 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
13033 (setq end (1- (match-beginning 0)))))
13034 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
13035 (goto-char (point-min))
13036 (select-window cwin))))
13038 ;;; The mark ring for links jumps
13040 (defvar org-mark-ring nil
13041 "Mark ring for positions before jumps in Org-mode.")
13042 (defvar org-mark-ring-last-goto nil
13043 "Last position in the mark ring used to go back.")
13044 ;; Fill and close the ring
13045 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
13046 (loop for i from 1 to org-mark-ring-length do
13047 (push (make-marker) org-mark-ring))
13048 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
13049 org-mark-ring)
13051 (defun org-mark-ring-push (&optional pos buffer)
13052 "Put the current position or POS into the mark ring and rotate it."
13053 (interactive)
13054 (setq pos (or pos (point)))
13055 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
13056 (move-marker (car org-mark-ring)
13057 (or pos (point))
13058 (or buffer (current-buffer)))
13059 (message "%s"
13060 (substitute-command-keys
13061 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
13063 (defun org-mark-ring-goto (&optional n)
13064 "Jump to the previous position in the mark ring.
13065 With prefix arg N, jump back that many stored positions. When
13066 called several times in succession, walk through the entire ring.
13067 Org-mode commands jumping to a different position in the current file,
13068 or to another Org-mode file, automatically push the old position
13069 onto the ring."
13070 (interactive "p")
13071 (let (p m)
13072 (if (eq last-command this-command)
13073 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
13074 (setq p org-mark-ring))
13075 (setq org-mark-ring-last-goto p)
13076 (setq m (car p))
13077 (switch-to-buffer (marker-buffer m))
13078 (goto-char m)
13079 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
13081 (defun org-remove-angle-brackets (s)
13082 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
13083 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
13085 (defun org-add-angle-brackets (s)
13086 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
13087 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
13090 ;;; Following specific links
13092 (defun org-follow-timestamp-link ()
13093 (cond
13094 ((org-at-date-range-p t)
13095 (let ((org-agenda-start-on-weekday)
13096 (t1 (match-string 1))
13097 (t2 (match-string 2)))
13098 (setq t1 (time-to-days (org-time-string-to-time t1))
13099 t2 (time-to-days (org-time-string-to-time t2)))
13100 (org-agenda-list nil t1 (1+ (- t2 t1)))))
13101 ((org-at-timestamp-p t)
13102 (org-agenda-list nil (time-to-days (org-time-string-to-time
13103 (substring (match-string 1) 0 10)))
13105 (t (error "This should not happen"))))
13108 (defun org-follow-bbdb-link (name)
13109 "Follow a BBDB link to NAME."
13110 (require 'bbdb)
13111 (let ((inhibit-redisplay (not debug-on-error))
13112 (bbdb-electric-p nil))
13113 (catch 'exit
13114 ;; Exact match on name
13115 (bbdb-name (concat "\\`" name "\\'") nil)
13116 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13117 ;; Exact match on name
13118 (bbdb-company (concat "\\`" name "\\'") nil)
13119 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13120 ;; Partial match on name
13121 (bbdb-name name nil)
13122 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13123 ;; Partial match on company
13124 (bbdb-company name nil)
13125 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13126 ;; General match including network address and notes
13127 (bbdb name nil)
13128 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
13129 (delete-window (get-buffer-window "*BBDB*"))
13130 (error "No matching BBDB record")))))
13132 (defun org-follow-info-link (name)
13133 "Follow an info file & node link to NAME."
13134 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
13135 (string-match "\\(.*\\)" name))
13136 (progn
13137 (require 'info)
13138 (if (match-string 2 name) ; If there isn't a node, choose "Top"
13139 (Info-find-node (match-string 1 name) (match-string 2 name))
13140 (Info-find-node (match-string 1 name) "Top")))
13141 (message "Could not open: %s" name)))
13143 (defun org-follow-gnus-link (&optional group article)
13144 "Follow a Gnus link to GROUP and ARTICLE."
13145 (require 'gnus)
13146 (funcall (cdr (assq 'gnus org-link-frame-setup)))
13147 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
13148 (cond ((and group article)
13149 (gnus-group-read-group 1 nil group)
13150 (gnus-summary-goto-article (string-to-number article) nil t))
13151 (group (gnus-group-jump-to-group group))))
13153 (defun org-follow-vm-link (&optional folder article readonly)
13154 "Follow a VM link to FOLDER and ARTICLE."
13155 (require 'vm)
13156 (setq article (org-add-angle-brackets article))
13157 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
13158 ;; ange-ftp or efs or tramp access
13159 (let ((user (or (match-string 1 folder) (user-login-name)))
13160 (host (match-string 2 folder))
13161 (file (match-string 3 folder)))
13162 (cond
13163 ((featurep 'tramp)
13164 ;; use tramp to access the file
13165 (if (featurep 'xemacs)
13166 (setq folder (format "[%s@%s]%s" user host file))
13167 (setq folder (format "/%s@%s:%s" user host file))))
13169 ;; use ange-ftp or efs
13170 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
13171 (setq folder (format "/%s@%s:%s" user host file))))))
13172 (when folder
13173 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
13174 (sit-for 0.1)
13175 (when article
13176 (vm-select-folder-buffer)
13177 (widen)
13178 (let ((case-fold-search t))
13179 (goto-char (point-min))
13180 (if (not (re-search-forward
13181 (concat "^" "message-id: *" (regexp-quote article))))
13182 (error "Could not find the specified message in this folder"))
13183 (vm-isearch-update)
13184 (vm-isearch-narrow)
13185 (vm-beginning-of-message)
13186 (vm-summarize)))))
13188 (defun org-follow-wl-link (folder article)
13189 "Follow a Wanderlust link to FOLDER and ARTICLE."
13190 (if (and (string= folder "%")
13191 article
13192 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
13193 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
13194 ;; Thus, we recompose folder and article ids.
13195 (setq folder (format "%s#%s" folder (match-string 1 article))
13196 article (match-string 3 article)))
13197 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
13198 (error "No such folder: %s" folder))
13199 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
13200 (and article
13201 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
13202 (wl-summary-redisplay)))
13204 (defun org-follow-rmail-link (folder article)
13205 "Follow an RMAIL link to FOLDER and ARTICLE."
13206 (setq article (org-add-angle-brackets article))
13207 (let (message-number)
13208 (save-excursion
13209 (save-window-excursion
13210 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13211 (setq message-number
13212 (save-restriction
13213 (widen)
13214 (goto-char (point-max))
13215 (if (re-search-backward
13216 (concat "^Message-ID:\\s-+" (regexp-quote
13217 (or article "")))
13218 nil t)
13219 (rmail-what-message))))))
13220 (if message-number
13221 (progn
13222 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13223 (rmail-show-message message-number)
13224 message-number)
13225 (error "Message not found"))))
13227 ;;; mh-e integration based on planner-mode
13228 (defun org-mhe-get-message-real-folder ()
13229 "Return the name of the current message real folder, so if you use
13230 sequences, it will now work."
13231 (save-excursion
13232 (let* ((folder
13233 (if (equal major-mode 'mh-folder-mode)
13234 mh-current-folder
13235 ;; Refer to the show buffer
13236 mh-show-folder-buffer))
13237 (end-index
13238 (if (boundp 'mh-index-folder)
13239 (min (length mh-index-folder) (length folder))))
13241 ;; a simple test on mh-index-data does not work, because
13242 ;; mh-index-data is always nil in a show buffer.
13243 (if (and (boundp 'mh-index-folder)
13244 (string= mh-index-folder (substring folder 0 end-index)))
13245 (if (equal major-mode 'mh-show-mode)
13246 (save-window-excursion
13247 (let (pop-up-frames)
13248 (when (buffer-live-p (get-buffer folder))
13249 (progn
13250 (pop-to-buffer folder)
13251 (org-mhe-get-message-folder-from-index)
13254 (org-mhe-get-message-folder-from-index)
13256 folder
13260 (defun org-mhe-get-message-folder-from-index ()
13261 "Returns the name of the message folder in a index folder buffer."
13262 (save-excursion
13263 (mh-index-previous-folder)
13264 (re-search-forward "^\\(+.*\\)$" nil t)
13265 (message "%s" (match-string 1))))
13267 (defun org-mhe-get-message-folder ()
13268 "Return the name of the current message folder. Be careful if you
13269 use sequences."
13270 (save-excursion
13271 (if (equal major-mode 'mh-folder-mode)
13272 mh-current-folder
13273 ;; Refer to the show buffer
13274 mh-show-folder-buffer)))
13276 (defun org-mhe-get-message-num ()
13277 "Return the number of the current message. Be careful if you
13278 use sequences."
13279 (save-excursion
13280 (if (equal major-mode 'mh-folder-mode)
13281 (mh-get-msg-num nil)
13282 ;; Refer to the show buffer
13283 (mh-show-buffer-message-number))))
13285 (defun org-mhe-get-header (header)
13286 "Return a header of the message in folder mode. This will create a
13287 show buffer for the corresponding message. If you have a more clever
13288 idea..."
13289 (let* ((folder (org-mhe-get-message-folder))
13290 (num (org-mhe-get-message-num))
13291 (buffer (get-buffer-create (concat "show-" folder)))
13292 (header-field))
13293 (with-current-buffer buffer
13294 (mh-display-msg num folder)
13295 (if (equal major-mode 'mh-folder-mode)
13296 (mh-header-display)
13297 (mh-show-header-display))
13298 (set-buffer buffer)
13299 (setq header-field (mh-get-header-field header))
13300 (if (equal major-mode 'mh-folder-mode)
13301 (mh-show)
13302 (mh-show-show))
13303 header-field)))
13305 (defun org-follow-mhe-link (folder article)
13306 "Follow an MHE link to FOLDER and ARTICLE.
13307 If ARTICLE is nil FOLDER is shown. If the configuration variable
13308 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
13309 ARTICLE is searched in all folders. Indexed searches (swish++,
13310 namazu, and others supported by MH-E) will always search in all
13311 folders."
13312 (require 'mh-e)
13313 (require 'mh-search)
13314 (require 'mh-utils)
13315 (mh-find-path)
13316 (if (not article)
13317 (mh-visit-folder (mh-normalize-folder-name folder))
13318 (setq article (org-add-angle-brackets article))
13319 (mh-search-choose)
13320 (if (equal mh-searcher 'pick)
13321 (progn
13322 (mh-search folder (list "--message-id" article))
13323 (when (and org-mhe-search-all-folders
13324 (not (org-mhe-get-message-real-folder)))
13325 (kill-this-buffer)
13326 (mh-search "+" (list "--message-id" article))))
13327 (mh-search "+" article))
13328 (if (org-mhe-get-message-real-folder)
13329 (mh-show-msg 1)
13330 (kill-this-buffer)
13331 (error "Message not found"))))
13333 ;;; BibTeX links
13335 ;; Use the custom search meachnism to construct and use search strings for
13336 ;; file links to BibTeX database entries.
13338 (defun org-create-file-search-in-bibtex ()
13339 "Create the search string and description for a BibTeX database entry."
13340 (when (eq major-mode 'bibtex-mode)
13341 ;; yes, we want to construct this search string.
13342 ;; Make a good description for this entry, using names, year and the title
13343 ;; Put it into the `description' variable which is dynamically scoped.
13344 (let ((bibtex-autokey-names 1)
13345 (bibtex-autokey-names-stretch 1)
13346 (bibtex-autokey-name-case-convert-function 'identity)
13347 (bibtex-autokey-name-separator " & ")
13348 (bibtex-autokey-additional-names " et al.")
13349 (bibtex-autokey-year-length 4)
13350 (bibtex-autokey-name-year-separator " ")
13351 (bibtex-autokey-titlewords 3)
13352 (bibtex-autokey-titleword-separator " ")
13353 (bibtex-autokey-titleword-case-convert-function 'identity)
13354 (bibtex-autokey-titleword-length 'infty)
13355 (bibtex-autokey-year-title-separator ": "))
13356 (setq description (bibtex-generate-autokey)))
13357 ;; Now parse the entry, get the key and return it.
13358 (save-excursion
13359 (bibtex-beginning-of-entry)
13360 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13362 (defun org-execute-file-search-in-bibtex (s)
13363 "Find the link search string S as a key for a database entry."
13364 (when (eq major-mode 'bibtex-mode)
13365 ;; Yes, we want to do the search in this file.
13366 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13367 (goto-char (point-min))
13368 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13369 (regexp-quote s) "[ \t\n]*,") nil t)
13370 (goto-char (match-beginning 0)))
13371 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13372 ;; Use double prefix to indicate that any web link should be browsed
13373 (let ((b (current-buffer)) (p (point)))
13374 ;; Restore the window configuration because we just use the web link
13375 (set-window-configuration org-window-config-before-follow-link)
13376 (save-excursion (set-buffer b) (goto-char p)
13377 (bibtex-url)))
13378 (recenter 0)) ; Move entry start to beginning of window
13379 ;; return t to indicate that the search is done.
13382 ;; Finally add the functions to the right hooks.
13383 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13384 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13386 ;; end of Bibtex link setup
13388 ;;; Following file links
13390 (defun org-open-file (path &optional in-emacs line search)
13391 "Open the file at PATH.
13392 First, this expands any special file name abbreviations. Then the
13393 configuration variable `org-file-apps' is checked if it contains an
13394 entry for this file type, and if yes, the corresponding command is launched.
13395 If no application is found, Emacs simply visits the file.
13396 With optional argument IN-EMACS, Emacs will visit the file.
13397 Optional LINE specifies a line to go to, optional SEARCH a string to
13398 search for. If LINE or SEARCH is given, the file will always be
13399 opened in Emacs.
13400 If the file does not exist, an error is thrown."
13401 (setq in-emacs (or in-emacs line search))
13402 (let* ((file (if (equal path "")
13403 buffer-file-name
13404 (substitute-in-file-name (expand-file-name path))))
13405 (apps (append org-file-apps (org-default-apps)))
13406 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13407 (dirp (if remp nil (file-directory-p file)))
13408 (dfile (downcase file))
13409 (old-buffer (current-buffer))
13410 (old-pos (point))
13411 (old-mode major-mode)
13412 ext cmd)
13413 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13414 (setq ext (match-string 1 dfile))
13415 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13416 (setq ext (match-string 1 dfile))))
13417 (if in-emacs
13418 (setq cmd 'emacs)
13419 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13420 (and dirp (cdr (assoc 'directory apps)))
13421 (cdr (assoc ext apps))
13422 (cdr (assoc t apps)))))
13423 (when (eq cmd 'mailcap)
13424 (require 'mailcap)
13425 (mailcap-parse-mailcaps)
13426 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13427 (command (mailcap-mime-info mime-type)))
13428 (if (stringp command)
13429 (setq cmd command)
13430 (setq cmd 'emacs))))
13431 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13432 (not (file-exists-p file))
13433 (not org-open-non-existing-files))
13434 (error "No such file: %s" file))
13435 (cond
13436 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13437 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13438 (while (string-match "['\"]%s['\"]" cmd)
13439 (setq cmd (replace-match "%s" t t cmd)))
13440 (while (string-match "%s" cmd)
13441 (setq cmd (replace-match
13442 (save-match-data (shell-quote-argument file))
13443 t t cmd)))
13444 (save-window-excursion
13445 (start-process-shell-command cmd nil cmd)))
13446 ((or (stringp cmd)
13447 (eq cmd 'emacs))
13448 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13449 (widen)
13450 (if line (goto-line line)
13451 (if search (org-link-search search))))
13452 ((consp cmd)
13453 (eval cmd))
13454 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13455 (and (org-mode-p) (eq old-mode 'org-mode)
13456 (or (not (equal old-buffer (current-buffer)))
13457 (not (equal old-pos (point))))
13458 (org-mark-ring-push old-pos old-buffer))))
13460 (defun org-default-apps ()
13461 "Return the default applications for this operating system."
13462 (cond
13463 ((eq system-type 'darwin)
13464 org-file-apps-defaults-macosx)
13465 ((eq system-type 'windows-nt)
13466 org-file-apps-defaults-windowsnt)
13467 (t org-file-apps-defaults-gnu)))
13469 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13470 (defun org-file-remote-p (file)
13471 "Test whether FILE specifies a location on a remote system.
13472 Return non-nil if the location is indeed remote.
13474 For example, the filename \"/user@host:/foo\" specifies a location
13475 on the system \"/user@host:\"."
13476 (cond ((fboundp 'file-remote-p)
13477 (file-remote-p file))
13478 ((fboundp 'tramp-handle-file-remote-p)
13479 (tramp-handle-file-remote-p file))
13480 ((and (boundp 'ange-ftp-name-format)
13481 (string-match (car ange-ftp-name-format) file))
13483 (t nil)))
13486 ;;;; Hooks for remember.el, and refiling
13488 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13489 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13491 ;;;###autoload
13492 (defun org-remember-insinuate ()
13493 "Setup remember.el for use wiht Org-mode."
13494 (require 'remember)
13495 (setq remember-annotation-functions '(org-remember-annotation))
13496 (setq remember-handler-functions '(org-remember-handler))
13497 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13499 ;;;###autoload
13500 (defun org-remember-annotation ()
13501 "Return a link to the current location as an annotation for remember.el.
13502 If you are using Org-mode files as target for data storage with
13503 remember.el, then the annotations should include a link compatible with the
13504 conventions in Org-mode. This function returns such a link."
13505 (org-store-link nil))
13507 (defconst org-remember-help
13508 "Select a destination location for the note.
13509 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13510 RET on headline -> Store as sublevel entry to current headline
13511 RET at beg-of-buf -> Append to file as level 2 headline
13512 <left>/<right> -> before/after current headline, same headings level")
13514 (defvar org-remember-previous-location nil)
13515 (defvar org-force-remember-template-char) ;; dynamically scoped
13517 (defun org-select-remember-template (&optional use-char)
13518 (when org-remember-templates
13519 (let* ((templates (mapcar (lambda (x)
13520 (if (stringp (car x))
13521 (append (list (nth 1 x) (car x)) (cddr x))
13522 (append (list (car x) "") (cdr x))))
13523 org-remember-templates))
13524 (char (or use-char
13525 (cond
13526 ((= (length templates) 1)
13527 (caar templates))
13528 ((and (boundp 'org-force-remember-template-char)
13529 org-force-remember-template-char)
13530 (if (stringp org-force-remember-template-char)
13531 (string-to-char org-force-remember-template-char)
13532 org-force-remember-template-char))
13534 (message "Select template: %s"
13535 (mapconcat
13536 (lambda (x)
13537 (cond
13538 ((not (string-match "\\S-" (nth 1 x)))
13539 (format "[%c]" (car x)))
13540 ((equal (downcase (car x))
13541 (downcase (aref (nth 1 x) 0)))
13542 (format "[%c]%s" (car x)
13543 (substring (nth 1 x) 1)))
13544 (t (format "[%c]%s" (car x) (nth 1 x)))))
13545 templates " "))
13546 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13547 (when (equal char0 ?\C-g)
13548 (jump-to-register remember-register)
13549 (kill-buffer remember-buffer))
13550 char0))))))
13551 (cddr (assoc char templates)))))
13553 (defvar x-last-selected-text)
13554 (defvar x-last-selected-text-primary)
13556 ;;;###autoload
13557 (defun org-remember-apply-template (&optional use-char skip-interactive)
13558 "Initialize *remember* buffer with template, invoke `org-mode'.
13559 This function should be placed into `remember-mode-hook' and in fact requires
13560 to be run from that hook to function properly."
13561 (if org-remember-templates
13562 (let* ((entry (org-select-remember-template use-char))
13563 (tpl (car entry))
13564 (plist-p (if org-store-link-plist t nil))
13565 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13566 (string-match "\\S-" (nth 1 entry)))
13567 (nth 1 entry)
13568 org-default-notes-file))
13569 (headline (nth 2 entry))
13570 (v-c (or (and (eq window-system 'x)
13571 (fboundp 'x-cut-buffer-or-selection-value)
13572 (x-cut-buffer-or-selection-value))
13573 (org-bound-and-true-p x-last-selected-text)
13574 (org-bound-and-true-p x-last-selected-text-primary)
13575 (and (> (length kill-ring) 0) (current-kill 0))))
13576 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13577 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13578 (v-u (concat "[" (substring v-t 1 -1) "]"))
13579 (v-U (concat "[" (substring v-T 1 -1) "]"))
13580 ;; `initial' and `annotation' are bound in `remember'
13581 (v-i (if (boundp 'initial) initial))
13582 (v-a (if (and (boundp 'annotation) annotation)
13583 (if (equal annotation "[[]]") "" annotation)
13584 ""))
13585 (v-A (if (and v-a
13586 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13587 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13588 v-a))
13589 (v-n user-full-name)
13590 (org-startup-folded nil)
13591 org-time-was-given org-end-time-was-given x
13592 prompt completions char time pos default histvar)
13593 (setq org-store-link-plist
13594 (append (list :annotation v-a :initial v-i)
13595 org-store-link-plist))
13596 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13597 (erase-buffer)
13598 (insert (substitute-command-keys
13599 (format
13600 "## Filing location: Select interactively, default, or last used:
13601 ## %s to select file and header location interactively.
13602 ## %s \"%s\" -> \"* %s\"
13603 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13604 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13605 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13606 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13607 (abbreviate-file-name (or file org-default-notes-file))
13608 (or headline "")
13609 (or (car org-remember-previous-location) "???")
13610 (or (cdr org-remember-previous-location) "???"))))
13611 (insert tpl) (goto-char (point-min))
13612 ;; Simple %-escapes
13613 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13614 (when (and initial (equal (match-string 0) "%i"))
13615 (save-match-data
13616 (let* ((lead (buffer-substring
13617 (point-at-bol) (match-beginning 0))))
13618 (setq v-i (mapconcat 'identity
13619 (org-split-string initial "\n")
13620 (concat "\n" lead))))))
13621 (replace-match
13622 (or (eval (intern (concat "v-" (match-string 1)))) "")
13623 t t))
13625 ;; %[] Insert contents of a file.
13626 (goto-char (point-min))
13627 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13628 (let ((start (match-beginning 0))
13629 (end (match-end 0))
13630 (filename (expand-file-name (match-string 1))))
13631 (goto-char start)
13632 (delete-region start end)
13633 (condition-case error
13634 (insert-file-contents filename)
13635 (error (insert (format "%%![Couldn't insert %s: %s]"
13636 filename error))))))
13637 ;; %() embedded elisp
13638 (goto-char (point-min))
13639 (while (re-search-forward "%\\((.+)\\)" nil t)
13640 (goto-char (match-beginning 0))
13641 (let ((template-start (point)))
13642 (forward-char 1)
13643 (let ((result
13644 (condition-case error
13645 (eval (read (current-buffer)))
13646 (error (format "%%![Error: %s]" error)))))
13647 (delete-region template-start (point))
13648 (insert result))))
13650 ;; From the property list
13651 (when plist-p
13652 (goto-char (point-min))
13653 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13654 (and (setq x (or (plist-get org-store-link-plist
13655 (intern (match-string 1))) ""))
13656 (replace-match x t t))))
13658 ;; Turn on org-mode in the remember buffer, set local variables
13659 (org-mode)
13660 (org-set-local 'org-finish-function 'org-remember-finalize)
13661 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13662 (org-set-local 'org-default-notes-file file))
13663 (if (and headline (stringp headline) (string-match "\\S-" headline))
13664 (org-set-local 'org-remember-default-headline headline))
13665 ;; Interactive template entries
13666 (goto-char (point-min))
13667 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGuUtT]\\)?" nil t)
13668 (setq char (if (match-end 3) (match-string 3))
13669 prompt (if (match-end 2) (match-string 2)))
13670 (goto-char (match-beginning 0))
13671 (replace-match "")
13672 (setq completions nil default nil)
13673 (when prompt
13674 (setq completions (org-split-string prompt "|")
13675 prompt (pop completions)
13676 default (car completions)
13677 histvar (intern (concat
13678 "org-remember-template-prompt-history::"
13679 (or prompt "")))
13680 completions (mapcar 'list completions)))
13681 (cond
13682 ((member char '("G" "g"))
13683 (let* ((org-last-tags-completion-table
13684 (org-global-tags-completion-table
13685 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13686 (org-add-colon-after-tag-completion t)
13687 (ins (completing-read
13688 (if prompt (concat prompt ": ") "Tags: ")
13689 'org-tags-completion-function nil nil nil
13690 'org-tags-history)))
13691 (setq ins (mapconcat 'identity
13692 (org-split-string ins (org-re "[^[:alnum:]_@]+"))
13693 ":"))
13694 (when (string-match "\\S-" ins)
13695 (or (equal (char-before) ?:) (insert ":"))
13696 (insert ins)
13697 (or (equal (char-after) ?:) (insert ":")))))
13698 (char
13699 (setq org-time-was-given (equal (upcase char) char))
13700 (setq time (org-read-date (equal (upcase char) "U") t nil
13701 prompt))
13702 (org-insert-time-stamp time org-time-was-given
13703 (member char '("u" "U"))
13704 nil nil (list org-end-time-was-given)))
13706 (insert (org-completing-read
13707 (concat (if prompt prompt "Enter string")
13708 (if default (concat " [" default "]"))
13709 ": ")
13710 completions nil nil nil histvar default)))))
13711 (goto-char (point-min))
13712 (if (re-search-forward "%\\?" nil t)
13713 (replace-match "")
13714 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13715 (org-mode)
13716 (org-set-local 'org-finish-function 'org-remember-finalize))
13717 (when (save-excursion
13718 (goto-char (point-min))
13719 (re-search-forward "%!" nil t))
13720 (replace-match "")
13721 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13723 (defun org-remember-finish-immediately ()
13724 "File remember note immediately.
13725 This should be run in `post-command-hook' and will remove itself
13726 from that hook."
13727 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13728 (when org-finish-function
13729 (funcall org-finish-function)))
13731 (defvar org-clock-marker) ; Defined below
13732 (defun org-remember-finalize ()
13733 "Finalize the remember process."
13734 (unless (fboundp 'remember-finalize)
13735 (defalias 'remember-finalize 'remember-buffer))
13736 (when (and org-clock-marker
13737 (equal (marker-buffer org-clock-marker) (current-buffer)))
13738 ;; FIXME: test this, this is w/o notetaking!
13739 (let (org-log-note-clock-out) (org-clock-out)))
13740 (when buffer-file-name
13741 (save-buffer)
13742 (setq buffer-file-name nil))
13743 (remember-finalize))
13745 ;;;###autoload
13746 (defun org-remember (&optional goto org-force-remember-template-char)
13747 "Call `remember'. If this is already a remember buffer, re-apply template.
13748 If there is an active region, make sure remember uses it as initial content
13749 of the remember buffer.
13751 When called interactively with a `C-u' prefix argument GOTO, don't remember
13752 anything, just go to the file/headline where the selected template usually
13753 stores its notes. With a double prefix arg `C-u C-u', go to the last
13754 note stored by remember.
13756 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13757 associated with a template in `org-remember-templates'."
13758 (interactive "P")
13759 (cond
13760 ((equal goto '(4)) (org-go-to-remember-target))
13761 ((equal goto '(16)) (org-remember-goto-last-stored))
13763 (if (memq org-finish-function '(remember-buffer remember-finalize))
13764 (progn
13765 (when (< (length org-remember-templates) 2)
13766 (error "No other template available"))
13767 (erase-buffer)
13768 (let ((annotation (plist-get org-store-link-plist :annotation))
13769 (initial (plist-get org-store-link-plist :initial)))
13770 (org-remember-apply-template))
13771 (message "Press C-c C-c to remember data"))
13772 (if (org-region-active-p)
13773 (remember (buffer-substring (point) (mark)))
13774 (call-interactively 'remember))))))
13776 (defun org-remember-goto-last-stored ()
13777 "Go to the location where the last remember note was stored."
13778 (interactive)
13779 (bookmark-jump "org-remember-last-stored")
13780 (message "This is the last note stored by remember"))
13782 (defun org-go-to-remember-target (&optional template-key)
13783 "Go to the target location of a remember template.
13784 The user is queried for the template."
13785 (interactive)
13786 (let* ((entry (org-select-remember-template template-key))
13787 (file (nth 1 entry))
13788 (heading (nth 2 entry))
13789 visiting)
13790 (unless (and file (stringp file) (string-match "\\S-" file))
13791 (setq file org-default-notes-file))
13792 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13793 (setq heading org-remember-default-headline))
13794 (setq visiting (org-find-base-buffer-visiting file))
13795 (if (not visiting) (find-file-noselect file))
13796 (switch-to-buffer (or visiting (get-file-buffer file)))
13797 (widen)
13798 (goto-char (point-min))
13799 (if (re-search-forward
13800 (concat "^\\*+[ \t]+" (regexp-quote heading)
13801 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13802 nil t)
13803 (goto-char (match-beginning 0))
13804 (error "Target headline not found: %s" heading))))
13806 (defvar org-note-abort nil) ; dynamically scoped
13808 ;;;###autoload
13809 (defun org-remember-handler ()
13810 "Store stuff from remember.el into an org file.
13811 First prompts for an org file. If the user just presses return, the value
13812 of `org-default-notes-file' is used.
13813 Then the command offers the headings tree of the selected file in order to
13814 file the text at a specific location.
13815 You can either immediately press RET to get the note appended to the
13816 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13817 find a better place. Then press RET or <left> or <right> in insert the note.
13819 Key Cursor position Note gets inserted
13820 -----------------------------------------------------------------------------
13821 RET buffer-start as level 1 heading at end of file
13822 RET on headline as sublevel of the heading at cursor
13823 RET no heading at cursor position, level taken from context.
13824 Or use prefix arg to specify level manually.
13825 <left> on headline as same level, before current heading
13826 <right> on headline as same level, after current heading
13828 So the fastest way to store the note is to press RET RET to append it to
13829 the default file. This way your current train of thought is not
13830 interrupted, in accordance with the principles of remember.el.
13831 You can also get the fast execution without prompting by using
13832 C-u C-c C-c to exit the remember buffer. See also the variable
13833 `org-remember-store-without-prompt'.
13835 Before being stored away, the function ensures that the text has a
13836 headline, i.e. a first line that starts with a \"*\". If not, a headline
13837 is constructed from the current date and some additional data.
13839 If the variable `org-adapt-indentation' is non-nil, the entire text is
13840 also indented so that it starts in the same column as the headline
13841 \(i.e. after the stars).
13843 See also the variable `org-reverse-note-order'."
13844 (goto-char (point-min))
13845 (while (looking-at "^[ \t]*\n\\|^##.*\n")
13846 (replace-match ""))
13847 (goto-char (point-max))
13848 (beginning-of-line 1)
13849 (while (looking-at "[ \t]*$\\|##.*")
13850 (delete-region (1- (point)) (point-max))
13851 (beginning-of-line 1))
13852 (catch 'quit
13853 (if org-note-abort (throw 'quit nil))
13854 (let* ((txt (buffer-substring (point-min) (point-max)))
13855 (fastp (org-xor (equal current-prefix-arg '(4))
13856 org-remember-store-without-prompt))
13857 (file (cond
13858 (fastp org-default-notes-file)
13859 ((and (eq org-remember-interactive-interface 'refile)
13860 org-refile-targets)
13861 org-default-notes-file)
13862 ((not (and (equal current-prefix-arg '(16))
13863 org-remember-previous-location))
13864 (org-get-org-file))))
13865 (heading org-remember-default-headline)
13866 (visiting (and file (org-find-base-buffer-visiting file)))
13867 (org-startup-folded nil)
13868 (org-startup-align-all-tables nil)
13869 (org-goto-start-pos 1)
13870 spos exitcmd level indent reversed)
13871 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
13872 (setq file (car org-remember-previous-location)
13873 heading (cdr org-remember-previous-location)
13874 fastp t))
13875 (setq current-prefix-arg nil)
13876 (if (string-match "[ \t\n]+\\'" txt)
13877 (setq txt (replace-match "" t t txt)))
13878 ;; Modify text so that it becomes a nice subtree which can be inserted
13879 ;; into an org tree.
13880 (let* ((lines (split-string txt "\n"))
13881 first)
13882 (setq first (car lines) lines (cdr lines))
13883 (if (string-match "^\\*+ " first)
13884 ;; Is already a headline
13885 (setq indent nil)
13886 ;; We need to add a headline: Use time and first buffer line
13887 (setq lines (cons first lines)
13888 first (concat "* " (current-time-string)
13889 " (" (remember-buffer-desc) ")")
13890 indent " "))
13891 (if (and org-adapt-indentation indent)
13892 (setq lines (mapcar
13893 (lambda (x)
13894 (if (string-match "\\S-" x)
13895 (concat indent x) x))
13896 lines)))
13897 (setq txt (concat first "\n"
13898 (mapconcat 'identity lines "\n"))))
13899 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
13900 (setq txt (replace-match "\n\n" t t txt))
13901 (if (string-match "[ \t\n]*\\'" txt)
13902 (setq txt (replace-match "\n" t t txt))))
13903 ;; Put the modified text back into the remember buffer, for refile.
13904 (erase-buffer)
13905 (insert txt)
13906 (goto-char (point-min))
13907 (when (and (eq org-remember-interactive-interface 'refile)
13908 (not fastp))
13909 (org-refile nil (or visiting (find-file-noselect file)))
13910 (throw 'quit t))
13911 ;; Find the file
13912 (if (not visiting) (find-file-noselect file))
13913 (with-current-buffer (or visiting (get-file-buffer file))
13914 (unless (org-mode-p)
13915 (error "Target files for remember notes must be in Org-mode"))
13916 (save-excursion
13917 (save-restriction
13918 (widen)
13919 (and (goto-char (point-min))
13920 (not (re-search-forward "^\\* " nil t))
13921 (insert "\n* " (or heading "Notes") "\n"))
13922 (setq reversed (org-notes-order-reversed-p))
13924 ;; Find the default location
13925 (when (and heading (stringp heading) (string-match "\\S-" heading))
13926 (goto-char (point-min))
13927 (if (re-search-forward
13928 (concat "^\\*+[ \t]+" (regexp-quote heading)
13929 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13930 nil t)
13931 (setq org-goto-start-pos (match-beginning 0))
13932 (when fastp
13933 (goto-char (point-max))
13934 (unless (bolp) (newline))
13935 (insert "* " heading "\n")
13936 (setq org-goto-start-pos (point-at-bol 0)))))
13938 ;; Ask the User for a location, using the appropriate interface
13939 (cond
13940 (fastp (setq spos org-goto-start-pos
13941 exitcmd 'return))
13942 ((eq org-remember-interactive-interface 'outline)
13943 (setq spos (org-get-location (current-buffer)
13944 org-remember-help)
13945 exitcmd (cdr spos)
13946 spos (car spos)))
13947 ((eq org-remember-interactive-interface 'outline-path-completion)
13948 (let ((org-refile-targets '((nil . (:maxlevel . 10))))
13949 (org-refile-use-outline-path t))
13950 (setq spos (org-refile-get-location "Heading: ")
13951 exitcmd 'return
13952 spos (nth 3 spos))))
13953 (t (error "this should not hapen")))
13954 (if (not spos) (throw 'quit nil)) ; return nil to show we did
13955 ; not handle this note
13956 (goto-char spos)
13957 (cond ((org-on-heading-p t)
13958 (org-back-to-heading t)
13959 (setq level (funcall outline-level))
13960 (cond
13961 ((eq exitcmd 'return)
13962 ;; sublevel of current
13963 (setq org-remember-previous-location
13964 (cons (abbreviate-file-name file)
13965 (org-get-heading 'notags)))
13966 (if reversed
13967 (outline-next-heading)
13968 (org-end-of-subtree t)
13969 (if (not (bolp))
13970 (if (looking-at "[ \t]*\n")
13971 (beginning-of-line 2)
13972 (end-of-line 1)
13973 (insert "\n"))))
13974 (bookmark-set "org-remember-last-stored")
13975 (org-paste-subtree (org-get-legal-level level 1) txt))
13976 ((eq exitcmd 'left)
13977 ;; before current
13978 (bookmark-set "org-remember-last-stored")
13979 (org-paste-subtree level txt))
13980 ((eq exitcmd 'right)
13981 ;; after current
13982 (org-end-of-subtree t)
13983 (bookmark-set "org-remember-last-stored")
13984 (org-paste-subtree level txt))
13985 (t (error "This should not happen"))))
13987 ((and (bobp) (not reversed))
13988 ;; Put it at the end, one level below level 1
13989 (save-restriction
13990 (widen)
13991 (goto-char (point-max))
13992 (if (not (bolp)) (newline))
13993 (bookmark-set "org-remember-last-stored")
13994 (org-paste-subtree (org-get-legal-level 1 1) txt)))
13996 ((and (bobp) reversed)
13997 ;; Put it at the start, as level 1
13998 (save-restriction
13999 (widen)
14000 (goto-char (point-min))
14001 (re-search-forward "^\\*+ " nil t)
14002 (beginning-of-line 1)
14003 (bookmark-set "org-remember-last-stored")
14004 (org-paste-subtree 1 txt)))
14006 ;; Put it right there, with automatic level determined by
14007 ;; org-paste-subtree or from prefix arg
14008 (bookmark-set "org-remember-last-stored")
14009 (org-paste-subtree
14010 (if (numberp current-prefix-arg) current-prefix-arg)
14011 txt)))
14012 (when remember-save-after-remembering
14013 (save-buffer)
14014 (if (not visiting) (kill-buffer (current-buffer)))))))))
14016 t) ;; return t to indicate that we took care of this note.
14018 (defun org-get-org-file ()
14019 "Read a filename, with default directory `org-directory'."
14020 (let ((default (or org-default-notes-file remember-data-file)))
14021 (read-file-name (format "File name [%s]: " default)
14022 (file-name-as-directory org-directory)
14023 default)))
14025 (defun org-notes-order-reversed-p ()
14026 "Check if the current file should receive notes in reversed order."
14027 (cond
14028 ((not org-reverse-note-order) nil)
14029 ((eq t org-reverse-note-order) t)
14030 ((not (listp org-reverse-note-order)) nil)
14031 (t (catch 'exit
14032 (let ((all org-reverse-note-order)
14033 entry)
14034 (while (setq entry (pop all))
14035 (if (string-match (car entry) buffer-file-name)
14036 (throw 'exit (cdr entry))))
14037 nil)))))
14039 ;;; Refiling
14041 (defvar org-refile-target-table nil
14042 "The list of refile targets, created by `org-refile'.")
14044 (defvar org-agenda-new-buffers nil
14045 "Buffers created to visit agenda files.")
14047 (defun org-get-refile-targets (&optional default-buffer)
14048 "Produce a table with refile targets."
14049 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
14050 targets txt re files f desc descre)
14051 (with-current-buffer (or default-buffer (current-buffer))
14052 (while (setq entry (pop entries))
14053 (setq files (car entry) desc (cdr entry))
14054 (cond
14055 ((null files) (setq files (list (current-buffer))))
14056 ((eq files 'org-agenda-files)
14057 (setq files (org-agenda-files 'unrestricted)))
14058 ((and (symbolp files) (fboundp files))
14059 (setq files (funcall files)))
14060 ((and (symbolp files) (boundp files))
14061 (setq files (symbol-value files))))
14062 (if (stringp files) (setq files (list files)))
14063 (cond
14064 ((eq (car desc) :tag)
14065 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
14066 ((eq (car desc) :todo)
14067 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
14068 ((eq (car desc) :regexp)
14069 (setq descre (cdr desc)))
14070 ((eq (car desc) :level)
14071 (setq descre (concat "^\\*\\{" (number-to-string
14072 (if org-odd-levels-only
14073 (1- (* 2 (cdr desc)))
14074 (cdr desc)))
14075 "\\}[ \t]")))
14076 ((eq (car desc) :maxlevel)
14077 (setq descre (concat "^\\*\\{1," (number-to-string
14078 (if org-odd-levels-only
14079 (1- (* 2 (cdr desc)))
14080 (cdr desc)))
14081 "\\}[ \t]")))
14082 (t (error "Bad refiling target description %s" desc)))
14083 (while (setq f (pop files))
14084 (save-excursion
14085 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
14086 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
14087 (save-excursion
14088 (save-restriction
14089 (widen)
14090 (goto-char (point-min))
14091 (while (re-search-forward descre nil t)
14092 (goto-char (point-at-bol))
14093 (when (looking-at org-complex-heading-regexp)
14094 (setq txt (match-string 4)
14095 re (concat "^" (regexp-quote
14096 (buffer-substring (match-beginning 1)
14097 (match-end 4)))))
14098 (if (match-end 5) (setq re (concat re "[ \t]+"
14099 (regexp-quote
14100 (match-string 5)))))
14101 (setq re (concat re "[ \t]*$"))
14102 (when org-refile-use-outline-path
14103 (setq txt (mapconcat 'identity
14104 (append
14105 (if (eq org-refile-use-outline-path 'file)
14106 (list (file-name-nondirectory
14107 (buffer-file-name (buffer-base-buffer))))
14108 (if (eq org-refile-use-outline-path 'full-file-path)
14109 (list (buffer-file-name (buffer-base-buffer)))))
14110 (org-get-outline-path)
14111 (list txt))
14112 "/")))
14113 (push (list txt f re (point)) targets))
14114 (goto-char (point-at-eol))))))))
14115 (nreverse targets))))
14117 (defun org-get-outline-path ()
14118 "Return the outline path to the current entry, as a list."
14119 (let (rtn)
14120 (save-excursion
14121 (while (org-up-heading-safe)
14122 (when (looking-at org-complex-heading-regexp)
14123 (push (org-match-string-no-properties 4) rtn)))
14124 rtn)))
14126 (defvar org-refile-history nil
14127 "History for refiling operations.")
14129 (defun org-refile (&optional goto default-buffer)
14130 "Move the entry at point to another heading.
14131 The list of target headings is compiled using the information in
14132 `org-refile-targets', which see. This list is created upon first use, and
14133 you can update it by calling this command with a double prefix (`C-u C-u').
14134 FIXME: Can we find a better way of updating?
14136 At the target location, the entry is filed as a subitem of the target heading.
14137 Depending on `org-reverse-note-order', the new subitem will either be the
14138 first of the last subitem.
14140 With prefix arg GOTO, the command will only visit the target location,
14141 not actually move anything.
14142 With a double prefix `C-c C-c', go to the location where the last refiling
14143 operation has put the subtree.
14145 With a double prefix argument, the command can be used to jump to any
14146 heading in the current buffer."
14147 (interactive "P")
14148 (let* ((cbuf (current-buffer))
14149 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14150 pos it nbuf file re level reversed)
14151 (if (equal goto '(16))
14152 (org-refile-goto-last-stored)
14153 (when (setq it (org-refile-get-location
14154 (if goto "Goto: " "Refile to: ") default-buffer))
14155 (setq file (nth 1 it)
14156 re (nth 2 it)
14157 pos (nth 3 it))
14158 (setq nbuf (or (find-buffer-visiting file)
14159 (find-file-noselect file)))
14160 (if goto
14161 (progn
14162 (switch-to-buffer nbuf)
14163 (goto-char pos)
14164 (org-show-context 'org-goto))
14165 (org-copy-special)
14166 (save-excursion
14167 (set-buffer (setq nbuf (or (find-buffer-visiting file)
14168 (find-file-noselect file))))
14169 (setq reversed (org-notes-order-reversed-p))
14170 (save-excursion
14171 (save-restriction
14172 (widen)
14173 (goto-char pos)
14174 (looking-at outline-regexp)
14175 (setq level (org-get-legal-level (funcall outline-level) 1))
14176 (goto-char
14177 (if reversed
14178 (outline-next-heading)
14179 (or (save-excursion (outline-get-next-sibling))
14180 (org-end-of-subtree t t)
14181 (point-max))))
14182 (bookmark-set "org-refile-last-stored")
14183 (org-paste-subtree level))))
14184 (org-cut-special)
14185 (message "Entry refiled to \"%s\"" (car it)))))))
14187 (defun org-refile-goto-last-stored ()
14188 "Go to the location where the last refile was stored."
14189 (interactive)
14190 (bookmark-jump "org-refile-last-stored")
14191 (message "This is the location of the last refile"))
14193 (defun org-refile-get-location (&optional prompt default-buffer)
14194 "Prompt the user for a refile location, using PROMPT."
14195 (let ((org-refile-targets org-refile-targets)
14196 (org-refile-use-outline-path org-refile-use-outline-path))
14197 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
14198 (unless org-refile-target-table
14199 (error "No refile targets"))
14200 (let* ((cbuf (current-buffer))
14201 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14202 (fname (and filename (file-truename filename)))
14203 (tbl (mapcar
14204 (lambda (x)
14205 (if (not (equal fname (file-truename (nth 1 x))))
14206 (cons (concat (car x) " (" (file-name-nondirectory
14207 (nth 1 x)) ")")
14208 (cdr x))
14210 org-refile-target-table))
14211 (completion-ignore-case t))
14212 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
14213 tbl)))
14215 ;;;; Dynamic blocks
14217 (defun org-find-dblock (name)
14218 "Find the first dynamic block with name NAME in the buffer.
14219 If not found, stay at current position and return nil."
14220 (let (pos)
14221 (save-excursion
14222 (goto-char (point-min))
14223 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
14224 nil t)
14225 (match-beginning 0))))
14226 (if pos (goto-char pos))
14227 pos))
14229 (defconst org-dblock-start-re
14230 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
14231 "Matches the startline of a dynamic block, with parameters.")
14233 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
14234 "Matches the end of a dyhamic block.")
14236 (defun org-create-dblock (plist)
14237 "Create a dynamic block section, with parameters taken from PLIST.
14238 PLIST must containe a :name entry which is used as name of the block."
14239 (unless (bolp) (newline))
14240 (let ((name (plist-get plist :name)))
14241 (insert "#+BEGIN: " name)
14242 (while plist
14243 (if (eq (car plist) :name)
14244 (setq plist (cddr plist))
14245 (insert " " (prin1-to-string (pop plist)))))
14246 (insert "\n\n#+END:\n")
14247 (beginning-of-line -2)))
14249 (defun org-prepare-dblock ()
14250 "Prepare dynamic block for refresh.
14251 This empties the block, puts the cursor at the insert position and returns
14252 the property list including an extra property :name with the block name."
14253 (unless (looking-at org-dblock-start-re)
14254 (error "Not at a dynamic block"))
14255 (let* ((begdel (1+ (match-end 0)))
14256 (name (org-no-properties (match-string 1)))
14257 (params (append (list :name name)
14258 (read (concat "(" (match-string 3) ")")))))
14259 (unless (re-search-forward org-dblock-end-re nil t)
14260 (error "Dynamic block not terminated"))
14261 (delete-region begdel (match-beginning 0))
14262 (goto-char begdel)
14263 (open-line 1)
14264 params))
14266 (defun org-map-dblocks (&optional command)
14267 "Apply COMMAND to all dynamic blocks in the current buffer.
14268 If COMMAND is not given, use `org-update-dblock'."
14269 (let ((cmd (or command 'org-update-dblock))
14270 pos)
14271 (save-excursion
14272 (goto-char (point-min))
14273 (while (re-search-forward org-dblock-start-re nil t)
14274 (goto-char (setq pos (match-beginning 0)))
14275 (condition-case nil
14276 (funcall cmd)
14277 (error (message "Error during update of dynamic block")))
14278 (goto-char pos)
14279 (unless (re-search-forward org-dblock-end-re nil t)
14280 (error "Dynamic block not terminated"))))))
14282 (defun org-dblock-update (&optional arg)
14283 "User command for updating dynamic blocks.
14284 Update the dynamic block at point. With prefix ARG, update all dynamic
14285 blocks in the buffer."
14286 (interactive "P")
14287 (if arg
14288 (org-update-all-dblocks)
14289 (or (looking-at org-dblock-start-re)
14290 (org-beginning-of-dblock))
14291 (org-update-dblock)))
14293 (defun org-update-dblock ()
14294 "Update the dynamic block at point
14295 This means to empty the block, parse for parameters and then call
14296 the correct writing function."
14297 (save-window-excursion
14298 (let* ((pos (point))
14299 (line (org-current-line))
14300 (params (org-prepare-dblock))
14301 (name (plist-get params :name))
14302 (cmd (intern (concat "org-dblock-write:" name))))
14303 (message "Updating dynamic block `%s' at line %d..." name line)
14304 (funcall cmd params)
14305 (message "Updating dynamic block `%s' at line %d...done" name line)
14306 (goto-char pos))))
14308 (defun org-beginning-of-dblock ()
14309 "Find the beginning of the dynamic block at point.
14310 Error if there is no scuh block at point."
14311 (let ((pos (point))
14312 beg)
14313 (end-of-line 1)
14314 (if (and (re-search-backward org-dblock-start-re nil t)
14315 (setq beg (match-beginning 0))
14316 (re-search-forward org-dblock-end-re nil t)
14317 (> (match-end 0) pos))
14318 (goto-char beg)
14319 (goto-char pos)
14320 (error "Not in a dynamic block"))))
14322 (defun org-update-all-dblocks ()
14323 "Update all dynamic blocks in the buffer.
14324 This function can be used in a hook."
14325 (when (org-mode-p)
14326 (org-map-dblocks 'org-update-dblock)))
14329 ;;;; Completion
14331 (defconst org-additional-option-like-keywords
14332 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14333 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
14334 "BEGIN_EXAMPLE" "END_EXAMPLE"))
14336 (defun org-complete (&optional arg)
14337 "Perform completion on word at point.
14338 At the beginning of a headline, this completes TODO keywords as given in
14339 `org-todo-keywords'.
14340 If the current word is preceded by a backslash, completes the TeX symbols
14341 that are supported for HTML support.
14342 If the current word is preceded by \"#+\", completes special words for
14343 setting file options.
14344 In the line after \"#+STARTUP:, complete valid keywords.\"
14345 At all other locations, this simply calls the value of
14346 `org-completion-fallback-command'."
14347 (interactive "P")
14348 (org-without-partial-completion
14349 (catch 'exit
14350 (let* ((end (point))
14351 (beg1 (save-excursion
14352 (skip-chars-backward (org-re "[:alnum:]_@"))
14353 (point)))
14354 (beg (save-excursion
14355 (skip-chars-backward "a-zA-Z0-9_:$")
14356 (point)))
14357 (confirm (lambda (x) (stringp (car x))))
14358 (searchhead (equal (char-before beg) ?*))
14359 (tag (and (equal (char-before beg1) ?:)
14360 (equal (char-after (point-at-bol)) ?*)))
14361 (prop (and (equal (char-before beg1) ?:)
14362 (not (equal (char-after (point-at-bol)) ?*))))
14363 (texp (equal (char-before beg) ?\\))
14364 (link (equal (char-before beg) ?\[))
14365 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14366 beg)
14367 "#+"))
14368 (startup (string-match "^#\\+STARTUP:.*"
14369 (buffer-substring (point-at-bol) (point))))
14370 (completion-ignore-case opt)
14371 (type nil)
14372 (tbl nil)
14373 (table (cond
14374 (opt
14375 (setq type :opt)
14376 (append
14377 (mapcar
14378 (lambda (x)
14379 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14380 (cons (match-string 2 x) (match-string 1 x)))
14381 (org-split-string (org-get-current-options) "\n"))
14382 (mapcar 'list org-additional-option-like-keywords)))
14383 (startup
14384 (setq type :startup)
14385 org-startup-options)
14386 (link (append org-link-abbrev-alist-local
14387 org-link-abbrev-alist))
14388 (texp
14389 (setq type :tex)
14390 org-html-entities)
14391 ((string-match "\\`\\*+[ \t]+\\'"
14392 (buffer-substring (point-at-bol) beg))
14393 (setq type :todo)
14394 (mapcar 'list org-todo-keywords-1))
14395 (searchhead
14396 (setq type :searchhead)
14397 (save-excursion
14398 (goto-char (point-min))
14399 (while (re-search-forward org-todo-line-regexp nil t)
14400 (push (list
14401 (org-make-org-heading-search-string
14402 (match-string 3) t))
14403 tbl)))
14404 tbl)
14405 (tag (setq type :tag beg beg1)
14406 (or org-tag-alist (org-get-buffer-tags)))
14407 (prop (setq type :prop beg beg1)
14408 (mapcar 'list (org-buffer-property-keys nil t t)))
14409 (t (progn
14410 (call-interactively org-completion-fallback-command)
14411 (throw 'exit nil)))))
14412 (pattern (buffer-substring-no-properties beg end))
14413 (completion (try-completion pattern table confirm)))
14414 (cond ((eq completion t)
14415 (if (not (assoc (upcase pattern) table))
14416 (message "Already complete")
14417 (if (equal type :opt)
14418 (insert (substring (cdr (assoc (upcase pattern) table))
14419 (length pattern)))
14420 (if (memq type '(:tag :prop)) (insert ":")))))
14421 ((null completion)
14422 (message "Can't find completion for \"%s\"" pattern)
14423 (ding))
14424 ((not (string= pattern completion))
14425 (delete-region beg end)
14426 (if (string-match " +$" completion)
14427 (setq completion (replace-match "" t t completion)))
14428 (insert completion)
14429 (if (get-buffer-window "*Completions*")
14430 (delete-window (get-buffer-window "*Completions*")))
14431 (if (assoc completion table)
14432 (if (eq type :todo) (insert " ")
14433 (if (memq type '(:tag :prop)) (insert ":"))))
14434 (if (and (equal type :opt) (assoc completion table))
14435 (message "%s" (substitute-command-keys
14436 "Press \\[org-complete] again to insert example settings"))))
14438 (message "Making completion list...")
14439 (let ((list (sort (all-completions pattern table confirm)
14440 'string<)))
14441 (with-output-to-temp-buffer "*Completions*"
14442 (condition-case nil
14443 ;; Protection needed for XEmacs and emacs 21
14444 (display-completion-list list pattern)
14445 (error (display-completion-list list)))))
14446 (message "Making completion list...%s" "done")))))))
14448 ;;;; TODO, DEADLINE, Comments
14450 (defun org-toggle-comment ()
14451 "Change the COMMENT state of an entry."
14452 (interactive)
14453 (save-excursion
14454 (org-back-to-heading)
14455 (let (case-fold-search)
14456 (if (looking-at (concat outline-regexp
14457 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14458 (replace-match "" t t nil 1)
14459 (if (looking-at outline-regexp)
14460 (progn
14461 (goto-char (match-end 0))
14462 (insert org-comment-string " ")))))))
14464 (defvar org-last-todo-state-is-todo nil
14465 "This is non-nil when the last TODO state change led to a TODO state.
14466 If the last change removed the TODO tag or switched to DONE, then
14467 this is nil.")
14469 (defvar org-setting-tags nil) ; dynamically skiped
14471 ;; FIXME: better place
14472 (defun org-property-or-variable-value (var &optional inherit)
14473 "Check if there is a property fixing the value of VAR.
14474 If yes, return this value. If not, return the current value of the variable."
14475 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14476 (if (and prop (stringp prop) (string-match "\\S-" prop))
14477 (read prop)
14478 (symbol-value var))))
14480 (defun org-parse-local-options (string var)
14481 "Parse STRING for startup setting relevant for variable VAR."
14482 (let ((rtn (symbol-value var))
14483 e opts)
14484 (save-match-data
14485 (if (or (not string) (not (string-match "\\S-" string)))
14487 (setq opts (delq nil (mapcar (lambda (x)
14488 (setq e (assoc x org-startup-options))
14489 (if (eq (nth 1 e) var) e nil))
14490 (org-split-string string "[ \t]+"))))
14491 (if (not opts)
14493 (setq rtn nil)
14494 (while (setq e (pop opts))
14495 (if (not (nth 3 e))
14496 (setq rtn (nth 2 e))
14497 (if (not (listp rtn)) (setq rtn nil))
14498 (push (nth 2 e) rtn)))
14499 rtn)))))
14501 (defvar org-blocker-hook nil
14502 "Hook for functions that are allowed to block a state change.
14504 Each function gets as its single argument a property list, see
14505 `org-trigger-hook' for more information about this list.
14507 If any of the functions in this hook returns nil, the state change
14508 is blocked.")
14510 (defvar org-trigger-hook nil
14511 "Hook for functions that are triggered by a state change.
14513 Each function gets as its single argument a property list with at least
14514 the following elements:
14516 (:type type-of-change :position pos-at-entry-start
14517 :from old-state :to new-state)
14519 Depending on the type, more properties may be present.
14521 This mechanism is currently implemented for:
14523 TODO state changes
14524 ------------------
14525 :type todo-state-change
14526 :from previous state (keyword as a string), or nil
14527 :to new state (keyword as a string), or nil")
14530 (defun org-todo (&optional arg)
14531 "Change the TODO state of an item.
14532 The state of an item is given by a keyword at the start of the heading,
14533 like
14534 *** TODO Write paper
14535 *** DONE Call mom
14537 The different keywords are specified in the variable `org-todo-keywords'.
14538 By default the available states are \"TODO\" and \"DONE\".
14539 So for this example: when the item starts with TODO, it is changed to DONE.
14540 When it starts with DONE, the DONE is removed. And when neither TODO nor
14541 DONE are present, add TODO at the beginning of the heading.
14543 With C-u prefix arg, use completion to determine the new state.
14544 With numeric prefix arg, switch to that state.
14546 For calling through lisp, arg is also interpreted in the following way:
14547 'none -> empty state
14548 \"\"(empty string) -> switch to empty state
14549 'done -> switch to DONE
14550 'nextset -> switch to the next set of keywords
14551 'previousset -> switch to the previous set of keywords
14552 \"WAITING\" -> switch to the specified keyword, but only if it
14553 really is a member of `org-todo-keywords'."
14554 (interactive "P")
14555 (save-excursion
14556 (catch 'exit
14557 (org-back-to-heading)
14558 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14559 (or (looking-at (concat " +" org-todo-regexp " *"))
14560 (looking-at " *"))
14561 (let* ((match-data (match-data))
14562 (startpos (point-at-bol))
14563 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14564 (org-log-done org-log-done)
14565 (org-log-repeat org-log-repeat)
14566 (org-todo-log-states org-todo-log-states)
14567 (this (match-string 1))
14568 (hl-pos (match-beginning 0))
14569 (head (org-get-todo-sequence-head this))
14570 (ass (assoc head org-todo-kwd-alist))
14571 (interpret (nth 1 ass))
14572 (done-word (nth 3 ass))
14573 (final-done-word (nth 4 ass))
14574 (last-state (or this ""))
14575 (completion-ignore-case t)
14576 (member (member this org-todo-keywords-1))
14577 (tail (cdr member))
14578 (state (cond
14579 ((and org-todo-key-trigger
14580 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14581 (and (not arg) org-use-fast-todo-selection
14582 (not (eq org-use-fast-todo-selection 'prefix)))))
14583 ;; Use fast selection
14584 (org-fast-todo-selection))
14585 ((and (equal arg '(4))
14586 (or (not org-use-fast-todo-selection)
14587 (not org-todo-key-trigger)))
14588 ;; Read a state with completion
14589 (completing-read "State: " (mapcar (lambda(x) (list x))
14590 org-todo-keywords-1)
14591 nil t))
14592 ((eq arg 'right)
14593 (if this
14594 (if tail (car tail) nil)
14595 (car org-todo-keywords-1)))
14596 ((eq arg 'left)
14597 (if (equal member org-todo-keywords-1)
14599 (if this
14600 (nth (- (length org-todo-keywords-1) (length tail) 2)
14601 org-todo-keywords-1)
14602 (org-last org-todo-keywords-1))))
14603 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14604 (setq arg nil))) ; hack to fall back to cycling
14605 (arg
14606 ;; user or caller requests a specific state
14607 (cond
14608 ((equal arg "") nil)
14609 ((eq arg 'none) nil)
14610 ((eq arg 'done) (or done-word (car org-done-keywords)))
14611 ((eq arg 'nextset)
14612 (or (car (cdr (member head org-todo-heads)))
14613 (car org-todo-heads)))
14614 ((eq arg 'previousset)
14615 (let ((org-todo-heads (reverse org-todo-heads)))
14616 (or (car (cdr (member head org-todo-heads)))
14617 (car org-todo-heads))))
14618 ((car (member arg org-todo-keywords-1)))
14619 ((nth (1- (prefix-numeric-value arg))
14620 org-todo-keywords-1))))
14621 ((null member) (or head (car org-todo-keywords-1)))
14622 ((equal this final-done-word) nil) ;; -> make empty
14623 ((null tail) nil) ;; -> first entry
14624 ((eq interpret 'sequence)
14625 (car tail))
14626 ((memq interpret '(type priority))
14627 (if (eq this-command last-command)
14628 (car tail)
14629 (if (> (length tail) 0)
14630 (or done-word (car org-done-keywords))
14631 nil)))
14632 (t nil)))
14633 (next (if state (concat " " state " ") " "))
14634 (change-plist (list :type 'todo-state-change :from this :to state
14635 :position startpos))
14636 dolog now-done-p)
14637 (when org-blocker-hook
14638 (unless (save-excursion
14639 (save-match-data
14640 (run-hook-with-args-until-failure
14641 'org-blocker-hook change-plist)))
14642 (if (interactive-p)
14643 (error "TODO state change from %s to %s blocked" this state)
14644 ;; fail silently
14645 (message "TODO state change from %s to %s blocked" this state)
14646 (throw 'exit nil))))
14647 (store-match-data match-data)
14648 (replace-match next t t)
14649 (unless (pos-visible-in-window-p hl-pos)
14650 (message "TODO state changed to %s" (org-trim next)))
14651 (unless head
14652 (setq head (org-get-todo-sequence-head state)
14653 ass (assoc head org-todo-kwd-alist)
14654 interpret (nth 1 ass)
14655 done-word (nth 3 ass)
14656 final-done-word (nth 4 ass)))
14657 (when (memq arg '(nextset previousset))
14658 (message "Keyword-Set %d/%d: %s"
14659 (- (length org-todo-sets) -1
14660 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14661 (length org-todo-sets)
14662 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14663 (setq org-last-todo-state-is-todo
14664 (not (member state org-done-keywords)))
14665 (setq now-done-p (and (member state org-done-keywords)
14666 (not (member this org-done-keywords))))
14667 (and logging (org-local-logging logging))
14668 (when (and (or org-todo-log-states org-log-done)
14669 (not (memq arg '(nextset previousset))))
14670 ;; we need to look at recording a time and note
14671 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
14672 (nth 2 (assoc this org-todo-log-states))))
14673 (when (and state
14674 (member state org-not-done-keywords)
14675 (not (member this org-not-done-keywords)))
14676 ;; This is now a todo state and was not one before
14677 ;; If there was a CLOSED time stamp, get rid of it.
14678 (org-add-planning-info nil nil 'closed))
14679 (when (and now-done-p org-log-done)
14680 ;; It is now done, and it was not done before
14681 (org-add-planning-info 'closed (org-current-time))
14682 (if (and (not dolog) (eq 'note org-log-done))
14683 (org-add-log-maybe 'done state 'findpos 'note)))
14684 (when (and state dolog)
14685 ;; This is a non-nil state, and we need to log it
14686 (org-add-log-maybe 'state state 'findpos dolog)))
14687 ;; Fixup tag positioning
14688 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14689 (run-hooks 'org-after-todo-state-change-hook)
14690 (if (and arg (not (member state org-done-keywords)))
14691 (setq head (org-get-todo-sequence-head state)))
14692 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14693 ;; Do we need to trigger a repeat?
14694 (when now-done-p (org-auto-repeat-maybe state))
14695 ;; Fixup cursor location if close to the keyword
14696 (if (and (outline-on-heading-p)
14697 (not (bolp))
14698 (save-excursion (beginning-of-line 1)
14699 (looking-at org-todo-line-regexp))
14700 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14701 (progn
14702 (goto-char (or (match-end 2) (match-end 1)))
14703 (just-one-space)))
14704 (when org-trigger-hook
14705 (save-excursion
14706 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14708 (defun org-local-logging (value)
14709 "Get logging settings from a property VALUE."
14710 (let* (words w a)
14711 ;; directly set the variables, they are already local.
14712 (setq org-log-done nil
14713 org-log-repeat nil
14714 org-todo-log-states nil)
14715 (setq words (org-split-string value))
14716 (while (setq w (pop words))
14717 (cond
14718 ((setq a (assoc w org-startup-options))
14719 (and (member (nth 1 a) '(org-log-done org-log-repeat))
14720 (set (nth 1 a) (nth 2 a))))
14721 ((setq a (org-extract-log-state-settings w))
14722 (and (member (car a) org-todo-keywords-1)
14723 (push a org-todo-log-states)))))))
14725 (defun org-get-todo-sequence-head (kwd)
14726 "Return the head of the TODO sequence to which KWD belongs.
14727 If KWD is not set, check if there is a text property remembering the
14728 right sequence."
14729 (let (p)
14730 (cond
14731 ((not kwd)
14732 (or (get-text-property (point-at-bol) 'org-todo-head)
14733 (progn
14734 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14735 nil (point-at-eol)))
14736 (get-text-property p 'org-todo-head))))
14737 ((not (member kwd org-todo-keywords-1))
14738 (car org-todo-keywords-1))
14739 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14741 (defun org-fast-todo-selection ()
14742 "Fast TODO keyword selection with single keys.
14743 Returns the new TODO keyword, or nil if no state change should occur."
14744 (let* ((fulltable org-todo-key-alist)
14745 (done-keywords org-done-keywords) ;; needed for the faces.
14746 (maxlen (apply 'max (mapcar
14747 (lambda (x)
14748 (if (stringp (car x)) (string-width (car x)) 0))
14749 fulltable)))
14750 (expert nil)
14751 (fwidth (+ maxlen 3 1 3))
14752 (ncol (/ (- (window-width) 4) fwidth))
14753 tg cnt e c tbl
14754 groups ingroup)
14755 (save-window-excursion
14756 (if expert
14757 (set-buffer (get-buffer-create " *Org todo*"))
14758 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14759 (erase-buffer)
14760 (org-set-local 'org-done-keywords done-keywords)
14761 (setq tbl fulltable cnt 0)
14762 (while (setq e (pop tbl))
14763 (cond
14764 ((equal e '(:startgroup))
14765 (push '() groups) (setq ingroup t)
14766 (when (not (= cnt 0))
14767 (setq cnt 0)
14768 (insert "\n"))
14769 (insert "{ "))
14770 ((equal e '(:endgroup))
14771 (setq ingroup nil cnt 0)
14772 (insert "}\n"))
14774 (setq tg (car e) c (cdr e))
14775 (if ingroup (push tg (car groups)))
14776 (setq tg (org-add-props tg nil 'face
14777 (org-get-todo-face tg)))
14778 (if (and (= cnt 0) (not ingroup)) (insert " "))
14779 (insert "[" c "] " tg (make-string
14780 (- fwidth 4 (length tg)) ?\ ))
14781 (when (= (setq cnt (1+ cnt)) ncol)
14782 (insert "\n")
14783 (if ingroup (insert " "))
14784 (setq cnt 0)))))
14785 (insert "\n")
14786 (goto-char (point-min))
14787 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14788 (fit-window-to-buffer))
14789 (message "[a-z..]:Set [SPC]:clear")
14790 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14791 (cond
14792 ((or (= c ?\C-g)
14793 (and (= c ?q) (not (rassoc c fulltable))))
14794 (setq quit-flag t))
14795 ((= c ?\ ) nil)
14796 ((setq e (rassoc c fulltable) tg (car e))
14798 (t (setq quit-flag t))))))
14800 (defun org-get-repeat ()
14801 "Check if tere is a deadline/schedule with repeater in this entry."
14802 (save-match-data
14803 (save-excursion
14804 (org-back-to-heading t)
14805 (if (re-search-forward
14806 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
14807 (match-string 1)))))
14809 (defvar org-last-changed-timestamp)
14810 (defvar org-log-post-message)
14811 (defvar org-log-note-purpose)
14812 (defun org-auto-repeat-maybe (done-word)
14813 "Check if the current headline contains a repeated deadline/schedule.
14814 If yes, set TODO state back to what it was and change the base date
14815 of repeating deadline/scheduled time stamps to new date.
14816 This function should be run in the `org-after-todo-state-change-hook'."
14817 ;; last-state is dynamically scoped into this function
14818 (let* ((repeat (org-get-repeat))
14819 (aa (assoc last-state org-todo-kwd-alist))
14820 (interpret (nth 1 aa))
14821 (head (nth 2 aa))
14822 (whata '(("d" . day) ("m" . month) ("y" . year)))
14823 (msg "Entry repeats: ")
14824 (org-log-done nil)
14825 re type n what ts)
14826 (when repeat
14827 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
14828 (org-todo (if (eq interpret 'type) last-state head))
14829 (when (and org-log-repeat
14830 (or (not (memq 'org-add-log-note
14831 (default-value 'post-command-hook)))
14832 (eq org-log-note-purpose 'done)))
14833 ;; Make sure a note is taken;
14834 (org-add-log-maybe 'state (or done-word (car org-done-keywords))
14835 'findpos org-log-repeat))
14836 (org-back-to-heading t)
14837 (org-add-planning-info nil nil 'closed)
14838 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
14839 org-deadline-time-regexp "\\)\\|\\("
14840 org-ts-regexp "\\)"))
14841 (while (re-search-forward
14842 re (save-excursion (outline-next-heading) (point)) t)
14843 (setq type (if (match-end 1) org-scheduled-string
14844 (if (match-end 3) org-deadline-string "Plain:"))
14845 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
14846 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
14847 (setq n (string-to-number (match-string 1 ts))
14848 what (match-string 2 ts))
14849 (if (equal what "w") (setq n (* n 7) what "d"))
14850 (org-timestamp-change n (cdr (assoc what whata)))
14851 (setq msg (concat msg type org-last-changed-timestamp " "))))
14852 (setq org-log-post-message msg)
14853 (message "%s" msg))))
14855 (defun org-show-todo-tree (arg)
14856 "Make a compact tree which shows all headlines marked with TODO.
14857 The tree will show the lines where the regexp matches, and all higher
14858 headlines above the match.
14859 With \\[universal-argument] prefix, also show the DONE entries.
14860 With a numeric prefix N, construct a sparse tree for the Nth element
14861 of `org-todo-keywords-1'."
14862 (interactive "P")
14863 (let ((case-fold-search nil)
14864 (kwd-re
14865 (cond ((null arg) org-not-done-regexp)
14866 ((equal arg '(4))
14867 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
14868 (mapcar 'list org-todo-keywords-1))))
14869 (concat "\\("
14870 (mapconcat 'identity (org-split-string kwd "|") "\\|")
14871 "\\)\\>")))
14872 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
14873 (regexp-quote (nth (1- (prefix-numeric-value arg))
14874 org-todo-keywords-1)))
14875 (t (error "Invalid prefix argument: %s" arg)))))
14876 (message "%d TODO entries found"
14877 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
14879 (defun org-deadline (&optional remove)
14880 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
14881 With argument REMOVE, remove any deadline from the item."
14882 (interactive "P")
14883 (if remove
14884 (progn
14885 (org-remove-timestamp-with-keyword org-deadline-string)
14886 (message "Item no longer has a deadline."))
14887 (org-add-planning-info 'deadline nil 'closed)))
14889 (defun org-schedule (&optional remove)
14890 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
14891 With argument REMOVE, remove any scheduling date from the item."
14892 (interactive "P")
14893 (if remove
14894 (progn
14895 (org-remove-timestamp-with-keyword org-scheduled-string)
14896 (message "Item is no longer scheduled."))
14897 (org-add-planning-info 'scheduled nil 'closed)))
14899 (defun org-remove-timestamp-with-keyword (keyword)
14900 "Remove all time stamps with KEYWORD in the current entry."
14901 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
14902 beg)
14903 (save-excursion
14904 (org-back-to-heading t)
14905 (setq beg (point))
14906 (org-end-of-subtree t t)
14907 (while (re-search-backward re beg t)
14908 (replace-match "")
14909 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
14910 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
14912 (defun org-add-planning-info (what &optional time &rest remove)
14913 "Insert new timestamp with keyword in the line directly after the headline.
14914 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
14915 If non is given, the user is prompted for a date.
14916 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
14917 be removed."
14918 (interactive)
14919 (let (org-time-was-given org-end-time-was-given)
14920 (when what (setq time (or time (org-read-date nil 'to-time))))
14921 (when (and org-insert-labeled-timestamps-at-point
14922 (member what '(scheduled deadline)))
14923 (insert
14924 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
14925 (org-insert-time-stamp time org-time-was-given
14926 nil nil nil (list org-end-time-was-given))
14927 (setq what nil))
14928 (save-excursion
14929 (save-restriction
14930 (let (col list elt ts buffer-invisibility-spec)
14931 (org-back-to-heading t)
14932 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
14933 (goto-char (match-end 1))
14934 (setq col (current-column))
14935 (goto-char (match-end 0))
14936 (if (eobp) (insert "\n") (forward-char 1))
14937 (if (and (not (looking-at outline-regexp))
14938 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
14939 "[^\r\n]*"))
14940 (not (equal (match-string 1) org-clock-string)))
14941 (narrow-to-region (match-beginning 0) (match-end 0))
14942 (insert-before-markers "\n")
14943 (backward-char 1)
14944 (narrow-to-region (point) (point))
14945 (indent-to-column col))
14946 ;; Check if we have to remove something.
14947 (setq list (cons what remove))
14948 (while list
14949 (setq elt (pop list))
14950 (goto-char (point-min))
14951 (when (or (and (eq elt 'scheduled)
14952 (re-search-forward org-scheduled-time-regexp nil t))
14953 (and (eq elt 'deadline)
14954 (re-search-forward org-deadline-time-regexp nil t))
14955 (and (eq elt 'closed)
14956 (re-search-forward org-closed-time-regexp nil t)))
14957 (replace-match "")
14958 (if (looking-at "--+<[^>]+>") (replace-match ""))
14959 (if (looking-at " +") (replace-match ""))))
14960 (goto-char (point-max))
14961 (when what
14962 (insert
14963 (if (not (equal (char-before) ?\ )) " " "")
14964 (cond ((eq what 'scheduled) org-scheduled-string)
14965 ((eq what 'deadline) org-deadline-string)
14966 ((eq what 'closed) org-closed-string))
14967 " ")
14968 (setq ts (org-insert-time-stamp
14969 time
14970 (or org-time-was-given
14971 (and (eq what 'closed) org-log-done-with-time))
14972 (eq what 'closed)
14973 nil nil (list org-end-time-was-given)))
14974 (end-of-line 1))
14975 (goto-char (point-min))
14976 (widen)
14977 (if (looking-at "[ \t]+\r?\n")
14978 (replace-match ""))
14979 ts)))))
14981 (defvar org-log-note-marker (make-marker))
14982 (defvar org-log-note-purpose nil)
14983 (defvar org-log-note-state nil)
14984 (defvar org-log-note-how nil)
14985 (defvar org-log-note-window-configuration nil)
14986 (defvar org-log-note-return-to (make-marker))
14987 (defvar org-log-post-message nil
14988 "Message to be displayed after a log note has been stored.
14989 The auto-repeater uses this.")
14991 (defun org-add-log-maybe (&optional purpose state findpos how)
14992 "Set up the post command hook to take a note.
14993 If this is about to TODO state change, the new state is expected in STATE.
14994 When FINDPOS is non-nil, find the correct position for the note in
14995 the current entry. If not, assume that it can be inserted at point."
14996 (save-excursion
14997 (when findpos
14998 (org-back-to-heading t)
14999 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
15000 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
15001 "[^\r\n]*\\)?"))
15002 (goto-char (match-end 0))
15003 (unless org-log-states-order-reversed
15004 (and (= (char-after) ?\n) (forward-char 1))
15005 (org-skip-over-state-notes)
15006 (skip-chars-backward " \t\n\r")))
15007 (move-marker org-log-note-marker (point))
15008 (setq org-log-note-purpose purpose
15009 org-log-note-state state
15010 org-log-note-how how)
15011 (add-hook 'post-command-hook 'org-add-log-note 'append)))
15013 (defun org-skip-over-state-notes ()
15014 "Skip past the list of State notes in an entry."
15015 (if (looking-at "\n[ \t]*- State") (forward-char 1))
15016 (while (looking-at "[ \t]*- State")
15017 (condition-case nil
15018 (org-next-item)
15019 (error (org-end-of-item)))))
15021 (defun org-add-log-note (&optional purpose)
15022 "Pop up a window for taking a note, and add this note later at point."
15023 (remove-hook 'post-command-hook 'org-add-log-note)
15024 (setq org-log-note-window-configuration (current-window-configuration))
15025 (delete-other-windows)
15026 (move-marker org-log-note-return-to (point))
15027 (switch-to-buffer (marker-buffer org-log-note-marker))
15028 (goto-char org-log-note-marker)
15029 (org-switch-to-buffer-other-window "*Org Note*")
15030 (erase-buffer)
15031 (if (memq org-log-note-how '(time state)) ; FIXME: time or state????????????
15032 (org-store-log-note)
15033 (let ((org-inhibit-startup t)) (org-mode))
15034 (insert (format "# Insert note for %s.
15035 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
15036 (cond
15037 ((eq org-log-note-purpose 'clock-out) "stopped clock")
15038 ((eq org-log-note-purpose 'done) "closed todo item")
15039 ((eq org-log-note-purpose 'state)
15040 (format "state change to \"%s\"" org-log-note-state))
15041 (t (error "This should not happen")))))
15042 (org-set-local 'org-finish-function 'org-store-log-note)))
15044 (defun org-store-log-note ()
15045 "Finish taking a log note, and insert it to where it belongs."
15046 (let ((txt (buffer-string))
15047 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
15048 lines ind)
15049 (kill-buffer (current-buffer))
15050 (while (string-match "\\`#.*\n[ \t\n]*" txt)
15051 (setq txt (replace-match "" t t txt)))
15052 (if (string-match "\\s-+\\'" txt)
15053 (setq txt (replace-match "" t t txt)))
15054 (setq lines (org-split-string txt "\n"))
15055 (when (and note (string-match "\\S-" note))
15056 (setq note
15057 (org-replace-escapes
15058 note
15059 (list (cons "%u" (user-login-name))
15060 (cons "%U" user-full-name)
15061 (cons "%t" (format-time-string
15062 (org-time-stamp-format 'long 'inactive)
15063 (current-time)))
15064 (cons "%s" (if org-log-note-state
15065 (concat "\"" org-log-note-state "\"")
15066 "")))))
15067 (if lines (setq note (concat note " \\\\")))
15068 (push note lines))
15069 (when (or current-prefix-arg org-note-abort) (setq lines nil))
15070 (when lines
15071 (save-excursion
15072 (set-buffer (marker-buffer org-log-note-marker))
15073 (save-excursion
15074 (goto-char org-log-note-marker)
15075 (move-marker org-log-note-marker nil)
15076 (end-of-line 1)
15077 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
15078 (indent-relative nil)
15079 (insert "- " (pop lines))
15080 (org-indent-line-function)
15081 (beginning-of-line 1)
15082 (looking-at "[ \t]*")
15083 (setq ind (concat (match-string 0) " "))
15084 (end-of-line 1)
15085 (while lines (insert "\n" ind (pop lines)))))))
15086 (set-window-configuration org-log-note-window-configuration)
15087 (with-current-buffer (marker-buffer org-log-note-return-to)
15088 (goto-char org-log-note-return-to))
15089 (move-marker org-log-note-return-to nil)
15090 (and org-log-post-message (message "%s" org-log-post-message)))
15092 ;; FIXME: what else would be useful?
15093 ;; - priority
15094 ;; - date
15096 (defun org-sparse-tree (&optional arg)
15097 "Create a sparse tree, prompt for the details.
15098 This command can create sparse trees. You first need to select the type
15099 of match used to create the tree:
15101 t Show entries with a specific TODO keyword.
15102 T Show entries selected by a tags match.
15103 p Enter a property name and its value (both with completion on existing
15104 names/values) and show entries with that property.
15105 r Show entries matching a regular expression
15106 d Show deadlines due within `org-deadline-warning-days'."
15107 (interactive "P")
15108 (let (ans kwd value)
15109 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
15110 (setq ans (read-char-exclusive))
15111 (cond
15112 ((equal ans ?d)
15113 (call-interactively 'org-check-deadlines))
15114 ((equal ans ?b)
15115 (call-interactively 'org-check-before-date))
15116 ((equal ans ?t)
15117 (org-show-todo-tree '(4)))
15118 ((equal ans ?T)
15119 (call-interactively 'org-tags-sparse-tree))
15120 ((member ans '(?p ?P))
15121 (setq kwd (completing-read "Property: "
15122 (mapcar 'list (org-buffer-property-keys))))
15123 (setq value (completing-read "Value: "
15124 (mapcar 'list (org-property-values kwd))))
15125 (unless (string-match "\\`{.*}\\'" value)
15126 (setq value (concat "\"" value "\"")))
15127 (org-tags-sparse-tree arg (concat kwd "=" value)))
15128 ((member ans '(?r ?R ?/))
15129 (call-interactively 'org-occur))
15130 (t (error "No such sparse tree command \"%c\"" ans)))))
15132 (defvar org-occur-highlights nil)
15133 (make-variable-buffer-local 'org-occur-highlights)
15135 (defun org-occur (regexp &optional keep-previous callback)
15136 "Make a compact tree which shows all matches of REGEXP.
15137 The tree will show the lines where the regexp matches, and all higher
15138 headlines above the match. It will also show the heading after the match,
15139 to make sure editing the matching entry is easy.
15140 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
15141 call to `org-occur' will be kept, to allow stacking of calls to this
15142 command.
15143 If CALLBACK is non-nil, it is a function which is called to confirm
15144 that the match should indeed be shown."
15145 (interactive "sRegexp: \nP")
15146 (or keep-previous (org-remove-occur-highlights nil nil t))
15147 (let ((cnt 0))
15148 (save-excursion
15149 (goto-char (point-min))
15150 (if (or (not keep-previous) ; do not want to keep
15151 (not org-occur-highlights)) ; no previous matches
15152 ;; hide everything
15153 (org-overview))
15154 (while (re-search-forward regexp nil t)
15155 (when (or (not callback)
15156 (save-match-data (funcall callback)))
15157 (setq cnt (1+ cnt))
15158 (when org-highlight-sparse-tree-matches
15159 (org-highlight-new-match (match-beginning 0) (match-end 0)))
15160 (org-show-context 'occur-tree))))
15161 (when org-remove-highlights-with-change
15162 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
15163 nil 'local))
15164 (unless org-sparse-tree-open-archived-trees
15165 (org-hide-archived-subtrees (point-min) (point-max)))
15166 (run-hooks 'org-occur-hook)
15167 (if (interactive-p)
15168 (message "%d match(es) for regexp %s" cnt regexp))
15169 cnt))
15171 (defun org-show-context (&optional key)
15172 "Make sure point and context and visible.
15173 How much context is shown depends upon the variables
15174 `org-show-hierarchy-above', `org-show-following-heading'. and
15175 `org-show-siblings'."
15176 (let ((heading-p (org-on-heading-p t))
15177 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
15178 (following-p (org-get-alist-option org-show-following-heading key))
15179 (entry-p (org-get-alist-option org-show-entry-below key))
15180 (siblings-p (org-get-alist-option org-show-siblings key)))
15181 (catch 'exit
15182 ;; Show heading or entry text
15183 (if (and heading-p (not entry-p))
15184 (org-flag-heading nil) ; only show the heading
15185 (and (or entry-p (org-invisible-p) (org-invisible-p2))
15186 (org-show-hidden-entry))) ; show entire entry
15187 (when following-p
15188 ;; Show next sibling, or heading below text
15189 (save-excursion
15190 (and (if heading-p (org-goto-sibling) (outline-next-heading))
15191 (org-flag-heading nil))))
15192 (when siblings-p (org-show-siblings))
15193 (when hierarchy-p
15194 ;; show all higher headings, possibly with siblings
15195 (save-excursion
15196 (while (and (condition-case nil
15197 (progn (org-up-heading-all 1) t)
15198 (error nil))
15199 (not (bobp)))
15200 (org-flag-heading nil)
15201 (when siblings-p (org-show-siblings))))))))
15203 (defun org-reveal (&optional siblings)
15204 "Show current entry, hierarchy above it, and the following headline.
15205 This can be used to show a consistent set of context around locations
15206 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
15207 not t for the search context.
15209 With optional argument SIBLINGS, on each level of the hierarchy all
15210 siblings are shown. This repairs the tree structure to what it would
15211 look like when opened with hierarchical calls to `org-cycle'."
15212 (interactive "P")
15213 (let ((org-show-hierarchy-above t)
15214 (org-show-following-heading t)
15215 (org-show-siblings (if siblings t org-show-siblings)))
15216 (org-show-context nil)))
15218 (defun org-highlight-new-match (beg end)
15219 "Highlight from BEG to END and mark the highlight is an occur headline."
15220 (let ((ov (org-make-overlay beg end)))
15221 (org-overlay-put ov 'face 'secondary-selection)
15222 (push ov org-occur-highlights)))
15224 (defun org-remove-occur-highlights (&optional beg end noremove)
15225 "Remove the occur highlights from the buffer.
15226 BEG and END are ignored. If NOREMOVE is nil, remove this function
15227 from the `before-change-functions' in the current buffer."
15228 (interactive)
15229 (unless org-inhibit-highlight-removal
15230 (mapc 'org-delete-overlay org-occur-highlights)
15231 (setq org-occur-highlights nil)
15232 (unless noremove
15233 (remove-hook 'before-change-functions
15234 'org-remove-occur-highlights 'local))))
15236 ;;;; Priorities
15238 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
15239 "Regular expression matching the priority indicator.")
15241 (defvar org-remove-priority-next-time nil)
15243 (defun org-priority-up ()
15244 "Increase the priority of the current item."
15245 (interactive)
15246 (org-priority 'up))
15248 (defun org-priority-down ()
15249 "Decrease the priority of the current item."
15250 (interactive)
15251 (org-priority 'down))
15253 (defun org-priority (&optional action)
15254 "Change the priority of an item by ARG.
15255 ACTION can be `set', `up', `down', or a character."
15256 (interactive)
15257 (setq action (or action 'set))
15258 (let (current new news have remove)
15259 (save-excursion
15260 (org-back-to-heading)
15261 (if (looking-at org-priority-regexp)
15262 (setq current (string-to-char (match-string 2))
15263 have t)
15264 (setq current org-default-priority))
15265 (cond
15266 ((or (eq action 'set) (integerp action))
15267 (if (integerp action)
15268 (setq new action)
15269 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
15270 (setq new (read-char-exclusive)))
15271 (if (and (= (upcase org-highest-priority) org-highest-priority)
15272 (= (upcase org-lowest-priority) org-lowest-priority))
15273 (setq new (upcase new)))
15274 (cond ((equal new ?\ ) (setq remove t))
15275 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
15276 (error "Priority must be between `%c' and `%c'"
15277 org-highest-priority org-lowest-priority))))
15278 ((eq action 'up)
15279 (if (and (not have) (eq last-command this-command))
15280 (setq new org-lowest-priority)
15281 (setq new (if (and org-priority-start-cycle-with-default (not have))
15282 org-default-priority (1- current)))))
15283 ((eq action 'down)
15284 (if (and (not have) (eq last-command this-command))
15285 (setq new org-highest-priority)
15286 (setq new (if (and org-priority-start-cycle-with-default (not have))
15287 org-default-priority (1+ current)))))
15288 (t (error "Invalid action")))
15289 (if (or (< (upcase new) org-highest-priority)
15290 (> (upcase new) org-lowest-priority))
15291 (setq remove t))
15292 (setq news (format "%c" new))
15293 (if have
15294 (if remove
15295 (replace-match "" t t nil 1)
15296 (replace-match news t t nil 2))
15297 (if remove
15298 (error "No priority cookie found in line")
15299 (looking-at org-todo-line-regexp)
15300 (if (match-end 2)
15301 (progn
15302 (goto-char (match-end 2))
15303 (insert " [#" news "]"))
15304 (goto-char (match-beginning 3))
15305 (insert "[#" news "] ")))))
15306 (org-preserve-lc (org-set-tags nil 'align))
15307 (if remove
15308 (message "Priority removed")
15309 (message "Priority of current item set to %s" news))))
15312 (defun org-get-priority (s)
15313 "Find priority cookie and return priority."
15314 (save-match-data
15315 (if (not (string-match org-priority-regexp s))
15316 (* 1000 (- org-lowest-priority org-default-priority))
15317 (* 1000 (- org-lowest-priority
15318 (string-to-char (match-string 2 s)))))))
15320 ;;;; Tags
15322 (defun org-scan-tags (action matcher &optional todo-only)
15323 "Scan headline tags with inheritance and produce output ACTION.
15324 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
15325 evaluated, testing if a given set of tags qualifies a headline for
15326 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
15327 are included in the output."
15328 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
15329 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
15330 (org-re
15331 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
15332 (props (list 'face nil
15333 'done-face 'org-done
15334 'undone-face nil
15335 'mouse-face 'highlight
15336 'org-not-done-regexp org-not-done-regexp
15337 'org-todo-regexp org-todo-regexp
15338 'keymap org-agenda-keymap
15339 'help-echo
15340 (format "mouse-2 or RET jump to org file %s"
15341 (abbreviate-file-name
15342 (or (buffer-file-name (buffer-base-buffer))
15343 (buffer-name (buffer-base-buffer)))))))
15344 (case-fold-search nil)
15345 lspos
15346 tags tags-list tags-alist (llast 0) rtn level category i txt
15347 todo marker entry priority)
15348 (save-excursion
15349 (goto-char (point-min))
15350 (when (eq action 'sparse-tree)
15351 (org-overview)
15352 (org-remove-occur-highlights))
15353 (while (re-search-forward re nil t)
15354 (catch :skip
15355 (setq todo (if (match-end 1) (match-string 2))
15356 tags (if (match-end 4) (match-string 4)))
15357 (goto-char (setq lspos (1+ (match-beginning 0))))
15358 (setq level (org-reduced-level (funcall outline-level))
15359 category (org-get-category))
15360 (setq i llast llast level)
15361 ;; remove tag lists from same and sublevels
15362 (while (>= i level)
15363 (when (setq entry (assoc i tags-alist))
15364 (setq tags-alist (delete entry tags-alist)))
15365 (setq i (1- i)))
15366 ;; add the nex tags
15367 (when tags
15368 (setq tags (mapcar 'downcase (org-split-string tags ":"))
15369 tags-alist
15370 (cons (cons level tags) tags-alist)))
15371 ;; compile tags for current headline
15372 (setq tags-list
15373 (if org-use-tag-inheritance
15374 (apply 'append (mapcar 'cdr tags-alist))
15375 tags))
15376 (when (and (or (not todo-only) (member todo org-not-done-keywords))
15377 (eval matcher)
15378 (or (not org-agenda-skip-archived-trees)
15379 (not (member org-archive-tag tags-list))))
15380 (and (eq action 'agenda) (org-agenda-skip))
15381 ;; list this headline
15383 (if (eq action 'sparse-tree)
15384 (progn
15385 (and org-highlight-sparse-tree-matches
15386 (org-get-heading) (match-end 0)
15387 (org-highlight-new-match
15388 (match-beginning 0) (match-beginning 1)))
15389 (org-show-context 'tags-tree))
15390 (setq txt (org-format-agenda-item
15392 (concat
15393 (if org-tags-match-list-sublevels
15394 (make-string (1- level) ?.) "")
15395 (org-get-heading))
15396 category tags-list)
15397 priority (org-get-priority txt))
15398 (goto-char lspos)
15399 (setq marker (org-agenda-new-marker))
15400 (org-add-props txt props
15401 'org-marker marker 'org-hd-marker marker 'org-category category
15402 'priority priority 'type "tagsmatch")
15403 (push txt rtn))
15404 ;; if we are to skip sublevels, jump to end of subtree
15405 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15406 (when (and (eq action 'sparse-tree)
15407 (not org-sparse-tree-open-archived-trees))
15408 (org-hide-archived-subtrees (point-min) (point-max)))
15409 (nreverse rtn)))
15411 (defvar todo-only) ;; dynamically scoped
15413 (defun org-tags-sparse-tree (&optional todo-only match)
15414 "Create a sparse tree according to tags string MATCH.
15415 MATCH can contain positive and negative selection of tags, like
15416 \"+WORK+URGENT-WITHBOSS\".
15417 If optional argument TODO_ONLY is non-nil, only select lines that are
15418 also TODO lines."
15419 (interactive "P")
15420 (org-prepare-agenda-buffers (list (current-buffer)))
15421 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15423 (defvar org-cached-props nil)
15424 (defun org-cached-entry-get (pom property)
15425 (if (or (eq t org-use-property-inheritance)
15426 (member property org-use-property-inheritance))
15427 ;; Caching is not possible, check it directly
15428 (org-entry-get pom property 'inherit)
15429 ;; Get all properties, so that we can do complicated checks easily
15430 (cdr (assoc property (or org-cached-props
15431 (setq org-cached-props
15432 (org-entry-properties pom)))))))
15434 (defun org-global-tags-completion-table (&optional files)
15435 "Return the list of all tags in all agenda buffer/files."
15436 (save-excursion
15437 (org-uniquify
15438 (delq nil
15439 (apply 'append
15440 (mapcar
15441 (lambda (file)
15442 (set-buffer (find-file-noselect file))
15443 (append (org-get-buffer-tags)
15444 (mapcar (lambda (x) (if (stringp (car-safe x))
15445 (list (car-safe x)) nil))
15446 org-tag-alist)))
15447 (if (and files (car files))
15448 files
15449 (org-agenda-files))))))))
15451 (defun org-make-tags-matcher (match)
15452 "Create the TAGS//TODO matcher form for the selection string MATCH."
15453 ;; todo-only is scoped dynamically into this function, and the function
15454 ;; may change it it the matcher asksk for it.
15455 (unless match
15456 ;; Get a new match request, with completion
15457 (let ((org-last-tags-completion-table
15458 (org-global-tags-completion-table)))
15459 (setq match (completing-read
15460 "Match: " 'org-tags-completion-function nil nil nil
15461 'org-tags-history))))
15463 ;; Parse the string and create a lisp form
15464 (let ((match0 match)
15465 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]*\"\\)\\|[[:alnum:]_@]+\\)"))
15466 minus tag mm
15467 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15468 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15469 (if (string-match "/+" match)
15470 ;; match contains also a todo-matching request
15471 (progn
15472 (setq tagsmatch (substring match 0 (match-beginning 0))
15473 todomatch (substring match (match-end 0)))
15474 (if (string-match "^!" todomatch)
15475 (setq todo-only t todomatch (substring todomatch 1)))
15476 (if (string-match "^\\s-*$" todomatch)
15477 (setq todomatch nil)))
15478 ;; only matching tags
15479 (setq tagsmatch match todomatch nil))
15481 ;; Make the tags matcher
15482 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15483 (setq tagsmatcher t)
15484 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15485 (while (setq term (pop orterms))
15486 (while (and (equal (substring term -1) "\\") orterms)
15487 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15488 (while (string-match re term)
15489 (setq minus (and (match-end 1)
15490 (equal (match-string 1 term) "-"))
15491 tag (match-string 2 term)
15492 re-p (equal (string-to-char tag) ?{)
15493 level-p (match-end 3)
15494 prop-p (match-end 4)
15495 mm (cond
15496 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15497 (level-p `(= level ,(string-to-number
15498 (match-string 3 term))))
15499 (prop-p
15500 (setq pn (match-string 4 term)
15501 pv (match-string 5 term)
15502 cat-p (equal pn "CATEGORY")
15503 re-p (equal (string-to-char pv) ?{)
15504 pv (substring pv 1 -1))
15505 (if (equal pn "CATEGORY")
15506 (setq gv '(get-text-property (point) 'org-category))
15507 (setq gv `(org-cached-entry-get nil ,pn)))
15508 (if re-p
15509 `(string-match ,pv (or ,gv ""))
15510 `(equal ,pv (or ,gv ""))))
15511 (t `(member ,(downcase tag) tags-list)))
15512 mm (if minus (list 'not mm) mm)
15513 term (substring term (match-end 0)))
15514 (push mm tagsmatcher))
15515 (push (if (> (length tagsmatcher) 1)
15516 (cons 'and tagsmatcher)
15517 (car tagsmatcher))
15518 orlist)
15519 (setq tagsmatcher nil))
15520 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15521 (setq tagsmatcher
15522 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15524 ;; Make the todo matcher
15525 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15526 (setq todomatcher t)
15527 (setq orterms (org-split-string todomatch "|") orlist nil)
15528 (while (setq term (pop orterms))
15529 (while (string-match re term)
15530 (setq minus (and (match-end 1)
15531 (equal (match-string 1 term) "-"))
15532 kwd (match-string 2 term)
15533 re-p (equal (string-to-char kwd) ?{)
15534 term (substring term (match-end 0))
15535 mm (if re-p
15536 `(string-match ,(substring kwd 1 -1) todo)
15537 (list 'equal 'todo kwd))
15538 mm (if minus (list 'not mm) mm))
15539 (push mm todomatcher))
15540 (push (if (> (length todomatcher) 1)
15541 (cons 'and todomatcher)
15542 (car todomatcher))
15543 orlist)
15544 (setq todomatcher nil))
15545 (setq todomatcher (if (> (length orlist) 1)
15546 (cons 'or orlist) (car orlist))))
15548 ;; Return the string and lisp forms of the matcher
15549 (setq matcher (if todomatcher
15550 (list 'and tagsmatcher todomatcher)
15551 tagsmatcher))
15552 (cons match0 matcher)))
15554 (defun org-match-any-p (re list)
15555 "Does re match any element of list?"
15556 (setq list (mapcar (lambda (x) (string-match re x)) list))
15557 (delq nil list))
15559 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15560 (defvar org-tags-overlay (org-make-overlay 1 1))
15561 (org-detach-overlay org-tags-overlay)
15563 (defun org-align-tags-here (to-col)
15564 ;; Assumes that this is a headline
15565 (let ((pos (point)) (col (current-column)) tags)
15566 (beginning-of-line 1)
15567 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15568 (< pos (match-beginning 2)))
15569 (progn
15570 (setq tags (match-string 2))
15571 (goto-char (match-beginning 1))
15572 (insert " ")
15573 (delete-region (point) (1+ (match-end 0)))
15574 (backward-char 1)
15575 (move-to-column
15576 (max (1+ (current-column))
15577 (1+ col)
15578 (if (> to-col 0)
15579 to-col
15580 (- (abs to-col) (length tags))))
15582 (insert tags)
15583 (move-to-column (min (current-column) col) t))
15584 (goto-char pos))))
15586 (defun org-set-tags (&optional arg just-align)
15587 "Set the tags for the current headline.
15588 With prefix ARG, realign all tags in headings in the current buffer."
15589 (interactive "P")
15590 (let* ((re (concat "^" outline-regexp))
15591 (current (org-get-tags-string))
15592 (col (current-column))
15593 (org-setting-tags t)
15594 table current-tags inherited-tags ; computed below when needed
15595 tags p0 c0 c1 rpl)
15596 (if arg
15597 (save-excursion
15598 (goto-char (point-min))
15599 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15600 (while (re-search-forward re nil t)
15601 (org-set-tags nil t)
15602 (end-of-line 1)))
15603 (message "All tags realigned to column %d" org-tags-column))
15604 (if just-align
15605 (setq tags current)
15606 ;; Get a new set of tags from the user
15607 (save-excursion
15608 (setq table (or org-tag-alist (org-get-buffer-tags))
15609 org-last-tags-completion-table table
15610 current-tags (org-split-string current ":")
15611 inherited-tags (nreverse
15612 (nthcdr (length current-tags)
15613 (nreverse (org-get-tags-at))))
15614 tags
15615 (if (or (eq t org-use-fast-tag-selection)
15616 (and org-use-fast-tag-selection
15617 (delq nil (mapcar 'cdr table))))
15618 (org-fast-tag-selection
15619 current-tags inherited-tags table
15620 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15621 (let ((org-add-colon-after-tag-completion t))
15622 (org-trim
15623 (org-without-partial-completion
15624 (completing-read "Tags: " 'org-tags-completion-function
15625 nil nil current 'org-tags-history)))))))
15626 (while (string-match "[-+&]+" tags)
15627 ;; No boolean logic, just a list
15628 (setq tags (replace-match ":" t t tags))))
15630 (if (string-match "\\`[\t ]*\\'" tags)
15631 (setq tags "")
15632 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15633 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15635 ;; Insert new tags at the correct column
15636 (beginning-of-line 1)
15637 (cond
15638 ((and (equal current "") (equal tags "")))
15639 ((re-search-forward
15640 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15641 (point-at-eol) t)
15642 (if (equal tags "")
15643 (setq rpl "")
15644 (goto-char (match-beginning 0))
15645 (setq c0 (current-column) p0 (point)
15646 c1 (max (1+ c0) (if (> org-tags-column 0)
15647 org-tags-column
15648 (- (- org-tags-column) (length tags))))
15649 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15650 (replace-match rpl t t)
15651 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
15652 tags)
15653 (t (error "Tags alignment failed")))
15654 (move-to-column col)
15655 (unless just-align
15656 (run-hooks 'org-after-tags-change-hook)))))
15658 (defun org-change-tag-in-region (beg end tag off)
15659 "Add or remove TAG for each entry in the region.
15660 This works in the agenda, and also in an org-mode buffer."
15661 (interactive
15662 (list (region-beginning) (region-end)
15663 (let ((org-last-tags-completion-table
15664 (if (org-mode-p)
15665 (org-get-buffer-tags)
15666 (org-global-tags-completion-table))))
15667 (completing-read
15668 "Tag: " 'org-tags-completion-function nil nil nil
15669 'org-tags-history))
15670 (progn
15671 (message "[s]et or [r]emove? ")
15672 (equal (read-char-exclusive) ?r))))
15673 (if (fboundp 'deactivate-mark) (deactivate-mark))
15674 (let ((agendap (equal major-mode 'org-agenda-mode))
15675 l1 l2 m buf pos newhead (cnt 0))
15676 (goto-char end)
15677 (setq l2 (1- (org-current-line)))
15678 (goto-char beg)
15679 (setq l1 (org-current-line))
15680 (loop for l from l1 to l2 do
15681 (goto-line l)
15682 (setq m (get-text-property (point) 'org-hd-marker))
15683 (when (or (and (org-mode-p) (org-on-heading-p))
15684 (and agendap m))
15685 (setq buf (if agendap (marker-buffer m) (current-buffer))
15686 pos (if agendap m (point)))
15687 (with-current-buffer buf
15688 (save-excursion
15689 (save-restriction
15690 (goto-char pos)
15691 (setq cnt (1+ cnt))
15692 (org-toggle-tag tag (if off 'off 'on))
15693 (setq newhead (org-get-heading)))))
15694 (and agendap (org-agenda-change-all-lines newhead m))))
15695 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15697 (defun org-tags-completion-function (string predicate &optional flag)
15698 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15699 (confirm (lambda (x) (stringp (car x)))))
15700 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15701 (setq s1 (match-string 1 string)
15702 s2 (match-string 2 string))
15703 (setq s1 "" s2 string))
15704 (cond
15705 ((eq flag nil)
15706 ;; try completion
15707 (setq rtn (try-completion s2 ctable confirm))
15708 (if (stringp rtn)
15709 (setq rtn
15710 (concat s1 s2 (substring rtn (length s2))
15711 (if (and org-add-colon-after-tag-completion
15712 (assoc rtn ctable))
15713 ":" ""))))
15714 rtn)
15715 ((eq flag t)
15716 ;; all-completions
15717 (all-completions s2 ctable confirm)
15719 ((eq flag 'lambda)
15720 ;; exact match?
15721 (assoc s2 ctable)))
15724 (defun org-fast-tag-insert (kwd tags face &optional end)
15725 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15726 (insert (format "%-12s" (concat kwd ":"))
15727 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15728 (or end "")))
15730 (defun org-fast-tag-show-exit (flag)
15731 (save-excursion
15732 (goto-line 3)
15733 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15734 (replace-match ""))
15735 (when flag
15736 (end-of-line 1)
15737 (move-to-column (- (window-width) 19) t)
15738 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15740 (defun org-set-current-tags-overlay (current prefix)
15741 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15742 (if (featurep 'xemacs)
15743 (org-overlay-display org-tags-overlay (concat prefix s)
15744 'secondary-selection)
15745 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15746 (org-overlay-display org-tags-overlay (concat prefix s)))))
15748 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15749 "Fast tag selection with single keys.
15750 CURRENT is the current list of tags in the headline, INHERITED is the
15751 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15752 possibly with grouping information. TODO-TABLE is a similar table with
15753 TODO keywords, should these have keys assigned to them.
15754 If the keys are nil, a-z are automatically assigned.
15755 Returns the new tags string, or nil to not change the current settings."
15756 (let* ((fulltable (append table todo-table))
15757 (maxlen (apply 'max (mapcar
15758 (lambda (x)
15759 (if (stringp (car x)) (string-width (car x)) 0))
15760 fulltable)))
15761 (buf (current-buffer))
15762 (expert (eq org-fast-tag-selection-single-key 'expert))
15763 (buffer-tags nil)
15764 (fwidth (+ maxlen 3 1 3))
15765 (ncol (/ (- (window-width) 4) fwidth))
15766 (i-face 'org-done)
15767 (c-face 'org-todo)
15768 tg cnt e c char c1 c2 ntable tbl rtn
15769 ov-start ov-end ov-prefix
15770 (exit-after-next org-fast-tag-selection-single-key)
15771 (done-keywords org-done-keywords)
15772 groups ingroup)
15773 (save-excursion
15774 (beginning-of-line 1)
15775 (if (looking-at
15776 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15777 (setq ov-start (match-beginning 1)
15778 ov-end (match-end 1)
15779 ov-prefix "")
15780 (setq ov-start (1- (point-at-eol))
15781 ov-end (1+ ov-start))
15782 (skip-chars-forward "^\n\r")
15783 (setq ov-prefix
15784 (concat
15785 (buffer-substring (1- (point)) (point))
15786 (if (> (current-column) org-tags-column)
15788 (make-string (- org-tags-column (current-column)) ?\ ))))))
15789 (org-move-overlay org-tags-overlay ov-start ov-end)
15790 (save-window-excursion
15791 (if expert
15792 (set-buffer (get-buffer-create " *Org tags*"))
15793 (delete-other-windows)
15794 (split-window-vertically)
15795 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
15796 (erase-buffer)
15797 (org-set-local 'org-done-keywords done-keywords)
15798 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15799 (org-fast-tag-insert "Current" current c-face "\n\n")
15800 (org-fast-tag-show-exit exit-after-next)
15801 (org-set-current-tags-overlay current ov-prefix)
15802 (setq tbl fulltable char ?a cnt 0)
15803 (while (setq e (pop tbl))
15804 (cond
15805 ((equal e '(:startgroup))
15806 (push '() groups) (setq ingroup t)
15807 (when (not (= cnt 0))
15808 (setq cnt 0)
15809 (insert "\n"))
15810 (insert "{ "))
15811 ((equal e '(:endgroup))
15812 (setq ingroup nil cnt 0)
15813 (insert "}\n"))
15815 (setq tg (car e) c2 nil)
15816 (if (cdr e)
15817 (setq c (cdr e))
15818 ;; automatically assign a character.
15819 (setq c1 (string-to-char
15820 (downcase (substring
15821 tg (if (= (string-to-char tg) ?@) 1 0)))))
15822 (if (or (rassoc c1 ntable) (rassoc c1 table))
15823 (while (or (rassoc char ntable) (rassoc char table))
15824 (setq char (1+ char)))
15825 (setq c2 c1))
15826 (setq c (or c2 char)))
15827 (if ingroup (push tg (car groups)))
15828 (setq tg (org-add-props tg nil 'face
15829 (cond
15830 ((not (assoc tg table))
15831 (org-get-todo-face tg))
15832 ((member tg current) c-face)
15833 ((member tg inherited) i-face)
15834 (t nil))))
15835 (if (and (= cnt 0) (not ingroup)) (insert " "))
15836 (insert "[" c "] " tg (make-string
15837 (- fwidth 4 (length tg)) ?\ ))
15838 (push (cons tg c) ntable)
15839 (when (= (setq cnt (1+ cnt)) ncol)
15840 (insert "\n")
15841 (if ingroup (insert " "))
15842 (setq cnt 0)))))
15843 (setq ntable (nreverse ntable))
15844 (insert "\n")
15845 (goto-char (point-min))
15846 (if (and (not expert) (fboundp 'fit-window-to-buffer))
15847 (fit-window-to-buffer))
15848 (setq rtn
15849 (catch 'exit
15850 (while t
15851 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
15852 (if groups " [!] no groups" " [!]groups")
15853 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15854 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15855 (cond
15856 ((= c ?\r) (throw 'exit t))
15857 ((= c ?!)
15858 (setq groups (not groups))
15859 (goto-char (point-min))
15860 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15861 ((= c ?\C-c)
15862 (if (not expert)
15863 (org-fast-tag-show-exit
15864 (setq exit-after-next (not exit-after-next)))
15865 (setq expert nil)
15866 (delete-other-windows)
15867 (split-window-vertically)
15868 (org-switch-to-buffer-other-window " *Org tags*")
15869 (and (fboundp 'fit-window-to-buffer)
15870 (fit-window-to-buffer))))
15871 ((or (= c ?\C-g)
15872 (and (= c ?q) (not (rassoc c ntable))))
15873 (org-detach-overlay org-tags-overlay)
15874 (setq quit-flag t))
15875 ((= c ?\ )
15876 (setq current nil)
15877 (if exit-after-next (setq exit-after-next 'now)))
15878 ((= c ?\t)
15879 (condition-case nil
15880 (setq tg (completing-read
15881 "Tag: "
15882 (or buffer-tags
15883 (with-current-buffer buf
15884 (org-get-buffer-tags)))))
15885 (quit (setq tg "")))
15886 (when (string-match "\\S-" tg)
15887 (add-to-list 'buffer-tags (list tg))
15888 (if (member tg current)
15889 (setq current (delete tg current))
15890 (push tg current)))
15891 (if exit-after-next (setq exit-after-next 'now)))
15892 ((setq e (rassoc c todo-table) tg (car e))
15893 (with-current-buffer buf
15894 (save-excursion (org-todo tg)))
15895 (if exit-after-next (setq exit-after-next 'now)))
15896 ((setq e (rassoc c ntable) tg (car e))
15897 (if (member tg current)
15898 (setq current (delete tg current))
15899 (loop for g in groups do
15900 (if (member tg g)
15901 (mapc (lambda (x)
15902 (setq current (delete x current)))
15903 g)))
15904 (push tg current))
15905 (if exit-after-next (setq exit-after-next 'now))))
15907 ;; Create a sorted list
15908 (setq current
15909 (sort current
15910 (lambda (a b)
15911 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15912 (if (eq exit-after-next 'now) (throw 'exit t))
15913 (goto-char (point-min))
15914 (beginning-of-line 2)
15915 (delete-region (point) (point-at-eol))
15916 (org-fast-tag-insert "Current" current c-face)
15917 (org-set-current-tags-overlay current ov-prefix)
15918 (while (re-search-forward
15919 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
15920 (setq tg (match-string 1))
15921 (add-text-properties
15922 (match-beginning 1) (match-end 1)
15923 (list 'face
15924 (cond
15925 ((member tg current) c-face)
15926 ((member tg inherited) i-face)
15927 (t (get-text-property (match-beginning 1) 'face))))))
15928 (goto-char (point-min)))))
15929 (org-detach-overlay org-tags-overlay)
15930 (if rtn
15931 (mapconcat 'identity current ":")
15932 nil))))
15934 (defun org-get-tags-string ()
15935 "Get the TAGS string in the current headline."
15936 (unless (org-on-heading-p t)
15937 (error "Not on a heading"))
15938 (save-excursion
15939 (beginning-of-line 1)
15940 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15941 (org-match-string-no-properties 1)
15942 "")))
15944 (defun org-get-tags ()
15945 "Get the list of tags specified in the current headline."
15946 (org-split-string (org-get-tags-string) ":"))
15948 (defun org-get-buffer-tags ()
15949 "Get a table of all tags used in the buffer, for completion."
15950 (let (tags)
15951 (save-excursion
15952 (goto-char (point-min))
15953 (while (re-search-forward
15954 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
15955 (when (equal (char-after (point-at-bol 0)) ?*)
15956 (mapc (lambda (x) (add-to-list 'tags x))
15957 (org-split-string (org-match-string-no-properties 1) ":")))))
15958 (mapcar 'list tags)))
15961 ;;;; Properties
15963 ;;; Setting and retrieving properties
15965 (defconst org-special-properties
15966 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
15967 "TIMESTAMP" "TIMESTAMP_IA")
15968 "The special properties valid in Org-mode.
15970 These are properties that are not defined in the property drawer,
15971 but in some other way.")
15973 (defconst org-default-properties
15974 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
15975 "LOCATION" "LOGGING" "COLUMNS")
15976 "Some properties that are used by Org-mode for various purposes.
15977 Being in this list makes sure that they are offered for completion.")
15979 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15980 "Regular expression matching the first line of a property drawer.")
15982 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15983 "Regular expression matching the first line of a property drawer.")
15985 (defun org-property-action ()
15986 "Do an action on properties."
15987 (interactive)
15988 (let (c)
15989 (org-at-property-p)
15990 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15991 (setq c (read-char-exclusive))
15992 (cond
15993 ((equal c ?s)
15994 (call-interactively 'org-set-property))
15995 ((equal c ?d)
15996 (call-interactively 'org-delete-property))
15997 ((equal c ?D)
15998 (call-interactively 'org-delete-property-globally))
15999 ((equal c ?c)
16000 (call-interactively 'org-compute-property-at-point))
16001 (t (error "No such property action %c" c)))))
16003 (defun org-at-property-p ()
16004 "Is the cursor in a property line?"
16005 ;; FIXME: Does not check if we are actually in the drawer.
16006 ;; FIXME: also returns true on any drawers.....
16007 ;; This is used by C-c C-c for property action.
16008 (save-excursion
16009 (beginning-of-line 1)
16010 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
16012 (defmacro org-with-point-at (pom &rest body)
16013 "Move to buffer and point of point-or-marker POM for the duration of BODY."
16014 (declare (indent 1) (debug t))
16015 `(save-excursion
16016 (if (markerp pom) (set-buffer (marker-buffer pom)))
16017 (save-excursion
16018 (goto-char (or pom (point)))
16019 ,@body)))
16021 (defun org-get-property-block (&optional beg end force)
16022 "Return the (beg . end) range of the body of the property drawer.
16023 BEG and END can be beginning and end of subtree, if not given
16024 they will be found.
16025 If the drawer does not exist and FORCE is non-nil, create the drawer."
16026 (catch 'exit
16027 (save-excursion
16028 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
16029 (end (or end (progn (outline-next-heading) (point)))))
16030 (goto-char beg)
16031 (if (re-search-forward org-property-start-re end t)
16032 (setq beg (1+ (match-end 0)))
16033 (if force
16034 (save-excursion
16035 (org-insert-property-drawer)
16036 (setq end (progn (outline-next-heading) (point))))
16037 (throw 'exit nil))
16038 (goto-char beg)
16039 (if (re-search-forward org-property-start-re end t)
16040 (setq beg (1+ (match-end 0)))))
16041 (if (re-search-forward org-property-end-re end t)
16042 (setq end (match-beginning 0))
16043 (or force (throw 'exit nil))
16044 (goto-char beg)
16045 (setq end beg)
16046 (org-indent-line-function)
16047 (insert ":END:\n"))
16048 (cons beg end)))))
16050 (defun org-entry-properties (&optional pom which)
16051 "Get all properties of the entry at point-or-marker POM.
16052 This includes the TODO keyword, the tags, time strings for deadline,
16053 scheduled, and clocking, and any additional properties defined in the
16054 entry. The return value is an alist, keys may occur multiple times
16055 if the property key was used several times.
16056 POM may also be nil, in which case the current entry is used.
16057 If WHICH is nil or `all', get all properties. If WHICH is
16058 `special' or `standard', only get that subclass."
16059 (setq which (or which 'all))
16060 (org-with-point-at pom
16061 (let ((clockstr (substring org-clock-string 0 -1))
16062 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
16063 beg end range props sum-props key value string clocksum)
16064 (save-excursion
16065 (when (condition-case nil (org-back-to-heading t) (error nil))
16066 (setq beg (point))
16067 (setq sum-props (get-text-property (point) 'org-summaries))
16068 (setq clocksum (get-text-property (point) :org-clock-minutes))
16069 (outline-next-heading)
16070 (setq end (point))
16071 (when (memq which '(all special))
16072 ;; Get the special properties, like TODO and tags
16073 (goto-char beg)
16074 (when (and (looking-at org-todo-line-regexp) (match-end 2))
16075 (push (cons "TODO" (org-match-string-no-properties 2)) props))
16076 (when (looking-at org-priority-regexp)
16077 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
16078 (when (and (setq value (org-get-tags-string))
16079 (string-match "\\S-" value))
16080 (push (cons "TAGS" value) props))
16081 (when (setq value (org-get-tags-at))
16082 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
16083 props))
16084 (while (re-search-forward org-maybe-keyword-time-regexp end t)
16085 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
16086 string (if (equal key clockstr)
16087 (org-no-properties
16088 (org-trim
16089 (buffer-substring
16090 (match-beginning 3) (goto-char (point-at-eol)))))
16091 (substring (org-match-string-no-properties 3) 1 -1)))
16092 (unless key
16093 (if (= (char-after (match-beginning 3)) ?\[)
16094 (setq key "TIMESTAMP_IA")
16095 (setq key "TIMESTAMP")))
16096 (when (or (equal key clockstr) (not (assoc key props)))
16097 (push (cons key string) props)))
16101 (when (memq which '(all standard))
16102 ;; Get the standard properties, like :PORP: ...
16103 (setq range (org-get-property-block beg end))
16104 (when range
16105 (goto-char (car range))
16106 (while (re-search-forward
16107 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
16108 (cdr range) t)
16109 (setq key (org-match-string-no-properties 1)
16110 value (org-trim (or (org-match-string-no-properties 2) "")))
16111 (unless (member key excluded)
16112 (push (cons key (or value "")) props)))))
16113 (if clocksum
16114 (push (cons "CLOCKSUM"
16115 (org-column-number-to-string (/ (float clocksum) 60.)
16116 'add_times))
16117 props))
16118 (append sum-props (nreverse props)))))))
16120 (defun org-entry-get (pom property &optional inherit)
16121 "Get value of PROPERTY for entry at point-or-marker POM.
16122 If INHERIT is non-nil and the entry does not have the property,
16123 then also check higher levels of the hierarchy.
16124 If the property is present but empty, the return value is the empty string.
16125 If the property is not present at all, nil is returned."
16126 (org-with-point-at pom
16127 (if inherit
16128 (org-entry-get-with-inheritance property)
16129 (if (member property org-special-properties)
16130 ;; We need a special property. Use brute force, get all properties.
16131 (cdr (assoc property (org-entry-properties nil 'special)))
16132 (let ((range (org-get-property-block)))
16133 (if (and range
16134 (goto-char (car range))
16135 (re-search-forward
16136 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
16137 (cdr range) t))
16138 ;; Found the property, return it.
16139 (if (match-end 1)
16140 (org-match-string-no-properties 1)
16141 "")))))))
16143 (defun org-entry-delete (pom property)
16144 "Delete the property PROPERTY from entry at point-or-marker POM."
16145 (org-with-point-at pom
16146 (if (member property org-special-properties)
16147 nil ; cannot delete these properties.
16148 (let ((range (org-get-property-block)))
16149 (if (and range
16150 (goto-char (car range))
16151 (re-search-forward
16152 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
16153 (cdr range) t))
16154 (progn
16155 (delete-region (match-beginning 0) (1+ (point-at-eol)))
16157 nil)))))
16159 ;; Multi-values properties are properties that contain multiple values
16160 ;; These values are assumed to be single words, separated by whitespace.
16161 (defun org-entry-add-to-multivalued-property (pom property value)
16162 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16163 (let* ((old (org-entry-get pom property))
16164 (values (and old (org-split-string old "[ \t]"))))
16165 (unless (member value values)
16166 (setq values (cons value values))
16167 (org-entry-put pom property
16168 (mapconcat 'identity values " ")))))
16170 (defun org-entry-remove-from-multivalued-property (pom property value)
16171 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16172 (let* ((old (org-entry-get pom property))
16173 (values (and old (org-split-string old "[ \t]"))))
16174 (when (member value values)
16175 (setq values (delete value values))
16176 (org-entry-put pom property
16177 (mapconcat 'identity values " ")))))
16179 (defun org-entry-member-in-multivalued-property (pom property value)
16180 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16181 (let* ((old (org-entry-get pom property))
16182 (values (and old (org-split-string old "[ \t]"))))
16183 (member value values)))
16185 (defvar org-entry-property-inherited-from (make-marker))
16187 (defun org-entry-get-with-inheritance (property)
16188 "Get entry property, and search higher levels if not present."
16189 (let (tmp)
16190 (save-excursion
16191 (save-restriction
16192 (widen)
16193 (catch 'ex
16194 (while t
16195 (when (setq tmp (org-entry-get nil property))
16196 (org-back-to-heading t)
16197 (move-marker org-entry-property-inherited-from (point))
16198 (throw 'ex tmp))
16199 (or (org-up-heading-safe) (throw 'ex nil)))))
16200 (or tmp (cdr (assoc property org-local-properties))
16201 (cdr (assoc property org-global-properties))))))
16203 (defun org-entry-put (pom property value)
16204 "Set PROPERTY to VALUE for entry at point-or-marker POM."
16205 (org-with-point-at pom
16206 (org-back-to-heading t)
16207 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
16208 range)
16209 (cond
16210 ((equal property "TODO")
16211 (when (and (stringp value) (string-match "\\S-" value)
16212 (not (member value org-todo-keywords-1)))
16213 (error "\"%s\" is not a valid TODO state" value))
16214 (if (or (not value)
16215 (not (string-match "\\S-" value)))
16216 (setq value 'none))
16217 (org-todo value)
16218 (org-set-tags nil 'align))
16219 ((equal property "PRIORITY")
16220 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
16221 (string-to-char value) ?\ ))
16222 (org-set-tags nil 'align))
16223 ((equal property "SCHEDULED")
16224 (if (re-search-forward org-scheduled-time-regexp end t)
16225 (cond
16226 ((eq value 'earlier) (org-timestamp-change -1 'day))
16227 ((eq value 'later) (org-timestamp-change 1 'day))
16228 (t (call-interactively 'org-schedule)))
16229 (call-interactively 'org-schedule)))
16230 ((equal property "DEADLINE")
16231 (if (re-search-forward org-deadline-time-regexp end t)
16232 (cond
16233 ((eq value 'earlier) (org-timestamp-change -1 'day))
16234 ((eq value 'later) (org-timestamp-change 1 'day))
16235 (t (call-interactively 'org-deadline)))
16236 (call-interactively 'org-deadline)))
16237 ((member property org-special-properties)
16238 (error "The %s property can not yet be set with `org-entry-put'"
16239 property))
16240 (t ; a non-special property
16241 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
16242 (setq range (org-get-property-block beg end 'force))
16243 (goto-char (car range))
16244 (if (re-search-forward
16245 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
16246 (progn
16247 (delete-region (match-beginning 1) (match-end 1))
16248 (goto-char (match-beginning 1)))
16249 (goto-char (cdr range))
16250 (insert "\n")
16251 (backward-char 1)
16252 (org-indent-line-function)
16253 (insert ":" property ":"))
16254 (and value (insert " " value))
16255 (org-indent-line-function)))))))
16257 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
16258 "Get all property keys in the current buffer.
16259 With INCLUDE-SPECIALS, also list the special properties that relect things
16260 like tags and TODO state.
16261 With INCLUDE-DEFAULTS, also include properties that has special meaning
16262 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
16263 With INCLUDE-COLUMNS, also include property names given in COLUMN
16264 formats in the current buffer."
16265 (let (rtn range cfmt cols s p)
16266 (save-excursion
16267 (save-restriction
16268 (widen)
16269 (goto-char (point-min))
16270 (while (re-search-forward org-property-start-re nil t)
16271 (setq range (org-get-property-block))
16272 (goto-char (car range))
16273 (while (re-search-forward
16274 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
16275 (cdr range) t)
16276 (add-to-list 'rtn (org-match-string-no-properties 1)))
16277 (outline-next-heading))))
16279 (when include-specials
16280 (setq rtn (append org-special-properties rtn)))
16282 (when include-defaults
16283 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
16285 (when include-columns
16286 (save-excursion
16287 (save-restriction
16288 (widen)
16289 (goto-char (point-min))
16290 (while (re-search-forward
16291 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
16292 nil t)
16293 (setq cfmt (match-string 2) s 0)
16294 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
16295 cfmt s)
16296 (setq s (match-end 0)
16297 p (match-string 1 cfmt))
16298 (unless (or (equal p "ITEM")
16299 (member p org-special-properties))
16300 (add-to-list 'rtn (match-string 1 cfmt))))))))
16302 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
16304 (defun org-property-values (key)
16305 "Return a list of all values of property KEY."
16306 (save-excursion
16307 (save-restriction
16308 (widen)
16309 (goto-char (point-min))
16310 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
16311 values)
16312 (while (re-search-forward re nil t)
16313 (add-to-list 'values (org-trim (match-string 1))))
16314 (delete "" values)))))
16316 (defun org-insert-property-drawer ()
16317 "Insert a property drawer into the current entry."
16318 (interactive)
16319 (org-back-to-heading t)
16320 (looking-at outline-regexp)
16321 (let ((indent (- (match-end 0)(match-beginning 0)))
16322 (beg (point))
16323 (re (concat "^[ \t]*" org-keyword-time-regexp))
16324 end hiddenp)
16325 (outline-next-heading)
16326 (setq end (point))
16327 (goto-char beg)
16328 (while (re-search-forward re end t))
16329 (setq hiddenp (org-invisible-p))
16330 (end-of-line 1)
16331 (and (equal (char-after) ?\n) (forward-char 1))
16332 (org-skip-over-state-notes)
16333 (skip-chars-backward " \t\n\r")
16334 (if (eq (char-before) ?*) (forward-char 1))
16335 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
16336 (beginning-of-line 0)
16337 (indent-to-column indent)
16338 (beginning-of-line 2)
16339 (indent-to-column indent)
16340 (beginning-of-line 0)
16341 (if hiddenp
16342 (save-excursion
16343 (org-back-to-heading t)
16344 (hide-entry))
16345 (org-flag-drawer t))))
16347 (defun org-set-property (property value)
16348 "In the current entry, set PROPERTY to VALUE.
16349 When called interactively, this will prompt for a property name, offering
16350 completion on existing and default properties. And then it will prompt
16351 for a value, offering competion either on allowed values (via an inherited
16352 xxx_ALL property) or on existing values in other instances of this property
16353 in the current file."
16354 (interactive
16355 (let* ((prop (completing-read
16356 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
16357 (cur (org-entry-get nil prop))
16358 (allowed (org-property-get-allowed-values nil prop 'table))
16359 (existing (mapcar 'list (org-property-values prop)))
16360 (val (if allowed
16361 (completing-read "Value: " allowed nil 'req-match)
16362 (completing-read
16363 (concat "Value" (if (and cur (string-match "\\S-" cur))
16364 (concat "[" cur "]") "")
16365 ": ")
16366 existing nil nil "" nil cur))))
16367 (list prop (if (equal val "") cur val))))
16368 (unless (equal (org-entry-get nil property) value)
16369 (org-entry-put nil property value)))
16371 (defun org-delete-property (property)
16372 "In the current entry, delete PROPERTY."
16373 (interactive
16374 (let* ((prop (completing-read
16375 "Property: " (org-entry-properties nil 'standard))))
16376 (list prop)))
16377 (message "Property %s %s" property
16378 (if (org-entry-delete nil property)
16379 "deleted"
16380 "was not present in the entry")))
16382 (defun org-delete-property-globally (property)
16383 "Remove PROPERTY globally, from all entries."
16384 (interactive
16385 (let* ((prop (completing-read
16386 "Globally remove property: "
16387 (mapcar 'list (org-buffer-property-keys)))))
16388 (list prop)))
16389 (save-excursion
16390 (save-restriction
16391 (widen)
16392 (goto-char (point-min))
16393 (let ((cnt 0))
16394 (while (re-search-forward
16395 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16396 nil t)
16397 (setq cnt (1+ cnt))
16398 (replace-match ""))
16399 (message "Property \"%s\" removed from %d entries" property cnt)))))
16401 (defvar org-columns-current-fmt-compiled) ; defined below
16403 (defun org-compute-property-at-point ()
16404 "Compute the property at point.
16405 This looks for an enclosing column format, extracts the operator and
16406 then applies it to the proerty in the column format's scope."
16407 (interactive)
16408 (unless (org-at-property-p)
16409 (error "Not at a property"))
16410 (let ((prop (org-match-string-no-properties 2)))
16411 (org-columns-get-format-and-top-level)
16412 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16413 (error "No operator defined for property %s" prop))
16414 (org-columns-compute prop)))
16416 (defun org-property-get-allowed-values (pom property &optional table)
16417 "Get allowed values for the property PROPERTY.
16418 When TABLE is non-nil, return an alist that can directly be used for
16419 completion."
16420 (let (vals)
16421 (cond
16422 ((equal property "TODO")
16423 (setq vals (org-with-point-at pom
16424 (append org-todo-keywords-1 '("")))))
16425 ((equal property "PRIORITY")
16426 (let ((n org-lowest-priority))
16427 (while (>= n org-highest-priority)
16428 (push (char-to-string n) vals)
16429 (setq n (1- n)))))
16430 ((member property org-special-properties))
16432 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16434 (when (and vals (string-match "\\S-" vals))
16435 (setq vals (car (read-from-string (concat "(" vals ")"))))
16436 (setq vals (mapcar (lambda (x)
16437 (cond ((stringp x) x)
16438 ((numberp x) (number-to-string x))
16439 ((symbolp x) (symbol-name x))
16440 (t "???")))
16441 vals)))))
16442 (if table (mapcar 'list vals) vals)))
16444 (defun org-property-previous-allowed-value (&optional previous)
16445 "Switch to the next allowed value for this property."
16446 (interactive)
16447 (org-property-next-allowed-value t))
16449 (defun org-property-next-allowed-value (&optional previous)
16450 "Switch to the next allowed value for this property."
16451 (interactive)
16452 (unless (org-at-property-p)
16453 (error "Not at a property"))
16454 (let* ((key (match-string 2))
16455 (value (match-string 3))
16456 (allowed (or (org-property-get-allowed-values (point) key)
16457 (and (member value '("[ ]" "[-]" "[X]"))
16458 '("[ ]" "[X]"))))
16459 nval)
16460 (unless allowed
16461 (error "Allowed values for this property have not been defined"))
16462 (if previous (setq allowed (reverse allowed)))
16463 (if (member value allowed)
16464 (setq nval (car (cdr (member value allowed)))))
16465 (setq nval (or nval (car allowed)))
16466 (if (equal nval value)
16467 (error "Only one allowed value for this property"))
16468 (org-at-property-p)
16469 (replace-match (concat " :" key ": " nval) t t)
16470 (org-indent-line-function)
16471 (beginning-of-line 1)
16472 (skip-chars-forward " \t")))
16474 (defun org-find-entry-with-id (ident)
16475 "Locate the entry that contains the ID property with exact value IDENT.
16476 IDENT can be a string, a symbol or a number, this function will search for
16477 the string representation of it.
16478 Return the position where this entry starts, or nil if there is no such entry."
16479 (let ((id (cond
16480 ((stringp ident) ident)
16481 ((symbol-name ident) (symbol-name ident))
16482 ((numberp ident) (number-to-string ident))
16483 (t (error "IDENT %s must be a string, symbol or number" ident))))
16484 (case-fold-search nil))
16485 (save-excursion
16486 (save-restriction
16487 (goto-char (point-min))
16488 (when (re-search-forward
16489 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16490 nil t)
16491 (org-back-to-heading)
16492 (point))))))
16494 ;;; Column View
16496 (defvar org-columns-overlays nil
16497 "Holds the list of current column overlays.")
16499 (defvar org-columns-current-fmt nil
16500 "Local variable, holds the currently active column format.")
16501 (defvar org-columns-current-fmt-compiled nil
16502 "Local variable, holds the currently active column format.
16503 This is the compiled version of the format.")
16504 (defvar org-columns-current-widths nil
16505 "Loval variable, holds the currently widths of fields.")
16506 (defvar org-columns-current-maxwidths nil
16507 "Loval variable, holds the currently active maximum column widths.")
16508 (defvar org-columns-begin-marker (make-marker)
16509 "Points to the position where last a column creation command was called.")
16510 (defvar org-columns-top-level-marker (make-marker)
16511 "Points to the position where current columns region starts.")
16513 (defvar org-columns-map (make-sparse-keymap)
16514 "The keymap valid in column display.")
16516 (defun org-columns-content ()
16517 "Switch to contents view while in columns view."
16518 (interactive)
16519 (org-overview)
16520 (org-content))
16522 (org-defkey org-columns-map "c" 'org-columns-content)
16523 (org-defkey org-columns-map "o" 'org-overview)
16524 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16525 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16526 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16527 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16528 (org-defkey org-columns-map "v" 'org-columns-show-value)
16529 (org-defkey org-columns-map "q" 'org-columns-quit)
16530 (org-defkey org-columns-map "r" 'org-columns-redo)
16531 (org-defkey org-columns-map "g" 'org-columns-redo)
16532 (org-defkey org-columns-map [left] 'backward-char)
16533 (org-defkey org-columns-map "\M-b" 'backward-char)
16534 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16535 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16536 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16537 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16538 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16539 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16540 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16541 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16542 (org-defkey org-columns-map "<" 'org-columns-narrow)
16543 (org-defkey org-columns-map ">" 'org-columns-widen)
16544 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16545 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16546 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16547 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16549 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16550 '("Column"
16551 ["Edit property" org-columns-edit-value t]
16552 ["Next allowed value" org-columns-next-allowed-value t]
16553 ["Previous allowed value" org-columns-previous-allowed-value t]
16554 ["Show full value" org-columns-show-value t]
16555 ["Edit allowed values" org-columns-edit-allowed t]
16556 "--"
16557 ["Edit column attributes" org-columns-edit-attributes t]
16558 ["Increase column width" org-columns-widen t]
16559 ["Decrease column width" org-columns-narrow t]
16560 "--"
16561 ["Move column right" org-columns-move-right t]
16562 ["Move column left" org-columns-move-left t]
16563 ["Add column" org-columns-new t]
16564 ["Delete column" org-columns-delete t]
16565 "--"
16566 ["CONTENTS" org-columns-content t]
16567 ["OVERVIEW" org-overview t]
16568 ["Refresh columns display" org-columns-redo t]
16569 "--"
16570 ["Open link" org-columns-open-link t]
16571 "--"
16572 ["Quit" org-columns-quit t]))
16574 (defun org-columns-new-overlay (beg end &optional string face)
16575 "Create a new column overlay and add it to the list."
16576 (let ((ov (org-make-overlay beg end)))
16577 (org-overlay-put ov 'face (or face 'secondary-selection))
16578 (org-overlay-display ov string face)
16579 (push ov org-columns-overlays)
16580 ov))
16582 (defun org-columns-display-here (&optional props)
16583 "Overlay the current line with column display."
16584 (interactive)
16585 (let* ((fmt org-columns-current-fmt-compiled)
16586 (beg (point-at-bol))
16587 (level-face (save-excursion
16588 (beginning-of-line 1)
16589 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16590 (org-get-level-face 2))))
16591 (color (list :foreground
16592 (face-attribute (or level-face 'default) :foreground)))
16593 props pom property ass width f string ov column val modval)
16594 ;; Check if the entry is in another buffer.
16595 (unless props
16596 (if (eq major-mode 'org-agenda-mode)
16597 (setq pom (or (get-text-property (point) 'org-hd-marker)
16598 (get-text-property (point) 'org-marker))
16599 props (if pom (org-entry-properties pom) nil))
16600 (setq props (org-entry-properties nil))))
16601 ;; Walk the format
16602 (while (setq column (pop fmt))
16603 (setq property (car column)
16604 ass (if (equal property "ITEM")
16605 (cons "ITEM"
16606 (save-match-data
16607 (org-no-properties
16608 (org-remove-tabs
16609 (buffer-substring-no-properties
16610 (point-at-bol) (point-at-eol))))))
16611 (assoc property props))
16612 width (or (cdr (assoc property org-columns-current-maxwidths))
16613 (nth 2 column)
16614 (length property))
16615 f (format "%%-%d.%ds | " width width)
16616 val (or (cdr ass) "")
16617 modval (if (equal property "ITEM")
16618 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16619 string (format f (or modval val)))
16620 ;; Create the overlay
16621 (org-unmodified
16622 (setq ov (org-columns-new-overlay
16623 beg (setq beg (1+ beg)) string
16624 (list color 'org-column)))
16625 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16626 (org-overlay-put ov 'keymap org-columns-map)
16627 (org-overlay-put ov 'org-columns-key property)
16628 (org-overlay-put ov 'org-columns-value (cdr ass))
16629 (org-overlay-put ov 'org-columns-value-modified modval)
16630 (org-overlay-put ov 'org-columns-pom pom)
16631 (org-overlay-put ov 'org-columns-format f))
16632 (if (or (not (char-after beg))
16633 (equal (char-after beg) ?\n))
16634 (let ((inhibit-read-only t))
16635 (save-excursion
16636 (goto-char beg)
16637 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16638 ;; Make the rest of the line disappear.
16639 (org-unmodified
16640 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16641 (org-overlay-put ov 'invisible t)
16642 (org-overlay-put ov 'keymap org-columns-map)
16643 (org-overlay-put ov 'intangible t)
16644 (push ov org-columns-overlays)
16645 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16646 (org-overlay-put ov 'keymap org-columns-map)
16647 (push ov org-columns-overlays)
16648 (let ((inhibit-read-only t))
16649 (put-text-property (max (point-min) (1- (point-at-bol)))
16650 (min (point-max) (1+ (point-at-eol)))
16651 'read-only "Type `e' to edit property")))))
16653 (defvar org-previous-header-line-format nil
16654 "The header line format before column view was turned on.")
16655 (defvar org-columns-inhibit-recalculation nil
16656 "Inhibit recomputing of columns on column view startup.")
16659 (defvar header-line-format)
16660 (defun org-columns-display-here-title ()
16661 "Overlay the newline before the current line with the table title."
16662 (interactive)
16663 (let ((fmt org-columns-current-fmt-compiled)
16664 string (title "")
16665 property width f column str widths)
16666 (while (setq column (pop fmt))
16667 (setq property (car column)
16668 str (or (nth 1 column) property)
16669 width (or (cdr (assoc property org-columns-current-maxwidths))
16670 (nth 2 column)
16671 (length str))
16672 widths (push width widths)
16673 f (format "%%-%d.%ds | " width width)
16674 string (format f str)
16675 title (concat title string)))
16676 (setq title (concat
16677 (org-add-props " " nil 'display '(space :align-to 0))
16678 (org-add-props title nil 'face '(:weight bold :underline t))))
16679 (org-set-local 'org-previous-header-line-format header-line-format)
16680 (org-set-local 'org-columns-current-widths (nreverse widths))
16681 (setq header-line-format title)))
16683 (defun org-columns-remove-overlays ()
16684 "Remove all currently active column overlays."
16685 (interactive)
16686 (when (marker-buffer org-columns-begin-marker)
16687 (with-current-buffer (marker-buffer org-columns-begin-marker)
16688 (when (local-variable-p 'org-previous-header-line-format)
16689 (setq header-line-format org-previous-header-line-format)
16690 (kill-local-variable 'org-previous-header-line-format))
16691 (move-marker org-columns-begin-marker nil)
16692 (move-marker org-columns-top-level-marker nil)
16693 (org-unmodified
16694 (mapc 'org-delete-overlay org-columns-overlays)
16695 (setq org-columns-overlays nil)
16696 (let ((inhibit-read-only t))
16697 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16699 (defun org-columns-cleanup-item (item fmt)
16700 "Remove from ITEM what is a column in the format FMT."
16701 (if (not org-complex-heading-regexp)
16702 item
16703 (when (string-match org-complex-heading-regexp item)
16704 (concat
16705 (org-add-props (concat (match-string 1 item) " ") nil
16706 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16707 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16708 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16709 " " (match-string 4 item)
16710 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16712 (defun org-columns-show-value ()
16713 "Show the full value of the property."
16714 (interactive)
16715 (let ((value (get-char-property (point) 'org-columns-value)))
16716 (message "Value is: %s" (or value ""))))
16718 (defun org-columns-quit ()
16719 "Remove the column overlays and in this way exit column editing."
16720 (interactive)
16721 (org-unmodified
16722 (org-columns-remove-overlays)
16723 (let ((inhibit-read-only t))
16724 (remove-text-properties (point-min) (point-max) '(read-only t))))
16725 (when (eq major-mode 'org-agenda-mode)
16726 (message
16727 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16729 (defun org-columns-check-computed ()
16730 "Check if this column value is computed.
16731 If yes, throw an error indicating that changing it does not make sense."
16732 (let ((val (get-char-property (point) 'org-columns-value)))
16733 (when (and (stringp val)
16734 (get-char-property 0 'org-computed val))
16735 (error "This value is computed from the entry's children"))))
16737 (defun org-columns-todo (&optional arg)
16738 "Change the TODO state during column view."
16739 (interactive "P")
16740 (org-columns-edit-value "TODO"))
16742 (defun org-columns-set-tags-or-toggle (&optional arg)
16743 "Toggle checkbox at point, or set tags for current headline."
16744 (interactive "P")
16745 (if (string-match "\\`\\[[ xX-]\\]\\'"
16746 (get-char-property (point) 'org-columns-value))
16747 (org-columns-next-allowed-value)
16748 (org-columns-edit-value "TAGS")))
16750 (defun org-columns-edit-value (&optional key)
16751 "Edit the value of the property at point in column view.
16752 Where possible, use the standard interface for changing this line."
16753 (interactive)
16754 (org-columns-check-computed)
16755 (let* ((external-key key)
16756 (col (current-column))
16757 (key (or key (get-char-property (point) 'org-columns-key)))
16758 (value (get-char-property (point) 'org-columns-value))
16759 (bol (point-at-bol)) (eol (point-at-eol))
16760 (pom (or (get-text-property bol 'org-hd-marker)
16761 (point))) ; keep despite of compiler waring
16762 (line-overlays
16763 (delq nil (mapcar (lambda (x)
16764 (and (eq (overlay-buffer x) (current-buffer))
16765 (>= (overlay-start x) bol)
16766 (<= (overlay-start x) eol)
16768 org-columns-overlays)))
16769 nval eval allowed)
16770 (cond
16771 ((equal key "CLOCKSUM")
16772 (error "This special column cannot be edited"))
16773 ((equal key "ITEM")
16774 (setq eval '(org-with-point-at pom
16775 (org-edit-headline))))
16776 ((equal key "TODO")
16777 (setq eval '(org-with-point-at pom
16778 (let ((current-prefix-arg
16779 (if external-key current-prefix-arg '(4))))
16780 (call-interactively 'org-todo)))))
16781 ((equal key "PRIORITY")
16782 (setq eval '(org-with-point-at pom
16783 (call-interactively 'org-priority))))
16784 ((equal key "TAGS")
16785 (setq eval '(org-with-point-at pom
16786 (let ((org-fast-tag-selection-single-key
16787 (if (eq org-fast-tag-selection-single-key 'expert)
16788 t org-fast-tag-selection-single-key)))
16789 (call-interactively 'org-set-tags)))))
16790 ((equal key "DEADLINE")
16791 (setq eval '(org-with-point-at pom
16792 (call-interactively 'org-deadline))))
16793 ((equal key "SCHEDULED")
16794 (setq eval '(org-with-point-at pom
16795 (call-interactively 'org-schedule))))
16797 (setq allowed (org-property-get-allowed-values pom key 'table))
16798 (if allowed
16799 (setq nval (completing-read "Value: " allowed nil t))
16800 (setq nval (read-string "Edit: " value)))
16801 (setq nval (org-trim nval))
16802 (when (not (equal nval value))
16803 (setq eval '(org-entry-put pom key nval)))))
16804 (when eval
16805 (let ((inhibit-read-only t))
16806 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
16807 (unwind-protect
16808 (progn
16809 (setq org-columns-overlays
16810 (org-delete-all line-overlays org-columns-overlays))
16811 (mapc 'org-delete-overlay line-overlays)
16812 (org-columns-eval eval))
16813 (org-columns-display-here))))
16814 (move-to-column col)
16815 (if (and (org-mode-p)
16816 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16817 (org-columns-update key))))
16819 (defun org-edit-headline () ; FIXME: this is not columns specific
16820 "Edit the current headline, the part without TODO keyword, TAGS."
16821 (org-back-to-heading)
16822 (when (looking-at org-todo-line-regexp)
16823 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
16824 (txt (match-string 3))
16825 (post "")
16826 txt2)
16827 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
16828 (setq post (match-string 0 txt)
16829 txt (substring txt 0 (match-beginning 0))))
16830 (setq txt2 (read-string "Edit: " txt))
16831 (when (not (equal txt txt2))
16832 (beginning-of-line 1)
16833 (insert pre txt2 post)
16834 (delete-region (point) (point-at-eol))
16835 (org-set-tags nil t)))))
16837 (defun org-columns-edit-allowed ()
16838 "Edit the list of allowed values for the current property."
16839 (interactive)
16840 (let* ((key (get-char-property (point) 'org-columns-key))
16841 (key1 (concat key "_ALL"))
16842 (allowed (org-entry-get (point) key1 t))
16843 nval)
16844 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
16845 (setq nval (read-string "Allowed: " allowed))
16846 (org-entry-put
16847 (cond ((marker-position org-entry-property-inherited-from)
16848 org-entry-property-inherited-from)
16849 ((marker-position org-columns-top-level-marker)
16850 org-columns-top-level-marker))
16851 key1 nval)))
16853 (defmacro org-no-warnings (&rest body)
16854 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
16856 (defun org-columns-eval (form)
16857 (let (hidep)
16858 (save-excursion
16859 (beginning-of-line 1)
16860 ;; `next-line' is needed here, because it skips invisible line.
16861 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
16862 (setq hidep (org-on-heading-p 1)))
16863 (eval form)
16864 (and hidep (hide-entry))))
16866 (defun org-columns-previous-allowed-value ()
16867 "Switch to the previous allowed value for this column."
16868 (interactive)
16869 (org-columns-next-allowed-value t))
16871 (defun org-columns-next-allowed-value (&optional previous)
16872 "Switch to the next allowed value for this column."
16873 (interactive)
16874 (org-columns-check-computed)
16875 (let* ((col (current-column))
16876 (key (get-char-property (point) 'org-columns-key))
16877 (value (get-char-property (point) 'org-columns-value))
16878 (bol (point-at-bol)) (eol (point-at-eol))
16879 (pom (or (get-text-property bol 'org-hd-marker)
16880 (point))) ; keep despite of compiler waring
16881 (line-overlays
16882 (delq nil (mapcar (lambda (x)
16883 (and (eq (overlay-buffer x) (current-buffer))
16884 (>= (overlay-start x) bol)
16885 (<= (overlay-start x) eol)
16887 org-columns-overlays)))
16888 (allowed (or (org-property-get-allowed-values pom key)
16889 (and (memq
16890 (nth 4 (assoc key org-columns-current-fmt-compiled))
16891 '(checkbox checkbox-n-of-m checkbox-percent))
16892 '("[ ]" "[X]"))))
16893 nval)
16894 (when (equal key "ITEM")
16895 (error "Cannot edit item headline from here"))
16896 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
16897 (error "Allowed values for this property have not been defined"))
16898 (if (member key '("SCHEDULED" "DEADLINE"))
16899 (setq nval (if previous 'earlier 'later))
16900 (if previous (setq allowed (reverse allowed)))
16901 (if (member value allowed)
16902 (setq nval (car (cdr (member value allowed)))))
16903 (setq nval (or nval (car allowed)))
16904 (if (equal nval value)
16905 (error "Only one allowed value for this property")))
16906 (let ((inhibit-read-only t))
16907 (remove-text-properties (1- bol) eol '(read-only t))
16908 (unwind-protect
16909 (progn
16910 (setq org-columns-overlays
16911 (org-delete-all line-overlays org-columns-overlays))
16912 (mapc 'org-delete-overlay line-overlays)
16913 (org-columns-eval '(org-entry-put pom key nval)))
16914 (org-columns-display-here)))
16915 (move-to-column col)
16916 (if (and (org-mode-p)
16917 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16918 (org-columns-update key))))
16920 (defun org-verify-version (task)
16921 (cond
16922 ((eq task 'columns)
16923 (if (or (featurep 'xemacs)
16924 (< emacs-major-version 22))
16925 (error "Emacs 22 is required for the columns feature")))))
16927 (defun org-columns-open-link (&optional arg)
16928 (interactive "P")
16929 (let ((value (get-char-property (point) 'org-columns-value)))
16930 (org-open-link-from-string value arg)))
16932 (defun org-open-link-from-string (s &optional arg)
16933 "Open a link in the string S, as if it was in Org-mode."
16934 (interactive)
16935 (with-temp-buffer
16936 (let ((org-inhibit-startup t))
16937 (org-mode)
16938 (insert s)
16939 (goto-char (point-min))
16940 (org-open-at-point arg))))
16942 (defun org-columns-get-format-and-top-level ()
16943 (let (fmt)
16944 (when (condition-case nil (org-back-to-heading) (error nil))
16945 (move-marker org-entry-property-inherited-from nil)
16946 (setq fmt (org-entry-get nil "COLUMNS" t)))
16947 (setq fmt (or fmt org-columns-default-format))
16948 (org-set-local 'org-columns-current-fmt fmt)
16949 (org-columns-compile-format fmt)
16950 (if (marker-position org-entry-property-inherited-from)
16951 (move-marker org-columns-top-level-marker
16952 org-entry-property-inherited-from)
16953 (move-marker org-columns-top-level-marker (point)))
16954 fmt))
16956 (defun org-columns ()
16957 "Turn on column view on an org-mode file."
16958 (interactive)
16959 (org-verify-version 'columns)
16960 (org-columns-remove-overlays)
16961 (move-marker org-columns-begin-marker (point))
16962 (let (beg end fmt cache maxwidths)
16963 (setq fmt (org-columns-get-format-and-top-level))
16964 (save-excursion
16965 (goto-char org-columns-top-level-marker)
16966 (setq beg (point))
16967 (unless org-columns-inhibit-recalculation
16968 (org-columns-compute-all))
16969 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
16970 (point-max)))
16971 ;; Get and cache the properties
16972 (goto-char beg)
16973 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
16974 (save-excursion
16975 (save-restriction
16976 (narrow-to-region beg end)
16977 (org-clock-sum))))
16978 (while (re-search-forward (concat "^" outline-regexp) end t)
16979 (push (cons (org-current-line) (org-entry-properties)) cache))
16980 (when cache
16981 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16982 (org-set-local 'org-columns-current-maxwidths maxwidths)
16983 (org-columns-display-here-title)
16984 (mapc (lambda (x)
16985 (goto-line (car x))
16986 (org-columns-display-here (cdr x)))
16987 cache)))))
16989 (defun org-columns-new (&optional prop title width op fmt &rest rest)
16990 "Insert a new column, to the leeft o the current column."
16991 (interactive)
16992 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
16993 cell)
16994 (setq prop (completing-read
16995 "Property: " (mapcar 'list (org-buffer-property-keys t nil t))
16996 nil nil prop))
16997 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
16998 (setq width (read-string "Column width: " (if width (number-to-string width))))
16999 (if (string-match "\\S-" width)
17000 (setq width (string-to-number width))
17001 (setq width nil))
17002 (setq fmt (completing-read "Summary [none]: "
17003 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox") ("checkbox-n-of-m") ("checkbox-percent"))
17004 nil t))
17005 (if (string-match "\\S-" fmt)
17006 (setq fmt (intern fmt))
17007 (setq fmt nil))
17008 (if (eq fmt 'none) (setq fmt nil))
17009 (if editp
17010 (progn
17011 (setcar editp prop)
17012 (setcdr editp (list title width nil fmt)))
17013 (setq cell (nthcdr (1- (current-column))
17014 org-columns-current-fmt-compiled))
17015 (setcdr cell (cons (list prop title width nil fmt)
17016 (cdr cell))))
17017 (org-columns-store-format)
17018 (org-columns-redo)))
17020 (defun org-columns-delete ()
17021 "Delete the column at point from columns view."
17022 (interactive)
17023 (let* ((n (current-column))
17024 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
17025 (when (y-or-n-p
17026 (format "Are you sure you want to remove column \"%s\"? " title))
17027 (setq org-columns-current-fmt-compiled
17028 (delq (nth n org-columns-current-fmt-compiled)
17029 org-columns-current-fmt-compiled))
17030 (org-columns-store-format)
17031 (org-columns-redo)
17032 (if (>= (current-column) (length org-columns-current-fmt-compiled))
17033 (backward-char 1)))))
17035 (defun org-columns-edit-attributes ()
17036 "Edit the attributes of the current column."
17037 (interactive)
17038 (let* ((n (current-column))
17039 (info (nth n org-columns-current-fmt-compiled)))
17040 (apply 'org-columns-new info)))
17042 (defun org-columns-widen (arg)
17043 "Make the column wider by ARG characters."
17044 (interactive "p")
17045 (let* ((n (current-column))
17046 (entry (nth n org-columns-current-fmt-compiled))
17047 (width (or (nth 2 entry)
17048 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
17049 (setq width (max 1 (+ width arg)))
17050 (setcar (nthcdr 2 entry) width)
17051 (org-columns-store-format)
17052 (org-columns-redo)))
17054 (defun org-columns-narrow (arg)
17055 "Make the column nrrower by ARG characters."
17056 (interactive "p")
17057 (org-columns-widen (- arg)))
17059 (defun org-columns-move-right ()
17060 "Swap this column with the one to the right."
17061 (interactive)
17062 (let* ((n (current-column))
17063 (cell (nthcdr n org-columns-current-fmt-compiled))
17065 (when (>= n (1- (length org-columns-current-fmt-compiled)))
17066 (error "Cannot shift this column further to the right"))
17067 (setq e (car cell))
17068 (setcar cell (car (cdr cell)))
17069 (setcdr cell (cons e (cdr (cdr cell))))
17070 (org-columns-store-format)
17071 (org-columns-redo)
17072 (forward-char 1)))
17074 (defun org-columns-move-left ()
17075 "Swap this column with the one to the left."
17076 (interactive)
17077 (let* ((n (current-column)))
17078 (when (= n 0)
17079 (error "Cannot shift this column further to the left"))
17080 (backward-char 1)
17081 (org-columns-move-right)
17082 (backward-char 1)))
17084 (defun org-columns-store-format ()
17085 "Store the text version of the current columns format in appropriate place.
17086 This is either in the COLUMNS property of the node starting the current column
17087 display, or in the #+COLUMNS line of the current buffer."
17088 (let (fmt (cnt 0))
17089 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
17090 (org-set-local 'org-columns-current-fmt fmt)
17091 (if (marker-position org-columns-top-level-marker)
17092 (save-excursion
17093 (goto-char org-columns-top-level-marker)
17094 (if (and (org-at-heading-p)
17095 (org-entry-get nil "COLUMNS"))
17096 (org-entry-put nil "COLUMNS" fmt)
17097 (goto-char (point-min))
17098 ;; Overwrite all #+COLUMNS lines....
17099 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
17100 (setq cnt (1+ cnt))
17101 (replace-match (concat "#+COLUMNS: " fmt) t t))
17102 (unless (> cnt 0)
17103 (goto-char (point-min))
17104 (or (org-on-heading-p t) (outline-next-heading))
17105 (let ((inhibit-read-only t))
17106 (insert-before-markers "#+COLUMNS: " fmt "\n")))
17107 (org-set-local 'org-columns-default-format fmt))))))
17109 (defvar org-overriding-columns-format nil
17110 "When set, overrides any other definition.")
17111 (defvar org-agenda-view-columns-initially nil
17112 "When set, switch to columns view immediately after creating the agenda.")
17114 (defun org-agenda-columns ()
17115 "Turn on column view in the agenda."
17116 (interactive)
17117 (org-verify-version 'columns)
17118 (org-columns-remove-overlays)
17119 (move-marker org-columns-begin-marker (point))
17120 (let (fmt cache maxwidths m)
17121 (cond
17122 ((and (local-variable-p 'org-overriding-columns-format)
17123 org-overriding-columns-format)
17124 (setq fmt org-overriding-columns-format))
17125 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
17126 (setq fmt (org-entry-get m "COLUMNS" t)))
17127 ((and (boundp 'org-columns-current-fmt)
17128 (local-variable-p 'org-columns-current-fmt)
17129 org-columns-current-fmt)
17130 (setq fmt org-columns-current-fmt))
17131 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
17132 (setq m (get-text-property m 'org-hd-marker))
17133 (setq fmt (org-entry-get m "COLUMNS" t))))
17134 (setq fmt (or fmt org-columns-default-format))
17135 (org-set-local 'org-columns-current-fmt fmt)
17136 (org-columns-compile-format fmt)
17137 (save-excursion
17138 ;; Get and cache the properties
17139 (goto-char (point-min))
17140 (while (not (eobp))
17141 (when (setq m (or (get-text-property (point) 'org-hd-marker)
17142 (get-text-property (point) 'org-marker)))
17143 (push (cons (org-current-line) (org-entry-properties m)) cache))
17144 (beginning-of-line 2))
17145 (when cache
17146 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17147 (org-set-local 'org-columns-current-maxwidths maxwidths)
17148 (org-columns-display-here-title)
17149 (mapc (lambda (x)
17150 (goto-line (car x))
17151 (org-columns-display-here (cdr x)))
17152 cache)))))
17154 (defun org-columns-get-autowidth-alist (s cache)
17155 "Derive the maximum column widths from the format and the cache."
17156 (let ((start 0) rtn)
17157 (while (string-match (org-re "%\\([[:alpha:]][[:alnum:]_-]*\\)") s start)
17158 (push (cons (match-string 1 s) 1) rtn)
17159 (setq start (match-end 0)))
17160 (mapc (lambda (x)
17161 (setcdr x (apply 'max
17162 (mapcar
17163 (lambda (y)
17164 (length (or (cdr (assoc (car x) (cdr y))) " ")))
17165 cache))))
17166 rtn)
17167 rtn))
17169 (defun org-columns-compute-all ()
17170 "Compute all columns that have operators defined."
17171 (org-unmodified
17172 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
17173 (let ((columns org-columns-current-fmt-compiled) col)
17174 (while (setq col (pop columns))
17175 (when (nth 3 col)
17176 (save-excursion
17177 (org-columns-compute (car col)))))))
17179 (defun org-columns-update (property)
17180 "Recompute PROPERTY, and update the columns display for it."
17181 (org-columns-compute property)
17182 (let (fmt val pos)
17183 (save-excursion
17184 (mapc (lambda (ov)
17185 (when (equal (org-overlay-get ov 'org-columns-key) property)
17186 (setq pos (org-overlay-start ov))
17187 (goto-char pos)
17188 (when (setq val (cdr (assoc property
17189 (get-text-property
17190 (point-at-bol) 'org-summaries))))
17191 (setq fmt (org-overlay-get ov 'org-columns-format))
17192 (org-overlay-put ov 'org-columns-value val)
17193 (org-overlay-put ov 'display (format fmt val)))))
17194 org-columns-overlays))))
17196 (defun org-columns-compute (property)
17197 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
17198 (interactive)
17199 (let* ((re (concat "^" outline-regexp))
17200 (lmax 30) ; Does anyone use deeper levels???
17201 (lsum (make-vector lmax 0))
17202 (lflag (make-vector lmax nil))
17203 (level 0)
17204 (ass (assoc property org-columns-current-fmt-compiled))
17205 (format (nth 4 ass))
17206 (printf (nth 5 ass))
17207 (beg org-columns-top-level-marker)
17208 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
17209 (save-excursion
17210 ;; Find the region to compute
17211 (goto-char beg)
17212 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
17213 (goto-char end)
17214 ;; Walk the tree from the back and do the computations
17215 (while (re-search-backward re beg t)
17216 (setq sumpos (match-beginning 0)
17217 last-level level
17218 level (org-outline-level)
17219 val (org-entry-get nil property)
17220 valflag (and val (string-match "\\S-" val)))
17221 (cond
17222 ((< level last-level)
17223 ;; put the sum of lower levels here as a property
17224 (setq sum (aref lsum last-level) ; current sum
17225 flag (aref lflag last-level) ; any valid entries from children?
17226 str (org-column-number-to-string sum format printf)
17227 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
17228 useval (if flag str1 (if valflag val ""))
17229 sum-alist (get-text-property sumpos 'org-summaries))
17230 (if (assoc property sum-alist)
17231 (setcdr (assoc property sum-alist) useval)
17232 (push (cons property useval) sum-alist)
17233 (org-unmodified
17234 (add-text-properties sumpos (1+ sumpos)
17235 (list 'org-summaries sum-alist))))
17236 (when val
17237 (org-entry-put nil property (if flag str val)))
17238 ;; add current to current level accumulator
17239 (when (or flag valflag)
17240 (aset lsum level (+ (aref lsum level)
17241 (if flag sum (org-column-string-to-number
17242 (if flag str val) format))))
17243 (aset lflag level t))
17244 ;; clear accumulators for deeper levels
17245 (loop for l from (1+ level) to (1- lmax) do
17246 (aset lsum l 0)
17247 (aset lflag l nil)))
17248 ((>= level last-level)
17249 ;; add what we have here to the accumulator for this level
17250 (aset lsum level (+ (aref lsum level)
17251 (org-column-string-to-number (or val "0") format)))
17252 (and valflag (aset lflag level t)))
17253 (t (error "This should not happen")))))))
17255 (defun org-columns-redo ()
17256 "Construct the column display again."
17257 (interactive)
17258 (message "Recomputing columns...")
17259 (save-excursion
17260 (if (marker-position org-columns-begin-marker)
17261 (goto-char org-columns-begin-marker))
17262 (org-columns-remove-overlays)
17263 (if (org-mode-p)
17264 (call-interactively 'org-columns)
17265 (call-interactively 'org-agenda-columns)))
17266 (message "Recomputing columns...done"))
17268 (defun org-columns-not-in-agenda ()
17269 (if (eq major-mode 'org-agenda-mode)
17270 (error "This command is only allowed in Org-mode buffers")))
17273 (defun org-string-to-number (s)
17274 "Convert string to number, and interpret hh:mm:ss."
17275 (if (not (string-match ":" s))
17276 (string-to-number s)
17277 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17278 (while l
17279 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17280 sum)))
17282 (defun org-column-number-to-string (n fmt &optional printf)
17283 "Convert a computed column number to a string value, according to FMT."
17284 (cond
17285 ((eq fmt 'add_times)
17286 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
17287 (format "%d:%02d" h m)))
17288 ((eq fmt 'checkbox)
17289 (cond ((= n (floor n)) "[X]")
17290 ((> n 1.) "[-]")
17291 (t "[ ]")))
17292 ((memq fmt '(checkbox-n-of-m checkbox-percent))
17293 (let* ((n1 (floor n)) (n2 (floor (+ .5 (* 1000000 (- n n1))))))
17294 (org-nofm-to-completion n1 (+ n2 n1) (eq fmt 'checkbox-percent))))
17295 (printf (format printf n))
17296 ((eq fmt 'currency)
17297 (format "%.2f" n))
17298 (t (number-to-string n))))
17300 (defun org-nofm-to-completion (n m &optional percent)
17301 (if (not percent)
17302 (format "[%d/%d]" n m)
17303 (format "[%d%%]"(floor (+ 0.5 (* 100. (/ (* 1.0 n) m)))))))
17305 (defun org-column-string-to-number (s fmt)
17306 "Convert a column value to a number that can be used for column computing."
17307 (cond
17308 ((string-match ":" s)
17309 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17310 (while l
17311 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17312 sum))
17313 ((memq fmt '(checkbox checkbox-n-of-m checkbox-percent))
17314 (if (equal s "[X]") 1. 0.000001))
17315 (t (string-to-number s))))
17317 (defun org-columns-uncompile-format (cfmt)
17318 "Turn the compiled columns format back into a string representation."
17319 (let ((rtn "") e s prop title op width fmt printf)
17320 (while (setq e (pop cfmt))
17321 (setq prop (car e)
17322 title (nth 1 e)
17323 width (nth 2 e)
17324 op (nth 3 e)
17325 fmt (nth 4 e)
17326 printf (nth 5 e))
17327 (cond
17328 ((eq fmt 'add_times) (setq op ":"))
17329 ((eq fmt 'checkbox) (setq op "X"))
17330 ((eq fmt 'checkbox-n-of-m) (setq op "X/"))
17331 ((eq fmt 'checkbox-percent) (setq op "X%"))
17332 ((eq fmt 'add_numbers) (setq op "+"))
17333 ((eq fmt 'currency) (setq op "$")))
17334 (if (and op printf) (setq op (concat op ";" printf)))
17335 (if (equal title prop) (setq title nil))
17336 (setq s (concat "%" (if width (number-to-string width))
17337 prop
17338 (if title (concat "(" title ")"))
17339 (if op (concat "{" op "}"))))
17340 (setq rtn (concat rtn " " s)))
17341 (org-trim rtn)))
17343 (defun org-columns-compile-format (fmt)
17344 "Turn a column format string into an alist of specifications.
17345 The alist has one entry for each column in the format. The elements of
17346 that list are:
17347 property the property
17348 title the title field for the columns
17349 width the column width in characters, can be nil for automatic
17350 operator the operator if any
17351 format the output format for computed results, derived from operator
17352 printf a printf format for computed values"
17353 (let ((start 0) width prop title op f printf)
17354 (setq org-columns-current-fmt-compiled nil)
17355 (while (string-match
17356 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
17357 fmt start)
17358 (setq start (match-end 0)
17359 width (match-string 1 fmt)
17360 prop (match-string 2 fmt)
17361 title (or (match-string 3 fmt) prop)
17362 op (match-string 4 fmt)
17363 f nil
17364 printf nil)
17365 (if width (setq width (string-to-number width)))
17366 (when (and op (string-match ";" op))
17367 (setq printf (substring op (match-end 0))
17368 op (substring op 0 (match-beginning 0))))
17369 (cond
17370 ((equal op "+") (setq f 'add_numbers))
17371 ((equal op "$") (setq f 'currency))
17372 ((equal op ":") (setq f 'add_times))
17373 ((equal op "X") (setq f 'checkbox))
17374 ((equal op "X/") (setq f 'checkbox-n-of-m))
17375 ((equal op "X%") (setq f 'checkbox-percent))
17377 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
17378 (setq org-columns-current-fmt-compiled
17379 (nreverse org-columns-current-fmt-compiled))))
17382 ;;; Dynamic block for Column view
17384 (defun org-columns-capture-view ()
17385 "Get the column view of the current buffer and return it as a list.
17386 The list will contains the title row and all other rows. Each row is
17387 a list of fields."
17388 (save-excursion
17389 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
17390 (n (length title)) row tbl)
17391 (goto-char (point-min))
17392 (while (re-search-forward "^\\*+ " nil t)
17393 (when (get-char-property (match-beginning 0) 'org-columns-key)
17394 (setq row nil)
17395 (loop for i from 0 to (1- n) do
17396 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
17397 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
17399 row))
17400 (setq row (nreverse row))
17401 (push row tbl)))
17402 (append (list title 'hline) (nreverse tbl)))))
17404 (defun org-dblock-write:columnview (params)
17405 "Write the column view table.
17406 PARAMS is a property list of parameters:
17408 :width enforce same column widths with <N> specifiers.
17409 :id the :ID: property of the entry where the columns view
17410 should be built, as a string. When `local', call locally.
17411 When `global' call column view with the cursor at the beginning
17412 of the buffer (usually this means that the whole buffer switches
17413 to column view).
17414 :hlines When t, insert a hline before each item. When a number, insert
17415 a hline before each level <= that number.
17416 :vlines When t, make each column a colgroup to enforce vertical lines."
17417 (let ((pos (move-marker (make-marker) (point)))
17418 (hlines (plist-get params :hlines))
17419 (vlines (plist-get params :vlines))
17420 tbl id idpos nfields tmp)
17421 (save-excursion
17422 (save-restriction
17423 (when (setq id (plist-get params :id))
17424 (cond ((not id) nil)
17425 ((eq id 'global) (goto-char (point-min)))
17426 ((eq id 'local) nil)
17427 ((setq idpos (org-find-entry-with-id id))
17428 (goto-char idpos))
17429 (t (error "Cannot find entry with :ID: %s" id))))
17430 (org-columns)
17431 (setq tbl (org-columns-capture-view))
17432 (setq nfields (length (car tbl)))
17433 (org-columns-quit)))
17434 (goto-char pos)
17435 (move-marker pos nil)
17436 (when tbl
17437 (when (plist-get params :hlines)
17438 (setq tmp nil)
17439 (while tbl
17440 (if (eq (car tbl) 'hline)
17441 (push (pop tbl) tmp)
17442 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17443 (if (and (not (eq (car tmp) 'hline))
17444 (or (eq hlines t)
17445 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17446 (push 'hline tmp)))
17447 (push (pop tbl) tmp)))
17448 (setq tbl (nreverse tmp)))
17449 (when vlines
17450 (setq tbl (mapcar (lambda (x)
17451 (if (eq 'hline x) x (cons "" x)))
17452 tbl))
17453 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17454 (setq pos (point))
17455 (insert (org-listtable-to-string tbl))
17456 (when (plist-get params :width)
17457 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17458 org-columns-current-widths "|")))
17459 (goto-char pos)
17460 (org-table-align))))
17462 (defun org-listtable-to-string (tbl)
17463 "Convert a listtable TBL to a string that contains the Org-mode table.
17464 The table still need to be alligned. The resulting string has no leading
17465 and tailing newline characters."
17466 (mapconcat
17467 (lambda (x)
17468 (cond
17469 ((listp x)
17470 (concat "|" (mapconcat 'identity x "|") "|"))
17471 ((eq x 'hline) "|-|")
17472 (t (error "Garbage in listtable: %s" x))))
17473 tbl "\n"))
17475 (defun org-insert-columns-dblock ()
17476 "Create a dynamic block capturing a column view table."
17477 (interactive)
17478 (let ((defaults '(:name "columnview" :hlines 1))
17479 (id (completing-read
17480 "Capture columns (local, global, entry with :ID: property) [local]: "
17481 (append '(("global") ("local"))
17482 (mapcar 'list (org-property-values "ID"))))))
17483 (if (equal id "") (setq id 'local))
17484 (if (equal id "global") (setq id 'global))
17485 (setq defaults (append defaults (list :id id)))
17486 (org-create-dblock defaults)
17487 (org-update-dblock)))
17489 ;;;; Timestamps
17491 (defvar org-last-changed-timestamp nil)
17492 (defvar org-time-was-given) ; dynamically scoped parameter
17493 (defvar org-end-time-was-given) ; dynamically scoped parameter
17494 (defvar org-ts-what) ; dynamically scoped parameter
17496 (defun org-time-stamp (arg)
17497 "Prompt for a date/time and insert a time stamp.
17498 If the user specifies a time like HH:MM, or if this command is called
17499 with a prefix argument, the time stamp will contain date and time.
17500 Otherwise, only the date will be included. All parts of a date not
17501 specified by the user will be filled in from the current date/time.
17502 So if you press just return without typing anything, the time stamp
17503 will represent the current date/time. If there is already a timestamp
17504 at the cursor, it will be modified."
17505 (interactive "P")
17506 (let* ((ts nil)
17507 (default-time
17508 ;; Default time is either today, or, when entering a range,
17509 ;; the range start.
17510 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17511 (save-excursion
17512 (re-search-backward
17513 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17514 (- (point) 20) t)))
17515 (apply 'encode-time (org-parse-time-string (match-string 1)))
17516 (current-time)))
17517 (default-input (and ts (org-get-compact-tod ts)))
17518 org-time-was-given org-end-time-was-given time)
17519 (cond
17520 ((and (org-at-timestamp-p)
17521 (eq last-command 'org-time-stamp)
17522 (eq this-command 'org-time-stamp))
17523 (insert "--")
17524 (setq time (let ((this-command this-command))
17525 (org-read-date arg 'totime nil nil default-time default-input)))
17526 (org-insert-time-stamp time (or org-time-was-given arg)))
17527 ((org-at-timestamp-p)
17528 (setq time (let ((this-command this-command))
17529 (org-read-date arg 'totime nil nil default-time default-input)))
17530 (when (org-at-timestamp-p) ; just to get the match data
17531 (replace-match "")
17532 (setq org-last-changed-timestamp
17533 (org-insert-time-stamp
17534 time (or org-time-was-given arg)
17535 nil nil nil (list org-end-time-was-given))))
17536 (message "Timestamp updated"))
17538 (setq time (let ((this-command this-command))
17539 (org-read-date arg 'totime nil nil default-time default-input)))
17540 (org-insert-time-stamp time (or org-time-was-given arg)
17541 nil nil nil (list org-end-time-was-given))))))
17543 ;; FIXME: can we use this for something else????
17544 ;; like computing time differences?????
17545 (defun org-get-compact-tod (s)
17546 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17547 (let* ((t1 (match-string 1 s))
17548 (h1 (string-to-number (match-string 2 s)))
17549 (m1 (string-to-number (match-string 3 s)))
17550 (t2 (and (match-end 4) (match-string 5 s)))
17551 (h2 (and t2 (string-to-number (match-string 6 s))))
17552 (m2 (and t2 (string-to-number (match-string 7 s))))
17553 dh dm)
17554 (if (not t2)
17556 (setq dh (- h2 h1) dm (- m2 m1))
17557 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17558 (concat t1 "+" (number-to-string dh)
17559 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17561 (defun org-time-stamp-inactive (&optional arg)
17562 "Insert an inactive time stamp.
17563 An inactive time stamp is enclosed in square brackets instead of angle
17564 brackets. It is inactive in the sense that it does not trigger agenda entries,
17565 does not link to the calendar and cannot be changed with the S-cursor keys.
17566 So these are more for recording a certain time/date."
17567 (interactive "P")
17568 (let (org-time-was-given org-end-time-was-given time)
17569 (setq time (org-read-date arg 'totime))
17570 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17571 nil nil (list org-end-time-was-given))))
17573 (defvar org-date-ovl (org-make-overlay 1 1))
17574 (org-overlay-put org-date-ovl 'face 'org-warning)
17575 (org-detach-overlay org-date-ovl)
17577 (defvar org-ans1) ; dynamically scoped parameter
17578 (defvar org-ans2) ; dynamically scoped parameter
17580 (defvar org-plain-time-of-day-regexp) ; defined below
17582 (defvar org-read-date-overlay nil)
17583 (defvar org-dcst nil) ; dynamically scoped
17585 (defun org-read-date (&optional with-time to-time from-string prompt
17586 default-time default-input)
17587 "Read a date, possibly a time, and make things smooth for the user.
17588 The prompt will suggest to enter an ISO date, but you can also enter anything
17589 which will at least partially be understood by `parse-time-string'.
17590 Unrecognized parts of the date will default to the current day, month, year,
17591 hour and minute. If this command is called to replace a timestamp at point,
17592 of to enter the second timestamp of a range, the default time is taken from the
17593 existing stamp. For example,
17594 3-2-5 --> 2003-02-05
17595 feb 15 --> currentyear-02-15
17596 sep 12 9 --> 2009-09-12
17597 12:45 --> today 12:45
17598 22 sept 0:34 --> currentyear-09-22 0:34
17599 12 --> currentyear-currentmonth-12
17600 Fri --> nearest Friday (today or later)
17601 etc.
17603 Furthermore you can specify a relative date by giving, as the *first* thing
17604 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17605 change in days weeks, months, years.
17606 With a single plus or minus, the date is relative to today. With a double
17607 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17608 +4d --> four days from today
17609 +4 --> same as above
17610 +2w --> two weeks from today
17611 ++5 --> five days from default date
17613 The function understands only English month and weekday abbreviations,
17614 but this can be configured with the variables `parse-time-months' and
17615 `parse-time-weekdays'.
17617 While prompting, a calendar is popped up - you can also select the
17618 date with the mouse (button 1). The calendar shows a period of three
17619 months. To scroll it to other months, use the keys `>' and `<'.
17620 If you don't like the calendar, turn it off with
17621 \(setq org-read-date-popup-calendar nil)
17623 With optional argument TO-TIME, the date will immediately be converted
17624 to an internal time.
17625 With an optional argument WITH-TIME, the prompt will suggest to also
17626 insert a time. Note that when WITH-TIME is not set, you can still
17627 enter a time, and this function will inform the calling routine about
17628 this change. The calling routine may then choose to change the format
17629 used to insert the time stamp into the buffer to include the time.
17630 With optional argument FROM-STRING, read from this string instead from
17631 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17632 the time/date that is used for everything that is not specified by the
17633 user."
17634 (require 'parse-time)
17635 (let* ((org-time-stamp-rounding-minutes
17636 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
17637 (org-dcst org-display-custom-times)
17638 (ct (org-current-time))
17639 (def (or default-time ct))
17640 (defdecode (decode-time def))
17641 (dummy (progn
17642 (when (< (nth 2 defdecode) org-extend-today-until)
17643 (setcar (nthcdr 2 defdecode) -1)
17644 (setcar (nthcdr 1 defdecode) 59)
17645 (setq def (apply 'encode-time defdecode)
17646 defdecode (decode-time def)))))
17647 (calendar-move-hook nil)
17648 (view-diary-entries-initially nil)
17649 (view-calendar-holidays-initially nil)
17650 (timestr (format-time-string
17651 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17652 (prompt (concat (if prompt (concat prompt " ") "")
17653 (format "Date+time [%s]: " timestr)))
17654 ans (org-ans0 "") org-ans1 org-ans2 final)
17656 (cond
17657 (from-string (setq ans from-string))
17658 (org-read-date-popup-calendar
17659 (save-excursion
17660 (save-window-excursion
17661 (calendar)
17662 (calendar-forward-day (- (time-to-days def)
17663 (calendar-absolute-from-gregorian
17664 (calendar-current-date))))
17665 (org-eval-in-calendar nil t)
17666 (let* ((old-map (current-local-map))
17667 (map (copy-keymap calendar-mode-map))
17668 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17669 (org-defkey map (kbd "RET") 'org-calendar-select)
17670 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17671 'org-calendar-select-mouse)
17672 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17673 'org-calendar-select-mouse)
17674 (org-defkey minibuffer-local-map [(meta shift left)]
17675 (lambda () (interactive)
17676 (org-eval-in-calendar '(calendar-backward-month 1))))
17677 (org-defkey minibuffer-local-map [(meta shift right)]
17678 (lambda () (interactive)
17679 (org-eval-in-calendar '(calendar-forward-month 1))))
17680 (org-defkey minibuffer-local-map [(meta shift up)]
17681 (lambda () (interactive)
17682 (org-eval-in-calendar '(calendar-backward-year 1))))
17683 (org-defkey minibuffer-local-map [(meta shift down)]
17684 (lambda () (interactive)
17685 (org-eval-in-calendar '(calendar-forward-year 1))))
17686 (org-defkey minibuffer-local-map [(shift up)]
17687 (lambda () (interactive)
17688 (org-eval-in-calendar '(calendar-backward-week 1))))
17689 (org-defkey minibuffer-local-map [(shift down)]
17690 (lambda () (interactive)
17691 (org-eval-in-calendar '(calendar-forward-week 1))))
17692 (org-defkey minibuffer-local-map [(shift left)]
17693 (lambda () (interactive)
17694 (org-eval-in-calendar '(calendar-backward-day 1))))
17695 (org-defkey minibuffer-local-map [(shift right)]
17696 (lambda () (interactive)
17697 (org-eval-in-calendar '(calendar-forward-day 1))))
17698 (org-defkey minibuffer-local-map ">"
17699 (lambda () (interactive)
17700 (org-eval-in-calendar '(scroll-calendar-left 1))))
17701 (org-defkey minibuffer-local-map "<"
17702 (lambda () (interactive)
17703 (org-eval-in-calendar '(scroll-calendar-right 1))))
17704 (unwind-protect
17705 (progn
17706 (use-local-map map)
17707 (add-hook 'post-command-hook 'org-read-date-display)
17708 (setq org-ans0 (read-string prompt default-input nil nil))
17709 ;; org-ans0: from prompt
17710 ;; org-ans1: from mouse click
17711 ;; org-ans2: from calendar motion
17712 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17713 (remove-hook 'post-command-hook 'org-read-date-display)
17714 (use-local-map old-map)
17715 (when org-read-date-overlay
17716 (org-delete-overlay org-read-date-overlay)
17717 (setq org-read-date-overlay nil)))))))
17719 (t ; Naked prompt only
17720 (unwind-protect
17721 (setq ans (read-string prompt default-input nil timestr))
17722 (when org-read-date-overlay
17723 (org-delete-overlay org-read-date-overlay)
17724 (setq org-read-date-overlay nil)))))
17726 (setq final (org-read-date-analyze ans def defdecode))
17728 (if to-time
17729 (apply 'encode-time final)
17730 (if (and (boundp 'org-time-was-given) org-time-was-given)
17731 (format "%04d-%02d-%02d %02d:%02d"
17732 (nth 5 final) (nth 4 final) (nth 3 final)
17733 (nth 2 final) (nth 1 final))
17734 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17735 (defvar def)
17736 (defvar defdecode)
17737 (defvar with-time)
17738 (defun org-read-date-display ()
17739 "Display the currrent date prompt interpretation in the minibuffer."
17740 (when org-read-date-display-live
17741 (when org-read-date-overlay
17742 (org-delete-overlay org-read-date-overlay))
17743 (let ((p (point)))
17744 (end-of-line 1)
17745 (while (not (equal (buffer-substring
17746 (max (point-min) (- (point) 4)) (point))
17747 " "))
17748 (insert " "))
17749 (goto-char p))
17750 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17751 " " (or org-ans1 org-ans2)))
17752 (org-end-time-was-given nil)
17753 (f (org-read-date-analyze ans def defdecode))
17754 (fmts (if org-dcst
17755 org-time-stamp-custom-formats
17756 org-time-stamp-formats))
17757 (fmt (if (or with-time
17758 (and (boundp 'org-time-was-given) org-time-was-given))
17759 (cdr fmts)
17760 (car fmts)))
17761 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
17762 (when (and org-end-time-was-given
17763 (string-match org-plain-time-of-day-regexp txt))
17764 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17765 org-end-time-was-given
17766 (substring txt (match-end 0)))))
17767 (setq org-read-date-overlay
17768 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17769 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
17771 (defun org-read-date-analyze (ans def defdecode)
17772 "Analyze the combined answer of the date prompt."
17773 ;; FIXME: cleanup and comment
17774 (let (delta deltan deltaw deltadef year month day
17775 hour minute second wday pm h2 m2 tl wday1)
17777 (when (setq delta (org-read-date-get-relative ans (current-time) def))
17778 (setq ans (replace-match "" t t ans)
17779 deltan (car delta)
17780 deltaw (nth 1 delta)
17781 deltadef (nth 2 delta)))
17783 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
17784 (when (string-match
17785 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17786 (setq year (if (match-end 2)
17787 (string-to-number (match-string 2 ans))
17788 (string-to-number (format-time-string "%Y")))
17789 month (string-to-number (match-string 3 ans))
17790 day (string-to-number (match-string 4 ans)))
17791 (if (< year 100) (setq year (+ 2000 year)))
17792 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17793 t nil ans)))
17794 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17795 ;; If there is a time with am/pm, and *no* time without it, we convert
17796 ;; so that matching will be successful.
17797 (loop for i from 1 to 2 do ; twice, for end time as well
17798 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17799 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17800 (setq hour (string-to-number (match-string 1 ans))
17801 minute (if (match-end 3)
17802 (string-to-number (match-string 3 ans))
17804 pm (equal ?p
17805 (string-to-char (downcase (match-string 4 ans)))))
17806 (if (and (= hour 12) (not pm))
17807 (setq hour 0)
17808 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17809 (setq ans (replace-match (format "%02d:%02d" hour minute)
17810 t t ans))))
17812 ;; Check if a time range is given as a duration
17813 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17814 (setq hour (string-to-number (match-string 1 ans))
17815 h2 (+ hour (string-to-number (match-string 3 ans)))
17816 minute (string-to-number (match-string 2 ans))
17817 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
17818 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17819 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
17821 ;; Check if there is a time range
17822 (when (boundp 'org-end-time-was-given)
17823 (setq org-time-was-given nil)
17824 (when (and (string-match org-plain-time-of-day-regexp ans)
17825 (match-end 8))
17826 (setq org-end-time-was-given (match-string 8 ans))
17827 (setq ans (concat (substring ans 0 (match-beginning 7))
17828 (substring ans (match-end 7))))))
17830 (setq tl (parse-time-string ans)
17831 day (or (nth 3 tl) (nth 3 defdecode))
17832 month (or (nth 4 tl)
17833 (if (and org-read-date-prefer-future
17834 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
17835 (1+ (nth 4 defdecode))
17836 (nth 4 defdecode)))
17837 year (or (nth 5 tl)
17838 (if (and org-read-date-prefer-future
17839 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
17840 (1+ (nth 5 defdecode))
17841 (nth 5 defdecode)))
17842 hour (or (nth 2 tl) (nth 2 defdecode))
17843 minute (or (nth 1 tl) (nth 1 defdecode))
17844 second (or (nth 0 tl) 0)
17845 wday (nth 6 tl))
17846 (when deltan
17847 (unless deltadef
17848 (let ((now (decode-time (current-time))))
17849 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17850 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17851 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17852 ((equal deltaw "m") (setq month (+ month deltan)))
17853 ((equal deltaw "y") (setq year (+ year deltan)))))
17854 (when (and wday (not (nth 3 tl)))
17855 ;; Weekday was given, but no day, so pick that day in the week
17856 ;; on or after the derived date.
17857 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17858 (unless (equal wday wday1)
17859 (setq day (+ day (% (- wday wday1 -7) 7)))))
17860 (if (and (boundp 'org-time-was-given)
17861 (nth 2 tl))
17862 (setq org-time-was-given t))
17863 (if (< year 100) (setq year (+ 2000 year)))
17864 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
17865 (list second minute hour day month year)))
17867 (defvar parse-time-weekdays)
17869 (defun org-read-date-get-relative (s today default)
17870 "Check string S for special relative date string.
17871 TODAY and DEFAULT are internal times, for today and for a default.
17872 Return shift list (N what def-flag)
17873 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17874 N is the number of WHATs to shift.
17875 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17876 the DEFAULT date rather than TODAY."
17877 (when (string-match
17878 (concat
17879 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
17880 "\\([0-9]+\\)?"
17881 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17882 "\\([ \t]\\|$\\)") s)
17883 (let* ((dir (if (match-end 1)
17884 (string-to-char (substring (match-string 1 s) -1))
17885 ?+))
17886 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17887 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17888 (what (if (match-end 3) (match-string 3 s) "d"))
17889 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17890 (date (if rel default today))
17891 (wday (nth 6 (decode-time date)))
17892 delta)
17893 (if wday1
17894 (progn
17895 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17896 (if (= dir ?-) (setq delta (- delta 7)))
17897 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17898 (list delta "d" rel))
17899 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17901 (defun org-eval-in-calendar (form &optional keepdate)
17902 "Eval FORM in the calendar window and return to current window.
17903 Also, store the cursor date in variable org-ans2."
17904 (let ((sw (selected-window)))
17905 (select-window (get-buffer-window "*Calendar*"))
17906 (eval form)
17907 (when (and (not keepdate) (calendar-cursor-to-date))
17908 (let* ((date (calendar-cursor-to-date))
17909 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17910 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17911 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17912 (select-window sw)))
17914 ; ;; Update the prompt to show new default date
17915 ; (save-excursion
17916 ; (goto-char (point-min))
17917 ; (when (and org-ans2
17918 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
17919 ; (get-text-property (match-end 0) 'field))
17920 ; (let ((inhibit-read-only t))
17921 ; (replace-match (concat "[" org-ans2 "]") t t)
17922 ; (add-text-properties (point-min) (1+ (match-end 0))
17923 ; (text-properties-at (1+ (point-min)))))))))
17925 (defun org-calendar-select ()
17926 "Return to `org-read-date' with the date currently selected.
17927 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17928 (interactive)
17929 (when (calendar-cursor-to-date)
17930 (let* ((date (calendar-cursor-to-date))
17931 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17932 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17933 (if (active-minibuffer-window) (exit-minibuffer))))
17935 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17936 "Insert a date stamp for the date given by the internal TIME.
17937 WITH-HM means, use the stamp format that includes the time of the day.
17938 INACTIVE means use square brackets instead of angular ones, so that the
17939 stamp will not contribute to the agenda.
17940 PRE and POST are optional strings to be inserted before and after the
17941 stamp.
17942 The command returns the inserted time stamp."
17943 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17944 stamp)
17945 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17946 (insert-before-markers (or pre ""))
17947 (insert-before-markers (setq stamp (format-time-string fmt time)))
17948 (when (listp extra)
17949 (setq extra (car extra))
17950 (if (and (stringp extra)
17951 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17952 (setq extra (format "-%02d:%02d"
17953 (string-to-number (match-string 1 extra))
17954 (string-to-number (match-string 2 extra))))
17955 (setq extra nil)))
17956 (when extra
17957 (backward-char 1)
17958 (insert-before-markers extra)
17959 (forward-char 1))
17960 (insert-before-markers (or post ""))
17961 stamp))
17963 (defun org-toggle-time-stamp-overlays ()
17964 "Toggle the use of custom time stamp formats."
17965 (interactive)
17966 (setq org-display-custom-times (not org-display-custom-times))
17967 (unless org-display-custom-times
17968 (let ((p (point-min)) (bmp (buffer-modified-p)))
17969 (while (setq p (next-single-property-change p 'display))
17970 (if (and (get-text-property p 'display)
17971 (eq (get-text-property p 'face) 'org-date))
17972 (remove-text-properties
17973 p (setq p (next-single-property-change p 'display))
17974 '(display t))))
17975 (set-buffer-modified-p bmp)))
17976 (if (featurep 'xemacs)
17977 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17978 (org-restart-font-lock)
17979 (setq org-table-may-need-update t)
17980 (if org-display-custom-times
17981 (message "Time stamps are overlayed with custom format")
17982 (message "Time stamp overlays removed")))
17984 (defun org-display-custom-time (beg end)
17985 "Overlay modified time stamp format over timestamp between BED and END."
17986 (let* ((ts (buffer-substring beg end))
17987 t1 w1 with-hm tf time str w2 (off 0))
17988 (save-match-data
17989 (setq t1 (org-parse-time-string ts t))
17990 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
17991 (setq off (- (match-end 0) (match-beginning 0)))))
17992 (setq end (- end off))
17993 (setq w1 (- end beg)
17994 with-hm (and (nth 1 t1) (nth 2 t1))
17995 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17996 time (org-fix-decoded-time t1)
17997 str (org-add-props
17998 (format-time-string
17999 (substring tf 1 -1) (apply 'encode-time time))
18000 nil 'mouse-face 'highlight)
18001 w2 (length str))
18002 (if (not (= w2 w1))
18003 (add-text-properties (1+ beg) (+ 2 beg)
18004 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
18005 (if (featurep 'xemacs)
18006 (progn
18007 (put-text-property beg end 'invisible t)
18008 (put-text-property beg end 'end-glyph (make-glyph str)))
18009 (put-text-property beg end 'display str))))
18011 (defun org-translate-time (string)
18012 "Translate all timestamps in STRING to custom format.
18013 But do this only if the variable `org-display-custom-times' is set."
18014 (when org-display-custom-times
18015 (save-match-data
18016 (let* ((start 0)
18017 (re org-ts-regexp-both)
18018 t1 with-hm inactive tf time str beg end)
18019 (while (setq start (string-match re string start))
18020 (setq beg (match-beginning 0)
18021 end (match-end 0)
18022 t1 (save-match-data
18023 (org-parse-time-string (substring string beg end) t))
18024 with-hm (and (nth 1 t1) (nth 2 t1))
18025 inactive (equal (substring string beg (1+ beg)) "[")
18026 tf (funcall (if with-hm 'cdr 'car)
18027 org-time-stamp-custom-formats)
18028 time (org-fix-decoded-time t1)
18029 str (format-time-string
18030 (concat
18031 (if inactive "[" "<") (substring tf 1 -1)
18032 (if inactive "]" ">"))
18033 (apply 'encode-time time))
18034 string (replace-match str t t string)
18035 start (+ start (length str)))))))
18036 string)
18038 (defun org-fix-decoded-time (time)
18039 "Set 0 instead of nil for the first 6 elements of time.
18040 Don't touch the rest."
18041 (let ((n 0))
18042 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
18044 (defun org-days-to-time (timestamp-string)
18045 "Difference between TIMESTAMP-STRING and now in days."
18046 (- (time-to-days (org-time-string-to-time timestamp-string))
18047 (time-to-days (current-time))))
18049 (defun org-deadline-close (timestamp-string &optional ndays)
18050 "Is the time in TIMESTAMP-STRING close to the current date?"
18051 (setq ndays (or ndays (org-get-wdays timestamp-string)))
18052 (and (< (org-days-to-time timestamp-string) ndays)
18053 (not (org-entry-is-done-p))))
18055 (defun org-get-wdays (ts)
18056 "Get the deadline lead time appropriate for timestring TS."
18057 (cond
18058 ((<= org-deadline-warning-days 0)
18059 ;; 0 or negative, enforce this value no matter what
18060 (- org-deadline-warning-days))
18061 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
18062 ;; lead time is specified.
18063 (floor (* (string-to-number (match-string 1 ts))
18064 (cdr (assoc (match-string 2 ts)
18065 '(("d" . 1) ("w" . 7)
18066 ("m" . 30.4) ("y" . 365.25)))))))
18067 ;; go for the default.
18068 (t org-deadline-warning-days)))
18070 (defun org-calendar-select-mouse (ev)
18071 "Return to `org-read-date' with the date currently selected.
18072 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
18073 (interactive "e")
18074 (mouse-set-point ev)
18075 (when (calendar-cursor-to-date)
18076 (let* ((date (calendar-cursor-to-date))
18077 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18078 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18079 (if (active-minibuffer-window) (exit-minibuffer))))
18081 (defun org-check-deadlines (ndays)
18082 "Check if there are any deadlines due or past due.
18083 A deadline is considered due if it happens within `org-deadline-warning-days'
18084 days from today's date. If the deadline appears in an entry marked DONE,
18085 it is not shown. The prefix arg NDAYS can be used to test that many
18086 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
18087 (interactive "P")
18088 (let* ((org-warn-days
18089 (cond
18090 ((equal ndays '(4)) 100000)
18091 (ndays (prefix-numeric-value ndays))
18092 (t (abs org-deadline-warning-days))))
18093 (case-fold-search nil)
18094 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
18095 (callback
18096 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
18098 (message "%d deadlines past-due or due within %d days"
18099 (org-occur regexp nil callback)
18100 org-warn-days)))
18102 (defun org-check-before-date (date)
18103 "Check if there are deadlines or scheduled entries before DATE."
18104 (interactive (list (org-read-date)))
18105 (let ((case-fold-search nil)
18106 (regexp (concat "\\<\\(" org-deadline-string
18107 "\\|" org-scheduled-string
18108 "\\) *<\\([^>]+\\)>"))
18109 (callback
18110 (lambda () (time-less-p
18111 (org-time-string-to-time (match-string 2))
18112 (org-time-string-to-time date)))))
18113 (message "%d entries before %s"
18114 (org-occur regexp nil callback) date)))
18116 (defun org-evaluate-time-range (&optional to-buffer)
18117 "Evaluate a time range by computing the difference between start and end.
18118 Normally the result is just printed in the echo area, but with prefix arg
18119 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
18120 If the time range is actually in a table, the result is inserted into the
18121 next column.
18122 For time difference computation, a year is assumed to be exactly 365
18123 days in order to avoid rounding problems."
18124 (interactive "P")
18126 (org-clock-update-time-maybe)
18127 (save-excursion
18128 (unless (org-at-date-range-p t)
18129 (goto-char (point-at-bol))
18130 (re-search-forward org-tr-regexp-both (point-at-eol) t))
18131 (if (not (org-at-date-range-p t))
18132 (error "Not at a time-stamp range, and none found in current line")))
18133 (let* ((ts1 (match-string 1))
18134 (ts2 (match-string 2))
18135 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
18136 (match-end (match-end 0))
18137 (time1 (org-time-string-to-time ts1))
18138 (time2 (org-time-string-to-time ts2))
18139 (t1 (time-to-seconds time1))
18140 (t2 (time-to-seconds time2))
18141 (diff (abs (- t2 t1)))
18142 (negative (< (- t2 t1) 0))
18143 ;; (ys (floor (* 365 24 60 60)))
18144 (ds (* 24 60 60))
18145 (hs (* 60 60))
18146 (fy "%dy %dd %02d:%02d")
18147 (fy1 "%dy %dd")
18148 (fd "%dd %02d:%02d")
18149 (fd1 "%dd")
18150 (fh "%02d:%02d")
18151 y d h m align)
18152 (if havetime
18153 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18155 d (floor (/ diff ds)) diff (mod diff ds)
18156 h (floor (/ diff hs)) diff (mod diff hs)
18157 m (floor (/ diff 60)))
18158 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18160 d (floor (+ (/ diff ds) 0.5))
18161 h 0 m 0))
18162 (if (not to-buffer)
18163 (message "%s" (org-make-tdiff-string y d h m))
18164 (if (org-at-table-p)
18165 (progn
18166 (goto-char match-end)
18167 (setq align t)
18168 (and (looking-at " *|") (goto-char (match-end 0))))
18169 (goto-char match-end))
18170 (if (looking-at
18171 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
18172 (replace-match ""))
18173 (if negative (insert " -"))
18174 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
18175 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
18176 (insert " " (format fh h m))))
18177 (if align (org-table-align))
18178 (message "Time difference inserted")))))
18180 (defun org-make-tdiff-string (y d h m)
18181 (let ((fmt "")
18182 (l nil))
18183 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
18184 l (push y l)))
18185 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
18186 l (push d l)))
18187 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
18188 l (push h l)))
18189 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
18190 l (push m l)))
18191 (apply 'format fmt (nreverse l))))
18193 (defun org-time-string-to-time (s)
18194 (apply 'encode-time (org-parse-time-string s)))
18196 (defun org-time-string-to-absolute (s &optional daynr prefer)
18197 "Convert a time stamp to an absolute day number.
18198 If there is a specifyer for a cyclic time stamp, get the closest date to
18199 DAYNR."
18200 (cond
18201 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
18202 (if (org-diary-sexp-entry (match-string 1 s) "" date)
18203 daynr
18204 (+ daynr 1000)))
18205 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
18206 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
18207 (time-to-days (current-time))) (match-string 0 s)
18208 prefer))
18209 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
18211 (defun org-time-from-absolute (d)
18212 "Return the time corresponding to date D.
18213 D may be an absolute day number, or a calendar-type list (month day year)."
18214 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
18215 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
18217 (defun org-calendar-holiday ()
18218 "List of holidays, for Diary display in Org-mode."
18219 (require 'holidays)
18220 (let ((hl (funcall
18221 (if (fboundp 'calendar-check-holidays)
18222 'calendar-check-holidays 'check-calendar-holidays) date)))
18223 (if hl (mapconcat 'identity hl "; "))))
18225 (defun org-diary-sexp-entry (sexp entry date)
18226 "Process a SEXP diary ENTRY for DATE."
18227 (require 'diary-lib)
18228 (let ((result (if calendar-debug-sexp
18229 (let ((stack-trace-on-error t))
18230 (eval (car (read-from-string sexp))))
18231 (condition-case nil
18232 (eval (car (read-from-string sexp)))
18233 (error
18234 (beep)
18235 (message "Bad sexp at line %d in %s: %s"
18236 (org-current-line)
18237 (buffer-file-name) sexp)
18238 (sleep-for 2))))))
18239 (cond ((stringp result) result)
18240 ((and (consp result)
18241 (stringp (cdr result))) (cdr result))
18242 (result entry)
18243 (t nil))))
18245 (defun org-diary-to-ical-string (frombuf)
18246 "Get iCalendar entries from diary entries in buffer FROMBUF.
18247 This uses the icalendar.el library."
18248 (let* ((tmpdir (if (featurep 'xemacs)
18249 (temp-directory)
18250 temporary-file-directory))
18251 (tmpfile (make-temp-name
18252 (expand-file-name "orgics" tmpdir)))
18253 buf rtn b e)
18254 (save-excursion
18255 (set-buffer frombuf)
18256 (icalendar-export-region (point-min) (point-max) tmpfile)
18257 (setq buf (find-buffer-visiting tmpfile))
18258 (set-buffer buf)
18259 (goto-char (point-min))
18260 (if (re-search-forward "^BEGIN:VEVENT" nil t)
18261 (setq b (match-beginning 0)))
18262 (goto-char (point-max))
18263 (if (re-search-backward "^END:VEVENT" nil t)
18264 (setq e (match-end 0)))
18265 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
18266 (kill-buffer buf)
18267 (kill-buffer frombuf)
18268 (delete-file tmpfile)
18269 rtn))
18271 (defun org-closest-date (start current change prefer)
18272 "Find the date closest to CURRENT that is consistent with START and CHANGE.
18273 When PREFER is `past' return a date that is either CURRENT or past.
18274 When PREFER is `future', return a date that is either CURRENT or future."
18275 ;; Make the proper lists from the dates
18276 (catch 'exit
18277 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
18278 dn dw sday cday n1 n2
18279 d m y y1 y2 date1 date2 nmonths nm ny m2)
18281 (setq start (org-date-to-gregorian start)
18282 current (org-date-to-gregorian
18283 (if org-agenda-repeating-timestamp-show-all
18284 current
18285 (time-to-days (current-time))))
18286 sday (calendar-absolute-from-gregorian start)
18287 cday (calendar-absolute-from-gregorian current))
18289 (if (<= cday sday) (throw 'exit sday))
18291 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
18292 (setq dn (string-to-number (match-string 1 change))
18293 dw (cdr (assoc (match-string 2 change) a1)))
18294 (error "Invalid change specifyer: %s" change))
18295 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
18296 (cond
18297 ((eq dw 'day)
18298 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
18299 n2 (+ n1 dn)))
18300 ((eq dw 'year)
18301 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
18302 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
18303 (setq date1 (list m d y1)
18304 n1 (calendar-absolute-from-gregorian date1)
18305 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
18306 n2 (calendar-absolute-from-gregorian date2)))
18307 ((eq dw 'month)
18308 ;; approx number of month between the tow dates
18309 (setq nmonths (floor (/ (- cday sday) 30.436875)))
18310 ;; How often does dn fit in there?
18311 (setq d (nth 1 start) m (car start) y (nth 2 start)
18312 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
18313 m (+ m nm)
18314 ny (floor (/ m 12))
18315 y (+ y ny)
18316 m (- m (* ny 12)))
18317 (while (> m 12) (setq m (- m 12) y (1+ y)))
18318 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
18319 (setq m2 (+ m dn) y2 y)
18320 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18321 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
18322 (while (< n2 cday)
18323 (setq n1 n2 m m2 y y2)
18324 (setq m2 (+ m dn) y2 y)
18325 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18326 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
18328 (if org-agenda-repeating-timestamp-show-all
18329 (cond
18330 ((eq prefer 'past) n1)
18331 ((eq prefer 'future) (if (= cday n1) n1 n2))
18332 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
18333 (cond
18334 ((eq prefer 'past) n1)
18335 ((eq prefer 'future) (if (= cday n1) n1 n2))
18336 (t (if (= cday n1) n1 n2)))))))
18338 (defun org-date-to-gregorian (date)
18339 "Turn any specification of DATE into a gregorian date for the calendar."
18340 (cond ((integerp date) (calendar-gregorian-from-absolute date))
18341 ((and (listp date) (= (length date) 3)) date)
18342 ((stringp date)
18343 (setq date (org-parse-time-string date))
18344 (list (nth 4 date) (nth 3 date) (nth 5 date)))
18345 ((listp date)
18346 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
18348 (defun org-parse-time-string (s &optional nodefault)
18349 "Parse the standard Org-mode time string.
18350 This should be a lot faster than the normal `parse-time-string'.
18351 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18352 hour and minute fields will be nil if not given."
18353 (if (string-match org-ts-regexp0 s)
18354 (list 0
18355 (if (or (match-beginning 8) (not nodefault))
18356 (string-to-number (or (match-string 8 s) "0")))
18357 (if (or (match-beginning 7) (not nodefault))
18358 (string-to-number (or (match-string 7 s) "0")))
18359 (string-to-number (match-string 4 s))
18360 (string-to-number (match-string 3 s))
18361 (string-to-number (match-string 2 s))
18362 nil nil nil)
18363 (make-list 9 0)))
18365 (defun org-timestamp-up (&optional arg)
18366 "Increase the date item at the cursor by one.
18367 If the cursor is on the year, change the year. If it is on the month or
18368 the day, change that.
18369 With prefix ARG, change by that many units."
18370 (interactive "p")
18371 (org-timestamp-change (prefix-numeric-value arg)))
18373 (defun org-timestamp-down (&optional arg)
18374 "Decrease the date item at the cursor by one.
18375 If the cursor is on the year, change the year. If it is on the month or
18376 the day, change that.
18377 With prefix ARG, change by that many units."
18378 (interactive "p")
18379 (org-timestamp-change (- (prefix-numeric-value arg))))
18381 (defun org-timestamp-up-day (&optional arg)
18382 "Increase the date in the time stamp by one day.
18383 With prefix ARG, change that many days."
18384 (interactive "p")
18385 (if (and (not (org-at-timestamp-p t))
18386 (org-on-heading-p))
18387 (org-todo 'up)
18388 (org-timestamp-change (prefix-numeric-value arg) 'day)))
18390 (defun org-timestamp-down-day (&optional arg)
18391 "Decrease the date in the time stamp by one day.
18392 With prefix ARG, change that many days."
18393 (interactive "p")
18394 (if (and (not (org-at-timestamp-p t))
18395 (org-on-heading-p))
18396 (org-todo 'down)
18397 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
18399 (defsubst org-pos-in-match-range (pos n)
18400 (and (match-beginning n)
18401 (<= (match-beginning n) pos)
18402 (>= (match-end n) pos)))
18404 (defun org-at-timestamp-p (&optional inactive-ok)
18405 "Determine if the cursor is in or at a timestamp."
18406 (interactive)
18407 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18408 (pos (point))
18409 (ans (or (looking-at tsr)
18410 (save-excursion
18411 (skip-chars-backward "^[<\n\r\t")
18412 (if (> (point) (point-min)) (backward-char 1))
18413 (and (looking-at tsr)
18414 (> (- (match-end 0) pos) -1))))))
18415 (and ans
18416 (boundp 'org-ts-what)
18417 (setq org-ts-what
18418 (cond
18419 ((= pos (match-beginning 0)) 'bracket)
18420 ((= pos (1- (match-end 0))) 'bracket)
18421 ((org-pos-in-match-range pos 2) 'year)
18422 ((org-pos-in-match-range pos 3) 'month)
18423 ((org-pos-in-match-range pos 7) 'hour)
18424 ((org-pos-in-match-range pos 8) 'minute)
18425 ((or (org-pos-in-match-range pos 4)
18426 (org-pos-in-match-range pos 5)) 'day)
18427 ((and (> pos (or (match-end 8) (match-end 5)))
18428 (< pos (match-end 0)))
18429 (- pos (or (match-end 8) (match-end 5))))
18430 (t 'day))))
18431 ans))
18433 (defun org-toggle-timestamp-type ()
18435 (interactive)
18436 (when (org-at-timestamp-p t)
18437 (save-excursion
18438 (goto-char (match-beginning 0))
18439 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18440 (goto-char (1- (match-end 0)))
18441 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18442 (message "Timestamp is now %sactive"
18443 (if (equal (char-before) ?>) "in" ""))))
18445 (defun org-timestamp-change (n &optional what)
18446 "Change the date in the time stamp at point.
18447 The date will be changed by N times WHAT. WHAT can be `day', `month',
18448 `year', `minute', `second'. If WHAT is not given, the cursor position
18449 in the timestamp determines what will be changed."
18450 (let ((pos (point))
18451 with-hm inactive
18452 org-ts-what
18453 extra
18454 ts time time0)
18455 (if (not (org-at-timestamp-p t))
18456 (error "Not at a timestamp"))
18457 (if (and (not what) (eq org-ts-what 'bracket))
18458 (org-toggle-timestamp-type)
18459 (if (and (not what) (not (eq org-ts-what 'day))
18460 org-display-custom-times
18461 (get-text-property (point) 'display)
18462 (not (get-text-property (1- (point)) 'display)))
18463 (setq org-ts-what 'day))
18464 (setq org-ts-what (or what org-ts-what)
18465 inactive (= (char-after (match-beginning 0)) ?\[)
18466 ts (match-string 0))
18467 (replace-match "")
18468 (if (string-match
18469 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
18471 (setq extra (match-string 1 ts)))
18472 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18473 (setq with-hm t))
18474 (setq time0 (org-parse-time-string ts))
18475 (setq time
18476 (encode-time (or (car time0) 0)
18477 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18478 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18479 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18480 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18481 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18482 (nthcdr 6 time0)))
18483 (when (integerp org-ts-what)
18484 (setq extra (org-modify-ts-extra extra org-ts-what n)))
18485 (if (eq what 'calendar)
18486 (let ((cal-date (org-get-date-from-calendar)))
18487 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18488 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18489 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18490 (setcar time0 (or (car time0) 0))
18491 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18492 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18493 (setq time (apply 'encode-time time0))))
18494 (setq org-last-changed-timestamp
18495 (org-insert-time-stamp time with-hm inactive nil nil extra))
18496 (org-clock-update-time-maybe)
18497 (goto-char pos)
18498 ;; Try to recenter the calendar window, if any
18499 (if (and org-calendar-follow-timestamp-change
18500 (get-buffer-window "*Calendar*" t)
18501 (memq org-ts-what '(day month year)))
18502 (org-recenter-calendar (time-to-days time))))))
18504 ;; FIXME: does not yet work for lead times
18505 (defun org-modify-ts-extra (s pos n)
18506 "Change the different parts of the lead-time and repeat fields in timestamp."
18507 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18508 ng h m new)
18509 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18510 (cond
18511 ((or (org-pos-in-match-range pos 2)
18512 (org-pos-in-match-range pos 3))
18513 (setq m (string-to-number (match-string 3 s))
18514 h (string-to-number (match-string 2 s)))
18515 (if (org-pos-in-match-range pos 2)
18516 (setq h (+ h n))
18517 (setq m (+ m n)))
18518 (if (< m 0) (setq m (+ m 60) h (1- h)))
18519 (if (> m 59) (setq m (- m 60) h (1+ h)))
18520 (setq h (min 24 (max 0 h)))
18521 (setq ng 1 new (format "-%02d:%02d" h m)))
18522 ((org-pos-in-match-range pos 6)
18523 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18524 ((org-pos-in-match-range pos 5)
18525 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
18527 (when ng
18528 (setq s (concat
18529 (substring s 0 (match-beginning ng))
18531 (substring s (match-end ng))))))
18534 (defun org-recenter-calendar (date)
18535 "If the calendar is visible, recenter it to DATE."
18536 (let* ((win (selected-window))
18537 (cwin (get-buffer-window "*Calendar*" t))
18538 (calendar-move-hook nil))
18539 (when cwin
18540 (select-window cwin)
18541 (calendar-goto-date (if (listp date) date
18542 (calendar-gregorian-from-absolute date)))
18543 (select-window win))))
18545 (defun org-goto-calendar (&optional arg)
18546 "Go to the Emacs calendar at the current date.
18547 If there is a time stamp in the current line, go to that date.
18548 A prefix ARG can be used to force the current date."
18549 (interactive "P")
18550 (let ((tsr org-ts-regexp) diff
18551 (calendar-move-hook nil)
18552 (view-calendar-holidays-initially nil)
18553 (view-diary-entries-initially nil))
18554 (if (or (org-at-timestamp-p)
18555 (save-excursion
18556 (beginning-of-line 1)
18557 (looking-at (concat ".*" tsr))))
18558 (let ((d1 (time-to-days (current-time)))
18559 (d2 (time-to-days
18560 (org-time-string-to-time (match-string 1)))))
18561 (setq diff (- d2 d1))))
18562 (calendar)
18563 (calendar-goto-today)
18564 (if (and diff (not arg)) (calendar-forward-day diff))))
18566 (defun org-get-date-from-calendar ()
18567 "Return a list (month day year) of date at point in calendar."
18568 (with-current-buffer "*Calendar*"
18569 (save-match-data
18570 (calendar-cursor-to-date))))
18572 (defun org-date-from-calendar ()
18573 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18574 If there is already a time stamp at the cursor position, update it."
18575 (interactive)
18576 (if (org-at-timestamp-p t)
18577 (org-timestamp-change 0 'calendar)
18578 (let ((cal-date (org-get-date-from-calendar)))
18579 (org-insert-time-stamp
18580 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18582 ;;;###autoload
18583 (defun org-agenda-to-appt (&optional filter)
18584 "Activate appointments found in `org-agenda-files'.
18585 When prefixed, prompt for a regular expression and use it as a
18586 filter: only add entries if they match this regular expression.
18588 FILTER can be a string. In this case, use this string as a
18589 regular expression to filter results.
18591 FILTER can also be an alist, with the car of each cell being
18592 either 'headline or 'category. For example:
18594 '((headline \"IMPORTANT\")
18595 (category \"Work\"))
18597 will only add headlines containing IMPORTANT or headlines
18598 belonging to the category \"Work\"."
18599 (interactive "P")
18600 (require 'calendar)
18601 (require 'appt)
18602 (setq appt-time-msg-list nil)
18603 (save-window-excursion (appt-check t))
18604 (if (equal filter '(4))
18605 (setq filter (read-from-minibuffer "Regexp filter: ")))
18606 (let* ((cnt 0) ; count added events
18607 (org-agenda-new-buffers nil)
18608 (today (org-date-to-gregorian
18609 (time-to-days (current-time))))
18610 (files (org-agenda-files)) entries file)
18611 ;; Get all entries which may contain an appt
18612 (while (setq file (pop files))
18613 (setq entries
18614 (append entries
18615 (org-agenda-get-day-entries
18616 file today :timestamp :scheduled))))
18617 (setq entries (delq nil entries))
18618 ;; Map thru entries and find if we should filter them out
18619 (mapc
18620 (lambda(x)
18621 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18622 (cat (get-text-property 1 'org-category x))
18623 (tod (get-text-property 1 'time-of-day x))
18624 (ok (or (null filter)
18625 (and (stringp filter) (string-match filter evt))
18626 (and (listp filter)
18627 (or (string-match
18628 (cadr (assoc 'category filter)) cat)
18629 (string-match
18630 (cadr (assoc 'headline filter)) evt))))))
18631 ;; FIXME: Shall we remove text-properties for the appt text?
18632 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18633 (when (and ok tod)
18634 (setq tod (number-to-string tod)
18635 tod (when (string-match
18636 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18637 (concat (match-string 1 tod) ":"
18638 (match-string 2 tod))))
18639 (appt-add tod evt)
18640 (setq cnt (1+ cnt))))) entries)
18641 (org-release-buffers org-agenda-new-buffers)
18642 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" ""))))
18644 ;;; The clock for measuring work time.
18646 (defvar org-mode-line-string "")
18647 (put 'org-mode-line-string 'risky-local-variable t)
18649 (defvar org-mode-line-timer nil)
18650 (defvar org-clock-heading "")
18651 (defvar org-clock-start-time "")
18653 (defun org-update-mode-line ()
18654 (let* ((delta (- (time-to-seconds (current-time))
18655 (time-to-seconds org-clock-start-time)))
18656 (h (floor delta 3600))
18657 (m (floor (- delta (* 3600 h)) 60)))
18658 (setq org-mode-line-string
18659 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18660 'help-echo "Org-mode clock is running"))
18661 (force-mode-line-update)))
18663 (defvar org-clock-marker (make-marker)
18664 "Marker recording the last clock-in.")
18665 (defvar org-clock-mode-line-entry nil
18666 "Information for the modeline about the running clock.")
18668 (defun org-clock-in ()
18669 "Start the clock on the current item.
18670 If necessary, clock-out of the currently active clock."
18671 (interactive)
18672 (org-clock-out t)
18673 (let (ts)
18674 (save-excursion
18675 (org-back-to-heading t)
18676 (when (and org-clock-in-switch-to-state
18677 (not (looking-at (concat outline-regexp "[ \t]*"
18678 org-clock-in-switch-to-state
18679 "\\>"))))
18680 (org-todo org-clock-in-switch-to-state))
18681 (if (and org-clock-heading-function
18682 (functionp org-clock-heading-function))
18683 (setq org-clock-heading (funcall org-clock-heading-function))
18684 (if (looking-at org-complex-heading-regexp)
18685 (setq org-clock-heading (match-string 4))
18686 (setq org-clock-heading "???")))
18687 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18688 (org-clock-find-position)
18690 (insert "\n") (backward-char 1)
18691 (indent-relative)
18692 (insert org-clock-string " ")
18693 (setq org-clock-start-time (current-time))
18694 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18695 (move-marker org-clock-marker (point) (buffer-base-buffer))
18696 (or global-mode-string (setq global-mode-string '("")))
18697 (or (memq 'org-mode-line-string global-mode-string)
18698 (setq global-mode-string
18699 (append global-mode-string '(org-mode-line-string))))
18700 (org-update-mode-line)
18701 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18702 (message "Clock started at %s" ts))))
18704 (defun org-clock-find-position ()
18705 "Find the location where the next clock line should be inserted."
18706 (org-back-to-heading t)
18707 (catch 'exit
18708 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
18709 (re (concat "^[ \t]*" org-clock-string))
18710 (cnt 0)
18711 first last)
18712 (goto-char beg)
18713 (when (eobp) (newline) (setq end (max (point) end)))
18714 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
18715 ;; we seem to have a CLOCK drawer, so go there.
18716 (beginning-of-line 2)
18717 (throw 'exit t))
18718 ;; Lets count the CLOCK lines
18719 (goto-char beg)
18720 (while (re-search-forward re end t)
18721 (setq first (or first (match-beginning 0))
18722 last (match-beginning 0)
18723 cnt (1+ cnt)))
18724 (when (and (integerp org-clock-into-drawer)
18725 (>= (1+ cnt) org-clock-into-drawer))
18726 ;; Wrap current entries into a new drawer
18727 (goto-char last)
18728 (beginning-of-line 2)
18729 (if (org-at-item-p) (org-end-of-item))
18730 (insert ":END:\n")
18731 (beginning-of-line 0)
18732 (org-indent-line-function)
18733 (goto-char first)
18734 (insert ":CLOCK:\n")
18735 (beginning-of-line 0)
18736 (org-indent-line-function)
18737 (org-flag-drawer t)
18738 (beginning-of-line 2)
18739 (throw 'exit nil))
18741 (goto-char beg)
18742 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18743 (not (equal (match-string 1) org-clock-string)))
18744 ;; Planning info, skip to after it
18745 (beginning-of-line 2)
18746 (or (bolp) (newline)))
18747 (when (eq t org-clock-into-drawer)
18748 (insert ":CLOCK:\n:END:\n")
18749 (beginning-of-line -1)
18750 (org-indent-line-function)
18751 (org-flag-drawer t)
18752 (beginning-of-line 2)
18753 (org-indent-line-function)))))
18755 (defun org-clock-out (&optional fail-quietly)
18756 "Stop the currently running clock.
18757 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
18758 (interactive)
18759 (catch 'exit
18760 (if (not (marker-buffer org-clock-marker))
18761 (if fail-quietly (throw 'exit t) (error "No active clock")))
18762 (let (ts te s h m)
18763 (save-excursion
18764 (set-buffer (marker-buffer org-clock-marker))
18765 (goto-char org-clock-marker)
18766 (beginning-of-line 1)
18767 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18768 (equal (match-string 1) org-clock-string))
18769 (setq ts (match-string 2))
18770 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
18771 (goto-char (match-end 0))
18772 (delete-region (point) (point-at-eol))
18773 (insert "--")
18774 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18775 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
18776 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
18777 h (floor (/ s 3600))
18778 s (- s (* 3600 h))
18779 m (floor (/ s 60))
18780 s (- s (* 60 s)))
18781 (insert " => " (format "%2d:%02d" h m))
18782 (move-marker org-clock-marker nil)
18783 (when org-log-note-clock-out
18784 (org-add-log-maybe 'clock-out))
18785 (when org-mode-line-timer
18786 (cancel-timer org-mode-line-timer)
18787 (setq org-mode-line-timer nil))
18788 (setq global-mode-string
18789 (delq 'org-mode-line-string global-mode-string))
18790 (force-mode-line-update)
18791 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
18793 (defun org-clock-cancel ()
18794 "Cancel the running clock be removing the start timestamp."
18795 (interactive)
18796 (if (not (marker-buffer org-clock-marker))
18797 (error "No active clock"))
18798 (save-excursion
18799 (set-buffer (marker-buffer org-clock-marker))
18800 (goto-char org-clock-marker)
18801 (delete-region (1- (point-at-bol)) (point-at-eol)))
18802 (setq global-mode-string
18803 (delq 'org-mode-line-string global-mode-string))
18804 (force-mode-line-update)
18805 (message "Clock canceled"))
18807 (defun org-clock-goto (&optional delete-windows)
18808 "Go to the currently clocked-in entry."
18809 (interactive "P")
18810 (if (not (marker-buffer org-clock-marker))
18811 (error "No active clock"))
18812 (switch-to-buffer-other-window
18813 (marker-buffer org-clock-marker))
18814 (if delete-windows (delete-other-windows))
18815 (goto-char org-clock-marker)
18816 (org-show-entry)
18817 (org-back-to-heading)
18818 (recenter))
18820 (defvar org-clock-file-total-minutes nil
18821 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
18822 (make-variable-buffer-local 'org-clock-file-total-minutes)
18824 (defun org-clock-sum (&optional tstart tend)
18825 "Sum the times for each subtree.
18826 Puts the resulting times in minutes as a text property on each headline."
18827 (interactive)
18828 (let* ((bmp (buffer-modified-p))
18829 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
18830 org-clock-string
18831 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
18832 (lmax 30)
18833 (ltimes (make-vector lmax 0))
18834 (t1 0)
18835 (level 0)
18836 ts te dt
18837 time)
18838 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
18839 (save-excursion
18840 (goto-char (point-max))
18841 (while (re-search-backward re nil t)
18842 (cond
18843 ((match-end 2)
18844 ;; Two time stamps
18845 (setq ts (match-string 2)
18846 te (match-string 3)
18847 ts (time-to-seconds
18848 (apply 'encode-time (org-parse-time-string ts)))
18849 te (time-to-seconds
18850 (apply 'encode-time (org-parse-time-string te)))
18851 ts (if tstart (max ts tstart) ts)
18852 te (if tend (min te tend) te)
18853 dt (- te ts)
18854 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
18855 ((match-end 4)
18856 ;; A naket time
18857 (setq t1 (+ t1 (string-to-number (match-string 5))
18858 (* 60 (string-to-number (match-string 4))))))
18859 (t ;; A headline
18860 (setq level (- (match-end 1) (match-beginning 1)))
18861 (when (or (> t1 0) (> (aref ltimes level) 0))
18862 (loop for l from 0 to level do
18863 (aset ltimes l (+ (aref ltimes l) t1)))
18864 (setq t1 0 time (aref ltimes level))
18865 (loop for l from level to (1- lmax) do
18866 (aset ltimes l 0))
18867 (goto-char (match-beginning 0))
18868 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
18869 (setq org-clock-file-total-minutes (aref ltimes 0)))
18870 (set-buffer-modified-p bmp)))
18872 (defun org-clock-display (&optional total-only)
18873 "Show subtree times in the entire buffer.
18874 If TOTAL-ONLY is non-nil, only show the total time for the entire file
18875 in the echo area."
18876 (interactive)
18877 (org-remove-clock-overlays)
18878 (let (time h m p)
18879 (org-clock-sum)
18880 (unless total-only
18881 (save-excursion
18882 (goto-char (point-min))
18883 (while (or (and (equal (setq p (point)) (point-min))
18884 (get-text-property p :org-clock-minutes))
18885 (setq p (next-single-property-change
18886 (point) :org-clock-minutes)))
18887 (goto-char p)
18888 (when (setq time (get-text-property p :org-clock-minutes))
18889 (org-put-clock-overlay time (funcall outline-level))))
18890 (setq h (/ org-clock-file-total-minutes 60)
18891 m (- org-clock-file-total-minutes (* 60 h)))
18892 ;; Arrange to remove the overlays upon next change.
18893 (when org-remove-highlights-with-change
18894 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
18895 nil 'local))))
18896 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
18898 (defvar org-clock-overlays nil)
18899 (make-variable-buffer-local 'org-clock-overlays)
18901 (defun org-put-clock-overlay (time &optional level)
18902 "Put an overlays on the current line, displaying TIME.
18903 If LEVEL is given, prefix time with a corresponding number of stars.
18904 This creates a new overlay and stores it in `org-clock-overlays', so that it
18905 will be easy to remove."
18906 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
18907 (l (if level (org-get-legal-level level 0) 0))
18908 (off 0)
18909 ov tx)
18910 (move-to-column c)
18911 (unless (eolp) (skip-chars-backward "^ \t"))
18912 (skip-chars-backward " \t")
18913 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
18914 tx (concat (buffer-substring (1- (point)) (point))
18915 (make-string (+ off (max 0 (- c (current-column)))) ?.)
18916 (org-add-props (format "%s %2d:%02d%s"
18917 (make-string l ?*) h m
18918 (make-string (- 10 l) ?\ ))
18919 '(face secondary-selection))
18920 ""))
18921 (if (not (featurep 'xemacs))
18922 (org-overlay-put ov 'display tx)
18923 (org-overlay-put ov 'invisible t)
18924 (org-overlay-put ov 'end-glyph (make-glyph tx)))
18925 (push ov org-clock-overlays)))
18927 (defun org-remove-clock-overlays (&optional beg end noremove)
18928 "Remove the occur highlights from the buffer.
18929 BEG and END are ignored. If NOREMOVE is nil, remove this function
18930 from the `before-change-functions' in the current buffer."
18931 (interactive)
18932 (unless org-inhibit-highlight-removal
18933 (mapc 'org-delete-overlay org-clock-overlays)
18934 (setq org-clock-overlays nil)
18935 (unless noremove
18936 (remove-hook 'before-change-functions
18937 'org-remove-clock-overlays 'local))))
18939 (defun org-clock-out-if-current ()
18940 "Clock out if the current entry contains the running clock.
18941 This is used to stop the clock after a TODO entry is marked DONE,
18942 and is only done if the variable `org-clock-out-when-done' is not nil."
18943 (when (and org-clock-out-when-done
18944 (member state org-done-keywords)
18945 (equal (marker-buffer org-clock-marker) (current-buffer))
18946 (< (point) org-clock-marker)
18947 (> (save-excursion (outline-next-heading) (point))
18948 org-clock-marker))
18949 ;; Clock out, but don't accept a logging message for this.
18950 (let ((org-log-note-clock-out nil))
18951 (org-clock-out))))
18953 (add-hook 'org-after-todo-state-change-hook
18954 'org-clock-out-if-current)
18956 (defun org-check-running-clock ()
18957 "Check if the current buffer contains the running clock.
18958 If yes, offer to stop it and to save the buffer with the changes."
18959 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
18960 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
18961 (buffer-name))))
18962 (org-clock-out)
18963 (when (y-or-n-p "Save changed buffer?")
18964 (save-buffer))))
18966 (defun org-clock-report (&optional arg)
18967 "Create a table containing a report about clocked time.
18968 If the cursor is inside an existing clocktable block, then the table
18969 will be updated. If not, a new clocktable will be inserted.
18970 When called with a prefix argument, move to the first clock table in the
18971 buffer and update it."
18972 (interactive "P")
18973 (org-remove-clock-overlays)
18974 (when arg
18975 (org-find-dblock "clocktable")
18976 (org-show-entry))
18977 (if (org-in-clocktable-p)
18978 (goto-char (org-in-clocktable-p))
18979 (org-create-dblock (list :name "clocktable"
18980 :maxlevel 2 :scope 'file)))
18981 (org-update-dblock))
18983 (defun org-in-clocktable-p ()
18984 "Check if the cursor is in a clocktable."
18985 (let ((pos (point)) start)
18986 (save-excursion
18987 (end-of-line 1)
18988 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
18989 (setq start (match-beginning 0))
18990 (re-search-forward "^#\\+END:.*" nil t)
18991 (>= (match-end 0) pos)
18992 start))))
18994 (defun org-clock-update-time-maybe ()
18995 "If this is a CLOCK line, update it and return t.
18996 Otherwise, return nil."
18997 (interactive)
18998 (save-excursion
18999 (beginning-of-line 1)
19000 (skip-chars-forward " \t")
19001 (when (looking-at org-clock-string)
19002 (let ((re (concat "[ \t]*" org-clock-string
19003 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
19004 "\\([ \t]*=>.*\\)?"))
19005 ts te h m s)
19006 (if (not (looking-at re))
19008 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
19009 (end-of-line 1)
19010 (setq ts (match-string 1)
19011 te (match-string 2))
19012 (setq s (- (time-to-seconds
19013 (apply 'encode-time (org-parse-time-string te)))
19014 (time-to-seconds
19015 (apply 'encode-time (org-parse-time-string ts))))
19016 h (floor (/ s 3600))
19017 s (- s (* 3600 h))
19018 m (floor (/ s 60))
19019 s (- s (* 60 s)))
19020 (insert " => " (format "%2d:%02d" h m))
19021 t)))))
19023 (defun org-clock-special-range (key &optional time as-strings)
19024 "Return two times bordering a special time range.
19025 Key is a symbol specifying the range and can be one of `today', `yesterday',
19026 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
19027 A week starts Monday 0:00 and ends Sunday 24:00.
19028 The range is determined relative to TIME. TIME defaults to the current time.
19029 The return value is a cons cell with two internal times like the ones
19030 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
19031 the returned times will be formatted strings."
19032 (let* ((tm (decode-time (or time (current-time))))
19033 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
19034 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
19035 (dow (nth 6 tm))
19036 s1 m1 h1 d1 month1 y1 diff ts te fm)
19037 (cond
19038 ((eq key 'today)
19039 (setq h 0 m 0 h1 24 m1 0))
19040 ((eq key 'yesterday)
19041 (setq d (1- d) h 0 m 0 h1 24 m1 0))
19042 ((eq key 'thisweek)
19043 (setq diff (if (= dow 0) 6 (1- dow))
19044 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19045 ((eq key 'lastweek)
19046 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
19047 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19048 ((eq key 'thismonth)
19049 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
19050 ((eq key 'lastmonth)
19051 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
19052 ((eq key 'thisyear)
19053 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
19054 ((eq key 'lastyear)
19055 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
19056 (t (error "No such time block %s" key)))
19057 (setq ts (encode-time s m h d month y)
19058 te (encode-time (or s1 s) (or m1 m) (or h1 h)
19059 (or d1 d) (or month1 month) (or y1 y)))
19060 (setq fm (cdr org-time-stamp-formats))
19061 (if as-strings
19062 (cons (format-time-string fm ts) (format-time-string fm te))
19063 (cons ts te))))
19065 (defun org-dblock-write:clocktable (params)
19066 "Write the standard clocktable."
19067 (catch 'exit
19068 (let* ((hlchars '((1 . "*") (2 . "/")))
19069 (ins (make-marker))
19070 (total-time nil)
19071 (scope (plist-get params :scope))
19072 (tostring (plist-get params :tostring))
19073 (multifile (plist-get params :multifile))
19074 (header (plist-get params :header))
19075 (maxlevel (or (plist-get params :maxlevel) 3))
19076 (step (plist-get params :step))
19077 (emph (plist-get params :emphasize))
19078 (ts (plist-get params :tstart))
19079 (te (plist-get params :tend))
19080 (block (plist-get params :block))
19081 ipos time h m p level hlc hdl
19082 cc beg end pos tbl)
19083 (when step
19084 (org-clocktable-steps params)
19085 (throw 'exit nil))
19086 (when block
19087 (setq cc (org-clock-special-range block nil t)
19088 ts (car cc) te (cdr cc)))
19089 (if ts (setq ts (time-to-seconds
19090 (apply 'encode-time (org-parse-time-string ts)))))
19091 (if te (setq te (time-to-seconds
19092 (apply 'encode-time (org-parse-time-string te)))))
19093 (move-marker ins (point))
19094 (setq ipos (point))
19096 ;; Get the right scope
19097 (setq pos (point))
19098 (save-restriction
19099 (cond
19100 ((not scope))
19101 ((eq scope 'file) (widen))
19102 ((eq scope 'subtree) (org-narrow-to-subtree))
19103 ((eq scope 'tree)
19104 (while (org-up-heading-safe))
19105 (org-narrow-to-subtree))
19106 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
19107 (symbol-name scope)))
19108 (setq level (string-to-number (match-string 1 (symbol-name scope))))
19109 (catch 'exit
19110 (while (org-up-heading-safe)
19111 (looking-at outline-regexp)
19112 (if (<= (org-reduced-level (funcall outline-level)) level)
19113 (throw 'exit nil))))
19114 (org-narrow-to-subtree))
19115 ((or (listp scope) (eq scope 'agenda))
19116 (let* ((files (if (listp scope) scope (org-agenda-files)))
19117 (scope 'agenda)
19118 (p1 (copy-sequence params))
19119 file)
19120 (plist-put p1 :tostring t)
19121 (plist-put p1 :multifile t)
19122 (plist-put p1 :scope 'file)
19123 (org-prepare-agenda-buffers files)
19124 (while (setq file (pop files))
19125 (with-current-buffer (find-buffer-visiting file)
19126 (push (org-clocktable-add-file
19127 file (org-dblock-write:clocktable p1)) tbl)
19128 (setq total-time (+ (or total-time 0)
19129 org-clock-file-total-minutes)))))))
19130 (goto-char pos)
19132 (unless (eq scope 'agenda)
19133 (org-clock-sum ts te)
19134 (goto-char (point-min))
19135 (while (setq p (next-single-property-change (point) :org-clock-minutes))
19136 (goto-char p)
19137 (when (setq time (get-text-property p :org-clock-minutes))
19138 (save-excursion
19139 (beginning-of-line 1)
19140 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
19141 (setq level (org-reduced-level
19142 (- (match-end 1) (match-beginning 1))))
19143 (<= level maxlevel))
19144 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
19145 hdl (match-string 2)
19146 h (/ time 60)
19147 m (- time (* 60 h)))
19148 (if (and (not multifile) (= level 1)) (push "|-" tbl))
19149 (push (concat
19150 "| " (int-to-string level) "|" hlc hdl hlc " |"
19151 (make-string (1- level) ?|)
19152 hlc (format "%d:%02d" h m) hlc
19153 " |") tbl))))))
19154 (setq tbl (nreverse tbl))
19155 (if tostring
19156 (if tbl (mapconcat 'identity tbl "\n") nil)
19157 (goto-char ins)
19158 (insert-before-markers
19159 (or header
19160 (concat
19161 "Clock summary at ["
19162 (substring
19163 (format-time-string (cdr org-time-stamp-formats))
19164 1 -1)
19165 "]."
19166 (if block
19167 (format " Considered range is /%s/." block)
19169 "\n\n"))
19170 (if (eq scope 'agenda) "|File" "")
19171 "|L|Headline|Time|\n")
19172 (setq total-time (or total-time org-clock-file-total-minutes)
19173 h (/ total-time 60)
19174 m (- total-time (* 60 h)))
19175 (insert-before-markers
19176 "|-\n|"
19177 (if (eq scope 'agenda) "|" "")
19179 "*Total time*| "
19180 (format "*%d:%02d*" h m)
19181 "|\n|-\n")
19182 (setq tbl (delq nil tbl))
19183 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
19184 (equal (substring (car tbl) 0 2) "|-"))
19185 (pop tbl))
19186 (insert-before-markers (mapconcat
19187 'identity (delq nil tbl)
19188 (if (eq scope 'agenda) "\n|-\n" "\n")))
19189 (backward-delete-char 1)
19190 (goto-char ipos)
19191 (skip-chars-forward "^|")
19192 (org-table-align))))))
19194 (defun org-clocktable-steps (params)
19195 (let* ((p1 (copy-sequence params))
19196 (ts (plist-get p1 :tstart))
19197 (te (plist-get p1 :tend))
19198 (step0 (plist-get p1 :step))
19199 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
19200 (block (plist-get p1 :block))
19202 (when block
19203 (setq cc (org-clock-special-range block nil t)
19204 ts (car cc) te (cdr cc)))
19205 (if ts (setq ts (time-to-seconds
19206 (apply 'encode-time (org-parse-time-string ts)))))
19207 (if te (setq te (time-to-seconds
19208 (apply 'encode-time (org-parse-time-string te)))))
19209 (plist-put p1 :header "")
19210 (plist-put p1 :step nil)
19211 (plist-put p1 :block nil)
19212 (while (< ts te)
19213 (or (bolp) (insert "\n"))
19214 (plist-put p1 :tstart (format-time-string
19215 (car org-time-stamp-formats)
19216 (seconds-to-time ts)))
19217 (plist-put p1 :tend (format-time-string
19218 (car org-time-stamp-formats)
19219 (seconds-to-time (setq ts (+ ts step)))))
19220 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
19221 (plist-get p1 :tstart) "\n")
19222 (org-dblock-write:clocktable p1)
19223 (re-search-forward "#\\+END:")
19224 (end-of-line 0))))
19227 (defun org-clocktable-add-file (file table)
19228 (if table
19229 (let ((lines (org-split-string table "\n"))
19230 (ff (file-name-nondirectory file)))
19231 (mapconcat 'identity
19232 (mapcar (lambda (x)
19233 (if (string-match org-table-dataline-regexp x)
19234 (concat "|" ff x)
19236 lines)
19237 "\n"))))
19239 ;; FIXME: I don't think anybody uses this, ask David
19240 (defun org-collect-clock-time-entries ()
19241 "Return an internal list with clocking information.
19242 This list has one entry for each CLOCK interval.
19243 FIXME: describe the elements."
19244 (interactive)
19245 (let ((re (concat "^[ \t]*" org-clock-string
19246 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
19247 rtn beg end next cont level title total closedp leafp
19248 clockpos titlepos h m donep)
19249 (save-excursion
19250 (org-clock-sum)
19251 (goto-char (point-min))
19252 (while (re-search-forward re nil t)
19253 (setq clockpos (match-beginning 0)
19254 beg (match-string 1) end (match-string 2)
19255 cont (match-end 0))
19256 (setq beg (apply 'encode-time (org-parse-time-string beg))
19257 end (apply 'encode-time (org-parse-time-string end)))
19258 (org-back-to-heading t)
19259 (setq donep (org-entry-is-done-p))
19260 (setq titlepos (point)
19261 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
19262 h (/ total 60) m (- total (* 60 h))
19263 total (cons h m))
19264 (looking-at "\\(\\*+\\) +\\(.*\\)")
19265 (setq level (- (match-end 1) (match-beginning 1))
19266 title (org-match-string-no-properties 2))
19267 (save-excursion (outline-next-heading) (setq next (point)))
19268 (setq closedp (re-search-forward org-closed-time-regexp next t))
19269 (goto-char next)
19270 (setq leafp (and (looking-at "^\\*+ ")
19271 (<= (- (match-end 0) (point)) level)))
19272 (push (list beg end clockpos closedp donep
19273 total title titlepos level leafp)
19274 rtn)
19275 (goto-char cont)))
19276 (nreverse rtn)))
19278 ;;;; Agenda, and Diary Integration
19280 ;;; Define the Org-agenda-mode
19282 (defvar org-agenda-mode-map (make-sparse-keymap)
19283 "Keymap for `org-agenda-mode'.")
19285 (defvar org-agenda-menu) ; defined later in this file.
19286 (defvar org-agenda-follow-mode nil)
19287 (defvar org-agenda-show-log nil)
19288 (defvar org-agenda-redo-command nil)
19289 (defvar org-agenda-mode-hook nil)
19290 (defvar org-agenda-type nil)
19291 (defvar org-agenda-force-single-file nil)
19293 (defun org-agenda-mode ()
19294 "Mode for time-sorted view on action items in Org-mode files.
19296 The following commands are available:
19298 \\{org-agenda-mode-map}"
19299 (interactive)
19300 (kill-all-local-variables)
19301 (setq org-agenda-undo-list nil
19302 org-agenda-pending-undo-list nil)
19303 (setq major-mode 'org-agenda-mode)
19304 ;; Keep global-font-lock-mode from turning on font-lock-mode
19305 (org-set-local 'font-lock-global-modes (list 'not major-mode))
19306 (setq mode-name "Org-Agenda")
19307 (use-local-map org-agenda-mode-map)
19308 (easy-menu-add org-agenda-menu)
19309 (if org-startup-truncated (setq truncate-lines t))
19310 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
19311 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
19312 ;; Make sure properties are removed when copying text
19313 (when (boundp 'buffer-substring-filters)
19314 (org-set-local 'buffer-substring-filters
19315 (cons (lambda (x)
19316 (set-text-properties 0 (length x) nil x) x)
19317 buffer-substring-filters)))
19318 (unless org-agenda-keep-modes
19319 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
19320 org-agenda-show-log nil))
19321 (easy-menu-change
19322 '("Agenda") "Agenda Files"
19323 (append
19324 (list
19325 (vector
19326 (if (get 'org-agenda-files 'org-restrict)
19327 "Restricted to single file"
19328 "Edit File List")
19329 '(org-edit-agenda-file-list)
19330 (not (get 'org-agenda-files 'org-restrict)))
19331 "--")
19332 (mapcar 'org-file-menu-entry (org-agenda-files))))
19333 (org-agenda-set-mode-name)
19334 (apply
19335 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
19336 (list 'org-agenda-mode-hook)))
19338 (substitute-key-definition 'undo 'org-agenda-undo
19339 org-agenda-mode-map global-map)
19340 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
19341 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
19342 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
19343 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
19344 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
19345 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
19346 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
19347 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
19348 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
19349 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
19350 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
19351 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
19352 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
19353 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
19354 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
19355 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
19356 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
19357 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
19358 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
19359 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
19360 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
19361 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
19362 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
19363 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
19364 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
19365 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
19366 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
19367 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
19368 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
19370 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
19371 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
19372 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
19373 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
19374 (while l (org-defkey org-agenda-mode-map
19375 (int-to-string (pop l)) 'digit-argument)))
19377 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
19378 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
19379 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
19380 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
19381 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
19382 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
19383 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
19384 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
19385 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
19386 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
19387 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
19388 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
19389 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
19390 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
19391 (org-defkey org-agenda-mode-map "n" 'next-line)
19392 (org-defkey org-agenda-mode-map "p" 'previous-line)
19393 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
19394 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
19395 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
19396 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
19397 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
19398 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
19399 (eval-after-load "calendar"
19400 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
19401 'org-calendar-goto-agenda))
19402 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
19403 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
19404 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
19405 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
19406 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
19407 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
19408 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
19409 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
19410 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
19411 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
19412 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
19413 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19414 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
19415 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
19416 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
19417 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
19418 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
19419 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
19420 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
19421 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
19422 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
19423 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
19425 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
19426 "Local keymap for agenda entries from Org-mode.")
19428 (org-defkey org-agenda-keymap
19429 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
19430 (org-defkey org-agenda-keymap
19431 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
19432 (when org-agenda-mouse-1-follows-link
19433 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
19434 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
19435 '("Agenda"
19436 ("Agenda Files")
19437 "--"
19438 ["Show" org-agenda-show t]
19439 ["Go To (other window)" org-agenda-goto t]
19440 ["Go To (this window)" org-agenda-switch-to t]
19441 ["Follow Mode" org-agenda-follow-mode
19442 :style toggle :selected org-agenda-follow-mode :active t]
19443 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
19444 "--"
19445 ["Cycle TODO" org-agenda-todo t]
19446 ["Archive subtree" org-agenda-archive t]
19447 ["Delete subtree" org-agenda-kill t]
19448 "--"
19449 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
19450 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
19451 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
19452 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
19453 "--"
19454 ("Tags and Properties"
19455 ["Show all Tags" org-agenda-show-tags t]
19456 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
19457 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
19458 "--"
19459 ["Column View" org-columns t])
19460 ("Date/Schedule"
19461 ["Schedule" org-agenda-schedule t]
19462 ["Set Deadline" org-agenda-deadline t]
19463 "--"
19464 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19465 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19466 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19467 ("Clock"
19468 ["Clock in" org-agenda-clock-in t]
19469 ["Clock out" org-agenda-clock-out t]
19470 ["Clock cancel" org-agenda-clock-cancel t]
19471 ["Goto running clock" org-clock-goto t])
19472 ("Priority"
19473 ["Set Priority" org-agenda-priority t]
19474 ["Increase Priority" org-agenda-priority-up t]
19475 ["Decrease Priority" org-agenda-priority-down t]
19476 ["Show Priority" org-agenda-show-priority t])
19477 ("Calendar/Diary"
19478 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19479 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19480 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19481 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19482 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19483 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19484 "--"
19485 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19486 "--"
19487 ("View"
19488 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19489 :style radio :selected (equal org-agenda-ndays 1)]
19490 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19491 :style radio :selected (equal org-agenda-ndays 7)]
19492 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19493 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19494 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19495 :style radio :selected (member org-agenda-ndays '(365 366))]
19496 "--"
19497 ["Show Logbook entries" org-agenda-log-mode
19498 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19499 ["Include Diary" org-agenda-toggle-diary
19500 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19501 ["Use Time Grid" org-agenda-toggle-time-grid
19502 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19503 ["Write view to file" org-write-agenda t]
19504 ["Rebuild buffer" org-agenda-redo t]
19505 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19506 "--"
19507 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19508 "--"
19509 ["Quit" org-agenda-quit t]
19510 ["Exit and Release Buffers" org-agenda-exit t]
19513 ;;; Agenda undo
19515 (defvar org-agenda-allow-remote-undo t
19516 "Non-nil means, allow remote undo from the agenda buffer.")
19517 (defvar org-agenda-undo-list nil
19518 "List of undoable operations in the agenda since last refresh.")
19519 (defvar org-agenda-undo-has-started-in nil
19520 "Buffers that have already seen `undo-start' in the current undo sequence.")
19521 (defvar org-agenda-pending-undo-list nil
19522 "In a series of undo commands, this is the list of remaning undo items.")
19524 (defmacro org-if-unprotected (&rest body)
19525 "Execute BODY if there is no `org-protected' text property at point."
19526 (declare (debug t))
19527 `(unless (get-text-property (point) 'org-protected)
19528 ,@body))
19530 (defmacro org-with-remote-undo (_buffer &rest _body)
19531 "Execute BODY while recording undo information in two buffers."
19532 (declare (indent 1) (debug t))
19533 `(let ((_cline (org-current-line))
19534 (_cmd this-command)
19535 (_buf1 (current-buffer))
19536 (_buf2 ,_buffer)
19537 (_undo1 buffer-undo-list)
19538 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19539 _c1 _c2)
19540 ,@_body
19541 (when org-agenda-allow-remote-undo
19542 (setq _c1 (org-verify-change-for-undo
19543 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19544 _c2 (org-verify-change-for-undo
19545 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19546 (when (or _c1 _c2)
19547 ;; make sure there are undo boundaries
19548 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19549 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19550 ;; remember which buffer to undo
19551 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19552 org-agenda-undo-list)))))
19554 (defun org-agenda-undo ()
19555 "Undo a remote editing step in the agenda.
19556 This undoes changes both in the agenda buffer and in the remote buffer
19557 that have been changed along."
19558 (interactive)
19559 (or org-agenda-allow-remote-undo
19560 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19561 (if (not (eq this-command last-command))
19562 (setq org-agenda-undo-has-started-in nil
19563 org-agenda-pending-undo-list org-agenda-undo-list))
19564 (if (not org-agenda-pending-undo-list)
19565 (error "No further undo information"))
19566 (let* ((entry (pop org-agenda-pending-undo-list))
19567 buf line cmd rembuf)
19568 (setq cmd (pop entry) line (pop entry))
19569 (setq rembuf (nth 2 entry))
19570 (org-with-remote-undo rembuf
19571 (while (bufferp (setq buf (pop entry)))
19572 (if (pop entry)
19573 (with-current-buffer buf
19574 (let ((last-undo-buffer buf)
19575 (inhibit-read-only t))
19576 (unless (memq buf org-agenda-undo-has-started-in)
19577 (push buf org-agenda-undo-has-started-in)
19578 (make-local-variable 'pending-undo-list)
19579 (undo-start))
19580 (while (and pending-undo-list
19581 (listp pending-undo-list)
19582 (not (car pending-undo-list)))
19583 (pop pending-undo-list))
19584 (undo-more 1))))))
19585 (goto-line line)
19586 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19588 (defun org-verify-change-for-undo (l1 l2)
19589 "Verify that a real change occurred between the undo lists L1 and L2."
19590 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19591 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19592 (not (eq l1 l2)))
19594 ;;; Agenda dispatch
19596 (defvar org-agenda-restrict nil)
19597 (defvar org-agenda-restrict-begin (make-marker))
19598 (defvar org-agenda-restrict-end (make-marker))
19599 (defvar org-agenda-last-dispatch-buffer nil)
19600 (defvar org-agenda-overriding-restriction nil)
19602 ;;;###autoload
19603 (defun org-agenda (arg &optional keys restriction)
19604 "Dispatch agenda commands to collect entries to the agenda buffer.
19605 Prompts for a command to execute. Any prefix arg will be passed
19606 on to the selected command. The default selections are:
19608 a Call `org-agenda-list' to display the agenda for current day or week.
19609 t Call `org-todo-list' to display the global todo list.
19610 T Call `org-todo-list' to display the global todo list, select only
19611 entries with a specific TODO keyword (the user gets a prompt).
19612 m Call `org-tags-view' to display headlines with tags matching
19613 a condition (the user is prompted for the condition).
19614 M Like `m', but select only TODO entries, no ordinary headlines.
19615 L Create a timeline for the current buffer.
19616 e Export views to associated files.
19618 More commands can be added by configuring the variable
19619 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19620 searches can be pre-defined in this way.
19622 If the current buffer is in Org-mode and visiting a file, you can also
19623 first press `<' once to indicate that the agenda should be temporarily
19624 \(until the next use of \\[org-agenda]) restricted to the current file.
19625 Pressing `<' twice means to restrict to the current subtree or region
19626 \(if active)."
19627 (interactive "P")
19628 (catch 'exit
19629 (let* ((prefix-descriptions nil)
19630 (org-agenda-custom-commands-orig org-agenda-custom-commands)
19631 (org-agenda-custom-commands
19632 ;; normalize different versions
19633 (delq nil
19634 (mapcar
19635 (lambda (x)
19636 (cond ((stringp (cdr x))
19637 (push x prefix-descriptions)
19638 nil)
19639 ((stringp (nth 1 x)) x)
19640 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19641 (t (cons (car x) (cons "" (cdr x))))))
19642 org-agenda-custom-commands)))
19643 (buf (current-buffer))
19644 (bfn (buffer-file-name (buffer-base-buffer)))
19645 entry key type match lprops ans)
19646 ;; Turn off restriction unless there is an overriding one
19647 (unless org-agenda-overriding-restriction
19648 (put 'org-agenda-files 'org-restrict nil)
19649 (setq org-agenda-restrict nil)
19650 (move-marker org-agenda-restrict-begin nil)
19651 (move-marker org-agenda-restrict-end nil))
19652 ;; Delete old local properties
19653 (put 'org-agenda-redo-command 'org-lprops nil)
19654 ;; Remember where this call originated
19655 (setq org-agenda-last-dispatch-buffer (current-buffer))
19656 (unless keys
19657 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19658 keys (car ans)
19659 restriction (cdr ans)))
19660 ;; Estabish the restriction, if any
19661 (when (and (not org-agenda-overriding-restriction) restriction)
19662 (put 'org-agenda-files 'org-restrict (list bfn))
19663 (cond
19664 ((eq restriction 'region)
19665 (setq org-agenda-restrict t)
19666 (move-marker org-agenda-restrict-begin (region-beginning))
19667 (move-marker org-agenda-restrict-end (region-end)))
19668 ((eq restriction 'subtree)
19669 (save-excursion
19670 (setq org-agenda-restrict t)
19671 (org-back-to-heading t)
19672 (move-marker org-agenda-restrict-begin (point))
19673 (move-marker org-agenda-restrict-end
19674 (progn (org-end-of-subtree t)))))))
19676 (require 'calendar) ; FIXME: can we avoid this for some commands?
19677 ;; For example the todo list should not need it (but does...)
19678 (cond
19679 ((setq entry (assoc keys org-agenda-custom-commands))
19680 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19681 (progn
19682 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19683 (put 'org-agenda-redo-command 'org-lprops lprops)
19684 (cond
19685 ((eq type 'agenda)
19686 (org-let lprops '(org-agenda-list current-prefix-arg)))
19687 ((eq type 'alltodo)
19688 (org-let lprops '(org-todo-list current-prefix-arg)))
19689 ((eq type 'stuck)
19690 (org-let lprops '(org-agenda-list-stuck-projects
19691 current-prefix-arg)))
19692 ((eq type 'tags)
19693 (org-let lprops '(org-tags-view current-prefix-arg match)))
19694 ((eq type 'tags-todo)
19695 (org-let lprops '(org-tags-view '(4) match)))
19696 ((eq type 'todo)
19697 (org-let lprops '(org-todo-list match)))
19698 ((eq type 'tags-tree)
19699 (org-check-for-org-mode)
19700 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
19701 ((eq type 'todo-tree)
19702 (org-check-for-org-mode)
19703 (org-let lprops
19704 '(org-occur (concat "^" outline-regexp "[ \t]*"
19705 (regexp-quote match) "\\>"))))
19706 ((eq type 'occur-tree)
19707 (org-check-for-org-mode)
19708 (org-let lprops '(org-occur match)))
19709 ((functionp type)
19710 (org-let lprops '(funcall type match)))
19711 ((fboundp type)
19712 (org-let lprops '(funcall type match)))
19713 (t (error "Invalid custom agenda command type %s" type))))
19714 (org-run-agenda-series (nth 1 entry) (cddr entry))))
19715 ((equal keys "C")
19716 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
19717 (customize-variable 'org-agenda-custom-commands))
19718 ((equal keys "a") (call-interactively 'org-agenda-list))
19719 ((equal keys "t") (call-interactively 'org-todo-list))
19720 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
19721 ((equal keys "m") (call-interactively 'org-tags-view))
19722 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
19723 ((equal keys "e") (call-interactively 'org-store-agenda-views))
19724 ((equal keys "L")
19725 (unless (org-mode-p)
19726 (error "This is not an Org-mode file"))
19727 (unless restriction
19728 (put 'org-agenda-files 'org-restrict (list bfn))
19729 (org-call-with-arg 'org-timeline arg)))
19730 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
19731 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
19732 ((equal keys "!") (customize-variable 'org-stuck-projects))
19733 (t (error "Invalid agenda key"))))))
19735 (defun org-agenda-normalize-custom-commands (cmds)
19736 (delq nil
19737 (mapcar
19738 (lambda (x)
19739 (cond ((stringp (cdr x)) nil)
19740 ((stringp (nth 1 x)) x)
19741 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19742 (t (cons (car x) (cons "" (cdr x))))))
19743 cmds)))
19745 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
19746 "The user interface for selecting an agenda command."
19747 (catch 'exit
19748 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
19749 (restrict-ok (and bfn (org-mode-p)))
19750 (region-p (org-region-active-p))
19751 (custom org-agenda-custom-commands)
19752 (selstring "")
19753 restriction second-time
19754 c entry key type match prefixes rmheader header-end custom1 desc)
19755 (save-window-excursion
19756 (delete-other-windows)
19757 (org-switch-to-buffer-other-window " *Agenda Commands*")
19758 (erase-buffer)
19759 (insert (eval-when-compile
19760 (let ((header
19762 Press key for an agenda command: < Buffer,subtree/region restriction
19763 -------------------------------- > Remove restriction
19764 a Agenda for current week or day e Export agenda views
19765 t List of all TODO entries T Entries with special TODO kwd
19766 m Match a TAGS query M Like m, but only TODO entries
19767 L Timeline for current buffer # List stuck projects (!=configure)
19768 / Multi-occur C Configure custom agenda commands
19770 (start 0))
19771 (while (string-match
19772 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
19773 header start)
19774 (setq start (match-end 0))
19775 (add-text-properties (match-beginning 2) (match-end 2)
19776 '(face bold) header))
19777 header)))
19778 (setq header-end (move-marker (make-marker) (point)))
19779 (while t
19780 (setq custom1 custom)
19781 (when (eq rmheader t)
19782 (goto-line 1)
19783 (re-search-forward ":" nil t)
19784 (delete-region (match-end 0) (point-at-eol))
19785 (forward-char 1)
19786 (looking-at "-+")
19787 (delete-region (match-end 0) (point-at-eol))
19788 (move-marker header-end (match-end 0)))
19789 (goto-char header-end)
19790 (delete-region (point) (point-max))
19791 (while (setq entry (pop custom1))
19792 (setq key (car entry) desc (nth 1 entry)
19793 type (nth 2 entry) match (nth 3 entry))
19794 (if (> (length key) 1)
19795 (add-to-list 'prefixes (string-to-char key))
19796 (insert
19797 (format
19798 "\n%-4s%-14s: %s"
19799 (org-add-props (copy-sequence key)
19800 '(face bold))
19801 (cond
19802 ((string-match "\\S-" desc) desc)
19803 ((eq type 'agenda) "Agenda for current week or day")
19804 ((eq type 'alltodo) "List of all TODO entries")
19805 ((eq type 'stuck) "List of stuck projects")
19806 ((eq type 'todo) "TODO keyword")
19807 ((eq type 'tags) "Tags query")
19808 ((eq type 'tags-todo) "Tags (TODO)")
19809 ((eq type 'tags-tree) "Tags tree")
19810 ((eq type 'todo-tree) "TODO kwd tree")
19811 ((eq type 'occur-tree) "Occur tree")
19812 ((functionp type) (if (symbolp type)
19813 (symbol-name type)
19814 "Lambda expression"))
19815 (t "???"))
19816 (cond
19817 ((stringp match)
19818 (org-add-props match nil 'face 'org-warning))
19819 (match
19820 (format "set of %d commands" (length match)))
19821 (t ""))))))
19822 (when prefixes
19823 (mapc (lambda (x)
19824 (insert
19825 (format "\n%s %s"
19826 (org-add-props (char-to-string x)
19827 nil 'face 'bold)
19828 (or (cdr (assoc (concat selstring (char-to-string x))
19829 prefix-descriptions))
19830 "Prefix key"))))
19831 prefixes))
19832 (goto-char (point-min))
19833 (when (fboundp 'fit-window-to-buffer)
19834 (if second-time
19835 (if (not (pos-visible-in-window-p (point-max)))
19836 (fit-window-to-buffer))
19837 (setq second-time t)
19838 (fit-window-to-buffer)))
19839 (message "Press key for agenda command%s:"
19840 (if (or restrict-ok org-agenda-overriding-restriction)
19841 (if org-agenda-overriding-restriction
19842 " (restriction lock active)"
19843 (if restriction
19844 (format " (restricted to %s)" restriction)
19845 " (unrestricted)"))
19846 ""))
19847 (setq c (read-char-exclusive))
19848 (message "")
19849 (cond
19850 ((assoc (char-to-string c) custom)
19851 (setq selstring (concat selstring (char-to-string c)))
19852 (throw 'exit (cons selstring restriction)))
19853 ((memq c prefixes)
19854 (setq selstring (concat selstring (char-to-string c))
19855 prefixes nil
19856 rmheader (or rmheader t)
19857 custom (delq nil (mapcar
19858 (lambda (x)
19859 (if (or (= (length (car x)) 1)
19860 (/= (string-to-char (car x)) c))
19862 (cons (substring (car x) 1) (cdr x))))
19863 custom))))
19864 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
19865 (message "Restriction is only possible in Org-mode buffers")
19866 (ding) (sit-for 1))
19867 ((eq c ?1)
19868 (org-agenda-remove-restriction-lock 'noupdate)
19869 (setq restriction 'buffer))
19870 ((eq c ?0)
19871 (org-agenda-remove-restriction-lock 'noupdate)
19872 (setq restriction (if region-p 'region 'subtree)))
19873 ((eq c ?<)
19874 (org-agenda-remove-restriction-lock 'noupdate)
19875 (setq restriction
19876 (cond
19877 ((eq restriction 'buffer)
19878 (if region-p 'region 'subtree))
19879 ((memq restriction '(subtree region))
19880 nil)
19881 (t 'buffer))))
19882 ((eq c ?>)
19883 (org-agenda-remove-restriction-lock 'noupdate)
19884 (setq restriction nil))
19885 ((and (equal selstring "") (memq c '(?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
19886 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
19887 ((and (> (length selstring) 0) (eq c ?\d))
19888 (delete-window)
19889 (org-agenda-get-restriction-and-command prefix-descriptions))
19891 ((equal c ?q) (error "Abort"))
19892 (t (error "Invalid key %c" c))))))))
19894 (defun org-run-agenda-series (name series)
19895 (org-prepare-agenda name)
19896 (let* ((org-agenda-multi t)
19897 (redo (list 'org-run-agenda-series name (list 'quote series)))
19898 (cmds (car series))
19899 (gprops (nth 1 series))
19900 match ;; The byte compiler incorrectly complains about this. Keep it!
19901 cmd type lprops)
19902 (while (setq cmd (pop cmds))
19903 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
19904 (cond
19905 ((eq type 'agenda)
19906 (org-let2 gprops lprops
19907 '(call-interactively 'org-agenda-list)))
19908 ((eq type 'alltodo)
19909 (org-let2 gprops lprops
19910 '(call-interactively 'org-todo-list)))
19911 ((eq type 'stuck)
19912 (org-let2 gprops lprops
19913 '(call-interactively 'org-agenda-list-stuck-projects)))
19914 ((eq type 'tags)
19915 (org-let2 gprops lprops
19916 '(org-tags-view current-prefix-arg match)))
19917 ((eq type 'tags-todo)
19918 (org-let2 gprops lprops
19919 '(org-tags-view '(4) match)))
19920 ((eq type 'todo)
19921 (org-let2 gprops lprops
19922 '(org-todo-list match)))
19923 ((fboundp type)
19924 (org-let2 gprops lprops
19925 '(funcall type match)))
19926 (t (error "Invalid type in command series"))))
19927 (widen)
19928 (setq org-agenda-redo-command redo)
19929 (goto-char (point-min)))
19930 (org-finalize-agenda))
19932 ;;;###autoload
19933 (defmacro org-batch-agenda (cmd-key &rest parameters)
19934 "Run an agenda command in batch mode and send the result to STDOUT.
19935 If CMD-KEY is a string of length 1, it is used as a key in
19936 `org-agenda-custom-commands' and triggers this command. If it is a
19937 longer string it is used as a tags/todo match string.
19938 Paramters are alternating variable names and values that will be bound
19939 before running the agenda command."
19940 (let (pars)
19941 (while parameters
19942 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19943 (if (> (length cmd-key) 2)
19944 (eval (list 'let (nreverse pars)
19945 (list 'org-tags-view nil cmd-key)))
19946 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19947 (set-buffer org-agenda-buffer-name)
19948 (princ (org-encode-for-stdout (buffer-string)))))
19950 (defun org-encode-for-stdout (string)
19951 (if (fboundp 'encode-coding-string)
19952 (encode-coding-string string buffer-file-coding-system)
19953 string))
19955 (defvar org-agenda-info nil)
19957 ;;;###autoload
19958 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
19959 "Run an agenda command in batch mode and send the result to STDOUT.
19960 If CMD-KEY is a string of length 1, it is used as a key in
19961 `org-agenda-custom-commands' and triggers this command. If it is a
19962 longer string it is used as a tags/todo match string.
19963 Paramters are alternating variable names and values that will be bound
19964 before running the agenda command.
19966 The output gives a line for each selected agenda item. Each
19967 item is a list of comma-separated values, like this:
19969 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
19971 category The category of the item
19972 head The headline, without TODO kwd, TAGS and PRIORITY
19973 type The type of the agenda entry, can be
19974 todo selected in TODO match
19975 tagsmatch selected in tags match
19976 diary imported from diary
19977 deadline a deadline on given date
19978 scheduled scheduled on given date
19979 timestamp entry has timestamp on given date
19980 closed entry was closed on given date
19981 upcoming-deadline warning about deadline
19982 past-scheduled forwarded scheduled item
19983 block entry has date block including g. date
19984 todo The todo keyword, if any
19985 tags All tags including inherited ones, separated by colons
19986 date The relevant date, like 2007-2-14
19987 time The time, like 15:00-16:50
19988 extra Sting with extra planning info
19989 priority-l The priority letter if any was given
19990 priority-n The computed numerical priority
19991 agenda-day The day in the agenda where this is listed"
19993 (let (pars)
19994 (while parameters
19995 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19996 (push (list 'org-agenda-remove-tags t) pars)
19997 (if (> (length cmd-key) 2)
19998 (eval (list 'let (nreverse pars)
19999 (list 'org-tags-view nil cmd-key)))
20000 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20001 (set-buffer org-agenda-buffer-name)
20002 (let* ((lines (org-split-string (buffer-string) "\n"))
20003 line)
20004 (while (setq line (pop lines))
20005 (catch 'next
20006 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
20007 (setq org-agenda-info
20008 (org-fix-agenda-info (text-properties-at 0 line)))
20009 (princ
20010 (org-encode-for-stdout
20011 (mapconcat 'org-agenda-export-csv-mapper
20012 '(org-category txt type todo tags date time-of-day extra
20013 priority-letter priority agenda-day)
20014 ",")))
20015 (princ "\n"))))))
20017 (defun org-fix-agenda-info (props)
20018 "Make sure all properties on an agenda item have a canonical form,
20019 so the export commands can easily use it."
20020 (let (tmp re)
20021 (when (setq tmp (plist-get props 'tags))
20022 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
20023 (when (setq tmp (plist-get props 'date))
20024 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20025 (let ((calendar-date-display-form '(year "-" month "-" day)))
20026 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
20028 (setq tmp (calendar-date-string tmp)))
20029 (setq props (plist-put props 'date tmp)))
20030 (when (setq tmp (plist-get props 'day))
20031 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20032 (let ((calendar-date-display-form '(year "-" month "-" day)))
20033 (setq tmp (calendar-date-string tmp)))
20034 (setq props (plist-put props 'day tmp))
20035 (setq props (plist-put props 'agenda-day tmp)))
20036 (when (setq tmp (plist-get props 'txt))
20037 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
20038 (plist-put props 'priority-letter (match-string 1 tmp))
20039 (setq tmp (replace-match "" t t tmp)))
20040 (when (and (setq re (plist-get props 'org-todo-regexp))
20041 (setq re (concat "\\`\\.*" re " ?"))
20042 (string-match re tmp))
20043 (plist-put props 'todo (match-string 1 tmp))
20044 (setq tmp (replace-match "" t t tmp)))
20045 (plist-put props 'txt tmp)))
20046 props)
20048 (defun org-agenda-export-csv-mapper (prop)
20049 (let ((res (plist-get org-agenda-info prop)))
20050 (setq res
20051 (cond
20052 ((not res) "")
20053 ((stringp res) res)
20054 (t (prin1-to-string res))))
20055 (while (string-match "," res)
20056 (setq res (replace-match ";" t t res)))
20057 (org-trim res)))
20060 ;;;###autoload
20061 (defun org-store-agenda-views (&rest parameters)
20062 (interactive)
20063 (eval (list 'org-batch-store-agenda-views)))
20065 ;; FIXME, why is this a macro?????
20066 ;;;###autoload
20067 (defmacro org-batch-store-agenda-views (&rest parameters)
20068 "Run all custom agenda commands that have a file argument."
20069 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
20070 (pop-up-frames nil)
20071 (dir default-directory)
20072 pars cmd thiscmdkey files opts)
20073 (while parameters
20074 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20075 (setq pars (reverse pars))
20076 (save-window-excursion
20077 (while cmds
20078 (setq cmd (pop cmds)
20079 thiscmdkey (car cmd)
20080 opts (nth 4 cmd)
20081 files (nth 5 cmd))
20082 (if (stringp files) (setq files (list files)))
20083 (when files
20084 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20085 (list 'org-agenda nil thiscmdkey)))
20086 (set-buffer org-agenda-buffer-name)
20087 (while files
20088 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20089 (list 'org-write-agenda
20090 (expand-file-name (pop files) dir) t))))
20091 (and (get-buffer org-agenda-buffer-name)
20092 (kill-buffer org-agenda-buffer-name)))))))
20094 (defun org-write-agenda (file &optional nosettings)
20095 "Write the current buffer (an agenda view) as a file.
20096 Depending on the extension of the file name, plain text (.txt),
20097 HTML (.html or .htm) or Postscript (.ps) is produced.
20098 If NOSETTINGS is given, do not scope the settings of
20099 `org-agenda-exporter-settings' into the export commands. This is used when
20100 the settings have already been scoped and we do not wish to overrule other,
20101 higher priority settings."
20102 (interactive "FWrite agenda to file: ")
20103 (if (not (file-writable-p file))
20104 (error "Cannot write agenda to file %s" file))
20105 (cond
20106 ((string-match "\\.html?\\'" file) (require 'htmlize))
20107 ((string-match "\\.ps\\'" file) (require 'ps-print)))
20108 (org-let (if nosettings nil org-agenda-exporter-settings)
20109 '(save-excursion
20110 (save-window-excursion
20111 (cond
20112 ((string-match "\\.html?\\'" file)
20113 (set-buffer (htmlize-buffer (current-buffer)))
20115 (when (and org-agenda-export-html-style
20116 (string-match "<style>" org-agenda-export-html-style))
20117 ;; replace <style> section with org-agenda-export-html-style
20118 (goto-char (point-min))
20119 (kill-region (- (search-forward "<style") 6)
20120 (search-forward "</style>"))
20121 (insert org-agenda-export-html-style))
20122 (write-file file)
20123 (kill-buffer (current-buffer))
20124 (message "HTML written to %s" file))
20125 ((string-match "\\.ps\\'" file)
20126 (ps-print-buffer-with-faces file)
20127 (message "Postscript written to %s" file))
20129 (let ((bs (buffer-string)))
20130 (find-file file)
20131 (insert bs)
20132 (save-buffer 0)
20133 (kill-buffer (current-buffer))
20134 (message "Plain text written to %s" file))))))
20135 (set-buffer org-agenda-buffer-name)))
20137 (defmacro org-no-read-only (&rest body)
20138 "Inhibit read-only for BODY."
20139 `(let ((inhibit-read-only t)) ,@body))
20141 (defun org-check-for-org-mode ()
20142 "Make sure current buffer is in org-mode. Error if not."
20143 (or (org-mode-p)
20144 (error "Cannot execute org-mode agenda command on buffer in %s."
20145 major-mode)))
20147 (defun org-fit-agenda-window ()
20148 "Fit the window to the buffer size."
20149 (and (memq org-agenda-window-setup '(reorganize-frame))
20150 (fboundp 'fit-window-to-buffer)
20151 (fit-window-to-buffer
20153 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
20154 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
20156 ;;; Agenda file list
20158 (defun org-agenda-files (&optional unrestricted)
20159 "Get the list of agenda files.
20160 Optional UNRESTRICTED means return the full list even if a restriction
20161 is currently in place."
20162 (let ((files
20163 (cond
20164 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
20165 ((stringp org-agenda-files) (org-read-agenda-file-list))
20166 ((listp org-agenda-files) org-agenda-files)
20167 (t (error "Invalid value of `org-agenda-files'")))))
20168 (setq files (apply 'append
20169 (mapcar (lambda (f)
20170 (if (file-directory-p f)
20171 (directory-files f t
20172 org-agenda-file-regexp)
20173 (list f)))
20174 files)))
20175 (if org-agenda-skip-unavailable-files
20176 (delq nil
20177 (mapcar (function
20178 (lambda (file)
20179 (and (file-readable-p file) file)))
20180 files))
20181 files))) ; `org-check-agenda-file' will remove them from the list
20183 (defun org-edit-agenda-file-list ()
20184 "Edit the list of agenda files.
20185 Depending on setup, this either uses customize to edit the variable
20186 `org-agenda-files', or it visits the file that is holding the list. In the
20187 latter case, the buffer is set up in a way that saving it automatically kills
20188 the buffer and restores the previous window configuration."
20189 (interactive)
20190 (if (stringp org-agenda-files)
20191 (let ((cw (current-window-configuration)))
20192 (find-file org-agenda-files)
20193 (org-set-local 'org-window-configuration cw)
20194 (org-add-hook 'after-save-hook
20195 (lambda ()
20196 (set-window-configuration
20197 (prog1 org-window-configuration
20198 (kill-buffer (current-buffer))))
20199 (org-install-agenda-files-menu)
20200 (message "New agenda file list installed"))
20201 nil 'local)
20202 (message "%s" (substitute-command-keys
20203 "Edit list and finish with \\[save-buffer]")))
20204 (customize-variable 'org-agenda-files)))
20206 (defun org-store-new-agenda-file-list (list)
20207 "Set new value for the agenda file list and save it correcly."
20208 (if (stringp org-agenda-files)
20209 (let ((f org-agenda-files) b)
20210 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
20211 (with-temp-file f
20212 (insert (mapconcat 'identity list "\n") "\n")))
20213 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
20214 (setq org-agenda-files list)
20215 (customize-save-variable 'org-agenda-files org-agenda-files))))
20217 (defun org-read-agenda-file-list ()
20218 "Read the list of agenda files from a file."
20219 (when (stringp org-agenda-files)
20220 (with-temp-buffer
20221 (insert-file-contents org-agenda-files)
20222 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
20225 ;;;###autoload
20226 (defun org-cycle-agenda-files ()
20227 "Cycle through the files in `org-agenda-files'.
20228 If the current buffer visits an agenda file, find the next one in the list.
20229 If the current buffer does not, find the first agenda file."
20230 (interactive)
20231 (let* ((fs (org-agenda-files t))
20232 (files (append fs (list (car fs))))
20233 (tcf (if buffer-file-name (file-truename buffer-file-name)))
20234 file)
20235 (unless files (error "No agenda files"))
20236 (catch 'exit
20237 (while (setq file (pop files))
20238 (if (equal (file-truename file) tcf)
20239 (when (car files)
20240 (find-file (car files))
20241 (throw 'exit t))))
20242 (find-file (car fs)))
20243 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
20245 (defun org-agenda-file-to-front (&optional to-end)
20246 "Move/add the current file to the top of the agenda file list.
20247 If the file is not present in the list, it is added to the front. If it is
20248 present, it is moved there. With optional argument TO-END, add/move to the
20249 end of the list."
20250 (interactive "P")
20251 (let ((org-agenda-skip-unavailable-files nil)
20252 (file-alist (mapcar (lambda (x)
20253 (cons (file-truename x) x))
20254 (org-agenda-files t)))
20255 (ctf (file-truename buffer-file-name))
20256 x had)
20257 (setq x (assoc ctf file-alist) had x)
20259 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
20260 (if to-end
20261 (setq file-alist (append (delq x file-alist) (list x)))
20262 (setq file-alist (cons x (delq x file-alist))))
20263 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
20264 (org-install-agenda-files-menu)
20265 (message "File %s to %s of agenda file list"
20266 (if had "moved" "added") (if to-end "end" "front"))))
20268 (defun org-remove-file (&optional file)
20269 "Remove current file from the list of files in variable `org-agenda-files'.
20270 These are the files which are being checked for agenda entries.
20271 Optional argument FILE means, use this file instead of the current."
20272 (interactive)
20273 (let* ((org-agenda-skip-unavailable-files nil)
20274 (file (or file buffer-file-name))
20275 (true-file (file-truename file))
20276 (afile (abbreviate-file-name file))
20277 (files (delq nil (mapcar
20278 (lambda (x)
20279 (if (equal true-file
20280 (file-truename x))
20281 nil x))
20282 (org-agenda-files t)))))
20283 (if (not (= (length files) (length (org-agenda-files t))))
20284 (progn
20285 (org-store-new-agenda-file-list files)
20286 (org-install-agenda-files-menu)
20287 (message "Removed file: %s" afile))
20288 (message "File was not in list: %s (not removed)" afile))))
20290 (defun org-file-menu-entry (file)
20291 (vector file (list 'find-file file) t))
20293 (defun org-check-agenda-file (file)
20294 "Make sure FILE exists. If not, ask user what to do."
20295 (when (not (file-exists-p file))
20296 (message "non-existent file %s. [R]emove from list or [A]bort?"
20297 (abbreviate-file-name file))
20298 (let ((r (downcase (read-char-exclusive))))
20299 (cond
20300 ((equal r ?r)
20301 (org-remove-file file)
20302 (throw 'nextfile t))
20303 (t (error "Abort"))))))
20305 ;;; Agenda prepare and finalize
20307 (defvar org-agenda-multi nil) ; dynammically scoped
20308 (defvar org-agenda-buffer-name "*Org Agenda*")
20309 (defvar org-pre-agenda-window-conf nil)
20310 (defvar org-agenda-name nil)
20311 (defun org-prepare-agenda (&optional name)
20312 (setq org-todo-keywords-for-agenda nil)
20313 (setq org-done-keywords-for-agenda nil)
20314 (if org-agenda-multi
20315 (progn
20316 (setq buffer-read-only nil)
20317 (goto-char (point-max))
20318 (unless (or (bobp) org-agenda-compact-blocks)
20319 (insert "\n" (make-string (window-width) ?=) "\n"))
20320 (narrow-to-region (point) (point-max)))
20321 (org-agenda-reset-markers)
20322 (org-prepare-agenda-buffers (org-agenda-files))
20323 (setq org-todo-keywords-for-agenda
20324 (org-uniquify org-todo-keywords-for-agenda))
20325 (setq org-done-keywords-for-agenda
20326 (org-uniquify org-done-keywords-for-agenda))
20327 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
20328 (awin (get-buffer-window abuf)))
20329 (cond
20330 ((equal (current-buffer) abuf) nil)
20331 (awin (select-window awin))
20332 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
20333 ((equal org-agenda-window-setup 'current-window)
20334 (switch-to-buffer abuf))
20335 ((equal org-agenda-window-setup 'other-window)
20336 (org-switch-to-buffer-other-window abuf))
20337 ((equal org-agenda-window-setup 'other-frame)
20338 (switch-to-buffer-other-frame abuf))
20339 ((equal org-agenda-window-setup 'reorganize-frame)
20340 (delete-other-windows)
20341 (org-switch-to-buffer-other-window abuf))))
20342 (setq buffer-read-only nil)
20343 (erase-buffer)
20344 (org-agenda-mode)
20345 (and name (not org-agenda-name)
20346 (org-set-local 'org-agenda-name name)))
20347 (setq buffer-read-only nil))
20349 (defun org-finalize-agenda ()
20350 "Finishing touch for the agenda buffer, called just before displaying it."
20351 (unless org-agenda-multi
20352 (save-excursion
20353 (let ((inhibit-read-only t))
20354 (goto-char (point-min))
20355 (while (org-activate-bracket-links (point-max))
20356 (add-text-properties (match-beginning 0) (match-end 0)
20357 '(face org-link)))
20358 (org-agenda-align-tags)
20359 (unless org-agenda-with-colors
20360 (remove-text-properties (point-min) (point-max) '(face nil))))
20361 (if (and (boundp 'org-overriding-columns-format)
20362 org-overriding-columns-format)
20363 (org-set-local 'org-overriding-columns-format
20364 org-overriding-columns-format))
20365 (if (and (boundp 'org-agenda-view-columns-initially)
20366 org-agenda-view-columns-initially)
20367 (org-agenda-columns))
20368 (when org-agenda-fontify-priorities
20369 (org-fontify-priorities))
20370 (run-hooks 'org-finalize-agenda-hook)
20371 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20374 (defun org-fontify-priorities ()
20375 "Make highest priority lines bold, and lowest italic."
20376 (interactive)
20377 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
20378 (org-delete-overlay o)))
20379 (org-overlays-in (point-min) (point-max)))
20380 (save-excursion
20381 (let ((inhibit-read-only t)
20382 b e p ov h l)
20383 (goto-char (point-min))
20384 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
20385 (setq h (or (get-char-property (point) 'org-highest-priority)
20386 org-highest-priority)
20387 l (or (get-char-property (point) 'org-lowest-priority)
20388 org-lowest-priority)
20389 p (string-to-char (match-string 1))
20390 b (match-beginning 0) e (point-at-eol)
20391 ov (org-make-overlay b e))
20392 (org-overlay-put
20393 ov 'face
20394 (cond ((listp org-agenda-fontify-priorities)
20395 (cdr (assoc p org-agenda-fontify-priorities)))
20396 ((equal p l) 'italic)
20397 ((equal p h) 'bold)))
20398 (org-overlay-put ov 'org-type 'org-priority)))))
20400 (defun org-prepare-agenda-buffers (files)
20401 "Create buffers for all agenda files, protect archived trees and comments."
20402 (interactive)
20403 (let ((pa '(:org-archived t))
20404 (pc '(:org-comment t))
20405 (pall '(:org-archived t :org-comment t))
20406 (inhibit-read-only t)
20407 (rea (concat ":" org-archive-tag ":"))
20408 bmp file re)
20409 (save-excursion
20410 (save-restriction
20411 (while (setq file (pop files))
20412 (if (bufferp file)
20413 (set-buffer file)
20414 (org-check-agenda-file file)
20415 (set-buffer (org-get-agenda-file-buffer file)))
20416 (widen)
20417 (setq bmp (buffer-modified-p))
20418 (org-refresh-category-properties)
20419 (setq org-todo-keywords-for-agenda
20420 (append org-todo-keywords-for-agenda org-todo-keywords-1))
20421 (setq org-done-keywords-for-agenda
20422 (append org-done-keywords-for-agenda org-done-keywords))
20423 (save-excursion
20424 (remove-text-properties (point-min) (point-max) pall)
20425 (when org-agenda-skip-archived-trees
20426 (goto-char (point-min))
20427 (while (re-search-forward rea nil t)
20428 (if (org-on-heading-p t)
20429 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
20430 (goto-char (point-min))
20431 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
20432 (while (re-search-forward re nil t)
20433 (add-text-properties
20434 (match-beginning 0) (org-end-of-subtree t) pc)))
20435 (set-buffer-modified-p bmp))))))
20437 (defvar org-agenda-skip-function nil
20438 "Function to be called at each match during agenda construction.
20439 If this function returns nil, the current match should not be skipped.
20440 Otherwise, the function must return a position from where the search
20441 should be continued.
20442 This may also be a Lisp form, it will be evaluated.
20443 Never set this variable using `setq' or so, because then it will apply
20444 to all future agenda commands. Instead, bind it with `let' to scope
20445 it dynamically into the agenda-constructing command. A good way to set
20446 it is through options in org-agenda-custom-commands.")
20448 (defun org-agenda-skip ()
20449 "Throw to `:skip' in places that should be skipped.
20450 Also moves point to the end of the skipped region, so that search can
20451 continue from there."
20452 (let ((p (point-at-bol)) to fp)
20453 (and org-agenda-skip-archived-trees
20454 (get-text-property p :org-archived)
20455 (org-end-of-subtree t)
20456 (throw :skip t))
20457 (and (get-text-property p :org-comment)
20458 (org-end-of-subtree t)
20459 (throw :skip t))
20460 (if (equal (char-after p) ?#) (throw :skip t))
20461 (when (and (or (setq fp (functionp org-agenda-skip-function))
20462 (consp org-agenda-skip-function))
20463 (setq to (save-excursion
20464 (save-match-data
20465 (if fp
20466 (funcall org-agenda-skip-function)
20467 (eval org-agenda-skip-function))))))
20468 (goto-char to)
20469 (throw :skip t))))
20471 (defvar org-agenda-markers nil
20472 "List of all currently active markers created by `org-agenda'.")
20473 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20474 "Creation time of the last agenda marker.")
20476 (defun org-agenda-new-marker (&optional pos)
20477 "Return a new agenda marker.
20478 Org-mode keeps a list of these markers and resets them when they are
20479 no longer in use."
20480 (let ((m (copy-marker (or pos (point)))))
20481 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20482 (push m org-agenda-markers)
20485 (defun org-agenda-reset-markers ()
20486 "Reset markers created by `org-agenda'."
20487 (while org-agenda-markers
20488 (move-marker (pop org-agenda-markers) nil)))
20490 (defun org-get-agenda-file-buffer (file)
20491 "Get a buffer visiting FILE. If the buffer needs to be created, add
20492 it to the list of buffers which might be released later."
20493 (let ((buf (org-find-base-buffer-visiting file)))
20494 (if buf
20495 buf ; just return it
20496 ;; Make a new buffer and remember it
20497 (setq buf (find-file-noselect file))
20498 (if buf (push buf org-agenda-new-buffers))
20499 buf)))
20501 (defun org-release-buffers (blist)
20502 "Release all buffers in list, asking the user for confirmation when needed.
20503 When a buffer is unmodified, it is just killed. When modified, it is saved
20504 \(if the user agrees) and then killed."
20505 (let (buf file)
20506 (while (setq buf (pop blist))
20507 (setq file (buffer-file-name buf))
20508 (when (and (buffer-modified-p buf)
20509 file
20510 (y-or-n-p (format "Save file %s? " file)))
20511 (with-current-buffer buf (save-buffer)))
20512 (kill-buffer buf))))
20514 (defun org-get-category (&optional pos)
20515 "Get the category applying to position POS."
20516 (get-text-property (or pos (point)) 'org-category))
20518 ;;; Agenda timeline
20520 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20522 (defun org-timeline (&optional include-all)
20523 "Show a time-sorted view of the entries in the current org file.
20524 Only entries with a time stamp of today or later will be listed. With
20525 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20526 under the current date.
20527 If the buffer contains an active region, only check the region for
20528 dates."
20529 (interactive "P")
20530 (require 'calendar)
20531 (org-compile-prefix-format 'timeline)
20532 (org-set-sorting-strategy 'timeline)
20533 (let* ((dopast t)
20534 (dotodo include-all)
20535 (doclosed org-agenda-show-log)
20536 (entry buffer-file-name)
20537 (date (calendar-current-date))
20538 (beg (if (org-region-active-p) (region-beginning) (point-min)))
20539 (end (if (org-region-active-p) (region-end) (point-max)))
20540 (day-numbers (org-get-all-dates beg end 'no-ranges
20541 t doclosed ; always include today
20542 org-timeline-show-empty-dates))
20543 (org-deadline-warning-days 0)
20544 (org-agenda-only-exact-dates t)
20545 (today (time-to-days (current-time)))
20546 (past t)
20547 args
20548 s e rtn d emptyp)
20549 (setq org-agenda-redo-command
20550 (list 'progn
20551 (list 'org-switch-to-buffer-other-window (current-buffer))
20552 (list 'org-timeline (list 'quote include-all))))
20553 (if (not dopast)
20554 ;; Remove past dates from the list of dates.
20555 (setq day-numbers (delq nil (mapcar (lambda(x)
20556 (if (>= x today) x nil))
20557 day-numbers))))
20558 (org-prepare-agenda (concat "Timeline "
20559 (file-name-nondirectory buffer-file-name)))
20560 (if doclosed (push :closed args))
20561 (push :timestamp args)
20562 (push :deadline args)
20563 (push :scheduled args)
20564 (push :sexp args)
20565 (if dotodo (push :todo args))
20566 (while (setq d (pop day-numbers))
20567 (if (and (listp d) (eq (car d) :omitted))
20568 (progn
20569 (setq s (point))
20570 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20571 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20572 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20573 (if (and (>= d today)
20574 dopast
20575 past)
20576 (progn
20577 (setq past nil)
20578 (insert (make-string 79 ?-) "\n")))
20579 (setq date (calendar-gregorian-from-absolute d))
20580 (setq s (point))
20581 (setq rtn (and (not emptyp)
20582 (apply 'org-agenda-get-day-entries entry
20583 date args)))
20584 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20585 (progn
20586 (insert
20587 (if (stringp org-agenda-format-date)
20588 (format-time-string org-agenda-format-date
20589 (org-time-from-absolute date))
20590 (funcall org-agenda-format-date date))
20591 "\n")
20592 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20593 (put-text-property s (1- (point)) 'org-date-line t)
20594 (if (equal d today)
20595 (put-text-property s (1- (point)) 'org-today t))
20596 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20597 (put-text-property s (1- (point)) 'day d)))))
20598 (goto-char (point-min))
20599 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20600 (point-min)))
20601 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20602 (org-finalize-agenda)
20603 (setq buffer-read-only t)))
20605 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty pre-re)
20606 "Return a list of all relevant day numbers from BEG to END buffer positions.
20607 If NO-RANGES is non-nil, include only the start and end dates of a range,
20608 not every single day in the range. If FORCE-TODAY is non-nil, make
20609 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20610 inactive time stamps (those in square brackets) are included.
20611 When EMPTY is non-nil, also include days without any entries."
20612 (let ((re (concat
20613 (if pre-re pre-re "")
20614 (if inactive org-ts-regexp-both org-ts-regexp)))
20615 dates dates1 date day day1 day2 ts1 ts2)
20616 (if force-today
20617 (setq dates (list (time-to-days (current-time)))))
20618 (save-excursion
20619 (goto-char beg)
20620 (while (re-search-forward re end t)
20621 (setq day (time-to-days (org-time-string-to-time
20622 (substring (match-string 1) 0 10))))
20623 (or (memq day dates) (push day dates)))
20624 (unless no-ranges
20625 (goto-char beg)
20626 (while (re-search-forward org-tr-regexp end t)
20627 (setq ts1 (substring (match-string 1) 0 10)
20628 ts2 (substring (match-string 2) 0 10)
20629 day1 (time-to-days (org-time-string-to-time ts1))
20630 day2 (time-to-days (org-time-string-to-time ts2)))
20631 (while (< (setq day1 (1+ day1)) day2)
20632 (or (memq day1 dates) (push day1 dates)))))
20633 (setq dates (sort dates '<))
20634 (when empty
20635 (while (setq day (pop dates))
20636 (setq day2 (car dates))
20637 (push day dates1)
20638 (when (and day2 empty)
20639 (if (or (eq empty t)
20640 (and (numberp empty) (<= (- day2 day) empty)))
20641 (while (< (setq day (1+ day)) day2)
20642 (push (list day) dates1))
20643 (push (cons :omitted (- day2 day)) dates1))))
20644 (setq dates (nreverse dates1)))
20645 dates)))
20647 ;;; Agenda Daily/Weekly
20649 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
20650 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
20651 (defvar org-agenda-last-arguments nil
20652 "The arguments of the previous call to org-agenda")
20653 (defvar org-starting-day nil) ; local variable in the agenda buffer
20654 (defvar org-agenda-span nil) ; local variable in the agenda buffer
20655 (defvar org-include-all-loc nil) ; local variable
20656 (defvar org-agenda-remove-date nil) ; dynamically scoped
20658 ;;;###autoload
20659 (defun org-agenda-list (&optional include-all start-day ndays)
20660 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
20661 The view will be for the current day or week, but from the overview buffer
20662 you will be able to go to other days/weeks.
20664 With one \\[universal-argument] prefix argument INCLUDE-ALL,
20665 all unfinished TODO items will also be shown, before the agenda.
20666 This feature is considered obsolete, please use the TODO list or a block
20667 agenda instead.
20669 With a numeric prefix argument in an interactive call, the agenda will
20670 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
20671 the number of days. NDAYS defaults to `org-agenda-ndays'.
20673 START-DAY defaults to TODAY, or to the most recent match for the weekday
20674 given in `org-agenda-start-on-weekday'."
20675 (interactive "P")
20676 (if (and (integerp include-all) (> include-all 0))
20677 (setq ndays include-all include-all nil))
20678 (setq ndays (or ndays org-agenda-ndays)
20679 start-day (or start-day org-agenda-start-day))
20680 (if org-agenda-overriding-arguments
20681 (setq include-all (car org-agenda-overriding-arguments)
20682 start-day (nth 1 org-agenda-overriding-arguments)
20683 ndays (nth 2 org-agenda-overriding-arguments)))
20684 (if (stringp start-day)
20685 ;; Convert to an absolute day number
20686 (setq start-day (time-to-days (org-read-date nil t start-day))))
20687 (setq org-agenda-last-arguments (list include-all start-day ndays))
20688 (org-compile-prefix-format 'agenda)
20689 (org-set-sorting-strategy 'agenda)
20690 (require 'calendar)
20691 (let* ((org-agenda-start-on-weekday
20692 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
20693 org-agenda-start-on-weekday nil))
20694 (thefiles (org-agenda-files))
20695 (files thefiles)
20696 (today (time-to-days
20697 (time-subtract (current-time)
20698 (list 0 (* 3600 org-extend-today-until) 0))))
20699 (sd (or start-day today))
20700 (start (if (or (null org-agenda-start-on-weekday)
20701 (< org-agenda-ndays 7))
20703 (let* ((nt (calendar-day-of-week
20704 (calendar-gregorian-from-absolute sd)))
20705 (n1 org-agenda-start-on-weekday)
20706 (d (- nt n1)))
20707 (- sd (+ (if (< d 0) 7 0) d)))))
20708 (day-numbers (list start))
20709 (day-cnt 0)
20710 (inhibit-redisplay (not debug-on-error))
20711 s e rtn rtnall file date d start-pos end-pos todayp nd)
20712 (setq org-agenda-redo-command
20713 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
20714 ;; Make the list of days
20715 (setq ndays (or ndays org-agenda-ndays)
20716 nd ndays)
20717 (while (> ndays 1)
20718 (push (1+ (car day-numbers)) day-numbers)
20719 (setq ndays (1- ndays)))
20720 (setq day-numbers (nreverse day-numbers))
20721 (org-prepare-agenda "Day/Week")
20722 (org-set-local 'org-starting-day (car day-numbers))
20723 (org-set-local 'org-include-all-loc include-all)
20724 (org-set-local 'org-agenda-span
20725 (org-agenda-ndays-to-span nd))
20726 (when (and (or include-all org-agenda-include-all-todo)
20727 (member today day-numbers))
20728 (setq files thefiles
20729 rtnall nil)
20730 (while (setq file (pop files))
20731 (catch 'nextfile
20732 (org-check-agenda-file file)
20733 (setq date (calendar-gregorian-from-absolute today)
20734 rtn (org-agenda-get-day-entries
20735 file date :todo))
20736 (setq rtnall (append rtnall rtn))))
20737 (when rtnall
20738 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
20739 (add-text-properties (point-min) (1- (point))
20740 (list 'face 'org-agenda-structure))
20741 (insert (org-finalize-agenda-entries rtnall) "\n")))
20742 (unless org-agenda-compact-blocks
20743 (setq s (point))
20744 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
20745 "-agenda:\n")
20746 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
20747 'org-date-line t)))
20748 (while (setq d (pop day-numbers))
20749 (setq date (calendar-gregorian-from-absolute d)
20750 s (point))
20751 (if (or (setq todayp (= d today))
20752 (and (not start-pos) (= d sd)))
20753 (setq start-pos (point))
20754 (if (and start-pos (not end-pos))
20755 (setq end-pos (point))))
20756 (setq files thefiles
20757 rtnall nil)
20758 (while (setq file (pop files))
20759 (catch 'nextfile
20760 (org-check-agenda-file file)
20761 (if org-agenda-show-log
20762 (setq rtn (org-agenda-get-day-entries
20763 file date
20764 :deadline :scheduled :timestamp :sexp :closed))
20765 (setq rtn (org-agenda-get-day-entries
20766 file date
20767 :deadline :scheduled :sexp :timestamp)))
20768 (setq rtnall (append rtnall rtn))))
20769 (if org-agenda-include-diary
20770 (progn
20771 (require 'diary-lib)
20772 (setq rtn (org-get-entries-from-diary date))
20773 (setq rtnall (append rtnall rtn))))
20774 (if (or rtnall org-agenda-show-all-dates)
20775 (progn
20776 (setq day-cnt (1+ day-cnt))
20777 (insert
20778 (if (stringp org-agenda-format-date)
20779 (format-time-string org-agenda-format-date
20780 (org-time-from-absolute date))
20781 (funcall org-agenda-format-date date))
20782 "\n")
20783 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20784 (put-text-property s (1- (point)) 'org-date-line t)
20785 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
20786 (if todayp (put-text-property s (1- (point)) 'org-today t))
20787 (if rtnall (insert
20788 (org-finalize-agenda-entries
20789 (org-agenda-add-time-grid-maybe
20790 rtnall nd todayp))
20791 "\n"))
20792 (put-text-property s (1- (point)) 'day d)
20793 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
20794 (goto-char (point-min))
20795 (org-fit-agenda-window)
20796 (unless (and (pos-visible-in-window-p (point-min))
20797 (pos-visible-in-window-p (point-max)))
20798 (goto-char (1- (point-max)))
20799 (recenter -1)
20800 (if (not (pos-visible-in-window-p (or start-pos 1)))
20801 (progn
20802 (goto-char (or start-pos 1))
20803 (recenter 1))))
20804 (goto-char (or start-pos 1))
20805 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
20806 (org-finalize-agenda)
20807 (setq buffer-read-only t)
20808 (message "")))
20810 (defun org-agenda-ndays-to-span (n)
20811 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
20813 ;;; Agenda TODO list
20815 (defvar org-select-this-todo-keyword nil)
20816 (defvar org-last-arg nil)
20818 ;;;###autoload
20819 (defun org-todo-list (arg)
20820 "Show all TODO entries from all agenda file in a single list.
20821 The prefix arg can be used to select a specific TODO keyword and limit
20822 the list to these. When using \\[universal-argument], you will be prompted
20823 for a keyword. A numeric prefix directly selects the Nth keyword in
20824 `org-todo-keywords-1'."
20825 (interactive "P")
20826 (require 'calendar)
20827 (org-compile-prefix-format 'todo)
20828 (org-set-sorting-strategy 'todo)
20829 (org-prepare-agenda "TODO")
20830 (let* ((today (time-to-days (current-time)))
20831 (date (calendar-gregorian-from-absolute today))
20832 (kwds org-todo-keywords-for-agenda)
20833 (completion-ignore-case t)
20834 (org-select-this-todo-keyword
20835 (if (stringp arg) arg
20836 (and arg (integerp arg) (> arg 0)
20837 (nth (1- arg) kwds))))
20838 rtn rtnall files file pos)
20839 (when (equal arg '(4))
20840 (setq org-select-this-todo-keyword
20841 (completing-read "Keyword (or KWD1|K2D2|...): "
20842 (mapcar 'list kwds) nil nil)))
20843 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
20844 (org-set-local 'org-last-arg arg)
20845 (setq org-agenda-redo-command
20846 '(org-todo-list (or current-prefix-arg org-last-arg)))
20847 (setq files (org-agenda-files)
20848 rtnall nil)
20849 (while (setq file (pop files))
20850 (catch 'nextfile
20851 (org-check-agenda-file file)
20852 (setq rtn (org-agenda-get-day-entries file date :todo))
20853 (setq rtnall (append rtnall rtn))))
20854 (if org-agenda-overriding-header
20855 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20856 nil 'face 'org-agenda-structure) "\n")
20857 (insert "Global list of TODO items of type: ")
20858 (add-text-properties (point-min) (1- (point))
20859 (list 'face 'org-agenda-structure))
20860 (setq pos (point))
20861 (insert (or org-select-this-todo-keyword "ALL") "\n")
20862 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20863 (setq pos (point))
20864 (unless org-agenda-multi
20865 (insert "Available with `N r': (0)ALL")
20866 (let ((n 0) s)
20867 (mapc (lambda (x)
20868 (setq s (format "(%d)%s" (setq n (1+ n)) x))
20869 (if (> (+ (current-column) (string-width s) 1) (frame-width))
20870 (insert "\n "))
20871 (insert " " s))
20872 kwds))
20873 (insert "\n"))
20874 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20875 (when rtnall
20876 (insert (org-finalize-agenda-entries rtnall) "\n"))
20877 (goto-char (point-min))
20878 (org-fit-agenda-window)
20879 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
20880 (org-finalize-agenda)
20881 (setq buffer-read-only t)))
20883 ;;; Agenda tags match
20885 ;;;###autoload
20886 (defun org-tags-view (&optional todo-only match)
20887 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
20888 The prefix arg TODO-ONLY limits the search to TODO entries."
20889 (interactive "P")
20890 (org-compile-prefix-format 'tags)
20891 (org-set-sorting-strategy 'tags)
20892 (let* ((org-tags-match-list-sublevels
20893 (if todo-only t org-tags-match-list-sublevels))
20894 (completion-ignore-case t)
20895 rtn rtnall files file pos matcher
20896 buffer)
20897 (setq matcher (org-make-tags-matcher match)
20898 match (car matcher) matcher (cdr matcher))
20899 (org-prepare-agenda (concat "TAGS " match))
20900 (setq org-agenda-redo-command
20901 (list 'org-tags-view (list 'quote todo-only)
20902 (list 'if 'current-prefix-arg nil match)))
20903 (setq files (org-agenda-files)
20904 rtnall nil)
20905 (while (setq file (pop files))
20906 (catch 'nextfile
20907 (org-check-agenda-file file)
20908 (setq buffer (if (file-exists-p file)
20909 (org-get-agenda-file-buffer file)
20910 (error "No such file %s" file)))
20911 (if (not buffer)
20912 ;; If file does not exist, merror message to agenda
20913 (setq rtn (list
20914 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
20915 rtnall (append rtnall rtn))
20916 (with-current-buffer buffer
20917 (unless (org-mode-p)
20918 (error "Agenda file %s is not in `org-mode'" file))
20919 (save-excursion
20920 (save-restriction
20921 (if org-agenda-restrict
20922 (narrow-to-region org-agenda-restrict-begin
20923 org-agenda-restrict-end)
20924 (widen))
20925 (setq rtn (org-scan-tags 'agenda matcher todo-only))
20926 (setq rtnall (append rtnall rtn))))))))
20927 (if org-agenda-overriding-header
20928 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20929 nil 'face 'org-agenda-structure) "\n")
20930 (insert "Headlines with TAGS match: ")
20931 (add-text-properties (point-min) (1- (point))
20932 (list 'face 'org-agenda-structure))
20933 (setq pos (point))
20934 (insert match "\n")
20935 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20936 (setq pos (point))
20937 (unless org-agenda-multi
20938 (insert "Press `C-u r' to search again with new search string\n"))
20939 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20940 (when rtnall
20941 (insert (org-finalize-agenda-entries rtnall) "\n"))
20942 (goto-char (point-min))
20943 (org-fit-agenda-window)
20944 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
20945 (org-finalize-agenda)
20946 (setq buffer-read-only t)))
20948 ;;; Agenda Finding stuck projects
20950 (defvar org-agenda-skip-regexp nil
20951 "Regular expression used in skipping subtrees for the agenda.
20952 This is basically a temporary global variable that can be set and then
20953 used by user-defined selections using `org-agenda-skip-function'.")
20955 (defvar org-agenda-overriding-header nil
20956 "When this is set during todo and tags searches, will replace header.")
20958 (defun org-agenda-skip-subtree-when-regexp-matches ()
20959 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
20960 If yes, it returns the end position of this tree, causing agenda commands
20961 to skip this subtree. This is a function that can be put into
20962 `org-agenda-skip-function' for the duration of a command."
20963 (let ((end (save-excursion (org-end-of-subtree t)))
20964 skip)
20965 (save-excursion
20966 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
20967 (and skip end)))
20969 (defun org-agenda-skip-entry-if (&rest conditions)
20970 "Skip entry if any of CONDITIONS is true.
20971 See `org-agenda-skip-if' for details."
20972 (org-agenda-skip-if nil conditions))
20974 (defun org-agenda-skip-subtree-if (&rest conditions)
20975 "Skip entry if any of CONDITIONS is true.
20976 See `org-agenda-skip-if' for details."
20977 (org-agenda-skip-if t conditions))
20979 (defun org-agenda-skip-if (subtree conditions)
20980 "Checks current entity for CONDITIONS.
20981 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
20982 the entry, i.e. the text before the next heading is checked.
20984 CONDITIONS is a list of symbols, boolean OR is used to combine the results
20985 from different tests. Valid conditions are:
20987 scheduled Check if there is a scheduled cookie
20988 notscheduled Check if there is no scheduled cookie
20989 deadline Check if there is a deadline
20990 notdeadline Check if there is no deadline
20991 regexp Check if regexp matches
20992 notregexp Check if regexp does not match.
20994 The regexp is taken from the conditions list, it must come right after
20995 the `regexp' or `notregexp' element.
20997 If any of these conditions is met, this function returns the end point of
20998 the entity, causing the search to continue from there. This is a function
20999 that can be put into `org-agenda-skip-function' for the duration of a command."
21000 (let (beg end m)
21001 (org-back-to-heading t)
21002 (setq beg (point)
21003 end (if subtree
21004 (progn (org-end-of-subtree t) (point))
21005 (progn (outline-next-heading) (1- (point)))))
21006 (goto-char beg)
21007 (and
21009 (and (memq 'scheduled conditions)
21010 (re-search-forward org-scheduled-time-regexp end t))
21011 (and (memq 'notscheduled conditions)
21012 (not (re-search-forward org-scheduled-time-regexp end t)))
21013 (and (memq 'deadline conditions)
21014 (re-search-forward org-deadline-time-regexp end t))
21015 (and (memq 'notdeadline conditions)
21016 (not (re-search-forward org-deadline-time-regexp end t)))
21017 (and (setq m (memq 'regexp conditions))
21018 (stringp (nth 1 m))
21019 (re-search-forward (nth 1 m) end t))
21020 (and (setq m (memq 'notregexp conditions))
21021 (stringp (nth 1 m))
21022 (not (re-search-forward (nth 1 m) end t))))
21023 end)))
21025 ;;;###autoload
21026 (defun org-agenda-list-stuck-projects (&rest ignore)
21027 "Create agenda view for projects that are stuck.
21028 Stuck projects are project that have no next actions. For the definitions
21029 of what a project is and how to check if it stuck, customize the variable
21030 `org-stuck-projects'.
21031 MATCH is being ignored."
21032 (interactive)
21033 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
21034 ;; FIXME: we could have used org-agenda-skip-if here.
21035 (org-agenda-overriding-header "List of stuck projects: ")
21036 (matcher (nth 0 org-stuck-projects))
21037 (todo (nth 1 org-stuck-projects))
21038 (todo-wds (if (member "*" todo)
21039 (progn
21040 (org-prepare-agenda-buffers (org-agenda-files))
21041 (org-delete-all
21042 org-done-keywords-for-agenda
21043 (copy-sequence org-todo-keywords-for-agenda)))
21044 todo))
21045 (todo-re (concat "^\\*+[ \t]+\\("
21046 (mapconcat 'identity todo-wds "\\|")
21047 "\\)\\>"))
21048 (tags (nth 2 org-stuck-projects))
21049 (tags-re (if (member "*" tags)
21050 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
21051 (concat "^\\*+ .*:\\("
21052 (mapconcat 'identity tags "\\|")
21053 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
21054 (gen-re (nth 3 org-stuck-projects))
21055 (re-list
21056 (delq nil
21057 (list
21058 (if todo todo-re)
21059 (if tags tags-re)
21060 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
21061 gen-re)))))
21062 (setq org-agenda-skip-regexp
21063 (if re-list
21064 (mapconcat 'identity re-list "\\|")
21065 (error "No information how to identify unstuck projects")))
21066 (org-tags-view nil matcher)
21067 (with-current-buffer org-agenda-buffer-name
21068 (setq org-agenda-redo-command
21069 '(org-agenda-list-stuck-projects
21070 (or current-prefix-arg org-last-arg))))))
21072 ;;; Diary integration
21074 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
21076 (defun org-get-entries-from-diary (date)
21077 "Get the (Emacs Calendar) diary entries for DATE."
21078 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
21079 (diary-display-hook '(fancy-diary-display))
21080 (pop-up-frames nil)
21081 (list-diary-entries-hook
21082 (cons 'org-diary-default-entry list-diary-entries-hook))
21083 (diary-file-name-prefix-function nil) ; turn this feature off
21084 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
21085 entries
21086 (org-disable-agenda-to-diary t))
21087 (save-excursion
21088 (save-window-excursion
21089 (funcall (if (fboundp 'diary-list-entries)
21090 'diary-list-entries 'list-diary-entries)
21091 date 1)))
21092 (if (not (get-buffer fancy-diary-buffer))
21093 (setq entries nil)
21094 (with-current-buffer fancy-diary-buffer
21095 (setq buffer-read-only nil)
21096 (if (zerop (buffer-size))
21097 ;; No entries
21098 (setq entries nil)
21099 ;; Omit the date and other unnecessary stuff
21100 (org-agenda-cleanup-fancy-diary)
21101 ;; Add prefix to each line and extend the text properties
21102 (if (zerop (buffer-size))
21103 (setq entries nil)
21104 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
21105 (set-buffer-modified-p nil)
21106 (kill-buffer fancy-diary-buffer)))
21107 (when entries
21108 (setq entries (org-split-string entries "\n"))
21109 (setq entries
21110 (mapcar
21111 (lambda (x)
21112 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
21113 ;; Extend the text properties to the beginning of the line
21114 (org-add-props x (text-properties-at (1- (length x)) x)
21115 'type "diary" 'date date))
21116 entries)))))
21118 (defun org-agenda-cleanup-fancy-diary ()
21119 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
21120 This gets rid of the date, the underline under the date, and
21121 the dummy entry installed by `org-mode' to ensure non-empty diary for each
21122 date. It also removes lines that contain only whitespace."
21123 (goto-char (point-min))
21124 (if (looking-at ".*?:[ \t]*")
21125 (progn
21126 (replace-match "")
21127 (re-search-forward "\n=+$" nil t)
21128 (replace-match "")
21129 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
21130 (re-search-forward "\n=+$" nil t)
21131 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
21132 (goto-char (point-min))
21133 (while (re-search-forward "^ +\n" nil t)
21134 (replace-match ""))
21135 (goto-char (point-min))
21136 (if (re-search-forward "^Org-mode dummy\n?" nil t)
21137 (replace-match "")))
21139 ;; Make sure entries from the diary have the right text properties.
21140 (eval-after-load "diary-lib"
21141 '(if (boundp 'diary-modify-entry-list-string-function)
21142 ;; We can rely on the hook, nothing to do
21144 ;; Hook not avaiable, must use advice to make this work
21145 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
21146 "Make the position visible."
21147 (if (and org-disable-agenda-to-diary ;; called from org-agenda
21148 (stringp string)
21149 buffer-file-name)
21150 (setq string (org-modify-diary-entry-string string))))))
21152 (defun org-modify-diary-entry-string (string)
21153 "Add text properties to string, allowing org-mode to act on it."
21154 (org-add-props string nil
21155 'mouse-face 'highlight
21156 'keymap org-agenda-keymap
21157 'help-echo (if buffer-file-name
21158 (format "mouse-2 or RET jump to diary file %s"
21159 (abbreviate-file-name buffer-file-name))
21161 'org-agenda-diary-link t
21162 'org-marker (org-agenda-new-marker (point-at-bol))))
21164 (defun org-diary-default-entry ()
21165 "Add a dummy entry to the diary.
21166 Needed to avoid empty dates which mess up holiday display."
21167 ;; Catch the error if dealing with the new add-to-diary-alist
21168 (when org-disable-agenda-to-diary
21169 (condition-case nil
21170 (add-to-diary-list original-date "Org-mode dummy" "")
21171 (error
21172 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
21174 ;;;###autoload
21175 (defun org-diary (&rest args)
21176 "Return diary information from org-files.
21177 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
21178 It accesses org files and extracts information from those files to be
21179 listed in the diary. The function accepts arguments specifying what
21180 items should be listed. The following arguments are allowed:
21182 :timestamp List the headlines of items containing a date stamp or
21183 date range matching the selected date. Deadlines will
21184 also be listed, on the expiration day.
21186 :sexp List entries resulting from diary-like sexps.
21188 :deadline List any deadlines past due, or due within
21189 `org-deadline-warning-days'. The listing occurs only
21190 in the diary for *today*, not at any other date. If
21191 an entry is marked DONE, it is no longer listed.
21193 :scheduled List all items which are scheduled for the given date.
21194 The diary for *today* also contains items which were
21195 scheduled earlier and are not yet marked DONE.
21197 :todo List all TODO items from the org-file. This may be a
21198 long list - so this is not turned on by default.
21199 Like deadlines, these entries only show up in the
21200 diary for *today*, not at any other date.
21202 The call in the diary file should look like this:
21204 &%%(org-diary) ~/path/to/some/orgfile.org
21206 Use a separate line for each org file to check. Or, if you omit the file name,
21207 all files listed in `org-agenda-files' will be checked automatically:
21209 &%%(org-diary)
21211 If you don't give any arguments (as in the example above), the default
21212 arguments (:deadline :scheduled :timestamp :sexp) are used.
21213 So the example above may also be written as
21215 &%%(org-diary :deadline :timestamp :sexp :scheduled)
21217 The function expects the lisp variables `entry' and `date' to be provided
21218 by the caller, because this is how the calendar works. Don't use this
21219 function from a program - use `org-agenda-get-day-entries' instead."
21220 (when (> (- (time-to-seconds (current-time))
21221 org-agenda-last-marker-time)
21223 (org-agenda-reset-markers))
21224 (org-compile-prefix-format 'agenda)
21225 (org-set-sorting-strategy 'agenda)
21226 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21227 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
21228 (list entry)
21229 (org-agenda-files t)))
21230 file rtn results)
21231 (org-prepare-agenda-buffers files)
21232 ;; If this is called during org-agenda, don't return any entries to
21233 ;; the calendar. Org Agenda will list these entries itself.
21234 (if org-disable-agenda-to-diary (setq files nil))
21235 (while (setq file (pop files))
21236 (setq rtn (apply 'org-agenda-get-day-entries file date args))
21237 (setq results (append results rtn)))
21238 (if results
21239 (concat (org-finalize-agenda-entries results) "\n"))))
21241 ;;; Agenda entry finders
21243 (defun org-agenda-get-day-entries (file date &rest args)
21244 "Does the work for `org-diary' and `org-agenda'.
21245 FILE is the path to a file to be checked for entries. DATE is date like
21246 the one returned by `calendar-current-date'. ARGS are symbols indicating
21247 which kind of entries should be extracted. For details about these, see
21248 the documentation of `org-diary'."
21249 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21250 (let* ((org-startup-folded nil)
21251 (org-startup-align-all-tables nil)
21252 (buffer (if (file-exists-p file)
21253 (org-get-agenda-file-buffer file)
21254 (error "No such file %s" file)))
21255 arg results rtn)
21256 (if (not buffer)
21257 ;; If file does not exist, make sure an error message ends up in diary
21258 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21259 (with-current-buffer buffer
21260 (unless (org-mode-p)
21261 (error "Agenda file %s is not in `org-mode'" file))
21262 (let ((case-fold-search nil))
21263 (save-excursion
21264 (save-restriction
21265 (if org-agenda-restrict
21266 (narrow-to-region org-agenda-restrict-begin
21267 org-agenda-restrict-end)
21268 (widen))
21269 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
21270 (while (setq arg (pop args))
21271 (cond
21272 ((and (eq arg :todo)
21273 (equal date (calendar-current-date)))
21274 (setq rtn (org-agenda-get-todos))
21275 (setq results (append results rtn)))
21276 ((eq arg :timestamp)
21277 (setq rtn (org-agenda-get-blocks))
21278 (setq results (append results rtn))
21279 (setq rtn (org-agenda-get-timestamps))
21280 (setq results (append results rtn)))
21281 ((eq arg :sexp)
21282 (setq rtn (org-agenda-get-sexps))
21283 (setq results (append results rtn)))
21284 ((eq arg :scheduled)
21285 (setq rtn (org-agenda-get-scheduled))
21286 (setq results (append results rtn)))
21287 ((eq arg :closed)
21288 (setq rtn (org-agenda-get-closed))
21289 (setq results (append results rtn)))
21290 ((eq arg :deadline)
21291 (setq rtn (org-agenda-get-deadlines))
21292 (setq results (append results rtn))))))))
21293 results))))
21295 (defun org-entry-is-todo-p ()
21296 (member (org-get-todo-state) org-not-done-keywords))
21298 (defun org-entry-is-done-p ()
21299 (member (org-get-todo-state) org-done-keywords))
21301 (defun org-get-todo-state ()
21302 (save-excursion
21303 (org-back-to-heading t)
21304 (and (looking-at org-todo-line-regexp)
21305 (match-end 2)
21306 (match-string 2))))
21308 (defun org-at-date-range-p (&optional inactive-ok)
21309 "Is the cursor inside a date range?"
21310 (interactive)
21311 (save-excursion
21312 (catch 'exit
21313 (let ((pos (point)))
21314 (skip-chars-backward "^[<\r\n")
21315 (skip-chars-backward "<[")
21316 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21317 (>= (match-end 0) pos)
21318 (throw 'exit t))
21319 (skip-chars-backward "^<[\r\n")
21320 (skip-chars-backward "<[")
21321 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21322 (>= (match-end 0) pos)
21323 (throw 'exit t)))
21324 nil)))
21326 (defun org-agenda-get-todos ()
21327 "Return the TODO information for agenda display."
21328 (let* ((props (list 'face nil
21329 'done-face 'org-done
21330 'org-not-done-regexp org-not-done-regexp
21331 'org-todo-regexp org-todo-regexp
21332 'mouse-face 'highlight
21333 'keymap org-agenda-keymap
21334 'help-echo
21335 (format "mouse-2 or RET jump to org file %s"
21336 (abbreviate-file-name buffer-file-name))))
21337 ;; FIXME: get rid of the \n at some point but watch out
21338 (regexp (concat "^\\*+[ \t]+\\("
21339 (if org-select-this-todo-keyword
21340 (if (equal org-select-this-todo-keyword "*")
21341 org-todo-regexp
21342 (concat "\\<\\("
21343 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
21344 "\\)\\>"))
21345 org-not-done-regexp)
21346 "[^\n\r]*\\)"))
21347 marker priority category tags
21348 ee txt beg end)
21349 (goto-char (point-min))
21350 (while (re-search-forward regexp nil t)
21351 (catch :skip
21352 (save-match-data
21353 (beginning-of-line)
21354 (setq beg (point) end (progn (outline-next-heading) (point)))
21355 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
21356 (re-search-forward org-ts-regexp end t))
21357 (and org-agenda-todo-ignore-scheduled (goto-char beg)
21358 (re-search-forward org-scheduled-time-regexp end t))
21359 (and org-agenda-todo-ignore-deadlines (goto-char beg)
21360 (re-search-forward org-deadline-time-regexp end t)
21361 (org-deadline-close (match-string 1))))
21362 (goto-char (1+ beg))
21363 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
21364 (throw :skip nil)))
21365 (goto-char beg)
21366 (org-agenda-skip)
21367 (goto-char (match-beginning 1))
21368 (setq marker (org-agenda-new-marker (match-beginning 0))
21369 category (org-get-category)
21370 tags (org-get-tags-at (point))
21371 txt (org-format-agenda-item "" (match-string 1) category tags)
21372 priority (1+ (org-get-priority txt)))
21373 (org-add-props txt props
21374 'org-marker marker 'org-hd-marker marker
21375 'priority priority 'org-category category
21376 'type "todo")
21377 (push txt ee)
21378 (if org-agenda-todo-list-sublevels
21379 (goto-char (match-end 1))
21380 (org-end-of-subtree 'invisible))))
21381 (nreverse ee)))
21383 (defconst org-agenda-no-heading-message
21384 "No heading for this item in buffer or region.")
21386 (defun org-agenda-get-timestamps ()
21387 "Return the date stamp information for agenda display."
21388 (let* ((props (list 'face nil
21389 'org-not-done-regexp org-not-done-regexp
21390 'org-todo-regexp org-todo-regexp
21391 'mouse-face 'highlight
21392 'keymap org-agenda-keymap
21393 'help-echo
21394 (format "mouse-2 or RET jump to org file %s"
21395 (abbreviate-file-name buffer-file-name))))
21396 (d1 (calendar-absolute-from-gregorian date))
21397 (remove-re
21398 (concat
21399 (regexp-quote
21400 (format-time-string
21401 "<%Y-%m-%d"
21402 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
21403 ".*?>"))
21404 (regexp
21405 (concat
21406 (regexp-quote
21407 (substring
21408 (format-time-string
21409 (car org-time-stamp-formats)
21410 (apply 'encode-time ; DATE bound by calendar
21411 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21412 0 11))
21413 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
21414 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
21415 marker hdmarker deadlinep scheduledp donep tmp priority category
21416 ee txt timestr tags b0 b3 e3 head)
21417 (goto-char (point-min))
21418 (while (re-search-forward regexp nil t)
21419 (setq b0 (match-beginning 0)
21420 b3 (match-beginning 3) e3 (match-end 3))
21421 (catch :skip
21422 (and (org-at-date-range-p) (throw :skip nil))
21423 (org-agenda-skip)
21424 (if (and (match-end 1)
21425 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
21426 (throw :skip nil))
21427 (if (and e3
21428 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
21429 (throw :skip nil))
21430 (setq marker (org-agenda-new-marker b0)
21431 category (org-get-category b0)
21432 tmp (buffer-substring (max (point-min)
21433 (- b0 org-ds-keyword-length))
21435 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
21436 deadlinep (string-match org-deadline-regexp tmp)
21437 scheduledp (string-match org-scheduled-regexp tmp)
21438 donep (org-entry-is-done-p))
21439 (if (or scheduledp deadlinep) (throw :skip t))
21440 (if (string-match ">" timestr)
21441 ;; substring should only run to end of time stamp
21442 (setq timestr (substring timestr 0 (match-end 0))))
21443 (save-excursion
21444 (if (re-search-backward "^\\*+ " nil t)
21445 (progn
21446 (goto-char (match-beginning 0))
21447 (setq hdmarker (org-agenda-new-marker)
21448 tags (org-get-tags-at))
21449 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21450 (setq head (match-string 1))
21451 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
21452 (setq txt (org-format-agenda-item
21453 nil head category tags timestr nil
21454 remove-re)))
21455 (setq txt org-agenda-no-heading-message))
21456 (setq priority (org-get-priority txt))
21457 (org-add-props txt props
21458 'org-marker marker 'org-hd-marker hdmarker)
21459 (org-add-props txt nil 'priority priority
21460 'org-category category 'date date
21461 'type "timestamp")
21462 (push txt ee))
21463 (outline-next-heading)))
21464 (nreverse ee)))
21466 (defun org-agenda-get-sexps ()
21467 "Return the sexp information for agenda display."
21468 (require 'diary-lib)
21469 (let* ((props (list 'face nil
21470 'mouse-face 'highlight
21471 'keymap org-agenda-keymap
21472 'help-echo
21473 (format "mouse-2 or RET jump to org file %s"
21474 (abbreviate-file-name buffer-file-name))))
21475 (regexp "^&?%%(")
21476 marker category ee txt tags entry result beg b sexp sexp-entry)
21477 (goto-char (point-min))
21478 (while (re-search-forward regexp nil t)
21479 (catch :skip
21480 (org-agenda-skip)
21481 (setq beg (match-beginning 0))
21482 (goto-char (1- (match-end 0)))
21483 (setq b (point))
21484 (forward-sexp 1)
21485 (setq sexp (buffer-substring b (point)))
21486 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
21487 (org-trim (match-string 1))
21488 ""))
21489 (setq result (org-diary-sexp-entry sexp sexp-entry date))
21490 (when result
21491 (setq marker (org-agenda-new-marker beg)
21492 category (org-get-category beg))
21494 (if (string-match "\\S-" result)
21495 (setq txt result)
21496 (setq txt "SEXP entry returned empty string"))
21498 (setq txt (org-format-agenda-item
21499 "" txt category tags 'time))
21500 (org-add-props txt props 'org-marker marker)
21501 (org-add-props txt nil
21502 'org-category category 'date date
21503 'type "sexp")
21504 (push txt ee))))
21505 (nreverse ee)))
21507 (defun org-agenda-get-closed ()
21508 "Return the logged TODO entries for agenda display."
21509 (let* ((props (list 'mouse-face 'highlight
21510 'org-not-done-regexp org-not-done-regexp
21511 'org-todo-regexp org-todo-regexp
21512 'keymap org-agenda-keymap
21513 'help-echo
21514 (format "mouse-2 or RET jump to org file %s"
21515 (abbreviate-file-name buffer-file-name))))
21516 (regexp (concat
21517 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
21518 (regexp-quote
21519 (substring
21520 (format-time-string
21521 (car org-time-stamp-formats)
21522 (apply 'encode-time ; DATE bound by calendar
21523 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21524 1 11))))
21525 marker hdmarker priority category tags closedp
21526 ee txt timestr)
21527 (goto-char (point-min))
21528 (while (re-search-forward regexp nil t)
21529 (catch :skip
21530 (org-agenda-skip)
21531 (setq marker (org-agenda-new-marker (match-beginning 0))
21532 closedp (equal (match-string 1) org-closed-string)
21533 category (org-get-category (match-beginning 0))
21534 timestr (buffer-substring (match-beginning 0) (point-at-eol))
21535 ;; donep (org-entry-is-done-p)
21537 (if (string-match "\\]" timestr)
21538 ;; substring should only run to end of time stamp
21539 (setq timestr (substring timestr 0 (match-end 0))))
21540 (save-excursion
21541 (if (re-search-backward "^\\*+ " nil t)
21542 (progn
21543 (goto-char (match-beginning 0))
21544 (setq hdmarker (org-agenda-new-marker)
21545 tags (org-get-tags-at))
21546 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21547 (setq txt (org-format-agenda-item
21548 (if closedp "Closed: " "Clocked: ")
21549 (match-string 1) category tags timestr)))
21550 (setq txt org-agenda-no-heading-message))
21551 (setq priority 100000)
21552 (org-add-props txt props
21553 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
21554 'priority priority 'org-category category
21555 'type "closed" 'date date
21556 'undone-face 'org-warning 'done-face 'org-done)
21557 (push txt ee))
21558 (goto-char (point-at-eol))))
21559 (nreverse ee)))
21561 (defun org-agenda-get-deadlines ()
21562 "Return the deadline information for agenda display."
21563 (let* ((props (list 'mouse-face 'highlight
21564 'org-not-done-regexp org-not-done-regexp
21565 'org-todo-regexp org-todo-regexp
21566 'keymap org-agenda-keymap
21567 'help-echo
21568 (format "mouse-2 or RET jump to org file %s"
21569 (abbreviate-file-name buffer-file-name))))
21570 (regexp org-deadline-time-regexp)
21571 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21572 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21573 d2 diff dfrac wdays pos pos1 category tags
21574 ee txt head face s upcomingp donep timestr)
21575 (goto-char (point-min))
21576 (while (re-search-forward regexp nil t)
21577 (catch :skip
21578 (org-agenda-skip)
21579 (setq s (match-string 1)
21580 pos (1- (match-beginning 1))
21581 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21582 diff (- d2 d1)
21583 wdays (org-get-wdays s)
21584 dfrac (/ (* 1.0 (- wdays diff)) (max wdays 1))
21585 upcomingp (and todayp (> diff 0)))
21586 ;; When to show a deadline in the calendar:
21587 ;; If the expiration is within wdays warning time.
21588 ;; Past-due deadlines are only shown on the current date
21589 (if (or (and (<= diff wdays)
21590 (and todayp (not org-agenda-only-exact-dates)))
21591 (= diff 0))
21592 (save-excursion
21593 (setq category (org-get-category))
21594 (if (re-search-backward "^\\*+[ \t]+" nil t)
21595 (progn
21596 (goto-char (match-end 0))
21597 (setq pos1 (match-beginning 0))
21598 (setq tags (org-get-tags-at pos1))
21599 (setq head (buffer-substring-no-properties
21600 (point)
21601 (progn (skip-chars-forward "^\r\n")
21602 (point))))
21603 (setq donep (string-match org-looking-at-done-regexp head))
21604 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21605 (setq timestr
21606 (concat (substring s (match-beginning 1)) " "))
21607 (setq timestr 'time))
21608 (if (and donep
21609 (or org-agenda-skip-deadline-if-done
21610 (not (= diff 0))))
21611 (setq txt nil)
21612 (setq txt (org-format-agenda-item
21613 (if (= diff 0)
21614 (car org-agenda-deadline-leaders)
21615 (format (nth 1 org-agenda-deadline-leaders)
21616 diff))
21617 head category tags timestr))))
21618 (setq txt org-agenda-no-heading-message))
21619 (when txt
21620 (setq face (org-agenda-deadline-face dfrac))
21621 (org-add-props txt props
21622 'org-marker (org-agenda-new-marker pos)
21623 'org-hd-marker (org-agenda-new-marker pos1)
21624 'priority (+ (- diff)
21625 (org-get-priority txt))
21626 'org-category category
21627 'type (if upcomingp "upcoming-deadline" "deadline")
21628 'date (if upcomingp date d2)
21629 'face (if donep 'org-done face)
21630 'undone-face face 'done-face 'org-done)
21631 (push txt ee))))))
21632 (nreverse ee)))
21634 (defun org-agenda-deadline-face (fraction)
21635 "Return the face to displaying a deadline item.
21636 FRACTION is what fraction of the head-warning time has passed."
21637 (let ((faces org-agenda-deadline-faces) f)
21638 (catch 'exit
21639 (while (setq f (pop faces))
21640 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
21642 (defun org-agenda-get-scheduled ()
21643 "Return the scheduled information for agenda display."
21644 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
21645 'org-todo-regexp org-todo-regexp
21646 'done-face 'org-done
21647 'mouse-face 'highlight
21648 'keymap org-agenda-keymap
21649 'help-echo
21650 (format "mouse-2 or RET jump to org file %s"
21651 (abbreviate-file-name buffer-file-name))))
21652 (regexp org-scheduled-time-regexp)
21653 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21654 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21655 d2 diff pos pos1 category tags
21656 ee txt head pastschedp donep face timestr s)
21657 (goto-char (point-min))
21658 (while (re-search-forward regexp nil t)
21659 (catch :skip
21660 (org-agenda-skip)
21661 (setq s (match-string 1)
21662 pos (1- (match-beginning 1))
21663 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21664 ;;; is this right?
21665 ;;; do we need to do this for deadleine too????
21666 ;;; d2 (org-time-string-to-absolute (match-string 1) (if todayp nil d1))
21667 diff (- d2 d1))
21668 (setq pastschedp (and todayp (< diff 0)))
21669 ;; When to show a scheduled item in the calendar:
21670 ;; If it is on or past the date.
21671 (if (or (and (< diff 0)
21672 (and todayp (not org-agenda-only-exact-dates)))
21673 (= diff 0))
21674 (save-excursion
21675 (setq category (org-get-category))
21676 (if (re-search-backward "^\\*+[ \t]+" nil t)
21677 (progn
21678 (goto-char (match-end 0))
21679 (setq pos1 (match-beginning 0))
21680 (setq tags (org-get-tags-at))
21681 (setq head (buffer-substring-no-properties
21682 (point)
21683 (progn (skip-chars-forward "^\r\n") (point))))
21684 (setq donep (string-match org-looking-at-done-regexp head))
21685 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21686 (setq timestr
21687 (concat (substring s (match-beginning 1)) " "))
21688 (setq timestr 'time))
21689 (if (and donep
21690 (or org-agenda-skip-scheduled-if-done
21691 (not (= diff 0))))
21692 (setq txt nil)
21693 (setq txt (org-format-agenda-item
21694 (if (= diff 0)
21695 (car org-agenda-scheduled-leaders)
21696 (format (nth 1 org-agenda-scheduled-leaders)
21697 (- 1 diff)))
21698 head category tags timestr))))
21699 (setq txt org-agenda-no-heading-message))
21700 (when txt
21701 (setq face (if pastschedp
21702 'org-scheduled-previously
21703 'org-scheduled-today))
21704 (org-add-props txt props
21705 'undone-face face
21706 'face (if donep 'org-done face)
21707 'org-marker (org-agenda-new-marker pos)
21708 'org-hd-marker (org-agenda-new-marker pos1)
21709 'type (if pastschedp "past-scheduled" "scheduled")
21710 'date (if pastschedp d2 date)
21711 'priority (+ 94 (- 5 diff) (org-get-priority txt))
21712 'org-category category)
21713 (push txt ee))))))
21714 (nreverse ee)))
21716 (defun org-agenda-get-blocks ()
21717 "Return the date-range information for agenda display."
21718 (let* ((props (list 'face nil
21719 'org-not-done-regexp org-not-done-regexp
21720 'org-todo-regexp org-todo-regexp
21721 'mouse-face 'highlight
21722 'keymap org-agenda-keymap
21723 'help-echo
21724 (format "mouse-2 or RET jump to org file %s"
21725 (abbreviate-file-name buffer-file-name))))
21726 (regexp org-tr-regexp)
21727 (d0 (calendar-absolute-from-gregorian date))
21728 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
21729 donep head)
21730 (goto-char (point-min))
21731 (while (re-search-forward regexp nil t)
21732 (catch :skip
21733 (org-agenda-skip)
21734 (setq pos (point))
21735 (setq timestr (match-string 0)
21736 s1 (match-string 1)
21737 s2 (match-string 2)
21738 d1 (time-to-days (org-time-string-to-time s1))
21739 d2 (time-to-days (org-time-string-to-time s2)))
21740 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
21741 ;; Only allow days between the limits, because the normal
21742 ;; date stamps will catch the limits.
21743 (save-excursion
21744 (setq marker (org-agenda-new-marker (point)))
21745 (setq category (org-get-category))
21746 (if (re-search-backward "^\\*+ " nil t)
21747 (progn
21748 (goto-char (match-beginning 0))
21749 (setq hdmarker (org-agenda-new-marker (point)))
21750 (setq tags (org-get-tags-at))
21751 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21752 (setq head (match-string 1))
21753 (and org-agenda-skip-timestamp-if-done
21754 (org-entry-is-done-p)
21755 (throw :skip t))
21756 (setq txt (org-format-agenda-item
21757 (format (if (= d1 d2) "" "(%d/%d): ")
21758 (1+ (- d0 d1)) (1+ (- d2 d1)))
21759 head category tags
21760 (if (= d0 d1) timestr))))
21761 (setq txt org-agenda-no-heading-message))
21762 (org-add-props txt props
21763 'org-marker marker 'org-hd-marker hdmarker
21764 'type "block" 'date date
21765 'priority (org-get-priority txt) 'org-category category)
21766 (push txt ee)))
21767 (goto-char pos)))
21768 ;; Sort the entries by expiration date.
21769 (nreverse ee)))
21771 ;;; Agenda presentation and sorting
21773 (defconst org-plain-time-of-day-regexp
21774 (concat
21775 "\\(\\<[012]?[0-9]"
21776 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21777 "\\(--?"
21778 "\\(\\<[012]?[0-9]"
21779 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21780 "\\)?")
21781 "Regular expression to match a plain time or time range.
21782 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
21783 groups carry important information:
21784 0 the full match
21785 1 the first time, range or not
21786 8 the second time, if it is a range.")
21788 (defconst org-plain-time-extension-regexp
21789 (concat
21790 "\\(\\<[012]?[0-9]"
21791 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21792 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
21793 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
21794 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
21795 groups carry important information:
21796 0 the full match
21797 7 hours of duration
21798 9 minutes of duration")
21800 (defconst org-stamp-time-of-day-regexp
21801 (concat
21802 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
21803 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
21804 "\\(--?"
21805 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
21806 "Regular expression to match a timestamp time or time range.
21807 After a match, the following groups carry important information:
21808 0 the full match
21809 1 date plus weekday, for backreferencing to make sure both times on same day
21810 2 the first time, range or not
21811 4 the second time, if it is a range.")
21813 (defvar org-prefix-has-time nil
21814 "A flag, set by `org-compile-prefix-format'.
21815 The flag is set if the currently compiled format contains a `%t'.")
21816 (defvar org-prefix-has-tag nil
21817 "A flag, set by `org-compile-prefix-format'.
21818 The flag is set if the currently compiled format contains a `%T'.")
21820 (defun org-format-agenda-item (extra txt &optional category tags dotime
21821 noprefix remove-re)
21822 "Format TXT to be inserted into the agenda buffer.
21823 In particular, it adds the prefix and corresponding text properties. EXTRA
21824 must be a string and replaces the `%s' specifier in the prefix format.
21825 CATEGORY (string, symbol or nil) may be used to overrule the default
21826 category taken from local variable or file name. It will replace the `%c'
21827 specifier in the format. DOTIME, when non-nil, indicates that a
21828 time-of-day should be extracted from TXT for sorting of this entry, and for
21829 the `%t' specifier in the format. When DOTIME is a string, this string is
21830 searched for a time before TXT is. NOPREFIX is a flag and indicates that
21831 only the correctly processes TXT should be returned - this is used by
21832 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
21833 Any match of REMOVE-RE will be removed from TXT."
21834 (save-match-data
21835 ;; Diary entries sometimes have extra whitespace at the beginning
21836 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
21837 (let* ((category (or category
21838 org-category
21839 (if buffer-file-name
21840 (file-name-sans-extension
21841 (file-name-nondirectory buffer-file-name))
21842 "")))
21843 (tag (if tags (nth (1- (length tags)) tags) ""))
21844 time ; time and tag are needed for the eval of the prefix format
21845 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
21846 (time-of-day (and dotime (org-get-time-of-day ts)))
21847 stamp plain s0 s1 s2 rtn srp)
21848 (when (and dotime time-of-day org-prefix-has-time)
21849 ;; Extract starting and ending time and move them to prefix
21850 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
21851 (setq plain (string-match org-plain-time-of-day-regexp ts)))
21852 (setq s0 (match-string 0 ts)
21853 srp (and stamp (match-end 3))
21854 s1 (match-string (if plain 1 2) ts)
21855 s2 (match-string (if plain 8 (if srp 4 6)) ts))
21857 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
21858 ;; them, we might want to remove them there to avoid duplication.
21859 ;; The user can turn this off with a variable.
21860 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
21861 (string-match (concat (regexp-quote s0) " *") txt)
21862 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
21863 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
21864 (= (match-beginning 0) 0)
21866 (setq txt (replace-match "" nil nil txt))))
21867 ;; Normalize the time(s) to 24 hour
21868 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
21869 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
21871 (when (and s1 (not s2) org-agenda-default-appointment-duration
21872 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
21873 (let ((m (+ (string-to-number (match-string 2 s1))
21874 (* 60 (string-to-number (match-string 1 s1)))
21875 org-agenda-default-appointment-duration))
21877 (setq h (/ m 60) m (- m (* h 60)))
21878 (setq s2 (format "%02d:%02d" h m))))
21880 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
21881 txt)
21882 ;; Tags are in the string
21883 (if (or (eq org-agenda-remove-tags t)
21884 (and org-agenda-remove-tags
21885 org-prefix-has-tag))
21886 (setq txt (replace-match "" t t txt))
21887 (setq txt (replace-match
21888 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
21889 (match-string 2 txt))
21890 t t txt))))
21892 (when remove-re
21893 (while (string-match remove-re txt)
21894 (setq txt (replace-match "" t t txt))))
21896 ;; Create the final string
21897 (if noprefix
21898 (setq rtn txt)
21899 ;; Prepare the variables needed in the eval of the compiled format
21900 (setq time (cond (s2 (concat s1 "-" s2))
21901 (s1 (concat s1 "......"))
21902 (t ""))
21903 extra (or extra "")
21904 category (if (symbolp category) (symbol-name category) category))
21905 ;; Evaluate the compiled format
21906 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
21908 ;; And finally add the text properties
21909 (org-add-props rtn nil
21910 'org-category (downcase category) 'tags tags
21911 'org-highest-priority org-highest-priority
21912 'org-lowest-priority org-lowest-priority
21913 'prefix-length (- (length rtn) (length txt))
21914 'time-of-day time-of-day
21915 'txt txt
21916 'time time
21917 'extra extra
21918 'dotime dotime))))
21920 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
21921 (defvar org-agenda-sorting-strategy-selected nil)
21923 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
21924 (catch 'exit
21925 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
21926 ((and todayp (member 'today (car org-agenda-time-grid))))
21927 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
21928 ((member 'weekly (car org-agenda-time-grid)))
21929 (t (throw 'exit list)))
21930 (let* ((have (delq nil (mapcar
21931 (lambda (x) (get-text-property 1 'time-of-day x))
21932 list)))
21933 (string (nth 1 org-agenda-time-grid))
21934 (gridtimes (nth 2 org-agenda-time-grid))
21935 (req (car org-agenda-time-grid))
21936 (remove (member 'remove-match req))
21937 new time)
21938 (if (and (member 'require-timed req) (not have))
21939 ;; don't show empty grid
21940 (throw 'exit list))
21941 (while (setq time (pop gridtimes))
21942 (unless (and remove (member time have))
21943 (setq time (int-to-string time))
21944 (push (org-format-agenda-item
21945 nil string "" nil
21946 (concat (substring time 0 -2) ":" (substring time -2)))
21947 new)
21948 (put-text-property
21949 1 (length (car new)) 'face 'org-time-grid (car new))))
21950 (if (member 'time-up org-agenda-sorting-strategy-selected)
21951 (append new list)
21952 (append list new)))))
21954 (defun org-compile-prefix-format (key)
21955 "Compile the prefix format into a Lisp form that can be evaluated.
21956 The resulting form is returned and stored in the variable
21957 `org-prefix-format-compiled'."
21958 (setq org-prefix-has-time nil org-prefix-has-tag nil)
21959 (let ((s (cond
21960 ((stringp org-agenda-prefix-format)
21961 org-agenda-prefix-format)
21962 ((assq key org-agenda-prefix-format)
21963 (cdr (assq key org-agenda-prefix-format)))
21964 (t " %-12:c%?-12t% s")))
21965 (start 0)
21966 varform vars var e c f opt)
21967 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
21968 s start)
21969 (setq var (cdr (assoc (match-string 4 s)
21970 '(("c" . category) ("t" . time) ("s" . extra)
21971 ("T" . tag))))
21972 c (or (match-string 3 s) "")
21973 opt (match-beginning 1)
21974 start (1+ (match-beginning 0)))
21975 (if (equal var 'time) (setq org-prefix-has-time t))
21976 (if (equal var 'tag) (setq org-prefix-has-tag t))
21977 (setq f (concat "%" (match-string 2 s) "s"))
21978 (if opt
21979 (setq varform
21980 `(if (equal "" ,var)
21982 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
21983 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
21984 (setq s (replace-match "%s" t nil s))
21985 (push varform vars))
21986 (setq vars (nreverse vars))
21987 (setq org-prefix-format-compiled `(format ,s ,@vars))))
21989 (defun org-set-sorting-strategy (key)
21990 (if (symbolp (car org-agenda-sorting-strategy))
21991 ;; the old format
21992 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
21993 (setq org-agenda-sorting-strategy-selected
21994 (or (cdr (assq key org-agenda-sorting-strategy))
21995 (cdr (assq 'agenda org-agenda-sorting-strategy))
21996 '(time-up category-keep priority-down)))))
21998 (defun org-get-time-of-day (s &optional string mod24)
21999 "Check string S for a time of day.
22000 If found, return it as a military time number between 0 and 2400.
22001 If not found, return nil.
22002 The optional STRING argument forces conversion into a 5 character wide string
22003 HH:MM."
22004 (save-match-data
22005 (when
22006 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
22007 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
22008 (let* ((h (string-to-number (match-string 1 s)))
22009 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
22010 (ampm (if (match-end 4) (downcase (match-string 4 s))))
22011 (am-p (equal ampm "am"))
22012 (h1 (cond ((not ampm) h)
22013 ((= h 12) (if am-p 0 12))
22014 (t (+ h (if am-p 0 12)))))
22015 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
22016 (mod h1 24) h1))
22017 (t0 (+ (* 100 h2) m))
22018 (t1 (concat (if (>= h1 24) "+" " ")
22019 (if (< t0 100) "0" "")
22020 (if (< t0 10) "0" "")
22021 (int-to-string t0))))
22022 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
22024 (defun org-finalize-agenda-entries (list &optional nosort)
22025 "Sort and concatenate the agenda items."
22026 (setq list (mapcar 'org-agenda-highlight-todo list))
22027 (if nosort
22028 list
22029 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
22031 (defun org-agenda-highlight-todo (x)
22032 (let (re pl)
22033 (if (eq x 'line)
22034 (save-excursion
22035 (beginning-of-line 1)
22036 (setq re (get-text-property (point) 'org-todo-regexp))
22037 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
22038 (when (looking-at (concat "[ \t]*\\.*" re " +"))
22039 (add-text-properties (match-beginning 0) (match-end 0)
22040 (list 'face (org-get-todo-face 0)))
22041 (let ((s (buffer-substring (match-beginning 1) (match-end 1))))
22042 (delete-region (match-beginning 1) (1- (match-end 0)))
22043 (goto-char (match-beginning 1))
22044 (insert (format org-agenda-todo-keyword-format s)))))
22045 (setq re (concat (get-text-property 0 'org-todo-regexp x))
22046 pl (get-text-property 0 'prefix-length x))
22047 (when (and re
22048 (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)")
22049 x (or pl 0)) pl))
22050 (add-text-properties
22051 (or (match-end 1) (match-end 0)) (match-end 0)
22052 (list 'face (org-get-todo-face (match-string 2 x)))
22054 (setq x (concat (substring x 0 (match-end 1))
22055 (format org-agenda-todo-keyword-format
22056 (match-string 2 x))
22058 (substring x (match-end 3)))))
22059 x)))
22061 (defsubst org-cmp-priority (a b)
22062 "Compare the priorities of string A and B."
22063 (let ((pa (or (get-text-property 1 'priority a) 0))
22064 (pb (or (get-text-property 1 'priority b) 0)))
22065 (cond ((> pa pb) +1)
22066 ((< pa pb) -1)
22067 (t nil))))
22069 (defsubst org-cmp-category (a b)
22070 "Compare the string values of categories of strings A and B."
22071 (let ((ca (or (get-text-property 1 'org-category a) ""))
22072 (cb (or (get-text-property 1 'org-category b) "")))
22073 (cond ((string-lessp ca cb) -1)
22074 ((string-lessp cb ca) +1)
22075 (t nil))))
22077 (defsubst org-cmp-tag (a b)
22078 "Compare the string values of categories of strings A and B."
22079 (let ((ta (car (last (get-text-property 1 'tags a))))
22080 (tb (car (last (get-text-property 1 'tags b)))))
22081 (cond ((not ta) +1)
22082 ((not tb) -1)
22083 ((string-lessp ta tb) -1)
22084 ((string-lessp tb ta) +1)
22085 (t nil))))
22087 (defsubst org-cmp-time (a b)
22088 "Compare the time-of-day values of strings A and B."
22089 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
22090 (ta (or (get-text-property 1 'time-of-day a) def))
22091 (tb (or (get-text-property 1 'time-of-day b) def)))
22092 (cond ((< ta tb) -1)
22093 ((< tb ta) +1)
22094 (t nil))))
22096 (defun org-entries-lessp (a b)
22097 "Predicate for sorting agenda entries."
22098 ;; The following variables will be used when the form is evaluated.
22099 ;; So even though the compiler complains, keep them.
22100 (let* ((time-up (org-cmp-time a b))
22101 (time-down (if time-up (- time-up) nil))
22102 (priority-up (org-cmp-priority a b))
22103 (priority-down (if priority-up (- priority-up) nil))
22104 (category-up (org-cmp-category a b))
22105 (category-down (if category-up (- category-up) nil))
22106 (category-keep (if category-up +1 nil))
22107 (tag-up (org-cmp-tag a b))
22108 (tag-down (if tag-up (- tag-up) nil)))
22109 (cdr (assoc
22110 (eval (cons 'or org-agenda-sorting-strategy-selected))
22111 '((-1 . t) (1 . nil) (nil . nil))))))
22113 ;;; Agenda restriction lock
22115 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
22116 "Overlay to mark the headline to which arenda commands are restricted.")
22117 (org-overlay-put org-agenda-restriction-lock-overlay
22118 'face 'org-agenda-restriction-lock)
22119 (org-overlay-put org-agenda-restriction-lock-overlay
22120 'help-echo "Agendas are currently limited to this subtree.")
22121 (org-detach-overlay org-agenda-restriction-lock-overlay)
22122 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
22123 "Overlay marking the agenda restriction line in speedbar.")
22124 (org-overlay-put org-speedbar-restriction-lock-overlay
22125 'face 'org-agenda-restriction-lock)
22126 (org-overlay-put org-speedbar-restriction-lock-overlay
22127 'help-echo "Agendas are currently limited to this item.")
22128 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22130 (defun org-agenda-set-restriction-lock (&optional type)
22131 "Set restriction lock for agenda, to current subtree or file.
22132 Restriction will be the file if TYPE is `file', or if type is the
22133 universal prefix '(4), or if the cursor is before the first headline
22134 in the file. Otherwise, restriction will be to the current subtree."
22135 (interactive "P")
22136 (and (equal type '(4)) (setq type 'file))
22137 (setq type (cond
22138 (type type)
22139 ((org-at-heading-p) 'subtree)
22140 ((condition-case nil (org-back-to-heading t) (error nil))
22141 'subtree)
22142 (t 'file)))
22143 (if (eq type 'subtree)
22144 (progn
22145 (setq org-agenda-restrict t)
22146 (setq org-agenda-overriding-restriction 'subtree)
22147 (put 'org-agenda-files 'org-restrict
22148 (list (buffer-file-name (buffer-base-buffer))))
22149 (org-back-to-heading t)
22150 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
22151 (move-marker org-agenda-restrict-begin (point))
22152 (move-marker org-agenda-restrict-end
22153 (save-excursion (org-end-of-subtree t)))
22154 (message "Locking agenda restriction to subtree"))
22155 (put 'org-agenda-files 'org-restrict
22156 (list (buffer-file-name (buffer-base-buffer))))
22157 (setq org-agenda-restrict nil)
22158 (setq org-agenda-overriding-restriction 'file)
22159 (move-marker org-agenda-restrict-begin nil)
22160 (move-marker org-agenda-restrict-end nil)
22161 (message "Locking agenda restriction to file"))
22162 (setq current-prefix-arg nil)
22163 (org-agenda-maybe-redo))
22165 (defun org-agenda-remove-restriction-lock (&optional noupdate)
22166 "Remove the agenda restriction lock."
22167 (interactive "P")
22168 (org-detach-overlay org-agenda-restriction-lock-overlay)
22169 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22170 (setq org-agenda-overriding-restriction nil)
22171 (setq org-agenda-restrict nil)
22172 (put 'org-agenda-files 'org-restrict nil)
22173 (move-marker org-agenda-restrict-begin nil)
22174 (move-marker org-agenda-restrict-end nil)
22175 (setq current-prefix-arg nil)
22176 (message "Agenda restriction lock removed")
22177 (or noupdate (org-agenda-maybe-redo)))
22179 (defun org-agenda-maybe-redo ()
22180 "If there is any window showing the agenda view, update it."
22181 (let ((w (get-buffer-window org-agenda-buffer-name t))
22182 (w0 (selected-window)))
22183 (when w
22184 (select-window w)
22185 (org-agenda-redo)
22186 (select-window w0)
22187 (if org-agenda-overriding-restriction
22188 (message "Agenda view shifted to new %s restriction"
22189 org-agenda-overriding-restriction)
22190 (message "Agenda restriction lock removed")))))
22192 ;;; Agenda commands
22194 (defun org-agenda-check-type (error &rest types)
22195 "Check if agenda buffer is of allowed type.
22196 If ERROR is non-nil, throw an error, otherwise just return nil."
22197 (if (memq org-agenda-type types)
22199 (if error
22200 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
22201 nil)))
22203 (defun org-agenda-quit ()
22204 "Exit agenda by removing the window or the buffer."
22205 (interactive)
22206 (let ((buf (current-buffer)))
22207 (if (not (one-window-p)) (delete-window))
22208 (kill-buffer buf)
22209 (org-agenda-reset-markers)
22210 (org-columns-remove-overlays))
22211 ;; Maybe restore the pre-agenda window configuration.
22212 (and org-agenda-restore-windows-after-quit
22213 (not (eq org-agenda-window-setup 'other-frame))
22214 org-pre-agenda-window-conf
22215 (set-window-configuration org-pre-agenda-window-conf)))
22217 (defun org-agenda-exit ()
22218 "Exit agenda by removing the window or the buffer.
22219 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
22220 Org-mode buffers visited directly by the user will not be touched."
22221 (interactive)
22222 (org-release-buffers org-agenda-new-buffers)
22223 (setq org-agenda-new-buffers nil)
22224 (org-agenda-quit))
22226 (defun org-agenda-execute (arg)
22227 "Execute another agenda command, keeping same window.\\<global-map>
22228 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
22229 (interactive "P")
22230 (let ((org-agenda-window-setup 'current-window))
22231 (org-agenda arg)))
22233 (defun org-save-all-org-buffers ()
22234 "Save all Org-mode buffers without user confirmation."
22235 (interactive)
22236 (message "Saving all Org-mode buffers...")
22237 (save-some-buffers t 'org-mode-p)
22238 (message "Saving all Org-mode buffers... done"))
22240 (defun org-agenda-redo ()
22241 "Rebuild Agenda.
22242 When this is the global TODO list, a prefix argument will be interpreted."
22243 (interactive)
22244 (let* ((org-agenda-keep-modes t)
22245 (line (org-current-line))
22246 (window-line (- line (org-current-line (window-start))))
22247 (lprops (get 'org-agenda-redo-command 'org-lprops)))
22248 (message "Rebuilding agenda buffer...")
22249 (org-let lprops '(eval org-agenda-redo-command))
22250 (setq org-agenda-undo-list nil
22251 org-agenda-pending-undo-list nil)
22252 (message "Rebuilding agenda buffer...done")
22253 (goto-line line)
22254 (recenter window-line)))
22256 (defun org-agenda-goto-date (date)
22257 "Jump to DATE in agenda."
22258 (interactive (list (org-read-date)))
22259 (org-agenda-list nil date))
22261 (defun org-agenda-goto-today ()
22262 "Go to today."
22263 (interactive)
22264 (org-agenda-check-type t 'timeline 'agenda)
22265 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
22266 (cond
22267 (tdpos (goto-char tdpos))
22268 ((eq org-agenda-type 'agenda)
22269 (let* ((sd (time-to-days
22270 (time-subtract (current-time)
22271 (list 0 (* 3600 org-extend-today-until) 0))))
22272 (comp (org-agenda-compute-time-span sd org-agenda-span))
22273 (org-agenda-overriding-arguments org-agenda-last-arguments))
22274 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
22275 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
22276 (org-agenda-redo)
22277 (org-agenda-find-same-or-today-or-agenda)))
22278 (t (error "Cannot find today")))))
22280 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
22281 (goto-char
22282 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
22283 (text-property-any (point-min) (point-max) 'org-today t)
22284 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
22285 (point-min))))
22287 (defun org-agenda-later (arg)
22288 "Go forward in time by thee current span.
22289 With prefix ARG, go forward that many times the current span."
22290 (interactive "p")
22291 (org-agenda-check-type t 'agenda)
22292 (let* ((span org-agenda-span)
22293 (sd org-starting-day)
22294 (greg (calendar-gregorian-from-absolute sd))
22295 (cnt (get-text-property (point) 'org-day-cnt))
22296 greg2 nd)
22297 (cond
22298 ((eq span 'day)
22299 (setq sd (+ arg sd) nd 1))
22300 ((eq span 'week)
22301 (setq sd (+ (* 7 arg) sd) nd 7))
22302 ((eq span 'month)
22303 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
22304 sd (calendar-absolute-from-gregorian greg2))
22305 (setcar greg2 (1+ (car greg2)))
22306 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
22307 ((eq span 'year)
22308 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
22309 sd (calendar-absolute-from-gregorian greg2))
22310 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
22311 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
22312 (let ((org-agenda-overriding-arguments
22313 (list (car org-agenda-last-arguments) sd nd t)))
22314 (org-agenda-redo)
22315 (org-agenda-find-same-or-today-or-agenda cnt))))
22317 (defun org-agenda-earlier (arg)
22318 "Go backward in time by the current span.
22319 With prefix ARG, go backward that many times the current span."
22320 (interactive "p")
22321 (org-agenda-later (- arg)))
22323 (defun org-agenda-day-view ()
22324 "Switch to daily view for agenda."
22325 (interactive)
22326 (setq org-agenda-ndays 1)
22327 (org-agenda-change-time-span 'day))
22328 (defun org-agenda-week-view ()
22329 "Switch to daily view for agenda."
22330 (interactive)
22331 (setq org-agenda-ndays 7)
22332 (org-agenda-change-time-span 'week))
22333 (defun org-agenda-month-view ()
22334 "Switch to daily view for agenda."
22335 (interactive)
22336 (org-agenda-change-time-span 'month))
22337 (defun org-agenda-year-view ()
22338 "Switch to daily view for agenda."
22339 (interactive)
22340 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
22341 (org-agenda-change-time-span 'year)
22342 (error "Abort")))
22344 (defun org-agenda-change-time-span (span)
22345 "Change the agenda view to SPAN.
22346 SPAN may be `day', `week', `month', `year'."
22347 (org-agenda-check-type t 'agenda)
22348 (if (equal org-agenda-span span)
22349 (error "Viewing span is already \"%s\"" span))
22350 (let* ((sd (or (get-text-property (point) 'day)
22351 org-starting-day))
22352 (computed (org-agenda-compute-time-span sd span))
22353 (org-agenda-overriding-arguments
22354 (list (car org-agenda-last-arguments)
22355 (car computed) (cdr computed) t)))
22356 (org-agenda-redo)
22357 (org-agenda-find-same-or-today-or-agenda))
22358 (org-agenda-set-mode-name)
22359 (message "Switched to %s view" span))
22361 (defun org-agenda-compute-time-span (sd span)
22362 "Compute starting date and number of days for agenda.
22363 SPAN may be `day', `week', `month', `year'. The return value
22364 is a cons cell with the starting date and the number of days,
22365 so that the date SD will be in that range."
22366 (let* ((greg (calendar-gregorian-from-absolute sd))
22368 (cond
22369 ((eq span 'day)
22370 (setq nd 1))
22371 ((eq span 'week)
22372 (let* ((nt (calendar-day-of-week
22373 (calendar-gregorian-from-absolute sd)))
22374 (d (if org-agenda-start-on-weekday
22375 (- nt org-agenda-start-on-weekday)
22376 0)))
22377 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
22378 (setq nd 7)))
22379 ((eq span 'month)
22380 (setq sd (calendar-absolute-from-gregorian
22381 (list (car greg) 1 (nth 2 greg)))
22382 nd (- (calendar-absolute-from-gregorian
22383 (list (1+ (car greg)) 1 (nth 2 greg)))
22384 sd)))
22385 ((eq span 'year)
22386 (setq sd (calendar-absolute-from-gregorian
22387 (list 1 1 (nth 2 greg)))
22388 nd (- (calendar-absolute-from-gregorian
22389 (list 1 1 (1+ (nth 2 greg))))
22390 sd))))
22391 (cons sd nd)))
22393 ;; FIXME: does not work if user makes date format that starts with a blank
22394 (defun org-agenda-next-date-line (&optional arg)
22395 "Jump to the next line indicating a date in agenda buffer."
22396 (interactive "p")
22397 (org-agenda-check-type t 'agenda 'timeline)
22398 (beginning-of-line 1)
22399 (if (looking-at "^\\S-") (forward-char 1))
22400 (if (not (re-search-forward "^\\S-" nil t arg))
22401 (progn
22402 (backward-char 1)
22403 (error "No next date after this line in this buffer")))
22404 (goto-char (match-beginning 0)))
22406 (defun org-agenda-previous-date-line (&optional arg)
22407 "Jump to the previous line indicating a date in agenda buffer."
22408 (interactive "p")
22409 (org-agenda-check-type t 'agenda 'timeline)
22410 (beginning-of-line 1)
22411 (if (not (re-search-backward "^\\S-" nil t arg))
22412 (error "No previous date before this line in this buffer")))
22414 ;; Initialize the highlight
22415 (defvar org-hl (org-make-overlay 1 1))
22416 (org-overlay-put org-hl 'face 'highlight)
22418 (defun org-highlight (begin end &optional buffer)
22419 "Highlight a region with overlay."
22420 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
22421 org-hl begin end (or buffer (current-buffer))))
22423 (defun org-unhighlight ()
22424 "Detach overlay INDEX."
22425 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
22427 ;; FIXME this is currently not used.
22428 (defun org-highlight-until-next-command (beg end &optional buffer)
22429 (org-highlight beg end buffer)
22430 (add-hook 'pre-command-hook 'org-unhighlight-once))
22431 (defun org-unhighlight-once ()
22432 (remove-hook 'pre-command-hook 'org-unhighlight-once)
22433 (org-unhighlight))
22435 (defun org-agenda-follow-mode ()
22436 "Toggle follow mode in an agenda buffer."
22437 (interactive)
22438 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
22439 (org-agenda-set-mode-name)
22440 (message "Follow mode is %s"
22441 (if org-agenda-follow-mode "on" "off")))
22443 (defun org-agenda-log-mode ()
22444 "Toggle log mode in an agenda buffer."
22445 (interactive)
22446 (org-agenda-check-type t 'agenda 'timeline)
22447 (setq org-agenda-show-log (not org-agenda-show-log))
22448 (org-agenda-set-mode-name)
22449 (org-agenda-redo)
22450 (message "Log mode is %s"
22451 (if org-agenda-show-log "on" "off")))
22453 (defun org-agenda-toggle-diary ()
22454 "Toggle diary inclusion in an agenda buffer."
22455 (interactive)
22456 (org-agenda-check-type t 'agenda)
22457 (setq org-agenda-include-diary (not org-agenda-include-diary))
22458 (org-agenda-redo)
22459 (org-agenda-set-mode-name)
22460 (message "Diary inclusion turned %s"
22461 (if org-agenda-include-diary "on" "off")))
22463 (defun org-agenda-toggle-time-grid ()
22464 "Toggle time grid in an agenda buffer."
22465 (interactive)
22466 (org-agenda-check-type t 'agenda)
22467 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
22468 (org-agenda-redo)
22469 (org-agenda-set-mode-name)
22470 (message "Time-grid turned %s"
22471 (if org-agenda-use-time-grid "on" "off")))
22473 (defun org-agenda-set-mode-name ()
22474 "Set the mode name to indicate all the small mode settings."
22475 (setq mode-name
22476 (concat "Org-Agenda"
22477 (if (equal org-agenda-ndays 1) " Day" "")
22478 (if (equal org-agenda-ndays 7) " Week" "")
22479 (if org-agenda-follow-mode " Follow" "")
22480 (if org-agenda-include-diary " Diary" "")
22481 (if org-agenda-use-time-grid " Grid" "")
22482 (if org-agenda-show-log " Log" "")))
22483 (force-mode-line-update))
22485 (defun org-agenda-post-command-hook ()
22486 (and (eolp) (not (bolp)) (backward-char 1))
22487 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
22488 (if (and org-agenda-follow-mode
22489 (get-text-property (point) 'org-marker))
22490 (org-agenda-show)))
22492 (defun org-agenda-show-priority ()
22493 "Show the priority of the current item.
22494 This priority is composed of the main priority given with the [#A] cookies,
22495 and by additional input from the age of a schedules or deadline entry."
22496 (interactive)
22497 (let* ((pri (get-text-property (point-at-bol) 'priority)))
22498 (message "Priority is %d" (if pri pri -1000))))
22500 (defun org-agenda-show-tags ()
22501 "Show the tags applicable to the current item."
22502 (interactive)
22503 (let* ((tags (get-text-property (point-at-bol) 'tags)))
22504 (if tags
22505 (message "Tags are :%s:"
22506 (org-no-properties (mapconcat 'identity tags ":")))
22507 (message "No tags associated with this line"))))
22509 (defun org-agenda-goto (&optional highlight)
22510 "Go to the Org-mode file which contains the item at point."
22511 (interactive)
22512 (let* ((marker (or (get-text-property (point) 'org-marker)
22513 (org-agenda-error)))
22514 (buffer (marker-buffer marker))
22515 (pos (marker-position marker)))
22516 (switch-to-buffer-other-window buffer)
22517 (widen)
22518 (goto-char pos)
22519 (when (org-mode-p)
22520 (org-show-context 'agenda)
22521 (save-excursion
22522 (and (outline-next-heading)
22523 (org-flag-heading nil)))) ; show the next heading
22524 (recenter (/ (window-height) 2))
22525 (run-hooks 'org-agenda-after-show-hook)
22526 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
22528 (defvar org-agenda-after-show-hook nil
22529 "Normal hook run after an item has been shown from the agenda.
22530 Point is in the buffer where the item originated.")
22532 (defun org-agenda-kill ()
22533 "Kill the entry or subtree belonging to the current agenda entry."
22534 (interactive)
22535 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22536 (let* ((marker (or (get-text-property (point) 'org-marker)
22537 (org-agenda-error)))
22538 (buffer (marker-buffer marker))
22539 (pos (marker-position marker))
22540 (type (get-text-property (point) 'type))
22541 dbeg dend (n 0) conf)
22542 (org-with-remote-undo buffer
22543 (with-current-buffer buffer
22544 (save-excursion
22545 (goto-char pos)
22546 (if (and (org-mode-p) (not (member type '("sexp"))))
22547 (setq dbeg (progn (org-back-to-heading t) (point))
22548 dend (org-end-of-subtree t t))
22549 (setq dbeg (point-at-bol)
22550 dend (min (point-max) (1+ (point-at-eol)))))
22551 (goto-char dbeg)
22552 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
22553 (setq conf (or (eq t org-agenda-confirm-kill)
22554 (and (numberp org-agenda-confirm-kill)
22555 (> n org-agenda-confirm-kill))))
22556 (and conf
22557 (not (y-or-n-p
22558 (format "Delete entry with %d lines in buffer \"%s\"? "
22559 n (buffer-name buffer))))
22560 (error "Abort"))
22561 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
22562 (with-current-buffer buffer (delete-region dbeg dend))
22563 (message "Agenda item and source killed"))))
22565 (defun org-agenda-archive ()
22566 "Kill the entry or subtree belonging to the current agenda entry."
22567 (interactive)
22568 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22569 (let* ((marker (or (get-text-property (point) 'org-marker)
22570 (org-agenda-error)))
22571 (buffer (marker-buffer marker))
22572 (pos (marker-position marker)))
22573 (org-with-remote-undo buffer
22574 (with-current-buffer buffer
22575 (if (org-mode-p)
22576 (save-excursion
22577 (goto-char pos)
22578 (org-remove-subtree-entries-from-agenda)
22579 (org-back-to-heading t)
22580 (org-archive-subtree))
22581 (error "Archiving works only in Org-mode files"))))))
22583 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
22584 "Remove all lines in the agenda that correspond to a given subtree.
22585 The subtree is the one in buffer BUF, starting at BEG and ending at END.
22586 If this information is not given, the function uses the tree at point."
22587 (let ((buf (or buf (current-buffer))) m p)
22588 (save-excursion
22589 (unless (and beg end)
22590 (org-back-to-heading t)
22591 (setq beg (point))
22592 (org-end-of-subtree t)
22593 (setq end (point)))
22594 (set-buffer (get-buffer org-agenda-buffer-name))
22595 (save-excursion
22596 (goto-char (point-max))
22597 (beginning-of-line 1)
22598 (while (not (bobp))
22599 (when (and (setq m (get-text-property (point) 'org-marker))
22600 (equal buf (marker-buffer m))
22601 (setq p (marker-position m))
22602 (>= p beg)
22603 (<= p end))
22604 (let ((inhibit-read-only t))
22605 (delete-region (point-at-bol) (1+ (point-at-eol)))))
22606 (beginning-of-line 0))))))
22608 (defun org-agenda-open-link ()
22609 "Follow the link in the current line, if any."
22610 (interactive)
22611 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
22612 (save-excursion
22613 (save-restriction
22614 (narrow-to-region (point-at-bol) (point-at-eol))
22615 (org-open-at-point))))
22617 (defun org-agenda-copy-local-variable (var)
22618 "Get a variable from a referenced buffer and install it here."
22619 (let ((m (get-text-property (point) 'org-marker)))
22620 (when (and m (buffer-live-p (marker-buffer m)))
22621 (org-set-local var (with-current-buffer (marker-buffer m)
22622 (symbol-value var))))))
22624 (defun org-agenda-switch-to (&optional delete-other-windows)
22625 "Go to the Org-mode file which contains the item at point."
22626 (interactive)
22627 (let* ((marker (or (get-text-property (point) 'org-marker)
22628 (org-agenda-error)))
22629 (buffer (marker-buffer marker))
22630 (pos (marker-position marker)))
22631 (switch-to-buffer buffer)
22632 (and delete-other-windows (delete-other-windows))
22633 (widen)
22634 (goto-char pos)
22635 (when (org-mode-p)
22636 (org-show-context 'agenda)
22637 (save-excursion
22638 (and (outline-next-heading)
22639 (org-flag-heading nil)))))) ; show the next heading
22641 (defun org-agenda-goto-mouse (ev)
22642 "Go to the Org-mode file which contains the item at the mouse click."
22643 (interactive "e")
22644 (mouse-set-point ev)
22645 (org-agenda-goto))
22647 (defun org-agenda-show ()
22648 "Display the Org-mode file which contains the item at point."
22649 (interactive)
22650 (let ((win (selected-window)))
22651 (org-agenda-goto t)
22652 (select-window win)))
22654 (defun org-agenda-recenter (arg)
22655 "Display the Org-mode file which contains the item at point and recenter."
22656 (interactive "P")
22657 (let ((win (selected-window)))
22658 (org-agenda-goto t)
22659 (recenter arg)
22660 (select-window win)))
22662 (defun org-agenda-show-mouse (ev)
22663 "Display the Org-mode file which contains the item at the mouse click."
22664 (interactive "e")
22665 (mouse-set-point ev)
22666 (org-agenda-show))
22668 (defun org-agenda-check-no-diary ()
22669 "Check if the entry is a diary link and abort if yes."
22670 (if (get-text-property (point) 'org-agenda-diary-link)
22671 (org-agenda-error)))
22673 (defun org-agenda-error ()
22674 (error "Command not allowed in this line"))
22676 (defun org-agenda-tree-to-indirect-buffer ()
22677 "Show the subtree corresponding to the current entry in an indirect buffer.
22678 This calls the command `org-tree-to-indirect-buffer' from the original
22679 Org-mode buffer.
22680 With numerical prefix arg ARG, go up to this level and then take that tree.
22681 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
22682 dedicated frame)."
22683 (interactive)
22684 (org-agenda-check-no-diary)
22685 (let* ((marker (or (get-text-property (point) 'org-marker)
22686 (org-agenda-error)))
22687 (buffer (marker-buffer marker))
22688 (pos (marker-position marker)))
22689 (with-current-buffer buffer
22690 (save-excursion
22691 (goto-char pos)
22692 (call-interactively 'org-tree-to-indirect-buffer)))))
22694 (defvar org-last-heading-marker (make-marker)
22695 "Marker pointing to the headline that last changed its TODO state
22696 by a remote command from the agenda.")
22698 (defun org-agenda-todo-nextset ()
22699 "Switch TODO entry to next sequence."
22700 (interactive)
22701 (org-agenda-todo 'nextset))
22703 (defun org-agenda-todo-previousset ()
22704 "Switch TODO entry to previous sequence."
22705 (interactive)
22706 (org-agenda-todo 'previousset))
22708 (defun org-agenda-todo (&optional arg)
22709 "Cycle TODO state of line at point, also in Org-mode file.
22710 This changes the line at point, all other lines in the agenda referring to
22711 the same tree node, and the headline of the tree node in the Org-mode file."
22712 (interactive "P")
22713 (org-agenda-check-no-diary)
22714 (let* ((col (current-column))
22715 (marker (or (get-text-property (point) 'org-marker)
22716 (org-agenda-error)))
22717 (buffer (marker-buffer marker))
22718 (pos (marker-position marker))
22719 (hdmarker (get-text-property (point) 'org-hd-marker))
22720 (inhibit-read-only t)
22721 newhead)
22722 (org-with-remote-undo buffer
22723 (with-current-buffer buffer
22724 (widen)
22725 (goto-char pos)
22726 (org-show-context 'agenda)
22727 (save-excursion
22728 (and (outline-next-heading)
22729 (org-flag-heading nil))) ; show the next heading
22730 (org-todo arg)
22731 (and (bolp) (forward-char 1))
22732 (setq newhead (org-get-heading))
22733 (save-excursion
22734 (org-back-to-heading)
22735 (move-marker org-last-heading-marker (point))))
22736 (beginning-of-line 1)
22737 (save-excursion
22738 (org-agenda-change-all-lines newhead hdmarker 'fixface))
22739 (move-to-column col))))
22741 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
22742 "Change all lines in the agenda buffer which match HDMARKER.
22743 The new content of the line will be NEWHEAD (as modified by
22744 `org-format-agenda-item'). HDMARKER is checked with
22745 `equal' against all `org-hd-marker' text properties in the file.
22746 If FIXFACE is non-nil, the face of each item is modified acording to
22747 the new TODO state."
22748 (let* ((inhibit-read-only t)
22749 props m pl undone-face done-face finish new dotime cat tags)
22750 (save-excursion
22751 (goto-char (point-max))
22752 (beginning-of-line 1)
22753 (while (not finish)
22754 (setq finish (bobp))
22755 (when (and (setq m (get-text-property (point) 'org-hd-marker))
22756 (equal m hdmarker))
22757 (setq props (text-properties-at (point))
22758 dotime (get-text-property (point) 'dotime)
22759 cat (get-text-property (point) 'org-category)
22760 tags (get-text-property (point) 'tags)
22761 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
22762 pl (get-text-property (point) 'prefix-length)
22763 undone-face (get-text-property (point) 'undone-face)
22764 done-face (get-text-property (point) 'done-face))
22765 (move-to-column pl)
22766 (cond
22767 ((equal new "")
22768 (beginning-of-line 1)
22769 (and (looking-at ".*\n?") (replace-match "")))
22770 ((looking-at ".*")
22771 (replace-match new t t)
22772 (beginning-of-line 1)
22773 (add-text-properties (point-at-bol) (point-at-eol) props)
22774 (when fixface
22775 (add-text-properties
22776 (point-at-bol) (point-at-eol)
22777 (list 'face
22778 (if org-last-todo-state-is-todo
22779 undone-face done-face))))
22780 (org-agenda-highlight-todo 'line)
22781 (beginning-of-line 1))
22782 (t (error "Line update did not work"))))
22783 (beginning-of-line 0)))
22784 (org-finalize-agenda)))
22786 (defun org-agenda-align-tags (&optional line)
22787 "Align all tags in agenda items to `org-agenda-tags-column'."
22788 (let ((inhibit-read-only t) l c)
22789 (save-excursion
22790 (goto-char (if line (point-at-bol) (point-min)))
22791 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22792 (if line (point-at-eol) nil) t)
22793 (add-text-properties
22794 (match-beginning 2) (match-end 2)
22795 (list 'face (list 'org-tag (get-text-property
22796 (match-beginning 2) 'face))))
22797 (setq l (- (match-end 2) (match-beginning 2))
22798 c (if (< org-agenda-tags-column 0)
22799 (- (abs org-agenda-tags-column) l)
22800 org-agenda-tags-column))
22801 (delete-region (match-beginning 1) (match-end 1))
22802 (goto-char (match-beginning 1))
22803 (insert (org-add-props
22804 (make-string (max 1 (- c (current-column))) ?\ )
22805 (text-properties-at (point))))))))
22807 (defun org-agenda-priority-up ()
22808 "Increase the priority of line at point, also in Org-mode file."
22809 (interactive)
22810 (org-agenda-priority 'up))
22812 (defun org-agenda-priority-down ()
22813 "Decrease the priority of line at point, also in Org-mode file."
22814 (interactive)
22815 (org-agenda-priority 'down))
22817 (defun org-agenda-priority (&optional force-direction)
22818 "Set the priority of line at point, also in Org-mode file.
22819 This changes the line at point, all other lines in the agenda referring to
22820 the same tree node, and the headline of the tree node in the Org-mode file."
22821 (interactive)
22822 (org-agenda-check-no-diary)
22823 (let* ((marker (or (get-text-property (point) 'org-marker)
22824 (org-agenda-error)))
22825 (hdmarker (get-text-property (point) 'org-hd-marker))
22826 (buffer (marker-buffer hdmarker))
22827 (pos (marker-position hdmarker))
22828 (inhibit-read-only t)
22829 newhead)
22830 (org-with-remote-undo buffer
22831 (with-current-buffer buffer
22832 (widen)
22833 (goto-char pos)
22834 (org-show-context 'agenda)
22835 (save-excursion
22836 (and (outline-next-heading)
22837 (org-flag-heading nil))) ; show the next heading
22838 (funcall 'org-priority force-direction)
22839 (end-of-line 1)
22840 (setq newhead (org-get-heading)))
22841 (org-agenda-change-all-lines newhead hdmarker)
22842 (beginning-of-line 1))))
22844 (defun org-get-tags-at (&optional pos)
22845 "Get a list of all headline tags applicable at POS.
22846 POS defaults to point. If tags are inherited, the list contains
22847 the targets in the same sequence as the headlines appear, i.e.
22848 the tags of the current headline come last."
22849 (interactive)
22850 (let (tags lastpos)
22851 (save-excursion
22852 (save-restriction
22853 (widen)
22854 (goto-char (or pos (point)))
22855 (save-match-data
22856 (org-back-to-heading t)
22857 (condition-case nil
22858 (while (not (equal lastpos (point)))
22859 (setq lastpos (point))
22860 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
22861 (setq tags (append (org-split-string
22862 (org-match-string-no-properties 1) ":")
22863 tags)))
22864 (or org-use-tag-inheritance (error ""))
22865 (org-up-heading-all 1))
22866 (error nil))))
22867 tags)))
22869 ;; FIXME: should fix the tags property of the agenda line.
22870 (defun org-agenda-set-tags ()
22871 "Set tags for the current headline."
22872 (interactive)
22873 (org-agenda-check-no-diary)
22874 (if (and (org-region-active-p) (interactive-p))
22875 (call-interactively 'org-change-tag-in-region)
22876 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22877 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22878 (org-agenda-error)))
22879 (buffer (marker-buffer hdmarker))
22880 (pos (marker-position hdmarker))
22881 (inhibit-read-only t)
22882 newhead)
22883 (org-with-remote-undo buffer
22884 (with-current-buffer buffer
22885 (widen)
22886 (goto-char pos)
22887 (save-excursion
22888 (org-show-context 'agenda))
22889 (save-excursion
22890 (and (outline-next-heading)
22891 (org-flag-heading nil))) ; show the next heading
22892 (goto-char pos)
22893 (call-interactively 'org-set-tags)
22894 (end-of-line 1)
22895 (setq newhead (org-get-heading)))
22896 (org-agenda-change-all-lines newhead hdmarker)
22897 (beginning-of-line 1)))))
22899 (defun org-agenda-toggle-archive-tag ()
22900 "Toggle the archive tag for the current entry."
22901 (interactive)
22902 (org-agenda-check-no-diary)
22903 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22904 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22905 (org-agenda-error)))
22906 (buffer (marker-buffer hdmarker))
22907 (pos (marker-position hdmarker))
22908 (inhibit-read-only t)
22909 newhead)
22910 (org-with-remote-undo buffer
22911 (with-current-buffer buffer
22912 (widen)
22913 (goto-char pos)
22914 (org-show-context 'agenda)
22915 (save-excursion
22916 (and (outline-next-heading)
22917 (org-flag-heading nil))) ; show the next heading
22918 (call-interactively 'org-toggle-archive-tag)
22919 (end-of-line 1)
22920 (setq newhead (org-get-heading)))
22921 (org-agenda-change-all-lines newhead hdmarker)
22922 (beginning-of-line 1))))
22924 (defun org-agenda-date-later (arg &optional what)
22925 "Change the date of this item to one day later."
22926 (interactive "p")
22927 (org-agenda-check-type t 'agenda 'timeline)
22928 (org-agenda-check-no-diary)
22929 (let* ((marker (or (get-text-property (point) 'org-marker)
22930 (org-agenda-error)))
22931 (buffer (marker-buffer marker))
22932 (pos (marker-position marker)))
22933 (org-with-remote-undo buffer
22934 (with-current-buffer buffer
22935 (widen)
22936 (goto-char pos)
22937 (if (not (org-at-timestamp-p))
22938 (error "Cannot find time stamp"))
22939 (org-timestamp-change arg (or what 'day)))
22940 (org-agenda-show-new-time marker org-last-changed-timestamp))
22941 (message "Time stamp changed to %s" org-last-changed-timestamp)))
22943 (defun org-agenda-date-earlier (arg &optional what)
22944 "Change the date of this item to one day earlier."
22945 (interactive "p")
22946 (org-agenda-date-later (- arg) what))
22948 (defun org-agenda-show-new-time (marker stamp &optional prefix)
22949 "Show new date stamp via text properties."
22950 ;; We use text properties to make this undoable
22951 (let ((inhibit-read-only t))
22952 (setq stamp (concat " " prefix " => " stamp))
22953 (save-excursion
22954 (goto-char (point-max))
22955 (while (not (bobp))
22956 (when (equal marker (get-text-property (point) 'org-marker))
22957 (move-to-column (- (window-width) (length stamp)) t)
22958 (if (featurep 'xemacs)
22959 ;; Use `duplicable' property to trigger undo recording
22960 (let ((ex (make-extent nil nil))
22961 (gl (make-glyph stamp)))
22962 (set-glyph-face gl 'secondary-selection)
22963 (set-extent-properties
22964 ex (list 'invisible t 'end-glyph gl 'duplicable t))
22965 (insert-extent ex (1- (point)) (point-at-eol)))
22966 (add-text-properties
22967 (1- (point)) (point-at-eol)
22968 (list 'display (org-add-props stamp nil
22969 'face 'secondary-selection))))
22970 (beginning-of-line 1))
22971 (beginning-of-line 0)))))
22973 (defun org-agenda-date-prompt (arg)
22974 "Change the date of this item. Date is prompted for, with default today.
22975 The prefix ARG is passed to the `org-time-stamp' command and can therefore
22976 be used to request time specification in the time stamp."
22977 (interactive "P")
22978 (org-agenda-check-type t 'agenda 'timeline)
22979 (org-agenda-check-no-diary)
22980 (let* ((marker (or (get-text-property (point) 'org-marker)
22981 (org-agenda-error)))
22982 (buffer (marker-buffer marker))
22983 (pos (marker-position marker)))
22984 (org-with-remote-undo buffer
22985 (with-current-buffer buffer
22986 (widen)
22987 (goto-char pos)
22988 (if (not (org-at-timestamp-p))
22989 (error "Cannot find time stamp"))
22990 (org-time-stamp arg)
22991 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
22993 (defun org-agenda-schedule (arg)
22994 "Schedule the item at point."
22995 (interactive "P")
22996 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22997 (org-agenda-check-no-diary)
22998 (let* ((marker (or (get-text-property (point) 'org-marker)
22999 (org-agenda-error)))
23000 (buffer (marker-buffer marker))
23001 (pos (marker-position marker))
23002 (org-insert-labeled-timestamps-at-point nil)
23004 (message "%s" (marker-insertion-type marker)) (sit-for 3)
23005 (set-marker-insertion-type marker t)
23006 (org-with-remote-undo buffer
23007 (with-current-buffer buffer
23008 (widen)
23009 (goto-char pos)
23010 (setq ts (org-schedule arg)))
23011 (org-agenda-show-new-time marker ts "S"))
23012 (message "Item scheduled for %s" ts)))
23014 (defun org-agenda-deadline (arg)
23015 "Schedule the item at point."
23016 (interactive "P")
23017 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23018 (org-agenda-check-no-diary)
23019 (let* ((marker (or (get-text-property (point) 'org-marker)
23020 (org-agenda-error)))
23021 (buffer (marker-buffer marker))
23022 (pos (marker-position marker))
23023 (org-insert-labeled-timestamps-at-point nil)
23025 (org-with-remote-undo buffer
23026 (with-current-buffer buffer
23027 (widen)
23028 (goto-char pos)
23029 (setq ts (org-deadline arg)))
23030 (org-agenda-show-new-time marker ts "S"))
23031 (message "Deadline for this item set to %s" ts)))
23033 (defun org-get-heading (&optional no-tags)
23034 "Return the heading of the current entry, without the stars."
23035 (save-excursion
23036 (org-back-to-heading t)
23037 (if (looking-at
23038 (if no-tags
23039 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
23040 "\\*+[ \t]+\\([^\r\n]*\\)"))
23041 (match-string 1) "")))
23043 (defun org-agenda-clock-in (&optional arg)
23044 "Start the clock on the currently selected item."
23045 (interactive "P")
23046 (org-agenda-check-no-diary)
23047 (let* ((marker (or (get-text-property (point) 'org-marker)
23048 (org-agenda-error)))
23049 (pos (marker-position marker)))
23050 (org-with-remote-undo (marker-buffer marker)
23051 (with-current-buffer (marker-buffer marker)
23052 (widen)
23053 (goto-char pos)
23054 (org-clock-in)))))
23056 (defun org-agenda-clock-out (&optional arg)
23057 "Stop the currently running clock."
23058 (interactive "P")
23059 (unless (marker-buffer org-clock-marker)
23060 (error "No running clock"))
23061 (org-with-remote-undo (marker-buffer org-clock-marker)
23062 (org-clock-out)))
23064 (defun org-agenda-clock-cancel (&optional arg)
23065 "Cancel the currently running clock."
23066 (interactive "P")
23067 (unless (marker-buffer org-clock-marker)
23068 (error "No running clock"))
23069 (org-with-remote-undo (marker-buffer org-clock-marker)
23070 (org-clock-cancel)))
23072 (defun org-agenda-diary-entry ()
23073 "Make a diary entry, like the `i' command from the calendar.
23074 All the standard commands work: block, weekly etc."
23075 (interactive)
23076 (org-agenda-check-type t 'agenda 'timeline)
23077 (require 'diary-lib)
23078 (let* ((char (progn
23079 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
23080 (read-char-exclusive)))
23081 (cmd (cdr (assoc char
23082 '((?d . insert-diary-entry)
23083 (?w . insert-weekly-diary-entry)
23084 (?m . insert-monthly-diary-entry)
23085 (?y . insert-yearly-diary-entry)
23086 (?a . insert-anniversary-diary-entry)
23087 (?b . insert-block-diary-entry)
23088 (?c . insert-cyclic-diary-entry)))))
23089 (oldf (symbol-function 'calendar-cursor-to-date))
23090 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
23091 (point (point))
23092 (mark (or (mark t) (point))))
23093 (unless cmd
23094 (error "No command associated with <%c>" char))
23095 (unless (and (get-text-property point 'day)
23096 (or (not (equal ?b char))
23097 (get-text-property mark 'day)))
23098 (error "Don't know which date to use for diary entry"))
23099 ;; We implement this by hacking the `calendar-cursor-to-date' function
23100 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
23101 (let ((calendar-mark-ring
23102 (list (calendar-gregorian-from-absolute
23103 (or (get-text-property mark 'day)
23104 (get-text-property point 'day))))))
23105 (unwind-protect
23106 (progn
23107 (fset 'calendar-cursor-to-date
23108 (lambda (&optional error)
23109 (calendar-gregorian-from-absolute
23110 (get-text-property point 'day))))
23111 (call-interactively cmd))
23112 (fset 'calendar-cursor-to-date oldf)))))
23115 (defun org-agenda-execute-calendar-command (cmd)
23116 "Execute a calendar command from the agenda, with the date associated to
23117 the cursor position."
23118 (org-agenda-check-type t 'agenda 'timeline)
23119 (require 'diary-lib)
23120 (unless (get-text-property (point) 'day)
23121 (error "Don't know which date to use for calendar command"))
23122 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
23123 (point (point))
23124 (date (calendar-gregorian-from-absolute
23125 (get-text-property point 'day)))
23126 ;; the following 3 vars are needed in the calendar
23127 (displayed-day (extract-calendar-day date))
23128 (displayed-month (extract-calendar-month date))
23129 (displayed-year (extract-calendar-year date)))
23130 (unwind-protect
23131 (progn
23132 (fset 'calendar-cursor-to-date
23133 (lambda (&optional error)
23134 (calendar-gregorian-from-absolute
23135 (get-text-property point 'day))))
23136 (call-interactively cmd))
23137 (fset 'calendar-cursor-to-date oldf))))
23139 (defun org-agenda-phases-of-moon ()
23140 "Display the phases of the moon for the 3 months around the cursor date."
23141 (interactive)
23142 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
23144 (defun org-agenda-holidays ()
23145 "Display the holidays for the 3 months around the cursor date."
23146 (interactive)
23147 (org-agenda-execute-calendar-command 'list-calendar-holidays))
23149 (defun org-agenda-sunrise-sunset (arg)
23150 "Display sunrise and sunset for the cursor date.
23151 Latitude and longitude can be specified with the variables
23152 `calendar-latitude' and `calendar-longitude'. When called with prefix
23153 argument, latitude and longitude will be prompted for."
23154 (interactive "P")
23155 (let ((calendar-longitude (if arg nil calendar-longitude))
23156 (calendar-latitude (if arg nil calendar-latitude))
23157 (calendar-location-name
23158 (if arg "the given coordinates" calendar-location-name)))
23159 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
23161 (defun org-agenda-goto-calendar ()
23162 "Open the Emacs calendar with the date at the cursor."
23163 (interactive)
23164 (org-agenda-check-type t 'agenda 'timeline)
23165 (let* ((day (or (get-text-property (point) 'day)
23166 (error "Don't know which date to open in calendar")))
23167 (date (calendar-gregorian-from-absolute day))
23168 (calendar-move-hook nil)
23169 (view-calendar-holidays-initially nil)
23170 (view-diary-entries-initially nil))
23171 (calendar)
23172 (calendar-goto-date date)))
23174 (defun org-calendar-goto-agenda ()
23175 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
23176 This is a command that has to be installed in `calendar-mode-map'."
23177 (interactive)
23178 (org-agenda-list nil (calendar-absolute-from-gregorian
23179 (calendar-cursor-to-date))
23180 nil))
23182 (defun org-agenda-convert-date ()
23183 (interactive)
23184 (org-agenda-check-type t 'agenda 'timeline)
23185 (let ((day (get-text-property (point) 'day))
23186 date s)
23187 (unless day
23188 (error "Don't know which date to convert"))
23189 (setq date (calendar-gregorian-from-absolute day))
23190 (setq s (concat
23191 "Gregorian: " (calendar-date-string date) "\n"
23192 "ISO: " (calendar-iso-date-string date) "\n"
23193 "Day of Yr: " (calendar-day-of-year-string date) "\n"
23194 "Julian: " (calendar-julian-date-string date) "\n"
23195 "Astron. JD: " (calendar-astro-date-string date)
23196 " (Julian date number at noon UTC)\n"
23197 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
23198 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
23199 "French: " (calendar-french-date-string date) "\n"
23200 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
23201 "Mayan: " (calendar-mayan-date-string date) "\n"
23202 "Coptic: " (calendar-coptic-date-string date) "\n"
23203 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
23204 "Persian: " (calendar-persian-date-string date) "\n"
23205 "Chinese: " (calendar-chinese-date-string date) "\n"))
23206 (with-output-to-temp-buffer "*Dates*"
23207 (princ s))
23208 (if (fboundp 'fit-window-to-buffer)
23209 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
23212 ;;;; Embedded LaTeX
23214 (defvar org-cdlatex-mode-map (make-sparse-keymap)
23215 "Keymap for the minor `org-cdlatex-mode'.")
23217 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
23218 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
23219 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
23220 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
23221 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
23223 (defvar org-cdlatex-texmathp-advice-is-done nil
23224 "Flag remembering if we have applied the advice to texmathp already.")
23226 (define-minor-mode org-cdlatex-mode
23227 "Toggle the minor `org-cdlatex-mode'.
23228 This mode supports entering LaTeX environment and math in LaTeX fragments
23229 in Org-mode.
23230 \\{org-cdlatex-mode-map}"
23231 nil " OCDL" nil
23232 (when org-cdlatex-mode (require 'cdlatex))
23233 (unless org-cdlatex-texmathp-advice-is-done
23234 (setq org-cdlatex-texmathp-advice-is-done t)
23235 (defadvice texmathp (around org-math-always-on activate)
23236 "Always return t in org-mode buffers.
23237 This is because we want to insert math symbols without dollars even outside
23238 the LaTeX math segments. If Orgmode thinks that point is actually inside
23239 en embedded LaTeX fragement, let texmathp do its job.
23240 \\[org-cdlatex-mode-map]"
23241 (interactive)
23242 (let (p)
23243 (cond
23244 ((not (org-mode-p)) ad-do-it)
23245 ((eq this-command 'cdlatex-math-symbol)
23246 (setq ad-return-value t
23247 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
23249 (let ((p (org-inside-LaTeX-fragment-p)))
23250 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
23251 (setq ad-return-value t
23252 texmathp-why '("Org-mode embedded math" . 0))
23253 (if p ad-do-it)))))))))
23255 (defun turn-on-org-cdlatex ()
23256 "Unconditionally turn on `org-cdlatex-mode'."
23257 (org-cdlatex-mode 1))
23259 (defun org-inside-LaTeX-fragment-p ()
23260 "Test if point is inside a LaTeX fragment.
23261 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
23262 sequence appearing also before point.
23263 Even though the matchers for math are configurable, this function assumes
23264 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
23265 delimiters are skipped when they have been removed by customization.
23266 The return value is nil, or a cons cell with the delimiter and
23267 and the position of this delimiter.
23269 This function does a reasonably good job, but can locally be fooled by
23270 for example currency specifications. For example it will assume being in
23271 inline math after \"$22.34\". The LaTeX fragment formatter will only format
23272 fragments that are properly closed, but during editing, we have to live
23273 with the uncertainty caused by missing closing delimiters. This function
23274 looks only before point, not after."
23275 (catch 'exit
23276 (let ((pos (point))
23277 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
23278 (lim (progn
23279 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
23280 (point)))
23281 dd-on str (start 0) m re)
23282 (goto-char pos)
23283 (when dodollar
23284 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
23285 re (nth 1 (assoc "$" org-latex-regexps)))
23286 (while (string-match re str start)
23287 (cond
23288 ((= (match-end 0) (length str))
23289 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
23290 ((= (match-end 0) (- (length str) 5))
23291 (throw 'exit nil))
23292 (t (setq start (match-end 0))))))
23293 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
23294 (goto-char pos)
23295 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
23296 (and (match-beginning 2) (throw 'exit nil))
23297 ;; count $$
23298 (while (re-search-backward "\\$\\$" lim t)
23299 (setq dd-on (not dd-on)))
23300 (goto-char pos)
23301 (if dd-on (cons "$$" m))))))
23304 (defun org-try-cdlatex-tab ()
23305 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
23306 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
23307 - inside a LaTeX fragment, or
23308 - after the first word in a line, where an abbreviation expansion could
23309 insert a LaTeX environment."
23310 (when org-cdlatex-mode
23311 (cond
23312 ((save-excursion
23313 (skip-chars-backward "a-zA-Z0-9*")
23314 (skip-chars-backward " \t")
23315 (bolp))
23316 (cdlatex-tab) t)
23317 ((org-inside-LaTeX-fragment-p)
23318 (cdlatex-tab) t)
23319 (t nil))))
23321 (defun org-cdlatex-underscore-caret (&optional arg)
23322 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
23323 Revert to the normal definition outside of these fragments."
23324 (interactive "P")
23325 (if (org-inside-LaTeX-fragment-p)
23326 (call-interactively 'cdlatex-sub-superscript)
23327 (let (org-cdlatex-mode)
23328 (call-interactively (key-binding (vector last-input-event))))))
23330 (defun org-cdlatex-math-modify (&optional arg)
23331 "Execute `cdlatex-math-modify' in LaTeX fragments.
23332 Revert to the normal definition outside of these fragments."
23333 (interactive "P")
23334 (if (org-inside-LaTeX-fragment-p)
23335 (call-interactively 'cdlatex-math-modify)
23336 (let (org-cdlatex-mode)
23337 (call-interactively (key-binding (vector last-input-event))))))
23339 (defvar org-latex-fragment-image-overlays nil
23340 "List of overlays carrying the images of latex fragments.")
23341 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
23343 (defun org-remove-latex-fragment-image-overlays ()
23344 "Remove all overlays with LaTeX fragment images in current buffer."
23345 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
23346 (setq org-latex-fragment-image-overlays nil))
23348 (defun org-preview-latex-fragment (&optional subtree)
23349 "Preview the LaTeX fragment at point, or all locally or globally.
23350 If the cursor is in a LaTeX fragment, create the image and overlay
23351 it over the source code. If there is no fragment at point, display
23352 all fragments in the current text, from one headline to the next. With
23353 prefix SUBTREE, display all fragments in the current subtree. With a
23354 double prefix `C-u C-u', or when the cursor is before the first headline,
23355 display all fragments in the buffer.
23356 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
23357 (interactive "P")
23358 (org-remove-latex-fragment-image-overlays)
23359 (save-excursion
23360 (save-restriction
23361 (let (beg end at msg)
23362 (cond
23363 ((or (equal subtree '(16))
23364 (not (save-excursion
23365 (re-search-backward (concat "^" outline-regexp) nil t))))
23366 (setq beg (point-min) end (point-max)
23367 msg "Creating images for buffer...%s"))
23368 ((equal subtree '(4))
23369 (org-back-to-heading)
23370 (setq beg (point) end (org-end-of-subtree t)
23371 msg "Creating images for subtree...%s"))
23373 (if (setq at (org-inside-LaTeX-fragment-p))
23374 (goto-char (max (point-min) (- (cdr at) 2)))
23375 (org-back-to-heading))
23376 (setq beg (point) end (progn (outline-next-heading) (point))
23377 msg (if at "Creating image...%s"
23378 "Creating images for entry...%s"))))
23379 (message msg "")
23380 (narrow-to-region beg end)
23381 (goto-char beg)
23382 (org-format-latex
23383 (concat "ltxpng/" (file-name-sans-extension
23384 (file-name-nondirectory
23385 buffer-file-name)))
23386 default-directory 'overlays msg at 'forbuffer)
23387 (message msg "done. Use `C-c C-c' to remove images.")))))
23389 (defvar org-latex-regexps
23390 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
23391 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
23392 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
23393 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
23394 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
23395 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
23396 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
23397 "Regular expressions for matching embedded LaTeX.")
23399 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
23400 "Replace LaTeX fragments with links to an image, and produce images."
23401 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
23402 (let* ((prefixnodir (file-name-nondirectory prefix))
23403 (absprefix (expand-file-name prefix dir))
23404 (todir (file-name-directory absprefix))
23405 (opt org-format-latex-options)
23406 (matchers (plist-get opt :matchers))
23407 (re-list org-latex-regexps)
23408 (cnt 0) txt link beg end re e checkdir
23409 m n block linkfile movefile ov)
23410 ;; Check if there are old images files with this prefix, and remove them
23411 (when (file-directory-p todir)
23412 (mapc 'delete-file
23413 (directory-files
23414 todir 'full
23415 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
23416 ;; Check the different regular expressions
23417 (while (setq e (pop re-list))
23418 (setq m (car e) re (nth 1 e) n (nth 2 e)
23419 block (if (nth 3 e) "\n\n" ""))
23420 (when (member m matchers)
23421 (goto-char (point-min))
23422 (while (re-search-forward re nil t)
23423 (when (or (not at) (equal (cdr at) (match-beginning n)))
23424 (setq txt (match-string n)
23425 beg (match-beginning n) end (match-end n)
23426 cnt (1+ cnt)
23427 linkfile (format "%s_%04d.png" prefix cnt)
23428 movefile (format "%s_%04d.png" absprefix cnt)
23429 link (concat block "[[file:" linkfile "]]" block))
23430 (if msg (message msg cnt))
23431 (goto-char beg)
23432 (unless checkdir ; make sure the directory exists
23433 (setq checkdir t)
23434 (or (file-directory-p todir) (make-directory todir)))
23435 (org-create-formula-image
23436 txt movefile opt forbuffer)
23437 (if overlays
23438 (progn
23439 (setq ov (org-make-overlay beg end))
23440 (if (featurep 'xemacs)
23441 (progn
23442 (org-overlay-put ov 'invisible t)
23443 (org-overlay-put
23444 ov 'end-glyph
23445 (make-glyph (vector 'png :file movefile))))
23446 (org-overlay-put
23447 ov 'display
23448 (list 'image :type 'png :file movefile :ascent 'center)))
23449 (push ov org-latex-fragment-image-overlays)
23450 (goto-char end))
23451 (delete-region beg end)
23452 (insert link))))))))
23454 ;; This function borrows from Ganesh Swami's latex2png.el
23455 (defun org-create-formula-image (string tofile options buffer)
23456 (let* ((tmpdir (if (featurep 'xemacs)
23457 (temp-directory)
23458 temporary-file-directory))
23459 (texfilebase (make-temp-name
23460 (expand-file-name "orgtex" tmpdir)))
23461 (texfile (concat texfilebase ".tex"))
23462 (dvifile (concat texfilebase ".dvi"))
23463 (pngfile (concat texfilebase ".png"))
23464 (fnh (face-attribute 'default :height nil))
23465 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
23466 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
23467 (fg (or (plist-get options (if buffer :foreground :html-foreground))
23468 "Black"))
23469 (bg (or (plist-get options (if buffer :background :html-background))
23470 "Transparent")))
23471 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
23472 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
23473 (with-temp-file texfile
23474 (insert org-format-latex-header
23475 "\n\\begin{document}\n" string "\n\\end{document}\n"))
23476 (let ((dir default-directory))
23477 (condition-case nil
23478 (progn
23479 (cd tmpdir)
23480 (call-process "latex" nil nil nil texfile))
23481 (error nil))
23482 (cd dir))
23483 (if (not (file-exists-p dvifile))
23484 (progn (message "Failed to create dvi file from %s" texfile) nil)
23485 (call-process "dvipng" nil nil nil
23486 "-E" "-fg" fg "-bg" bg
23487 "-D" dpi
23488 ;;"-x" scale "-y" scale
23489 "-T" "tight"
23490 "-o" pngfile
23491 dvifile)
23492 (if (not (file-exists-p pngfile))
23493 (progn (message "Failed to create png file from %s" texfile) nil)
23494 ;; Use the requested file name and clean up
23495 (copy-file pngfile tofile 'replace)
23496 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
23497 (delete-file (concat texfilebase e)))
23498 pngfile))))
23500 (defun org-dvipng-color (attr)
23501 "Return an rgb color specification for dvipng."
23502 (apply 'format "rgb %s %s %s"
23503 (mapcar 'org-normalize-color
23504 (color-values (face-attribute 'default attr nil)))))
23506 (defun org-normalize-color (value)
23507 "Return string to be used as color value for an RGB component."
23508 (format "%g" (/ value 65535.0)))
23510 ;;;; Exporting
23512 ;;; Variables, constants, and parameter plists
23514 (defconst org-level-max 20)
23516 (defvar org-export-html-preamble nil
23517 "Preamble, to be inserted just after <body>. Set by publishing functions.")
23518 (defvar org-export-html-postamble nil
23519 "Preamble, to be inserted just before </body>. Set by publishing functions.")
23520 (defvar org-export-html-auto-preamble t
23521 "Should default preamble be inserted? Set by publishing functions.")
23522 (defvar org-export-html-auto-postamble t
23523 "Should default postamble be inserted? Set by publishing functions.")
23524 (defvar org-current-export-file nil) ; dynamically scoped parameter
23525 (defvar org-current-export-dir nil) ; dynamically scoped parameter
23528 (defconst org-export-plist-vars
23529 '((:language . org-export-default-language)
23530 (:customtime . org-display-custom-times)
23531 (:headline-levels . org-export-headline-levels)
23532 (:section-numbers . org-export-with-section-numbers)
23533 (:table-of-contents . org-export-with-toc)
23534 (:preserve-breaks . org-export-preserve-breaks)
23535 (:archived-trees . org-export-with-archived-trees)
23536 (:emphasize . org-export-with-emphasize)
23537 (:sub-superscript . org-export-with-sub-superscripts)
23538 (:special-strings . org-export-with-special-strings)
23539 (:footnotes . org-export-with-footnotes)
23540 (:drawers . org-export-with-drawers)
23541 (:tags . org-export-with-tags)
23542 (:TeX-macros . org-export-with-TeX-macros)
23543 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
23544 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
23545 (:fixed-width . org-export-with-fixed-width)
23546 (:timestamps . org-export-with-timestamps)
23547 (:author-info . org-export-author-info)
23548 (:time-stamp-file . org-export-time-stamp-file)
23549 (:tables . org-export-with-tables)
23550 (:table-auto-headline . org-export-highlight-first-table-line)
23551 (:style . org-export-html-style)
23552 (:agenda-style . org-agenda-export-html-style)
23553 (:convert-org-links . org-export-html-link-org-files-as-html)
23554 (:inline-images . org-export-html-inline-images)
23555 (:html-extension . org-export-html-extension)
23556 (:html-table-tag . org-export-html-table-tag)
23557 (:expand-quoted-html . org-export-html-expand)
23558 (:timestamp . org-export-html-with-timestamp)
23559 (:publishing-directory . org-export-publishing-directory)
23560 (:preamble . org-export-html-preamble)
23561 (:postamble . org-export-html-postamble)
23562 (:auto-preamble . org-export-html-auto-preamble)
23563 (:auto-postamble . org-export-html-auto-postamble)
23564 (:author . user-full-name)
23565 (:email . user-mail-address)))
23567 (defun org-default-export-plist ()
23568 "Return the property list with default settings for the export variables."
23569 (let ((l org-export-plist-vars) rtn e)
23570 (while (setq e (pop l))
23571 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
23572 rtn))
23574 (defun org-infile-export-plist ()
23575 "Return the property list with file-local settings for export."
23576 (save-excursion
23577 (save-restriction
23578 (widen)
23579 (goto-char 0)
23580 (let ((re (org-make-options-regexp
23581 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
23582 p key val text options)
23583 (while (re-search-forward re nil t)
23584 (setq key (org-match-string-no-properties 1)
23585 val (org-match-string-no-properties 2))
23586 (cond
23587 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
23588 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
23589 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
23590 ((string-equal key "DATE") (setq p (plist-put p :date val)))
23591 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
23592 ((string-equal key "TEXT")
23593 (setq text (if text (concat text "\n" val) val)))
23594 ((string-equal key "OPTIONS") (setq options val))))
23595 (setq p (plist-put p :text text))
23596 (when options
23597 (let ((op '(("H" . :headline-levels)
23598 ("num" . :section-numbers)
23599 ("toc" . :table-of-contents)
23600 ("\\n" . :preserve-breaks)
23601 ("@" . :expand-quoted-html)
23602 (":" . :fixed-width)
23603 ("|" . :tables)
23604 ("^" . :sub-superscript)
23605 ("-" . :special-strings)
23606 ("f" . :footnotes)
23607 ("d" . :drawers)
23608 ("tags" . :tags)
23609 ("*" . :emphasize)
23610 ("TeX" . :TeX-macros)
23611 ("LaTeX" . :LaTeX-fragments)
23612 ("skip" . :skip-before-1st-heading)
23613 ("author" . :author-info)
23614 ("timestamp" . :time-stamp-file)))
23616 (while (setq o (pop op))
23617 (if (string-match (concat (regexp-quote (car o))
23618 ":\\([^ \t\n\r;,.]*\\)")
23619 options)
23620 (setq p (plist-put p (cdr o)
23621 (car (read-from-string
23622 (match-string 1 options)))))))))
23623 p))))
23625 (defun org-export-directory (type plist)
23626 (let* ((val (plist-get plist :publishing-directory))
23627 (dir (if (listp val)
23628 (or (cdr (assoc type val)) ".")
23629 val)))
23630 dir))
23632 (defun org-skip-comments (lines)
23633 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
23634 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
23635 (re2 "^\\(\\*+\\)[ \t\n\r]")
23636 (case-fold-search nil)
23637 rtn line level)
23638 (while (setq line (pop lines))
23639 (cond
23640 ((and (string-match re1 line)
23641 (setq level (- (match-end 1) (match-beginning 1))))
23642 ;; Beginning of a COMMENT subtree. Skip it.
23643 (while (and (setq line (pop lines))
23644 (or (not (string-match re2 line))
23645 (> (- (match-end 1) (match-beginning 1)) level))))
23646 (setq lines (cons line lines)))
23647 ((string-match "^#" line)
23648 ;; an ordinary comment line
23650 ((and org-export-table-remove-special-lines
23651 (string-match "^[ \t]*|" line)
23652 (or (string-match "^[ \t]*| *[!_^] *|" line)
23653 (and (string-match "| *<[0-9]+> *|" line)
23654 (not (string-match "| *[^ <|]" line)))))
23655 ;; a special table line that should be removed
23657 (t (setq rtn (cons line rtn)))))
23658 (nreverse rtn)))
23660 (defun org-export (&optional arg)
23661 (interactive)
23662 (let ((help "[t] insert the export option template
23663 \[v] limit export to visible part of outline tree
23665 \[a] export as ASCII
23667 \[h] export as HTML
23668 \[H] export as HTML to temporary buffer
23669 \[R] export region as HTML
23670 \[b] export as HTML and browse immediately
23671 \[x] export as XOXO
23673 \[l] export as LaTeX
23674 \[L] export as LaTeX to temporary buffer
23676 \[i] export current file as iCalendar file
23677 \[I] export all agenda files as iCalendar files
23678 \[c] export agenda files into combined iCalendar file
23680 \[F] publish current file
23681 \[P] publish current project
23682 \[X] publish... (project will be prompted for)
23683 \[A] publish all projects")
23684 (cmds
23685 '((?t . org-insert-export-options-template)
23686 (?v . org-export-visible)
23687 (?a . org-export-as-ascii)
23688 (?h . org-export-as-html)
23689 (?b . org-export-as-html-and-open)
23690 (?H . org-export-as-html-to-buffer)
23691 (?R . org-export-region-as-html)
23692 (?x . org-export-as-xoxo)
23693 (?l . org-export-as-latex)
23694 (?L . org-export-as-latex-to-buffer)
23695 (?i . org-export-icalendar-this-file)
23696 (?I . org-export-icalendar-all-agenda-files)
23697 (?c . org-export-icalendar-combine-agenda-files)
23698 (?F . org-publish-current-file)
23699 (?P . org-publish-current-project)
23700 (?X . org-publish)
23701 (?A . org-publish-all)))
23702 r1 r2 ass)
23703 (save-window-excursion
23704 (delete-other-windows)
23705 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
23706 (princ help))
23707 (message "Select command: ")
23708 (setq r1 (read-char-exclusive)))
23709 (setq r2 (if (< r1 27) (+ r1 96) r1))
23710 (if (setq ass (assq r2 cmds))
23711 (call-interactively (cdr ass))
23712 (error "No command associated with key %c" r1))))
23714 (defconst org-html-entities
23715 '(("nbsp")
23716 ("iexcl")
23717 ("cent")
23718 ("pound")
23719 ("curren")
23720 ("yen")
23721 ("brvbar")
23722 ("vert" . "&#124;")
23723 ("sect")
23724 ("uml")
23725 ("copy")
23726 ("ordf")
23727 ("laquo")
23728 ("not")
23729 ("shy")
23730 ("reg")
23731 ("macr")
23732 ("deg")
23733 ("plusmn")
23734 ("sup2")
23735 ("sup3")
23736 ("acute")
23737 ("micro")
23738 ("para")
23739 ("middot")
23740 ("odot"."o")
23741 ("star"."*")
23742 ("cedil")
23743 ("sup1")
23744 ("ordm")
23745 ("raquo")
23746 ("frac14")
23747 ("frac12")
23748 ("frac34")
23749 ("iquest")
23750 ("Agrave")
23751 ("Aacute")
23752 ("Acirc")
23753 ("Atilde")
23754 ("Auml")
23755 ("Aring") ("AA"."&Aring;")
23756 ("AElig")
23757 ("Ccedil")
23758 ("Egrave")
23759 ("Eacute")
23760 ("Ecirc")
23761 ("Euml")
23762 ("Igrave")
23763 ("Iacute")
23764 ("Icirc")
23765 ("Iuml")
23766 ("ETH")
23767 ("Ntilde")
23768 ("Ograve")
23769 ("Oacute")
23770 ("Ocirc")
23771 ("Otilde")
23772 ("Ouml")
23773 ("times")
23774 ("Oslash")
23775 ("Ugrave")
23776 ("Uacute")
23777 ("Ucirc")
23778 ("Uuml")
23779 ("Yacute")
23780 ("THORN")
23781 ("szlig")
23782 ("agrave")
23783 ("aacute")
23784 ("acirc")
23785 ("atilde")
23786 ("auml")
23787 ("aring")
23788 ("aelig")
23789 ("ccedil")
23790 ("egrave")
23791 ("eacute")
23792 ("ecirc")
23793 ("euml")
23794 ("igrave")
23795 ("iacute")
23796 ("icirc")
23797 ("iuml")
23798 ("eth")
23799 ("ntilde")
23800 ("ograve")
23801 ("oacute")
23802 ("ocirc")
23803 ("otilde")
23804 ("ouml")
23805 ("divide")
23806 ("oslash")
23807 ("ugrave")
23808 ("uacute")
23809 ("ucirc")
23810 ("uuml")
23811 ("yacute")
23812 ("thorn")
23813 ("yuml")
23814 ("fnof")
23815 ("Alpha")
23816 ("Beta")
23817 ("Gamma")
23818 ("Delta")
23819 ("Epsilon")
23820 ("Zeta")
23821 ("Eta")
23822 ("Theta")
23823 ("Iota")
23824 ("Kappa")
23825 ("Lambda")
23826 ("Mu")
23827 ("Nu")
23828 ("Xi")
23829 ("Omicron")
23830 ("Pi")
23831 ("Rho")
23832 ("Sigma")
23833 ("Tau")
23834 ("Upsilon")
23835 ("Phi")
23836 ("Chi")
23837 ("Psi")
23838 ("Omega")
23839 ("alpha")
23840 ("beta")
23841 ("gamma")
23842 ("delta")
23843 ("epsilon")
23844 ("varepsilon"."&epsilon;")
23845 ("zeta")
23846 ("eta")
23847 ("theta")
23848 ("iota")
23849 ("kappa")
23850 ("lambda")
23851 ("mu")
23852 ("nu")
23853 ("xi")
23854 ("omicron")
23855 ("pi")
23856 ("rho")
23857 ("sigmaf") ("varsigma"."&sigmaf;")
23858 ("sigma")
23859 ("tau")
23860 ("upsilon")
23861 ("phi")
23862 ("chi")
23863 ("psi")
23864 ("omega")
23865 ("thetasym") ("vartheta"."&thetasym;")
23866 ("upsih")
23867 ("piv")
23868 ("bull") ("bullet"."&bull;")
23869 ("hellip") ("dots"."&hellip;")
23870 ("prime")
23871 ("Prime")
23872 ("oline")
23873 ("frasl")
23874 ("weierp")
23875 ("image")
23876 ("real")
23877 ("trade")
23878 ("alefsym")
23879 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
23880 ("uarr") ("uparrow"."&uarr;")
23881 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
23882 ("darr")("downarrow"."&darr;")
23883 ("harr") ("leftrightarrow"."&harr;")
23884 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
23885 ("lArr") ("Leftarrow"."&lArr;")
23886 ("uArr") ("Uparrow"."&uArr;")
23887 ("rArr") ("Rightarrow"."&rArr;")
23888 ("dArr") ("Downarrow"."&dArr;")
23889 ("hArr") ("Leftrightarrow"."&hArr;")
23890 ("forall")
23891 ("part") ("partial"."&part;")
23892 ("exist") ("exists"."&exist;")
23893 ("empty") ("emptyset"."&empty;")
23894 ("nabla")
23895 ("isin") ("in"."&isin;")
23896 ("notin")
23897 ("ni")
23898 ("prod")
23899 ("sum")
23900 ("minus")
23901 ("lowast") ("ast"."&lowast;")
23902 ("radic")
23903 ("prop") ("proptp"."&prop;")
23904 ("infin") ("infty"."&infin;")
23905 ("ang") ("angle"."&ang;")
23906 ("and") ("wedge"."&and;")
23907 ("or") ("vee"."&or;")
23908 ("cap")
23909 ("cup")
23910 ("int")
23911 ("there4")
23912 ("sim")
23913 ("cong") ("simeq"."&cong;")
23914 ("asymp")("approx"."&asymp;")
23915 ("ne") ("neq"."&ne;")
23916 ("equiv")
23917 ("le")
23918 ("ge")
23919 ("sub") ("subset"."&sub;")
23920 ("sup") ("supset"."&sup;")
23921 ("nsub")
23922 ("sube")
23923 ("supe")
23924 ("oplus")
23925 ("otimes")
23926 ("perp")
23927 ("sdot") ("cdot"."&sdot;")
23928 ("lceil")
23929 ("rceil")
23930 ("lfloor")
23931 ("rfloor")
23932 ("lang")
23933 ("rang")
23934 ("loz") ("Diamond"."&loz;")
23935 ("spades") ("spadesuit"."&spades;")
23936 ("clubs") ("clubsuit"."&clubs;")
23937 ("hearts") ("diamondsuit"."&hearts;")
23938 ("diams") ("diamondsuit"."&diams;")
23939 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
23940 ("quot")
23941 ("amp")
23942 ("lt")
23943 ("gt")
23944 ("OElig")
23945 ("oelig")
23946 ("Scaron")
23947 ("scaron")
23948 ("Yuml")
23949 ("circ")
23950 ("tilde")
23951 ("ensp")
23952 ("emsp")
23953 ("thinsp")
23954 ("zwnj")
23955 ("zwj")
23956 ("lrm")
23957 ("rlm")
23958 ("ndash")
23959 ("mdash")
23960 ("lsquo")
23961 ("rsquo")
23962 ("sbquo")
23963 ("ldquo")
23964 ("rdquo")
23965 ("bdquo")
23966 ("dagger")
23967 ("Dagger")
23968 ("permil")
23969 ("lsaquo")
23970 ("rsaquo")
23971 ("euro")
23973 ("arccos"."arccos")
23974 ("arcsin"."arcsin")
23975 ("arctan"."arctan")
23976 ("arg"."arg")
23977 ("cos"."cos")
23978 ("cosh"."cosh")
23979 ("cot"."cot")
23980 ("coth"."coth")
23981 ("csc"."csc")
23982 ("deg"."deg")
23983 ("det"."det")
23984 ("dim"."dim")
23985 ("exp"."exp")
23986 ("gcd"."gcd")
23987 ("hom"."hom")
23988 ("inf"."inf")
23989 ("ker"."ker")
23990 ("lg"."lg")
23991 ("lim"."lim")
23992 ("liminf"."liminf")
23993 ("limsup"."limsup")
23994 ("ln"."ln")
23995 ("log"."log")
23996 ("max"."max")
23997 ("min"."min")
23998 ("Pr"."Pr")
23999 ("sec"."sec")
24000 ("sin"."sin")
24001 ("sinh"."sinh")
24002 ("sup"."sup")
24003 ("tan"."tan")
24004 ("tanh"."tanh")
24006 "Entities for TeX->HTML translation.
24007 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
24008 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
24009 In that case, \"\\ent\" will be translated to \"&other;\".
24010 The list contains HTML entities for Latin-1, Greek and other symbols.
24011 It is supplemented by a number of commonly used TeX macros with appropriate
24012 translations. There is currently no way for users to extend this.")
24014 ;;; General functions for all backends
24016 (defun org-cleaned-string-for-export (string &rest parameters)
24017 "Cleanup a buffer STRING so that links can be created safely."
24018 (interactive)
24019 (let* ((re-radio (and org-target-link-regexp
24020 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
24021 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
24022 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
24023 (re-archive (concat ":" org-archive-tag ":"))
24024 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
24025 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
24026 (htmlp (plist-get parameters :for-html))
24027 (asciip (plist-get parameters :for-ascii))
24028 (latexp (plist-get parameters :for-LaTeX))
24029 (commentsp (plist-get parameters :comments))
24030 (archived-trees (plist-get parameters :archived-trees))
24031 (inhibit-read-only t)
24032 (drawers org-drawers)
24033 (exp-drawers (plist-get parameters :drawers))
24034 (outline-regexp "\\*+ ")
24035 a b xx
24036 rtn p)
24037 (with-current-buffer (get-buffer-create " org-mode-tmp")
24038 (erase-buffer)
24039 (insert string)
24040 ;; Remove license-to-kill stuff
24041 (while (setq p (text-property-any (point-min) (point-max)
24042 :org-license-to-kill t))
24043 (delete-region p (next-single-property-change p :org-license-to-kill)))
24045 (let ((org-inhibit-startup t)) (org-mode))
24046 (untabify (point-min) (point-max))
24048 ;; Get rid of drawers
24049 (unless (eq t exp-drawers)
24050 (goto-char (point-min))
24051 (let ((re (concat "^[ \t]*:\\("
24052 (mapconcat
24053 'identity
24054 (org-delete-all exp-drawers
24055 (copy-sequence drawers))
24056 "\\|")
24057 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
24058 (while (re-search-forward re nil t)
24059 (replace-match ""))))
24061 ;; Get the correct stuff before the first headline
24062 (when (plist-get parameters :skip-before-1st-heading)
24063 (goto-char (point-min))
24064 (when (re-search-forward "^\\*+[ \t]" nil t)
24065 (delete-region (point-min) (match-beginning 0))
24066 (goto-char (point-min))
24067 (insert "\n")))
24068 (when (plist-get parameters :add-text)
24069 (goto-char (point-min))
24070 (insert (plist-get parameters :add-text) "\n"))
24072 ;; Get rid of archived trees
24073 (when (not (eq archived-trees t))
24074 (goto-char (point-min))
24075 (while (re-search-forward re-archive nil t)
24076 (if (not (org-on-heading-p t))
24077 (org-end-of-subtree t)
24078 (beginning-of-line 1)
24079 (setq a (if archived-trees
24080 (1+ (point-at-eol)) (point))
24081 b (org-end-of-subtree t))
24082 (if (> b a) (delete-region a b)))))
24084 ;; Find targets in comments and move them out of comments,
24085 ;; but mark them as targets that should be invisible
24086 (goto-char (point-min))
24087 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
24088 (replace-match "\\1(INVISIBLE)"))
24090 ;; Protect backend specific stuff, throw away the others.
24091 (let ((formatters
24092 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
24093 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
24094 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
24095 fmt)
24096 (goto-char (point-min))
24097 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
24098 (goto-char (match-end 0))
24099 (while (not (looking-at "#\\+END_EXAMPLE"))
24100 (insert ": ")
24101 (beginning-of-line 2)))
24102 (goto-char (point-min))
24103 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
24104 (add-text-properties (match-beginning 0) (match-end 0)
24105 '(org-protected t)))
24106 (while formatters
24107 (setq fmt (pop formatters))
24108 (when (car fmt)
24109 (goto-char (point-min))
24110 (while (re-search-forward (concat "^#\\+" (cadr fmt)
24111 ":[ \t]*\\(.*\\)") nil t)
24112 (replace-match "\\1" t)
24113 (add-text-properties
24114 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
24115 '(org-protected t))))
24116 (goto-char (point-min))
24117 (while (re-search-forward
24118 (concat "^#\\+"
24119 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
24120 (cadddr fmt) "\\>.*\n?") nil t)
24121 (if (car fmt)
24122 (add-text-properties (match-beginning 1) (1+ (match-end 1))
24123 '(org-protected t))
24124 (delete-region (match-beginning 0) (match-end 0))))))
24126 ;; Protect quoted subtrees
24127 (goto-char (point-min))
24128 (while (re-search-forward re-quote nil t)
24129 (goto-char (match-beginning 0))
24130 (end-of-line 1)
24131 (add-text-properties (point) (org-end-of-subtree t)
24132 '(org-protected t)))
24134 ;; Protect verbatim elements
24135 (goto-char (point-min))
24136 (while (re-search-forward org-verbatim-re nil t)
24137 (add-text-properties (match-beginning 4) (match-end 4)
24138 '(org-protected t))
24139 (goto-char (1+ (match-end 4))))
24141 ;; Remove subtrees that are commented
24142 (goto-char (point-min))
24143 (while (re-search-forward re-commented nil t)
24144 (goto-char (match-beginning 0))
24145 (delete-region (point) (org-end-of-subtree t)))
24147 ;; Remove special table lines
24148 (when org-export-table-remove-special-lines
24149 (goto-char (point-min))
24150 (while (re-search-forward "^[ \t]*|" nil t)
24151 (beginning-of-line 1)
24152 (if (or (looking-at "[ \t]*| *[!_^] *|")
24153 (and (looking-at ".*?| *<[0-9]+> *|")
24154 (not (looking-at ".*?| *[^ <|]"))))
24155 (delete-region (max (point-min) (1- (point-at-bol)))
24156 (point-at-eol))
24157 (end-of-line 1))))
24159 ;; Specific LaTeX stuff
24160 (when latexp
24161 (require 'org-export-latex nil)
24162 (org-export-latex-cleaned-string))
24164 (when asciip
24165 (org-export-ascii-clean-string))
24167 ;; Specific HTML stuff
24168 (when htmlp
24169 ;; Convert LaTeX fragments to images
24170 (when (plist-get parameters :LaTeX-fragments)
24171 (org-format-latex
24172 (concat "ltxpng/" (file-name-sans-extension
24173 (file-name-nondirectory
24174 org-current-export-file)))
24175 org-current-export-dir nil "Creating LaTeX image %s"))
24176 (message "Exporting..."))
24178 ;; Remove or replace comments
24179 (goto-char (point-min))
24180 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
24181 (if commentsp
24182 (progn (add-text-properties
24183 (match-beginning 0) (match-end 0) '(org-protected t))
24184 (replace-match (format commentsp (match-string 1)) t t))
24185 (replace-match "")))
24187 ;; Find matches for radio targets and turn them into internal links
24188 (goto-char (point-min))
24189 (when re-radio
24190 (while (re-search-forward re-radio nil t)
24191 (org-if-unprotected
24192 (replace-match "\\1[[\\2]]"))))
24194 ;; Find all links that contain a newline and put them into a single line
24195 (goto-char (point-min))
24196 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
24197 (org-if-unprotected
24198 (replace-match "\\1 \\3")
24199 (goto-char (match-beginning 0))))
24202 ;; Normalize links: Convert angle and plain links into bracket links
24203 ;; Expand link abbreviations
24204 (goto-char (point-min))
24205 (while (re-search-forward re-plain-link nil t)
24206 (goto-char (1- (match-end 0)))
24207 (org-if-unprotected
24208 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24209 ":" (match-string 3) "]]")))
24210 ;; added 'org-link face to links
24211 (put-text-property 0 (length s) 'face 'org-link s)
24212 (replace-match s t t))))
24213 (goto-char (point-min))
24214 (while (re-search-forward re-angle-link nil t)
24215 (goto-char (1- (match-end 0)))
24216 (org-if-unprotected
24217 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24218 ":" (match-string 3) "]]")))
24219 (put-text-property 0 (length s) 'face 'org-link s)
24220 (replace-match s t t))))
24221 (goto-char (point-min))
24222 (while (re-search-forward org-bracket-link-regexp nil t)
24223 (org-if-unprotected
24224 (let* ((s (concat "[[" (setq xx (save-match-data
24225 (org-link-expand-abbrev (match-string 1))))
24227 (if (match-end 3)
24228 (match-string 2)
24229 (concat "[" xx "]"))
24230 "]")))
24231 (put-text-property 0 (length s) 'face 'org-link s)
24232 (replace-match s t t))))
24234 ;; Find multiline emphasis and put them into single line
24235 (when (plist-get parameters :emph-multiline)
24236 (goto-char (point-min))
24237 (while (re-search-forward org-emph-re nil t)
24238 (if (not (= (char-after (match-beginning 3))
24239 (char-after (match-beginning 4))))
24240 (org-if-unprotected
24241 (subst-char-in-region (match-beginning 0) (match-end 0)
24242 ?\n ?\ t)
24243 (goto-char (1- (match-end 0))))
24244 (goto-char (1+ (match-beginning 0))))))
24246 (setq rtn (buffer-string)))
24247 (kill-buffer " org-mode-tmp")
24248 rtn))
24250 (defun org-export-grab-title-from-buffer ()
24251 "Get a title for the current document, from looking at the buffer."
24252 (let ((inhibit-read-only t))
24253 (save-excursion
24254 (goto-char (point-min))
24255 (let ((end (save-excursion (outline-next-heading) (point))))
24256 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
24257 ;; Mark the line so that it will not be exported as normal text.
24258 (org-unmodified
24259 (add-text-properties (match-beginning 0) (match-end 0)
24260 (list :org-license-to-kill t)))
24261 ;; Return the title string
24262 (org-trim (match-string 0)))))))
24264 (defun org-export-get-title-from-subtree ()
24265 "Return subtree title and exclude it from export."
24266 (let (title (m (mark)))
24267 (save-excursion
24268 (goto-char (region-beginning))
24269 (when (and (org-at-heading-p)
24270 (>= (org-end-of-subtree t t) (region-end)))
24271 ;; This is a subtree, we take the title from the first heading
24272 (goto-char (region-beginning))
24273 (looking-at org-todo-line-regexp)
24274 (setq title (match-string 3))
24275 (org-unmodified
24276 (add-text-properties (point) (1+ (point-at-eol))
24277 (list :org-license-to-kill t)))))
24278 title))
24280 (defun org-solidify-link-text (s &optional alist)
24281 "Take link text and make a safe target out of it."
24282 (save-match-data
24283 (let* ((rtn
24284 (mapconcat
24285 'identity
24286 (org-split-string s "[ \t\r\n]+") "--"))
24287 (a (assoc rtn alist)))
24288 (or (cdr a) rtn))))
24290 (defun org-get-min-level (lines)
24291 "Get the minimum level in LINES."
24292 (let ((re "^\\(\\*+\\) ") l min)
24293 (catch 'exit
24294 (while (setq l (pop lines))
24295 (if (string-match re l)
24296 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24297 1)))
24299 ;; Variable holding the vector with section numbers
24300 (defvar org-section-numbers (make-vector org-level-max 0))
24302 (defun org-init-section-numbers ()
24303 "Initialize the vector for the section numbers."
24304 (let* ((level -1)
24305 (numbers (nreverse (org-split-string "" "\\.")))
24306 (depth (1- (length org-section-numbers)))
24307 (i depth) number-string)
24308 (while (>= i 0)
24309 (if (> i level)
24310 (aset org-section-numbers i 0)
24311 (setq number-string (or (car numbers) "0"))
24312 (if (string-match "\\`[A-Z]\\'" number-string)
24313 (aset org-section-numbers i
24314 (- (string-to-char number-string) ?A -1))
24315 (aset org-section-numbers i (string-to-number number-string)))
24316 (pop numbers))
24317 (setq i (1- i)))))
24319 (defun org-section-number (&optional level)
24320 "Return a string with the current section number.
24321 When LEVEL is non-nil, increase section numbers on that level."
24322 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
24323 (when level
24324 (when (> level -1)
24325 (aset org-section-numbers
24326 level (1+ (aref org-section-numbers level))))
24327 (setq idx (1+ level))
24328 (while (<= idx depth)
24329 (if (not (= idx 1))
24330 (aset org-section-numbers idx 0))
24331 (setq idx (1+ idx))))
24332 (setq idx 0)
24333 (while (<= idx depth)
24334 (setq n (aref org-section-numbers idx))
24335 (setq string (concat string (if (not (string= string "")) "." "")
24336 (int-to-string n)))
24337 (setq idx (1+ idx)))
24338 (save-match-data
24339 (if (string-match "\\`\\([@0]\\.\\)+" string)
24340 (setq string (replace-match "" t nil string)))
24341 (if (string-match "\\(\\.0\\)+\\'" string)
24342 (setq string (replace-match "" t nil string))))
24343 string))
24345 ;;; ASCII export
24347 (defvar org-last-level nil) ; dynamically scoped variable
24348 (defvar org-min-level nil) ; dynamically scoped variable
24349 (defvar org-levels-open nil) ; dynamically scoped parameter
24350 (defvar org-ascii-current-indentation nil) ; For communication
24352 (defun org-export-as-ascii (arg)
24353 "Export the outline as a pretty ASCII file.
24354 If there is an active region, export only the region.
24355 The prefix ARG specifies how many levels of the outline should become
24356 underlined headlines. The default is 3."
24357 (interactive "P")
24358 (setq-default org-todo-line-regexp org-todo-line-regexp)
24359 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24360 (org-infile-export-plist)))
24361 (region-p (org-region-active-p))
24362 (subtree-p
24363 (when region-p
24364 (save-excursion
24365 (goto-char (region-beginning))
24366 (and (org-at-heading-p)
24367 (>= (org-end-of-subtree t t) (region-end))))))
24368 (custom-times org-display-custom-times)
24369 (org-ascii-current-indentation '(0 . 0))
24370 (level 0) line txt
24371 (umax nil)
24372 (umax-toc nil)
24373 (case-fold-search nil)
24374 (filename (concat (file-name-as-directory
24375 (org-export-directory :ascii opt-plist))
24376 (file-name-sans-extension
24377 (or (and subtree-p
24378 (org-entry-get (region-beginning)
24379 "EXPORT_FILE_NAME" t))
24380 (file-name-nondirectory buffer-file-name)))
24381 ".txt"))
24382 (filename (if (equal (file-truename filename)
24383 (file-truename buffer-file-name))
24384 (concat filename ".txt")
24385 filename))
24386 (buffer (find-file-noselect filename))
24387 (org-levels-open (make-vector org-level-max nil))
24388 (odd org-odd-levels-only)
24389 (date (plist-get opt-plist :date))
24390 (author (plist-get opt-plist :author))
24391 (title (or (and subtree-p (org-export-get-title-from-subtree))
24392 (plist-get opt-plist :title)
24393 (and (not
24394 (plist-get opt-plist :skip-before-1st-heading))
24395 (org-export-grab-title-from-buffer))
24396 (file-name-sans-extension
24397 (file-name-nondirectory buffer-file-name))))
24398 (email (plist-get opt-plist :email))
24399 (language (plist-get opt-plist :language))
24400 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24401 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
24402 (todo nil)
24403 (lang-words nil)
24404 (region
24405 (buffer-substring
24406 (if (org-region-active-p) (region-beginning) (point-min))
24407 (if (org-region-active-p) (region-end) (point-max))))
24408 (lines (org-split-string
24409 (org-cleaned-string-for-export
24410 region
24411 :for-ascii t
24412 :skip-before-1st-heading
24413 (plist-get opt-plist :skip-before-1st-heading)
24414 :drawers (plist-get opt-plist :drawers)
24415 :verbatim-multiline t
24416 :archived-trees
24417 (plist-get opt-plist :archived-trees)
24418 :add-text (plist-get opt-plist :text))
24419 "\n"))
24420 thetoc have-headings first-heading-pos
24421 table-open table-buffer)
24423 (let ((inhibit-read-only t))
24424 (org-unmodified
24425 (remove-text-properties (point-min) (point-max)
24426 '(:org-license-to-kill t))))
24428 (setq org-min-level (org-get-min-level lines))
24429 (setq org-last-level org-min-level)
24430 (org-init-section-numbers)
24432 (find-file-noselect filename)
24434 (setq lang-words (or (assoc language org-export-language-setup)
24435 (assoc "en" org-export-language-setup)))
24436 (switch-to-buffer-other-window buffer)
24437 (erase-buffer)
24438 (fundamental-mode)
24439 ;; create local variables for all options, to make sure all called
24440 ;; functions get the correct information
24441 (mapc (lambda (x)
24442 (set (make-local-variable (cdr x))
24443 (plist-get opt-plist (car x))))
24444 org-export-plist-vars)
24445 (org-set-local 'org-odd-levels-only odd)
24446 (setq umax (if arg (prefix-numeric-value arg)
24447 org-export-headline-levels))
24448 (setq umax-toc (if (integerp org-export-with-toc)
24449 (min org-export-with-toc umax)
24450 umax))
24452 ;; File header
24453 (if title (org-insert-centered title ?=))
24454 (insert "\n")
24455 (if (and (or author email)
24456 org-export-author-info)
24457 (insert (concat (nth 1 lang-words) ": " (or author "")
24458 (if email (concat " <" email ">") "")
24459 "\n")))
24461 (cond
24462 ((and date (string-match "%" date))
24463 (setq date (format-time-string date (current-time))))
24464 (date)
24465 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24467 (if (and date org-export-time-stamp-file)
24468 (insert (concat (nth 2 lang-words) ": " date"\n")))
24470 (insert "\n\n")
24472 (if org-export-with-toc
24473 (progn
24474 (push (concat (nth 3 lang-words) "\n") thetoc)
24475 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
24476 (mapc '(lambda (line)
24477 (if (string-match org-todo-line-regexp
24478 line)
24479 ;; This is a headline
24480 (progn
24481 (setq have-headings t)
24482 (setq level (- (match-end 1) (match-beginning 1))
24483 level (org-tr-level level)
24484 txt (match-string 3 line)
24485 todo
24486 (or (and org-export-mark-todo-in-toc
24487 (match-beginning 2)
24488 (not (member (match-string 2 line)
24489 org-done-keywords)))
24490 ; TODO, not DONE
24491 (and org-export-mark-todo-in-toc
24492 (= level umax-toc)
24493 (org-search-todo-below
24494 line lines level))))
24495 (setq txt (org-html-expand-for-ascii txt))
24497 (while (string-match org-bracket-link-regexp txt)
24498 (setq txt
24499 (replace-match
24500 (match-string (if (match-end 2) 3 1) txt)
24501 t t txt)))
24503 (if (and (memq org-export-with-tags '(not-in-toc nil))
24504 (string-match
24505 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
24506 txt))
24507 (setq txt (replace-match "" t t txt)))
24508 (if (string-match quote-re0 txt)
24509 (setq txt (replace-match "" t t txt)))
24511 (if org-export-with-section-numbers
24512 (setq txt (concat (org-section-number level)
24513 " " txt)))
24514 (if (<= level umax-toc)
24515 (progn
24516 (push
24517 (concat
24518 (make-string
24519 (* (max 0 (- level org-min-level)) 4) ?\ )
24520 (format (if todo "%s (*)\n" "%s\n") txt))
24521 thetoc)
24522 (setq org-last-level level))
24523 ))))
24524 lines)
24525 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24527 (org-init-section-numbers)
24528 (while (setq line (pop lines))
24529 ;; Remove the quoted HTML tags.
24530 (setq line (org-html-expand-for-ascii line))
24531 ;; Remove targets
24532 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
24533 (setq line (replace-match "" t t line)))
24534 ;; Replace internal links
24535 (while (string-match org-bracket-link-regexp line)
24536 (setq line (replace-match
24537 (if (match-end 3) "[\\3]" "[\\1]")
24538 t nil line)))
24539 (when custom-times
24540 (setq line (org-translate-time line)))
24541 (cond
24542 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24543 ;; a Headline
24544 (setq first-heading-pos (or first-heading-pos (point)))
24545 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24546 txt (match-string 2 line))
24547 (org-ascii-level-start level txt umax lines))
24549 ((and org-export-with-tables
24550 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24551 (if (not table-open)
24552 ;; New table starts
24553 (setq table-open t table-buffer nil))
24554 ;; Accumulate lines
24555 (setq table-buffer (cons line table-buffer))
24556 (when (or (not lines)
24557 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24558 (car lines))))
24559 (setq table-open nil
24560 table-buffer (nreverse table-buffer))
24561 (insert (mapconcat
24562 (lambda (x)
24563 (org-fix-indentation x org-ascii-current-indentation))
24564 (org-format-table-ascii table-buffer)
24565 "\n") "\n")))
24567 (setq line (org-fix-indentation line org-ascii-current-indentation))
24568 (if (and org-export-with-fixed-width
24569 (string-match "^\\([ \t]*\\)\\(:\\)" line))
24570 (setq line (replace-match "\\1" nil nil line)))
24571 (insert line "\n"))))
24573 (normal-mode)
24575 ;; insert the table of contents
24576 (when thetoc
24577 (goto-char (point-min))
24578 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
24579 (progn
24580 (goto-char (match-beginning 0))
24581 (replace-match ""))
24582 (goto-char first-heading-pos))
24583 (mapc 'insert thetoc)
24584 (or (looking-at "[ \t]*\n[ \t]*\n")
24585 (insert "\n\n")))
24587 ;; Convert whitespace place holders
24588 (goto-char (point-min))
24589 (let (beg end)
24590 (while (setq beg (next-single-property-change (point) 'org-whitespace))
24591 (setq end (next-single-property-change beg 'org-whitespace))
24592 (goto-char beg)
24593 (delete-region beg end)
24594 (insert (make-string (- end beg) ?\ ))))
24596 (save-buffer)
24597 ;; remove display and invisible chars
24598 (let (beg end)
24599 (goto-char (point-min))
24600 (while (setq beg (next-single-property-change (point) 'display))
24601 (setq end (next-single-property-change beg 'display))
24602 (delete-region beg end)
24603 (goto-char beg)
24604 (insert "=>"))
24605 (goto-char (point-min))
24606 (while (setq beg (next-single-property-change (point) 'org-cwidth))
24607 (setq end (next-single-property-change beg 'org-cwidth))
24608 (delete-region beg end)
24609 (goto-char beg)))
24610 (goto-char (point-min))))
24612 (defun org-export-ascii-clean-string ()
24613 "Do extra work for ASCII export"
24614 (goto-char (point-min))
24615 (while (re-search-forward org-verbatim-re nil t)
24616 (goto-char (match-end 2))
24617 (backward-delete-char 1) (insert "'")
24618 (goto-char (match-beginning 2))
24619 (delete-char 1) (insert "`")
24620 (goto-char (match-end 2))))
24622 (defun org-search-todo-below (line lines level)
24623 "Search the subtree below LINE for any TODO entries."
24624 (let ((rest (cdr (memq line lines)))
24625 (re org-todo-line-regexp)
24626 line lv todo)
24627 (catch 'exit
24628 (while (setq line (pop rest))
24629 (if (string-match re line)
24630 (progn
24631 (setq lv (- (match-end 1) (match-beginning 1))
24632 todo (and (match-beginning 2)
24633 (not (member (match-string 2 line)
24634 org-done-keywords))))
24635 ; TODO, not DONE
24636 (if (<= lv level) (throw 'exit nil))
24637 (if todo (throw 'exit t))))))))
24639 (defun org-html-expand-for-ascii (line)
24640 "Handle quoted HTML for ASCII export."
24641 (if org-export-html-expand
24642 (while (string-match "@<[^<>\n]*>" line)
24643 ;; We just remove the tags for now.
24644 (setq line (replace-match "" nil nil line))))
24645 line)
24647 (defun org-insert-centered (s &optional underline)
24648 "Insert the string S centered and underline it with character UNDERLINE."
24649 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
24650 (insert (make-string ind ?\ ) s "\n")
24651 (if underline
24652 (insert (make-string ind ?\ )
24653 (make-string (string-width s) underline)
24654 "\n"))))
24656 (defun org-ascii-level-start (level title umax &optional lines)
24657 "Insert a new level in ASCII export."
24658 (let (char (n (- level umax 1)) (ind 0))
24659 (if (> level umax)
24660 (progn
24661 (insert (make-string (* 2 n) ?\ )
24662 (char-to-string (nth (% n (length org-export-ascii-bullets))
24663 org-export-ascii-bullets))
24664 " " title "\n")
24665 ;; find the indentation of the next non-empty line
24666 (catch 'stop
24667 (while lines
24668 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
24669 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
24670 (throw 'stop (setq ind (org-get-indentation (car lines)))))
24671 (pop lines)))
24672 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
24673 (if (or (not (equal (char-before) ?\n))
24674 (not (equal (char-before (1- (point))) ?\n)))
24675 (insert "\n"))
24676 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
24677 (unless org-export-with-tags
24678 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
24679 (setq title (replace-match "" t t title))))
24680 (if org-export-with-section-numbers
24681 (setq title (concat (org-section-number level) " " title)))
24682 (insert title "\n" (make-string (string-width title) char) "\n")
24683 (setq org-ascii-current-indentation '(0 . 0)))))
24685 (defun org-export-visible (type arg)
24686 "Create a copy of the visible part of the current buffer, and export it.
24687 The copy is created in a temporary buffer and removed after use.
24688 TYPE is the final key (as a string) that also select the export command in
24689 the `C-c C-e' export dispatcher.
24690 As a special case, if the you type SPC at the prompt, the temporary
24691 org-mode file will not be removed but presented to you so that you can
24692 continue to use it. The prefix arg ARG is passed through to the exporting
24693 command."
24694 (interactive
24695 (list (progn
24696 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
24697 (read-char-exclusive))
24698 current-prefix-arg))
24699 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
24700 (error "Invalid export key"))
24701 (let* ((binding (cdr (assoc type
24702 '((?a . org-export-as-ascii)
24703 (?\C-a . org-export-as-ascii)
24704 (?b . org-export-as-html-and-open)
24705 (?\C-b . org-export-as-html-and-open)
24706 (?h . org-export-as-html)
24707 (?H . org-export-as-html-to-buffer)
24708 (?R . org-export-region-as-html)
24709 (?x . org-export-as-xoxo)))))
24710 (keepp (equal type ?\ ))
24711 (file buffer-file-name)
24712 (buffer (get-buffer-create "*Org Export Visible*"))
24713 s e)
24714 ;; Need to hack the drawers here.
24715 (save-excursion
24716 (goto-char (point-min))
24717 (while (re-search-forward org-drawer-regexp nil t)
24718 (goto-char (match-beginning 1))
24719 (or (org-invisible-p) (org-flag-drawer nil))))
24720 (with-current-buffer buffer (erase-buffer))
24721 (save-excursion
24722 (setq s (goto-char (point-min)))
24723 (while (not (= (point) (point-max)))
24724 (goto-char (org-find-invisible))
24725 (append-to-buffer buffer s (point))
24726 (setq s (goto-char (org-find-visible))))
24727 (org-cycle-hide-drawers 'all)
24728 (goto-char (point-min))
24729 (unless keepp
24730 ;; Copy all comment lines to the end, to make sure #+ settings are
24731 ;; still available for the second export step. Kind of a hack, but
24732 ;; does do the trick.
24733 (if (looking-at "#[^\r\n]*")
24734 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
24735 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
24736 (append-to-buffer buffer (1+ (match-beginning 0))
24737 (min (point-max) (1+ (match-end 0))))))
24738 (set-buffer buffer)
24739 (let ((buffer-file-name file)
24740 (org-inhibit-startup t))
24741 (org-mode)
24742 (show-all)
24743 (unless keepp (funcall binding arg))))
24744 (if (not keepp)
24745 (kill-buffer buffer)
24746 (switch-to-buffer-other-window buffer)
24747 (goto-char (point-min)))))
24749 (defun org-find-visible ()
24750 (let ((s (point)))
24751 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24752 (get-char-property s 'invisible)))
24754 (defun org-find-invisible ()
24755 (let ((s (point)))
24756 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24757 (not (get-char-property s 'invisible))))
24760 ;;; HTML export
24762 (defun org-get-current-options ()
24763 "Return a string with current options as keyword options.
24764 Does include HTML export options as well as TODO and CATEGORY stuff."
24765 (format
24766 "#+TITLE: %s
24767 #+AUTHOR: %s
24768 #+EMAIL: %s
24769 #+LANGUAGE: %s
24770 #+TEXT: Some descriptive text to be emitted. Several lines OK.
24771 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s -:%s f:%s *:%s TeX:%s LaTeX:%s skip:%s d:%s tags:%s
24772 #+CATEGORY: %s
24773 #+SEQ_TODO: %s
24774 #+TYP_TODO: %s
24775 #+PRIORITIES: %c %c %c
24776 #+DRAWERS: %s
24777 #+STARTUP: %s %s %s %s %s
24778 #+TAGS: %s
24779 #+ARCHIVE: %s
24780 #+LINK: %s
24782 (buffer-name) (user-full-name) user-mail-address org-export-default-language
24783 org-export-headline-levels
24784 org-export-with-section-numbers
24785 org-export-with-toc
24786 org-export-preserve-breaks
24787 org-export-html-expand
24788 org-export-with-fixed-width
24789 org-export-with-tables
24790 org-export-with-sub-superscripts
24791 org-export-with-special-strings
24792 org-export-with-footnotes
24793 org-export-with-emphasize
24794 org-export-with-TeX-macros
24795 org-export-with-LaTeX-fragments
24796 org-export-skip-text-before-1st-heading
24797 org-export-with-drawers
24798 org-export-with-tags
24799 (file-name-nondirectory buffer-file-name)
24800 "TODO FEEDBACK VERIFY DONE"
24801 "Me Jason Marie DONE"
24802 org-highest-priority org-lowest-priority org-default-priority
24803 (mapconcat 'identity org-drawers " ")
24804 (cdr (assoc org-startup-folded
24805 '((nil . "showall") (t . "overview") (content . "content"))))
24806 (if org-odd-levels-only "odd" "oddeven")
24807 (if org-hide-leading-stars "hidestars" "showstars")
24808 (if org-startup-align-all-tables "align" "noalign")
24809 (cond ((eq org-log-done t) "logdone")
24810 ((equal org-log-done 'note) "lognotedone")
24811 ((not org-log-done) "nologdone"))
24812 (or (mapconcat (lambda (x)
24813 (cond
24814 ((equal '(:startgroup) x) "{")
24815 ((equal '(:endgroup) x) "}")
24816 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
24817 (t (car x))))
24818 (or org-tag-alist (org-get-buffer-tags)) " ") "")
24819 org-archive-location
24820 "org file:~/org/%s.org"
24823 (defun org-insert-export-options-template ()
24824 "Insert into the buffer a template with information for exporting."
24825 (interactive)
24826 (if (not (bolp)) (newline))
24827 (let ((s (org-get-current-options)))
24828 (and (string-match "#\\+CATEGORY" s)
24829 (setq s (substring s 0 (match-beginning 0))))
24830 (insert s)))
24832 (defun org-toggle-fixed-width-section (arg)
24833 "Toggle the fixed-width export.
24834 If there is no active region, the QUOTE keyword at the current headline is
24835 inserted or removed. When present, it causes the text between this headline
24836 and the next to be exported as fixed-width text, and unmodified.
24837 If there is an active region, this command adds or removes a colon as the
24838 first character of this line. If the first character of a line is a colon,
24839 this line is also exported in fixed-width font."
24840 (interactive "P")
24841 (let* ((cc 0)
24842 (regionp (org-region-active-p))
24843 (beg (if regionp (region-beginning) (point)))
24844 (end (if regionp (region-end)))
24845 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
24846 (case-fold-search nil)
24847 (re "[ \t]*\\(:\\)")
24848 off)
24849 (if regionp
24850 (save-excursion
24851 (goto-char beg)
24852 (setq cc (current-column))
24853 (beginning-of-line 1)
24854 (setq off (looking-at re))
24855 (while (> nlines 0)
24856 (setq nlines (1- nlines))
24857 (beginning-of-line 1)
24858 (cond
24859 (arg
24860 (move-to-column cc t)
24861 (insert ":\n")
24862 (forward-line -1))
24863 ((and off (looking-at re))
24864 (replace-match "" t t nil 1))
24865 ((not off) (move-to-column cc t) (insert ":")))
24866 (forward-line 1)))
24867 (save-excursion
24868 (org-back-to-heading)
24869 (if (looking-at (concat outline-regexp
24870 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
24871 (replace-match "" t t nil 1)
24872 (if (looking-at outline-regexp)
24873 (progn
24874 (goto-char (match-end 0))
24875 (insert org-quote-string " "))))))))
24877 (defun org-export-as-html-and-open (arg)
24878 "Export the outline as HTML and immediately open it with a browser.
24879 If there is an active region, export only the region.
24880 The prefix ARG specifies how many levels of the outline should become
24881 headlines. The default is 3. Lower levels will become bulleted lists."
24882 (interactive "P")
24883 (org-export-as-html arg 'hidden)
24884 (org-open-file buffer-file-name))
24886 (defun org-export-as-html-batch ()
24887 "Call `org-export-as-html', may be used in batch processing as
24888 emacs --batch
24889 --load=$HOME/lib/emacs/org.el
24890 --eval \"(setq org-export-headline-levels 2)\"
24891 --visit=MyFile --funcall org-export-as-html-batch"
24892 (org-export-as-html org-export-headline-levels 'hidden))
24894 (defun org-export-as-html-to-buffer (arg)
24895 "Call `org-exort-as-html` with output to a temporary buffer.
24896 No file is created. The prefix ARG is passed through to `org-export-as-html'."
24897 (interactive "P")
24898 (org-export-as-html arg nil nil "*Org HTML Export*")
24899 (switch-to-buffer-other-window "*Org HTML Export*"))
24901 (defun org-replace-region-by-html (beg end)
24902 "Assume the current region has org-mode syntax, and convert it to HTML.
24903 This can be used in any buffer. For example, you could write an
24904 itemized list in org-mode syntax in an HTML buffer and then use this
24905 command to convert it."
24906 (interactive "r")
24907 (let (reg html buf pop-up-frames)
24908 (save-window-excursion
24909 (if (org-mode-p)
24910 (setq html (org-export-region-as-html
24911 beg end t 'string))
24912 (setq reg (buffer-substring beg end)
24913 buf (get-buffer-create "*Org tmp*"))
24914 (with-current-buffer buf
24915 (erase-buffer)
24916 (insert reg)
24917 (org-mode)
24918 (setq html (org-export-region-as-html
24919 (point-min) (point-max) t 'string)))
24920 (kill-buffer buf)))
24921 (delete-region beg end)
24922 (insert html)))
24924 (defun org-export-region-as-html (beg end &optional body-only buffer)
24925 "Convert region from BEG to END in org-mode buffer to HTML.
24926 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
24927 contents, and only produce the region of converted text, useful for
24928 cut-and-paste operations.
24929 If BUFFER is a buffer or a string, use/create that buffer as a target
24930 of the converted HTML. If BUFFER is the symbol `string', return the
24931 produced HTML as a string and leave not buffer behind. For example,
24932 a Lisp program could call this function in the following way:
24934 (setq html (org-export-region-as-html beg end t 'string))
24936 When called interactively, the output buffer is selected, and shown
24937 in a window. A non-interactive call will only retunr the buffer."
24938 (interactive "r\nP")
24939 (when (interactive-p)
24940 (setq buffer "*Org HTML Export*"))
24941 (let ((transient-mark-mode t) (zmacs-regions t)
24942 rtn)
24943 (goto-char end)
24944 (set-mark (point)) ;; to activate the region
24945 (goto-char beg)
24946 (setq rtn (org-export-as-html
24947 nil nil nil
24948 buffer body-only))
24949 (if (fboundp 'deactivate-mark) (deactivate-mark))
24950 (if (and (interactive-p) (bufferp rtn))
24951 (switch-to-buffer-other-window rtn)
24952 rtn)))
24954 (defvar html-table-tag nil) ; dynamically scoped into this.
24955 (defun org-export-as-html (arg &optional hidden ext-plist
24956 to-buffer body-only)
24957 "Export the outline as a pretty HTML file.
24958 If there is an active region, export only the region. The prefix
24959 ARG specifies how many levels of the outline should become
24960 headlines. The default is 3. Lower levels will become bulleted
24961 lists. When HIDDEN is non-nil, don't display the HTML buffer.
24962 EXT-PLIST is a property list with external parameters overriding
24963 org-mode's default settings, but still inferior to file-local
24964 settings. When TO-BUFFER is non-nil, create a buffer with that
24965 name and export to that buffer. If TO-BUFFER is the symbol `string',
24966 don't leave any buffer behind but just return the resulting HTML as
24967 a string. When BODY-ONLY is set, don't produce the file header and footer,
24968 simply return the content of <body>...</body>, without even
24969 the body tags themselves."
24970 (interactive "P")
24972 ;; Make sure we have a file name when we need it.
24973 (when (and (not (or to-buffer body-only))
24974 (not buffer-file-name))
24975 (if (buffer-base-buffer)
24976 (org-set-local 'buffer-file-name
24977 (with-current-buffer (buffer-base-buffer)
24978 buffer-file-name))
24979 (error "Need a file name to be able to export.")))
24981 (message "Exporting...")
24982 (setq-default org-todo-line-regexp org-todo-line-regexp)
24983 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
24984 (setq-default org-done-keywords org-done-keywords)
24985 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
24986 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24987 ext-plist
24988 (org-infile-export-plist)))
24990 (style (plist-get opt-plist :style))
24991 (html-extension (plist-get opt-plist :html-extension))
24992 (link-validate (plist-get opt-plist :link-validation-function))
24993 valid thetoc have-headings first-heading-pos
24994 (odd org-odd-levels-only)
24995 (region-p (org-region-active-p))
24996 (subtree-p
24997 (when region-p
24998 (save-excursion
24999 (goto-char (region-beginning))
25000 (and (org-at-heading-p)
25001 (>= (org-end-of-subtree t t) (region-end))))))
25002 ;; The following two are dynamically scoped into other
25003 ;; routines below.
25004 (org-current-export-dir (org-export-directory :html opt-plist))
25005 (org-current-export-file buffer-file-name)
25006 (level 0) (line "") (origline "") txt todo
25007 (umax nil)
25008 (umax-toc nil)
25009 (filename (if to-buffer nil
25010 (expand-file-name
25011 (concat
25012 (file-name-sans-extension
25013 (or (and subtree-p
25014 (org-entry-get (region-beginning)
25015 "EXPORT_FILE_NAME" t))
25016 (file-name-nondirectory buffer-file-name)))
25017 "." html-extension)
25018 (file-name-as-directory
25019 (org-export-directory :html opt-plist)))))
25020 (current-dir (if buffer-file-name
25021 (file-name-directory buffer-file-name)
25022 default-directory))
25023 (buffer (if to-buffer
25024 (cond
25025 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
25026 (t (get-buffer-create to-buffer)))
25027 (find-file-noselect filename)))
25028 (org-levels-open (make-vector org-level-max nil))
25029 (date (plist-get opt-plist :date))
25030 (author (plist-get opt-plist :author))
25031 (title (or (and subtree-p (org-export-get-title-from-subtree))
25032 (plist-get opt-plist :title)
25033 (and (not
25034 (plist-get opt-plist :skip-before-1st-heading))
25035 (org-export-grab-title-from-buffer))
25036 (and buffer-file-name
25037 (file-name-sans-extension
25038 (file-name-nondirectory buffer-file-name)))
25039 "UNTITLED"))
25040 (html-table-tag (plist-get opt-plist :html-table-tag))
25041 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
25042 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
25043 (inquote nil)
25044 (infixed nil)
25045 (in-local-list nil)
25046 (local-list-num nil)
25047 (local-list-indent nil)
25048 (llt org-plain-list-ordered-item-terminator)
25049 (email (plist-get opt-plist :email))
25050 (language (plist-get opt-plist :language))
25051 (lang-words nil)
25052 (target-alist nil) tg
25053 (head-count 0) cnt
25054 (start 0)
25055 (coding-system (and (boundp 'buffer-file-coding-system)
25056 buffer-file-coding-system))
25057 (coding-system-for-write (or org-export-html-coding-system
25058 coding-system))
25059 (save-buffer-coding-system (or org-export-html-coding-system
25060 coding-system))
25061 (charset (and coding-system-for-write
25062 (fboundp 'coding-system-get)
25063 (coding-system-get coding-system-for-write
25064 'mime-charset)))
25065 (region
25066 (buffer-substring
25067 (if region-p (region-beginning) (point-min))
25068 (if region-p (region-end) (point-max))))
25069 (lines
25070 (org-split-string
25071 (org-cleaned-string-for-export
25072 region
25073 :emph-multiline t
25074 :for-html t
25075 :skip-before-1st-heading
25076 (plist-get opt-plist :skip-before-1st-heading)
25077 :drawers (plist-get opt-plist :drawers)
25078 :archived-trees
25079 (plist-get opt-plist :archived-trees)
25080 :add-text
25081 (plist-get opt-plist :text)
25082 :LaTeX-fragments
25083 (plist-get opt-plist :LaTeX-fragments))
25084 "[\r\n]"))
25085 table-open type
25086 table-buffer table-orig-buffer
25087 ind start-is-num starter didclose
25088 rpl path desc descp desc1 desc2 link
25091 (let ((inhibit-read-only t))
25092 (org-unmodified
25093 (remove-text-properties (point-min) (point-max)
25094 '(:org-license-to-kill t))))
25096 (message "Exporting...")
25098 (setq org-min-level (org-get-min-level lines))
25099 (setq org-last-level org-min-level)
25100 (org-init-section-numbers)
25102 (cond
25103 ((and date (string-match "%" date))
25104 (setq date (format-time-string date (current-time))))
25105 (date)
25106 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
25108 ;; Get the language-dependent settings
25109 (setq lang-words (or (assoc language org-export-language-setup)
25110 (assoc "en" org-export-language-setup)))
25112 ;; Switch to the output buffer
25113 (set-buffer buffer)
25114 (let ((inhibit-read-only t)) (erase-buffer))
25115 (fundamental-mode)
25117 (and (fboundp 'set-buffer-file-coding-system)
25118 (set-buffer-file-coding-system coding-system-for-write))
25120 (let ((case-fold-search nil)
25121 (org-odd-levels-only odd))
25122 ;; create local variables for all options, to make sure all called
25123 ;; functions get the correct information
25124 (mapc (lambda (x)
25125 (set (make-local-variable (cdr x))
25126 (plist-get opt-plist (car x))))
25127 org-export-plist-vars)
25128 (setq umax (if arg (prefix-numeric-value arg)
25129 org-export-headline-levels))
25130 (setq umax-toc (if (integerp org-export-with-toc)
25131 (min org-export-with-toc umax)
25132 umax))
25133 (unless body-only
25134 ;; File header
25135 (insert (format
25136 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
25137 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
25138 <html xmlns=\"http://www.w3.org/1999/xhtml\"
25139 lang=\"%s\" xml:lang=\"%s\">
25140 <head>
25141 <title>%s</title>
25142 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
25143 <meta name=\"generator\" content=\"Org-mode\"/>
25144 <meta name=\"generated\" content=\"%s\"/>
25145 <meta name=\"author\" content=\"%s\"/>
25147 </head><body>
25149 language language (org-html-expand title)
25150 (or charset "iso-8859-1") date author style))
25152 (insert (or (plist-get opt-plist :preamble) ""))
25154 (when (plist-get opt-plist :auto-preamble)
25155 (if title (insert (format org-export-html-title-format
25156 (org-html-expand title))))))
25158 (if (and org-export-with-toc (not body-only))
25159 (progn
25160 (push (format "<h%d>%s</h%d>\n"
25161 org-export-html-toplevel-hlevel
25162 (nth 3 lang-words)
25163 org-export-html-toplevel-hlevel)
25164 thetoc)
25165 (push "<ul>\n<li>" thetoc)
25166 (setq lines
25167 (mapcar '(lambda (line)
25168 (if (string-match org-todo-line-regexp line)
25169 ;; This is a headline
25170 (progn
25171 (setq have-headings t)
25172 (setq level (- (match-end 1) (match-beginning 1))
25173 level (org-tr-level level)
25174 txt (save-match-data
25175 (org-html-expand
25176 (org-export-cleanup-toc-line
25177 (match-string 3 line))))
25178 todo
25179 (or (and org-export-mark-todo-in-toc
25180 (match-beginning 2)
25181 (not (member (match-string 2 line)
25182 org-done-keywords)))
25183 ; TODO, not DONE
25184 (and org-export-mark-todo-in-toc
25185 (= level umax-toc)
25186 (org-search-todo-below
25187 line lines level))))
25188 (if (string-match
25189 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
25190 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
25191 (if (string-match quote-re0 txt)
25192 (setq txt (replace-match "" t t txt)))
25193 (if org-export-with-section-numbers
25194 (setq txt (concat (org-section-number level)
25195 " " txt)))
25196 (if (<= level (max umax umax-toc))
25197 (setq head-count (+ head-count 1)))
25198 (if (<= level umax-toc)
25199 (progn
25200 (if (> level org-last-level)
25201 (progn
25202 (setq cnt (- level org-last-level))
25203 (while (>= (setq cnt (1- cnt)) 0)
25204 (push "\n<ul>\n<li>" thetoc))
25205 (push "\n" thetoc)))
25206 (if (< level org-last-level)
25207 (progn
25208 (setq cnt (- org-last-level level))
25209 (while (>= (setq cnt (1- cnt)) 0)
25210 (push "</li>\n</ul>" thetoc))
25211 (push "\n" thetoc)))
25212 ;; Check for targets
25213 (while (string-match org-target-regexp line)
25214 (setq tg (match-string 1 line)
25215 line (replace-match
25216 (concat "@<span class=\"target\">" tg "@</span> ")
25217 t t line))
25218 (push (cons (org-solidify-link-text tg)
25219 (format "sec-%d" head-count))
25220 target-alist))
25221 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
25222 (setq txt (replace-match "" t t txt)))
25223 (push
25224 (format
25225 (if todo
25226 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
25227 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
25228 head-count txt) thetoc)
25230 (setq org-last-level level))
25232 line)
25233 lines))
25234 (while (> org-last-level (1- org-min-level))
25235 (setq org-last-level (1- org-last-level))
25236 (push "</li>\n</ul>\n" thetoc))
25237 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25239 (setq head-count 0)
25240 (org-init-section-numbers)
25242 (while (setq line (pop lines) origline line)
25243 (catch 'nextline
25245 ;; end of quote section?
25246 (when (and inquote (string-match "^\\*+ " line))
25247 (insert "</pre>\n")
25248 (setq inquote nil))
25249 ;; inside a quote section?
25250 (when inquote
25251 (insert (org-html-protect line) "\n")
25252 (throw 'nextline nil))
25254 ;; verbatim lines
25255 (when (and org-export-with-fixed-width
25256 (string-match "^[ \t]*:\\(.*\\)" line))
25257 (when (not infixed)
25258 (setq infixed t)
25259 (insert "<pre>\n"))
25260 (insert (org-html-protect (match-string 1 line)) "\n")
25261 (when (and lines
25262 (not (string-match "^[ \t]*\\(:.*\\)"
25263 (car lines))))
25264 (setq infixed nil)
25265 (insert "</pre>\n"))
25266 (throw 'nextline nil))
25268 ;; Protected HTML
25269 (when (get-text-property 0 'org-protected line)
25270 (let (par)
25271 (when (re-search-backward
25272 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
25273 (setq par (match-string 1))
25274 (replace-match "\\2\n"))
25275 (insert line "\n")
25276 (while (and lines
25277 (or (= (length (car lines)) 0)
25278 (get-text-property 0 'org-protected (car lines))))
25279 (insert (pop lines) "\n"))
25280 (and par (insert "<p>\n")))
25281 (throw 'nextline nil))
25283 ;; Horizontal line
25284 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
25285 (insert "\n<hr/>\n")
25286 (throw 'nextline nil))
25288 ;; make targets to anchors
25289 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
25290 (cond
25291 ((match-end 2)
25292 (setq line (replace-match
25293 (concat "@<a name=\""
25294 (org-solidify-link-text (match-string 1 line))
25295 "\">\\nbsp@</a>")
25296 t t line)))
25297 ((and org-export-with-toc (equal (string-to-char line) ?*))
25298 (setq line (replace-match
25299 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
25300 ; (concat "@<i>" (match-string 1 line) "@</i> ")
25301 t t line)))
25303 (setq line (replace-match
25304 (concat "@<a name=\""
25305 (org-solidify-link-text (match-string 1 line))
25306 "\" class=\"target\">" (match-string 1 line) "@</a> ")
25307 t t line)))))
25309 (setq line (org-html-handle-time-stamps line))
25311 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
25312 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
25313 ;; Also handle sub_superscripts and checkboxes
25314 (or (string-match org-table-hline-regexp line)
25315 (setq line (org-html-expand line)))
25317 ;; Format the links
25318 (setq start 0)
25319 (while (string-match org-bracket-link-analytic-regexp line start)
25320 (setq start (match-beginning 0))
25321 (setq type (if (match-end 2) (match-string 2 line) "internal"))
25322 (setq path (match-string 3 line))
25323 (setq desc1 (if (match-end 5) (match-string 5 line))
25324 desc2 (if (match-end 2) (concat type ":" path) path)
25325 descp (and desc1 (not (equal desc1 desc2)))
25326 desc (or desc1 desc2))
25327 ;; Make an image out of the description if that is so wanted
25328 (when (and descp (org-file-image-p desc))
25329 (save-match-data
25330 (if (string-match "^file:" desc)
25331 (setq desc (substring desc (match-end 0)))))
25332 (setq desc (concat "<img src=\"" desc "\"/>")))
25333 ;; FIXME: do we need to unescape here somewhere?
25334 (cond
25335 ((equal type "internal")
25336 (setq rpl
25337 (concat
25338 "<a href=\"#"
25339 (org-solidify-link-text
25340 (save-match-data (org-link-unescape path)) target-alist)
25341 "\">" desc "</a>")))
25342 ((member type '("http" "https"))
25343 ;; standard URL, just check if we need to inline an image
25344 (if (and (or (eq t org-export-html-inline-images)
25345 (and org-export-html-inline-images (not descp)))
25346 (org-file-image-p path))
25347 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
25348 (setq link (concat type ":" path))
25349 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
25350 ((member type '("ftp" "mailto" "news"))
25351 ;; standard URL
25352 (setq link (concat type ":" path))
25353 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
25354 ((string= type "file")
25355 ;; FILE link
25356 (let* ((filename path)
25357 (abs-p (file-name-absolute-p filename))
25358 thefile file-is-image-p search)
25359 (save-match-data
25360 (if (string-match "::\\(.*\\)" filename)
25361 (setq search (match-string 1 filename)
25362 filename (replace-match "" t nil filename)))
25363 (setq valid
25364 (if (functionp link-validate)
25365 (funcall link-validate filename current-dir)
25367 (setq file-is-image-p (org-file-image-p filename))
25368 (setq thefile (if abs-p (expand-file-name filename) filename))
25369 (when (and org-export-html-link-org-files-as-html
25370 (string-match "\\.org$" thefile))
25371 (setq thefile (concat (substring thefile 0
25372 (match-beginning 0))
25373 "." html-extension))
25374 (if (and search
25375 ;; make sure this is can be used as target search
25376 (not (string-match "^[0-9]*$" search))
25377 (not (string-match "^\\*" search))
25378 (not (string-match "^/.*/$" search)))
25379 (setq thefile (concat thefile "#"
25380 (org-solidify-link-text
25381 (org-link-unescape search)))))
25382 (when (string-match "^file:" desc)
25383 (setq desc (replace-match "" t t desc))
25384 (if (string-match "\\.org$" desc)
25385 (setq desc (replace-match "" t t desc))))))
25386 (setq rpl (if (and file-is-image-p
25387 (or (eq t org-export-html-inline-images)
25388 (and org-export-html-inline-images
25389 (not descp))))
25390 (concat "<img src=\"" thefile "\"/>")
25391 (concat "<a href=\"" thefile "\">" desc "</a>")))
25392 (if (not valid) (setq rpl desc))))
25393 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
25394 (setq rpl (concat "<i>&lt;" type ":"
25395 (save-match-data (org-link-unescape path))
25396 "&gt;</i>"))))
25397 (setq line (replace-match rpl t t line)
25398 start (+ start (length rpl))))
25400 ;; TODO items
25401 (if (and (string-match org-todo-line-regexp line)
25402 (match-beginning 2))
25404 (setq line
25405 (concat (substring line 0 (match-beginning 2))
25406 "<span class=\""
25407 (if (member (match-string 2 line)
25408 org-done-keywords)
25409 "done" "todo")
25410 "\">" (match-string 2 line)
25411 "</span>" (substring line (match-end 2)))))
25413 ;; Does this contain a reference to a footnote?
25414 (when org-export-with-footnotes
25415 (setq start 0)
25416 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
25417 (if (get-text-property (match-beginning 2) 'org-protected line)
25418 (setq start (match-end 2))
25419 (let ((n (match-string 2 line)))
25420 (setq line
25421 (replace-match
25422 (format
25423 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
25424 (match-string 1 line) n n n)
25425 t t line))))))
25427 (cond
25428 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25429 ;; This is a headline
25430 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25431 txt (match-string 2 line))
25432 (if (string-match quote-re0 txt)
25433 (setq txt (replace-match "" t t txt)))
25434 (if (<= level (max umax umax-toc))
25435 (setq head-count (+ head-count 1)))
25436 (when in-local-list
25437 ;; Close any local lists before inserting a new header line
25438 (while local-list-num
25439 (org-close-li)
25440 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25441 (pop local-list-num))
25442 (setq local-list-indent nil
25443 in-local-list nil))
25444 (setq first-heading-pos (or first-heading-pos (point)))
25445 (org-html-level-start level txt umax
25446 (and org-export-with-toc (<= level umax))
25447 head-count)
25448 ;; QUOTES
25449 (when (string-match quote-re line)
25450 (insert "<pre>")
25451 (setq inquote t)))
25453 ((and org-export-with-tables
25454 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25455 (if (not table-open)
25456 ;; New table starts
25457 (setq table-open t table-buffer nil table-orig-buffer nil))
25458 ;; Accumulate lines
25459 (setq table-buffer (cons line table-buffer)
25460 table-orig-buffer (cons origline table-orig-buffer))
25461 (when (or (not lines)
25462 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25463 (car lines))))
25464 (setq table-open nil
25465 table-buffer (nreverse table-buffer)
25466 table-orig-buffer (nreverse table-orig-buffer))
25467 (org-close-par-maybe)
25468 (insert (org-format-table-html table-buffer table-orig-buffer))))
25470 ;; Normal lines
25471 (when (string-match
25472 (cond
25473 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25474 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25475 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25476 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
25477 line)
25478 (setq ind (org-get-string-indentation line)
25479 start-is-num (match-beginning 4)
25480 starter (if (match-beginning 2)
25481 (substring (match-string 2 line) 0 -1))
25482 line (substring line (match-beginning 5)))
25483 (unless (string-match "[^ \t]" line)
25484 ;; empty line. Pretend indentation is large.
25485 (setq ind (if org-empty-line-terminates-plain-lists
25487 (1+ (or (car local-list-indent) 1)))))
25488 (setq didclose nil)
25489 (while (and in-local-list
25490 (or (and (= ind (car local-list-indent))
25491 (not starter))
25492 (< ind (car local-list-indent))))
25493 (setq didclose t)
25494 (org-close-li)
25495 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25496 (pop local-list-num) (pop local-list-indent)
25497 (setq in-local-list local-list-indent))
25498 (cond
25499 ((and starter
25500 (or (not in-local-list)
25501 (> ind (car local-list-indent))))
25502 ;; Start new (level of) list
25503 (org-close-par-maybe)
25504 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
25505 (push start-is-num local-list-num)
25506 (push ind local-list-indent)
25507 (setq in-local-list t))
25508 (starter
25509 ;; continue current list
25510 (org-close-li)
25511 (insert "<li>\n"))
25512 (didclose
25513 ;; we did close a list, normal text follows: need <p>
25514 (org-open-par)))
25515 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
25516 (setq line
25517 (replace-match
25518 (if (equal (match-string 1 line) "X")
25519 "<b>[X]</b>"
25520 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
25521 t t line))))
25523 ;; Empty lines start a new paragraph. If hand-formatted lists
25524 ;; are not fully interpreted, lines starting with "-", "+", "*"
25525 ;; also start a new paragraph.
25526 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
25528 ;; Is this the start of a footnote?
25529 (when org-export-with-footnotes
25530 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
25531 (org-close-par-maybe)
25532 (let ((n (match-string 1 line)))
25533 (setq line (replace-match
25534 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
25536 ;; Check if the line break needs to be conserved
25537 (cond
25538 ((string-match "\\\\\\\\[ \t]*$" line)
25539 (setq line (replace-match "<br/>" t t line)))
25540 (org-export-preserve-breaks
25541 (setq line (concat line "<br/>"))))
25543 (insert line "\n")))))
25545 ;; Properly close all local lists and other lists
25546 (when inquote (insert "</pre>\n"))
25547 (when in-local-list
25548 ;; Close any local lists before inserting a new header line
25549 (while local-list-num
25550 (org-close-li)
25551 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
25552 (pop local-list-num))
25553 (setq local-list-indent nil
25554 in-local-list nil))
25555 (org-html-level-start 1 nil umax
25556 (and org-export-with-toc (<= level umax))
25557 head-count)
25559 (unless body-only
25560 (when (plist-get opt-plist :auto-postamble)
25561 (insert "<div id=\"postamble\">")
25562 (when (and org-export-author-info author)
25563 (insert "<p class=\"author\"> "
25564 (nth 1 lang-words) ": " author "\n")
25565 (when email
25566 (if (listp (split-string email ",+ *"))
25567 (mapc (lambda(e)
25568 (insert "<a href=\"mailto:" e "\">&lt;"
25569 e "&gt;</a>\n"))
25570 (split-string email ",+ *"))
25571 (insert "<a href=\"mailto:" email "\">&lt;"
25572 email "&gt;</a>\n")))
25573 (insert "</p>\n"))
25574 (when (and date org-export-time-stamp-file)
25575 (insert "<p class=\"date\"> "
25576 (nth 2 lang-words) ": "
25577 date "</p>\n"))
25578 (insert "</div>"))
25580 (if org-export-html-with-timestamp
25581 (insert org-export-html-html-helper-timestamp))
25582 (insert (or (plist-get opt-plist :postamble) ""))
25583 (insert "</body>\n</html>\n"))
25585 (normal-mode)
25586 (if (eq major-mode default-major-mode) (html-mode))
25588 ;; insert the table of contents
25589 (goto-char (point-min))
25590 (when thetoc
25591 (if (or (re-search-forward
25592 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
25593 (re-search-forward
25594 "\\[TABLE-OF-CONTENTS\\]" nil t))
25595 (progn
25596 (goto-char (match-beginning 0))
25597 (replace-match ""))
25598 (goto-char first-heading-pos)
25599 (when (looking-at "\\s-*</p>")
25600 (goto-char (match-end 0))
25601 (insert "\n")))
25602 (insert "<div id=\"table-of-contents\">\n")
25603 (mapc 'insert thetoc)
25604 (insert "</div>\n"))
25605 ;; remove empty paragraphs and lists
25606 (goto-char (point-min))
25607 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
25608 (replace-match ""))
25609 (goto-char (point-min))
25610 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
25611 (replace-match ""))
25612 (goto-char (point-min))
25613 (while (re-search-forward "</ul>\\s-*<ul>\n?" nil t)
25614 (replace-match ""))
25615 ;; Convert whitespace place holders
25616 (goto-char (point-min))
25617 (let (beg end n)
25618 (while (setq beg (next-single-property-change (point) 'org-whitespace))
25619 (setq n (get-text-property beg 'org-whitespace)
25620 end (next-single-property-change beg 'org-whitespace))
25621 (goto-char beg)
25622 (delete-region beg end)
25623 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
25624 (make-string n ?x)))))
25626 (or to-buffer (save-buffer))
25627 (goto-char (point-min))
25628 (message "Exporting... done")
25629 (if (eq to-buffer 'string)
25630 (prog1 (buffer-substring (point-min) (point-max))
25631 (kill-buffer (current-buffer)))
25632 (current-buffer)))))
25634 (defvar org-table-colgroup-info nil)
25635 (defun org-format-table-ascii (lines)
25636 "Format a table for ascii export."
25637 (if (stringp lines)
25638 (setq lines (org-split-string lines "\n")))
25639 (if (not (string-match "^[ \t]*|" (car lines)))
25640 ;; Table made by table.el - test for spanning
25641 lines
25643 ;; A normal org table
25644 ;; Get rid of hlines at beginning and end
25645 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25646 (setq lines (nreverse lines))
25647 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25648 (setq lines (nreverse lines))
25649 (when org-export-table-remove-special-lines
25650 ;; Check if the table has a marking column. If yes remove the
25651 ;; column and the special lines
25652 (setq lines (org-table-clean-before-export lines)))
25653 ;; Get rid of the vertical lines except for grouping
25654 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
25655 rtn line vl1 start)
25656 (while (setq line (pop lines))
25657 (if (string-match org-table-hline-regexp line)
25658 (and (string-match "|\\(.*\\)|" line)
25659 (setq line (replace-match " \\1" t nil line)))
25660 (setq start 0 vl1 vl)
25661 (while (string-match "|" line start)
25662 (setq start (match-end 0))
25663 (or (pop vl1) (setq line (replace-match " " t t line)))))
25664 (push line rtn))
25665 (nreverse rtn))))
25667 (defun org-colgroup-info-to-vline-list (info)
25668 (let (vl new last)
25669 (while info
25670 (setq last new new (pop info))
25671 (if (or (memq last '(:end :startend))
25672 (memq new '(:start :startend)))
25673 (push t vl)
25674 (push nil vl)))
25675 (setq vl (nreverse vl))
25676 (and vl (setcar vl nil))
25677 vl))
25679 (defun org-format-table-html (lines olines)
25680 "Find out which HTML converter to use and return the HTML code."
25681 (if (stringp lines)
25682 (setq lines (org-split-string lines "\n")))
25683 (if (string-match "^[ \t]*|" (car lines))
25684 ;; A normal org table
25685 (org-format-org-table-html lines)
25686 ;; Table made by table.el - test for spanning
25687 (let* ((hlines (delq nil (mapcar
25688 (lambda (x)
25689 (if (string-match "^[ \t]*\\+-" x) x
25690 nil))
25691 lines)))
25692 (first (car hlines))
25693 (ll (and (string-match "\\S-+" first)
25694 (match-string 0 first)))
25695 (re (concat "^[ \t]*" (regexp-quote ll)))
25696 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
25697 hlines))))
25698 (if (and (not spanning)
25699 (not org-export-prefer-native-exporter-for-tables))
25700 ;; We can use my own converter with HTML conversions
25701 (org-format-table-table-html lines)
25702 ;; Need to use the code generator in table.el, with the original text.
25703 (org-format-table-table-html-using-table-generate-source olines)))))
25705 (defun org-format-org-table-html (lines &optional splice)
25706 "Format a table into HTML."
25707 ;; Get rid of hlines at beginning and end
25708 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25709 (setq lines (nreverse lines))
25710 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25711 (setq lines (nreverse lines))
25712 (when org-export-table-remove-special-lines
25713 ;; Check if the table has a marking column. If yes remove the
25714 ;; column and the special lines
25715 (setq lines (org-table-clean-before-export lines)))
25717 (let ((head (and org-export-highlight-first-table-line
25718 (delq nil (mapcar
25719 (lambda (x) (string-match "^[ \t]*|-" x))
25720 (cdr lines)))))
25721 (nlines 0) fnum i
25722 tbopen line fields html gr colgropen)
25723 (if splice (setq head nil))
25724 (unless splice (push (if head "<thead>" "<tbody>") html))
25725 (setq tbopen t)
25726 (while (setq line (pop lines))
25727 (catch 'next-line
25728 (if (string-match "^[ \t]*|-" line)
25729 (progn
25730 (unless splice
25731 (push (if head "</thead>" "</tbody>") html)
25732 (if lines (push "<tbody>" html) (setq tbopen nil)))
25733 (setq head nil) ;; head ends here, first time around
25734 ;; ignore this line
25735 (throw 'next-line t)))
25736 ;; Break the line into fields
25737 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25738 (unless fnum (setq fnum (make-vector (length fields) 0)))
25739 (setq nlines (1+ nlines) i -1)
25740 (push (concat "<tr>"
25741 (mapconcat
25742 (lambda (x)
25743 (setq i (1+ i))
25744 (if (and (< i nlines)
25745 (string-match org-table-number-regexp x))
25746 (incf (aref fnum i)))
25747 (if head
25748 (concat (car org-export-table-header-tags) x
25749 (cdr org-export-table-header-tags))
25750 (concat (car org-export-table-data-tags) x
25751 (cdr org-export-table-data-tags))))
25752 fields "")
25753 "</tr>")
25754 html)))
25755 (unless splice (if tbopen (push "</tbody>" html)))
25756 (unless splice (push "</table>\n" html))
25757 (setq html (nreverse html))
25758 (unless splice
25759 ;; Put in col tags with the alignment (unfortuntely often ignored...)
25760 (push (mapconcat
25761 (lambda (x)
25762 (setq gr (pop org-table-colgroup-info))
25763 (format "%s<col align=\"%s\"></col>%s"
25764 (if (memq gr '(:start :startend))
25765 (prog1
25766 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
25767 (setq colgropen t))
25769 (if (> (/ (float x) nlines) org-table-number-fraction)
25770 "right" "left")
25771 (if (memq gr '(:end :startend))
25772 (progn (setq colgropen nil) "</colgroup>")
25773 "")))
25774 fnum "")
25775 html)
25776 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
25777 (push html-table-tag html))
25778 (concat (mapconcat 'identity html "\n") "\n")))
25780 (defun org-table-clean-before-export (lines)
25781 "Check if the table has a marking column.
25782 If yes remove the column and the special lines."
25783 (setq org-table-colgroup-info nil)
25784 (if (memq nil
25785 (mapcar
25786 (lambda (x) (or (string-match "^[ \t]*|-" x)
25787 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
25788 lines))
25789 (progn
25790 (setq org-table-clean-did-remove-column nil)
25791 (delq nil
25792 (mapcar
25793 (lambda (x)
25794 (cond
25795 ((string-match "^[ \t]*| */ *|" x)
25796 (setq org-table-colgroup-info
25797 (mapcar (lambda (x)
25798 (cond ((member x '("<" "&lt;")) :start)
25799 ((member x '(">" "&gt;")) :end)
25800 ((member x '("<>" "&lt;&gt;")) :startend)
25801 (t nil)))
25802 (org-split-string x "[ \t]*|[ \t]*")))
25803 nil)
25804 (t x)))
25805 lines)))
25806 (setq org-table-clean-did-remove-column t)
25807 (delq nil
25808 (mapcar
25809 (lambda (x)
25810 (cond
25811 ((string-match "^[ \t]*| */ *|" x)
25812 (setq org-table-colgroup-info
25813 (mapcar (lambda (x)
25814 (cond ((member x '("<" "&lt;")) :start)
25815 ((member x '(">" "&gt;")) :end)
25816 ((member x '("<>" "&lt;&gt;")) :startend)
25817 (t nil)))
25818 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
25819 nil)
25820 ((string-match "^[ \t]*| *[!_^/] *|" x)
25821 nil) ; ignore this line
25822 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
25823 (string-match "^\\([ \t]*\\)|[^|]*|" x))
25824 ;; remove the first column
25825 (replace-match "\\1|" t nil x))))
25826 lines))))
25828 (defun org-format-table-table-html (lines)
25829 "Format a table generated by table.el into HTML.
25830 This conversion does *not* use `table-generate-source' from table.el.
25831 This has the advantage that Org-mode's HTML conversions can be used.
25832 But it has the disadvantage, that no cell- or row-spanning is allowed."
25833 (let (line field-buffer
25834 (head org-export-highlight-first-table-line)
25835 fields html empty)
25836 (setq html (concat html-table-tag "\n"))
25837 (while (setq line (pop lines))
25838 (setq empty "&nbsp;")
25839 (catch 'next-line
25840 (if (string-match "^[ \t]*\\+-" line)
25841 (progn
25842 (if field-buffer
25843 (progn
25844 (setq
25845 html
25846 (concat
25847 html
25848 "<tr>"
25849 (mapconcat
25850 (lambda (x)
25851 (if (equal x "") (setq x empty))
25852 (if head
25853 (concat (car org-export-table-header-tags) x
25854 (cdr org-export-table-header-tags))
25855 (concat (car org-export-table-data-tags) x
25856 (cdr org-export-table-data-tags))))
25857 field-buffer "\n")
25858 "</tr>\n"))
25859 (setq head nil)
25860 (setq field-buffer nil)))
25861 ;; Ignore this line
25862 (throw 'next-line t)))
25863 ;; Break the line into fields and store the fields
25864 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25865 (if field-buffer
25866 (setq field-buffer (mapcar
25867 (lambda (x)
25868 (concat x "<br/>" (pop fields)))
25869 field-buffer))
25870 (setq field-buffer fields))))
25871 (setq html (concat html "</table>\n"))
25872 html))
25874 (defun org-format-table-table-html-using-table-generate-source (lines)
25875 "Format a table into html, using `table-generate-source' from table.el.
25876 This has the advantage that cell- or row-spanning is allowed.
25877 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
25878 (require 'table)
25879 (with-current-buffer (get-buffer-create " org-tmp1 ")
25880 (erase-buffer)
25881 (insert (mapconcat 'identity lines "\n"))
25882 (goto-char (point-min))
25883 (if (not (re-search-forward "|[^+]" nil t))
25884 (error "Error processing table"))
25885 (table-recognize-table)
25886 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
25887 (table-generate-source 'html " org-tmp2 ")
25888 (set-buffer " org-tmp2 ")
25889 (buffer-substring (point-min) (point-max))))
25891 (defun org-html-handle-time-stamps (s)
25892 "Format time stamps in string S, or remove them."
25893 (catch 'exit
25894 (let (r b)
25895 (while (string-match org-maybe-keyword-time-regexp s)
25896 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
25897 ;; never export CLOCK
25898 (throw 'exit ""))
25899 (or b (setq b (substring s 0 (match-beginning 0))))
25900 (if (not org-export-with-timestamps)
25901 (setq r (concat r (substring s 0 (match-beginning 0)))
25902 s (substring s (match-end 0)))
25903 (setq r (concat
25904 r (substring s 0 (match-beginning 0))
25905 (if (match-end 1)
25906 (format "@<span class=\"timestamp-kwd\">%s @</span>"
25907 (match-string 1 s)))
25908 (format " @<span class=\"timestamp\">%s@</span>"
25909 (substring
25910 (org-translate-time (match-string 3 s)) 1 -1)))
25911 s (substring s (match-end 0)))))
25912 ;; Line break if line started and ended with time stamp stuff
25913 (if (not r)
25915 (setq r (concat r s))
25916 (unless (string-match "\\S-" (concat b s))
25917 (setq r (concat r "@<br/>")))
25918 r))))
25920 (defun org-html-protect (s)
25921 ;; convert & to &amp;, < to &lt; and > to &gt;
25922 (let ((start 0))
25923 (while (string-match "&" s start)
25924 (setq s (replace-match "&amp;" t t s)
25925 start (1+ (match-beginning 0))))
25926 (while (string-match "<" s)
25927 (setq s (replace-match "&lt;" t t s)))
25928 (while (string-match ">" s)
25929 (setq s (replace-match "&gt;" t t s))))
25932 (defun org-export-cleanup-toc-line (s)
25933 "Remove tags and time staps from lines going into the toc."
25934 (when (memq org-export-with-tags '(not-in-toc nil))
25935 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
25936 (setq s (replace-match "" t t s))))
25937 (when org-export-remove-timestamps-from-toc
25938 (while (string-match org-maybe-keyword-time-regexp s)
25939 (setq s (replace-match "" t t s))))
25940 (while (string-match org-bracket-link-regexp s)
25941 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
25942 t t s)))
25945 (defun org-html-expand (string)
25946 "Prepare STRING for HTML export. Applies all active conversions.
25947 If there are links in the string, don't modify these."
25948 (let* ((re (concat org-bracket-link-regexp "\\|"
25949 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
25950 m s l res)
25951 (while (setq m (string-match re string))
25952 (setq s (substring string 0 m)
25953 l (match-string 0 string)
25954 string (substring string (match-end 0)))
25955 (push (org-html-do-expand s) res)
25956 (push l res))
25957 (push (org-html-do-expand string) res)
25958 (apply 'concat (nreverse res))))
25960 (defun org-html-do-expand (s)
25961 "Apply all active conversions to translate special ASCII to HTML."
25962 (setq s (org-html-protect s))
25963 (if org-export-html-expand
25964 (let ((start 0))
25965 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
25966 (setq s (replace-match "<\\1>" t nil s)))))
25967 (if org-export-with-emphasize
25968 (setq s (org-export-html-convert-emphasize s)))
25969 (if org-export-with-special-strings
25970 (setq s (org-export-html-convert-special-strings s)))
25971 (if org-export-with-sub-superscripts
25972 (setq s (org-export-html-convert-sub-super s)))
25973 (if org-export-with-TeX-macros
25974 (let ((start 0) wd ass)
25975 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
25976 (if (get-text-property (match-beginning 0) 'org-protected s)
25977 (setq start (match-end 0))
25978 (setq wd (match-string 1 s))
25979 (if (setq ass (assoc wd org-html-entities))
25980 (setq s (replace-match (or (cdr ass)
25981 (concat "&" (car ass) ";"))
25982 t t s))
25983 (setq start (+ start (length wd))))))))
25986 (defun org-create-multibrace-regexp (left right n)
25987 "Create a regular expression which will match a balanced sexp.
25988 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
25989 as single character strings.
25990 The regexp returned will match the entire expression including the
25991 delimiters. It will also define a single group which contains the
25992 match except for the outermost delimiters. The maximum depth of
25993 stacked delimiters is N. Escaping delimiters is not possible."
25994 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
25995 (or "\\|")
25996 (re nothing)
25997 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
25998 (while (> n 1)
25999 (setq n (1- n)
26000 re (concat re or next)
26001 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
26002 (concat left "\\(" re "\\)" right)))
26004 (defvar org-match-substring-regexp
26005 (concat
26006 "\\([^\\]\\)\\([_^]\\)\\("
26007 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26008 "\\|"
26009 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
26010 "\\|"
26011 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
26012 "The regular expression matching a sub- or superscript.")
26014 (defvar org-match-substring-with-braces-regexp
26015 (concat
26016 "\\([^\\]\\)\\([_^]\\)\\("
26017 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26018 "\\)")
26019 "The regular expression matching a sub- or superscript, forcing braces.")
26021 (defconst org-export-html-special-string-regexps
26022 '(("\\\\-" . "&shy;")
26023 ("---\\([^-]\\)" . "&mdash;\\1")
26024 ("--\\([^-]\\)" . "&ndash;\\1")
26025 ("\\.\\.\\." . "&hellip;"))
26026 "Regular expressions for special string conversion.")
26028 (defun org-export-html-convert-special-strings (string)
26029 "Convert special characters in STRING to HTML."
26030 (let ((all org-export-html-special-string-regexps)
26031 e a re rpl start)
26032 (while (setq a (pop all))
26033 (setq re (car a) rpl (cdr a) start 0)
26034 (while (string-match re string start)
26035 (if (get-text-property (match-beginning 0) 'org-protected string)
26036 (setq start (match-end 0))
26037 (setq string (replace-match rpl t nil string)))))
26038 string))
26040 (defun org-export-html-convert-sub-super (string)
26041 "Convert sub- and superscripts in STRING to HTML."
26042 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
26043 (while (string-match org-match-substring-regexp string s)
26044 (cond
26045 ((and requireb (match-end 8)) (setq s (match-end 2)))
26046 ((get-text-property (match-beginning 2) 'org-protected string)
26047 (setq s (match-end 2)))
26049 (setq s (match-end 1)
26050 key (if (string= (match-string 2 string) "_") "sub" "sup")
26051 c (or (match-string 8 string)
26052 (match-string 6 string)
26053 (match-string 5 string))
26054 string (replace-match
26055 (concat (match-string 1 string)
26056 "<" key ">" c "</" key ">")
26057 t t string)))))
26058 (while (string-match "\\\\\\([_^]\\)" string)
26059 (setq string (replace-match (match-string 1 string) t t string)))
26060 string))
26062 (defun org-export-html-convert-emphasize (string)
26063 "Apply emphasis."
26064 (let ((s 0) rpl)
26065 (while (string-match org-emph-re string s)
26066 (if (not (equal
26067 (substring string (match-beginning 3) (1+ (match-beginning 3)))
26068 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
26069 (setq s (match-beginning 0)
26071 (concat
26072 (match-string 1 string)
26073 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
26074 (match-string 4 string)
26075 (nth 3 (assoc (match-string 3 string)
26076 org-emphasis-alist))
26077 (match-string 5 string))
26078 string (replace-match rpl t t string)
26079 s (+ s (- (length rpl) 2)))
26080 (setq s (1+ s))))
26081 string))
26083 (defvar org-par-open nil)
26084 (defun org-open-par ()
26085 "Insert <p>, but first close previous paragraph if any."
26086 (org-close-par-maybe)
26087 (insert "\n<p>")
26088 (setq org-par-open t))
26089 (defun org-close-par-maybe ()
26090 "Close paragraph if there is one open."
26091 (when org-par-open
26092 (insert "</p>")
26093 (setq org-par-open nil)))
26094 (defun org-close-li ()
26095 "Close <li> if necessary."
26096 (org-close-par-maybe)
26097 (insert "</li>\n"))
26099 (defvar body-only) ; dynamically scoped into this.
26100 (defun org-html-level-start (level title umax with-toc head-count)
26101 "Insert a new level in HTML export.
26102 When TITLE is nil, just close all open levels."
26103 (org-close-par-maybe)
26104 (let ((l org-level-max))
26105 (while (>= l level)
26106 (if (aref org-levels-open (1- l))
26107 (progn
26108 (org-html-level-close l umax)
26109 (aset org-levels-open (1- l) nil)))
26110 (setq l (1- l)))
26111 (when title
26112 ;; If title is nil, this means this function is called to close
26113 ;; all levels, so the rest is done only if title is given
26114 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
26115 (setq title (replace-match
26116 (if org-export-with-tags
26117 (save-match-data
26118 (concat
26119 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
26120 (mapconcat 'identity (org-split-string
26121 (match-string 1 title) ":")
26122 "&nbsp;")
26123 "</span>"))
26125 t t title)))
26126 (if (> level umax)
26127 (progn
26128 (if (aref org-levels-open (1- level))
26129 (progn
26130 (org-close-li)
26131 (insert "<li>" title "<br/>\n"))
26132 (aset org-levels-open (1- level) t)
26133 (org-close-par-maybe)
26134 (insert "<ul>\n<li>" title "<br/>\n")))
26135 (aset org-levels-open (1- level) t)
26136 (if (and org-export-with-section-numbers (not body-only))
26137 (setq title (concat (org-section-number level) " " title)))
26138 (setq level (+ level org-export-html-toplevel-hlevel -1))
26139 (if with-toc
26140 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
26141 level level head-count title level))
26142 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
26143 (org-open-par)))))
26145 (defun org-html-level-close (level max-outline-level)
26146 "Terminate one level in HTML export."
26147 (if (<= level max-outline-level)
26148 (insert "</div>\n")
26149 (org-close-li)
26150 (insert "</ul>\n")))
26152 ;;; iCalendar export
26154 ;;;###autoload
26155 (defun org-export-icalendar-this-file ()
26156 "Export current file as an iCalendar file.
26157 The iCalendar file will be located in the same directory as the Org-mode
26158 file, but with extension `.ics'."
26159 (interactive)
26160 (org-export-icalendar nil buffer-file-name))
26162 ;;;###autoload
26163 (defun org-export-icalendar-all-agenda-files ()
26164 "Export all files in `org-agenda-files' to iCalendar .ics files.
26165 Each iCalendar file will be located in the same directory as the Org-mode
26166 file, but with extension `.ics'."
26167 (interactive)
26168 (apply 'org-export-icalendar nil (org-agenda-files t)))
26170 ;;;###autoload
26171 (defun org-export-icalendar-combine-agenda-files ()
26172 "Export all files in `org-agenda-files' to a single combined iCalendar file.
26173 The file is stored under the name `org-combined-agenda-icalendar-file'."
26174 (interactive)
26175 (apply 'org-export-icalendar t (org-agenda-files t)))
26177 (defun org-export-icalendar (combine &rest files)
26178 "Create iCalendar files for all elements of FILES.
26179 If COMBINE is non-nil, combine all calendar entries into a single large
26180 file and store it under the name `org-combined-agenda-icalendar-file'."
26181 (save-excursion
26182 (org-prepare-agenda-buffers files)
26183 (let* ((dir (org-export-directory
26184 :ical (list :publishing-directory
26185 org-export-publishing-directory)))
26186 file ical-file ical-buffer category started org-agenda-new-buffers)
26188 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
26189 (when combine
26190 (setq ical-file
26191 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
26192 org-combined-agenda-icalendar-file
26193 (expand-file-name org-combined-agenda-icalendar-file dir))
26194 ical-buffer (org-get-agenda-file-buffer ical-file))
26195 (set-buffer ical-buffer) (erase-buffer))
26196 (while (setq file (pop files))
26197 (catch 'nextfile
26198 (org-check-agenda-file file)
26199 (set-buffer (org-get-agenda-file-buffer file))
26200 (unless combine
26201 (setq ical-file (concat (file-name-as-directory dir)
26202 (file-name-sans-extension
26203 (file-name-nondirectory buffer-file-name))
26204 ".ics"))
26205 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
26206 (with-current-buffer ical-buffer (erase-buffer)))
26207 (setq category (or org-category
26208 (file-name-sans-extension
26209 (file-name-nondirectory buffer-file-name))))
26210 (if (symbolp category) (setq category (symbol-name category)))
26211 (let ((standard-output ical-buffer))
26212 (if combine
26213 (and (not started) (setq started t)
26214 (org-start-icalendar-file org-icalendar-combined-name))
26215 (org-start-icalendar-file category))
26216 (org-print-icalendar-entries combine)
26217 (when (or (and combine (not files)) (not combine))
26218 (org-finish-icalendar-file)
26219 (set-buffer ical-buffer)
26220 (save-buffer)
26221 (run-hooks 'org-after-save-iCalendar-file-hook)))))
26222 (org-release-buffers org-agenda-new-buffers))))
26224 (defvar org-after-save-iCalendar-file-hook nil
26225 "Hook run after an iCalendar file has been saved.
26226 The iCalendar buffer is still current when this hook is run.
26227 A good way to use this is to tell a desktop calenndar application to re-read
26228 the iCalendar file.")
26230 (defun org-print-icalendar-entries (&optional combine)
26231 "Print iCalendar entries for the current Org-mode file to `standard-output'.
26232 When COMBINE is non nil, add the category to each line."
26233 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
26234 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
26235 (dts (org-ical-ts-to-string
26236 (format-time-string (cdr org-time-stamp-formats) (current-time))
26237 "DTSTART"))
26238 hd ts ts2 state status (inc t) pos b sexp rrule
26239 scheduledp deadlinep tmp pri category entry location summary desc
26240 (sexp-buffer (get-buffer-create "*ical-tmp*")))
26241 (org-refresh-category-properties)
26242 (save-excursion
26243 (goto-char (point-min))
26244 (while (re-search-forward re1 nil t)
26245 (catch :skip
26246 (org-agenda-skip)
26247 (setq pos (match-beginning 0)
26248 ts (match-string 0)
26249 inc t
26250 hd (org-get-heading)
26251 summary (org-icalendar-cleanup-string
26252 (org-entry-get nil "SUMMARY"))
26253 desc (org-icalendar-cleanup-string
26254 (or (org-entry-get nil "DESCRIPTION")
26255 (and org-icalendar-include-body (org-get-entry)))
26256 t org-icalendar-include-body)
26257 location (org-icalendar-cleanup-string
26258 (org-entry-get nil "LOCATION"))
26259 category (org-get-category))
26260 (if (looking-at re2)
26261 (progn
26262 (goto-char (match-end 0))
26263 (setq ts2 (match-string 1) inc nil))
26264 (setq tmp (buffer-substring (max (point-min)
26265 (- pos org-ds-keyword-length))
26266 pos)
26267 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
26268 (progn
26269 (setq inc nil)
26270 (replace-match "\\1" t nil ts))
26272 deadlinep (string-match org-deadline-regexp tmp)
26273 scheduledp (string-match org-scheduled-regexp tmp)
26274 ;; donep (org-entry-is-done-p)
26276 (if (or (string-match org-tr-regexp hd)
26277 (string-match org-ts-regexp hd))
26278 (setq hd (replace-match "" t t hd)))
26279 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
26280 (setq rrule
26281 (concat "\nRRULE:FREQ="
26282 (cdr (assoc
26283 (match-string 2 ts)
26284 '(("d" . "DAILY")("w" . "WEEKLY")
26285 ("m" . "MONTHLY")("y" . "YEARLY"))))
26286 ";INTERVAL=" (match-string 1 ts)))
26287 (setq rrule ""))
26288 (setq summary (or summary hd))
26289 (if (string-match org-bracket-link-regexp summary)
26290 (setq summary
26291 (replace-match (if (match-end 3)
26292 (match-string 3 summary)
26293 (match-string 1 summary))
26294 t t summary)))
26295 (if deadlinep (setq summary (concat "DL: " summary)))
26296 (if scheduledp (setq summary (concat "S: " summary)))
26297 (if (string-match "\\`<%%" ts)
26298 (with-current-buffer sexp-buffer
26299 (insert (substring ts 1 -1) " " summary "\n"))
26300 (princ (format "BEGIN:VEVENT
26302 %s%s
26303 SUMMARY:%s%s%s
26304 CATEGORIES:%s
26305 END:VEVENT\n"
26306 (org-ical-ts-to-string ts "DTSTART")
26307 (org-ical-ts-to-string ts2 "DTEND" inc)
26308 rrule summary
26309 (if (and desc (string-match "\\S-" desc))
26310 (concat "\nDESCRIPTION: " desc) "")
26311 (if (and location (string-match "\\S-" location))
26312 (concat "\nLOCATION: " location) "")
26313 category)))))
26315 (when (and org-icalendar-include-sexps
26316 (condition-case nil (require 'icalendar) (error nil))
26317 (fboundp 'icalendar-export-region))
26318 ;; Get all the literal sexps
26319 (goto-char (point-min))
26320 (while (re-search-forward "^&?%%(" nil t)
26321 (catch :skip
26322 (org-agenda-skip)
26323 (setq b (match-beginning 0))
26324 (goto-char (1- (match-end 0)))
26325 (forward-sexp 1)
26326 (end-of-line 1)
26327 (setq sexp (buffer-substring b (point)))
26328 (with-current-buffer sexp-buffer
26329 (insert sexp "\n"))
26330 (princ (org-diary-to-ical-string sexp-buffer)))))
26332 (when org-icalendar-include-todo
26333 (goto-char (point-min))
26334 (while (re-search-forward org-todo-line-regexp nil t)
26335 (catch :skip
26336 (org-agenda-skip)
26337 (setq state (match-string 2))
26338 (setq status (if (member state org-done-keywords)
26339 "COMPLETED" "NEEDS-ACTION"))
26340 (when (and state
26341 (or (not (member state org-done-keywords))
26342 (eq org-icalendar-include-todo 'all))
26343 (not (member org-archive-tag (org-get-tags-at)))
26345 (setq hd (match-string 3)
26346 summary (org-icalendar-cleanup-string
26347 (org-entry-get nil "SUMMARY"))
26348 desc (org-icalendar-cleanup-string
26349 (or (org-entry-get nil "DESCRIPTION")
26350 (and org-icalendar-include-body (org-get-entry)))
26351 t org-icalendar-include-body)
26352 location (org-icalendar-cleanup-string
26353 (org-entry-get nil "LOCATION")))
26354 (if (string-match org-bracket-link-regexp hd)
26355 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
26356 (match-string 1 hd))
26357 t t hd)))
26358 (if (string-match org-priority-regexp hd)
26359 (setq pri (string-to-char (match-string 2 hd))
26360 hd (concat (substring hd 0 (match-beginning 1))
26361 (substring hd (match-end 1))))
26362 (setq pri org-default-priority))
26363 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
26364 (- org-lowest-priority org-highest-priority))))))
26366 (princ (format "BEGIN:VTODO
26368 SUMMARY:%s%s%s
26369 CATEGORIES:%s
26370 SEQUENCE:1
26371 PRIORITY:%d
26372 STATUS:%s
26373 END:VTODO\n"
26375 (or summary hd)
26376 (if (and location (string-match "\\S-" location))
26377 (concat "\nLOCATION: " location) "")
26378 (if (and desc (string-match "\\S-" desc))
26379 (concat "\nDESCRIPTION: " desc) "")
26380 category pri status)))))))))
26382 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
26383 "Take out stuff and quote what needs to be quoted.
26384 When IS-BODY is non-nil, assume that this is the body of an item, clean up
26385 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
26386 characters."
26387 (if (not s)
26389 (when is-body
26390 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
26391 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
26392 (while (string-match re s) (setq s (replace-match "" t t s)))
26393 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
26394 (let ((start 0))
26395 (while (string-match "\\([,;\\]\\)" s start)
26396 (setq start (+ (match-beginning 0) 2)
26397 s (replace-match "\\\\\\1" nil nil s))))
26398 (when is-body
26399 (while (string-match "[ \t]*\n[ \t]*" s)
26400 (setq s (replace-match "\\n" t t s))))
26401 (setq s (org-trim s))
26402 (if is-body
26403 (if maxlength
26404 (if (and (numberp maxlength)
26405 (> (length s) maxlength))
26406 (setq s (substring s 0 maxlength)))))
26409 (defun org-get-entry ()
26410 "Clean-up description string."
26411 (save-excursion
26412 (org-back-to-heading t)
26413 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
26415 (defun org-start-icalendar-file (name)
26416 "Start an iCalendar file by inserting the header."
26417 (let ((user user-full-name)
26418 (name (or name "unknown"))
26419 (timezone (cadr (current-time-zone))))
26420 (princ
26421 (format "BEGIN:VCALENDAR
26422 VERSION:2.0
26423 X-WR-CALNAME:%s
26424 PRODID:-//%s//Emacs with Org-mode//EN
26425 X-WR-TIMEZONE:%s
26426 CALSCALE:GREGORIAN\n" name user timezone))))
26428 (defun org-finish-icalendar-file ()
26429 "Finish an iCalendar file by inserting the END statement."
26430 (princ "END:VCALENDAR\n"))
26432 (defun org-ical-ts-to-string (s keyword &optional inc)
26433 "Take a time string S and convert it to iCalendar format.
26434 KEYWORD is added in front, to make a complete line like DTSTART....
26435 When INC is non-nil, increase the hour by two (if time string contains
26436 a time), or the day by one (if it does not contain a time)."
26437 (let ((t1 (org-parse-time-string s 'nodefault))
26438 t2 fmt have-time time)
26439 (if (and (car t1) (nth 1 t1) (nth 2 t1))
26440 (setq t2 t1 have-time t)
26441 (setq t2 (org-parse-time-string s)))
26442 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
26443 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
26444 (when inc
26445 (if have-time
26446 (if org-agenda-default-appointment-duration
26447 (setq mi (+ org-agenda-default-appointment-duration mi))
26448 (setq h (+ 2 h)))
26449 (setq d (1+ d))))
26450 (setq time (encode-time s mi h d m y)))
26451 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
26452 (concat keyword (format-time-string fmt time))))
26454 ;;; XOXO export
26456 (defun org-export-as-xoxo-insert-into (buffer &rest output)
26457 (with-current-buffer buffer
26458 (apply 'insert output)))
26459 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
26461 (defun org-export-as-xoxo (&optional buffer)
26462 "Export the org buffer as XOXO.
26463 The XOXO buffer is named *xoxo-<source buffer name>*"
26464 (interactive (list (current-buffer)))
26465 ;; A quickie abstraction
26467 ;; Output everything as XOXO
26468 (with-current-buffer (get-buffer buffer)
26469 (let* ((pos (point))
26470 (opt-plist (org-combine-plists (org-default-export-plist)
26471 (org-infile-export-plist)))
26472 (filename (concat (file-name-as-directory
26473 (org-export-directory :xoxo opt-plist))
26474 (file-name-sans-extension
26475 (file-name-nondirectory buffer-file-name))
26476 ".html"))
26477 (out (find-file-noselect filename))
26478 (last-level 1)
26479 (hanging-li nil))
26480 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
26481 ;; Check the output buffer is empty.
26482 (with-current-buffer out (erase-buffer))
26483 ;; Kick off the output
26484 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
26485 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
26486 (let* ((hd (match-string-no-properties 1))
26487 (level (length hd))
26488 (text (concat
26489 (match-string-no-properties 2)
26490 (save-excursion
26491 (goto-char (match-end 0))
26492 (let ((str ""))
26493 (catch 'loop
26494 (while 't
26495 (forward-line)
26496 (if (looking-at "^[ \t]\\(.*\\)")
26497 (setq str (concat str (match-string-no-properties 1)))
26498 (throw 'loop str)))))))))
26500 ;; Handle level rendering
26501 (cond
26502 ((> level last-level)
26503 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
26505 ((< level last-level)
26506 (dotimes (- (- last-level level) 1)
26507 (if hanging-li
26508 (org-export-as-xoxo-insert-into out "</li>\n"))
26509 (org-export-as-xoxo-insert-into out "</ol>\n"))
26510 (when hanging-li
26511 (org-export-as-xoxo-insert-into out "</li>\n")
26512 (setq hanging-li nil)))
26514 ((equal level last-level)
26515 (if hanging-li
26516 (org-export-as-xoxo-insert-into out "</li>\n")))
26519 (setq last-level level)
26521 ;; And output the new li
26522 (setq hanging-li 't)
26523 (if (equal ?+ (elt text 0))
26524 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
26525 (org-export-as-xoxo-insert-into out "<li>" text))))
26527 ;; Finally finish off the ol
26528 (dotimes (- last-level 1)
26529 (if hanging-li
26530 (org-export-as-xoxo-insert-into out "</li>\n"))
26531 (org-export-as-xoxo-insert-into out "</ol>\n"))
26533 (goto-char pos)
26534 ;; Finish the buffer off and clean it up.
26535 (switch-to-buffer-other-window out)
26536 (indent-region (point-min) (point-max) nil)
26537 (save-buffer)
26538 (goto-char (point-min))
26542 ;;;; Key bindings
26544 ;; Make `C-c C-x' a prefix key
26545 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
26547 ;; TAB key with modifiers
26548 (org-defkey org-mode-map "\C-i" 'org-cycle)
26549 (org-defkey org-mode-map [(tab)] 'org-cycle)
26550 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
26551 (org-defkey org-mode-map [(meta tab)] 'org-complete)
26552 (org-defkey org-mode-map "\M-\t" 'org-complete)
26553 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
26554 ;; The following line is necessary under Suse GNU/Linux
26555 (unless (featurep 'xemacs)
26556 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
26557 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
26558 (define-key org-mode-map [backtab] 'org-shifttab)
26560 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
26561 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
26562 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
26564 ;; Cursor keys with modifiers
26565 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
26566 (org-defkey org-mode-map [(meta right)] 'org-metaright)
26567 (org-defkey org-mode-map [(meta up)] 'org-metaup)
26568 (org-defkey org-mode-map [(meta down)] 'org-metadown)
26570 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
26571 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
26572 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
26573 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
26575 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
26576 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
26577 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
26578 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
26580 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
26581 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
26583 ;;; Extra keys for tty access.
26584 ;; We only set them when really needed because otherwise the
26585 ;; menus don't show the simple keys
26587 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
26588 (not window-system))
26589 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
26590 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
26591 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
26592 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
26593 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
26594 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
26595 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
26596 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
26597 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
26598 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
26599 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
26600 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
26601 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
26602 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
26603 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
26604 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
26605 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
26606 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
26607 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
26608 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
26609 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
26610 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
26612 ;; All the other keys
26614 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
26615 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
26616 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
26617 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
26618 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
26619 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
26620 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
26621 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
26622 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
26623 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
26624 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
26625 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
26626 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
26627 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
26628 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
26629 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
26630 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
26631 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
26632 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
26633 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
26634 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
26635 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
26636 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
26637 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
26638 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
26639 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
26640 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
26641 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
26642 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
26643 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
26644 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
26645 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
26646 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
26647 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
26648 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
26649 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
26650 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
26651 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
26652 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
26653 (org-defkey org-mode-map "\C-c^" 'org-sort)
26654 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
26655 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
26656 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
26657 (org-defkey org-mode-map "\C-m" 'org-return)
26658 (org-defkey org-mode-map "\C-j" 'org-return-indent)
26659 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
26660 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
26661 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
26662 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
26663 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
26664 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
26665 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
26666 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
26667 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
26668 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
26669 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
26670 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
26671 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
26672 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
26673 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
26674 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
26676 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
26677 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
26678 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
26679 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
26681 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
26682 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
26683 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
26684 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
26685 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
26686 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
26687 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
26688 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
26689 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
26690 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
26691 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
26692 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
26694 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
26696 (when (featurep 'xemacs)
26697 (org-defkey org-mode-map 'button3 'popup-mode-menu))
26699 (defsubst org-table-p () (org-at-table-p))
26701 (defun org-self-insert-command (N)
26702 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
26703 If the cursor is in a table looking at whitespace, the whitespace is
26704 overwritten, and the table is not marked as requiring realignment."
26705 (interactive "p")
26706 (if (and (org-table-p)
26707 (progn
26708 ;; check if we blank the field, and if that triggers align
26709 (and org-table-auto-blank-field
26710 (member last-command
26711 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
26712 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
26713 ;; got extra space, this field does not determine column width
26714 (let (org-table-may-need-update) (org-table-blank-field))
26715 ;; no extra space, this field may determine column width
26716 (org-table-blank-field)))
26718 (eq N 1)
26719 (looking-at "[^|\n]* |"))
26720 (let (org-table-may-need-update)
26721 (goto-char (1- (match-end 0)))
26722 (delete-backward-char 1)
26723 (goto-char (match-beginning 0))
26724 (self-insert-command N))
26725 (setq org-table-may-need-update t)
26726 (self-insert-command N)
26727 (org-fix-tags-on-the-fly)))
26729 (defun org-fix-tags-on-the-fly ()
26730 (when (and (equal (char-after (point-at-bol)) ?*)
26731 (org-on-heading-p))
26732 (org-align-tags-here org-tags-column)))
26734 (defun org-delete-backward-char (N)
26735 "Like `delete-backward-char', insert whitespace at field end in tables.
26736 When deleting backwards, in tables this function will insert whitespace in
26737 front of the next \"|\" separator, to keep the table aligned. The table will
26738 still be marked for re-alignment if the field did fill the entire column,
26739 because, in this case the deletion might narrow the column."
26740 (interactive "p")
26741 (if (and (org-table-p)
26742 (eq N 1)
26743 (string-match "|" (buffer-substring (point-at-bol) (point)))
26744 (looking-at ".*?|"))
26745 (let ((pos (point))
26746 (noalign (looking-at "[^|\n\r]* |"))
26747 (c org-table-may-need-update))
26748 (backward-delete-char N)
26749 (skip-chars-forward "^|")
26750 (insert " ")
26751 (goto-char (1- pos))
26752 ;; noalign: if there were two spaces at the end, this field
26753 ;; does not determine the width of the column.
26754 (if noalign (setq org-table-may-need-update c)))
26755 (backward-delete-char N)
26756 (org-fix-tags-on-the-fly)))
26758 (defun org-delete-char (N)
26759 "Like `delete-char', but insert whitespace at field end in tables.
26760 When deleting characters, in tables this function will insert whitespace in
26761 front of the next \"|\" separator, to keep the table aligned. The table will
26762 still be marked for re-alignment if the field did fill the entire column,
26763 because, in this case the deletion might narrow the column."
26764 (interactive "p")
26765 (if (and (org-table-p)
26766 (not (bolp))
26767 (not (= (char-after) ?|))
26768 (eq N 1))
26769 (if (looking-at ".*?|")
26770 (let ((pos (point))
26771 (noalign (looking-at "[^|\n\r]* |"))
26772 (c org-table-may-need-update))
26773 (replace-match (concat
26774 (substring (match-string 0) 1 -1)
26775 " |"))
26776 (goto-char pos)
26777 ;; noalign: if there were two spaces at the end, this field
26778 ;; does not determine the width of the column.
26779 (if noalign (setq org-table-may-need-update c)))
26780 (delete-char N))
26781 (delete-char N)
26782 (org-fix-tags-on-the-fly)))
26784 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
26785 (put 'org-self-insert-command 'delete-selection t)
26786 (put 'orgtbl-self-insert-command 'delete-selection t)
26787 (put 'org-delete-char 'delete-selection 'supersede)
26788 (put 'org-delete-backward-char 'delete-selection 'supersede)
26790 ;; Make `flyspell-mode' delay after some commands
26791 (put 'org-self-insert-command 'flyspell-delayed t)
26792 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
26793 (put 'org-delete-char 'flyspell-delayed t)
26794 (put 'org-delete-backward-char 'flyspell-delayed t)
26796 ;; Make pabbrev-mode expand after org-mode commands
26797 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
26798 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
26800 ;; How to do this: Measure non-white length of current string
26801 ;; If equal to column width, we should realign.
26803 (defun org-remap (map &rest commands)
26804 "In MAP, remap the functions given in COMMANDS.
26805 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
26806 (let (new old)
26807 (while commands
26808 (setq old (pop commands) new (pop commands))
26809 (if (fboundp 'command-remapping)
26810 (org-defkey map (vector 'remap old) new)
26811 (substitute-key-definition old new map global-map)))))
26813 (when (eq org-enable-table-editor 'optimized)
26814 ;; If the user wants maximum table support, we need to hijack
26815 ;; some standard editing functions
26816 (org-remap org-mode-map
26817 'self-insert-command 'org-self-insert-command
26818 'delete-char 'org-delete-char
26819 'delete-backward-char 'org-delete-backward-char)
26820 (org-defkey org-mode-map "|" 'org-force-self-insert))
26822 (defun org-shiftcursor-error ()
26823 "Throw an error because Shift-Cursor command was applied in wrong context."
26824 (error "This command is active in special context like tables, headlines or timestamps"))
26826 (defun org-shifttab (&optional arg)
26827 "Global visibility cycling or move to previous table field.
26828 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
26829 on context.
26830 See the individual commands for more information."
26831 (interactive "P")
26832 (cond
26833 ((org-at-table-p) (call-interactively 'org-table-previous-field))
26834 (arg (message "Content view to level: ")
26835 (org-content (prefix-numeric-value arg))
26836 (setq org-cycle-global-status 'overview))
26837 (t (call-interactively 'org-global-cycle))))
26839 (defun org-shiftmetaleft ()
26840 "Promote subtree or delete table column.
26841 Calls `org-promote-subtree', `org-outdent-item',
26842 or `org-table-delete-column', depending on context.
26843 See the individual commands for more information."
26844 (interactive)
26845 (cond
26846 ((org-at-table-p) (call-interactively 'org-table-delete-column))
26847 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
26848 ((org-at-item-p) (call-interactively 'org-outdent-item))
26849 (t (org-shiftcursor-error))))
26851 (defun org-shiftmetaright ()
26852 "Demote subtree or insert table column.
26853 Calls `org-demote-subtree', `org-indent-item',
26854 or `org-table-insert-column', depending on context.
26855 See the individual commands for more information."
26856 (interactive)
26857 (cond
26858 ((org-at-table-p) (call-interactively 'org-table-insert-column))
26859 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
26860 ((org-at-item-p) (call-interactively 'org-indent-item))
26861 (t (org-shiftcursor-error))))
26863 (defun org-shiftmetaup (&optional arg)
26864 "Move subtree up or kill table row.
26865 Calls `org-move-subtree-up' or `org-table-kill-row' or
26866 `org-move-item-up' depending on context. See the individual commands
26867 for more information."
26868 (interactive "P")
26869 (cond
26870 ((org-at-table-p) (call-interactively 'org-table-kill-row))
26871 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26872 ((org-at-item-p) (call-interactively 'org-move-item-up))
26873 (t (org-shiftcursor-error))))
26874 (defun org-shiftmetadown (&optional arg)
26875 "Move subtree down or insert table row.
26876 Calls `org-move-subtree-down' or `org-table-insert-row' or
26877 `org-move-item-down', depending on context. See the individual
26878 commands for more information."
26879 (interactive "P")
26880 (cond
26881 ((org-at-table-p) (call-interactively 'org-table-insert-row))
26882 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26883 ((org-at-item-p) (call-interactively 'org-move-item-down))
26884 (t (org-shiftcursor-error))))
26886 (defun org-metaleft (&optional arg)
26887 "Promote heading or move table column to left.
26888 Calls `org-do-promote' or `org-table-move-column', depending on context.
26889 With no specific context, calls the Emacs default `backward-word'.
26890 See the individual commands for more information."
26891 (interactive "P")
26892 (cond
26893 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
26894 ((or (org-on-heading-p) (org-region-active-p))
26895 (call-interactively 'org-do-promote))
26896 ((org-at-item-p) (call-interactively 'org-outdent-item))
26897 (t (call-interactively 'backward-word))))
26899 (defun org-metaright (&optional arg)
26900 "Demote subtree or move table column to right.
26901 Calls `org-do-demote' or `org-table-move-column', depending on context.
26902 With no specific context, calls the Emacs default `forward-word'.
26903 See the individual commands for more information."
26904 (interactive "P")
26905 (cond
26906 ((org-at-table-p) (call-interactively 'org-table-move-column))
26907 ((or (org-on-heading-p) (org-region-active-p))
26908 (call-interactively 'org-do-demote))
26909 ((org-at-item-p) (call-interactively 'org-indent-item))
26910 (t (call-interactively 'forward-word))))
26912 (defun org-metaup (&optional arg)
26913 "Move subtree up or move table row up.
26914 Calls `org-move-subtree-up' or `org-table-move-row' or
26915 `org-move-item-up', depending on context. See the individual commands
26916 for more information."
26917 (interactive "P")
26918 (cond
26919 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
26920 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26921 ((org-at-item-p) (call-interactively 'org-move-item-up))
26922 (t (transpose-lines 1) (beginning-of-line -1))))
26924 (defun org-metadown (&optional arg)
26925 "Move subtree down or move table row down.
26926 Calls `org-move-subtree-down' or `org-table-move-row' or
26927 `org-move-item-down', depending on context. See the individual
26928 commands for more information."
26929 (interactive "P")
26930 (cond
26931 ((org-at-table-p) (call-interactively 'org-table-move-row))
26932 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26933 ((org-at-item-p) (call-interactively 'org-move-item-down))
26934 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
26936 (defun org-shiftup (&optional arg)
26937 "Increase item in timestamp or increase priority of current headline.
26938 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
26939 depending on context. See the individual commands for more information."
26940 (interactive "P")
26941 (cond
26942 ((org-at-timestamp-p t)
26943 (call-interactively (if org-edit-timestamp-down-means-later
26944 'org-timestamp-down 'org-timestamp-up)))
26945 ((org-on-heading-p) (call-interactively 'org-priority-up))
26946 ((org-at-item-p) (call-interactively 'org-previous-item))
26947 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
26949 (defun org-shiftdown (&optional arg)
26950 "Decrease item in timestamp or decrease priority of current headline.
26951 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
26952 depending on context. See the individual commands for more information."
26953 (interactive "P")
26954 (cond
26955 ((org-at-timestamp-p t)
26956 (call-interactively (if org-edit-timestamp-down-means-later
26957 'org-timestamp-up 'org-timestamp-down)))
26958 ((org-on-heading-p) (call-interactively 'org-priority-down))
26959 (t (call-interactively 'org-next-item))))
26961 (defun org-shiftright ()
26962 "Next TODO keyword or timestamp one day later, depending on context."
26963 (interactive)
26964 (cond
26965 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
26966 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
26967 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
26968 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
26969 (t (org-shiftcursor-error))))
26971 (defun org-shiftleft ()
26972 "Previous TODO keyword or timestamp one day earlier, depending on context."
26973 (interactive)
26974 (cond
26975 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
26976 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
26977 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
26978 ((org-at-property-p)
26979 (call-interactively 'org-property-previous-allowed-value))
26980 (t (org-shiftcursor-error))))
26982 (defun org-shiftcontrolright ()
26983 "Switch to next TODO set."
26984 (interactive)
26985 (cond
26986 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
26987 (t (org-shiftcursor-error))))
26989 (defun org-shiftcontrolleft ()
26990 "Switch to previous TODO set."
26991 (interactive)
26992 (cond
26993 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
26994 (t (org-shiftcursor-error))))
26996 (defun org-ctrl-c-ret ()
26997 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
26998 (interactive)
26999 (cond
27000 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
27001 (t (call-interactively 'org-insert-heading))))
27003 (defun org-copy-special ()
27004 "Copy region in table or copy current subtree.
27005 Calls `org-table-copy' or `org-copy-subtree', depending on context.
27006 See the individual commands for more information."
27007 (interactive)
27008 (call-interactively
27009 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
27011 (defun org-cut-special ()
27012 "Cut region in table or cut current subtree.
27013 Calls `org-table-copy' or `org-cut-subtree', depending on context.
27014 See the individual commands for more information."
27015 (interactive)
27016 (call-interactively
27017 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
27019 (defun org-paste-special (arg)
27020 "Paste rectangular region into table, or past subtree relative to level.
27021 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
27022 See the individual commands for more information."
27023 (interactive "P")
27024 (if (org-at-table-p)
27025 (org-table-paste-rectangle)
27026 (org-paste-subtree arg)))
27028 (defun org-ctrl-c-ctrl-c (&optional arg)
27029 "Set tags in headline, or update according to changed information at point.
27031 This command does many different things, depending on context:
27033 - If the cursor is in a headline, prompt for tags and insert them
27034 into the current line, aligned to `org-tags-column'. When called
27035 with prefix arg, realign all tags in the current buffer.
27037 - If the cursor is in one of the special #+KEYWORD lines, this
27038 triggers scanning the buffer for these lines and updating the
27039 information.
27041 - If the cursor is inside a table, realign the table. This command
27042 works even if the automatic table editor has been turned off.
27044 - If the cursor is on a #+TBLFM line, re-apply the formulas to
27045 the entire table.
27047 - If the cursor is a the beginning of a dynamic block, update it.
27049 - If the cursor is inside a table created by the table.el package,
27050 activate that table.
27052 - If the current buffer is a remember buffer, close note and file it.
27053 with a prefix argument, file it without further interaction to the default
27054 location.
27056 - If the cursor is on a <<<target>>>, update radio targets and corresponding
27057 links in this buffer.
27059 - If the cursor is on a numbered item in a plain list, renumber the
27060 ordered list.
27062 - If the cursor is on a checkbox, toggle it."
27063 (interactive "P")
27064 (let ((org-enable-table-editor t))
27065 (cond
27066 ((or org-clock-overlays
27067 org-occur-highlights
27068 org-latex-fragment-image-overlays)
27069 (org-remove-clock-overlays)
27070 (org-remove-occur-highlights)
27071 (org-remove-latex-fragment-image-overlays)
27072 (message "Temporary highlights/overlays removed from current buffer"))
27073 ((and (local-variable-p 'org-finish-function (current-buffer))
27074 (fboundp org-finish-function))
27075 (funcall org-finish-function))
27076 ((org-at-property-p)
27077 (call-interactively 'org-property-action))
27078 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
27079 ((org-on-heading-p) (call-interactively 'org-set-tags))
27080 ((org-at-table.el-p)
27081 (require 'table)
27082 (beginning-of-line 1)
27083 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
27084 (call-interactively 'table-recognize-table))
27085 ((org-at-table-p)
27086 (org-table-maybe-eval-formula)
27087 (if arg
27088 (call-interactively 'org-table-recalculate)
27089 (org-table-maybe-recalculate-line))
27090 (call-interactively 'org-table-align))
27091 ((org-at-item-checkbox-p)
27092 (call-interactively 'org-toggle-checkbox))
27093 ((org-at-item-p)
27094 (call-interactively 'org-maybe-renumber-ordered-list))
27095 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
27096 ;; Dynamic block
27097 (beginning-of-line 1)
27098 (org-update-dblock))
27099 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
27100 (cond
27101 ((equal (match-string 1) "TBLFM")
27102 ;; Recalculate the table before this line
27103 (save-excursion
27104 (beginning-of-line 1)
27105 (skip-chars-backward " \r\n\t")
27106 (if (org-at-table-p)
27107 (org-call-with-arg 'org-table-recalculate t))))
27109 (call-interactively 'org-mode-restart))))
27110 (t (error "C-c C-c can do nothing useful at this location.")))))
27112 (defun org-mode-restart ()
27113 "Restart Org-mode, to scan again for special lines.
27114 Also updates the keyword regular expressions."
27115 (interactive)
27116 (let ((org-inhibit-startup t)) (org-mode))
27117 (message "Org-mode restarted to refresh keyword and special line setup"))
27119 (defun org-kill-note-or-show-branches ()
27120 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
27121 (interactive)
27122 (if (not org-finish-function)
27123 (call-interactively 'show-branches)
27124 (let ((org-note-abort t))
27125 (funcall org-finish-function))))
27127 (defun org-return (&optional indent)
27128 "Goto next table row or insert a newline.
27129 Calls `org-table-next-row' or `newline', depending on context.
27130 See the individual commands for more information."
27131 (interactive)
27132 (cond
27133 ((bobp) (if indent (newline-and-indent) (newline)))
27134 ((and (org-at-heading-p)
27135 (looking-at
27136 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
27137 (org-show-entry)
27138 (end-of-line 1)
27139 (newline))
27140 ((org-at-table-p)
27141 (org-table-justify-field-maybe)
27142 (call-interactively 'org-table-next-row))
27143 (t (if indent (newline-and-indent) (newline)))))
27145 (defun org-return-indent ()
27146 (interactive)
27147 "Goto next table row or insert a newline and indent.
27148 Calls `org-table-next-row' or `newline-and-indent', depending on
27149 context. See the individual commands for more information."
27150 (org-return t))
27152 (defun org-ctrl-c-minus ()
27153 "Insert separator line in table or modify bullet type in list.
27154 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
27155 depending on context."
27156 (interactive)
27157 (cond
27158 ((org-at-table-p)
27159 (call-interactively 'org-table-insert-hline))
27160 ((org-on-heading-p)
27161 ;; Convert to item
27162 (save-excursion
27163 (beginning-of-line 1)
27164 (if (looking-at "\\*+ ")
27165 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
27166 ((org-in-item-p)
27167 (call-interactively 'org-cycle-list-bullet))
27168 (t (error "`C-c -' does have no function here."))))
27170 (defun org-meta-return (&optional arg)
27171 "Insert a new heading or wrap a region in a table.
27172 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
27173 See the individual commands for more information."
27174 (interactive "P")
27175 (cond
27176 ((org-at-table-p)
27177 (call-interactively 'org-table-wrap-region))
27178 (t (call-interactively 'org-insert-heading))))
27180 ;;; Menu entries
27182 ;; Define the Org-mode menus
27183 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
27184 '("Tbl"
27185 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
27186 ["Next Field" org-cycle (org-at-table-p)]
27187 ["Previous Field" org-shifttab (org-at-table-p)]
27188 ["Next Row" org-return (org-at-table-p)]
27189 "--"
27190 ["Blank Field" org-table-blank-field (org-at-table-p)]
27191 ["Edit Field" org-table-edit-field (org-at-table-p)]
27192 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
27193 "--"
27194 ("Column"
27195 ["Move Column Left" org-metaleft (org-at-table-p)]
27196 ["Move Column Right" org-metaright (org-at-table-p)]
27197 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
27198 ["Insert Column" org-shiftmetaright (org-at-table-p)])
27199 ("Row"
27200 ["Move Row Up" org-metaup (org-at-table-p)]
27201 ["Move Row Down" org-metadown (org-at-table-p)]
27202 ["Delete Row" org-shiftmetaup (org-at-table-p)]
27203 ["Insert Row" org-shiftmetadown (org-at-table-p)]
27204 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
27205 "--"
27206 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
27207 ("Rectangle"
27208 ["Copy Rectangle" org-copy-special (org-at-table-p)]
27209 ["Cut Rectangle" org-cut-special (org-at-table-p)]
27210 ["Paste Rectangle" org-paste-special (org-at-table-p)]
27211 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
27212 "--"
27213 ("Calculate"
27214 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
27215 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
27216 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
27217 "--"
27218 ["Recalculate line" org-table-recalculate (org-at-table-p)]
27219 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
27220 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
27221 "--"
27222 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
27223 "--"
27224 ["Sum Column/Rectangle" org-table-sum
27225 (or (org-at-table-p) (org-region-active-p))]
27226 ["Which Column?" org-table-current-column (org-at-table-p)])
27227 ["Debug Formulas"
27228 org-table-toggle-formula-debugger
27229 :style toggle :selected org-table-formula-debug]
27230 ["Show Col/Row Numbers"
27231 org-table-toggle-coordinate-overlays
27232 :style toggle :selected org-table-overlay-coordinates]
27233 "--"
27234 ["Create" org-table-create (and (not (org-at-table-p))
27235 org-enable-table-editor)]
27236 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
27237 ["Import from File" org-table-import (not (org-at-table-p))]
27238 ["Export to File" org-table-export (org-at-table-p)]
27239 "--"
27240 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
27242 (easy-menu-define org-org-menu org-mode-map "Org menu"
27243 '("Org"
27244 ("Show/Hide"
27245 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
27246 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
27247 ["Sparse Tree" org-occur t]
27248 ["Reveal Context" org-reveal t]
27249 ["Show All" show-all t]
27250 "--"
27251 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
27252 "--"
27253 ["New Heading" org-insert-heading t]
27254 ("Navigate Headings"
27255 ["Up" outline-up-heading t]
27256 ["Next" outline-next-visible-heading t]
27257 ["Previous" outline-previous-visible-heading t]
27258 ["Next Same Level" outline-forward-same-level t]
27259 ["Previous Same Level" outline-backward-same-level t]
27260 "--"
27261 ["Jump" org-goto t])
27262 ("Edit Structure"
27263 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
27264 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
27265 "--"
27266 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
27267 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
27268 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
27269 "--"
27270 ["Promote Heading" org-metaleft (not (org-at-table-p))]
27271 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
27272 ["Demote Heading" org-metaright (not (org-at-table-p))]
27273 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
27274 "--"
27275 ["Sort Region/Children" org-sort (not (org-at-table-p))]
27276 "--"
27277 ["Convert to odd levels" org-convert-to-odd-levels t]
27278 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
27279 ("Editing"
27280 ["Emphasis..." org-emphasize t])
27281 ("Archive"
27282 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
27283 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
27284 ; :active t :keys "C-u C-c C-x C-a"]
27285 ["Sparse trees open ARCHIVE trees"
27286 (setq org-sparse-tree-open-archived-trees
27287 (not org-sparse-tree-open-archived-trees))
27288 :style toggle :selected org-sparse-tree-open-archived-trees]
27289 ["Cycling opens ARCHIVE trees"
27290 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
27291 :style toggle :selected org-cycle-open-archived-trees]
27292 ["Agenda includes ARCHIVE trees"
27293 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
27294 :style toggle :selected (not org-agenda-skip-archived-trees)]
27295 "--"
27296 ["Move Subtree to Archive" org-advertized-archive-subtree t]
27297 ; ["Check and Move Children" (org-archive-subtree '(4))
27298 ; :active t :keys "C-u C-c C-x C-s"]
27300 "--"
27301 ("TODO Lists"
27302 ["TODO/DONE/-" org-todo t]
27303 ("Select keyword"
27304 ["Next keyword" org-shiftright (org-on-heading-p)]
27305 ["Previous keyword" org-shiftleft (org-on-heading-p)]
27306 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
27307 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
27308 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
27309 ["Show TODO Tree" org-show-todo-tree t]
27310 ["Global TODO list" org-todo-list t]
27311 "--"
27312 ["Set Priority" org-priority t]
27313 ["Priority Up" org-shiftup t]
27314 ["Priority Down" org-shiftdown t])
27315 ("TAGS and Properties"
27316 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
27317 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
27318 "--"
27319 ["Set property" 'org-set-property t]
27320 ["Column view of properties" org-columns t]
27321 ["Insert Column View DBlock" org-insert-columns-dblock t])
27322 ("Dates and Scheduling"
27323 ["Timestamp" org-time-stamp t]
27324 ["Timestamp (inactive)" org-time-stamp-inactive t]
27325 ("Change Date"
27326 ["1 Day Later" org-shiftright t]
27327 ["1 Day Earlier" org-shiftleft t]
27328 ["1 ... Later" org-shiftup t]
27329 ["1 ... Earlier" org-shiftdown t])
27330 ["Compute Time Range" org-evaluate-time-range t]
27331 ["Schedule Item" org-schedule t]
27332 ["Deadline" org-deadline t]
27333 "--"
27334 ["Custom time format" org-toggle-time-stamp-overlays
27335 :style radio :selected org-display-custom-times]
27336 "--"
27337 ["Goto Calendar" org-goto-calendar t]
27338 ["Date from Calendar" org-date-from-calendar t])
27339 ("Logging work"
27340 ["Clock in" org-clock-in t]
27341 ["Clock out" org-clock-out t]
27342 ["Clock cancel" org-clock-cancel t]
27343 ["Goto running clock" org-clock-goto t]
27344 ["Display times" org-clock-display t]
27345 ["Create clock table" org-clock-report t]
27346 "--"
27347 ["Record DONE time"
27348 (progn (setq org-log-done (not org-log-done))
27349 (message "Switching to %s will %s record a timestamp"
27350 (car org-done-keywords)
27351 (if org-log-done "automatically" "not")))
27352 :style toggle :selected org-log-done])
27353 "--"
27354 ["Agenda Command..." org-agenda t]
27355 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
27356 ("File List for Agenda")
27357 ("Special views current file"
27358 ["TODO Tree" org-show-todo-tree t]
27359 ["Check Deadlines" org-check-deadlines t]
27360 ["Timeline" org-timeline t]
27361 ["Tags Tree" org-tags-sparse-tree t])
27362 "--"
27363 ("Hyperlinks"
27364 ["Store Link (Global)" org-store-link t]
27365 ["Insert Link" org-insert-link t]
27366 ["Follow Link" org-open-at-point t]
27367 "--"
27368 ["Next link" org-next-link t]
27369 ["Previous link" org-previous-link t]
27370 "--"
27371 ["Descriptive Links"
27372 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
27373 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
27374 ["Literal Links"
27375 (progn
27376 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
27377 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
27378 "--"
27379 ["Export/Publish..." org-export t]
27380 ("LaTeX"
27381 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
27382 :selected org-cdlatex-mode]
27383 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
27384 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
27385 ["Modify math symbol" org-cdlatex-math-modify
27386 (org-inside-LaTeX-fragment-p)]
27387 ["Export LaTeX fragments as images"
27388 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
27389 :style toggle :selected org-export-with-LaTeX-fragments])
27390 "--"
27391 ("Documentation"
27392 ["Show Version" org-version t]
27393 ["Info Documentation" org-info t])
27394 ("Customize"
27395 ["Browse Org Group" org-customize t]
27396 "--"
27397 ["Expand This Menu" org-create-customize-menu
27398 (fboundp 'customize-menu-create)])
27399 "--"
27400 ["Refresh setup" org-mode-restart t]
27403 (defun org-info (&optional node)
27404 "Read documentation for Org-mode in the info system.
27405 With optional NODE, go directly to that node."
27406 (interactive)
27407 (require 'info)
27408 (Info-goto-node (format "(org)%s" (or node ""))))
27410 (defun org-install-agenda-files-menu ()
27411 (let ((bl (buffer-list)))
27412 (save-excursion
27413 (while bl
27414 (set-buffer (pop bl))
27415 (if (org-mode-p) (setq bl nil)))
27416 (when (org-mode-p)
27417 (easy-menu-change
27418 '("Org") "File List for Agenda"
27419 (append
27420 (list
27421 ["Edit File List" (org-edit-agenda-file-list) t]
27422 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
27423 ["Remove Current File from List" org-remove-file t]
27424 ["Cycle through agenda files" org-cycle-agenda-files t]
27425 ["Occur in all agenda files" org-occur-in-agenda-files t]
27426 "--")
27427 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
27429 ;;;; Documentation
27431 (defun org-customize ()
27432 "Call the customize function with org as argument."
27433 (interactive)
27434 (customize-browse 'org))
27436 (defun org-create-customize-menu ()
27437 "Create a full customization menu for Org-mode, insert it into the menu."
27438 (interactive)
27439 (if (fboundp 'customize-menu-create)
27440 (progn
27441 (easy-menu-change
27442 '("Org") "Customize"
27443 `(["Browse Org group" org-customize t]
27444 "--"
27445 ,(customize-menu-create 'org)
27446 ["Set" Custom-set t]
27447 ["Save" Custom-save t]
27448 ["Reset to Current" Custom-reset-current t]
27449 ["Reset to Saved" Custom-reset-saved t]
27450 ["Reset to Standard Settings" Custom-reset-standard t]))
27451 (message "\"Org\"-menu now contains full customization menu"))
27452 (error "Cannot expand menu (outdated version of cus-edit.el)")))
27454 ;;;; Miscellaneous stuff
27457 ;;; Generally useful functions
27459 (defun org-context ()
27460 "Return a list of contexts of the current cursor position.
27461 If several contexts apply, all are returned.
27462 Each context entry is a list with a symbol naming the context, and
27463 two positions indicating start and end of the context. Possible
27464 contexts are:
27466 :headline anywhere in a headline
27467 :headline-stars on the leading stars in a headline
27468 :todo-keyword on a TODO keyword (including DONE) in a headline
27469 :tags on the TAGS in a headline
27470 :priority on the priority cookie in a headline
27471 :item on the first line of a plain list item
27472 :item-bullet on the bullet/number of a plain list item
27473 :checkbox on the checkbox in a plain list item
27474 :table in an org-mode table
27475 :table-special on a special filed in a table
27476 :table-table in a table.el table
27477 :link on a hyperlink
27478 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
27479 :target on a <<target>>
27480 :radio-target on a <<<radio-target>>>
27481 :latex-fragment on a LaTeX fragment
27482 :latex-preview on a LaTeX fragment with overlayed preview image
27484 This function expects the position to be visible because it uses font-lock
27485 faces as a help to recognize the following contexts: :table-special, :link,
27486 and :keyword."
27487 (let* ((f (get-text-property (point) 'face))
27488 (faces (if (listp f) f (list f)))
27489 (p (point)) clist o)
27490 ;; First the large context
27491 (cond
27492 ((org-on-heading-p t)
27493 (push (list :headline (point-at-bol) (point-at-eol)) clist)
27494 (when (progn
27495 (beginning-of-line 1)
27496 (looking-at org-todo-line-tags-regexp))
27497 (push (org-point-in-group p 1 :headline-stars) clist)
27498 (push (org-point-in-group p 2 :todo-keyword) clist)
27499 (push (org-point-in-group p 4 :tags) clist))
27500 (goto-char p)
27501 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
27502 (if (looking-at "\\[#[A-Z0-9]\\]")
27503 (push (org-point-in-group p 0 :priority) clist)))
27505 ((org-at-item-p)
27506 (push (org-point-in-group p 2 :item-bullet) clist)
27507 (push (list :item (point-at-bol)
27508 (save-excursion (org-end-of-item) (point)))
27509 clist)
27510 (and (org-at-item-checkbox-p)
27511 (push (org-point-in-group p 0 :checkbox) clist)))
27513 ((org-at-table-p)
27514 (push (list :table (org-table-begin) (org-table-end)) clist)
27515 (if (memq 'org-formula faces)
27516 (push (list :table-special
27517 (previous-single-property-change p 'face)
27518 (next-single-property-change p 'face)) clist)))
27519 ((org-at-table-p 'any)
27520 (push (list :table-table) clist)))
27521 (goto-char p)
27523 ;; Now the small context
27524 (cond
27525 ((org-at-timestamp-p)
27526 (push (org-point-in-group p 0 :timestamp) clist))
27527 ((memq 'org-link faces)
27528 (push (list :link
27529 (previous-single-property-change p 'face)
27530 (next-single-property-change p 'face)) clist))
27531 ((memq 'org-special-keyword faces)
27532 (push (list :keyword
27533 (previous-single-property-change p 'face)
27534 (next-single-property-change p 'face)) clist))
27535 ((org-on-target-p)
27536 (push (org-point-in-group p 0 :target) clist)
27537 (goto-char (1- (match-beginning 0)))
27538 (if (looking-at org-radio-target-regexp)
27539 (push (org-point-in-group p 0 :radio-target) clist))
27540 (goto-char p))
27541 ((setq o (car (delq nil
27542 (mapcar
27543 (lambda (x)
27544 (if (memq x org-latex-fragment-image-overlays) x))
27545 (org-overlays-at (point))))))
27546 (push (list :latex-fragment
27547 (org-overlay-start o) (org-overlay-end o)) clist)
27548 (push (list :latex-preview
27549 (org-overlay-start o) (org-overlay-end o)) clist))
27550 ((org-inside-LaTeX-fragment-p)
27551 ;; FIXME: positions wrong.
27552 (push (list :latex-fragment (point) (point)) clist)))
27554 (setq clist (nreverse (delq nil clist)))
27555 clist))
27557 ;; FIXME: Compare with at-regexp-p Do we need both?
27558 (defun org-in-regexp (re &optional nlines visually)
27559 "Check if point is inside a match of regexp.
27560 Normally only the current line is checked, but you can include NLINES extra
27561 lines both before and after point into the search.
27562 If VISUALLY is set, require that the cursor is not after the match but
27563 really on, so that the block visually is on the match."
27564 (catch 'exit
27565 (let ((pos (point))
27566 (eol (point-at-eol (+ 1 (or nlines 0))))
27567 (inc (if visually 1 0)))
27568 (save-excursion
27569 (beginning-of-line (- 1 (or nlines 0)))
27570 (while (re-search-forward re eol t)
27571 (if (and (<= (match-beginning 0) pos)
27572 (>= (+ inc (match-end 0)) pos))
27573 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
27575 (defun org-at-regexp-p (regexp)
27576 "Is point inside a match of REGEXP in the current line?"
27577 (catch 'exit
27578 (save-excursion
27579 (let ((pos (point)) (end (point-at-eol)))
27580 (beginning-of-line 1)
27581 (while (re-search-forward regexp end t)
27582 (if (and (<= (match-beginning 0) pos)
27583 (>= (match-end 0) pos))
27584 (throw 'exit t)))
27585 nil))))
27587 (defun org-occur-in-agenda-files (regexp &optional nlines)
27588 "Call `multi-occur' with buffers for all agenda files."
27589 (interactive "sOrg-files matching: \np")
27590 (let* ((files (org-agenda-files))
27591 (tnames (mapcar 'file-truename files))
27592 (extra org-agenda-multi-occur-extra-files)
27594 (while (setq f (pop extra))
27595 (unless (member (file-truename f) tnames)
27596 (add-to-list 'files f 'append)
27597 (add-to-list 'tnames (file-truename f) 'append)))
27598 (multi-occur
27599 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
27600 regexp)))
27602 (if (boundp 'occur-mode-find-occurrence-hook)
27603 ;; Emacs 23
27604 (add-hook 'occur-mode-find-occurrence-hook
27605 (lambda ()
27606 (when (org-mode-p)
27607 (org-reveal))))
27608 ;; Emacs 22
27609 (defadvice occur-mode-goto-occurrence
27610 (after org-occur-reveal activate)
27611 (and (org-mode-p) (org-reveal)))
27612 (defadvice occur-mode-goto-occurrence-other-window
27613 (after org-occur-reveal activate)
27614 (and (org-mode-p) (org-reveal)))
27615 (defadvice occur-mode-display-occurrence
27616 (after org-occur-reveal activate)
27617 (when (org-mode-p)
27618 (let ((pos (occur-mode-find-occurrence)))
27619 (with-current-buffer (marker-buffer pos)
27620 (save-excursion
27621 (goto-char pos)
27622 (org-reveal)))))))
27624 (defun org-uniquify (list)
27625 "Remove duplicate elements from LIST."
27626 (let (res)
27627 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
27628 res))
27630 (defun org-delete-all (elts list)
27631 "Remove all elements in ELTS from LIST."
27632 (while elts
27633 (setq list (delete (pop elts) list)))
27634 list)
27636 (defun org-back-over-empty-lines ()
27637 "Move backwards over witespace, to the beginning of the first empty line.
27638 Returns the number o empty lines passed."
27639 (let ((pos (point)))
27640 (skip-chars-backward " \t\n\r")
27641 (beginning-of-line 2)
27642 (goto-char (min (point) pos))
27643 (count-lines (point) pos)))
27645 (defun org-skip-whitespace ()
27646 (skip-chars-forward " \t\n\r"))
27648 (defun org-point-in-group (point group &optional context)
27649 "Check if POINT is in match-group GROUP.
27650 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
27651 match. If the match group does ot exist or point is not inside it,
27652 return nil."
27653 (and (match-beginning group)
27654 (>= point (match-beginning group))
27655 (<= point (match-end group))
27656 (if context
27657 (list context (match-beginning group) (match-end group))
27658 t)))
27660 (defun org-switch-to-buffer-other-window (&rest args)
27661 "Switch to buffer in a second window on the current frame.
27662 In particular, do not allow pop-up frames."
27663 (let (pop-up-frames special-display-buffer-names special-display-regexps
27664 special-display-function)
27665 (apply 'switch-to-buffer-other-window args)))
27667 (defun org-combine-plists (&rest plists)
27668 "Create a single property list from all plists in PLISTS.
27669 The process starts by copying the first list, and then setting properties
27670 from the other lists. Settings in the last list are the most significant
27671 ones and overrule settings in the other lists."
27672 (let ((rtn (copy-sequence (pop plists)))
27673 p v ls)
27674 (while plists
27675 (setq ls (pop plists))
27676 (while ls
27677 (setq p (pop ls) v (pop ls))
27678 (setq rtn (plist-put rtn p v))))
27679 rtn))
27681 (defun org-move-line-down (arg)
27682 "Move the current line down. With prefix argument, move it past ARG lines."
27683 (interactive "p")
27684 (let ((col (current-column))
27685 beg end pos)
27686 (beginning-of-line 1) (setq beg (point))
27687 (beginning-of-line 2) (setq end (point))
27688 (beginning-of-line (+ 1 arg))
27689 (setq pos (move-marker (make-marker) (point)))
27690 (insert (delete-and-extract-region beg end))
27691 (goto-char pos)
27692 (move-to-column col)))
27694 (defun org-move-line-up (arg)
27695 "Move the current line up. With prefix argument, move it past ARG lines."
27696 (interactive "p")
27697 (let ((col (current-column))
27698 beg end pos)
27699 (beginning-of-line 1) (setq beg (point))
27700 (beginning-of-line 2) (setq end (point))
27701 (beginning-of-line (- arg))
27702 (setq pos (move-marker (make-marker) (point)))
27703 (insert (delete-and-extract-region beg end))
27704 (goto-char pos)
27705 (move-to-column col)))
27707 (defun org-replace-escapes (string table)
27708 "Replace %-escapes in STRING with values in TABLE.
27709 TABLE is an association list with keys like \"%a\" and string values.
27710 The sequences in STRING may contain normal field width and padding information,
27711 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
27712 so values can contain further %-escapes if they are define later in TABLE."
27713 (let ((case-fold-search nil)
27714 e re rpl)
27715 (while (setq e (pop table))
27716 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
27717 (while (string-match re string)
27718 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
27719 (cdr e)))
27720 (setq string (replace-match rpl t t string))))
27721 string))
27724 (defun org-sublist (list start end)
27725 "Return a section of LIST, from START to END.
27726 Counting starts at 1."
27727 (let (rtn (c start))
27728 (setq list (nthcdr (1- start) list))
27729 (while (and list (<= c end))
27730 (push (pop list) rtn)
27731 (setq c (1+ c)))
27732 (nreverse rtn)))
27734 (defun org-find-base-buffer-visiting (file)
27735 "Like `find-buffer-visiting' but alway return the base buffer and
27736 not an indirect buffer"
27737 (let ((buf (find-buffer-visiting file)))
27738 (if buf
27739 (or (buffer-base-buffer buf) buf)
27740 nil)))
27742 (defun org-image-file-name-regexp ()
27743 "Return regexp matching the file names of images."
27744 (if (fboundp 'image-file-name-regexp)
27745 (image-file-name-regexp)
27746 (let ((image-file-name-extensions
27747 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
27748 "xbm" "xpm" "pbm" "pgm" "ppm")))
27749 (concat "\\."
27750 (regexp-opt (nconc (mapcar 'upcase
27751 image-file-name-extensions)
27752 image-file-name-extensions)
27754 "\\'"))))
27756 (defun org-file-image-p (file)
27757 "Return non-nil if FILE is an image."
27758 (save-match-data
27759 (string-match (org-image-file-name-regexp) file)))
27761 ;;; Paragraph filling stuff.
27762 ;; We want this to be just right, so use the full arsenal.
27764 (defun org-indent-line-function ()
27765 "Indent line like previous, but further if previous was headline or item."
27766 (interactive)
27767 (let* ((pos (point))
27768 (itemp (org-at-item-p))
27769 column bpos bcol tpos tcol bullet btype bullet-type)
27770 ;; Find the previous relevant line
27771 (beginning-of-line 1)
27772 (cond
27773 ((looking-at "#") (setq column 0))
27774 ((looking-at "\\*+ ") (setq column 0))
27776 (beginning-of-line 0)
27777 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
27778 (beginning-of-line 0))
27779 (cond
27780 ((looking-at "\\*+[ \t]+")
27781 (goto-char (match-end 0))
27782 (setq column (current-column)))
27783 ((org-in-item-p)
27784 (org-beginning-of-item)
27785 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
27786 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
27787 (setq bpos (match-beginning 1) tpos (match-end 0)
27788 bcol (progn (goto-char bpos) (current-column))
27789 tcol (progn (goto-char tpos) (current-column))
27790 bullet (match-string 1)
27791 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
27792 (if (not itemp)
27793 (setq column tcol)
27794 (goto-char pos)
27795 (beginning-of-line 1)
27796 (if (looking-at "\\S-")
27797 (progn
27798 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
27799 (setq bullet (match-string 1)
27800 btype (if (string-match "[0-9]" bullet) "n" bullet))
27801 (setq column (if (equal btype bullet-type) bcol tcol)))
27802 (setq column (org-get-indentation)))))
27803 (t (setq column (org-get-indentation))))))
27804 (goto-char pos)
27805 (if (<= (current-column) (current-indentation))
27806 (indent-line-to column)
27807 (save-excursion (indent-line-to column)))
27808 (setq column (current-column))
27809 (beginning-of-line 1)
27810 (if (looking-at
27811 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
27812 (replace-match (concat "\\1" (format org-property-format
27813 (match-string 2) (match-string 3)))
27814 t nil))
27815 (move-to-column column)))
27817 (defun org-set-autofill-regexps ()
27818 (interactive)
27819 ;; In the paragraph separator we include headlines, because filling
27820 ;; text in a line directly attached to a headline would otherwise
27821 ;; fill the headline as well.
27822 (org-set-local 'comment-start-skip "^#+[ \t]*")
27823 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
27824 ;; The paragraph starter includes hand-formatted lists.
27825 (org-set-local 'paragraph-start
27826 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
27827 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
27828 ;; But only if the user has not turned off tables or fixed-width regions
27829 (org-set-local
27830 'auto-fill-inhibit-regexp
27831 (concat "\\*+ \\|#\\+"
27832 "\\|[ \t]*" org-keyword-time-regexp
27833 (if (or org-enable-table-editor org-enable-fixed-width-editor)
27834 (concat
27835 "\\|[ \t]*["
27836 (if org-enable-table-editor "|" "")
27837 (if org-enable-fixed-width-editor ":" "")
27838 "]"))))
27839 ;; We use our own fill-paragraph function, to make sure that tables
27840 ;; and fixed-width regions are not wrapped. That function will pass
27841 ;; through to `fill-paragraph' when appropriate.
27842 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
27843 ; Adaptive filling: To get full control, first make sure that
27844 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
27845 (org-set-local 'adaptive-fill-regexp "\000")
27846 (org-set-local 'adaptive-fill-function
27847 'org-adaptive-fill-function)
27848 (org-set-local
27849 'align-mode-rules-list
27850 '((org-in-buffer-settings
27851 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
27852 (modes . '(org-mode))))))
27854 (defun org-fill-paragraph (&optional justify)
27855 "Re-align a table, pass through to fill-paragraph if no table."
27856 (let ((table-p (org-at-table-p))
27857 (table.el-p (org-at-table.el-p)))
27858 (cond ((and (equal (char-after (point-at-bol)) ?*)
27859 (save-excursion (goto-char (point-at-bol))
27860 (looking-at outline-regexp)))
27861 t) ; skip headlines
27862 (table.el-p t) ; skip table.el tables
27863 (table-p (org-table-align) t) ; align org-mode tables
27864 (t nil)))) ; call paragraph-fill
27866 ;; For reference, this is the default value of adaptive-fill-regexp
27867 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
27869 (defun org-adaptive-fill-function ()
27870 "Return a fill prefix for org-mode files.
27871 In particular, this makes sure hanging paragraphs for hand-formatted lists
27872 work correctly."
27873 (cond ((looking-at "#[ \t]+")
27874 (match-string 0))
27875 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
27876 (save-excursion
27877 (goto-char (match-end 0))
27878 (make-string (current-column) ?\ )))
27879 (t nil)))
27881 ;;;; Functions extending outline functionality
27884 (defun org-beginning-of-line (&optional arg)
27885 "Go to the beginning of the current line. If that is invisible, continue
27886 to a visible line beginning. This makes the function of C-a more intuitive.
27887 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27888 first attempt, and only move to after the tags when the cursor is already
27889 beyond the end of the headline."
27890 (interactive "P")
27891 (let ((pos (point)))
27892 (beginning-of-line 1)
27893 (if (bobp)
27895 (backward-char 1)
27896 (if (org-invisible-p)
27897 (while (and (not (bobp)) (org-invisible-p))
27898 (backward-char 1)
27899 (beginning-of-line 1))
27900 (forward-char 1)))
27901 (when org-special-ctrl-a/e
27902 (cond
27903 ((and (looking-at org-todo-line-regexp)
27904 (= (char-after (match-end 1)) ?\ ))
27905 (goto-char
27906 (if (eq org-special-ctrl-a/e t)
27907 (cond ((> pos (match-beginning 3)) (match-beginning 3))
27908 ((= pos (point)) (match-beginning 3))
27909 (t (point)))
27910 (cond ((> pos (point)) (point))
27911 ((not (eq last-command this-command)) (point))
27912 (t (match-beginning 3))))))
27913 ((org-at-item-p)
27914 (goto-char
27915 (if (eq org-special-ctrl-a/e t)
27916 (cond ((> pos (match-end 4)) (match-end 4))
27917 ((= pos (point)) (match-end 4))
27918 (t (point)))
27919 (cond ((> pos (point)) (point))
27920 ((not (eq last-command this-command)) (point))
27921 (t (match-end 4))))))))))
27923 (defun org-end-of-line (&optional arg)
27924 "Go to the end of the line.
27925 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27926 first attempt, and only move to after the tags when the cursor is already
27927 beyond the end of the headline."
27928 (interactive "P")
27929 (if (or (not org-special-ctrl-a/e)
27930 (not (org-on-heading-p)))
27931 (end-of-line arg)
27932 (let ((pos (point)))
27933 (beginning-of-line 1)
27934 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
27935 (if (eq org-special-ctrl-a/e t)
27936 (if (or (< pos (match-beginning 1))
27937 (= pos (match-end 0)))
27938 (goto-char (match-beginning 1))
27939 (goto-char (match-end 0)))
27940 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
27941 (goto-char (match-end 0))
27942 (goto-char (match-beginning 1))))
27943 (end-of-line arg)))))
27945 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
27946 (define-key org-mode-map "\C-e" 'org-end-of-line)
27948 (defun org-kill-line (&optional arg)
27949 "Kill line, to tags or end of line."
27950 (interactive "P")
27951 (cond
27952 ((or (not org-special-ctrl-k)
27953 (bolp)
27954 (not (org-on-heading-p)))
27955 (call-interactively 'kill-line))
27956 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
27957 (kill-region (point) (match-beginning 1))
27958 (org-set-tags nil t))
27959 (t (kill-region (point) (point-at-eol)))))
27961 (define-key org-mode-map "\C-k" 'org-kill-line)
27963 (defun org-invisible-p ()
27964 "Check if point is at a character currently not visible."
27965 ;; Early versions of noutline don't have `outline-invisible-p'.
27966 (if (fboundp 'outline-invisible-p)
27967 (outline-invisible-p)
27968 (get-char-property (point) 'invisible)))
27970 (defun org-invisible-p2 ()
27971 "Check if point is at a character currently not visible."
27972 (save-excursion
27973 (if (and (eolp) (not (bobp))) (backward-char 1))
27974 ;; Early versions of noutline don't have `outline-invisible-p'.
27975 (if (fboundp 'outline-invisible-p)
27976 (outline-invisible-p)
27977 (get-char-property (point) 'invisible))))
27979 (defalias 'org-back-to-heading 'outline-back-to-heading)
27980 (defalias 'org-on-heading-p 'outline-on-heading-p)
27981 (defalias 'org-at-heading-p 'outline-on-heading-p)
27982 (defun org-at-heading-or-item-p ()
27983 (or (org-on-heading-p) (org-at-item-p)))
27985 (defun org-on-target-p ()
27986 (or (org-in-regexp org-radio-target-regexp)
27987 (org-in-regexp org-target-regexp)))
27989 (defun org-up-heading-all (arg)
27990 "Move to the heading line of which the present line is a subheading.
27991 This function considers both visible and invisible heading lines.
27992 With argument, move up ARG levels."
27993 (if (fboundp 'outline-up-heading-all)
27994 (outline-up-heading-all arg) ; emacs 21 version of outline.el
27995 (outline-up-heading arg t))) ; emacs 22 version of outline.el
27997 (defun org-up-heading-safe ()
27998 "Move to the heading line of which the present line is a subheading.
27999 This version will not throw an error. It will return the level of the
28000 headline found, or nil if no higher level is found."
28001 (let ((pos (point)) start-level level
28002 (re (concat "^" outline-regexp)))
28003 (catch 'exit
28004 (outline-back-to-heading t)
28005 (setq start-level (funcall outline-level))
28006 (if (equal start-level 1) (throw 'exit nil))
28007 (while (re-search-backward re nil t)
28008 (setq level (funcall outline-level))
28009 (if (< level start-level) (throw 'exit level)))
28010 nil)))
28012 (defun org-first-sibling-p ()
28013 "Is this heading the first child of its parents?"
28014 (interactive)
28015 (let ((re (concat "^" outline-regexp))
28016 level l)
28017 (unless (org-at-heading-p t)
28018 (error "Not at a heading"))
28019 (setq level (funcall outline-level))
28020 (save-excursion
28021 (if (not (re-search-backward re nil t))
28023 (setq l (funcall outline-level))
28024 (< l level)))))
28026 (defun org-goto-sibling (&optional previous)
28027 "Goto the next sibling, even if it is invisible.
28028 When PREVIOUS is set, go to the previous sibling instead. Returns t
28029 when a sibling was found. When none is found, return nil and don't
28030 move point."
28031 (let ((fun (if previous 're-search-backward 're-search-forward))
28032 (pos (point))
28033 (re (concat "^" outline-regexp))
28034 level l)
28035 (when (condition-case nil (org-back-to-heading t) (error nil))
28036 (setq level (funcall outline-level))
28037 (catch 'exit
28038 (or previous (forward-char 1))
28039 (while (funcall fun re nil t)
28040 (setq l (funcall outline-level))
28041 (when (< l level) (goto-char pos) (throw 'exit nil))
28042 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
28043 (goto-char pos)
28044 nil))))
28046 (defun org-show-siblings ()
28047 "Show all siblings of the current headline."
28048 (save-excursion
28049 (while (org-goto-sibling) (org-flag-heading nil)))
28050 (save-excursion
28051 (while (org-goto-sibling 'previous)
28052 (org-flag-heading nil))))
28054 (defun org-show-hidden-entry ()
28055 "Show an entry where even the heading is hidden."
28056 (save-excursion
28057 (org-show-entry)))
28059 (defun org-flag-heading (flag &optional entry)
28060 "Flag the current heading. FLAG non-nil means make invisible.
28061 When ENTRY is non-nil, show the entire entry."
28062 (save-excursion
28063 (org-back-to-heading t)
28064 ;; Check if we should show the entire entry
28065 (if entry
28066 (progn
28067 (org-show-entry)
28068 (save-excursion
28069 (and (outline-next-heading)
28070 (org-flag-heading nil))))
28071 (outline-flag-region (max (point-min) (1- (point)))
28072 (save-excursion (outline-end-of-heading) (point))
28073 flag))))
28075 (defun org-end-of-subtree (&optional invisible-OK to-heading)
28076 ;; This is an exact copy of the original function, but it uses
28077 ;; `org-back-to-heading', to make it work also in invisible
28078 ;; trees. And is uses an invisible-OK argument.
28079 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
28080 (org-back-to-heading invisible-OK)
28081 (let ((first t)
28082 (level (funcall outline-level)))
28083 (while (and (not (eobp))
28084 (or first (> (funcall outline-level) level)))
28085 (setq first nil)
28086 (outline-next-heading))
28087 (unless to-heading
28088 (if (memq (preceding-char) '(?\n ?\^M))
28089 (progn
28090 ;; Go to end of line before heading
28091 (forward-char -1)
28092 (if (memq (preceding-char) '(?\n ?\^M))
28093 ;; leave blank line before heading
28094 (forward-char -1))))))
28095 (point))
28097 (defun org-show-subtree ()
28098 "Show everything after this heading at deeper levels."
28099 (outline-flag-region
28100 (point)
28101 (save-excursion
28102 (outline-end-of-subtree) (outline-next-heading) (point))
28103 nil))
28105 (defun org-show-entry ()
28106 "Show the body directly following this heading.
28107 Show the heading too, if it is currently invisible."
28108 (interactive)
28109 (save-excursion
28110 (condition-case nil
28111 (progn
28112 (org-back-to-heading t)
28113 (outline-flag-region
28114 (max (point-min) (1- (point)))
28115 (save-excursion
28116 (re-search-forward
28117 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
28118 (or (match-beginning 1) (point-max)))
28119 nil))
28120 (error nil))))
28122 (defun org-make-options-regexp (kwds)
28123 "Make a regular expression for keyword lines."
28124 (concat
28126 "#?[ \t]*\\+\\("
28127 (mapconcat 'regexp-quote kwds "\\|")
28128 "\\):[ \t]*"
28129 "\\(.+\\)"))
28131 ;; Make isearch reveal the necessary context
28132 (defun org-isearch-end ()
28133 "Reveal context after isearch exits."
28134 (when isearch-success ; only if search was successful
28135 (if (featurep 'xemacs)
28136 ;; Under XEmacs, the hook is run in the correct place,
28137 ;; we directly show the context.
28138 (org-show-context 'isearch)
28139 ;; In Emacs the hook runs *before* restoring the overlays.
28140 ;; So we have to use a one-time post-command-hook to do this.
28141 ;; (Emacs 22 has a special variable, see function `org-mode')
28142 (unless (and (boundp 'isearch-mode-end-hook-quit)
28143 isearch-mode-end-hook-quit)
28144 ;; Only when the isearch was not quitted.
28145 (org-add-hook 'post-command-hook 'org-isearch-post-command
28146 'append 'local)))))
28148 (defun org-isearch-post-command ()
28149 "Remove self from hook, and show context."
28150 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
28151 (org-show-context 'isearch))
28154 ;;;; Integration with and fixes for other packages
28156 ;;; Imenu support
28158 (defvar org-imenu-markers nil
28159 "All markers currently used by Imenu.")
28160 (make-variable-buffer-local 'org-imenu-markers)
28162 (defun org-imenu-new-marker (&optional pos)
28163 "Return a new marker for use by Imenu, and remember the marker."
28164 (let ((m (make-marker)))
28165 (move-marker m (or pos (point)))
28166 (push m org-imenu-markers)
28169 (defun org-imenu-get-tree ()
28170 "Produce the index for Imenu."
28171 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
28172 (setq org-imenu-markers nil)
28173 (let* ((n org-imenu-depth)
28174 (re (concat "^" outline-regexp))
28175 (subs (make-vector (1+ n) nil))
28176 (last-level 0)
28177 m tree level head)
28178 (save-excursion
28179 (save-restriction
28180 (widen)
28181 (goto-char (point-max))
28182 (while (re-search-backward re nil t)
28183 (setq level (org-reduced-level (funcall outline-level)))
28184 (when (<= level n)
28185 (looking-at org-complex-heading-regexp)
28186 (setq head (org-match-string-no-properties 4)
28187 m (org-imenu-new-marker))
28188 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
28189 (if (>= level last-level)
28190 (push (cons head m) (aref subs level))
28191 (push (cons head (aref subs (1+ level))) (aref subs level))
28192 (loop for i from (1+ level) to n do (aset subs i nil)))
28193 (setq last-level level)))))
28194 (aref subs 1)))
28196 (eval-after-load "imenu"
28197 '(progn
28198 (add-hook 'imenu-after-jump-hook
28199 (lambda () (org-show-context 'org-goto)))))
28201 ;; Speedbar support
28203 (defun org-speedbar-set-agenda-restriction ()
28204 "Restrict future agenda commands to the location at point in speedbar.
28205 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
28206 (interactive)
28207 (let (p m tp np dir txt w)
28208 (cond
28209 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28210 'org-imenu t))
28211 (setq m (get-text-property p 'org-imenu-marker))
28212 (save-excursion
28213 (save-restriction
28214 (set-buffer (marker-buffer m))
28215 (goto-char m)
28216 (org-agenda-set-restriction-lock 'subtree))))
28217 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28218 'speedbar-function 'speedbar-find-file))
28219 (setq tp (previous-single-property-change
28220 (1+ p) 'speedbar-function)
28221 np (next-single-property-change
28222 tp 'speedbar-function)
28223 dir (speedbar-line-directory)
28224 txt (buffer-substring-no-properties (or tp (point-min))
28225 (or np (point-max))))
28226 (save-excursion
28227 (save-restriction
28228 (set-buffer (find-file-noselect
28229 (let ((default-directory dir))
28230 (expand-file-name txt))))
28231 (unless (org-mode-p)
28232 (error "Cannot restrict to non-Org-mode file"))
28233 (org-agenda-set-restriction-lock 'file))))
28234 (t (error "Don't know how to restrict Org-mode's agenda")))
28235 (org-move-overlay org-speedbar-restriction-lock-overlay
28236 (point-at-bol) (point-at-eol))
28237 (setq current-prefix-arg nil)
28238 (org-agenda-maybe-redo)))
28240 (eval-after-load "speedbar"
28241 '(progn
28242 (speedbar-add-supported-extension ".org")
28243 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
28244 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
28245 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
28246 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
28247 (add-hook 'speedbar-visiting-tag-hook
28248 (lambda () (org-show-context 'org-goto)))))
28251 ;;; Fixes and Hacks
28253 ;; Make flyspell not check words in links, to not mess up our keymap
28254 (defun org-mode-flyspell-verify ()
28255 "Don't let flyspell put overlays at active buttons."
28256 (not (get-text-property (point) 'keymap)))
28258 ;; Make `bookmark-jump' show the jump location if it was hidden.
28259 (eval-after-load "bookmark"
28260 '(if (boundp 'bookmark-after-jump-hook)
28261 ;; We can use the hook
28262 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
28263 ;; Hook not available, use advice
28264 (defadvice bookmark-jump (after org-make-visible activate)
28265 "Make the position visible."
28266 (org-bookmark-jump-unhide))))
28268 (defun org-bookmark-jump-unhide ()
28269 "Unhide the current position, to show the bookmark location."
28270 (and (org-mode-p)
28271 (or (org-invisible-p)
28272 (save-excursion (goto-char (max (point-min) (1- (point))))
28273 (org-invisible-p)))
28274 (org-show-context 'bookmark-jump)))
28276 ;; Fix a bug in htmlize where there are text properties (face nil)
28277 (eval-after-load "htmlize"
28278 '(progn
28279 (defadvice htmlize-faces-in-buffer (after org-no-nil-faces activate)
28280 "Make sure there are no nil faces"
28281 (setq ad-return-value (delq nil ad-return-value)))))
28283 ;; Make session.el ignore our circular variable
28284 (eval-after-load "session"
28285 '(add-to-list 'session-globals-exclude 'org-mark-ring))
28287 ;;;; Experimental code
28289 (defun org-closed-in-range ()
28290 "Sparse tree of items closed in a certain time range.
28291 Still experimental, may disappear in the future."
28292 (interactive)
28293 ;; Get the time interval from the user.
28294 (let* ((time1 (time-to-seconds
28295 (org-read-date nil 'to-time nil "Starting date: ")))
28296 (time2 (time-to-seconds
28297 (org-read-date nil 'to-time nil "End date:")))
28298 ;; callback function
28299 (callback (lambda ()
28300 (let ((time
28301 (time-to-seconds
28302 (apply 'encode-time
28303 (org-parse-time-string
28304 (match-string 1))))))
28305 ;; check if time in interval
28306 (and (>= time time1) (<= time time2))))))
28307 ;; make tree, check each match with the callback
28308 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
28310 ;;;; Finish up
28312 (provide 'org)
28314 (run-hooks 'org-load-hook)
28316 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
28317 ;;; org.el ends here