use cooper theme -- end of git, I am trying livemesh
[srid.dotfiles.git] / emacs / external / org.el
bloba8557d355ce45c67e0e931ea2a24052943045577
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;; Version: 5.17a
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.17a"
88 "The version number of the file org.el.")
89 (defun org-version ()
90 (interactive)
91 (message "Org-mode version %s" org-version))
93 ;;; Compatibility constants
94 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
95 (defconst org-format-transports-properties-p
96 (let ((x "a"))
97 (add-text-properties 0 1 '(test t) x)
98 (get-text-property 0 'test (format "%s" x)))
99 "Does format transport text properties?")
101 (defmacro org-bound-and-true-p (var)
102 "Return the value of symbol VAR if it is bound, else nil."
103 `(and (boundp (quote ,var)) ,var))
105 (defmacro org-unmodified (&rest body)
106 "Execute body without changing buffer-modified-p."
107 `(set-buffer-modified-p
108 (prog1 (buffer-modified-p) ,@body)))
110 (defmacro org-re (s)
111 "Replace posix classes in regular expression."
112 (if (featurep 'xemacs)
113 (let ((ss s))
114 (save-match-data
115 (while (string-match "\\[:alnum:\\]" ss)
116 (setq ss (replace-match "a-zA-Z0-9" t t ss)))
117 (while (string-match "\\[:alpha:\\]" ss)
118 (setq ss (replace-match "a-zA-Z" t t ss)))
119 ss))
122 (defmacro org-preserve-lc (&rest body)
123 `(let ((_line (org-current-line))
124 (_col (current-column)))
125 (unwind-protect
126 (progn ,@body)
127 (goto-line _line)
128 (move-to-column _col))))
130 (defmacro org-without-partial-completion (&rest body)
131 `(let ((pc-mode (and (boundp 'partial-completion-mode)
132 partial-completion-mode)))
133 (unwind-protect
134 (progn
135 (if pc-mode (partial-completion-mode -1))
136 ,@body)
137 (if pc-mode (partial-completion-mode 1)))))
139 ;;; The custom variables
141 (defgroup org nil
142 "Outline-based notes management and organizer."
143 :tag "Org"
144 :group 'outlines
145 :group 'hypermedia
146 :group 'calendar)
148 ;; FIXME: Needs a separate group...
149 (defcustom org-completion-fallback-command 'hippie-expand
150 "The expansion command called by \\[org-complete] in normal context.
151 Normal means, no org-mode-specific context."
152 :group 'org
153 :type 'function)
155 (defgroup org-startup nil
156 "Options concerning startup of Org-mode."
157 :tag "Org Startup"
158 :group 'org)
160 (defcustom org-startup-folded t
161 "Non-nil means, entering Org-mode will switch to OVERVIEW.
162 This can also be configured on a per-file basis by adding one of
163 the following lines anywhere in the buffer:
165 #+STARTUP: fold
166 #+STARTUP: nofold
167 #+STARTUP: content"
168 :group 'org-startup
169 :type '(choice
170 (const :tag "nofold: show all" nil)
171 (const :tag "fold: overview" t)
172 (const :tag "content: all headlines" content)))
174 (defcustom org-startup-truncated t
175 "Non-nil means, entering Org-mode will set `truncate-lines'.
176 This is useful since some lines containing links can be very long and
177 uninteresting. Also tables look terrible when wrapped."
178 :group 'org-startup
179 :type 'boolean)
181 (defcustom org-startup-align-all-tables nil
182 "Non-nil means, align all tables when visiting a file.
183 This is useful when the column width in tables is forced with <N> cookies
184 in table fields. Such tables will look correct only after the first re-align.
185 This can also be configured on a per-file basis by adding one of
186 the following lines anywhere in the buffer:
187 #+STARTUP: align
188 #+STARTUP: noalign"
189 :group 'org-startup
190 :type 'boolean)
192 (defcustom org-insert-mode-line-in-empty-file nil
193 "Non-nil means insert the first line setting Org-mode in empty files.
194 When the function `org-mode' is called interactively in an empty file, this
195 normally means that the file name does not automatically trigger Org-mode.
196 To ensure that the file will always be in Org-mode in the future, a
197 line enforcing Org-mode will be inserted into the buffer, if this option
198 has been set."
199 :group 'org-startup
200 :type 'boolean)
202 (defcustom org-replace-disputed-keys nil
203 "Non-nil means use alternative key bindings for some keys.
204 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
205 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
206 If you want to use Org-mode together with one of these other modes,
207 or more generally if you would like to move some Org-mode commands to
208 other keys, set this variable and configure the keys with the variable
209 `org-disputed-keys'.
211 This option is only relevant at load-time of Org-mode, and must be set
212 *before* org.el is loaded. Changing it requires a restart of Emacs to
213 become effective."
214 :group 'org-startup
215 :type 'boolean)
217 (if (fboundp 'defvaralias)
218 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
220 (defcustom org-disputed-keys
221 '(([(shift up)] . [(meta p)])
222 ([(shift down)] . [(meta n)])
223 ([(shift left)] . [(meta -)])
224 ([(shift right)] . [(meta +)])
225 ([(control shift right)] . [(meta shift +)])
226 ([(control shift left)] . [(meta shift -)]))
227 "Keys for which Org-mode and other modes compete.
228 This is an alist, cars are the default keys, second element specifies
229 the alternative to use when `org-replace-disputed-keys' is t.
231 Keys can be specified in any syntax supported by `define-key'.
232 The value of this option takes effect only at Org-mode's startup,
233 therefore you'll have to restart Emacs to apply it after changing."
234 :group 'org-startup
235 :type 'alist)
237 (defun org-key (key)
238 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
239 Or return the original if not disputed."
240 (if org-replace-disputed-keys
241 (let* ((nkey (key-description key))
242 (x (org-find-if (lambda (x)
243 (equal (key-description (car x)) nkey))
244 org-disputed-keys)))
245 (if x (cdr x) key))
246 key))
248 (defun org-find-if (predicate seq)
249 (catch 'exit
250 (while seq
251 (if (funcall predicate (car seq))
252 (throw 'exit (car seq))
253 (pop seq)))))
255 (defun org-defkey (keymap key def)
256 "Define a key, possibly translated, as returned by `org-key'."
257 (define-key keymap (org-key key) def))
259 (defcustom org-ellipsis nil
260 "The ellipsis to use in the Org-mode outline.
261 When nil, just use the standard three dots. When a string, use that instead,
262 When a face, use the standart 3 dots, but with the specified face.
263 The change affects only Org-mode (which will then use its own display table).
264 Changing this requires executing `M-x org-mode' in a buffer to become
265 effective."
266 :group 'org-startup
267 :type '(choice (const :tag "Default" nil)
268 (face :tag "Face" :value org-warning)
269 (string :tag "String" :value "...#")))
271 (defvar org-display-table nil
272 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
274 (defgroup org-keywords nil
275 "Keywords in Org-mode."
276 :tag "Org Keywords"
277 :group 'org)
279 (defcustom org-deadline-string "DEADLINE:"
280 "String to mark deadline entries.
281 A deadline is this string, followed by a time stamp. Should be a word,
282 terminated by a colon. You can insert a schedule keyword and
283 a timestamp with \\[org-deadline].
284 Changes become only effective after restarting Emacs."
285 :group 'org-keywords
286 :type 'string)
288 (defcustom org-scheduled-string "SCHEDULED:"
289 "String to mark scheduled TODO entries.
290 A schedule is this string, followed by a time stamp. Should be a word,
291 terminated by a colon. You can insert a schedule keyword and
292 a timestamp with \\[org-schedule].
293 Changes become only effective after restarting Emacs."
294 :group 'org-keywords
295 :type 'string)
297 (defcustom org-closed-string "CLOSED:"
298 "String used as the prefix for timestamps logging closing a TODO entry."
299 :group 'org-keywords
300 :type 'string)
302 (defcustom org-clock-string "CLOCK:"
303 "String used as prefix for timestamps clocking work hours on an item."
304 :group 'org-keywords
305 :type 'string)
307 (defcustom org-comment-string "COMMENT"
308 "Entries starting with this keyword will never be exported.
309 An entry can be toggled between COMMENT and normal with
310 \\[org-toggle-comment].
311 Changes become only effective after restarting Emacs."
312 :group 'org-keywords
313 :type 'string)
315 (defcustom org-quote-string "QUOTE"
316 "Entries starting with this keyword will be exported in fixed-width font.
317 Quoting applies only to the text in the entry following the headline, and does
318 not extend beyond the next headline, even if that is lower level.
319 An entry can be toggled between QUOTE and normal with
320 \\[org-toggle-fixed-width-section]."
321 :group 'org-keywords
322 :type 'string)
324 (defconst org-repeat-re
325 (concat "\\(?:\\<\\(?:" org-scheduled-string "\\|" org-deadline-string "\\)"
326 " +<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\)\\(\\+[0-9]+[dwmy]\\)")
327 "Regular expression for specifying repeated events.
328 After a match, group 1 contains the repeat expression.")
330 (defgroup org-structure nil
331 "Options concerning the general structure of Org-mode files."
332 :tag "Org Structure"
333 :group 'org)
335 (defgroup org-reveal-location nil
336 "Options about how to make context of a location visible."
337 :tag "Org Reveal Location"
338 :group 'org-structure)
340 (defconst org-context-choice
341 '(choice
342 (const :tag "Always" t)
343 (const :tag "Never" nil)
344 (repeat :greedy t :tag "Individual contexts"
345 (cons
346 (choice :tag "Context"
347 (const agenda)
348 (const org-goto)
349 (const occur-tree)
350 (const tags-tree)
351 (const link-search)
352 (const mark-goto)
353 (const bookmark-jump)
354 (const isearch)
355 (const default))
356 (boolean))))
357 "Contexts for the reveal options.")
359 (defcustom org-show-hierarchy-above '((default . t))
360 "Non-nil means, show full hierarchy when revealing a location.
361 Org-mode often shows locations in an org-mode file which might have
362 been invisible before. When this is set, the hierarchy of headings
363 above the exposed location is shown.
364 Turning this off for example for sparse trees makes them very compact.
365 Instead of t, this can also be an alist specifying this option for different
366 contexts. Valid contexts are
367 agenda when exposing an entry from the agenda
368 org-goto when using the command `org-goto' on key C-c C-j
369 occur-tree when using the command `org-occur' on key C-c /
370 tags-tree when constructing a sparse tree based on tags matches
371 link-search when exposing search matches associated with a link
372 mark-goto when exposing the jump goal of a mark
373 bookmark-jump when exposing a bookmark location
374 isearch when exiting from an incremental search
375 default default for all contexts not set explicitly"
376 :group 'org-reveal-location
377 :type org-context-choice)
379 (defcustom org-show-following-heading '((default . nil))
380 "Non-nil means, show following heading when revealing a location.
381 Org-mode often shows locations in an org-mode file which might have
382 been invisible before. When this is set, the heading following the
383 match is shown.
384 Turning this off for example for sparse trees makes them very compact,
385 but makes it harder to edit the location of the match. In such a case,
386 use the command \\[org-reveal] to show more context.
387 Instead of t, this can also be an alist specifying this option for different
388 contexts. See `org-show-hierarchy-above' for valid contexts."
389 :group 'org-reveal-location
390 :type org-context-choice)
392 (defcustom org-show-siblings '((default . nil) (isearch t))
393 "Non-nil means, show all sibling heading when revealing a location.
394 Org-mode often shows locations in an org-mode file which might have
395 been invisible before. When this is set, the sibling of the current entry
396 heading are all made visible. If `org-show-hierarchy-above' is t,
397 the same happens on each level of the hierarchy above the current entry.
399 By default this is on for the isearch context, off for all other contexts.
400 Turning this off for example for sparse trees makes them very compact,
401 but makes it harder to edit the location of the match. In such a case,
402 use the command \\[org-reveal] to show more context.
403 Instead of t, this can also be an alist specifying this option for different
404 contexts. See `org-show-hierarchy-above' for valid contexts."
405 :group 'org-reveal-location
406 :type org-context-choice)
408 (defcustom org-show-entry-below '((default . nil))
409 "Non-nil means, show the entry below a headline when revealing a location.
410 Org-mode often shows locations in an org-mode file which might have
411 been invisible before. When this is set, the text below the headline that is
412 exposed is also shown.
414 By default this is off for all contexts.
415 Instead of t, this can also be an alist specifying this option for different
416 contexts. See `org-show-hierarchy-above' for valid contexts."
417 :group 'org-reveal-location
418 :type org-context-choice)
420 (defgroup org-cycle nil
421 "Options concerning visibility cycling in Org-mode."
422 :tag "Org Cycle"
423 :group 'org-structure)
425 (defcustom org-drawers '("PROPERTIES" "CLOCK")
426 "Names of drawers. Drawers are not opened by cycling on the headline above.
427 Drawers only open with a TAB on the drawer line itself. A drawer looks like
428 this:
429 :DRAWERNAME:
430 .....
431 :END:
432 The drawer \"PROPERTIES\" is special for capturing properties through
433 the property API.
435 Drawers can be defined on the per-file basis with a line like:
437 #+DRAWERS: HIDDEN STATE PROPERTIES"
438 :group 'org-structure
439 :type '(repeat (string :tag "Drawer Name")))
441 (defcustom org-cycle-global-at-bob nil
442 "Cycle globally if cursor is at beginning of buffer and not at a headline.
443 This makes it possible to do global cycling without having to use S-TAB or
444 C-u TAB. For this special case to work, the first line of the buffer
445 must not be a headline - it may be empty ot some other text. When used in
446 this way, `org-cycle-hook' is disables temporarily, to make sure the
447 cursor stays at the beginning of the buffer.
448 When this option is nil, don't do anything special at the beginning
449 of the buffer."
450 :group 'org-cycle
451 :type 'boolean)
453 (defcustom org-cycle-emulate-tab t
454 "Where should `org-cycle' emulate TAB.
455 nil Never
456 white Only in completely white lines
457 whitestart Only at the beginning of lines, before the first non-white char.
458 t Everywhere except in headlines
459 exc-hl-bol Everywhere except at the start of a headline
460 If TAB is used in a place where it does not emulate TAB, the current subtree
461 visibility is cycled."
462 :group 'org-cycle
463 :type '(choice (const :tag "Never" nil)
464 (const :tag "Only in completely white lines" white)
465 (const :tag "Before first char in a line" whitestart)
466 (const :tag "Everywhere except in headlines" t)
467 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
470 (defcustom org-cycle-separator-lines 2
471 "Number of empty lines needed to keep an empty line between collapsed trees.
472 If you leave an empty line between the end of a subtree and the following
473 headline, this empty line is hidden when the subtree is folded.
474 Org-mode will leave (exactly) one empty line visible if the number of
475 empty lines is equal or larger to the number given in this variable.
476 So the default 2 means, at least 2 empty lines after the end of a subtree
477 are needed to produce free space between a collapsed subtree and the
478 following headline.
480 Special case: when 0, never leave empty lines in collapsed view."
481 :group 'org-cycle
482 :type 'integer)
484 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
485 org-cycle-hide-drawers
486 org-cycle-show-empty-lines
487 org-optimize-window-after-visibility-change)
488 "Hook that is run after `org-cycle' has changed the buffer visibility.
489 The function(s) in this hook must accept a single argument which indicates
490 the new state that was set by the most recent `org-cycle' command. The
491 argument is a symbol. After a global state change, it can have the values
492 `overview', `content', or `all'. After a local state change, it can have
493 the values `folded', `children', or `subtree'."
494 :group 'org-cycle
495 :type 'hook)
497 (defgroup org-edit-structure nil
498 "Options concerning structure editing in Org-mode."
499 :tag "Org Edit Structure"
500 :group 'org-structure)
502 (defcustom org-special-ctrl-a/e nil
503 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
504 When t, `C-a' will bring back the cursor to the beginning of the
505 headline text, i.e. after the stars and after a possible TODO keyword.
506 In an item, this will be the position after the bullet.
507 When the cursor is already at that position, another `C-a' will bring
508 it to the beginning of the line.
509 `C-e' will jump to the end of the headline, ignoring the presence of tags
510 in the headline. A second `C-e' will then jump to the true end of the
511 line, after any tags.
512 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
513 and only a directly following, identical keypress will bring the cursor
514 to the special positions."
515 :group 'org-edit-structure
516 :type '(choice
517 (const :tag "off" nil)
518 (const :tag "after bullet first" t)
519 (const :tag "border first" reversed)))
521 (if (fboundp 'defvaralias)
522 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
524 (defcustom org-odd-levels-only nil
525 "Non-nil means, skip even levels and only use odd levels for the outline.
526 This has the effect that two stars are being added/taken away in
527 promotion/demotion commands. It also influences how levels are
528 handled by the exporters.
529 Changing it requires restart of `font-lock-mode' to become effective
530 for fontification also in regions already fontified.
531 You may also set this on a per-file basis by adding one of the following
532 lines to the buffer:
534 #+STARTUP: odd
535 #+STARTUP: oddeven"
536 :group 'org-edit-structure
537 :group 'org-font-lock
538 :type 'boolean)
540 (defcustom org-adapt-indentation t
541 "Non-nil means, adapt indentation when promoting and demoting.
542 When this is set and the *entire* text in an entry is indented, the
543 indentation is increased by one space in a demotion command, and
544 decreased by one in a promotion command. If any line in the entry
545 body starts at column 0, indentation is not changed at all."
546 :group 'org-edit-structure
547 :type 'boolean)
549 (defcustom org-blank-before-new-entry '((heading . nil)
550 (plain-list-item . nil))
551 "Should `org-insert-heading' leave a blank line before new heading/item?
552 The value is an alist, with `heading' and `plain-list-item' as car,
553 and a boolean flag as cdr."
554 :group 'org-edit-structure
555 :type '(list
556 (cons (const heading) (boolean))
557 (cons (const plain-list-item) (boolean))))
559 (defcustom org-insert-heading-hook nil
560 "Hook being run after inserting a new heading."
561 :group 'org-edit-structure
562 :type 'hook)
564 (defcustom org-enable-fixed-width-editor t
565 "Non-nil means, lines starting with \":\" are treated as fixed-width.
566 This currently only means, they are never auto-wrapped.
567 When nil, such lines will be treated like ordinary lines.
568 See also the QUOTE keyword."
569 :group 'org-edit-structure
570 :type 'boolean)
572 (defgroup org-sparse-trees nil
573 "Options concerning sparse trees in Org-mode."
574 :tag "Org Sparse Trees"
575 :group 'org-structure)
577 (defcustom org-highlight-sparse-tree-matches t
578 "Non-nil means, highlight all matches that define a sparse tree.
579 The highlights will automatically disappear the next time the buffer is
580 changed by an edit command."
581 :group 'org-sparse-trees
582 :type 'boolean)
584 (defcustom org-remove-highlights-with-change t
585 "Non-nil means, any change to the buffer will remove temporary highlights.
586 Such highlights are created by `org-occur' and `org-clock-display'.
587 When nil, `C-c C-c needs to be used to get rid of the highlights.
588 The highlights created by `org-preview-latex-fragment' always need
589 `C-c C-c' to be removed."
590 :group 'org-sparse-trees
591 :group 'org-time
592 :type 'boolean)
595 (defcustom org-occur-hook '(org-first-headline-recenter)
596 "Hook that is run after `org-occur' has constructed a sparse tree.
597 This can be used to recenter the window to show as much of the structure
598 as possible."
599 :group 'org-sparse-trees
600 :type 'hook)
602 (defgroup org-plain-lists nil
603 "Options concerning plain lists in Org-mode."
604 :tag "Org Plain lists"
605 :group 'org-structure)
607 (defcustom org-cycle-include-plain-lists nil
608 "Non-nil means, include plain lists into visibility cycling.
609 This means that during cycling, plain list items will *temporarily* be
610 interpreted as outline headlines with a level given by 1000+i where i is the
611 indentation of the bullet. In all other operations, plain list items are
612 not seen as headlines. For example, you cannot assign a TODO keyword to
613 such an item."
614 :group 'org-plain-lists
615 :type 'boolean)
617 (defcustom org-plain-list-ordered-item-terminator t
618 "The character that makes a line with leading number an ordered list item.
619 Valid values are ?. and ?\). To get both terminators, use t. While
620 ?. may look nicer, it creates the danger that a line with leading
621 number may be incorrectly interpreted as an item. ?\) therefore is
622 the safe choice."
623 :group 'org-plain-lists
624 :type '(choice (const :tag "dot like in \"2.\"" ?.)
625 (const :tag "paren like in \"2)\"" ?\))
626 (const :tab "both" t)))
628 (defcustom org-auto-renumber-ordered-lists t
629 "Non-nil means, automatically renumber ordered plain lists.
630 Renumbering happens when the sequence have been changed with
631 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
632 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
633 :group 'org-plain-lists
634 :type 'boolean)
636 (defcustom org-provide-checkbox-statistics t
637 "Non-nil means, update checkbox statistics after insert and toggle.
638 When this is set, checkbox statistics is updated each time you either insert
639 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
640 with \\[org-ctrl-c-ctrl-c\\]."
641 :group 'org-plain-lists
642 :type 'boolean)
644 (defgroup org-archive nil
645 "Options concerning archiving in Org-mode."
646 :tag "Org Archive"
647 :group 'org-structure)
649 (defcustom org-archive-tag "ARCHIVE"
650 "The tag that marks a subtree as archived.
651 An archived subtree does not open during visibility cycling, and does
652 not contribute to the agenda listings.
653 After changing this, font-lock must be restarted in the relevant buffers to
654 get the proper fontification."
655 :group 'org-archive
656 :group 'org-keywords
657 :type 'string)
659 (defcustom org-agenda-skip-archived-trees t
660 "Non-nil means, the agenda will skip any items located in archived trees.
661 An archived tree is a tree marked with the tag ARCHIVE."
662 :group 'org-archive
663 :group 'org-agenda-skip
664 :type 'boolean)
666 (defcustom org-cycle-open-archived-trees nil
667 "Non-nil means, `org-cycle' will open archived trees.
668 An archived tree is a tree marked with the tag ARCHIVE.
669 When nil, archived trees will stay folded. You can still open them with
670 normal outline commands like `show-all', but not with the cycling commands."
671 :group 'org-archive
672 :group 'org-cycle
673 :type 'boolean)
675 (defcustom org-sparse-tree-open-archived-trees nil
676 "Non-nil means sparse tree construction shows matches in archived trees.
677 When nil, matches in these trees are highlighted, but the trees are kept in
678 collapsed state."
679 :group 'org-archive
680 :group 'org-sparse-trees
681 :type 'boolean)
683 (defcustom org-archive-location "%s_archive::"
684 "The location where subtrees should be archived.
685 This string consists of two parts, separated by a double-colon.
687 The first part is a file name - when omitted, archiving happens in the same
688 file. %s will be replaced by the current file name (without directory part).
689 Archiving to a different file is useful to keep archived entries from
690 contributing to the Org-mode Agenda.
692 The part after the double colon is a headline. The archived entries will be
693 filed under that headline. When omitted, the subtrees are simply filed away
694 at the end of the file, as top-level entries.
696 Here are a few examples:
697 \"%s_archive::\"
698 If the current file is Projects.org, archive in file
699 Projects.org_archive, as top-level trees. This is the default.
701 \"::* Archived Tasks\"
702 Archive in the current file, under the top-level headline
703 \"* Archived Tasks\".
705 \"~/org/archive.org::\"
706 Archive in file ~/org/archive.org (absolute path), as top-level trees.
708 \"basement::** Finished Tasks\"
709 Archive in file ./basement (relative path), as level 3 trees
710 below the level 2 heading \"** Finished Tasks\".
712 You may set this option on a per-file basis by adding to the buffer a
713 line like
715 #+ARCHIVE: basement::** Finished Tasks"
716 :group 'org-archive
717 :type 'string)
719 (defcustom org-archive-mark-done t
720 "Non-nil means, mark entries as DONE when they are moved to the archive file.
721 This can be a string to set the keyword to use. When t, Org-mode will
722 use the first keyword in its list that means done."
723 :group 'org-archive
724 :type '(choice
725 (const :tag "No" nil)
726 (const :tag "Yes" t)
727 (string :tag "Use this keyword")))
729 (defcustom org-archive-stamp-time t
730 "Non-nil means, add a time stamp to entries moved to an archive file.
731 This variable is obsolete and has no effect anymore, instead add ot remove
732 `time' from the variablle `org-archive-save-context-info'."
733 :group 'org-archive
734 :type 'boolean)
736 (defcustom org-archive-save-context-info '(time file category todo itags)
737 "Parts of context info that should be stored as properties when archiving.
738 When a subtree is moved to an archive file, it looses information given by
739 context, like inherited tags, the category, and possibly also the TODO
740 state (depending on the variable `org-archive-mark-done').
741 This variable can be a list of any of the following symbols:
743 time The time of archiving.
744 file The file where the entry originates.
745 itags The local tags, in the headline of the subtree.
746 ltags The tags the subtree inherits from further up the hierarchy.
747 todo The pre-archive TODO state.
748 category The category, taken from file name or #+CATEGORY lines.
750 For each symbol present in the list, a property will be created in
751 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
752 information."
753 :group 'org-archive
754 :type '(set :greedy t
755 (const :tag "Time" time)
756 (const :tag "File" file)
757 (const :tag "Category" category)
758 (const :tag "TODO state" todo)
759 (const :tag "TODO state" priority)
760 (const :tag "Inherited tags" itags)
761 (const :tag "Local tags" ltags)))
763 (defgroup org-imenu-and-speedbar nil
764 "Options concerning imenu and speedbar in Org-mode."
765 :tag "Org Imenu and Speedbar"
766 :group 'org-structure)
768 (defcustom org-imenu-depth 2
769 "The maximum level for Imenu access to Org-mode headlines.
770 This also applied for speedbar access."
771 :group 'org-imenu-and-speedbar
772 :type 'number)
774 (defgroup org-table nil
775 "Options concerning tables in Org-mode."
776 :tag "Org Table"
777 :group 'org)
779 (defcustom org-enable-table-editor 'optimized
780 "Non-nil means, lines starting with \"|\" are handled by the table editor.
781 When nil, such lines will be treated like ordinary lines.
783 When equal to the symbol `optimized', the table editor will be optimized to
784 do the following:
785 - Automatic overwrite mode in front of whitespace in table fields.
786 This makes the structure of the table stay in tact as long as the edited
787 field does not exceed the column width.
788 - Minimize the number of realigns. Normally, the table is aligned each time
789 TAB or RET are pressed to move to another field. With optimization this
790 happens only if changes to a field might have changed the column width.
791 Optimization requires replacing the functions `self-insert-command',
792 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
793 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
794 very good at guessing when a re-align will be necessary, but you can always
795 force one with \\[org-ctrl-c-ctrl-c].
797 If you would like to use the optimized version in Org-mode, but the
798 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
800 This variable can be used to turn on and off the table editor during a session,
801 but in order to toggle optimization, a restart is required.
803 See also the variable `org-table-auto-blank-field'."
804 :group 'org-table
805 :type '(choice
806 (const :tag "off" nil)
807 (const :tag "on" t)
808 (const :tag "on, optimized" optimized)))
810 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
811 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
812 In the optimized version, the table editor takes over all simple keys that
813 normally just insert a character. In tables, the characters are inserted
814 in a way to minimize disturbing the table structure (i.e. in overwrite mode
815 for empty fields). Outside tables, the correct binding of the keys is
816 restored.
818 The default for this option is t if the optimized version is also used in
819 Org-mode. See the variable `org-enable-table-editor' for details. Changing
820 this variable requires a restart of Emacs to become effective."
821 :group 'org-table
822 :type 'boolean)
824 (defcustom orgtbl-radio-table-templates
825 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
826 % END RECEIVE ORGTBL %n
827 \\begin{comment}
828 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
829 | | |
830 \\end{comment}\n")
831 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
832 @c END RECEIVE ORGTBL %n
833 @ignore
834 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
835 | | |
836 @end ignore\n")
837 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
838 <!-- END RECEIVE ORGTBL %n -->
839 <!--
840 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
841 | | |
842 -->\n"))
843 "Templates for radio tables in different major modes.
844 All occurrences of %n in a template will be replaced with the name of the
845 table, obtained by prompting the user."
846 :group 'org-table
847 :type '(repeat
848 (list (symbol :tag "Major mode")
849 (string :tag "Format"))))
851 (defgroup org-table-settings nil
852 "Settings for tables in Org-mode."
853 :tag "Org Table Settings"
854 :group 'org-table)
856 (defcustom org-table-default-size "5x2"
857 "The default size for newly created tables, Columns x Rows."
858 :group 'org-table-settings
859 :type 'string)
861 (defcustom org-table-number-regexp
862 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
863 "Regular expression for recognizing numbers in table columns.
864 If a table column contains mostly numbers, it will be aligned to the
865 right. If not, it will be aligned to the left.
867 The default value of this option is a regular expression which allows
868 anything which looks remotely like a number as used in scientific
869 context. For example, all of the following will be considered a
870 number:
871 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
873 Other options offered by the customize interface are more restrictive."
874 :group 'org-table-settings
875 :type '(choice
876 (const :tag "Positive Integers"
877 "^[0-9]+$")
878 (const :tag "Integers"
879 "^[-+]?[0-9]+$")
880 (const :tag "Floating Point Numbers"
881 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
882 (const :tag "Floating Point Number or Integer"
883 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
884 (const :tag "Exponential, Floating point, Integer"
885 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
886 (const :tag "Very General Number-Like, including hex"
887 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
888 (string :tag "Regexp:")))
890 (defcustom org-table-number-fraction 0.5
891 "Fraction of numbers in a column required to make the column align right.
892 In a column all non-white fields are considered. If at least this
893 fraction of fields is matched by `org-table-number-fraction',
894 alignment to the right border applies."
895 :group 'org-table-settings
896 :type 'number)
898 (defgroup org-table-editing nil
899 "Behavior of tables during editing in Org-mode."
900 :tag "Org Table Editing"
901 :group 'org-table)
903 (defcustom org-table-automatic-realign t
904 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
905 When nil, aligning is only done with \\[org-table-align], or after column
906 removal/insertion."
907 :group 'org-table-editing
908 :type 'boolean)
910 (defcustom org-table-auto-blank-field t
911 "Non-nil means, automatically blank table field when starting to type into it.
912 This only happens when typing immediately after a field motion
913 command (TAB, S-TAB or RET).
914 Only relevant when `org-enable-table-editor' is equal to `optimized'."
915 :group 'org-table-editing
916 :type 'boolean)
918 (defcustom org-table-tab-jumps-over-hlines t
919 "Non-nil means, tab in the last column of a table with jump over a hline.
920 If a horizontal separator line is following the current line,
921 `org-table-next-field' can either create a new row before that line, or jump
922 over the line. When this option is nil, a new line will be created before
923 this line."
924 :group 'org-table-editing
925 :type 'boolean)
927 (defcustom org-table-tab-recognizes-table.el t
928 "Non-nil means, TAB will automatically notice a table.el table.
929 When it sees such a table, it moves point into it and - if necessary -
930 calls `table-recognize-table'."
931 :group 'org-table-editing
932 :type 'boolean)
934 (defgroup org-table-calculation nil
935 "Options concerning tables in Org-mode."
936 :tag "Org Table Calculation"
937 :group 'org-table)
939 (defcustom org-table-use-standard-references t
940 "Should org-mode work with table refrences like B3 instead of @3$2?
941 Possible values are:
942 nil never use them
943 from accept as input, do not present for editing
944 t: accept as input and present for editing"
945 :group 'org-table-calculation
946 :type '(choice
947 (const :tag "Never, don't even check unser input for them" nil)
948 (const :tag "Always, both as user input, and when editing" t)
949 (const :tag "Convert user input, don't offer during editing" 'from)))
951 (defcustom org-table-copy-increment t
952 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
953 :group 'org-table-calculation
954 :type 'boolean)
956 (defcustom org-calc-default-modes
957 '(calc-internal-prec 12
958 calc-float-format (float 5)
959 calc-angle-mode deg
960 calc-prefer-frac nil
961 calc-symbolic-mode nil
962 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
963 calc-display-working-message t
965 "List with Calc mode settings for use in calc-eval for table formulas.
966 The list must contain alternating symbols (Calc modes variables and values).
967 Don't remove any of the default settings, just change the values. Org-mode
968 relies on the variables to be present in the list."
969 :group 'org-table-calculation
970 :type 'plist)
972 (defcustom org-table-formula-evaluate-inline t
973 "Non-nil means, TAB and RET evaluate a formula in current table field.
974 If the current field starts with an equal sign, it is assumed to be a formula
975 which should be evaluated as described in the manual and in the documentation
976 string of the command `org-table-eval-formula'. This feature requires the
977 Emacs calc package.
978 When this variable is nil, formula calculation is only available through
979 the command \\[org-table-eval-formula]."
980 :group 'org-table-calculation
981 :type 'boolean)
983 (defcustom org-table-formula-use-constants t
984 "Non-nil means, interpret constants in formulas in tables.
985 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
986 by the value given in `org-table-formula-constants', or by a value obtained
987 from the `constants.el' package."
988 :group 'org-table-calculation
989 :type 'boolean)
991 (defcustom org-table-formula-constants nil
992 "Alist with constant names and values, for use in table formulas.
993 The car of each element is a name of a constant, without the `$' before it.
994 The cdr is the value as a string. For example, if you'd like to use the
995 speed of light in a formula, you would configure
997 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
999 and then use it in an equation like `$1*$c'.
1001 Constants can also be defined on a per-file basis using a line like
1003 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
1004 :group 'org-table-calculation
1005 :type '(repeat
1006 (cons (string :tag "name")
1007 (string :tag "value"))))
1009 (defvar org-table-formula-constants-local nil
1010 "Local version of `org-table-formula-constants'.")
1011 (make-variable-buffer-local 'org-table-formula-constants-local)
1013 (defcustom org-table-allow-automatic-line-recalculation t
1014 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1015 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1016 :group 'org-table-calculation
1017 :type 'boolean)
1019 (defgroup org-link nil
1020 "Options concerning links in Org-mode."
1021 :tag "Org Link"
1022 :group 'org)
1024 (defvar org-link-abbrev-alist-local nil
1025 "Buffer-local version of `org-link-abbrev-alist', which see.
1026 The value of this is taken from the #+LINK lines.")
1027 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1029 (defcustom org-link-abbrev-alist nil
1030 "Alist of link abbreviations.
1031 The car of each element is a string, to be replaced at the start of a link.
1032 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1033 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1035 [[linkkey:tag][description]]
1037 If REPLACE is a string, the tag will simply be appended to create the link.
1038 If the string contains \"%s\", the tag will be inserted there.
1040 REPLACE may also be a function that will be called with the tag as the
1041 only argument to create the link, which should be returned as a string.
1043 See the manual for examples."
1044 :group 'org-link
1045 :type 'alist)
1047 (defcustom org-descriptive-links t
1048 "Non-nil means, hide link part and only show description of bracket links.
1049 Bracket links are like [[link][descritpion]]. This variable sets the initial
1050 state in new org-mode buffers. The setting can then be toggled on a
1051 per-buffer basis from the Org->Hyperlinks menu."
1052 :group 'org-link
1053 :type 'boolean)
1055 (defcustom org-link-file-path-type 'adaptive
1056 "How the path name in file links should be stored.
1057 Valid values are:
1059 relative relative to the current directory, i.e. the directory of the file
1060 into which the link is being inserted.
1061 absolute absolute path, if possible with ~ for home directory.
1062 noabbrev absolute path, no abbreviation of home directory.
1063 adaptive Use relative path for files in the current directory and sub-
1064 directories of it. For other files, use an absolute path."
1065 :group 'org-link
1066 :type '(choice
1067 (const relative)
1068 (const absolute)
1069 (const noabbrev)
1070 (const adaptive)))
1072 (defcustom org-activate-links '(bracket angle plain radio tag date)
1073 "Types of links that should be activated in Org-mode files.
1074 This is a list of symbols, each leading to the activation of a certain link
1075 type. In principle, it does not hurt to turn on most link types - there may
1076 be a small gain when turning off unused link types. The types are:
1078 bracket The recommended [[link][description]] or [[link]] links with hiding.
1079 angular Links in angular brackes that may contain whitespace like
1080 <bbdb:Carsten Dominik>.
1081 plain Plain links in normal text, no whitespace, like http://google.com.
1082 radio Text that is matched by a radio target, see manual for details.
1083 tag Tag settings in a headline (link to tag search).
1084 date Time stamps (link to calendar).
1086 Changing this variable requires a restart of Emacs to become effective."
1087 :group 'org-link
1088 :type '(set (const :tag "Double bracket links (new style)" bracket)
1089 (const :tag "Angular bracket links (old style)" angular)
1090 (const :tag "plain text links" plain)
1091 (const :tag "Radio target matches" radio)
1092 (const :tag "Tags" tag)
1093 (const :tag "Tags" target)
1094 (const :tag "Timestamps" date)))
1096 (defgroup org-link-store nil
1097 "Options concerning storing links in Org-mode"
1098 :tag "Org Store Link"
1099 :group 'org-link)
1101 (defcustom org-email-link-description-format "Email %c: %.30s"
1102 "Format of the description part of a link to an email or usenet message.
1103 The following %-excapes will be replaced by corresponding information:
1105 %F full \"From\" field
1106 %f name, taken from \"From\" field, address if no name
1107 %T full \"To\" field
1108 %t first name in \"To\" field, address if no name
1109 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1110 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1111 %s subject
1112 %m message-id.
1114 You may use normal field width specification between the % and the letter.
1115 This is for example useful to limit the length of the subject.
1117 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1118 :group 'org-link-store
1119 :type 'string)
1121 (defcustom org-from-is-user-regexp
1122 (let (r1 r2)
1123 (when (and user-mail-address (not (string= user-mail-address "")))
1124 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1125 (when (and user-full-name (not (string= user-full-name "")))
1126 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1127 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1128 "Regexp mached against the \"From:\" header of an email or usenet message.
1129 It should match if the message is from the user him/herself."
1130 :group 'org-link-store
1131 :type 'regexp)
1133 (defcustom org-context-in-file-links t
1134 "Non-nil means, file links from `org-store-link' contain context.
1135 A search string will be added to the file name with :: as separator and
1136 used to find the context when the link is activated by the command
1137 `org-open-at-point'.
1138 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1139 negates this setting for the duration of the command."
1140 :group 'org-link-store
1141 :type 'boolean)
1143 (defcustom org-keep-stored-link-after-insertion nil
1144 "Non-nil means, keep link in list for entire session.
1146 The command `org-store-link' adds a link pointing to the current
1147 location to an internal list. These links accumulate during a session.
1148 The command `org-insert-link' can be used to insert links into any
1149 Org-mode file (offering completion for all stored links). When this
1150 option is nil, every link which has been inserted once using \\[org-insert-link]
1151 will be removed from the list, to make completing the unused links
1152 more efficient."
1153 :group 'org-link-store
1154 :type 'boolean)
1156 (defcustom org-usenet-links-prefer-google nil
1157 "Non-nil means, `org-store-link' will create web links to Google groups.
1158 When nil, Gnus will be used for such links.
1159 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1160 negates this setting for the duration of the command."
1161 :group 'org-link-store
1162 :type 'boolean)
1164 (defgroup org-link-follow nil
1165 "Options concerning following links in Org-mode"
1166 :tag "Org Follow Link"
1167 :group 'org-link)
1169 (defcustom org-tab-follows-link nil
1170 "Non-nil means, on links TAB will follow the link.
1171 Needs to be set before org.el is loaded."
1172 :group 'org-link-follow
1173 :type 'boolean)
1175 (defcustom org-return-follows-link nil
1176 "Non-nil means, on links RET will follow the link.
1177 Needs to be set before org.el is loaded."
1178 :group 'org-link-follow
1179 :type 'boolean)
1181 (defcustom org-mouse-1-follows-link t
1182 "Non-nil means, mouse-1 on a link will follow the link.
1183 A longer mouse click will still set point. Does not wortk on XEmacs.
1184 Needs to be set before org.el is loaded."
1185 :group 'org-link-follow
1186 :type 'boolean)
1188 (defcustom org-mark-ring-length 4
1189 "Number of different positions to be recorded in the ring
1190 Changing this requires a restart of Emacs to work correctly."
1191 :group 'org-link-follow
1192 :type 'interger)
1194 (defcustom org-link-frame-setup
1195 '((vm . vm-visit-folder-other-frame)
1196 (gnus . gnus-other-frame)
1197 (file . find-file-other-window))
1198 "Setup the frame configuration for following links.
1199 When following a link with Emacs, it may often be useful to display
1200 this link in another window or frame. This variable can be used to
1201 set this up for the different types of links.
1202 For VM, use any of
1203 `vm-visit-folder'
1204 `vm-visit-folder-other-frame'
1205 For Gnus, use any of
1206 `gnus'
1207 `gnus-other-frame'
1208 For FILE, use any of
1209 `find-file'
1210 `find-file-other-window'
1211 `find-file-other-frame'
1212 For the calendar, use the variable `calendar-setup'.
1213 For BBDB, it is currently only possible to display the matches in
1214 another window."
1215 :group 'org-link-follow
1216 :type '(list
1217 (cons (const vm)
1218 (choice
1219 (const vm-visit-folder)
1220 (const vm-visit-folder-other-window)
1221 (const vm-visit-folder-other-frame)))
1222 (cons (const gnus)
1223 (choice
1224 (const gnus)
1225 (const gnus-other-frame)))
1226 (cons (const file)
1227 (choice
1228 (const find-file)
1229 (const find-file-other-window)
1230 (const find-file-other-frame)))))
1232 (defcustom org-display-internal-link-with-indirect-buffer nil
1233 "Non-nil means, use indirect buffer to display infile links.
1234 Activating internal links (from one location in a file to another location
1235 in the same file) normally just jumps to the location. When the link is
1236 activated with a C-u prefix (or with mouse-3), the link is displayed in
1237 another window. When this option is set, the other window actually displays
1238 an indirect buffer clone of the current buffer, to avoid any visibility
1239 changes to the current buffer."
1240 :group 'org-link-follow
1241 :type 'boolean)
1243 (defcustom org-open-non-existing-files nil
1244 "Non-nil means, `org-open-file' will open non-existing files.
1245 When nil, an error will be generated."
1246 :group 'org-link-follow
1247 :type 'boolean)
1249 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1250 "Function and arguments to call for following mailto links.
1251 This is a list with the first element being a lisp function, and the
1252 remaining elements being arguments to the function. In string arguments,
1253 %a will be replaced by the address, and %s will be replaced by the subject
1254 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1255 :group 'org-link-follow
1256 :type '(choice
1257 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1258 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1259 (const :tag "message-mail" (message-mail "%a" "%s"))
1260 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1262 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1263 "Non-nil means, ask for confirmation before executing shell links.
1264 Shell links can be dangerous: just think about a link
1266 [[shell:rm -rf ~/*][Google Search]]
1268 This link would show up in your Org-mode document as \"Google Search\",
1269 but really it would remove your entire home directory.
1270 Therefore we advise against setting this variable to nil.
1271 Just change it to `y-or-n-p' of you want to confirm with a
1272 single keystroke rather than having to type \"yes\"."
1273 :group 'org-link-follow
1274 :type '(choice
1275 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1276 (const :tag "with y-or-n (faster)" y-or-n-p)
1277 (const :tag "no confirmation (dangerous)" nil)))
1279 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1280 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1281 Elisp links can be dangerous: just think about a link
1283 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1285 This link would show up in your Org-mode document as \"Google Search\",
1286 but really it would remove your entire home directory.
1287 Therefore we advise against setting this variable to nil.
1288 Just change it to `y-or-n-p' of you want to confirm with a
1289 single keystroke rather than having to type \"yes\"."
1290 :group 'org-link-follow
1291 :type '(choice
1292 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1293 (const :tag "with y-or-n (faster)" y-or-n-p)
1294 (const :tag "no confirmation (dangerous)" nil)))
1296 (defconst org-file-apps-defaults-gnu
1297 '((remote . emacs)
1298 (t . mailcap))
1299 "Default file applications on a UNIX or GNU/Linux system.
1300 See `org-file-apps'.")
1302 (defconst org-file-apps-defaults-macosx
1303 '((remote . emacs)
1304 (t . "open %s")
1305 ("ps" . "gv %s")
1306 ("ps.gz" . "gv %s")
1307 ("eps" . "gv %s")
1308 ("eps.gz" . "gv %s")
1309 ("dvi" . "xdvi %s")
1310 ("fig" . "xfig %s"))
1311 "Default file applications on a MacOS X system.
1312 The system \"open\" is known as a default, but we use X11 applications
1313 for some files for which the OS does not have a good default.
1314 See `org-file-apps'.")
1316 (defconst org-file-apps-defaults-windowsnt
1317 (list
1318 '(remote . emacs)
1319 (cons t
1320 (list (if (featurep 'xemacs)
1321 'mswindows-shell-execute
1322 'w32-shell-execute)
1323 "open" 'file)))
1324 "Default file applications on a Windows NT system.
1325 The system \"open\" is used for most files.
1326 See `org-file-apps'.")
1328 (defcustom org-file-apps
1330 ("txt" . emacs)
1331 ("tex" . emacs)
1332 ("ltx" . emacs)
1333 ("org" . emacs)
1334 ("el" . emacs)
1335 ("bib" . emacs)
1337 "External applications for opening `file:path' items in a document.
1338 Org-mode uses system defaults for different file types, but
1339 you can use this variable to set the application for a given file
1340 extension. The entries in this list are cons cells where the car identifies
1341 files and the cdr the corresponding command. Possible values for the
1342 file identifier are
1343 \"ext\" A string identifying an extension
1344 `directory' Matches a directory
1345 `remote' Matches a remote file, accessible through tramp or efs.
1346 Remote files most likely should be visited through Emacs
1347 because external applications cannot handle such paths.
1348 t Default for all remaining files
1350 Possible values for the command are:
1351 `emacs' The file will be visited by the current Emacs process.
1352 `default' Use the default application for this file type.
1353 string A command to be executed by a shell; %s will be replaced
1354 by the path to the file.
1355 sexp A Lisp form which will be evaluated. The file path will
1356 be available in the Lisp variable `file'.
1357 For more examples, see the system specific constants
1358 `org-file-apps-defaults-macosx'
1359 `org-file-apps-defaults-windowsnt'
1360 `org-file-apps-defaults-gnu'."
1361 :group 'org-link-follow
1362 :type '(repeat
1363 (cons (choice :value ""
1364 (string :tag "Extension")
1365 (const :tag "Default for unrecognized files" t)
1366 (const :tag "Remote file" remote)
1367 (const :tag "Links to a directory" directory))
1368 (choice :value ""
1369 (const :tag "Visit with Emacs" emacs)
1370 (const :tag "Use system default" default)
1371 (string :tag "Command")
1372 (sexp :tag "Lisp form")))))
1374 (defcustom org-mhe-search-all-folders nil
1375 "Non-nil means, that the search for the mh-message will be extended to
1376 all folders if the message cannot be found in the folder given in the link.
1377 Searching all folders is very efficient with one of the search engines
1378 supported by MH-E, but will be slow with pick."
1379 :group 'org-link-follow
1380 :type 'boolean)
1382 (defgroup org-remember nil
1383 "Options concerning interaction with remember.el."
1384 :tag "Org Remember"
1385 :group 'org)
1387 (defcustom org-directory "~/org"
1388 "Directory with org files.
1389 This directory will be used as default to prompt for org files.
1390 Used by the hooks for remember.el."
1391 :group 'org-remember
1392 :type 'directory)
1394 (defcustom org-default-notes-file "~/.notes"
1395 "Default target for storing notes.
1396 Used by the hooks for remember.el. This can be a string, or nil to mean
1397 the value of `remember-data-file'.
1398 You can set this on a per-template basis with the variable
1399 `org-remember-templates'."
1400 :group 'org-remember
1401 :type '(choice
1402 (const :tag "Default from remember-data-file" nil)
1403 file))
1405 (defcustom org-remember-store-without-prompt t
1406 "Non-nil means, `C-c C-c' stores remember note without further promts.
1407 In this case, you need `C-u C-c C-c' to get the prompts for
1408 note file and headline.
1409 When this variable is nil, `C-c C-c' give you the prompts, and
1410 `C-u C-c C-c' trigger the fasttrack."
1411 :group 'org-remember
1412 :type 'boolean)
1414 (defcustom org-remember-default-headline ""
1415 "The headline that should be the default location in the notes file.
1416 When filing remember notes, the cursor will start at that position.
1417 You can set this on a per-template basis with the variable
1418 `org-remember-templates'."
1419 :group 'org-remember
1420 :type 'string)
1422 (defcustom org-remember-templates nil
1423 "Templates for the creation of remember buffers.
1424 When nil, just let remember make the buffer.
1425 When not nil, this is a list of 5-element lists. In each entry, the first
1426 element is a the name of the template, It should be a single short word.
1427 The second element is a character, a unique key to select this template.
1428 The third element is the template. The forth element is optional and can
1429 specify a destination file for remember items created with this template.
1430 The default file is given by `org-default-notes-file'. An optional fifth
1431 element can specify the headline in that file that should be offered
1432 first when the user is asked to file the entry. The default headline is
1433 given in the variable `org-remember-default-headline'.
1435 The template specifies the structure of the remember buffer. It should have
1436 a first line starting with a star, to act as the org-mode headline.
1437 Furthermore, the following %-escapes will be replaced with content:
1439 %^{prompt} Prompt the user for a string and replace this sequence with it.
1440 A default value and a completion table ca be specified like this:
1441 %^{prompt|default|completion2|completion3|...}
1442 %t time stamp, date only
1443 %T time stamp with date and time
1444 %u, %U like the above, but inactive time stamps
1445 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1446 You may define a prompt like %^{Please specify birthday}t
1447 %n user name (taken from `user-full-name')
1448 %a annotation, normally the link created with org-store-link
1449 %i initial content, the region when remember is called with C-u.
1450 If %i is indented, the entire inserted text will be indented
1451 as well.
1452 %c content of the clipboard, or current kill ring head
1453 %^g prompt for tags, with completion on tags in target file
1454 %^G prompt for tags, with completion all tags in all agenda files
1455 %:keyword specific information for certain link types, see below
1456 %[pathname] insert the contents of the file given by `pathname'
1457 %(sexp) evaluate elisp `(sexp)' and replace with the result
1460 %? After completing the template, position cursor here.
1462 Apart from these general escapes, you can access information specific to the
1463 link type that is created. For example, calling `remember' in emails or gnus
1464 will record the author and the subject of the message, which you can access
1465 with %:author and %:subject, respectively. Here is a complete list of what
1466 is recorded for each link type.
1468 Link type | Available information
1469 -------------------+------------------------------------------------------
1470 bbdb | %:type %:name %:company
1471 vm, wl, mh, rmail | %:type %:subject %:message-id
1472 | %:from %:fromname %:fromaddress
1473 | %:to %:toname %:toaddress
1474 | %:fromto (either \"to NAME\" or \"from NAME\")
1475 gnus | %:group, for messages also all email fields
1476 w3, w3m | %:type %:url
1477 info | %:type %:file %:node
1478 calendar | %:type %:date"
1479 :group 'org-remember
1480 :get (lambda (var) ; Make sure all entries have 5 elements
1481 (mapcar (lambda (x)
1482 (if (not (stringp (car x))) (setq x (cons "" x)))
1483 (cond ((= (length x) 4) (append x '("")))
1484 ((= (length x) 3) (append x '("" "")))
1485 (t x)))
1486 (default-value var)))
1487 :type '(repeat
1488 :tag "enabled"
1489 (list :value ("" ?a "\n" nil nil)
1490 (string :tag "Name")
1491 (character :tag "Selection Key")
1492 (string :tag "Template")
1493 (choice
1494 (file :tag "Destination file")
1495 (const :tag "Prompt for file" nil))
1496 (choice
1497 (string :tag "Destination headline")
1498 (const :tag "Selection interface for heading")))))
1500 (defcustom org-reverse-note-order nil
1501 "Non-nil means, store new notes at the beginning of a file or entry.
1502 When nil, new notes will be filed to the end of a file or entry.
1503 This can also be a list with cons cells of regular expressions that
1504 are matched against file names, and values."
1505 :group 'org-remember
1506 :type '(choice
1507 (const :tag "Reverse always" t)
1508 (const :tag "Reverse never" nil)
1509 (repeat :tag "By file name regexp"
1510 (cons regexp boolean))))
1512 (defcustom org-refile-targets '((nil . (:level . 1)))
1513 "Targets for refiling entries with \\[org-refile].
1514 This is list of cons cells. Each cell contains:
1515 - a specification of the files to be considered, either a list of files,
1516 or a symbol whose function or value fields will be used to retrieve
1517 a file name or a list of file names. Nil means, refile to a different
1518 heading in the current buffer.
1519 - A specification of how to find candidate refile targets. This may be
1520 any of
1521 - a cons cell (:tag . \"TAG\") to identify refile targes by a tag.
1522 This tag has to be present in all target headlines, inheritance will
1523 not be considered.
1524 - a cons cell (:todo . \"KEYWORD\" to identify refile targets by
1525 todo keyword.
1526 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1527 headlines that are refiling targets.
1528 - a cons cell (:level . N). Any headline of level N is considered a target.
1529 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1530 ;; FIXME: what if there are a var and func with same name???
1531 :group 'org-remember
1532 :type '(repeat
1533 (cons
1534 (choice :value org-agenda-files
1535 (const :tag "All agenda files" org-agenda-files)
1536 (const :tag "Current buffer" nil)
1537 (function) (variable) (file))
1538 (choice :tag "Identify target headline by"
1539 (cons :tag "Specific tag" (const :tag) (string))
1540 (cons :tag "TODO keyword" (const :todo) (string))
1541 (cons :tag "Regular expression" (const :regexp) (regexp))
1542 (cons :tag "Level number" (const :level) (integer))
1543 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1545 (defcustom org-refile-use-outline-path nil
1546 "Non-nil means, provide refile targets as paths.
1547 So a level 3 headline will be available as level1/level2/level3."
1548 :group 'org-remember
1549 :type 'boolean)
1551 (defgroup org-todo nil
1552 "Options concerning TODO items in Org-mode."
1553 :tag "Org TODO"
1554 :group 'org)
1556 (defgroup org-progress nil
1557 "Options concerning Progress logging in Org-mode."
1558 :tag "Org Progress"
1559 :group 'org-time)
1561 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1562 "List of TODO entry keyword sequences and their interpretation.
1563 \\<org-mode-map>This is a list of sequences.
1565 Each sequence starts with a symbol, either `sequence' or `type',
1566 indicating if the keywords should be interpreted as a sequence of
1567 action steps, or as different types of TODO items. The first
1568 keywords are states requiring action - these states will select a headline
1569 for inclusion into the global TODO list Org-mode produces. If one of
1570 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1571 signify that no further action is necessary. If \"|\" is not found,
1572 the last keyword is treated as the only DONE state of the sequence.
1574 The command \\[org-todo] cycles an entry through these states, and one
1575 additional state where no keyword is present. For details about this
1576 cycling, see the manual.
1578 TODO keywords and interpretation can also be set on a per-file basis with
1579 the special #+SEQ_TODO and #+TYP_TODO lines.
1581 For backward compatibility, this variable may also be just a list
1582 of keywords - in this case the interptetation (sequence or type) will be
1583 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1584 :group 'org-todo
1585 :group 'org-keywords
1586 :type '(choice
1587 (repeat :tag "Old syntax, just keywords"
1588 (string :tag "Keyword"))
1589 (repeat :tag "New syntax"
1590 (cons
1591 (choice
1592 :tag "Interpretation"
1593 (const :tag "Sequence (cycling hits every state)" sequence)
1594 (const :tag "Type (cycling directly to DONE)" type))
1595 (repeat
1596 (string :tag "Keyword"))))))
1598 (defvar org-todo-keywords-1 nil)
1599 (make-variable-buffer-local 'org-todo-keywords-1)
1600 (defvar org-todo-keywords-for-agenda nil)
1601 (defvar org-done-keywords-for-agenda nil)
1602 (defvar org-not-done-keywords nil)
1603 (make-variable-buffer-local 'org-not-done-keywords)
1604 (defvar org-done-keywords nil)
1605 (make-variable-buffer-local 'org-done-keywords)
1606 (defvar org-todo-heads nil)
1607 (make-variable-buffer-local 'org-todo-heads)
1608 (defvar org-todo-sets nil)
1609 (make-variable-buffer-local 'org-todo-sets)
1610 (defvar org-todo-log-states nil)
1611 (make-variable-buffer-local 'org-todo-log-states)
1612 (defvar org-todo-kwd-alist nil)
1613 (make-variable-buffer-local 'org-todo-kwd-alist)
1614 (defvar org-todo-key-alist nil)
1615 (make-variable-buffer-local 'org-todo-key-alist)
1616 (defvar org-todo-key-trigger nil)
1617 (make-variable-buffer-local 'org-todo-key-trigger)
1619 (defcustom org-todo-interpretation 'sequence
1620 "Controls how TODO keywords are interpreted.
1621 This variable is in principle obsolete and is only used for
1622 backward compatibility, if the interpretation of todo keywords is
1623 not given already in `org-todo-keywords'. See that variable for
1624 more information."
1625 :group 'org-todo
1626 :group 'org-keywords
1627 :type '(choice (const sequence)
1628 (const type)))
1630 (defcustom org-use-fast-todo-selection 'prefix
1631 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1632 This variable describes if and under what circumstances the cycling
1633 mechanism for TODO keywords will be replaced by a single-key, direct
1634 selection scheme.
1636 When nil, fast selection is never used.
1638 When the symbol `prefix', it will be used when `org-todo' is called with
1639 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1640 in an agenda buffer.
1642 When t, fast selection is used by default. In this case, the prefix
1643 argument forces cycling instead.
1645 In all cases, the special interface is only used if access keys have actually
1646 been assigned by the user, i.e. if keywords in the configuration are followed
1647 by a letter in parenthesis, like TODO(t)."
1648 :group 'org-todo
1649 :type '(choice
1650 (const :tag "Never" nil)
1651 (const :tag "By default" t)
1652 (const :tag "Only with C-u C-c C-t" prefix)))
1654 (defcustom org-after-todo-state-change-hook nil
1655 "Hook which is run after the state of a TODO item was changed.
1656 The new state (a string with a TODO keyword, or nil) is available in the
1657 Lisp variable `state'."
1658 :group 'org-todo
1659 :type 'hook)
1661 (defcustom org-log-done nil
1662 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1663 When the state of an entry is changed from nothing or a DONE state to
1664 a not-done TODO state, remove a previous closing date.
1666 This can also be a list of symbols indicating under which conditions
1667 the time stamp recording the action should be annotated with a short note.
1668 Valid members of this list are
1670 done Offer to record a note when marking entries done
1671 state Offer to record a note whenever changing the TODO state
1672 of an item. This is only relevant if TODO keywords are
1673 interpreted as sequence, see variable `org-todo-interpretation'.
1674 When `state' is set, this includes tracking `done'.
1675 clock-out Offer to record a note when clocking out of an item.
1677 A separate window will then pop up and allow you to type a note.
1678 After finishing with C-c C-c, the note will be added directly after the
1679 timestamp, as a plain list item. See also the variable
1680 `org-log-note-headings'.
1682 Logging can also be configured on a per-file basis by adding one of
1683 the following lines anywhere in the buffer:
1685 #+STARTUP: logdone
1686 #+STARTUP: nologging
1687 #+STARTUP: lognotedone
1688 #+STARTUP: lognotestate
1689 #+STARTUP: lognoteclock-out
1691 You can have local logging settings for a subtree by setting the LOGGING
1692 property to one or more of these keywords."
1693 :group 'org-todo
1694 :group 'org-progress
1695 :type '(choice
1696 (const :tag "off" nil)
1697 (const :tag "on" t)
1698 (set :tag "on, with notes, detailed control" :greedy t :value (done)
1699 (const :tag "when item is marked DONE" done)
1700 (const :tag "when TODO state changes" state)
1701 (const :tag "when clocking out" clock-out))))
1703 (defcustom org-log-done-with-time t
1704 "Non-nil means, the CLOSED time stamp will contain date and time.
1705 When nil, only the date will be recorded."
1706 :group 'org-progress
1707 :type 'boolean)
1709 (defcustom org-log-note-headings
1710 '((done . "CLOSING NOTE %t")
1711 (state . "State %-12s %t")
1712 (clock-out . ""))
1713 "Headings for notes added when clocking out or closing TODO items.
1714 The value is an alist, with the car being a symbol indicating the note
1715 context, and the cdr is the heading to be used. The heading may also be the
1716 empty string.
1717 %t in the heading will be replaced by a time stamp.
1718 %s will be replaced by the new TODO state, in double quotes.
1719 %u will be replaced by the user name.
1720 %U will be replaced by the full user name."
1721 :group 'org-todo
1722 :group 'org-progress
1723 :type '(list :greedy t
1724 (cons (const :tag "Heading when closing an item" done) string)
1725 (cons (const :tag
1726 "Heading when changing todo state (todo sequence only)"
1727 state) string)
1728 (cons (const :tag "Heading when clocking out" clock-out) string)))
1730 (defcustom org-log-states-order-reversed t
1731 "Non-nil means, the latest state change note will be directly after heading.
1732 When nil, the notes will be orderer according to time."
1733 :group 'org-todo
1734 :group 'org-progress
1735 :type 'boolean)
1737 (defcustom org-log-repeat t
1738 "Non-nil means, prompt for a note when REPEAT is resetting a TODO entry.
1739 When nil, no note will be taken.
1740 This option can also be set with on a per-file-basis with
1742 #+STARTUP: logrepeat
1743 #+STARTUP: nologrepeat
1745 You can have local logging settings for a subtree by setting the LOGGING
1746 property to one or more of these keywords."
1747 :group 'org-todo
1748 :group 'org-progress
1749 :type 'boolean)
1751 (defcustom org-clock-into-drawer 2
1752 "Should clocking info be wrapped into a drawer?
1753 When t, clocking info will always be inserted into a :CLOCK: drawer.
1754 If necessary, the drawer will be created.
1755 When nil, the drawer will not be created, but used when present.
1756 When an integer and the number of clocking entries in an item
1757 reaches or exceeds this number, a drawer will be created."
1758 :group 'org-todo
1759 :group 'org-progress
1760 :type '(choice
1761 (const :tag "Always" t)
1762 (const :tag "Only when drawer exists" nil)
1763 (integer :tag "When at least N clock entries")))
1765 (defcustom org-clock-out-when-done t
1766 "When t, the clock will be stopped when the relevant entry is marked DONE.
1767 Nil means, clock will keep running until stopped explicitly with
1768 `C-c C-x C-o', or until the clock is started in a different item."
1769 :group 'org-progress
1770 :type 'boolean)
1772 (defgroup org-priorities nil
1773 "Priorities in Org-mode."
1774 :tag "Org Priorities"
1775 :group 'org-todo)
1777 (defcustom org-highest-priority ?A
1778 "The highest priority of TODO items. A character like ?A, ?B etc.
1779 Must have a smaller ASCII number than `org-lowest-priority'."
1780 :group 'org-priorities
1781 :type 'character)
1783 (defcustom org-lowest-priority ?C
1784 "The lowest priority of TODO items. A character like ?A, ?B etc.
1785 Must have a larger ASCII number than `org-highest-priority'."
1786 :group 'org-priorities
1787 :type 'character)
1789 (defcustom org-default-priority ?B
1790 "The default priority of TODO items.
1791 This is the priority an item get if no explicit priority is given."
1792 :group 'org-priorities
1793 :type 'character)
1795 (defcustom org-priority-start-cycle-with-default t
1796 "Non-nil means, start with default priority when starting to cycle.
1797 When this is nil, the first step in the cycle will be (depending on the
1798 command used) one higher or lower that the default priority."
1799 :group 'org-priorities
1800 :type 'boolean)
1802 (defgroup org-time nil
1803 "Options concerning time stamps and deadlines in Org-mode."
1804 :tag "Org Time"
1805 :group 'org)
1807 (defcustom org-insert-labeled-timestamps-at-point nil
1808 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1809 When nil, these labeled time stamps are forces into the second line of an
1810 entry, just after the headline. When scheduling from the global TODO list,
1811 the time stamp will always be forced into the second line."
1812 :group 'org-time
1813 :type 'boolean)
1815 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1816 "Formats for `format-time-string' which are used for time stamps.
1817 It is not recommended to change this constant.")
1819 (defcustom org-time-stamp-rounding-minutes 0
1820 "Number of minutes to round time stamps to upon insertion.
1821 When zero, insert the time unmodified. Useful rounding numbers
1822 should be factors of 60, so for example 5, 10, 15.
1823 When this is not zero, you can still force an exact time-stamp by using
1824 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1825 :group 'org-time
1826 :type 'integer)
1828 (defcustom org-display-custom-times nil
1829 "Non-nil means, overlay custom formats over all time stamps.
1830 The formats are defined through the variable `org-time-stamp-custom-formats'.
1831 To turn this on on a per-file basis, insert anywhere in the file:
1832 #+STARTUP: customtime"
1833 :group 'org-time
1834 :set 'set-default
1835 :type 'sexp)
1836 (make-variable-buffer-local 'org-display-custom-times)
1838 (defcustom org-time-stamp-custom-formats
1839 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1840 "Custom formats for time stamps. See `format-time-string' for the syntax.
1841 These are overlayed over the default ISO format if the variable
1842 `org-display-custom-times' is set. Time like %H:%M should be at the
1843 end of the second format."
1844 :group 'org-time
1845 :type 'sexp)
1847 (defun org-time-stamp-format (&optional long inactive)
1848 "Get the right format for a time string."
1849 (let ((f (if long (cdr org-time-stamp-formats)
1850 (car org-time-stamp-formats))))
1851 (if inactive
1852 (concat "[" (substring f 1 -1) "]")
1853 f)))
1855 (defcustom org-read-date-prefer-future t
1856 "Non-nil means, assume future for incomplete date input from user.
1857 This affects the following situations:
1858 1. The user gives a day, but no month.
1859 For example, if today is the 15th, and you enter \"3\", Org-mode will
1860 read this as the third of *next* month. However, if you enter \"17\",
1861 it will be considered as *this* month.
1862 2. The user gives a month but not a year.
1863 For example, if it is april and you enter \"feb 2\", this will be read
1864 as feb 2, *next* year. \"May 5\", however, will be this year.
1866 When this option is nil, the current month and year will always be used
1867 as defaults."
1868 :group 'org-time
1869 :type 'boolean)
1871 (defcustom org-read-date-display-live t
1872 "Non-nil means, display current interpretation of date prompt live.
1873 This display will be in an overlay, in the minibuffer."
1874 :group 'org-time
1875 :type 'boolean)
1877 (defcustom org-read-date-popup-calendar t
1878 "Non-nil means, pop up a calendar when prompting for a date.
1879 In the calendar, the date can be selected with mouse-1. However, the
1880 minibuffer will also be active, and you can simply enter the date as well.
1881 When nil, only the minibuffer will be available."
1882 :group 'org-time
1883 :type 'boolean)
1884 (if (fboundp 'defvaralias)
1885 (defvaralias 'org-popup-calendar-for-date-prompt
1886 'org-read-date-popup-calendar))
1888 (defcustom org-extend-today-until 0
1889 "The hour when your day really ends.
1890 This has influence for the following applications:
1891 - When switching the agenda to \"today\". It it is still earlier than
1892 the time given here, the day recognized as TODAY is actually yesterday.
1893 - When a date is read from the user and it is still before the time given
1894 here, the current date and time will be assumed to be yesterday, 23:59.
1896 FIXME:
1897 IMPORTANT: This is still a very experimental feature, it may disappear
1898 again or it may be extended to mean more things."
1899 :group 'org-time
1900 :type 'number)
1902 (defcustom org-edit-timestamp-down-means-later nil
1903 "Non-nil means, S-down will increase the time in a time stamp.
1904 When nil, S-up will increase."
1905 :group 'org-time
1906 :type 'boolean)
1908 (defcustom org-calendar-follow-timestamp-change t
1909 "Non-nil means, make the calendar window follow timestamp changes.
1910 When a timestamp is modified and the calendar window is visible, it will be
1911 moved to the new date."
1912 :group 'org-time
1913 :type 'boolean)
1915 (defcustom org-clock-heading-function nil
1916 "When non-nil, should be a function to create `org-clock-heading'.
1917 This is the string shown in the mode line when a clock is running.
1918 The function is called with point at the beginning of the headline."
1919 :group 'org-time ; FIXME: Should we have a separate group????
1920 :type 'function)
1922 (defgroup org-tags nil
1923 "Options concerning tags in Org-mode."
1924 :tag "Org Tags"
1925 :group 'org)
1927 (defcustom org-tag-alist nil
1928 "List of tags allowed in Org-mode files.
1929 When this list is nil, Org-mode will base TAG input on what is already in the
1930 buffer.
1931 The value of this variable is an alist, the car of each entry must be a
1932 keyword as a string, the cdr may be a character that is used to select
1933 that tag through the fast-tag-selection interface.
1934 See the manual for details."
1935 :group 'org-tags
1936 :type '(repeat
1937 (choice
1938 (cons (string :tag "Tag name")
1939 (character :tag "Access char"))
1940 (const :tag "Start radio group" (:startgroup))
1941 (const :tag "End radio group" (:endgroup)))))
1943 (defcustom org-use-fast-tag-selection 'auto
1944 "Non-nil means, use fast tag selection scheme.
1945 This is a special interface to select and deselect tags with single keys.
1946 When nil, fast selection is never used.
1947 When the symbol `auto', fast selection is used if and only if selection
1948 characters for tags have been configured, either through the variable
1949 `org-tag-alist' or through a #+TAGS line in the buffer.
1950 When t, fast selection is always used and selection keys are assigned
1951 automatically if necessary."
1952 :group 'org-tags
1953 :type '(choice
1954 (const :tag "Always" t)
1955 (const :tag "Never" nil)
1956 (const :tag "When selection characters are configured" 'auto)))
1958 (defcustom org-fast-tag-selection-single-key nil
1959 "Non-nil means, fast tag selection exits after first change.
1960 When nil, you have to press RET to exit it.
1961 During fast tag selection, you can toggle this flag with `C-c'.
1962 This variable can also have the value `expert'. In this case, the window
1963 displaying the tags menu is not even shown, until you press C-c again."
1964 :group 'org-tags
1965 :type '(choice
1966 (const :tag "No" nil)
1967 (const :tag "Yes" t)
1968 (const :tag "Expert" expert)))
1970 (defvar org-fast-tag-selection-include-todo nil
1971 "Non-nil means, fast tags selection interface will also offer TODO states.
1972 This is an undocumented feature, you should not rely on it.")
1974 (defcustom org-tags-column -80
1975 "The column to which tags should be indented in a headline.
1976 If this number is positive, it specifies the column. If it is negative,
1977 it means that the tags should be flushright to that column. For example,
1978 -80 works well for a normal 80 character screen."
1979 :group 'org-tags
1980 :type 'integer)
1982 (defcustom org-auto-align-tags t
1983 "Non-nil means, realign tags after pro/demotion of TODO state change.
1984 These operations change the length of a headline and therefore shift
1985 the tags around. With this options turned on, after each such operation
1986 the tags are again aligned to `org-tags-column'."
1987 :group 'org-tags
1988 :type 'boolean)
1990 (defcustom org-use-tag-inheritance t
1991 "Non-nil means, tags in levels apply also for sublevels.
1992 When nil, only the tags directly given in a specific line apply there.
1993 If you turn off this option, you very likely want to turn on the
1994 companion option `org-tags-match-list-sublevels'."
1995 :group 'org-tags
1996 :type 'boolean)
1998 (defcustom org-tags-match-list-sublevels nil
1999 "Non-nil means list also sublevels of headlines matching tag search.
2000 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2001 the sublevels of a headline matching a tag search often also match
2002 the same search. Listing all of them can create very long lists.
2003 Setting this variable to nil causes subtrees of a match to be skipped.
2004 This option is off by default, because inheritance in on. If you turn
2005 inheritance off, you very likely want to turn this option on.
2007 As a special case, if the tag search is restricted to TODO items, the
2008 value of this variable is ignored and sublevels are always checked, to
2009 make sure all corresponding TODO items find their way into the list."
2010 :group 'org-tags
2011 :type 'boolean)
2013 (defvar org-tags-history nil
2014 "History of minibuffer reads for tags.")
2015 (defvar org-last-tags-completion-table nil
2016 "The last used completion table for tags.")
2017 (defvar org-after-tags-change-hook nil
2018 "Hook that is run after the tags in a line have changed.")
2020 (defgroup org-properties nil
2021 "Options concerning properties in Org-mode."
2022 :tag "Org Properties"
2023 :group 'org)
2025 (defcustom org-property-format "%-10s %s"
2026 "How property key/value pairs should be formatted by `indent-line'.
2027 When `indent-line' hits a property definition, it will format the line
2028 according to this format, mainly to make sure that the values are
2029 lined-up with respect to each other."
2030 :group 'org-properties
2031 :type 'string)
2033 (defcustom org-use-property-inheritance nil
2034 "Non-nil means, properties apply also for sublevels.
2035 This setting is only relevant during property searches, not when querying
2036 an entry with `org-entry-get'. To retrieve a property with inheritance,
2037 you need to call `org-entry-get' with the inheritance flag.
2038 Turning this on can cause significant overhead when doing a search, so
2039 this is turned off by default.
2040 When nil, only the properties directly given in the current entry count.
2041 The value may also be a list of properties that shouldhave inheritance.
2043 However, note that some special properties use inheritance under special
2044 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2045 and the properties ending in \"_ALL\" when they are used as descriptor
2046 for valid values of a property."
2047 :group 'org-properties
2048 :type '(choice
2049 (const :tag "Not" nil)
2050 (const :tag "Always" nil)
2051 (repeat :tag "Specific properties")))
2053 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2054 "The default column format, if no other format has been defined.
2055 This variable can be set on the per-file basis by inserting a line
2057 #+COLUMNS: %25ITEM ....."
2058 :group 'org-properties
2059 :type 'string)
2061 (defcustom org-global-properties nil
2062 "List of property/value pairs that can be inherited by any entry.
2063 You can set buffer-local values for this by adding lines like
2065 #+PROPERTY: NAME VALUE"
2066 :group 'org-properties
2067 :type '(repeat
2068 (cons (string :tag "Property")
2069 (string :tag "Value"))))
2071 (defvar org-local-properties nil
2072 "List of property/value pairs that can be inherited by any entry.
2073 Valid for the current buffer.
2074 This variable is populated from #+PROPERTY lines.")
2076 (defgroup org-agenda nil
2077 "Options concerning agenda views in Org-mode."
2078 :tag "Org Agenda"
2079 :group 'org)
2081 (defvar org-category nil
2082 "Variable used by org files to set a category for agenda display.
2083 Such files should use a file variable to set it, for example
2085 # -*- mode: org; org-category: \"ELisp\"
2087 or contain a special line
2089 #+CATEGORY: ELisp
2091 If the file does not specify a category, then file's base name
2092 is used instead.")
2093 (make-variable-buffer-local 'org-category)
2095 (defcustom org-agenda-files nil
2096 "The files to be used for agenda display.
2097 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2098 \\[org-remove-file]. You can also use customize to edit the list.
2100 If an entry is a directory, all files in that directory that are matched by
2101 `org-agenda-file-regexp' will be part of the file list.
2103 If the value of the variable is not a list but a single file name, then
2104 the list of agenda files is actually stored and maintained in that file, one
2105 agenda file per line."
2106 :group 'org-agenda
2107 :type '(choice
2108 (repeat :tag "List of files and directories" file)
2109 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2111 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2112 "Regular expression to match files for `org-agenda-files'.
2113 If any element in the list in that variable contains a directory instead
2114 of a normal file, all files in that directory that are matched by this
2115 regular expression will be included."
2116 :group 'org-agenda
2117 :type 'regexp)
2119 (defcustom org-agenda-skip-unavailable-files nil
2120 "t means to just skip non-reachable files in `org-agenda-files'.
2121 Nil means to remove them, after a query, from the list."
2122 :group 'org-agenda
2123 :type 'boolean)
2125 (defcustom org-agenda-multi-occur-extra-files nil
2126 "List of extra files to be searched by `org-occur-in-agenda-files'.
2127 The files in `org-agenda-files' are always searched."
2128 :group 'org-agenda
2129 :type '(repeat file))
2131 (defcustom org-agenda-confirm-kill 1
2132 "When set, remote killing from the agenda buffer needs confirmation.
2133 When t, a confirmation is always needed. When a number N, confirmation is
2134 only needed when the text to be killed contains more than N non-white lines."
2135 :group 'org-agenda
2136 :type '(choice
2137 (const :tag "Never" nil)
2138 (const :tag "Always" t)
2139 (number :tag "When more than N lines")))
2141 (defcustom org-calendar-to-agenda-key [?c]
2142 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2143 The command `org-calendar-goto-agenda' will be bound to this key. The
2144 default is the character `c' because then `c' can be used to switch back and
2145 forth between agenda and calendar."
2146 :group 'org-agenda
2147 :type 'sexp)
2149 (defcustom org-agenda-compact-blocks nil
2150 "Non-nil means, make the block agenda more compact.
2151 This is done by leaving out unnecessary lines."
2152 :group 'org-agenda
2153 :type nil)
2155 (defgroup org-agenda-export nil
2156 "Options concerning exporting agenda views in Org-mode."
2157 :tag "Org Agenda Export"
2158 :group 'org-agenda)
2160 (defcustom org-agenda-with-colors t
2161 "Non-nil means, use colors in agenda views."
2162 :group 'org-agenda-export
2163 :type 'boolean)
2165 (defcustom org-agenda-exporter-settings nil
2166 "Alist of variable/value pairs that should be active during agenda export.
2167 This is a good place to set uptions for ps-print and for htmlize."
2168 :group 'org-agenda-export
2169 :type '(repeat
2170 (list
2171 (variable)
2172 (sexp :tag "Value"))))
2174 (defcustom org-agenda-export-html-style ""
2175 "The style specification for exported HTML Agenda files.
2176 If this variable contains a string, it will replace the default <style>
2177 section as produced by `htmlize'.
2178 Since there are different ways of setting style information, this variable
2179 needs to contain the full HTML structure to provide a style, including the
2180 surrounding HTML tags. The style specifications should include definitions
2181 the fonts used by the agenda, here is an example:
2183 <style type=\"text/css\">
2184 p { font-weight: normal; color: gray; }
2185 .org-agenda-structure {
2186 font-size: 110%;
2187 color: #003399;
2188 font-weight: 600;
2190 .org-todo {
2191 color: #cc6666;Week-agenda:
2192 font-weight: bold;
2194 .org-done {
2195 color: #339933;
2197 .title { text-align: center; }
2198 .todo, .deadline { color: red; }
2199 .done { color: green; }
2200 </style>
2202 or, if you want to keep the style in a file,
2204 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2206 As the value of this option simply gets inserted into the HTML <head> header,
2207 you can \"misuse\" it to also add other text to the header. However,
2208 <style>...</style> is required, if not present the variable will be ignored."
2209 :group 'org-agenda-export
2210 :group 'org-export-html
2211 :type 'string)
2213 (defgroup org-agenda-custom-commands nil
2214 "Options concerning agenda views in Org-mode."
2215 :tag "Org Agenda Custom Commands"
2216 :group 'org-agenda)
2218 (defcustom org-agenda-custom-commands nil
2219 "Custom commands for the agenda.
2220 These commands will be offered on the splash screen displayed by the
2221 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2223 (key desc type match options files)
2225 key The key (one or more characters as a string) to be associated
2226 with the command.
2227 desc A description of the commend, when omitted or nil, a default
2228 description is built using MATCH.
2229 type The command type, any of the following symbols:
2230 todo Entries with a specific TODO keyword, in all agenda files.
2231 tags Tags match in all agenda files.
2232 tags-todo Tags match in all agenda files, TODO entries only.
2233 todo-tree Sparse tree of specific TODO keyword in *current* file.
2234 tags-tree Sparse tree with all tags matches in *current* file.
2235 occur-tree Occur sparse tree for *current* file.
2236 ... A user-defined function.
2237 match What to search for:
2238 - a single keyword for TODO keyword searches
2239 - a tags match expression for tags searches
2240 - a regular expression for occur searches
2241 options A list of option settings, similar to that in a let form, so like
2242 this: ((opt1 val1) (opt2 val2) ...)
2243 files A list of files file to write the produced agenda buffer to
2244 with the command `org-store-agenda-views'.
2245 If a file name ends in \".html\", an HTML version of the buffer
2246 is written out. If it ends in \".ps\", a postscript version is
2247 produced. Otherwide, only the plain text is written to the file.
2249 You can also define a set of commands, to create a composite agenda buffer.
2250 In this case, an entry looks like this:
2252 (key desc (cmd1 cmd2 ...) general-options file)
2254 where
2256 desc A description string to be displayed in the dispatcher menu.
2257 cmd An agenda command, similar to the above. However, tree commands
2258 are no allowed, but instead you can get agenda and global todo list.
2259 So valid commands for a set are:
2260 (agenda)
2261 (alltodo)
2262 (stuck)
2263 (todo \"match\" options files)
2264 (tags \"match\" options files)
2265 (tags-todo \"match\" options files)
2267 Each command can carry a list of options, and another set of options can be
2268 given for the whole set of commands. Individual command options take
2269 precedence over the general options.
2271 When using several characters as key to a command, the first characters
2272 are prefix commands. For the dispatcher to display useful information, you
2273 should provide a description for the prefix, like
2275 (setq org-agenda-custom-commands
2276 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2277 (\"hl\" tags \"+HOME+Lisa\")
2278 (\"hp\" tags \"+HOME+Peter\")
2279 (\"hk\" tags \"+HOME+Kim\")))"
2280 :group 'org-agenda-custom-commands
2281 :type '(repeat
2282 (choice :value ("a" "" tags "" nil)
2283 (list :tag "Single command"
2284 (string :tag "Access Key(s) ")
2285 (option (string :tag "Description"))
2286 (choice
2287 (const :tag "Agenda" agenda)
2288 (const :tag "TODO list" alltodo)
2289 (const :tag "Stuck projects" stuck)
2290 (const :tag "Tags search (all agenda files)" tags)
2291 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2292 (const :tag "TODO keyword search (all agenda files)" todo)
2293 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2294 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2295 (const :tag "Occur tree (current buffer)" occur-tree)
2296 (sexp :tag "Other, user-defined function"))
2297 (string :tag "Match")
2298 (repeat :tag "Local options"
2299 (list (variable :tag "Option") (sexp :tag "Value")))
2300 (option (repeat :tag "Export" (file :tag "Export to"))))
2301 (list :tag "Command series, all agenda files"
2302 (string :tag "Access Key(s)")
2303 (string :tag "Description ")
2304 (repeat
2305 (choice
2306 (const :tag "Agenda" (agenda))
2307 (const :tag "TODO list" (alltodo))
2308 (const :tag "Stuck projects" (stuck))
2309 (list :tag "Tags search"
2310 (const :format "" tags)
2311 (string :tag "Match")
2312 (repeat :tag "Local options"
2313 (list (variable :tag "Option")
2314 (sexp :tag "Value"))))
2316 (list :tag "Tags search, TODO entries only"
2317 (const :format "" tags-todo)
2318 (string :tag "Match")
2319 (repeat :tag "Local options"
2320 (list (variable :tag "Option")
2321 (sexp :tag "Value"))))
2323 (list :tag "TODO keyword search"
2324 (const :format "" todo)
2325 (string :tag "Match")
2326 (repeat :tag "Local options"
2327 (list (variable :tag "Option")
2328 (sexp :tag "Value"))))
2330 (list :tag "Other, user-defined function"
2331 (symbol :tag "function")
2332 (string :tag "Match")
2333 (repeat :tag "Local options"
2334 (list (variable :tag "Option")
2335 (sexp :tag "Value"))))))
2337 (repeat :tag "General options"
2338 (list (variable :tag "Option")
2339 (sexp :tag "Value")))
2340 (option (repeat :tag "Export" (file :tag "Export to"))))
2341 (cons :tag "Prefix key documentation"
2342 (string :tag "Access Key(s)")
2343 (string :tag "Description ")))))
2345 (defcustom org-stuck-projects
2346 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2347 "How to identify stuck projects.
2348 This is a list of four items:
2349 1. A tags/todo matcher string that is used to identify a project.
2350 The entire tree below a headline matched by this is considered one project.
2351 2. A list of TODO keywords identifying non-stuck projects.
2352 If the project subtree contains any headline with one of these todo
2353 keywords, the project is considered to be not stuck. If you specify
2354 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2355 3. A list of tags identifying non-stuck projects.
2356 If the project subtree contains any headline with one of these tags,
2357 the project is considered to be not stuck. If you specify \"*\" as
2358 a tag, any tag will mark the project unstuck.
2359 4. An arbitrary regular expression matching non-stuck projects.
2361 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2362 or `C-c a #' to produce the list."
2363 :group 'org-agenda-custom-commands
2364 :type '(list
2365 (string :tag "Tags/TODO match to identify a project")
2366 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2367 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2368 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2371 (defgroup org-agenda-skip nil
2372 "Options concerning skipping parts of agenda files."
2373 :tag "Org Agenda Skip"
2374 :group 'org-agenda)
2376 (defcustom org-agenda-todo-list-sublevels t
2377 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2378 When nil, the sublevels of a TODO entry are not checked, resulting in
2379 potentially much shorter TODO lists."
2380 :group 'org-agenda-skip
2381 :group 'org-todo
2382 :type 'boolean)
2384 (defcustom org-agenda-todo-ignore-with-date nil
2385 "Non-nil means, don't show entries with a date in the global todo list.
2386 You can use this if you prefer to mark mere appointments with a TODO keyword,
2387 but don't want them to show up in the TODO list.
2388 When this is set, it also covers deadlines and scheduled items, the settings
2389 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2390 will be ignored."
2391 :group 'org-agenda-skip
2392 :group 'org-todo
2393 :type 'boolean)
2395 (defcustom org-agenda-todo-ignore-scheduled nil
2396 "Non-nil means, don't show scheduled entries in the global todo list.
2397 The idea behind this is that by scheduling it, you have already taken care
2398 of this item.
2399 See also `org-agenda-todo-ignore-with-date'."
2400 :group 'org-agenda-skip
2401 :group 'org-todo
2402 :type 'boolean)
2404 (defcustom org-agenda-todo-ignore-deadlines nil
2405 "Non-nil means, don't show near deadline entries in the global todo list.
2406 Near means closer than `org-deadline-warning-days' days.
2407 The idea behind this is that such items will appear in the agenda anyway.
2408 See also `org-agenda-todo-ignore-with-date'."
2409 :group 'org-agenda-skip
2410 :group 'org-todo
2411 :type 'boolean)
2413 (defcustom org-agenda-skip-scheduled-if-done nil
2414 "Non-nil means don't show scheduled items in agenda when they are done.
2415 This is relevant for the daily/weekly agenda, not for the TODO list. And
2416 it applies only to the actual date of the scheduling. Warnings about
2417 an item with a past scheduling dates are always turned off when the item
2418 is DONE."
2419 :group 'org-agenda-skip
2420 :type 'boolean)
2422 (defcustom org-agenda-skip-deadline-if-done nil
2423 "Non-nil means don't show deadines when the corresponding item is done.
2424 When nil, the deadline is still shown and should give you a happy feeling.
2425 This is relevant for the daily/weekly agenda. And it applied only to the
2426 actualy date of the deadline. Warnings about approching and past-due
2427 deadlines are always turned off when the item is DONE."
2428 :group 'org-agenda-skip
2429 :type 'boolean)
2431 (defcustom org-agenda-skip-timestamp-if-done nil
2432 "Non-nil means don't don't select item by timestamp or -range if it is DONE."
2433 :group 'org-agenda-skip
2434 :type 'boolean)
2436 (defcustom org-timeline-show-empty-dates 3
2437 "Non-nil means, `org-timeline' also shows dates without an entry.
2438 When nil, only the days which actually have entries are shown.
2439 When t, all days between the first and the last date are shown.
2440 When an integer, show also empty dates, but if there is a gap of more than
2441 N days, just insert a special line indicating the size of the gap."
2442 :group 'org-agenda-skip
2443 :type '(choice
2444 (const :tag "None" nil)
2445 (const :tag "All" t)
2446 (number :tag "at most")))
2449 (defgroup org-agenda-startup nil
2450 "Options concerning initial settings in the Agenda in Org Mode."
2451 :tag "Org Agenda Startup"
2452 :group 'org-agenda)
2454 (defcustom org-finalize-agenda-hook nil
2455 "Hook run just before displaying an agenda buffer."
2456 :group 'org-agenda-startup
2457 :type 'hook)
2459 (defcustom org-agenda-mouse-1-follows-link nil
2460 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2461 A longer mouse click will still set point. Does not wortk on XEmacs.
2462 Needs to be set before org.el is loaded."
2463 :group 'org-agenda-startup
2464 :type 'boolean)
2466 (defcustom org-agenda-start-with-follow-mode nil
2467 "The initial value of follow-mode in a newly created agenda window."
2468 :group 'org-agenda-startup
2469 :type 'boolean)
2471 (defgroup org-agenda-windows nil
2472 "Options concerning the windows used by the Agenda in Org Mode."
2473 :tag "Org Agenda Windows"
2474 :group 'org-agenda)
2476 (defcustom org-agenda-window-setup 'reorganize-frame
2477 "How the agenda buffer should be displayed.
2478 Possible values for this option are:
2480 current-window Show agenda in the current window, keeping all other windows.
2481 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2482 other-window Use `switch-to-buffer-other-window' to display agenda.
2483 reorganize-frame Show only two windows on the current frame, the current
2484 window and the agenda.
2485 See also the variable `org-agenda-restore-windows-after-quit'."
2486 :group 'org-agenda-windows
2487 :type '(choice
2488 (const current-window)
2489 (const other-frame)
2490 (const other-window)
2491 (const reorganize-frame)))
2493 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2494 "The min and max height of the agenda window as a fraction of frame height.
2495 The value of the variable is a cons cell with two numbers between 0 and 1.
2496 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2497 :group 'org-agenda-windows
2498 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2500 (defcustom org-agenda-restore-windows-after-quit nil
2501 "Non-nil means, restore window configuration open exiting agenda.
2502 Before the window configuration is changed for displaying the agenda,
2503 the current status is recorded. When the agenda is exited with
2504 `q' or `x' and this option is set, the old state is restored. If
2505 `org-agenda-window-setup' is `other-frame', the value of this
2506 option will be ignored.."
2507 :group 'org-agenda-windows
2508 :type 'boolean)
2510 (defcustom org-indirect-buffer-display 'other-window
2511 "How should indirect tree buffers be displayed?
2512 This applies to indirect buffers created with the commands
2513 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2514 Valid values are:
2515 current-window Display in the current window
2516 other-window Just display in another window.
2517 dedicated-frame Create one new frame, and re-use it each time.
2518 new-frame Make a new frame each time. Note that in this case
2519 previously-made indirect buffers are kept, and you need to
2520 kill these buffers yourself."
2521 :group 'org-structure
2522 :group 'org-agenda-windows
2523 :type '(choice
2524 (const :tag "In current window" current-window)
2525 (const :tag "In current frame, other window" other-window)
2526 (const :tag "Each time a new frame" new-frame)
2527 (const :tag "One dedicated frame" dedicated-frame)))
2529 (defgroup org-agenda-daily/weekly nil
2530 "Options concerning the daily/weekly agenda."
2531 :tag "Org Agenda Daily/Weekly"
2532 :group 'org-agenda)
2534 (defcustom org-agenda-ndays 7
2535 "Number of days to include in overview display.
2536 Should be 1 or 7."
2537 :group 'org-agenda-daily/weekly
2538 :type 'number)
2540 (defcustom org-agenda-start-on-weekday 1
2541 "Non-nil means, start the overview always on the specified weekday.
2542 0 denotes Sunday, 1 denotes Monday etc.
2543 When nil, always start on the current day."
2544 :group 'org-agenda-daily/weekly
2545 :type '(choice (const :tag "Today" nil)
2546 (number :tag "Weekday No.")))
2548 (defcustom org-agenda-show-all-dates t
2549 "Non-nil means, `org-agenda' shows every day in the selected range.
2550 When nil, only the days which actually have entries are shown."
2551 :group 'org-agenda-daily/weekly
2552 :type 'boolean)
2554 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2555 "Format string for displaying dates in the agenda.
2556 Used by the daily/weekly agenda and by the timeline. This should be
2557 a format string understood by `format-time-string', or a function returning
2558 the formatted date as a string. The function must take a single argument,
2559 a calendar-style date list like (month day year)."
2560 :group 'org-agenda-daily/weekly
2561 :type '(choice
2562 (string :tag "Format string")
2563 (function :tag "Function")))
2565 (defun org-agenda-format-date-aligned (date)
2566 "Format a date string for display in the daily/weekly agenda, or timeline.
2567 This function makes sure that dates are aligned for easy reading."
2568 (format "%-9s %2d %s %4d"
2569 (calendar-day-name date)
2570 (extract-calendar-day date)
2571 (calendar-month-name (extract-calendar-month date))
2572 (extract-calendar-year date)))
2574 (defcustom org-agenda-include-diary nil
2575 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2576 :group 'org-agenda-daily/weekly
2577 :type 'boolean)
2579 (defcustom org-agenda-include-all-todo nil
2580 "Set means weekly/daily agenda will always contain all TODO entries.
2581 The TODO entries will be listed at the top of the agenda, before
2582 the entries for specific days."
2583 :group 'org-agenda-daily/weekly
2584 :type 'boolean)
2586 (defcustom org-agenda-repeating-timestamp-show-all t
2587 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2588 When nil, only one occurence is shown, either today or the
2589 nearest into the future."
2590 :group 'org-agenda-daily/weekly
2591 :type 'boolean)
2593 (defcustom org-deadline-warning-days 14
2594 "No. of days before expiration during which a deadline becomes active.
2595 This variable governs the display in sparse trees and in the agenda.
2596 When negative, it means use this number (the absolute value of it)
2597 even if a deadline has a different individual lead time specified."
2598 :group 'org-time
2599 :group 'org-agenda-daily/weekly
2600 :type 'number)
2602 (defcustom org-scheduled-past-days 10000
2603 "No. of days to continue listing scheduled items that are not marked DONE.
2604 When an item is scheduled on a date, it shows up in the agenda on this
2605 day and will be listed until it is marked done for the number of days
2606 given here."
2607 :group 'org-agenda-daily/weekly
2608 :type 'number)
2610 (defgroup org-agenda-time-grid nil
2611 "Options concerning the time grid in the Org-mode Agenda."
2612 :tag "Org Agenda Time Grid"
2613 :group 'org-agenda)
2615 (defcustom org-agenda-use-time-grid t
2616 "Non-nil means, show a time grid in the agenda schedule.
2617 A time grid is a set of lines for specific times (like every two hours between
2618 8:00 and 20:00). The items scheduled for a day at specific times are
2619 sorted in between these lines.
2620 For details about when the grid will be shown, and what it will look like, see
2621 the variable `org-agenda-time-grid'."
2622 :group 'org-agenda-time-grid
2623 :type 'boolean)
2625 (defcustom org-agenda-time-grid
2626 '((daily today require-timed)
2627 "----------------"
2628 (800 1000 1200 1400 1600 1800 2000))
2630 "The settings for time grid for agenda display.
2631 This is a list of three items. The first item is again a list. It contains
2632 symbols specifying conditions when the grid should be displayed:
2634 daily if the agenda shows a single day
2635 weekly if the agenda shows an entire week
2636 today show grid on current date, independent of daily/weekly display
2637 require-timed show grid only if at least one item has a time specification
2639 The second item is a string which will be places behing the grid time.
2641 The third item is a list of integers, indicating the times that should have
2642 a grid line."
2643 :group 'org-agenda-time-grid
2644 :type
2645 '(list
2646 (set :greedy t :tag "Grid Display Options"
2647 (const :tag "Show grid in single day agenda display" daily)
2648 (const :tag "Show grid in weekly agenda display" weekly)
2649 (const :tag "Always show grid for today" today)
2650 (const :tag "Show grid only if any timed entries are present"
2651 require-timed)
2652 (const :tag "Skip grid times already present in an entry"
2653 remove-match))
2654 (string :tag "Grid String")
2655 (repeat :tag "Grid Times" (integer :tag "Time"))))
2657 (defgroup org-agenda-sorting nil
2658 "Options concerning sorting in the Org-mode Agenda."
2659 :tag "Org Agenda Sorting"
2660 :group 'org-agenda)
2662 (defconst org-sorting-choice
2663 '(choice
2664 (const time-up) (const time-down)
2665 (const category-keep) (const category-up) (const category-down)
2666 (const tag-down) (const tag-up)
2667 (const priority-up) (const priority-down))
2668 "Sorting choices.")
2670 (defcustom org-agenda-sorting-strategy
2671 '((agenda time-up category-keep priority-down)
2672 (todo category-keep priority-down)
2673 (tags category-keep priority-down))
2674 "Sorting structure for the agenda items of a single day.
2675 This is a list of symbols which will be used in sequence to determine
2676 if an entry should be listed before another entry. The following
2677 symbols are recognized:
2679 time-up Put entries with time-of-day indications first, early first
2680 time-down Put entries with time-of-day indications first, late first
2681 category-keep Keep the default order of categories, corresponding to the
2682 sequence in `org-agenda-files'.
2683 category-up Sort alphabetically by category, A-Z.
2684 category-down Sort alphabetically by category, Z-A.
2685 tag-up Sort alphabetically by last tag, A-Z.
2686 tag-down Sort alphabetically by last tag, Z-A.
2687 priority-up Sort numerically by priority, high priority last.
2688 priority-down Sort numerically by priority, high priority first.
2690 The different possibilities will be tried in sequence, and testing stops
2691 if one comparison returns a \"not-equal\". For example, the default
2692 '(time-up category-keep priority-down)
2693 means: Pull out all entries having a specified time of day and sort them,
2694 in order to make a time schedule for the current day the first thing in the
2695 agenda listing for the day. Of the entries without a time indication, keep
2696 the grouped in categories, don't sort the categories, but keep them in
2697 the sequence given in `org-agenda-files'. Within each category sort by
2698 priority.
2700 Leaving out `category-keep' would mean that items will be sorted across
2701 categories by priority.
2703 Instead of a single list, this can also be a set of list for specific
2704 contents, with a context symbol in the car of the list, any of
2705 `agenda', `todo', `tags' for the corresponding agenda views."
2706 :group 'org-agenda-sorting
2707 :type `(choice
2708 (repeat :tag "General" org-sorting-choice)
2709 (list :tag "Individually"
2710 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2711 (repeat ,org-sorting-choice))
2712 (cons (const :tag "Strategy for TODO lists" todo)
2713 (repeat ,org-sorting-choice))
2714 (cons (const :tag "Strategy for Tags matches" tags)
2715 (repeat ,org-sorting-choice)))))
2717 (defcustom org-sort-agenda-notime-is-late t
2718 "Non-nil means, items without time are considered late.
2719 This is only relevant for sorting. When t, items which have no explicit
2720 time like 15:30 will be considered as 99:01, i.e. later than any items which
2721 do have a time. When nil, the default time is before 0:00. You can use this
2722 option to decide if the schedule for today should come before or after timeless
2723 agenda entries."
2724 :group 'org-agenda-sorting
2725 :type 'boolean)
2727 (defgroup org-agenda-line-format nil
2728 "Options concerning the entry prefix in the Org-mode agenda display."
2729 :tag "Org Agenda Line Format"
2730 :group 'org-agenda)
2732 (defcustom org-agenda-prefix-format
2733 '((agenda . " %-12:c%?-12t% s")
2734 (timeline . " % s")
2735 (todo . " %-12:c")
2736 (tags . " %-12:c"))
2737 "Format specifications for the prefix of items in the agenda views.
2738 An alist with four entries, for the different agenda types. The keys to the
2739 sublists are `agenda', `timeline', `todo', and `tags'. The values
2740 are format strings.
2741 This format works similar to a printf format, with the following meaning:
2743 %c the category of the item, \"Diary\" for entries from the diary, or
2744 as given by the CATEGORY keyword or derived from the file name.
2745 %T the *last* tag of the item. Last because inherited tags come
2746 first in the list.
2747 %t the time-of-day specification if one applies to the entry, in the
2748 format HH:MM
2749 %s Scheduling/Deadline information, a short string
2751 All specifiers work basically like the standard `%s' of printf, but may
2752 contain two additional characters: A question mark just after the `%' and
2753 a whitespace/punctuation character just before the final letter.
2755 If the first character after `%' is a question mark, the entire field
2756 will only be included if the corresponding value applies to the
2757 current entry. This is useful for fields which should have fixed
2758 width when present, but zero width when absent. For example,
2759 \"%?-12t\" will result in a 12 character time field if a time of the
2760 day is specified, but will completely disappear in entries which do
2761 not contain a time.
2763 If there is punctuation or whitespace character just before the final
2764 format letter, this character will be appended to the field value if
2765 the value is not empty. For example, the format \"%-12:c\" leads to
2766 \"Diary: \" if the category is \"Diary\". If the category were be
2767 empty, no additional colon would be interted.
2769 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2770 - Indent the line with two space characters
2771 - Give the category in a 12 chars wide field, padded with whitespace on
2772 the right (because of `-'). Append a colon if there is a category
2773 (because of `:').
2774 - If there is a time-of-day, put it into a 12 chars wide field. If no
2775 time, don't put in an empty field, just skip it (because of '?').
2776 - Finally, put the scheduling information and append a whitespace.
2778 As another example, if you don't want the time-of-day of entries in
2779 the prefix, you could use:
2781 (setq org-agenda-prefix-format \" %-11:c% s\")
2783 See also the variables `org-agenda-remove-times-when-in-prefix' and
2784 `org-agenda-remove-tags'."
2785 :type '(choice
2786 (string :tag "General format")
2787 (list :greedy t :tag "View dependent"
2788 (cons (const agenda) (string :tag "Format"))
2789 (cons (const timeline) (string :tag "Format"))
2790 (cons (const todo) (string :tag "Format"))
2791 (cons (const tags) (string :tag "Format"))))
2792 :group 'org-agenda-line-format)
2794 (defvar org-prefix-format-compiled nil
2795 "The compiled version of the most recently used prefix format.
2796 See the variable `org-agenda-prefix-format'.")
2798 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
2799 "Text preceeding scheduled items in the agenda view.
2800 THis is a list with two strings. The first applies when the item is
2801 scheduled on the current day. The second applies when it has been scheduled
2802 previously, it may contain a %d to capture how many days ago the item was
2803 scheduled."
2804 :group 'org-agenda-line-format
2805 :type '(list
2806 (string :tag "Scheduled today ")
2807 (string :tag "Scheduled previously")))
2809 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
2810 "Text preceeding deadline items in the agenda view.
2811 This is a list with two strings. The first applies when the item has its
2812 deadline on the current day. The second applies when it is in the past or
2813 in the future, it may contain %d to capture how many days away the deadline
2814 is (was)."
2815 :group 'org-agenda-line-format
2816 :type '(list
2817 (string :tag "Deadline today ")
2818 (string :tag "Deadline relative")))
2820 (defcustom org-agenda-remove-times-when-in-prefix t
2821 "Non-nil means, remove duplicate time specifications in agenda items.
2822 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2823 time-of-day specification in a headline or diary entry is extracted and
2824 placed into the prefix. If this option is non-nil, the original specification
2825 \(a timestamp or -range, or just a plain time(range) specification like
2826 11:30-4pm) will be removed for agenda display. This makes the agenda less
2827 cluttered.
2828 The option can be t or nil. It may also be the symbol `beg', indicating
2829 that the time should only be removed what it is located at the beginning of
2830 the headline/diary entry."
2831 :group 'org-agenda-line-format
2832 :type '(choice
2833 (const :tag "Always" t)
2834 (const :tag "Never" nil)
2835 (const :tag "When at beginning of entry" beg)))
2838 (defcustom org-agenda-default-appointment-duration nil
2839 "Default duration for appointments that only have a starting time.
2840 When nil, no duration is specified in such cases.
2841 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
2842 :group 'org-agenda-line-format
2843 :type '(choice
2844 (integer :tag "Minutes")
2845 (const :tag "No default duration")))
2848 (defcustom org-agenda-remove-tags nil
2849 "Non-nil means, remove the tags from the headline copy in the agenda.
2850 When this is the symbol `prefix', only remove tags when
2851 `org-agenda-prefix-format' contains a `%T' specifier."
2852 :group 'org-agenda-line-format
2853 :type '(choice
2854 (const :tag "Always" t)
2855 (const :tag "Never" nil)
2856 (const :tag "When prefix format contains %T" prefix)))
2858 (if (fboundp 'defvaralias)
2859 (defvaralias 'org-agenda-remove-tags-when-in-prefix
2860 'org-agenda-remove-tags))
2862 (defcustom org-agenda-tags-column -80
2863 "Shift tags in agenda items to this column.
2864 If this number is positive, it specifies the column. If it is negative,
2865 it means that the tags should be flushright to that column. For example,
2866 -80 works well for a normal 80 character screen."
2867 :group 'org-agenda-line-format
2868 :type 'integer)
2870 (if (fboundp 'defvaralias)
2871 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
2873 (defcustom org-agenda-fontify-priorities t
2874 "Non-nil means, highlight low and high priorities in agenda.
2875 When t, the highest priority entries are bold, lowest priority italic.
2876 This may also be an association list of priority faces. The face may be
2877 a names face, or a list like `(:background \"Red\")'."
2878 :group 'org-agenda-line-format
2879 :type '(choice
2880 (const :tag "Never" nil)
2881 (const :tag "Defaults" t)
2882 (repeat :tag "Specify"
2883 (list (character :tag "Priority" :value ?A)
2884 (sexp :tag "face")))))
2886 (defgroup org-latex nil
2887 "Options for embedding LaTeX code into Org-mode"
2888 :tag "Org LaTeX"
2889 :group 'org)
2891 (defcustom org-format-latex-options
2892 '(:foreground default :background default :scale 1.0
2893 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2894 :matchers ("begin" "$" "$$" "\\(" "\\["))
2895 "Options for creating images from LaTeX fragments.
2896 This is a property list with the following properties:
2897 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
2898 `default' means use the forground of the default face.
2899 :background the background color, or \"Transparent\".
2900 `default' means use the background of the default face.
2901 :scale a scaling factor for the size of the images
2902 :html-foreground, :html-background, :html-scale
2903 The same numbers for HTML export.
2904 :matchers a list indicating which matchers should be used to
2905 find LaTeX fragments. Valid members of this list are:
2906 \"begin\" find environments
2907 \"$\" find math expressions surrounded by $...$
2908 \"$$\" find math expressions surrounded by $$....$$
2909 \"\\(\" find math expressions surrounded by \\(...\\)
2910 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2911 :group 'org-latex
2912 :type 'plist)
2914 (defcustom org-format-latex-header "\\documentclass{article}
2915 \\usepackage{fullpage} % do not remove
2916 \\usepackage{amssymb}
2917 \\usepackage[usenames]{color}
2918 \\usepackage{amsmath}
2919 \\usepackage{latexsym}
2920 \\usepackage[mathscr]{eucal}
2921 \\pagestyle{empty} % do not remove"
2922 "The document header used for processing LaTeX fragments."
2923 :group 'org-latex
2924 :type 'string)
2926 (defgroup org-export nil
2927 "Options for exporting org-listings."
2928 :tag "Org Export"
2929 :group 'org)
2931 (defgroup org-export-general nil
2932 "General options for exporting Org-mode files."
2933 :tag "Org Export General"
2934 :group 'org-export)
2936 ;; FIXME
2937 (defvar org-export-publishing-directory nil)
2939 (defcustom org-export-with-special-strings t
2940 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
2941 When this option is turned on, these strings will be exported as:
2943 Org HTML LaTeX
2944 -----+----------+--------
2945 \\- &shy; \\-
2946 -- &ndash; --
2947 --- &mdash; ---
2948 ... &hellip; \ldots
2950 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
2951 :group 'org-export-translation
2952 :type 'boolean)
2954 (defcustom org-export-language-setup
2955 '(("en" "Author" "Date" "Table of Contents")
2956 ("cs" "Autor" "Datum" "Obsah")
2957 ("da" "Ophavsmand" "Dato" "Indhold")
2958 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
2959 ("es" "Autor" "Fecha" "\xcdndice")
2960 ("fr" "Auteur" "Date" "Table des mati\xe8res")
2961 ("it" "Autore" "Data" "Indice")
2962 ("nl" "Auteur" "Datum" "Inhoudsopgave")
2963 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
2964 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
2965 "Terms used in export text, translated to different languages.
2966 Use the variable `org-export-default-language' to set the language,
2967 or use the +OPTION lines for a per-file setting."
2968 :group 'org-export-general
2969 :type '(repeat
2970 (list
2971 (string :tag "HTML language tag")
2972 (string :tag "Author")
2973 (string :tag "Date")
2974 (string :tag "Table of Contents"))))
2976 (defcustom org-export-default-language "en"
2977 "The default language of HTML export, as a string.
2978 This should have an association in `org-export-language-setup'."
2979 :group 'org-export-general
2980 :type 'string)
2982 (defcustom org-export-skip-text-before-1st-heading t
2983 "Non-nil means, skip all text before the first headline when exporting.
2984 When nil, that text is exported as well."
2985 :group 'org-export-general
2986 :type 'boolean)
2988 (defcustom org-export-headline-levels 3
2989 "The last level which is still exported as a headline.
2990 Inferior levels will produce itemize lists when exported.
2991 Note that a numeric prefix argument to an exporter function overrides
2992 this setting.
2994 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
2995 :group 'org-export-general
2996 :type 'number)
2998 (defcustom org-export-with-section-numbers t
2999 "Non-nil means, add section numbers to headlines when exporting.
3001 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
3002 :group 'org-export-general
3003 :type 'boolean)
3005 (defcustom org-export-with-toc t
3006 "Non-nil means, create a table of contents in exported files.
3007 The TOC contains headlines with levels up to`org-export-headline-levels'.
3008 When an integer, include levels up to N in the toc, this may then be
3009 different from `org-export-headline-levels', but it will not be allowed
3010 to be larger than the number of headline levels.
3011 When nil, no table of contents is made.
3013 Headlines which contain any TODO items will be marked with \"(*)\" in
3014 ASCII export, and with red color in HTML output, if the option
3015 `org-export-mark-todo-in-toc' is set.
3017 In HTML output, the TOC will be clickable.
3019 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
3020 or \"toc:3\"."
3021 :group 'org-export-general
3022 :type '(choice
3023 (const :tag "No Table of Contents" nil)
3024 (const :tag "Full Table of Contents" t)
3025 (integer :tag "TOC to level")))
3027 (defcustom org-export-mark-todo-in-toc nil
3028 "Non-nil means, mark TOC lines that contain any open TODO items."
3029 :group 'org-export-general
3030 :type 'boolean)
3032 (defcustom org-export-preserve-breaks nil
3033 "Non-nil means, preserve all line breaks when exporting.
3034 Normally, in HTML output paragraphs will be reformatted. In ASCII
3035 export, line breaks will always be preserved, regardless of this variable.
3037 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3038 :group 'org-export-general
3039 :type 'boolean)
3041 (defcustom org-export-with-archived-trees 'headline
3042 "Whether subtrees with the ARCHIVE tag should be exported.
3043 This can have three different values
3044 nil Do not export, pretend this tree is not present
3045 t Do export the entire tree
3046 headline Only export the headline, but skip the tree below it."
3047 :group 'org-export-general
3048 :group 'org-archive
3049 :type '(choice
3050 (const :tag "not at all" nil)
3051 (const :tag "headline only" 'headline)
3052 (const :tag "entirely" t)))
3054 (defcustom org-export-author-info t
3055 "Non-nil means, insert author name and email into the exported file.
3057 This option can also be set with the +OPTIONS line,
3058 e.g. \"author-info:nil\"."
3059 :group 'org-export-general
3060 :type 'boolean)
3062 (defcustom org-export-time-stamp-file t
3063 "Non-nil means, insert a time stamp into the exported file.
3064 The time stamp shows when the file was created.
3066 This option can also be set with the +OPTIONS line,
3067 e.g. \"timestamp:nil\"."
3068 :group 'org-export-general
3069 :type 'boolean)
3071 (defcustom org-export-with-timestamps t
3072 "If nil, do not export time stamps and associated keywords."
3073 :group 'org-export-general
3074 :type 'boolean)
3076 (defcustom org-export-remove-timestamps-from-toc t
3077 "If nil, remove timestamps from the table of contents entries."
3078 :group 'org-export-general
3079 :type 'boolean)
3081 (defcustom org-export-with-tags 'not-in-toc
3082 "If nil, do not export tags, just remove them from headlines.
3083 If this is the symbol `not-in-toc', tags will be removed from table of
3084 contents entries, but still be shown in the headlines of the document.
3086 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3087 :group 'org-export-general
3088 :type '(choice
3089 (const :tag "Off" nil)
3090 (const :tag "Not in TOC" not-in-toc)
3091 (const :tag "On" t)))
3093 (defcustom org-export-with-drawers nil
3094 "Non-nil means, export with drawers like the property drawer.
3095 When t, all drawers are exported. This may also be a list of
3096 drawer names to export."
3097 :group 'org-export-general
3098 :type '(choice
3099 (const :tag "All drawers" t)
3100 (const :tag "None" nil)
3101 (repeat :tag "Selected drawers"
3102 (string :tag "Drawer name"))))
3104 (defgroup org-export-translation nil
3105 "Options for translating special ascii sequences for the export backends."
3106 :tag "Org Export Translation"
3107 :group 'org-export)
3109 (defcustom org-export-with-emphasize t
3110 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3111 If the export target supports emphasizing text, the word will be
3112 typeset in bold, italic, or underlined, respectively. Works only for
3113 single words, but you can say: I *really* *mean* *this*.
3114 Not all export backends support this.
3116 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3117 :group 'org-export-translation
3118 :type 'boolean)
3120 (defcustom org-export-with-footnotes t
3121 "If nil, export [1] as a footnote marker.
3122 Lines starting with [1] will be formatted as footnotes.
3124 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3125 :group 'org-export-translation
3126 :type 'boolean)
3128 (defcustom org-export-with-sub-superscripts t
3129 "Non-nil means, interpret \"_\" and \"^\" for export.
3130 When this option is turned on, you can use TeX-like syntax for sub- and
3131 superscripts. Several characters after \"_\" or \"^\" will be
3132 considered as a single item - so grouping with {} is normally not
3133 needed. For example, the following things will be parsed as single
3134 sub- or superscripts.
3136 10^24 or 10^tau several digits will be considered 1 item.
3137 10^-12 or 10^-tau a leading sign with digits or a word
3138 x^2-y^3 will be read as x^2 - y^3, because items are
3139 terminated by almost any nonword/nondigit char.
3140 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3142 Still, ambiguity is possible - so when in doubt use {} to enclose the
3143 sub/superscript. If you set this variable to the symbol `{}',
3144 the braces are *required* in order to trigger interpretations as
3145 sub/superscript. This can be helpful in documents that need \"_\"
3146 frequently in plain text.
3148 Not all export backends support this, but HTML does.
3150 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3151 :group 'org-export-translation
3152 :type '(choice
3153 (const :tag "Always interpret" t)
3154 (const :tag "Only with braces" {})
3155 (const :tag "Never interpret" nil)))
3157 (defcustom org-export-with-special-strings t
3158 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3159 When this option is turned on, these strings will be exported as:
3161 \\- : &shy;
3162 -- : &ndash;
3163 --- : &mdash;
3165 Not all export backends support this, but HTML does.
3167 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3168 :group 'org-export-translation
3169 :type 'boolean)
3171 (defcustom org-export-with-TeX-macros t
3172 "Non-nil means, interpret simple TeX-like macros when exporting.
3173 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3174 No only real TeX macros will work here, but the standard HTML entities
3175 for math can be used as macro names as well. For a list of supported
3176 names in HTML export, see the constant `org-html-entities'.
3177 Not all export backends support this.
3179 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3180 :group 'org-export-translation
3181 :group 'org-export-latex
3182 :type 'boolean)
3184 (defcustom org-export-with-LaTeX-fragments nil
3185 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3186 When set, the exporter will find LaTeX environments if the \\begin line is
3187 the first non-white thing on a line. It will also find the math delimiters
3188 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3189 display math.
3191 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3192 :group 'org-export-translation
3193 :group 'org-export-latex
3194 :type 'boolean)
3196 (defcustom org-export-with-fixed-width t
3197 "Non-nil means, lines starting with \":\" will be in fixed width font.
3198 This can be used to have pre-formatted text, fragments of code etc. For
3199 example:
3200 : ;; Some Lisp examples
3201 : (while (defc cnt)
3202 : (ding))
3203 will be looking just like this in also HTML. See also the QUOTE keyword.
3204 Not all export backends support this.
3206 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3207 :group 'org-export-translation
3208 :type 'boolean)
3210 (defcustom org-match-sexp-depth 3
3211 "Number of stacked braces for sub/superscript matching.
3212 This has to be set before loading org.el to be effective."
3213 :group 'org-export-translation
3214 :type 'integer)
3216 (defgroup org-export-tables nil
3217 "Options for exporting tables in Org-mode."
3218 :tag "Org Export Tables"
3219 :group 'org-export)
3221 (defcustom org-export-with-tables t
3222 "If non-nil, lines starting with \"|\" define a table.
3223 For example:
3225 | Name | Address | Birthday |
3226 |-------------+----------+-----------|
3227 | Arthur Dent | England | 29.2.2100 |
3229 Not all export backends support this.
3231 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3232 :group 'org-export-tables
3233 :type 'boolean)
3235 (defcustom org-export-highlight-first-table-line t
3236 "Non-nil means, highlight the first table line.
3237 In HTML export, this means use <th> instead of <td>.
3238 In tables created with table.el, this applies to the first table line.
3239 In Org-mode tables, all lines before the first horizontal separator
3240 line will be formatted with <th> tags."
3241 :group 'org-export-tables
3242 :type 'boolean)
3244 (defcustom org-export-table-remove-special-lines t
3245 "Remove special lines and marking characters in calculating tables.
3246 This removes the special marking character column from tables that are set
3247 up for spreadsheet calculations. It also removes the entire lines
3248 marked with `!', `_', or `^'. The lines with `$' are kept, because
3249 the values of constants may be useful to have."
3250 :group 'org-export-tables
3251 :type 'boolean)
3253 (defcustom org-export-prefer-native-exporter-for-tables nil
3254 "Non-nil means, always export tables created with table.el natively.
3255 Natively means, use the HTML code generator in table.el.
3256 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3257 the table does not use row- or column-spanning). This has the
3258 advantage, that the automatic HTML conversions for math symbols and
3259 sub/superscripts can be applied. Org-mode's HTML generator is also
3260 much faster."
3261 :group 'org-export-tables
3262 :type 'boolean)
3264 (defgroup org-export-ascii nil
3265 "Options specific for ASCII export of Org-mode files."
3266 :tag "Org Export ASCII"
3267 :group 'org-export)
3269 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3270 "Characters for underlining headings in ASCII export.
3271 In the given sequence, these characters will be used for level 1, 2, ..."
3272 :group 'org-export-ascii
3273 :type '(repeat character))
3275 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3276 "Bullet characters for headlines converted to lists in ASCII export.
3277 The first character is is used for the first lest level generated in this
3278 way, and so on. If there are more levels than characters given here,
3279 the list will be repeated.
3280 Note that plain lists will keep the same bullets as the have in the
3281 Org-mode file."
3282 :group 'org-export-ascii
3283 :type '(repeat character))
3285 (defgroup org-export-xml nil
3286 "Options specific for XML export of Org-mode files."
3287 :tag "Org Export XML"
3288 :group 'org-export)
3290 (defgroup org-export-html nil
3291 "Options specific for HTML export of Org-mode files."
3292 :tag "Org Export HTML"
3293 :group 'org-export)
3295 (defcustom org-export-html-coding-system nil
3297 :group 'org-export-html
3298 :type 'coding-system)
3300 (defcustom org-export-html-extension "html"
3301 "The extension for exported HTML files."
3302 :group 'org-export-html
3303 :type 'string)
3305 (defcustom org-export-html-style
3306 "<style type=\"text/css\">
3307 html {
3308 font-family: Times, serif;
3309 font-size: 12pt;
3311 .title { text-align: center; }
3312 .todo { color: red; }
3313 .done { color: green; }
3314 .timestamp { color: grey }
3315 .timestamp-kwd { color: CadetBlue }
3316 .tag { background-color:lightblue; font-weight:normal }
3317 .target { background-color: lavender; }
3318 pre {
3319 border: 1pt solid #AEBDCC;
3320 background-color: #F3F5F7;
3321 padding: 5pt;
3322 font-family: courier, monospace;
3324 table { border-collapse: collapse; }
3325 td, th {
3326 vertical-align: top;
3327 <!--border: 1pt solid #ADB9CC;-->
3329 </style>"
3330 "The default style specification for exported HTML files.
3331 Since there are different ways of setting style information, this variable
3332 needs to contain the full HTML structure to provide a style, including the
3333 surrounding HTML tags. The style specifications should include definitions
3334 for new classes todo, done, title, and deadline. For example, legal values
3335 would be:
3337 <style type=\"text/css\">
3338 p { font-weight: normal; color: gray; }
3339 h1 { color: black; }
3340 .title { text-align: center; }
3341 .todo, .deadline { color: red; }
3342 .done { color: green; }
3343 </style>
3345 or, if you want to keep the style in a file,
3347 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3349 As the value of this option simply gets inserted into the HTML <head> header,
3350 you can \"misuse\" it to add arbitrary text to the header."
3351 :group 'org-export-html
3352 :type 'string)
3355 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3356 "Format for typesetting the document title in HTML export."
3357 :group 'org-export-html
3358 :type 'string)
3360 (defcustom org-export-html-toplevel-hlevel 2
3361 "The <H> level for level 1 headings in HTML export."
3362 :group 'org-export-html
3363 :type 'string)
3365 (defcustom org-export-html-link-org-files-as-html t
3366 "Non-nil means, make file links to `file.org' point to `file.html'.
3367 When org-mode is exporting an org-mode file to HTML, links to
3368 non-html files are directly put into a href tag in HTML.
3369 However, links to other Org-mode files (recognized by the
3370 extension `.org.) should become links to the corresponding html
3371 file, assuming that the linked org-mode file will also be
3372 converted to HTML.
3373 When nil, the links still point to the plain `.org' file."
3374 :group 'org-export-html
3375 :type 'boolean)
3377 (defcustom org-export-html-inline-images 'maybe
3378 "Non-nil means, inline images into exported HTML pages.
3379 This is done using an <img> tag. When nil, an anchor with href is used to
3380 link to the image. If this option is `maybe', then images in links with
3381 an empty description will be inlined, while images with a description will
3382 be linked only."
3383 :group 'org-export-html
3384 :type '(choice (const :tag "Never" nil)
3385 (const :tag "Always" t)
3386 (const :tag "When there is no description" maybe)))
3388 ;; FIXME: rename
3389 (defcustom org-export-html-expand t
3390 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3391 When nil, these tags will be exported as plain text and therefore
3392 not be interpreted by a browser.
3394 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3395 :group 'org-export-html
3396 :type 'boolean)
3398 (defcustom org-export-html-table-tag
3399 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3400 "The HTML tag that is used to start a table.
3401 This must be a <table> tag, but you may change the options like
3402 borders and spacing."
3403 :group 'org-export-html
3404 :type 'string)
3406 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3407 "The opening tag for table header fields.
3408 This is customizable so that alignment options can be specified."
3409 :group 'org-export-tables
3410 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3412 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3413 "The opening tag for table data fields.
3414 This is customizable so that alignment options can be specified."
3415 :group 'org-export-tables
3416 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3418 (defcustom org-export-html-with-timestamp nil
3419 "If non-nil, write `org-export-html-html-helper-timestamp'
3420 into the exported HTML text. Otherwise, the buffer will just be saved
3421 to a file."
3422 :group 'org-export-html
3423 :type 'boolean)
3425 (defcustom org-export-html-html-helper-timestamp
3426 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3427 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3428 :group 'org-export-html
3429 :type 'string)
3431 (defgroup org-export-icalendar nil
3432 "Options specific for iCalendar export of Org-mode files."
3433 :tag "Org Export iCalendar"
3434 :group 'org-export)
3436 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3437 "The file name for the iCalendar file covering all agenda files.
3438 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3439 The file name should be absolute, the file will be overwritten without warning."
3440 :group 'org-export-icalendar
3441 :type 'file)
3443 (defcustom org-icalendar-include-todo nil
3444 "Non-nil means, export to iCalendar files should also cover TODO items."
3445 :group 'org-export-icalendar
3446 :type '(choice
3447 (const :tag "None" nil)
3448 (const :tag "Unfinished" t)
3449 (const :tag "All" all)))
3451 (defcustom org-icalendar-include-sexps t
3452 "Non-nil means, export to iCalendar files should also cover sexp entries.
3453 These are entries like in the diary, but directly in an Org-mode file."
3454 :group 'org-export-icalendar
3455 :type 'boolean)
3457 (defcustom org-icalendar-include-body 100
3458 "Amount of text below headline to be included in iCalendar export.
3459 This is a number of characters that should maximally be included.
3460 Properties, scheduling and clocking lines will always be removed.
3461 The text will be inserted into the DESCRIPTION field."
3462 :group 'org-export-icalendar
3463 :type '(choice
3464 (const :tag "Nothing" nil)
3465 (const :tag "Everything" t)
3466 (integer :tag "Max characters")))
3468 (defcustom org-icalendar-combined-name "OrgMode"
3469 "Calendar name for the combined iCalendar representing all agenda files."
3470 :group 'org-export-icalendar
3471 :type 'string)
3473 (defgroup org-font-lock nil
3474 "Font-lock settings for highlighting in Org-mode."
3475 :tag "Org Font Lock"
3476 :group 'org)
3478 (defcustom org-level-color-stars-only nil
3479 "Non-nil means fontify only the stars in each headline.
3480 When nil, the entire headline is fontified.
3481 Changing it requires restart of `font-lock-mode' to become effective
3482 also in regions already fontified."
3483 :group 'org-font-lock
3484 :type 'boolean)
3486 (defcustom org-hide-leading-stars nil
3487 "Non-nil means, hide the first N-1 stars in a headline.
3488 This works by using the face `org-hide' for these stars. This
3489 face is white for a light background, and black for a dark
3490 background. You may have to customize the face `org-hide' to
3491 make this work.
3492 Changing it requires restart of `font-lock-mode' to become effective
3493 also in regions already fontified.
3494 You may also set this on a per-file basis by adding one of the following
3495 lines to the buffer:
3497 #+STARTUP: hidestars
3498 #+STARTUP: showstars"
3499 :group 'org-font-lock
3500 :type 'boolean)
3502 (defcustom org-fontify-done-headline nil
3503 "Non-nil means, change the face of a headline if it is marked DONE.
3504 Normally, only the TODO/DONE keyword indicates the state of a headline.
3505 When this is non-nil, the headline after the keyword is set to the
3506 `org-headline-done' as an additional indication."
3507 :group 'org-font-lock
3508 :type 'boolean)
3510 (defcustom org-fontify-emphasized-text t
3511 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3512 Changing this variable requires a restart of Emacs to take effect."
3513 :group 'org-font-lock
3514 :type 'boolean)
3516 (defcustom org-highlight-latex-fragments-and-specials nil
3517 "Non-nil means, fontify what is treated specially by the exporters."
3518 :group 'org-font-lock
3519 :type 'boolean)
3521 (defcustom org-hide-emphasis-markers nil
3522 "Non-nil mean font-lock should hide the emphasis marker characters."
3523 :group 'org-font-lock
3524 :type 'boolean)
3526 (defvar org-emph-re nil
3527 "Regular expression for matching emphasis.")
3528 (defvar org-verbatim-re nil
3529 "Regular expression for matching verbatim text.")
3530 (defvar org-emphasis-regexp-components) ; defined just below
3531 (defvar org-emphasis-alist) ; defined just below
3532 (defun org-set-emph-re (var val)
3533 "Set variable and compute the emphasis regular expression."
3534 (set var val)
3535 (when (and (boundp 'org-emphasis-alist)
3536 (boundp 'org-emphasis-regexp-components)
3537 org-emphasis-alist org-emphasis-regexp-components)
3538 (let* ((e org-emphasis-regexp-components)
3539 (pre (car e))
3540 (post (nth 1 e))
3541 (border (nth 2 e))
3542 (body (nth 3 e))
3543 (nl (nth 4 e))
3544 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3545 (body1 (concat body "*?"))
3546 (markers (mapconcat 'car org-emphasis-alist ""))
3547 (vmarkers (mapconcat
3548 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3549 org-emphasis-alist "")))
3550 ;; make sure special characters appear at the right position in the class
3551 (if (string-match "\\^" markers)
3552 (setq markers (concat (replace-match "" t t markers) "^")))
3553 (if (string-match "-" markers)
3554 (setq markers (concat (replace-match "" t t markers) "-")))
3555 (if (string-match "\\^" vmarkers)
3556 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3557 (if (string-match "-" vmarkers)
3558 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3559 (if (> nl 0)
3560 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3561 (int-to-string nl) "\\}")))
3562 ;; Make the regexp
3563 (setq org-emph-re
3564 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3565 "\\("
3566 "\\([" markers "]\\)"
3567 "\\("
3568 "[^" border "]\\|"
3569 "[^" border (if (and nil stacked) markers) "]"
3570 body1
3571 "[^" border (if (and nil stacked) markers) "]"
3572 "\\)"
3573 "\\3\\)"
3574 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3575 (setq org-verbatim-re
3576 (concat "\\([" pre "]\\|^\\)"
3577 "\\("
3578 "\\([" vmarkers "]\\)"
3579 "\\("
3580 "[^" border "]\\|"
3581 "[^" border "]"
3582 body1
3583 "[^" border "]"
3584 "\\)"
3585 "\\3\\)"
3586 "\\([" post "]\\|$\\)")))))
3588 (defcustom org-emphasis-regexp-components
3589 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3590 "Components used to build the regular expression for emphasis.
3591 This is a list with 6 entries. Terminology: In an emphasis string
3592 like \" *strong word* \", we call the initial space PREMATCH, the final
3593 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3594 and \"trong wor\" is the body. The different components in this variable
3595 specify what is allowed/forbidden in each part:
3597 pre Chars allowed as prematch. Beginning of line will be allowed too.
3598 post Chars allowed as postmatch. End of line will be allowed too.
3599 border The chars *forbidden* as border characters.
3600 body-regexp A regexp like \".\" to match a body character. Don't use
3601 non-shy groups here, and don't allow newline here.
3602 newline The maximum number of newlines allowed in an emphasis exp.
3604 Use customize to modify this, or restart Emacs after changing it."
3605 :group 'org-font-lock
3606 :set 'org-set-emph-re
3607 :type '(list
3608 (sexp :tag "Allowed chars in pre ")
3609 (sexp :tag "Allowed chars in post ")
3610 (sexp :tag "Forbidden chars in border ")
3611 (sexp :tag "Regexp for body ")
3612 (integer :tag "number of newlines allowed")
3613 (option (boolean :tag "Stacking (DISABLED) "))))
3615 (defcustom org-emphasis-alist
3616 '(("*" bold "<b>" "</b>")
3617 ("/" italic "<i>" "</i>")
3618 ("_" underline "<u>" "</u>")
3619 ("=" org-code "<code>" "</code>" verbatim)
3620 ("~" org-verbatim "" "" verbatim)
3621 ("+" (:strike-through t) "<del>" "</del>")
3623 "Special syntax for emphasized text.
3624 Text starting and ending with a special character will be emphasized, for
3625 example *bold*, _underlined_ and /italic/. This variable sets the marker
3626 characters, the face to be used by font-lock for highlighting in Org-mode
3627 Emacs buffers, and the HTML tags to be used for this.
3628 Use customize to modify this, or restart Emacs after changing it."
3629 :group 'org-font-lock
3630 :set 'org-set-emph-re
3631 :type '(repeat
3632 (list
3633 (string :tag "Marker character")
3634 (choice
3635 (face :tag "Font-lock-face")
3636 (plist :tag "Face property list"))
3637 (string :tag "HTML start tag")
3638 (string :tag "HTML end tag")
3639 (option (const verbatim)))))
3641 ;;; The faces
3643 (defgroup org-faces nil
3644 "Faces in Org-mode."
3645 :tag "Org Faces"
3646 :group 'org-font-lock)
3648 (defun org-compatible-face (inherits specs)
3649 "Make a compatible face specification.
3650 If INHERITS is an existing face and if the Emacs version supports it,
3651 just inherit the face. If not, use SPECS to define the face.
3652 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3653 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3654 to the top of the list. The `min-colors' attribute will be removed from
3655 any other entries, and any resulting duplicates will be removed entirely."
3656 (cond
3657 ((and inherits (facep inherits)
3658 (not (featurep 'xemacs)) (> emacs-major-version 22))
3659 ;; In Emacs 23, we use inheritance where possible.
3660 ;; We only do this in Emacs 23, because only there the outline
3661 ;; faces have been changed to the original org-mode-level-faces.
3662 (list (list t :inherit inherits)))
3663 ((or (featurep 'xemacs) (< emacs-major-version 22))
3664 ;; These do not understand the `min-colors' attribute.
3665 (let (r e a)
3666 (while (setq e (pop specs))
3667 (cond
3668 ((memq (car e) '(t default)) (push e r))
3669 ((setq a (member '(min-colors 8) (car e)))
3670 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3671 (cdr e)))))
3672 ((setq a (assq 'min-colors (car e)))
3673 (setq e (cons (delq a (car e)) (cdr e)))
3674 (or (assoc (car e) r) (push e r)))
3675 (t (or (assoc (car e) r) (push e r)))))
3676 (nreverse r)))
3677 (t specs)))
3678 (put 'org-compatible-face 'lisp-indent-function 1)
3680 (defface org-hide
3681 '((((background light)) (:foreground "white"))
3682 (((background dark)) (:foreground "black")))
3683 "Face used to hide leading stars in headlines.
3684 The forground color of this face should be equal to the background
3685 color of the frame."
3686 :group 'org-faces)
3688 (defface org-level-1 ;; font-lock-function-name-face
3689 (org-compatible-face 'outline-1
3690 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3691 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3692 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3693 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3694 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3695 (t (:bold t))))
3696 "Face used for level 1 headlines."
3697 :group 'org-faces)
3699 (defface org-level-2 ;; font-lock-variable-name-face
3700 (org-compatible-face 'outline-2
3701 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3702 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3703 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3704 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3705 (t (:bold t))))
3706 "Face used for level 2 headlines."
3707 :group 'org-faces)
3709 (defface org-level-3 ;; font-lock-keyword-face
3710 (org-compatible-face 'outline-3
3711 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3712 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3713 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3714 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3715 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3716 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3717 (t (:bold t))))
3718 "Face used for level 3 headlines."
3719 :group 'org-faces)
3721 (defface org-level-4 ;; font-lock-comment-face
3722 (org-compatible-face 'outline-4
3723 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3724 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3725 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3726 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3727 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3728 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3729 (t (:bold t))))
3730 "Face used for level 4 headlines."
3731 :group 'org-faces)
3733 (defface org-level-5 ;; font-lock-type-face
3734 (org-compatible-face 'outline-5
3735 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3736 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3737 (((class color) (min-colors 8)) (:foreground "green"))))
3738 "Face used for level 5 headlines."
3739 :group 'org-faces)
3741 (defface org-level-6 ;; font-lock-constant-face
3742 (org-compatible-face 'outline-6
3743 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3744 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3745 (((class color) (min-colors 8)) (:foreground "magenta"))))
3746 "Face used for level 6 headlines."
3747 :group 'org-faces)
3749 (defface org-level-7 ;; font-lock-builtin-face
3750 (org-compatible-face 'outline-7
3751 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3752 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3753 (((class color) (min-colors 8)) (:foreground "blue"))))
3754 "Face used for level 7 headlines."
3755 :group 'org-faces)
3757 (defface org-level-8 ;; font-lock-string-face
3758 (org-compatible-face 'outline-8
3759 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3760 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3761 (((class color) (min-colors 8)) (:foreground "green"))))
3762 "Face used for level 8 headlines."
3763 :group 'org-faces)
3765 (defface org-special-keyword ;; font-lock-string-face
3766 (org-compatible-face nil
3767 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3768 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3769 (t (:italic t))))
3770 "Face used for special keywords."
3771 :group 'org-faces)
3773 (defface org-drawer ;; font-lock-function-name-face
3774 (org-compatible-face nil
3775 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3776 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3777 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3778 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3779 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3780 (t (:bold t))))
3781 "Face used for drawers."
3782 :group 'org-faces)
3784 (defface org-property-value nil
3785 "Face used for the value of a property."
3786 :group 'org-faces)
3788 (defface org-column
3789 (org-compatible-face nil
3790 '((((class color) (min-colors 16) (background light))
3791 (:background "grey90"))
3792 (((class color) (min-colors 16) (background dark))
3793 (:background "grey30"))
3794 (((class color) (min-colors 8))
3795 (:background "cyan" :foreground "black"))
3796 (t (:inverse-video t))))
3797 "Face for column display of entry properties."
3798 :group 'org-faces)
3800 (when (fboundp 'set-face-attribute)
3801 ;; Make sure that a fixed-width face is used when we have a column table.
3802 (set-face-attribute 'org-column nil
3803 :height (face-attribute 'default :height)
3804 :family (face-attribute 'default :family)))
3806 (defface org-warning
3807 (org-compatible-face 'font-lock-warning-face
3808 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3809 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3810 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3811 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3812 (t (:bold t))))
3813 "Face for deadlines and TODO keywords."
3814 :group 'org-faces)
3816 (defface org-archived ; similar to shadow
3817 (org-compatible-face 'shadow
3818 '((((class color grayscale) (min-colors 88) (background light))
3819 (:foreground "grey50"))
3820 (((class color grayscale) (min-colors 88) (background dark))
3821 (:foreground "grey70"))
3822 (((class color) (min-colors 8) (background light))
3823 (:foreground "green"))
3824 (((class color) (min-colors 8) (background dark))
3825 (:foreground "yellow"))))
3826 "Face for headline with the ARCHIVE tag."
3827 :group 'org-faces)
3829 (defface org-link
3830 '((((class color) (background light)) (:foreground "Purple" :underline t))
3831 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3832 (t (:underline t)))
3833 "Face for links."
3834 :group 'org-faces)
3836 (defface org-ellipsis
3837 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
3838 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
3839 (t (:strike-through t)))
3840 "Face for the ellipsis in folded text."
3841 :group 'org-faces)
3843 (defface org-target
3844 '((((class color) (background light)) (:underline t))
3845 (((class color) (background dark)) (:underline t))
3846 (t (:underline t)))
3847 "Face for links."
3848 :group 'org-faces)
3850 (defface org-date
3851 '((((class color) (background light)) (:foreground "Purple" :underline t))
3852 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3853 (t (:underline t)))
3854 "Face for links."
3855 :group 'org-faces)
3857 (defface org-sexp-date
3858 '((((class color) (background light)) (:foreground "Purple"))
3859 (((class color) (background dark)) (:foreground "Cyan"))
3860 (t (:underline t)))
3861 "Face for links."
3862 :group 'org-faces)
3864 (defface org-tag
3865 '((t (:bold t)))
3866 "Face for tags."
3867 :group 'org-faces)
3869 (defface org-todo ; font-lock-warning-face
3870 (org-compatible-face nil
3871 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3872 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3873 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3874 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3875 (t (:inverse-video t :bold t))))
3876 "Face for TODO keywords."
3877 :group 'org-faces)
3879 (defface org-done ;; font-lock-type-face
3880 (org-compatible-face nil
3881 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
3882 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
3883 (((class color) (min-colors 8)) (:foreground "green"))
3884 (t (:bold t))))
3885 "Face used for todo keywords that indicate DONE items."
3886 :group 'org-faces)
3888 (defface org-headline-done ;; font-lock-string-face
3889 (org-compatible-face nil
3890 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3891 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3892 (((class color) (min-colors 8) (background light)) (:bold nil))))
3893 "Face used to indicate that a headline is DONE.
3894 This face is only used if `org-fontify-done-headline' is set. If applies
3895 to the part of the headline after the DONE keyword."
3896 :group 'org-faces)
3898 (defcustom org-todo-keyword-faces nil
3899 "Faces for specific TODO keywords.
3900 This is a list of cons cells, with TODO keywords in the car
3901 and faces in the cdr. The face can be a symbol, or a property
3902 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
3903 :group 'org-faces
3904 :group 'org-todo
3905 :type '(repeat
3906 (cons
3907 (string :tag "keyword")
3908 (sexp :tag "face"))))
3910 (defface org-table ;; font-lock-function-name-face
3911 (org-compatible-face nil
3912 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3913 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3914 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3915 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3916 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
3917 (((class color) (min-colors 8) (background dark)))))
3918 "Face used for tables."
3919 :group 'org-faces)
3921 (defface org-formula
3922 (org-compatible-face nil
3923 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3924 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3925 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3926 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
3927 (t (:bold t :italic t))))
3928 "Face for formulas."
3929 :group 'org-faces)
3931 (defface org-code
3932 (org-compatible-face nil
3933 '((((class color grayscale) (min-colors 88) (background light))
3934 (:foreground "grey50"))
3935 (((class color grayscale) (min-colors 88) (background dark))
3936 (:foreground "grey70"))
3937 (((class color) (min-colors 8) (background light))
3938 (:foreground "green"))
3939 (((class color) (min-colors 8) (background dark))
3940 (:foreground "yellow"))))
3941 "Face for fixed-with text like code snippets."
3942 :group 'org-faces
3943 :version "22.1")
3945 (defface org-verbatim
3946 (org-compatible-face nil
3947 '((((class color grayscale) (min-colors 88) (background light))
3948 (:foreground "grey50" :underline t))
3949 (((class color grayscale) (min-colors 88) (background dark))
3950 (:foreground "grey70" :underline t))
3951 (((class color) (min-colors 8) (background light))
3952 (:foreground "green" :underline t))
3953 (((class color) (min-colors 8) (background dark))
3954 (:foreground "yellow" :underline t))))
3955 "Face for fixed-with text like code snippets."
3956 :group 'org-faces
3957 :version "22.1")
3959 (defface org-agenda-structure ;; font-lock-function-name-face
3960 (org-compatible-face nil
3961 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3962 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3963 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3964 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3965 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3966 (t (:bold t))))
3967 "Face used in agenda for captions and dates."
3968 :group 'org-faces)
3970 (defface org-scheduled-today
3971 (org-compatible-face nil
3972 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
3973 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
3974 (((class color) (min-colors 8)) (:foreground "green"))
3975 (t (:bold t :italic t))))
3976 "Face for items scheduled for a certain day."
3977 :group 'org-faces)
3979 (defface org-scheduled-previously
3980 (org-compatible-face nil
3981 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3982 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3983 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3984 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3985 (t (:bold t))))
3986 "Face for items scheduled previously, and not yet done."
3987 :group 'org-faces)
3989 (defface org-upcoming-deadline
3990 (org-compatible-face nil
3991 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3992 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3993 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3994 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3995 (t (:bold t))))
3996 "Face for items scheduled previously, and not yet done."
3997 :group 'org-faces)
3999 (defcustom org-agenda-deadline-faces
4000 '((1.0 . org-warning)
4001 (0.5 . org-upcoming-deadline)
4002 (0.0 . default))
4003 "Faces for showing deadlines in the agenda.
4004 This is a list of cons cells. The cdr of each cess is a face to be used,
4005 and it can also just be a like like '(:foreground \"yellow\").
4006 Each car is a fraction of the head-warning time that must have passed for
4007 this the face in the cdr to be used for display. The numbers must be
4008 given in descending order. The head-warning time is normally taken
4009 from `org-deadline-warning-days', but can also be specified in the deadline
4010 timestamp itself, like this:
4012 DEADLINE: <2007-08-13 Mon -8d>
4014 You may use d for days, w for weeks, m for months and y for years. Months
4015 and years will only be treated in an approximate fashion (30.4 days for a
4016 month and 365.24 days for a year)."
4017 :group 'org-faces
4018 :group 'org-agenda-daily/weekly
4019 :type '(repeat
4020 (cons
4021 (number :tag "Fraction of head-warning time passed")
4022 (sexp :tag "Face"))))
4024 ;; FIXME: this is not a good face yet.
4025 (defface org-agenda-restriction-lock
4026 (org-compatible-face nil
4027 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
4028 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
4029 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
4030 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
4031 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
4032 (t (:inverse-video t))))
4033 "Face for showing the agenda restriction lock."
4034 :group 'org-faces)
4036 (defface org-time-grid ;; font-lock-variable-name-face
4037 (org-compatible-face nil
4038 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4039 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4040 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4041 "Face used for time grids."
4042 :group 'org-faces)
4044 (defconst org-level-faces
4045 '(org-level-1 org-level-2 org-level-3 org-level-4
4046 org-level-5 org-level-6 org-level-7 org-level-8
4049 (defcustom org-n-level-faces (length org-level-faces)
4050 "The number different faces to be used for headlines.
4051 Org-mode defines 8 different headline faces, so this can be at most 8.
4052 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4053 :type 'number
4054 :group 'org-faces)
4056 ;;; Functions and variables from ther packages
4057 ;; Declared here to avoid compiler warnings
4059 (eval-and-compile
4060 (unless (fboundp 'declare-function)
4061 (defmacro declare-function (fn file &optional arglist fileonly))))
4063 ;; XEmacs only
4064 (defvar outline-mode-menu-heading)
4065 (defvar outline-mode-menu-show)
4066 (defvar outline-mode-menu-hide)
4067 (defvar zmacs-regions) ; XEmacs regions
4069 ;; Emacs only
4070 (defvar mark-active)
4072 ;; Various packages
4073 ;; FIXME: get the argument lists for the UNKNOWN stuff
4074 (declare-function add-to-diary-list "diary-lib"
4075 (date string specifier &optional marker globcolor literal))
4076 (declare-function table--at-cell-p "table" (position &optional object at-column))
4077 (declare-function Info-find-node "info" (filename nodename &optional no-going-back))
4078 (declare-function Info-goto-node "info" (nodename &optional fork))
4079 (declare-function bbdb "ext:bbdb-com" (string elidep))
4080 (declare-function bbdb-company "ext:bbdb-com" (string elidep))
4081 (declare-function bbdb-current-record "ext:bbdb-com" (&optional planning-on-modifying))
4082 (declare-function bbdb-name "ext:bbdb-com" (string elidep))
4083 (declare-function bbdb-record-getprop "ext:bbdb" (record property))
4084 (declare-function bbdb-record-name "ext:bbdb" (record))
4085 (declare-function bibtex-beginning-of-entry "bibtex" ())
4086 (declare-function bibtex-generate-autokey "bibtex" ())
4087 (declare-function bibtex-parse-entry "bibtex" (&optional content))
4088 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
4089 (defvar calc-embedded-close-formula)
4090 (defvar calc-embedded-open-formula)
4091 (declare-function calendar-astro-date-string "cal-julian" (&optional date))
4092 (declare-function calendar-bahai-date-string "cal-bahai" (&optional date))
4093 (declare-function calendar-check-holidays "holidays" (date))
4094 (declare-function calendar-chinese-date-string "cal-china" (&optional date))
4095 (declare-function calendar-coptic-date-string "cal-coptic" (&optional date))
4096 (declare-function calendar-ethiopic-date-string "cal-coptic" (&optional date))
4097 (declare-function calendar-forward-day "cal-move" (arg))
4098 (declare-function calendar-french-date-string "cal-french" (&optional date))
4099 (declare-function calendar-goto-date "cal-move" (date))
4100 (declare-function calendar-goto-today "cal-move" ())
4101 (declare-function calendar-hebrew-date-string "cal-hebrew" (&optional date))
4102 (declare-function calendar-islamic-date-string "cal-islam" (&optional date))
4103 (declare-function calendar-iso-date-string "cal-iso" (&optional date))
4104 (declare-function calendar-julian-date-string "cal-julian" (&optional date))
4105 (declare-function calendar-mayan-date-string "cal-mayan" (&optional date))
4106 (declare-function calendar-persian-date-string "cal-persia" (&optional date))
4107 (defvar calendar-mode-map)
4108 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4109 (declare-function cdlatex-tab "ext:cdlatex" ())
4110 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4111 (declare-function elmo-folder-exists-p "ext:elmo" (folder) t)
4112 (declare-function elmo-message-entity-field "ext:elmo-msgdb" (entity field &optional type))
4113 (declare-function elmo-message-field "ext:elmo" (folder number field &optional type) t)
4114 (declare-function elmo-msgdb-overview-get-entity "ext:elmo" (&rest unknown) t)
4115 (defvar font-lock-unfontify-region-function)
4116 (declare-function gnus-article-show-summary "gnus-art" ())
4117 (declare-function gnus-summary-last-subject "gnus-sum" ())
4118 (defvar gnus-other-frame-object)
4119 (defvar gnus-group-name)
4120 (defvar gnus-article-current)
4121 (defvar Info-current-file)
4122 (defvar Info-current-node)
4123 (declare-function mh-display-msg "mh-show" (msg-num folder-name))
4124 (declare-function mh-find-path "mh-utils" ())
4125 (declare-function mh-get-header-field "mh-utils" (field))
4126 (declare-function mh-get-msg-num "mh-utils" (error-if-no-message))
4127 (declare-function mh-header-display "mh-show" ())
4128 (declare-function mh-index-previous-folder "mh-search" ())
4129 (declare-function mh-normalize-folder-name "mh-utils" (folder &optional empty-string-okay dont-remove-trailing-slash return-nil-if-folder-empty))
4130 (declare-function mh-search "mh-search" (folder search-regexp &optional redo-search-flag window-config))
4131 (declare-function mh-search-choose "mh-search" (&optional searcher))
4132 (declare-function mh-show "mh-show" (&optional message redisplay-flag))
4133 (declare-function mh-show-buffer-message-number "mh-comp" (&optional buffer))
4134 (declare-function mh-show-header-display "mh-show" t t)
4135 (declare-function mh-show-msg "mh-show" (msg))
4136 (declare-function mh-show-show "mh-show" t t)
4137 (declare-function mh-visit-folder "mh-folder" (folder &optional range index-data))
4138 (defvar mh-progs)
4139 (defvar mh-current-folder)
4140 (defvar mh-show-folder-buffer)
4141 (defvar mh-index-folder)
4142 (defvar mh-searcher)
4143 (declare-function org-export-latex-cleaned-string "org-export-latex" (&optional commentsp))
4144 (declare-function parse-time-string "parse-time" (string))
4145 (declare-function remember "remember" (&optional initial))
4146 (declare-function remember-buffer-desc "remember" ())
4147 (defvar remember-save-after-remembering)
4148 (defvar remember-data-file)
4149 (defvar remember-register)
4150 (defvar remember-buffer)
4151 (declare-function rmail-narrow-to-non-pruned-header "rmail" ())
4152 (declare-function rmail-show-message "rmail" (&optional n no-summary))
4153 (declare-function rmail-what-message "rmail" ())
4154 (defvar texmathp-why)
4155 (declare-function vm-beginning-of-message "ext:vm-page" ())
4156 (declare-function vm-follow-summary-cursor "ext:vm-motion" ())
4157 (declare-function vm-get-header-contents "ext:vm-summary" (message header-name-regexp &optional clump-sep))
4158 (declare-function vm-isearch-narrow "ext:vm-search" ())
4159 (declare-function vm-isearch-update "ext:vm-search" ())
4160 (declare-function vm-select-folder-buffer "ext:vm-macro" ())
4161 (declare-function vm-su-message-id "ext:vm-summary" (m))
4162 (declare-function vm-su-subject "ext:vm-summary" (m))
4163 (declare-function vm-summarize "ext:vm-summary" (&optional display raise))
4164 (defvar vm-message-pointer)
4165 (defvar vm-folder-directory)
4166 (defvar w3m-current-url)
4167 (defvar w3m-current-title)
4168 (declare-function wl-summary-buffer-msgdb "ext:wl-folder" (&rest unknown) t)
4169 (declare-function wl-folder-get-elmo-folder "ext:wl-folder" (entity &optional no-cache))
4170 (declare-function wl-summary-goto-folder-subr "ext:wl-summary" (&optional name scan-type other-window sticky interactive scoring force-exit))
4171 (declare-function wl-summary-jump-to-msg-by-message-id "ext:wl-summary" (&optional id))
4172 (declare-function wl-summary-line-from "ext:wl-summary" ())
4173 (declare-function wl-summary-line-subject "ext:wl-summary" ())
4174 (declare-function wl-summary-message-number "ext:wl-summary" ())
4175 (declare-function wl-summary-redisplay "ext:wl-summary" (&optional arg))
4176 (defvar wl-summary-buffer-elmo-folder)
4177 (defvar wl-summary-buffer-folder-name)
4178 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4180 (defvar org-latex-regexps)
4181 (defvar constants-unit-system)
4183 ;;; Variables for pre-computed regular expressions, all buffer local
4185 (defvar org-drawer-regexp nil
4186 "Matches first line of a hidden block.")
4187 (make-variable-buffer-local 'org-drawer-regexp)
4188 (defvar org-todo-regexp nil
4189 "Matches any of the TODO state keywords.")
4190 (make-variable-buffer-local 'org-todo-regexp)
4191 (defvar org-not-done-regexp nil
4192 "Matches any of the TODO state keywords except the last one.")
4193 (make-variable-buffer-local 'org-not-done-regexp)
4194 (defvar org-todo-line-regexp nil
4195 "Matches a headline and puts TODO state into group 2 if present.")
4196 (make-variable-buffer-local 'org-todo-line-regexp)
4197 (defvar org-complex-heading-regexp nil
4198 "Matches a headline and puts everything into groups:
4199 group 1: the stars
4200 group 2: The todo keyword, maybe
4201 group 3: Priority cookie
4202 group 4: True headline
4203 group 5: Tags")
4204 (make-variable-buffer-local 'org-complex-heading-regexp)
4205 (defvar org-todo-line-tags-regexp nil
4206 "Matches a headline and puts TODO state into group 2 if present.
4207 Also put tags into group 4 if tags are present.")
4208 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4209 (defvar org-nl-done-regexp nil
4210 "Matches newline followed by a headline with the DONE keyword.")
4211 (make-variable-buffer-local 'org-nl-done-regexp)
4212 (defvar org-looking-at-done-regexp nil
4213 "Matches the DONE keyword a point.")
4214 (make-variable-buffer-local 'org-looking-at-done-regexp)
4215 (defvar org-ds-keyword-length 12
4216 "Maximum length of the Deadline and SCHEDULED keywords.")
4217 (make-variable-buffer-local 'org-ds-keyword-length)
4218 (defvar org-deadline-regexp nil
4219 "Matches the DEADLINE keyword.")
4220 (make-variable-buffer-local 'org-deadline-regexp)
4221 (defvar org-deadline-time-regexp nil
4222 "Matches the DEADLINE keyword together with a time stamp.")
4223 (make-variable-buffer-local 'org-deadline-time-regexp)
4224 (defvar org-deadline-line-regexp nil
4225 "Matches the DEADLINE keyword and the rest of the line.")
4226 (make-variable-buffer-local 'org-deadline-line-regexp)
4227 (defvar org-scheduled-regexp nil
4228 "Matches the SCHEDULED keyword.")
4229 (make-variable-buffer-local 'org-scheduled-regexp)
4230 (defvar org-scheduled-time-regexp nil
4231 "Matches the SCHEDULED keyword together with a time stamp.")
4232 (make-variable-buffer-local 'org-scheduled-time-regexp)
4233 (defvar org-closed-time-regexp nil
4234 "Matches the CLOSED keyword together with a time stamp.")
4235 (make-variable-buffer-local 'org-closed-time-regexp)
4237 (defvar org-keyword-time-regexp nil
4238 "Matches any of the 4 keywords, together with the time stamp.")
4239 (make-variable-buffer-local 'org-keyword-time-regexp)
4240 (defvar org-keyword-time-not-clock-regexp nil
4241 "Matches any of the 3 keywords, together with the time stamp.")
4242 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4243 (defvar org-maybe-keyword-time-regexp nil
4244 "Matches a timestamp, possibly preceeded by a keyword.")
4245 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4246 (defvar org-planning-or-clock-line-re nil
4247 "Matches a line with planning or clock info.")
4248 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4250 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4251 rear-nonsticky t mouse-map t fontified t)
4252 "Properties to remove when a string without properties is wanted.")
4254 (defsubst org-match-string-no-properties (num &optional string)
4255 (if (featurep 'xemacs)
4256 (let ((s (match-string num string)))
4257 (remove-text-properties 0 (length s) org-rm-props s)
4259 (match-string-no-properties num string)))
4261 (defsubst org-no-properties (s)
4262 (if (fboundp 'set-text-properties)
4263 (set-text-properties 0 (length s) nil s)
4264 (remove-text-properties 0 (length s) org-rm-props s))
4267 (defsubst org-get-alist-option (option key)
4268 (cond ((eq key t) t)
4269 ((eq option t) t)
4270 ((assoc key option) (cdr (assoc key option)))
4271 (t (cdr (assq 'default option)))))
4273 (defsubst org-inhibit-invisibility ()
4274 "Modified `buffer-invisibility-spec' for Emacs 21.
4275 Some ops with invisible text do not work correctly on Emacs 21. For these
4276 we turn off invisibility temporarily. Use this in a `let' form."
4277 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4279 (defsubst org-set-local (var value)
4280 "Make VAR local in current buffer and set it to VALUE."
4281 (set (make-variable-buffer-local var) value))
4283 (defsubst org-mode-p ()
4284 "Check if the current buffer is in Org-mode."
4285 (eq major-mode 'org-mode))
4287 (defsubst org-last (list)
4288 "Return the last element of LIST."
4289 (car (last list)))
4291 (defun org-let (list &rest body)
4292 (eval (cons 'let (cons list body))))
4293 (put 'org-let 'lisp-indent-function 1)
4295 (defun org-let2 (list1 list2 &rest body)
4296 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4297 (put 'org-let2 'lisp-indent-function 2)
4298 (defconst org-startup-options
4299 '(("fold" org-startup-folded t)
4300 ("overview" org-startup-folded t)
4301 ("nofold" org-startup-folded nil)
4302 ("showall" org-startup-folded nil)
4303 ("content" org-startup-folded content)
4304 ("hidestars" org-hide-leading-stars t)
4305 ("showstars" org-hide-leading-stars nil)
4306 ("odd" org-odd-levels-only t)
4307 ("oddeven" org-odd-levels-only nil)
4308 ("align" org-startup-align-all-tables t)
4309 ("noalign" org-startup-align-all-tables nil)
4310 ("customtime" org-display-custom-times t)
4311 ("logging" org-log-done t)
4312 ("logdone" org-log-done t)
4313 ("nologging" org-log-done nil)
4314 ("lognotedone" org-log-done done push)
4315 ("lognotestate" org-log-done state push)
4316 ("lognoteclock-out" org-log-done clock-out push)
4317 ("logrepeat" org-log-repeat t)
4318 ("nologrepeat" org-log-repeat nil)
4319 ("constcgs" constants-unit-system cgs)
4320 ("constSI" constants-unit-system SI))
4321 "Variable associated with STARTUP options for org-mode.
4322 Each element is a list of three items: The startup options as written
4323 in the #+STARTUP line, the corresponding variable, and the value to
4324 set this variable to if the option is found. An optional forth element PUSH
4325 means to push this value onto the list in the variable.")
4327 (defun org-set-regexps-and-options ()
4328 "Precompute regular expressions for current buffer."
4329 (when (org-mode-p)
4330 (org-set-local 'org-todo-kwd-alist nil)
4331 (org-set-local 'org-todo-key-alist nil)
4332 (org-set-local 'org-todo-key-trigger nil)
4333 (org-set-local 'org-todo-keywords-1 nil)
4334 (org-set-local 'org-done-keywords nil)
4335 (org-set-local 'org-todo-heads nil)
4336 (org-set-local 'org-todo-sets nil)
4337 (org-set-local 'org-todo-log-states nil)
4338 (let ((re (org-make-options-regexp
4339 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4340 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4341 "CONSTANTS" "PROPERTY" "DRAWERS")))
4342 (splitre "[ \t]+")
4343 kwds kws0 kwsa key value cat arch tags const links hw dws
4344 tail sep kws1 prio props drawers
4345 ex log)
4346 (save-excursion
4347 (save-restriction
4348 (widen)
4349 (goto-char (point-min))
4350 (while (re-search-forward re nil t)
4351 (setq key (match-string 1) value (org-match-string-no-properties 2))
4352 (cond
4353 ((equal key "CATEGORY")
4354 (if (string-match "[ \t]+$" value)
4355 (setq value (replace-match "" t t value)))
4356 (setq cat value))
4357 ((member key '("SEQ_TODO" "TODO"))
4358 (push (cons 'sequence (org-split-string value splitre)) kwds))
4359 ((equal key "TYP_TODO")
4360 (push (cons 'type (org-split-string value splitre)) kwds))
4361 ((equal key "TAGS")
4362 (setq tags (append tags (org-split-string value splitre))))
4363 ((equal key "COLUMNS")
4364 (org-set-local 'org-columns-default-format value))
4365 ((equal key "LINK")
4366 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4367 (push (cons (match-string 1 value)
4368 (org-trim (match-string 2 value)))
4369 links)))
4370 ((equal key "PRIORITIES")
4371 (setq prio (org-split-string value " +")))
4372 ((equal key "PROPERTY")
4373 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4374 (push (cons (match-string 1 value) (match-string 2 value))
4375 props)))
4376 ((equal key "DRAWERS")
4377 (setq drawers (org-split-string value splitre)))
4378 ((equal key "CONSTANTS")
4379 (setq const (append const (org-split-string value splitre))))
4380 ((equal key "STARTUP")
4381 (let ((opts (org-split-string value splitre))
4382 l var val)
4383 (while (setq l (pop opts))
4384 (when (setq l (assoc l org-startup-options))
4385 (setq var (nth 1 l) val (nth 2 l))
4386 (if (not (nth 3 l))
4387 (set (make-local-variable var) val)
4388 (if (not (listp (symbol-value var)))
4389 (set (make-local-variable var) nil))
4390 (set (make-local-variable var) (symbol-value var))
4391 (add-to-list var val))))))
4392 ((equal key "ARCHIVE")
4393 (string-match " *$" value)
4394 (setq arch (replace-match "" t t value))
4395 (remove-text-properties 0 (length arch)
4396 '(face t fontified t) arch)))
4398 (when cat
4399 (org-set-local 'org-category (intern cat))
4400 (push (cons "CATEGORY" cat) props))
4401 (when prio
4402 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4403 (setq prio (mapcar 'string-to-char prio))
4404 (org-set-local 'org-highest-priority (nth 0 prio))
4405 (org-set-local 'org-lowest-priority (nth 1 prio))
4406 (org-set-local 'org-default-priority (nth 2 prio)))
4407 (and props (org-set-local 'org-local-properties (nreverse props)))
4408 (and drawers (org-set-local 'org-drawers drawers))
4409 (and arch (org-set-local 'org-archive-location arch))
4410 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4411 ;; Process the TODO keywords
4412 (unless kwds
4413 ;; Use the global values as if they had been given locally.
4414 (setq kwds (default-value 'org-todo-keywords))
4415 (if (stringp (car kwds))
4416 (setq kwds (list (cons org-todo-interpretation
4417 (default-value 'org-todo-keywords)))))
4418 (setq kwds (reverse kwds)))
4419 (setq kwds (nreverse kwds))
4420 (let (inter kws kw)
4421 (while (setq kws (pop kwds))
4422 (setq inter (pop kws) sep (member "|" kws)
4423 kws0 (delete "|" (copy-sequence kws))
4424 kwsa nil
4425 kws1 (mapcar
4426 (lambda (x)
4427 (if (string-match "^\\(.*?\\)\\(?:(\\(..?\\))\\)?$" x)
4428 (progn
4429 (setq kw (match-string 1 x)
4430 ex (and (match-end 2) (match-string 2 x))
4431 log (and ex (string-match "@" ex))
4432 key (and ex (substring ex 0 1)))
4433 (if (equal key "@") (setq key nil))
4434 (push (cons kw (and key (string-to-char key))) kwsa)
4435 (and log (push kw org-todo-log-states))
4437 (error "Invalid TODO keyword %s" x)))
4438 kws0)
4439 kwsa (if kwsa (append '((:startgroup))
4440 (nreverse kwsa)
4441 '((:endgroup))))
4442 hw (car kws1)
4443 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4444 tail (list inter hw (car dws) (org-last dws)))
4445 (add-to-list 'org-todo-heads hw 'append)
4446 (push kws1 org-todo-sets)
4447 (setq org-done-keywords (append org-done-keywords dws nil))
4448 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4449 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4450 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4451 (setq org-todo-sets (nreverse org-todo-sets)
4452 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4453 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4454 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4455 ;; Process the constants
4456 (when const
4457 (let (e cst)
4458 (while (setq e (pop const))
4459 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4460 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4461 (setq org-table-formula-constants-local cst)))
4463 ;; Process the tags.
4464 (when tags
4465 (let (e tgs)
4466 (while (setq e (pop tags))
4467 (cond
4468 ((equal e "{") (push '(:startgroup) tgs))
4469 ((equal e "}") (push '(:endgroup) tgs))
4470 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4471 (push (cons (match-string 1 e)
4472 (string-to-char (match-string 2 e)))
4473 tgs))
4474 (t (push (list e) tgs))))
4475 (org-set-local 'org-tag-alist nil)
4476 (while (setq e (pop tgs))
4477 (or (and (stringp (car e))
4478 (assoc (car e) org-tag-alist))
4479 (push e org-tag-alist))))))
4481 ;; Compute the regular expressions and other local variables
4482 (if (not org-done-keywords)
4483 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4484 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4485 (length org-scheduled-string)))
4486 org-drawer-regexp
4487 (concat "^[ \t]*:\\("
4488 (mapconcat 'regexp-quote org-drawers "\\|")
4489 "\\):[ \t]*$")
4490 org-not-done-keywords
4491 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4492 org-todo-regexp
4493 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4494 "\\|") "\\)\\>")
4495 org-not-done-regexp
4496 (concat "\\<\\("
4497 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4498 "\\)\\>")
4499 org-todo-line-regexp
4500 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4501 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4502 "\\)\\>\\)?[ \t]*\\(.*\\)")
4503 org-complex-heading-regexp
4504 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4505 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4506 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4507 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4508 org-nl-done-regexp
4509 (concat "\n\\*+[ \t]+"
4510 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4511 "\\)" "\\>")
4512 org-todo-line-tags-regexp
4513 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4514 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4515 (org-re
4516 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4517 org-looking-at-done-regexp
4518 (concat "^" "\\(?:"
4519 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4520 "\\>")
4521 org-deadline-regexp (concat "\\<" org-deadline-string)
4522 org-deadline-time-regexp
4523 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4524 org-deadline-line-regexp
4525 (concat "\\<\\(" org-deadline-string "\\).*")
4526 org-scheduled-regexp
4527 (concat "\\<" org-scheduled-string)
4528 org-scheduled-time-regexp
4529 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4530 org-closed-time-regexp
4531 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4532 org-keyword-time-regexp
4533 (concat "\\<\\(" org-scheduled-string
4534 "\\|" org-deadline-string
4535 "\\|" org-closed-string
4536 "\\|" org-clock-string "\\)"
4537 " *[[<]\\([^]>]+\\)[]>]")
4538 org-keyword-time-not-clock-regexp
4539 (concat "\\<\\(" org-scheduled-string
4540 "\\|" org-deadline-string
4541 "\\|" org-closed-string
4542 "\\)"
4543 " *[[<]\\([^]>]+\\)[]>]")
4544 org-maybe-keyword-time-regexp
4545 (concat "\\(\\<\\(" org-scheduled-string
4546 "\\|" org-deadline-string
4547 "\\|" org-closed-string
4548 "\\|" org-clock-string "\\)\\)?"
4549 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4550 org-planning-or-clock-line-re
4551 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4552 "\\|" org-deadline-string
4553 "\\|" org-closed-string "\\|" org-clock-string
4554 "\\)\\>\\)")
4556 (org-compute-latex-and-specials-regexp)
4557 (org-set-font-lock-defaults)))
4559 (defun org-remove-keyword-keys (list)
4560 (mapcar (lambda (x)
4561 (if (string-match "(..?)$" x)
4562 (substring x 0 (match-beginning 0))
4564 list))
4566 ;; FIXME: this could be done much better, using second characters etc.
4567 (defun org-assign-fast-keys (alist)
4568 "Assign fast keys to a keyword-key alist.
4569 Respect keys that are already there."
4570 (let (new e k c c1 c2 (char ?a))
4571 (while (setq e (pop alist))
4572 (cond
4573 ((equal e '(:startgroup)) (push e new))
4574 ((equal e '(:endgroup)) (push e new))
4576 (setq k (car e) c2 nil)
4577 (if (cdr e)
4578 (setq c (cdr e))
4579 ;; automatically assign a character.
4580 (setq c1 (string-to-char
4581 (downcase (substring
4582 k (if (= (string-to-char k) ?@) 1 0)))))
4583 (if (or (rassoc c1 new) (rassoc c1 alist))
4584 (while (or (rassoc char new) (rassoc char alist))
4585 (setq char (1+ char)))
4586 (setq c2 c1))
4587 (setq c (or c2 char)))
4588 (push (cons k c) new))))
4589 (nreverse new)))
4591 ;;; Some variables ujsed in various places
4593 (defvar org-window-configuration nil
4594 "Used in various places to store a window configuration.")
4595 (defvar org-finish-function nil
4596 "Function to be called when `C-c C-c' is used.
4597 This is for getting out of special buffers like remember.")
4600 ;; FIXME: Occasionally check by commenting these, to make sure
4601 ;; no other functions uses these, forgetting to let-bind them.
4602 (defvar entry)
4603 (defvar state)
4604 (defvar last-state)
4605 (defvar date)
4606 (defvar description)
4608 ;; Defined somewhere in this file, but used before definition.
4609 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4610 (defvar org-agenda-buffer-name)
4611 (defvar org-agenda-undo-list)
4612 (defvar org-agenda-pending-undo-list)
4613 (defvar org-agenda-overriding-header)
4614 (defvar orgtbl-mode)
4615 (defvar org-html-entities)
4616 (defvar org-struct-menu)
4617 (defvar org-org-menu)
4618 (defvar org-tbl-menu)
4619 (defvar org-agenda-keymap)
4621 ;;;; Emacs/XEmacs compatibility
4623 ;; Overlay compatibility functions
4624 (defun org-make-overlay (beg end &optional buffer)
4625 (if (featurep 'xemacs)
4626 (make-extent beg end buffer)
4627 (make-overlay beg end buffer)))
4628 (defun org-delete-overlay (ovl)
4629 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4630 (defun org-detach-overlay (ovl)
4631 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4632 (defun org-move-overlay (ovl beg end &optional buffer)
4633 (if (featurep 'xemacs)
4634 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4635 (move-overlay ovl beg end buffer)))
4636 (defun org-overlay-put (ovl prop value)
4637 (if (featurep 'xemacs)
4638 (set-extent-property ovl prop value)
4639 (overlay-put ovl prop value)))
4640 (defun org-overlay-display (ovl text &optional face evap)
4641 "Make overlay OVL display TEXT with face FACE."
4642 (if (featurep 'xemacs)
4643 (let ((gl (make-glyph text)))
4644 (and face (set-glyph-face gl face))
4645 (set-extent-property ovl 'invisible t)
4646 (set-extent-property ovl 'end-glyph gl))
4647 (overlay-put ovl 'display text)
4648 (if face (overlay-put ovl 'face face))
4649 (if evap (overlay-put ovl 'evaporate t))))
4650 (defun org-overlay-before-string (ovl text &optional face evap)
4651 "Make overlay OVL display TEXT with face FACE."
4652 (if (featurep 'xemacs)
4653 (let ((gl (make-glyph text)))
4654 (and face (set-glyph-face gl face))
4655 (set-extent-property ovl 'begin-glyph gl))
4656 (if face (org-add-props text nil 'face face))
4657 (overlay-put ovl 'before-string text)
4658 (if evap (overlay-put ovl 'evaporate t))))
4659 (defun org-overlay-get (ovl prop)
4660 (if (featurep 'xemacs)
4661 (extent-property ovl prop)
4662 (overlay-get ovl prop)))
4663 (defun org-overlays-at (pos)
4664 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4665 (defun org-overlays-in (&optional start end)
4666 (if (featurep 'xemacs)
4667 (extent-list nil start end)
4668 (overlays-in start end)))
4669 (defun org-overlay-start (o)
4670 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4671 (defun org-overlay-end (o)
4672 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4673 (defun org-find-overlays (prop &optional pos delete)
4674 "Find all overlays specifying PROP at POS or point.
4675 If DELETE is non-nil, delete all those overlays."
4676 (let ((overlays (org-overlays-at (or pos (point))))
4677 ov found)
4678 (while (setq ov (pop overlays))
4679 (if (org-overlay-get ov prop)
4680 (if delete (org-delete-overlay ov) (push ov found))))
4681 found))
4683 ;; Region compatibility
4685 (defun org-add-hook (hook function &optional append local)
4686 "Add-hook, compatible with both Emacsen."
4687 (if (and local (featurep 'xemacs))
4688 (add-local-hook hook function append)
4689 (add-hook hook function append local)))
4691 (defvar org-ignore-region nil
4692 "To temporarily disable the active region.")
4694 (defun org-region-active-p ()
4695 "Is `transient-mark-mode' on and the region active?
4696 Works on both Emacs and XEmacs."
4697 (if org-ignore-region
4699 (if (featurep 'xemacs)
4700 (and zmacs-regions (region-active-p))
4701 (and transient-mark-mode mark-active))))
4703 ;; Invisibility compatibility
4705 (defun org-add-to-invisibility-spec (arg)
4706 "Add elements to `buffer-invisibility-spec'.
4707 See documentation for `buffer-invisibility-spec' for the kind of elements
4708 that can be added."
4709 (cond
4710 ((fboundp 'add-to-invisibility-spec)
4711 (add-to-invisibility-spec arg))
4712 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4713 (setq buffer-invisibility-spec (list arg)))
4715 (setq buffer-invisibility-spec
4716 (cons arg buffer-invisibility-spec)))))
4718 (defun org-remove-from-invisibility-spec (arg)
4719 "Remove elements from `buffer-invisibility-spec'."
4720 (if (fboundp 'remove-from-invisibility-spec)
4721 (remove-from-invisibility-spec arg)
4722 (if (consp buffer-invisibility-spec)
4723 (setq buffer-invisibility-spec
4724 (delete arg buffer-invisibility-spec)))))
4726 (defun org-in-invisibility-spec-p (arg)
4727 "Is ARG a member of `buffer-invisibility-spec'?"
4728 (if (consp buffer-invisibility-spec)
4729 (member arg buffer-invisibility-spec)
4730 nil))
4732 ;;;; Define the Org-mode
4734 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4735 (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."))
4738 ;; We use a before-change function to check if a table might need
4739 ;; an update.
4740 (defvar org-table-may-need-update t
4741 "Indicates that a table might need an update.
4742 This variable is set by `org-before-change-function'.
4743 `org-table-align' sets it back to nil.")
4744 (defvar org-mode-map)
4745 (defvar org-mode-hook nil)
4746 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4747 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4748 (defvar org-table-buffer-is-an nil)
4749 (defconst org-outline-regexp "\\*+ ")
4751 ;;;###autoload
4752 (define-derived-mode org-mode outline-mode "Org"
4753 "Outline-based notes management and organizer, alias
4754 \"Carsten's outline-mode for keeping track of everything.\"
4756 Org-mode develops organizational tasks around a NOTES file which
4757 contains information about projects as plain text. Org-mode is
4758 implemented on top of outline-mode, which is ideal to keep the content
4759 of large files well structured. It supports ToDo items, deadlines and
4760 time stamps, which magically appear in the diary listing of the Emacs
4761 calendar. Tables are easily created with a built-in table editor.
4762 Plain text URL-like links connect to websites, emails (VM), Usenet
4763 messages (Gnus), BBDB entries, and any files related to the project.
4764 For printing and sharing of notes, an Org-mode file (or a part of it)
4765 can be exported as a structured ASCII or HTML file.
4767 The following commands are available:
4769 \\{org-mode-map}"
4771 ;; Get rid of Outline menus, they are not needed
4772 ;; Need to do this here because define-derived-mode sets up
4773 ;; the keymap so late. Still, it is a waste to call this each time
4774 ;; we switch another buffer into org-mode.
4775 (if (featurep 'xemacs)
4776 (when (boundp 'outline-mode-menu-heading)
4777 ;; Assume this is Greg's port, it used easymenu
4778 (easy-menu-remove outline-mode-menu-heading)
4779 (easy-menu-remove outline-mode-menu-show)
4780 (easy-menu-remove outline-mode-menu-hide))
4781 (define-key org-mode-map [menu-bar headings] 'undefined)
4782 (define-key org-mode-map [menu-bar hide] 'undefined)
4783 (define-key org-mode-map [menu-bar show] 'undefined))
4785 (easy-menu-add org-org-menu)
4786 (easy-menu-add org-tbl-menu)
4787 (org-install-agenda-files-menu)
4788 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4789 (org-add-to-invisibility-spec '(org-cwidth))
4790 (when (featurep 'xemacs)
4791 (org-set-local 'line-move-ignore-invisible t))
4792 (org-set-local 'outline-regexp org-outline-regexp)
4793 (org-set-local 'outline-level 'org-outline-level)
4794 (when (and org-ellipsis
4795 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4796 (fboundp 'make-glyph-code))
4797 (unless org-display-table
4798 (setq org-display-table (make-display-table)))
4799 (set-display-table-slot
4800 org-display-table 4
4801 (vconcat (mapcar
4802 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4803 org-ellipsis)))
4804 (if (stringp org-ellipsis) org-ellipsis "..."))))
4805 (setq buffer-display-table org-display-table))
4806 (org-set-regexps-and-options)
4807 ;; Calc embedded
4808 (org-set-local 'calc-embedded-open-mode "# ")
4809 (modify-syntax-entry ?# "<")
4810 (modify-syntax-entry ?@ "w")
4811 (if org-startup-truncated (setq truncate-lines t))
4812 (org-set-local 'font-lock-unfontify-region-function
4813 'org-unfontify-region)
4814 ;; Activate before-change-function
4815 (org-set-local 'org-table-may-need-update t)
4816 (org-add-hook 'before-change-functions 'org-before-change-function nil
4817 'local)
4818 ;; Check for running clock before killing a buffer
4819 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4820 ;; Paragraphs and auto-filling
4821 (org-set-autofill-regexps)
4822 (setq indent-line-function 'org-indent-line-function)
4823 (org-update-radio-target-regexp)
4825 ;; Comment characters
4826 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4827 (org-set-local 'comment-padding " ")
4829 ;; Imenu
4830 (org-set-local 'imenu-create-index-function
4831 'org-imenu-get-tree)
4833 ;; Make isearch reveal context
4834 (if (or (featurep 'xemacs)
4835 (not (boundp 'outline-isearch-open-invisible-function)))
4836 ;; Emacs 21 and XEmacs make use of the hook
4837 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4838 ;; Emacs 22 deals with this through a special variable
4839 (org-set-local 'outline-isearch-open-invisible-function
4840 (lambda (&rest ignore) (org-show-context 'isearch))))
4842 ;; If empty file that did not turn on org-mode automatically, make it to.
4843 (if (and org-insert-mode-line-in-empty-file
4844 (interactive-p)
4845 (= (point-min) (point-max)))
4846 (insert "# -*- mode: org -*-\n\n"))
4848 (unless org-inhibit-startup
4849 (when org-startup-align-all-tables
4850 (let ((bmp (buffer-modified-p)))
4851 (org-table-map-tables 'org-table-align)
4852 (set-buffer-modified-p bmp)))
4853 (org-cycle-hide-drawers 'all)
4854 (cond
4855 ((eq org-startup-folded t)
4856 (org-cycle '(4)))
4857 ((eq org-startup-folded 'content)
4858 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4859 (org-cycle '(4)) (org-cycle '(4)))))))
4861 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4863 (defsubst org-call-with-arg (command arg)
4864 "Call COMMAND interactively, but pretend prefix are was ARG."
4865 (let ((current-prefix-arg arg)) (call-interactively command)))
4867 (defsubst org-current-line (&optional pos)
4868 (save-excursion
4869 (and pos (goto-char pos))
4870 ;; works also in narrowed buffer, because we start at 1, not point-min
4871 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
4873 (defun org-current-time ()
4874 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4875 (if (> org-time-stamp-rounding-minutes 0)
4876 (let ((r org-time-stamp-rounding-minutes)
4877 (time (decode-time)))
4878 (apply 'encode-time
4879 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4880 (nthcdr 2 time))))
4881 (current-time)))
4883 (defun org-add-props (string plist &rest props)
4884 "Add text properties to entire string, from beginning to end.
4885 PLIST may be a list of properties, PROPS are individual properties and values
4886 that will be added to PLIST. Returns the string that was modified."
4887 (add-text-properties
4888 0 (length string) (if props (append plist props) plist) string)
4889 string)
4890 (put 'org-add-props 'lisp-indent-function 2)
4893 ;;;; Font-Lock stuff, including the activators
4895 (defvar org-mouse-map (make-sparse-keymap))
4896 (org-defkey org-mouse-map
4897 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4898 (org-defkey org-mouse-map
4899 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4900 (when org-mouse-1-follows-link
4901 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4902 (when org-tab-follows-link
4903 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4904 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4905 (when org-return-follows-link
4906 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
4907 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
4909 (require 'font-lock)
4911 (defconst org-non-link-chars "]\t\n\r<>")
4912 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
4913 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
4914 (defvar org-link-re-with-space nil
4915 "Matches a link with spaces, optional angular brackets around it.")
4916 (defvar org-link-re-with-space2 nil
4917 "Matches a link with spaces, optional angular brackets around it.")
4918 (defvar org-angle-link-re nil
4919 "Matches link with angular brackets, spaces are allowed.")
4920 (defvar org-plain-link-re nil
4921 "Matches plain link, without spaces.")
4922 (defvar org-bracket-link-regexp nil
4923 "Matches a link in double brackets.")
4924 (defvar org-bracket-link-analytic-regexp nil
4925 "Regular expression used to analyze links.
4926 Here is what the match groups contain after a match:
4927 1: http:
4928 2: http
4929 3: path
4930 4: [desc]
4931 5: desc")
4932 (defvar org-any-link-re nil
4933 "Regular expression matching any link.")
4935 (defun org-make-link-regexps ()
4936 "Update the link regular expressions.
4937 This should be called after the variable `org-link-types' has changed."
4938 (setq org-link-re-with-space
4939 (concat
4940 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4941 "\\([^" org-non-link-chars " ]"
4942 "[^" org-non-link-chars "]*"
4943 "[^" org-non-link-chars " ]\\)>?")
4944 org-link-re-with-space2
4945 (concat
4946 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4947 "\\([^" org-non-link-chars " ]"
4948 "[^]\t\n\r]*"
4949 "[^" org-non-link-chars " ]\\)>?")
4950 org-angle-link-re
4951 (concat
4952 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4953 "\\([^" org-non-link-chars " ]"
4954 "[^" org-non-link-chars "]*"
4955 "\\)>")
4956 org-plain-link-re
4957 (concat
4958 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4959 "\\([^]\t\n\r<>,;() ]+\\)")
4960 org-bracket-link-regexp
4961 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4962 org-bracket-link-analytic-regexp
4963 (concat
4964 "\\[\\["
4965 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4966 "\\([^]]+\\)"
4967 "\\]"
4968 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4969 "\\]")
4970 org-any-link-re
4971 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4972 org-angle-link-re "\\)\\|\\("
4973 org-plain-link-re "\\)")))
4975 (org-make-link-regexps)
4977 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4978 "Regular expression for fast time stamp matching.")
4979 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4980 "Regular expression for fast time stamp matching.")
4981 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4982 "Regular expression matching time strings for analysis.
4983 This one does not require the space after the date.")
4984 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4985 "Regular expression matching time strings for analysis.")
4986 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4987 "Regular expression matching time stamps, with groups.")
4988 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4989 "Regular expression matching time stamps (also [..]), with groups.")
4990 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4991 "Regular expression matching a time stamp range.")
4992 (defconst org-tr-regexp-both
4993 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4994 "Regular expression matching a time stamp range.")
4995 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4996 org-ts-regexp "\\)?")
4997 "Regular expression matching a time stamp or time stamp range.")
4998 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4999 org-ts-regexp-both "\\)?")
5000 "Regular expression matching a time stamp or time stamp range.
5001 The time stamps may be either active or inactive.")
5003 (defvar org-emph-face nil)
5005 (defun org-do-emphasis-faces (limit)
5006 "Run through the buffer and add overlays to links."
5007 (let (rtn)
5008 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5009 (if (not (= (char-after (match-beginning 3))
5010 (char-after (match-beginning 4))))
5011 (progn
5012 (setq rtn t)
5013 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5014 'face
5015 (nth 1 (assoc (match-string 3)
5016 org-emphasis-alist)))
5017 (add-text-properties (match-beginning 2) (match-end 2)
5018 '(font-lock-multiline t))
5019 (when org-hide-emphasis-markers
5020 (add-text-properties (match-end 4) (match-beginning 5)
5021 '(invisible org-link))
5022 (add-text-properties (match-beginning 3) (match-end 3)
5023 '(invisible org-link)))))
5024 (backward-char 1))
5025 rtn))
5027 (defun org-emphasize (&optional char)
5028 "Insert or change an emphasis, i.e. a font like bold or italic.
5029 If there is an active region, change that region to a new emphasis.
5030 If there is no region, just insert the marker characters and position
5031 the cursor between them.
5032 CHAR should be either the marker character, or the first character of the
5033 HTML tag associated with that emphasis. If CHAR is a space, the means
5034 to remove the emphasis of the selected region.
5035 If char is not given (for example in an interactive call) it
5036 will be prompted for."
5037 (interactive)
5038 (let ((eal org-emphasis-alist) e det
5039 (erc org-emphasis-regexp-components)
5040 (prompt "")
5041 (string "") beg end move tag c s)
5042 (if (org-region-active-p)
5043 (setq beg (region-beginning) end (region-end)
5044 string (buffer-substring beg end))
5045 (setq move t))
5047 (while (setq e (pop eal))
5048 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5049 c (aref tag 0))
5050 (push (cons c (string-to-char (car e))) det)
5051 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5052 (substring tag 1)))))
5053 (unless char
5054 (message "%s" (concat "Emphasis marker or tag:" prompt))
5055 (setq char (read-char-exclusive)))
5056 (setq char (or (cdr (assoc char det)) char))
5057 (if (equal char ?\ )
5058 (setq s "" move nil)
5059 (unless (assoc (char-to-string char) org-emphasis-alist)
5060 (error "No such emphasis marker: \"%c\"" char))
5061 (setq s (char-to-string char)))
5062 (while (and (> (length string) 1)
5063 (equal (substring string 0 1) (substring string -1))
5064 (assoc (substring string 0 1) org-emphasis-alist))
5065 (setq string (substring string 1 -1)))
5066 (setq string (concat s string s))
5067 (if beg (delete-region beg end))
5068 (unless (or (bolp)
5069 (string-match (concat "[" (nth 0 erc) "\n]")
5070 (char-to-string (char-before (point)))))
5071 (insert " "))
5072 (unless (string-match (concat "[" (nth 1 erc) "\n]")
5073 (char-to-string (char-after (point))))
5074 (insert " ") (backward-char 1))
5075 (insert string)
5076 (and move (backward-char 1))))
5078 (defconst org-nonsticky-props
5079 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5082 (defun org-activate-plain-links (limit)
5083 "Run through the buffer and add overlays to links."
5084 (catch 'exit
5085 (let (f)
5086 (while (re-search-forward org-plain-link-re limit t)
5087 (setq f (get-text-property (match-beginning 0) 'face))
5088 (if (or (eq f 'org-tag)
5089 (and (listp f) (memq 'org-tag f)))
5091 (add-text-properties (match-beginning 0) (match-end 0)
5092 (list 'mouse-face 'highlight
5093 'rear-nonsticky org-nonsticky-props
5094 'keymap org-mouse-map
5096 (throw 'exit t))))))
5098 (defun org-activate-code (limit)
5099 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
5100 (unless (get-text-property (match-beginning 1) 'face)
5101 (remove-text-properties (match-beginning 0) (match-end 0)
5102 '(display t invisible t intangible t))
5103 t)))
5105 (defun org-activate-angle-links (limit)
5106 "Run through the buffer and add overlays to links."
5107 (if (re-search-forward org-angle-link-re limit t)
5108 (progn
5109 (add-text-properties (match-beginning 0) (match-end 0)
5110 (list 'mouse-face 'highlight
5111 'rear-nonsticky org-nonsticky-props
5112 'keymap org-mouse-map
5114 t)))
5116 (defmacro org-maybe-intangible (props)
5117 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
5118 In emacs 21, invisible text is not avoided by the command loop, so the
5119 intangible property is needed to make sure point skips this text.
5120 In Emacs 22, this is not necessary. The intangible text property has
5121 led to problems with flyspell. These problems are fixed in flyspell.el,
5122 but we still avoid setting the property in Emacs 22 and later.
5123 We use a macro so that the test can happen at compilation time."
5124 (if (< emacs-major-version 22)
5125 `(append '(intangible t) ,props)
5126 props))
5128 (defun org-activate-bracket-links (limit)
5129 "Run through the buffer and add overlays to bracketed links."
5130 (if (re-search-forward org-bracket-link-regexp limit t)
5131 (let* ((help (concat "LINK: "
5132 (org-match-string-no-properties 1)))
5133 ;; FIXME: above we should remove the escapes.
5134 ;; but that requires another match, protecting match data,
5135 ;; a lot of overhead for font-lock.
5136 (ip (org-maybe-intangible
5137 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5138 'keymap org-mouse-map 'mouse-face 'highlight
5139 'font-lock-multiline t 'help-echo help)))
5140 (vp (list 'rear-nonsticky org-nonsticky-props
5141 'keymap org-mouse-map 'mouse-face 'highlight
5142 ' font-lock-multiline t 'help-echo help)))
5143 ;; We need to remove the invisible property here. Table narrowing
5144 ;; may have made some of this invisible.
5145 (remove-text-properties (match-beginning 0) (match-end 0)
5146 '(invisible nil))
5147 (if (match-end 3)
5148 (progn
5149 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5150 (add-text-properties (match-beginning 3) (match-end 3) vp)
5151 (add-text-properties (match-end 3) (match-end 0) ip))
5152 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5153 (add-text-properties (match-beginning 1) (match-end 1) vp)
5154 (add-text-properties (match-end 1) (match-end 0) ip))
5155 t)))
5157 (defun org-activate-dates (limit)
5158 "Run through the buffer and add overlays to dates."
5159 (if (re-search-forward org-tsr-regexp-both limit t)
5160 (progn
5161 (add-text-properties (match-beginning 0) (match-end 0)
5162 (list 'mouse-face 'highlight
5163 'rear-nonsticky org-nonsticky-props
5164 'keymap org-mouse-map))
5165 (when org-display-custom-times
5166 (if (match-end 3)
5167 (org-display-custom-time (match-beginning 3) (match-end 3)))
5168 (org-display-custom-time (match-beginning 1) (match-end 1)))
5169 t)))
5171 (defvar org-target-link-regexp nil
5172 "Regular expression matching radio targets in plain text.")
5173 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5174 "Regular expression matching a link target.")
5175 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5176 "Regular expression matching a radio target.")
5177 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5178 "Regular expression matching any target.")
5180 (defun org-activate-target-links (limit)
5181 "Run through the buffer and add overlays to target matches."
5182 (when org-target-link-regexp
5183 (let ((case-fold-search t))
5184 (if (re-search-forward org-target-link-regexp limit t)
5185 (progn
5186 (add-text-properties (match-beginning 0) (match-end 0)
5187 (list 'mouse-face 'highlight
5188 'rear-nonsticky org-nonsticky-props
5189 'keymap org-mouse-map
5190 'help-echo "Radio target link"
5191 'org-linked-text t))
5192 t)))))
5194 (defun org-update-radio-target-regexp ()
5195 "Find all radio targets in this file and update the regular expression."
5196 (interactive)
5197 (when (memq 'radio org-activate-links)
5198 (setq org-target-link-regexp
5199 (org-make-target-link-regexp (org-all-targets 'radio)))
5200 (org-restart-font-lock)))
5202 (defun org-hide-wide-columns (limit)
5203 (let (s e)
5204 (setq s (text-property-any (point) (or limit (point-max))
5205 'org-cwidth t))
5206 (when s
5207 (setq e (next-single-property-change s 'org-cwidth))
5208 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5209 (goto-char e)
5210 t)))
5212 (defvar org-latex-and-specials-regexp nil
5213 "Regular expression for highlighting export special stuff.")
5214 (defvar org-match-substring-regexp)
5215 (defvar org-match-substring-with-braces-regexp)
5216 (defvar org-export-html-special-string-regexps)
5218 (defun org-compute-latex-and-specials-regexp ()
5219 "Compute regular expression for stuff treated specially by exporters."
5220 (if (not org-highlight-latex-fragments-and-specials)
5221 (org-set-local 'org-latex-and-specials-regexp nil)
5222 (let*
5223 ((matchers (plist-get org-format-latex-options :matchers))
5224 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5225 org-latex-regexps)))
5226 (options (org-combine-plists (org-default-export-plist)
5227 (org-infile-export-plist)))
5228 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5229 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5230 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5231 (org-export-html-expand (plist-get options :expand-quoted-html))
5232 (org-export-with-special-strings (plist-get options :special-strings))
5233 (re-sub
5234 (cond
5235 ((equal org-export-with-sub-superscripts '{})
5236 (list org-match-substring-with-braces-regexp))
5237 (org-export-with-sub-superscripts
5238 (list org-match-substring-regexp))
5239 (t nil)))
5240 (re-latex
5241 (if org-export-with-LaTeX-fragments
5242 (mapcar (lambda (x) (nth 1 x)) latexs)))
5243 (re-macros
5244 (if org-export-with-TeX-macros
5245 (list (concat "\\\\"
5246 (regexp-opt
5247 (append (mapcar 'car org-html-entities)
5248 (if (boundp 'org-latex-entities)
5249 org-latex-entities nil))
5250 'words))) ; FIXME
5252 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5253 (re-special (if org-export-with-special-strings
5254 (mapcar (lambda (x) (car x))
5255 org-export-html-special-string-regexps)))
5256 (re-rest
5257 (delq nil
5258 (list
5259 (if org-export-html-expand "@<[^>\n]+>")
5260 ))))
5261 (org-set-local
5262 'org-latex-and-specials-regexp
5263 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5264 re-rest) "\\|")))))
5266 (defface org-latex-and-export-specials
5267 (let ((font (cond ((assq :inherit custom-face-attributes)
5268 '(:inherit underline))
5269 (t '(:underline t)))))
5270 `((((class grayscale) (background light))
5271 (:foreground "DimGray" ,@font))
5272 (((class grayscale) (background dark))
5273 (:foreground "LightGray" ,@font))
5274 (((class color) (background light))
5275 (:foreground "SaddleBrown"))
5276 (((class color) (background dark))
5277 (:foreground "burlywood"))
5278 (t (,@font))))
5279 "Face used to highlight math latex and other special exporter stuff."
5280 :group 'org-faces)
5282 (defun org-do-latex-and-special-faces (limit)
5283 "Run through the buffer and add overlays to links."
5284 (when org-latex-and-specials-regexp
5285 (let (rtn d)
5286 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5287 limit t))
5288 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5289 'face))
5290 '(org-code org-verbatim underline)))
5291 (progn
5292 (setq rtn t
5293 d (cond ((member (char-after (1+ (match-beginning 0)))
5294 '(?_ ?^)) 1)
5295 (t 0)))
5296 (font-lock-prepend-text-property
5297 (+ d (match-beginning 0)) (match-end 0)
5298 'face 'org-latex-and-export-specials)
5299 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5300 '(font-lock-multiline t)))))
5301 rtn)))
5303 (defun org-restart-font-lock ()
5304 "Restart font-lock-mode, to force refontification."
5305 (when (and (boundp 'font-lock-mode) font-lock-mode)
5306 (font-lock-mode -1)
5307 (font-lock-mode 1)))
5309 (defun org-all-targets (&optional radio)
5310 "Return a list of all targets in this file.
5311 With optional argument RADIO, only find radio targets."
5312 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5313 rtn)
5314 (save-excursion
5315 (goto-char (point-min))
5316 (while (re-search-forward re nil t)
5317 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5318 rtn)))
5320 (defun org-make-target-link-regexp (targets)
5321 "Make regular expression matching all strings in TARGETS.
5322 The regular expression finds the targets also if there is a line break
5323 between words."
5324 (and targets
5325 (concat
5326 "\\<\\("
5327 (mapconcat
5328 (lambda (x)
5329 (while (string-match " +" x)
5330 (setq x (replace-match "\\s-+" t t x)))
5332 targets
5333 "\\|")
5334 "\\)\\>")))
5336 (defun org-activate-tags (limit)
5337 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5338 (progn
5339 (add-text-properties (match-beginning 1) (match-end 1)
5340 (list 'mouse-face 'highlight
5341 'rear-nonsticky org-nonsticky-props
5342 'keymap org-mouse-map))
5343 t)))
5345 (defun org-outline-level ()
5346 (save-excursion
5347 (looking-at outline-regexp)
5348 (if (match-beginning 1)
5349 (+ (org-get-string-indentation (match-string 1)) 1000)
5350 (1- (- (match-end 0) (match-beginning 0))))))
5352 (defvar org-font-lock-keywords nil)
5354 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5355 "Regular expression matching a property line.")
5357 (defun org-set-font-lock-defaults ()
5358 (let* ((em org-fontify-emphasized-text)
5359 (lk org-activate-links)
5360 (org-font-lock-extra-keywords
5361 (list
5362 ;; Headlines
5363 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5364 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5365 ;; Table lines
5366 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5367 (1 'org-table t))
5368 ;; Table internals
5369 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5370 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5371 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5372 ;; Drawers
5373 (list org-drawer-regexp '(0 'org-special-keyword t))
5374 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5375 ;; Properties
5376 (list org-property-re
5377 '(1 'org-special-keyword t)
5378 '(3 'org-property-value t))
5379 (if org-format-transports-properties-p
5380 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5381 ;; Links
5382 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5383 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5384 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5385 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5386 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5387 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5388 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5389 '(org-hide-wide-columns (0 nil append))
5390 ;; TODO lines
5391 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5392 '(1 (org-get-todo-face 1) t))
5393 ;; DONE
5394 (if org-fontify-done-headline
5395 (list (concat "^[*]+ +\\<\\("
5396 (mapconcat 'regexp-quote org-done-keywords "\\|")
5397 "\\)\\(.*\\)")
5398 '(2 'org-headline-done t))
5399 nil)
5400 ;; Priorities
5401 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5402 ;; Special keywords
5403 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5404 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5405 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5406 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5407 ;; Emphasis
5408 (if em
5409 (if (featurep 'xemacs)
5410 '(org-do-emphasis-faces (0 nil append))
5411 '(org-do-emphasis-faces)))
5412 ;; Checkboxes
5413 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5414 2 'bold prepend)
5415 (if org-provide-checkbox-statistics
5416 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5417 (0 (org-get-checkbox-statistics-face) t)))
5418 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5419 '(1 'org-archived prepend))
5420 ;; Specials
5421 '(org-do-latex-and-special-faces)
5422 ;; Code
5423 '(org-activate-code (1 'org-code t))
5424 ;; COMMENT
5425 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5426 "\\|" org-quote-string "\\)\\>")
5427 '(1 'org-special-keyword t))
5428 '("^#.*" (0 'font-lock-comment-face t))
5430 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5431 ;; Now set the full font-lock-keywords
5432 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5433 (org-set-local 'font-lock-defaults
5434 '(org-font-lock-keywords t nil nil backward-paragraph))
5435 (kill-local-variable 'font-lock-keywords) nil))
5437 (defvar org-m nil)
5438 (defvar org-l nil)
5439 (defvar org-f nil)
5440 (defun org-get-level-face (n)
5441 "Get the right face for match N in font-lock matching of healdines."
5442 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5443 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5444 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5445 (cond
5446 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5447 ((eq n 2) org-f)
5448 (t (if org-level-color-stars-only nil org-f))))
5450 (defun org-get-todo-face (kwd)
5451 "Get the right face for a TODO keyword KWD.
5452 If KWD is a number, get the corresponding match group."
5453 (if (numberp kwd) (setq kwd (match-string kwd)))
5454 (or (cdr (assoc kwd org-todo-keyword-faces))
5455 (and (member kwd org-done-keywords) 'org-done)
5456 'org-todo))
5458 (defun org-unfontify-region (beg end &optional maybe_loudly)
5459 "Remove fontification and activation overlays from links."
5460 (font-lock-default-unfontify-region beg end)
5461 (let* ((buffer-undo-list t)
5462 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5463 (inhibit-modification-hooks t)
5464 deactivate-mark buffer-file-name buffer-file-truename)
5465 (remove-text-properties beg end
5466 '(mouse-face t keymap t org-linked-text t
5467 invisible t intangible t))))
5469 ;;;; Visibility cycling, including org-goto and indirect buffer
5471 ;;; Cycling
5473 (defvar org-cycle-global-status nil)
5474 (make-variable-buffer-local 'org-cycle-global-status)
5475 (defvar org-cycle-subtree-status nil)
5476 (make-variable-buffer-local 'org-cycle-subtree-status)
5478 ;;;###autoload
5479 (defun org-cycle (&optional arg)
5480 "Visibility cycling for Org-mode.
5482 - When this function is called with a prefix argument, rotate the entire
5483 buffer through 3 states (global cycling)
5484 1. OVERVIEW: Show only top-level headlines.
5485 2. CONTENTS: Show all headlines of all levels, but no body text.
5486 3. SHOW ALL: Show everything.
5488 - When point is at the beginning of a headline, rotate the subtree started
5489 by this line through 3 different states (local cycling)
5490 1. FOLDED: Only the main headline is shown.
5491 2. CHILDREN: The main headline and the direct children are shown.
5492 From this state, you can move to one of the children
5493 and zoom in further.
5494 3. SUBTREE: Show the entire subtree, including body text.
5496 - When there is a numeric prefix, go up to a heading with level ARG, do
5497 a `show-subtree' and return to the previous cursor position. If ARG
5498 is negative, go up that many levels.
5500 - When point is not at the beginning of a headline, execute
5501 `indent-relative', like TAB normally does. See the option
5502 `org-cycle-emulate-tab' for details.
5504 - Special case: if point is at the beginning of the buffer and there is
5505 no headline in line 1, this function will act as if called with prefix arg.
5506 But only if also the variable `org-cycle-global-at-bob' is t."
5507 (interactive "P")
5508 (let* ((outline-regexp
5509 (if (and (org-mode-p) org-cycle-include-plain-lists)
5510 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5511 outline-regexp))
5512 (bob-special (and org-cycle-global-at-bob (bobp)
5513 (not (looking-at outline-regexp))))
5514 (org-cycle-hook
5515 (if bob-special
5516 (delq 'org-optimize-window-after-visibility-change
5517 (copy-sequence org-cycle-hook))
5518 org-cycle-hook))
5519 (pos (point)))
5521 (if (or bob-special (equal arg '(4)))
5522 ;; special case: use global cycling
5523 (setq arg t))
5525 (cond
5527 ((org-at-table-p 'any)
5528 ;; Enter the table or move to the next field in the table
5529 (or (org-table-recognize-table.el)
5530 (progn
5531 (if arg (org-table-edit-field t)
5532 (org-table-justify-field-maybe)
5533 (call-interactively 'org-table-next-field)))))
5535 ((eq arg t) ;; Global cycling
5537 (cond
5538 ((and (eq last-command this-command)
5539 (eq org-cycle-global-status 'overview))
5540 ;; We just created the overview - now do table of contents
5541 ;; This can be slow in very large buffers, so indicate action
5542 (message "CONTENTS...")
5543 (org-content)
5544 (message "CONTENTS...done")
5545 (setq org-cycle-global-status 'contents)
5546 (run-hook-with-args 'org-cycle-hook 'contents))
5548 ((and (eq last-command this-command)
5549 (eq org-cycle-global-status 'contents))
5550 ;; We just showed the table of contents - now show everything
5551 (show-all)
5552 (message "SHOW ALL")
5553 (setq org-cycle-global-status 'all)
5554 (run-hook-with-args 'org-cycle-hook 'all))
5557 ;; Default action: go to overview
5558 (org-overview)
5559 (message "OVERVIEW")
5560 (setq org-cycle-global-status 'overview)
5561 (run-hook-with-args 'org-cycle-hook 'overview))))
5563 ((and org-drawers org-drawer-regexp
5564 (save-excursion
5565 (beginning-of-line 1)
5566 (looking-at org-drawer-regexp)))
5567 ;; Toggle block visibility
5568 (org-flag-drawer
5569 (not (get-char-property (match-end 0) 'invisible))))
5571 ((integerp arg)
5572 ;; Show-subtree, ARG levels up from here.
5573 (save-excursion
5574 (org-back-to-heading)
5575 (outline-up-heading (if (< arg 0) (- arg)
5576 (- (funcall outline-level) arg)))
5577 (org-show-subtree)))
5579 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5580 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5581 ;; At a heading: rotate between three different views
5582 (org-back-to-heading)
5583 (let ((goal-column 0) eoh eol eos)
5584 ;; First, some boundaries
5585 (save-excursion
5586 (org-back-to-heading)
5587 (save-excursion
5588 (beginning-of-line 2)
5589 (while (and (not (eobp)) ;; this is like `next-line'
5590 (get-char-property (1- (point)) 'invisible))
5591 (beginning-of-line 2)) (setq eol (point)))
5592 (outline-end-of-heading) (setq eoh (point))
5593 (org-end-of-subtree t)
5594 (unless (eobp)
5595 (skip-chars-forward " \t\n")
5596 (beginning-of-line 1) ; in case this is an item
5598 (setq eos (1- (point))))
5599 ;; Find out what to do next and set `this-command'
5600 (cond
5601 ((= eos eoh)
5602 ;; Nothing is hidden behind this heading
5603 (message "EMPTY ENTRY")
5604 (setq org-cycle-subtree-status nil)
5605 (save-excursion
5606 (goto-char eos)
5607 (outline-next-heading)
5608 (if (org-invisible-p) (org-flag-heading nil))))
5609 ((or (>= eol eos)
5610 (not (string-match "\\S-" (buffer-substring eol eos))))
5611 ;; Entire subtree is hidden in one line: open it
5612 (org-show-entry)
5613 (show-children)
5614 (message "CHILDREN")
5615 (save-excursion
5616 (goto-char eos)
5617 (outline-next-heading)
5618 (if (org-invisible-p) (org-flag-heading nil)))
5619 (setq org-cycle-subtree-status 'children)
5620 (run-hook-with-args 'org-cycle-hook 'children))
5621 ((and (eq last-command this-command)
5622 (eq org-cycle-subtree-status 'children))
5623 ;; We just showed the children, now show everything.
5624 (org-show-subtree)
5625 (message "SUBTREE")
5626 (setq org-cycle-subtree-status 'subtree)
5627 (run-hook-with-args 'org-cycle-hook 'subtree))
5629 ;; Default action: hide the subtree.
5630 (hide-subtree)
5631 (message "FOLDED")
5632 (setq org-cycle-subtree-status 'folded)
5633 (run-hook-with-args 'org-cycle-hook 'folded)))))
5635 ;; TAB emulation
5636 (buffer-read-only (org-back-to-heading))
5638 ((org-try-cdlatex-tab))
5640 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5641 (or (not (bolp))
5642 (not (looking-at outline-regexp))))
5643 (call-interactively (global-key-binding "\t")))
5645 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5646 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5647 (or (and (eq org-cycle-emulate-tab 'white)
5648 (= (match-end 0) (point-at-eol)))
5649 (and (eq org-cycle-emulate-tab 'whitestart)
5650 (>= (match-end 0) pos))))
5652 (eq org-cycle-emulate-tab t))
5653 ; (if (and (looking-at "[ \n\r\t]")
5654 ; (string-match "^[ \t]*$" (buffer-substring
5655 ; (point-at-bol) (point))))
5656 ; (progn
5657 ; (beginning-of-line 1)
5658 ; (and (looking-at "[ \t]+") (replace-match ""))))
5659 (call-interactively (global-key-binding "\t")))
5661 (t (save-excursion
5662 (org-back-to-heading)
5663 (org-cycle))))))
5665 ;;;###autoload
5666 (defun org-global-cycle (&optional arg)
5667 "Cycle the global visibility. For details see `org-cycle'."
5668 (interactive "P")
5669 (let ((org-cycle-include-plain-lists
5670 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5671 (if (integerp arg)
5672 (progn
5673 (show-all)
5674 (hide-sublevels arg)
5675 (setq org-cycle-global-status 'contents))
5676 (org-cycle '(4)))))
5678 (defun org-overview ()
5679 "Switch to overview mode, shoing only top-level headlines.
5680 Really, this shows all headlines with level equal or greater than the level
5681 of the first headline in the buffer. This is important, because if the
5682 first headline is not level one, then (hide-sublevels 1) gives confusing
5683 results."
5684 (interactive)
5685 (let ((level (save-excursion
5686 (goto-char (point-min))
5687 (if (re-search-forward (concat "^" outline-regexp) nil t)
5688 (progn
5689 (goto-char (match-beginning 0))
5690 (funcall outline-level))))))
5691 (and level (hide-sublevels level))))
5693 (defun org-content (&optional arg)
5694 "Show all headlines in the buffer, like a table of contents.
5695 With numerical argument N, show content up to level N."
5696 (interactive "P")
5697 (save-excursion
5698 ;; Visit all headings and show their offspring
5699 (and (integerp arg) (org-overview))
5700 (goto-char (point-max))
5701 (catch 'exit
5702 (while (and (progn (condition-case nil
5703 (outline-previous-visible-heading 1)
5704 (error (goto-char (point-min))))
5706 (looking-at outline-regexp))
5707 (if (integerp arg)
5708 (show-children (1- arg))
5709 (show-branches))
5710 (if (bobp) (throw 'exit nil))))))
5713 (defun org-optimize-window-after-visibility-change (state)
5714 "Adjust the window after a change in outline visibility.
5715 This function is the default value of the hook `org-cycle-hook'."
5716 (when (get-buffer-window (current-buffer))
5717 (cond
5718 ; ((eq state 'overview) (org-first-headline-recenter 1))
5719 ; ((eq state 'overview) (org-beginning-of-line))
5720 ((eq state 'content) nil)
5721 ((eq state 'all) nil)
5722 ((eq state 'folded) nil)
5723 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5724 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5727 (defun org-cycle-show-empty-lines (state)
5728 "Show empty lines above all visible headlines.
5729 The region to be covered depends on STATE when called through
5730 `org-cycle-hook'. Lisp program can use t for STATE to get the
5731 entire buffer covered. Note that an empty line is only shown if there
5732 are at least `org-cycle-separator-lines' empty lines before the headeline."
5733 (when (> org-cycle-separator-lines 0)
5734 (save-excursion
5735 (let* ((n org-cycle-separator-lines)
5736 (re (cond
5737 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5738 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5739 (t (let ((ns (number-to-string (- n 2))))
5740 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5741 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5742 beg end)
5743 (cond
5744 ((memq state '(overview contents t))
5745 (setq beg (point-min) end (point-max)))
5746 ((memq state '(children folded))
5747 (setq beg (point) end (progn (org-end-of-subtree t t)
5748 (beginning-of-line 2)
5749 (point)))))
5750 (when beg
5751 (goto-char beg)
5752 (while (re-search-forward re end t)
5753 (if (not (get-char-property (match-end 1) 'invisible))
5754 (outline-flag-region
5755 (match-beginning 1) (match-end 1) nil)))))))
5756 ;; Never hide empty lines at the end of the file.
5757 (save-excursion
5758 (goto-char (point-max))
5759 (outline-previous-heading)
5760 (outline-end-of-heading)
5761 (if (and (looking-at "[ \t\n]+")
5762 (= (match-end 0) (point-max)))
5763 (outline-flag-region (point) (match-end 0) nil))))
5765 (defun org-subtree-end-visible-p ()
5766 "Is the end of the current subtree visible?"
5767 (pos-visible-in-window-p
5768 (save-excursion (org-end-of-subtree t) (point))))
5770 (defun org-first-headline-recenter (&optional N)
5771 "Move cursor to the first headline and recenter the headline.
5772 Optional argument N means, put the headline into the Nth line of the window."
5773 (goto-char (point-min))
5774 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5775 (beginning-of-line)
5776 (recenter (prefix-numeric-value N))))
5778 ;;; Org-goto
5780 (defvar org-goto-window-configuration nil)
5781 (defvar org-goto-marker nil)
5782 (defvar org-goto-map
5783 (let ((map (make-sparse-keymap)))
5784 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5785 (while (setq cmd (pop cmds))
5786 (substitute-key-definition cmd cmd map global-map)))
5787 (suppress-keymap map)
5788 (org-defkey map "\C-m" 'org-goto-ret)
5789 (org-defkey map [(left)] 'org-goto-left)
5790 (org-defkey map [(right)] 'org-goto-right)
5791 (org-defkey map [(?q)] 'org-goto-quit)
5792 (org-defkey map [(control ?g)] 'org-goto-quit)
5793 (org-defkey map "\C-i" 'org-cycle)
5794 (org-defkey map [(tab)] 'org-cycle)
5795 (org-defkey map [(down)] 'outline-next-visible-heading)
5796 (org-defkey map [(up)] 'outline-previous-visible-heading)
5797 (org-defkey map "n" 'outline-next-visible-heading)
5798 (org-defkey map "p" 'outline-previous-visible-heading)
5799 (org-defkey map "f" 'outline-forward-same-level)
5800 (org-defkey map "b" 'outline-backward-same-level)
5801 (org-defkey map "u" 'outline-up-heading)
5802 (org-defkey map "/" 'org-occur)
5803 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5804 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5805 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5806 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5807 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5808 map))
5810 (defconst org-goto-help
5811 "Browse copy of buffer to find location or copy text.
5812 RET=jump to location [Q]uit and return to previous location
5813 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur"
5816 (defvar org-goto-start-pos) ; dynamically scoped parameter
5818 (defun org-goto ()
5819 "Look up a different location in the current file, keeping current visibility.
5821 When you want look-up or go to a different location in a document, the
5822 fastest way is often to fold the entire buffer and then dive into the tree.
5823 This method has the disadvantage, that the previous location will be folded,
5824 which may not be what you want.
5826 This command works around this by showing a copy of the current buffer
5827 in an indirect buffer, in overview mode. You can dive into the tree in
5828 that copy, use org-occur and incremental search to find a location.
5829 When pressing RET or `Q', the command returns to the original buffer in
5830 which the visibility is still unchanged. After RET is will also jump to
5831 the location selected in the indirect buffer and expose the
5832 the headline hierarchy above."
5833 (interactive)
5834 (let* ((org-goto-start-pos (point))
5835 (selected-point
5836 (car (org-get-location (current-buffer) org-goto-help))))
5837 (if selected-point
5838 (progn
5839 (org-mark-ring-push org-goto-start-pos)
5840 (goto-char selected-point)
5841 (if (or (org-invisible-p) (org-invisible-p2))
5842 (org-show-context 'org-goto)))
5843 (message "Quit"))))
5845 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5846 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5848 (defun org-get-location (buf help)
5849 "Let the user select a location in the Org-mode buffer BUF.
5850 This function uses a recursive edit. It returns the selected position
5851 or nil."
5852 (let (org-goto-selected-point org-goto-exit-command)
5853 (save-excursion
5854 (save-window-excursion
5855 (delete-other-windows)
5856 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5857 (switch-to-buffer
5858 (condition-case nil
5859 (make-indirect-buffer (current-buffer) "*org-goto*")
5860 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5861 (with-output-to-temp-buffer "*Help*"
5862 (princ help))
5863 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
5864 (setq buffer-read-only nil)
5865 (let ((org-startup-truncated t)
5866 (org-startup-folded nil)
5867 (org-startup-align-all-tables nil))
5868 (org-mode)
5869 (org-overview))
5870 (setq buffer-read-only t)
5871 (if (and (boundp 'org-goto-start-pos)
5872 (integer-or-marker-p org-goto-start-pos))
5873 (let ((org-show-hierarchy-above t)
5874 (org-show-siblings t)
5875 (org-show-following-heading t))
5876 (goto-char org-goto-start-pos)
5877 (and (org-invisible-p) (org-show-context)))
5878 (goto-char (point-min)))
5879 (org-beginning-of-line)
5880 (message "Select location and press RET")
5881 ;; now we make sure that during selection, ony very few keys work
5882 ;; and that it is impossible to switch to another window.
5883 ; (let ((gm (current-global-map))
5884 ; (overriding-local-map org-goto-map))
5885 ; (unwind-protect
5886 ; (progn
5887 ; (use-global-map org-goto-map)
5888 ; (recursive-edit))
5889 ; (use-global-map gm)))
5890 (use-local-map org-goto-map)
5891 (recursive-edit)
5893 (kill-buffer "*org-goto*")
5894 (cons org-goto-selected-point org-goto-exit-command)))
5896 (defun org-goto-ret (&optional arg)
5897 "Finish `org-goto' by going to the new location."
5898 (interactive "P")
5899 (setq org-goto-selected-point (point)
5900 org-goto-exit-command 'return)
5901 (throw 'exit nil))
5903 (defun org-goto-left ()
5904 "Finish `org-goto' by going to the new location."
5905 (interactive)
5906 (if (org-on-heading-p)
5907 (progn
5908 (beginning-of-line 1)
5909 (setq org-goto-selected-point (point)
5910 org-goto-exit-command 'left)
5911 (throw 'exit nil))
5912 (error "Not on a heading")))
5914 (defun org-goto-right ()
5915 "Finish `org-goto' by going to the new location."
5916 (interactive)
5917 (if (org-on-heading-p)
5918 (progn
5919 (setq org-goto-selected-point (point)
5920 org-goto-exit-command 'right)
5921 (throw 'exit nil))
5922 (error "Not on a heading")))
5924 (defun org-goto-quit ()
5925 "Finish `org-goto' without cursor motion."
5926 (interactive)
5927 (setq org-goto-selected-point nil)
5928 (setq org-goto-exit-command 'quit)
5929 (throw 'exit nil))
5931 ;;; Indirect buffer display of subtrees
5933 (defvar org-indirect-dedicated-frame nil
5934 "This is the frame being used for indirect tree display.")
5935 (defvar org-last-indirect-buffer nil)
5937 (defun org-tree-to-indirect-buffer (&optional arg)
5938 "Create indirect buffer and narrow it to current subtree.
5939 With numerical prefix ARG, go up to this level and then take that tree.
5940 If ARG is negative, go up that many levels.
5941 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5942 indirect buffer previously made with this command, to avoid proliferation of
5943 indirect buffers. However, when you call the command with a `C-u' prefix, or
5944 when `org-indirect-buffer-display' is `new-frame', the last buffer
5945 is kept so that you can work with several indirect buffers at the same time.
5946 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5947 requests that a new frame be made for the new buffer, so that the dedicated
5948 frame is not changed."
5949 (interactive "P")
5950 (let ((cbuf (current-buffer))
5951 (cwin (selected-window))
5952 (pos (point))
5953 beg end level heading ibuf)
5954 (save-excursion
5955 (org-back-to-heading t)
5956 (when (numberp arg)
5957 (setq level (org-outline-level))
5958 (if (< arg 0) (setq arg (+ level arg)))
5959 (while (> (setq level (org-outline-level)) arg)
5960 (outline-up-heading 1 t)))
5961 (setq beg (point)
5962 heading (org-get-heading))
5963 (org-end-of-subtree t) (setq end (point)))
5964 (if (and (buffer-live-p org-last-indirect-buffer)
5965 (not (eq org-indirect-buffer-display 'new-frame))
5966 (not arg))
5967 (kill-buffer org-last-indirect-buffer))
5968 (setq ibuf (org-get-indirect-buffer cbuf)
5969 org-last-indirect-buffer ibuf)
5970 (cond
5971 ((or (eq org-indirect-buffer-display 'new-frame)
5972 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5973 (select-frame (make-frame))
5974 (delete-other-windows)
5975 (switch-to-buffer ibuf)
5976 (org-set-frame-title heading))
5977 ((eq org-indirect-buffer-display 'dedicated-frame)
5978 (raise-frame
5979 (select-frame (or (and org-indirect-dedicated-frame
5980 (frame-live-p org-indirect-dedicated-frame)
5981 org-indirect-dedicated-frame)
5982 (setq org-indirect-dedicated-frame (make-frame)))))
5983 (delete-other-windows)
5984 (switch-to-buffer ibuf)
5985 (org-set-frame-title (concat "Indirect: " heading)))
5986 ((eq org-indirect-buffer-display 'current-window)
5987 (switch-to-buffer ibuf))
5988 ((eq org-indirect-buffer-display 'other-window)
5989 (pop-to-buffer ibuf))
5990 (t (error "Invalid value.")))
5991 (if (featurep 'xemacs)
5992 (save-excursion (org-mode) (turn-on-font-lock)))
5993 (narrow-to-region beg end)
5994 (show-all)
5995 (goto-char pos)
5996 (and (window-live-p cwin) (select-window cwin))))
5998 (defun org-get-indirect-buffer (&optional buffer)
5999 (setq buffer (or buffer (current-buffer)))
6000 (let ((n 1) (base (buffer-name buffer)) bname)
6001 (while (buffer-live-p
6002 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6003 (setq n (1+ n)))
6004 (condition-case nil
6005 (make-indirect-buffer buffer bname 'clone)
6006 (error (make-indirect-buffer buffer bname)))))
6008 (defun org-set-frame-title (title)
6009 "Set the title of the current frame to the string TITLE."
6010 ;; FIXME: how to name a single frame in XEmacs???
6011 (unless (featurep 'xemacs)
6012 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6014 ;;;; Structure editing
6016 ;;; Inserting headlines
6018 (defun org-insert-heading (&optional force-heading)
6019 "Insert a new heading or item with same depth at point.
6020 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6021 If point is at the beginning of a headline, insert a sibling before the
6022 current headline. If point is in the middle of a headline, split the headline
6023 at that position and make the rest of the headline part of the sibling below
6024 the current headline."
6025 (interactive "P")
6026 (if (= (buffer-size) 0)
6027 (insert "\n* ")
6028 (when (or force-heading (not (org-insert-item)))
6029 (let* ((head (save-excursion
6030 (condition-case nil
6031 (progn
6032 (org-back-to-heading)
6033 (match-string 0))
6034 (error "*"))))
6035 (blank (cdr (assq 'heading org-blank-before-new-entry)))
6036 pos)
6037 (cond
6038 ((and (org-on-heading-p) (bolp)
6039 (or (bobp)
6040 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6041 (open-line (if blank 2 1)))
6042 ((and (bolp)
6043 (or (bobp)
6044 (save-excursion
6045 (backward-char 1) (not (org-invisible-p)))))
6046 nil)
6047 (t (newline (if blank 2 1))))
6048 (insert head) (just-one-space)
6049 (setq pos (point))
6050 (end-of-line 1)
6051 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6052 (run-hooks 'org-insert-heading-hook)))))
6054 (defun org-insert-heading-after-current ()
6055 "Insert a new heading with same level as current, after current subtree."
6056 (interactive)
6057 (org-back-to-heading)
6058 (org-insert-heading)
6059 (org-move-subtree-down)
6060 (end-of-line 1))
6062 (defun org-insert-todo-heading (arg)
6063 "Insert a new heading with the same level and TODO state as current heading.
6064 If the heading has no TODO state, or if the state is DONE, use the first
6065 state (TODO by default). Also with prefix arg, force first state."
6066 (interactive "P")
6067 (when (not (org-insert-item 'checkbox))
6068 (org-insert-heading)
6069 (save-excursion
6070 (org-back-to-heading)
6071 (outline-previous-heading)
6072 (looking-at org-todo-line-regexp))
6073 (if (or arg
6074 (not (match-beginning 2))
6075 (member (match-string 2) org-done-keywords))
6076 (insert (car org-todo-keywords-1) " ")
6077 (insert (match-string 2) " "))))
6079 (defun org-insert-subheading (arg)
6080 "Insert a new subheading and demote it.
6081 Works for outline headings and for plain lists alike."
6082 (interactive "P")
6083 (org-insert-heading arg)
6084 (cond
6085 ((org-on-heading-p) (org-do-demote))
6086 ((org-at-item-p) (org-indent-item 1))))
6088 (defun org-insert-todo-subheading (arg)
6089 "Insert a new subheading with TODO keyword or checkbox and demote it.
6090 Works for outline headings and for plain lists alike."
6091 (interactive "P")
6092 (org-insert-todo-heading arg)
6093 (cond
6094 ((org-on-heading-p) (org-do-demote))
6095 ((org-at-item-p) (org-indent-item 1))))
6097 ;;; Promotion and Demotion
6099 (defun org-promote-subtree ()
6100 "Promote the entire subtree.
6101 See also `org-promote'."
6102 (interactive)
6103 (save-excursion
6104 (org-map-tree 'org-promote))
6105 (org-fix-position-after-promote))
6107 (defun org-demote-subtree ()
6108 "Demote the entire subtree. See `org-demote'.
6109 See also `org-promote'."
6110 (interactive)
6111 (save-excursion
6112 (org-map-tree 'org-demote))
6113 (org-fix-position-after-promote))
6116 (defun org-do-promote ()
6117 "Promote the current heading higher up the tree.
6118 If the region is active in `transient-mark-mode', promote all headings
6119 in the region."
6120 (interactive)
6121 (save-excursion
6122 (if (org-region-active-p)
6123 (org-map-region 'org-promote (region-beginning) (region-end))
6124 (org-promote)))
6125 (org-fix-position-after-promote))
6127 (defun org-do-demote ()
6128 "Demote the current heading lower down the tree.
6129 If the region is active in `transient-mark-mode', demote all headings
6130 in the region."
6131 (interactive)
6132 (save-excursion
6133 (if (org-region-active-p)
6134 (org-map-region 'org-demote (region-beginning) (region-end))
6135 (org-demote)))
6136 (org-fix-position-after-promote))
6138 (defun org-fix-position-after-promote ()
6139 "Make sure that after pro/demotion cursor position is right."
6140 (let ((pos (point)))
6141 (when (save-excursion
6142 (beginning-of-line 1)
6143 (looking-at org-todo-line-regexp)
6144 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6145 (cond ((eobp) (insert " "))
6146 ((eolp) (insert " "))
6147 ((equal (char-after) ?\ ) (forward-char 1))))))
6149 (defun org-reduced-level (l)
6150 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6152 (defun org-get-legal-level (level &optional change)
6153 "Rectify a level change under the influence of `org-odd-levels-only'
6154 LEVEL is a current level, CHANGE is by how much the level should be
6155 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6156 even level numbers will become the next higher odd number."
6157 (if org-odd-levels-only
6158 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6159 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6160 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6161 (max 1 (+ level change))))
6163 (defun org-promote ()
6164 "Promote the current heading higher up the tree.
6165 If the region is active in `transient-mark-mode', promote all headings
6166 in the region."
6167 (org-back-to-heading t)
6168 (let* ((level (save-match-data (funcall outline-level)))
6169 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
6170 (diff (abs (- level (length up-head) -1))))
6171 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6172 (replace-match up-head nil t)
6173 ;; Fixup tag positioning
6174 (and org-auto-align-tags (org-set-tags nil t))
6175 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
6177 (defun org-demote ()
6178 "Demote the current heading lower down the tree.
6179 If the region is active in `transient-mark-mode', demote all headings
6180 in the region."
6181 (org-back-to-heading t)
6182 (let* ((level (save-match-data (funcall outline-level)))
6183 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
6184 (diff (abs (- level (length down-head) -1))))
6185 (replace-match down-head nil t)
6186 ;; Fixup tag positioning
6187 (and org-auto-align-tags (org-set-tags nil t))
6188 (if org-adapt-indentation (org-fixup-indentation diff))))
6190 (defun org-map-tree (fun)
6191 "Call FUN for every heading underneath the current one."
6192 (org-back-to-heading)
6193 (let ((level (funcall outline-level)))
6194 (save-excursion
6195 (funcall fun)
6196 (while (and (progn
6197 (outline-next-heading)
6198 (> (funcall outline-level) level))
6199 (not (eobp)))
6200 (funcall fun)))))
6202 (defun org-map-region (fun beg end)
6203 "Call FUN for every heading between BEG and END."
6204 (let ((org-ignore-region t))
6205 (save-excursion
6206 (setq end (copy-marker end))
6207 (goto-char beg)
6208 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6209 (< (point) end))
6210 (funcall fun))
6211 (while (and (progn
6212 (outline-next-heading)
6213 (< (point) end))
6214 (not (eobp)))
6215 (funcall fun)))))
6217 (defun org-fixup-indentation (diff)
6218 "Change the indentation in the current entry by DIFF
6219 However, if any line in the current entry has no indentation, or if it
6220 would end up with no indentation after the change, nothing at all is done."
6221 (save-excursion
6222 (let ((end (save-excursion (outline-next-heading)
6223 (point-marker)))
6224 (prohibit (if (> diff 0)
6225 "^\\S-"
6226 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6227 col)
6228 (unless (save-excursion (end-of-line 1)
6229 (re-search-forward prohibit end t))
6230 (while (and (< (point) end)
6231 (re-search-forward "^[ \t]+" end t))
6232 (goto-char (match-end 0))
6233 (setq col (current-column))
6234 (if (< diff 0) (replace-match ""))
6235 (indent-to (+ diff col))))
6236 (move-marker end nil))))
6238 (defun org-convert-to-odd-levels ()
6239 "Convert an org-mode file with all levels allowed to one with odd levels.
6240 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6241 level 5 etc."
6242 (interactive)
6243 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6244 (let ((org-odd-levels-only nil) n)
6245 (save-excursion
6246 (goto-char (point-min))
6247 (while (re-search-forward "^\\*\\*+ " nil t)
6248 (setq n (- (length (match-string 0)) 2))
6249 (while (>= (setq n (1- n)) 0)
6250 (org-demote))
6251 (end-of-line 1))))))
6254 (defun org-convert-to-oddeven-levels ()
6255 "Convert an org-mode file with only odd levels to one with odd and even levels.
6256 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6257 section with an even level, conversion would destroy the structure of the file. An error
6258 is signaled in this case."
6259 (interactive)
6260 (goto-char (point-min))
6261 ;; First check if there are no even levels
6262 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6263 (org-show-context t)
6264 (error "Not all levels are odd in this file. Conversion not possible."))
6265 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6266 (let ((org-odd-levels-only nil) n)
6267 (save-excursion
6268 (goto-char (point-min))
6269 (while (re-search-forward "^\\*\\*+ " nil t)
6270 (setq n (/ (1- (length (match-string 0))) 2))
6271 (while (>= (setq n (1- n)) 0)
6272 (org-promote))
6273 (end-of-line 1))))))
6275 (defun org-tr-level (n)
6276 "Make N odd if required."
6277 (if org-odd-levels-only (1+ (/ n 2)) n))
6279 ;;; Vertical tree motion, cutting and pasting of subtrees
6281 (defun org-move-subtree-up (&optional arg)
6282 "Move the current subtree up past ARG headlines of the same level."
6283 (interactive "p")
6284 (org-move-subtree-down (- (prefix-numeric-value arg))))
6286 (defun org-move-subtree-down (&optional arg)
6287 "Move the current subtree down past ARG headlines of the same level."
6288 (interactive "p")
6289 (setq arg (prefix-numeric-value arg))
6290 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6291 'outline-get-last-sibling))
6292 (ins-point (make-marker))
6293 (cnt (abs arg))
6294 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6295 ;; Select the tree
6296 (org-back-to-heading)
6297 (setq beg0 (point))
6298 (save-excursion
6299 (setq ne-beg (org-back-over-empty-lines))
6300 (setq beg (point)))
6301 (save-match-data
6302 (save-excursion (outline-end-of-heading)
6303 (setq folded (org-invisible-p)))
6304 (outline-end-of-subtree))
6305 (outline-next-heading)
6306 (setq ne-end (org-back-over-empty-lines))
6307 (setq end (point))
6308 (goto-char beg0)
6309 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6310 ;; include less whitespace
6311 (save-excursion
6312 (goto-char beg)
6313 (forward-line (- ne-beg ne-end))
6314 (setq beg (point))))
6315 ;; Find insertion point, with error handling
6316 (while (> cnt 0)
6317 (or (and (funcall movfunc) (looking-at outline-regexp))
6318 (progn (goto-char beg0)
6319 (error "Cannot move past superior level or buffer limit")))
6320 (setq cnt (1- cnt)))
6321 (if (> arg 0)
6322 ;; Moving forward - still need to move over subtree
6323 (progn (outline-end-of-subtree)
6324 (org-back-over-empty-lines)
6325 (or (bolp) (newline))))
6326 (setq ne-ins (org-back-over-empty-lines))
6327 (move-marker ins-point (point))
6328 (setq txt (buffer-substring beg end))
6329 (delete-region beg end)
6330 (insert txt)
6331 (or (bolp) (insert "\n"))
6332 (setq ins-end (point))
6333 (goto-char ins-point)
6334 (org-skip-whitespace)
6335 (when (and (< arg 0)
6336 (org-first-sibling-p)
6337 (> ne-ins ne-beg))
6338 ;; Move whitespace back to beginning
6339 (save-excursion
6340 (goto-char ins-end)
6341 (let ((kill-whole-line t))
6342 (kill-line (- ne-ins ne-beg)) (point)))
6343 (insert (make-string (- ne-ins ne-beg) ?\n)))
6344 (if folded (hide-subtree))
6345 (move-marker ins-point nil)))
6347 (defvar org-subtree-clip ""
6348 "Clipboard for cut and paste of subtrees.
6349 This is actually only a copy of the kill, because we use the normal kill
6350 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6352 (defvar org-subtree-clip-folded nil
6353 "Was the last copied subtree folded?
6354 This is used to fold the tree back after pasting.")
6356 (defun org-cut-subtree (&optional n)
6357 "Cut the current subtree into the clipboard.
6358 With prefix arg N, cut this many sequential subtrees.
6359 This is a short-hand for marking the subtree and then cutting it."
6360 (interactive "p")
6361 (org-copy-subtree n 'cut))
6363 (defun org-copy-subtree (&optional n cut)
6364 "Cut the current subtree into the clipboard.
6365 With prefix arg N, cut this many sequential subtrees.
6366 This is a short-hand for marking the subtree and then copying it.
6367 If CUT is non-nil, actually cut the subtree."
6368 (interactive "p")
6369 (let (beg end folded)
6370 (if (interactive-p)
6371 (org-back-to-heading nil) ; take what looks like a subtree
6372 (org-back-to-heading t)) ; take what is really there
6373 (org-back-over-empty-lines)
6374 (setq beg (point))
6375 (skip-chars-forward " \t\r\n")
6376 (save-match-data
6377 (save-excursion (outline-end-of-heading)
6378 (setq folded (org-invisible-p)))
6379 (condition-case nil
6380 (outline-forward-same-level (1- n))
6381 (error nil))
6382 (org-end-of-subtree t t))
6383 (org-back-over-empty-lines)
6384 (setq end (point))
6385 (goto-char beg)
6386 (when (> end beg)
6387 (setq org-subtree-clip-folded folded)
6388 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6389 (setq org-subtree-clip (current-kill 0))
6390 (message "%s: Subtree(s) with %d characters"
6391 (if cut "Cut" "Copied")
6392 (length org-subtree-clip)))))
6394 (defun org-paste-subtree (&optional level tree)
6395 "Paste the clipboard as a subtree, with modification of headline level.
6396 The entire subtree is promoted or demoted in order to match a new headline
6397 level. By default, the new level is derived from the visible headings
6398 before and after the insertion point, and taken to be the inferior headline
6399 level of the two. So if the previous visible heading is level 3 and the
6400 next is level 4 (or vice versa), level 4 will be used for insertion.
6401 This makes sure that the subtree remains an independent subtree and does
6402 not swallow low level entries.
6404 You can also force a different level, either by using a numeric prefix
6405 argument, or by inserting the heading marker by hand. For example, if the
6406 cursor is after \"*****\", then the tree will be shifted to level 5.
6408 If you want to insert the tree as is, just use \\[yank].
6410 If optional TREE is given, use this text instead of the kill ring."
6411 (interactive "P")
6412 (unless (org-kill-is-subtree-p tree)
6413 (error "%s"
6414 (substitute-command-keys
6415 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6416 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6417 (^re (concat "^\\(" outline-regexp "\\)"))
6418 (re (concat "\\(" outline-regexp "\\)"))
6419 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6421 (old-level (if (string-match ^re txt)
6422 (- (match-end 0) (match-beginning 0) 1)
6423 -1))
6424 (force-level (cond (level (prefix-numeric-value level))
6425 ((string-match
6426 ^re_ (buffer-substring (point-at-bol) (point)))
6427 (- (match-end 1) (match-beginning 1)))
6428 (t nil)))
6429 (previous-level (save-excursion
6430 (condition-case nil
6431 (progn
6432 (outline-previous-visible-heading 1)
6433 (if (looking-at re)
6434 (- (match-end 0) (match-beginning 0) 1)
6436 (error 1))))
6437 (next-level (save-excursion
6438 (condition-case nil
6439 (progn
6440 (or (looking-at outline-regexp)
6441 (outline-next-visible-heading 1))
6442 (if (looking-at re)
6443 (- (match-end 0) (match-beginning 0) 1)
6445 (error 1))))
6446 (new-level (or force-level (max previous-level next-level)))
6447 (shift (if (or (= old-level -1)
6448 (= new-level -1)
6449 (= old-level new-level))
6451 (- new-level old-level)))
6452 (delta (if (> shift 0) -1 1))
6453 (func (if (> shift 0) 'org-demote 'org-promote))
6454 (org-odd-levels-only nil)
6455 beg end)
6456 ;; Remove the forced level indicator
6457 (if force-level
6458 (delete-region (point-at-bol) (point)))
6459 ;; Paste
6460 (beginning-of-line 1)
6461 (setq beg (point))
6462 (insert txt)
6463 (unless (string-match "\n\\'" txt) (insert "\n"))
6464 (setq end (point))
6465 (goto-char beg)
6466 (skip-chars-forward " \t\n\r")
6467 (setq beg (point))
6468 ;; Shift if necessary
6469 (unless (= shift 0)
6470 (save-restriction
6471 (narrow-to-region beg end)
6472 (while (not (= shift 0))
6473 (org-map-region func (point-min) (point-max))
6474 (setq shift (+ delta shift)))
6475 (goto-char (point-min))))
6476 (when (interactive-p)
6477 (message "Clipboard pasted as level %d subtree" new-level))
6478 (if (and kill-ring
6479 (eq org-subtree-clip (current-kill 0))
6480 org-subtree-clip-folded)
6481 ;; The tree was folded before it was killed/copied
6482 (hide-subtree))))
6484 (defun org-kill-is-subtree-p (&optional txt)
6485 "Check if the current kill is an outline subtree, or a set of trees.
6486 Returns nil if kill does not start with a headline, or if the first
6487 headline level is not the largest headline level in the tree.
6488 So this will actually accept several entries of equal levels as well,
6489 which is OK for `org-paste-subtree'.
6490 If optional TXT is given, check this string instead of the current kill."
6491 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6492 (start-level (and kill
6493 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6494 org-outline-regexp "\\)")
6495 kill)
6496 (- (match-end 2) (match-beginning 2) 1)))
6497 (re (concat "^" org-outline-regexp))
6498 (start (1+ (match-beginning 2))))
6499 (if (not start-level)
6500 (progn
6501 nil) ;; does not even start with a heading
6502 (catch 'exit
6503 (while (setq start (string-match re kill (1+ start)))
6504 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6505 (throw 'exit nil)))
6506 t))))
6508 (defun org-narrow-to-subtree ()
6509 "Narrow buffer to the current subtree."
6510 (interactive)
6511 (save-excursion
6512 (narrow-to-region
6513 (progn (org-back-to-heading) (point))
6514 (progn (org-end-of-subtree t t) (point)))))
6517 ;;; Outline Sorting
6519 (defun org-sort (with-case)
6520 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6521 Optional argument WITH-CASE means sort case-sensitively."
6522 (interactive "P")
6523 (if (org-at-table-p)
6524 (org-call-with-arg 'org-table-sort-lines with-case)
6525 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6527 (defvar org-priority-regexp) ; defined later in the file
6529 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6530 "Sort entries on a certain level of an outline tree.
6531 If there is an active region, the entries in the region are sorted.
6532 Else, if the cursor is before the first entry, sort the top-level items.
6533 Else, the children of the entry at point are sorted.
6535 Sorting can be alphabetically, numerically, and by date/time as given by
6536 the first time stamp in the entry. The command prompts for the sorting
6537 type unless it has been given to the function through the SORTING-TYPE
6538 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6539 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6540 called with point at the beginning of the record. It must return either
6541 a string or a number that should serve as the sorting key for that record.
6543 Comparing entries ignores case by default. However, with an optional argument
6544 WITH-CASE, the sorting considers case as well."
6545 (interactive "P")
6546 (let ((case-func (if with-case 'identity 'downcase))
6547 start beg end stars re re2
6548 txt what tmp plain-list-p)
6549 ;; Find beginning and end of region to sort
6550 (cond
6551 ((org-region-active-p)
6552 ;; we will sort the region
6553 (setq end (region-end)
6554 what "region")
6555 (goto-char (region-beginning))
6556 (if (not (org-on-heading-p)) (outline-next-heading))
6557 (setq start (point)))
6558 ((org-at-item-p)
6559 ;; we will sort this plain list
6560 (org-beginning-of-item-list) (setq start (point))
6561 (org-end-of-item-list) (setq end (point))
6562 (goto-char start)
6563 (setq plain-list-p t
6564 what "plain list"))
6565 ((or (org-on-heading-p)
6566 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6567 ;; we will sort the children of the current headline
6568 (org-back-to-heading)
6569 (setq start (point) end (org-end-of-subtree) what "children")
6570 (goto-char start)
6571 (show-subtree)
6572 (outline-next-heading))
6574 ;; we will sort the top-level entries in this file
6575 (goto-char (point-min))
6576 (or (org-on-heading-p) (outline-next-heading))
6577 (setq start (point) end (point-max) what "top-level")
6578 (goto-char start)
6579 (show-all)))
6581 (setq beg (point))
6582 (if (>= beg end) (error "Nothing to sort"))
6584 (unless plain-list-p
6585 (looking-at "\\(\\*+\\)")
6586 (setq stars (match-string 1)
6587 re (concat "^" (regexp-quote stars) " +")
6588 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6589 txt (buffer-substring beg end))
6590 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6591 (if (and (not (equal stars "*")) (string-match re2 txt))
6592 (error "Region to sort contains a level above the first entry")))
6594 (unless sorting-type
6595 (message
6596 (if plain-list-p
6597 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6598 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
6599 what)
6600 (setq sorting-type (read-char-exclusive))
6602 (and (= (downcase sorting-type) ?f)
6603 (setq getkey-func
6604 (completing-read "Sort using function: "
6605 obarray 'fboundp t nil nil))
6606 (setq getkey-func (intern getkey-func)))
6608 (and (= (downcase sorting-type) ?r)
6609 (setq property
6610 (completing-read "Property: "
6611 (mapcar 'list (org-buffer-property-keys t))
6612 nil t))))
6614 (message "Sorting entries...")
6616 (save-restriction
6617 (narrow-to-region start end)
6619 (let ((dcst (downcase sorting-type))
6620 (now (current-time)))
6621 (sort-subr
6622 (/= dcst sorting-type)
6623 ;; This function moves to the beginning character of the "record" to
6624 ;; be sorted.
6625 (if plain-list-p
6626 (lambda nil
6627 (if (org-at-item-p) t (goto-char (point-max))))
6628 (lambda nil
6629 (if (re-search-forward re nil t)
6630 (goto-char (match-beginning 0))
6631 (goto-char (point-max)))))
6632 ;; This function moves to the last character of the "record" being
6633 ;; sorted.
6634 (if plain-list-p
6635 'org-end-of-item
6636 (lambda nil
6637 (save-match-data
6638 (condition-case nil
6639 (outline-forward-same-level 1)
6640 (error
6641 (goto-char (point-max)))))))
6643 ;; This function returns the value that gets sorted against.
6644 (if plain-list-p
6645 (lambda nil
6646 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6647 (cond
6648 ((= dcst ?n)
6649 (string-to-number (buffer-substring (match-end 0)
6650 (point-at-eol))))
6651 ((= dcst ?a)
6652 (buffer-substring (match-end 0) (point-at-eol)))
6653 ((= dcst ?t)
6654 (if (re-search-forward org-ts-regexp
6655 (point-at-eol) t)
6656 (org-time-string-to-time (match-string 0))
6657 now))
6658 ((= dcst ?f)
6659 (if getkey-func
6660 (progn
6661 (setq tmp (funcall getkey-func))
6662 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6663 tmp)
6664 (error "Invalid key function `%s'" getkey-func)))
6665 (t (error "Invalid sorting type `%c'" sorting-type)))))
6666 (lambda nil
6667 (cond
6668 ((= dcst ?n)
6669 (if (looking-at outline-regexp)
6670 (string-to-number (buffer-substring (match-end 0)
6671 (point-at-eol)))
6672 nil))
6673 ((= dcst ?a)
6674 (funcall case-func (buffer-substring (point-at-bol)
6675 (point-at-eol))))
6676 ((= dcst ?t)
6677 (if (re-search-forward org-ts-regexp
6678 (save-excursion
6679 (forward-line 2)
6680 (point)) t)
6681 (org-time-string-to-time (match-string 0))
6682 now))
6683 ((= dcst ?p)
6684 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6685 (string-to-char (match-string 2))
6686 org-default-priority))
6687 ((= dcst ?r)
6688 (or (org-entry-get nil property) ""))
6689 ((= dcst ?f)
6690 (if getkey-func
6691 (progn
6692 (setq tmp (funcall getkey-func))
6693 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6694 tmp)
6695 (error "Invalid key function `%s'" getkey-func)))
6696 (t (error "Invalid sorting type `%c'" sorting-type)))))
6698 (cond
6699 ((= dcst ?a) 'string<)
6700 ((= dcst ?t) 'time-less-p)
6701 (t nil)))))
6702 (message "Sorting entries...done")))
6704 (defun org-do-sort (table what &optional with-case sorting-type)
6705 "Sort TABLE of WHAT according to SORTING-TYPE.
6706 The user will be prompted for the SORTING-TYPE if the call to this
6707 function does not specify it. WHAT is only for the prompt, to indicate
6708 what is being sorted. The sorting key will be extracted from
6709 the car of the elements of the table.
6710 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6711 (unless sorting-type
6712 (message
6713 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6714 what)
6715 (setq sorting-type (read-char-exclusive)))
6716 (let ((dcst (downcase sorting-type))
6717 extractfun comparefun)
6718 ;; Define the appropriate functions
6719 (cond
6720 ((= dcst ?n)
6721 (setq extractfun 'string-to-number
6722 comparefun (if (= dcst sorting-type) '< '>)))
6723 ((= dcst ?a)
6724 (setq extractfun (if with-case 'identity 'downcase)
6725 comparefun (if (= dcst sorting-type)
6726 'string<
6727 (lambda (a b) (and (not (string< a b))
6728 (not (string= a b)))))))
6729 ((= dcst ?t)
6730 (setq extractfun
6731 (lambda (x)
6732 (if (string-match org-ts-regexp x)
6733 (time-to-seconds
6734 (org-time-string-to-time (match-string 0 x)))
6736 comparefun (if (= dcst sorting-type) '< '>)))
6737 (t (error "Invalid sorting type `%c'" sorting-type)))
6739 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6740 table)
6741 (lambda (a b) (funcall comparefun (car a) (car b))))))
6743 ;;;; Plain list items, including checkboxes
6745 ;;; Plain list items
6747 (defun org-at-item-p ()
6748 "Is point in a line starting a hand-formatted item?"
6749 (let ((llt org-plain-list-ordered-item-terminator))
6750 (save-excursion
6751 (goto-char (point-at-bol))
6752 (looking-at
6753 (cond
6754 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6755 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6756 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6757 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
6759 (defun org-in-item-p ()
6760 "It the cursor inside a plain list item.
6761 Does not have to be the first line."
6762 (save-excursion
6763 (condition-case nil
6764 (progn
6765 (org-beginning-of-item)
6766 (org-at-item-p)
6768 (error nil))))
6770 (defun org-insert-item (&optional checkbox)
6771 "Insert a new item at the current level.
6772 Return t when things worked, nil when we are not in an item."
6773 (when (save-excursion
6774 (condition-case nil
6775 (progn
6776 (org-beginning-of-item)
6777 (org-at-item-p)
6778 (if (org-invisible-p) (error "Invisible item"))
6780 (error nil)))
6781 (let* ((bul (match-string 0))
6782 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
6783 (match-end 0)))
6784 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
6785 pos)
6786 (cond
6787 ((and (org-at-item-p) (<= (point) eow))
6788 ;; before the bullet
6789 (beginning-of-line 1)
6790 (open-line (if blank 2 1)))
6791 ((<= (point) eow)
6792 (beginning-of-line 1))
6793 (t (newline (if blank 2 1))))
6794 (insert bul (if checkbox "[ ]" ""))
6795 (just-one-space)
6796 (setq pos (point))
6797 (end-of-line 1)
6798 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
6799 (org-maybe-renumber-ordered-list)
6800 (and checkbox (org-update-checkbox-count-maybe))
6803 ;;; Checkboxes
6805 (defun org-at-item-checkbox-p ()
6806 "Is point at a line starting a plain-list item with a checklet?"
6807 (and (org-at-item-p)
6808 (save-excursion
6809 (goto-char (match-end 0))
6810 (skip-chars-forward " \t")
6811 (looking-at "\\[[- X]\\]"))))
6813 (defun org-toggle-checkbox (&optional arg)
6814 "Toggle the checkbox in the current line."
6815 (interactive "P")
6816 (catch 'exit
6817 (let (beg end status (firstnew 'unknown))
6818 (cond
6819 ((org-region-active-p)
6820 (setq beg (region-beginning) end (region-end)))
6821 ((org-on-heading-p)
6822 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
6823 ((org-at-item-checkbox-p)
6824 (let ((pos (point)))
6825 (replace-match
6826 (cond (arg "[-]")
6827 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
6828 (t "[ ]"))
6829 t t)
6830 (goto-char pos))
6831 (throw 'exit t))
6832 (t (error "Not at a checkbox or heading, and no active region")))
6833 (save-excursion
6834 (goto-char beg)
6835 (while (< (point) end)
6836 (when (org-at-item-checkbox-p)
6837 (setq status (equal (match-string 0) "[X]"))
6838 (when (eq firstnew 'unknown)
6839 (setq firstnew (not status)))
6840 (replace-match
6841 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
6842 (beginning-of-line 2)))))
6843 (org-update-checkbox-count-maybe))
6845 (defun org-update-checkbox-count-maybe ()
6846 "Update checkbox statistics unless turned off by user."
6847 (when org-provide-checkbox-statistics
6848 (org-update-checkbox-count)))
6850 (defun org-update-checkbox-count (&optional all)
6851 "Update the checkbox statistics in the current section.
6852 This will find all statistic cookies like [57%] and [6/12] and update them
6853 with the current numbers. With optional prefix argument ALL, do this for
6854 the whole buffer."
6855 (interactive "P")
6856 (save-excursion
6857 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
6858 (beg (condition-case nil
6859 (progn (outline-back-to-heading) (point))
6860 (error (point-min))))
6861 (end (move-marker (make-marker)
6862 (progn (outline-next-heading) (point))))
6863 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
6864 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
6865 b1 e1 f1 c-on c-off lim (cstat 0))
6866 (when all
6867 (goto-char (point-min))
6868 (outline-next-heading)
6869 (setq beg (point) end (point-max)))
6870 (goto-char beg)
6871 (while (re-search-forward re end t)
6872 (setq cstat (1+ cstat)
6873 b1 (match-beginning 0)
6874 e1 (match-end 0)
6875 f1 (match-beginning 1)
6876 lim (cond
6877 ((org-on-heading-p) (outline-next-heading) (point))
6878 ((org-at-item-p) (org-end-of-item) (point))
6879 (t nil))
6880 c-on 0 c-off 0)
6881 (goto-char e1)
6882 (when lim
6883 (while (re-search-forward re-box lim t)
6884 (if (member (match-string 2) '("[ ]" "[-]"))
6885 (setq c-off (1+ c-off))
6886 (setq c-on (1+ c-on))))
6887 ; (delete-region b1 e1)
6888 (goto-char b1)
6889 (insert (if f1
6890 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
6891 (format "[%d/%d]" c-on (+ c-on c-off))))
6892 (and (looking-at "\\[.*?\\]")
6893 (replace-match ""))))
6894 (when (interactive-p)
6895 (message "Checkbox satistics updated %s (%d places)"
6896 (if all "in entire file" "in current outline entry") cstat)))))
6898 (defun org-get-checkbox-statistics-face ()
6899 "Select the face for checkbox statistics.
6900 The face will be `org-done' when all relevant boxes are checked. Otherwise
6901 it will be `org-todo'."
6902 (if (match-end 1)
6903 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
6904 (if (and (> (match-end 2) (match-beginning 2))
6905 (equal (match-string 2) (match-string 3)))
6906 'org-done
6907 'org-todo)))
6909 (defun org-get-indentation (&optional line)
6910 "Get the indentation of the current line, interpreting tabs.
6911 When LINE is given, assume it represents a line and compute its indentation."
6912 (if line
6913 (if (string-match "^ *" (org-remove-tabs line))
6914 (match-end 0))
6915 (save-excursion
6916 (beginning-of-line 1)
6917 (skip-chars-forward " \t")
6918 (current-column))))
6920 (defun org-remove-tabs (s &optional width)
6921 "Replace tabulators in S with spaces.
6922 Assumes that s is a single line, starting in column 0."
6923 (setq width (or width tab-width))
6924 (while (string-match "\t" s)
6925 (setq s (replace-match
6926 (make-string
6927 (- (* width (/ (+ (match-beginning 0) width) width))
6928 (match-beginning 0)) ?\ )
6929 t t s)))
6932 (defun org-fix-indentation (line ind)
6933 "Fix indentation in LINE.
6934 IND is a cons cell with target and minimum indentation.
6935 If the current indenation in LINE is smaller than the minimum,
6936 leave it alone. If it is larger than ind, set it to the target."
6937 (let* ((l (org-remove-tabs line))
6938 (i (org-get-indentation l))
6939 (i1 (car ind)) (i2 (cdr ind)))
6940 (if (>= i i2) (setq l (substring line i2)))
6941 (if (> i1 0)
6942 (concat (make-string i1 ?\ ) l)
6943 l)))
6945 (defcustom org-empty-line-terminates-plain-lists nil
6946 "Non-nil means, an empty line ends all plain list levels.
6947 When nil, empty lines are part of the preceeding item."
6948 :group 'org-plain-lists
6949 :type 'boolean)
6951 (defun org-beginning-of-item ()
6952 "Go to the beginning of the current hand-formatted item.
6953 If the cursor is not in an item, throw an error."
6954 (interactive)
6955 (let ((pos (point))
6956 (limit (save-excursion
6957 (condition-case nil
6958 (progn
6959 (org-back-to-heading)
6960 (beginning-of-line 2) (point))
6961 (error (point-min)))))
6962 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
6963 ind ind1)
6964 (if (org-at-item-p)
6965 (beginning-of-line 1)
6966 (beginning-of-line 1)
6967 (skip-chars-forward " \t")
6968 (setq ind (current-column))
6969 (if (catch 'exit
6970 (while t
6971 (beginning-of-line 0)
6972 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
6974 (if (looking-at "[ \t]*$")
6975 (setq ind1 ind-empty)
6976 (skip-chars-forward " \t")
6977 (setq ind1 (current-column)))
6978 (if (< ind1 ind)
6979 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
6981 (goto-char pos)
6982 (error "Not in an item")))))
6984 (defun org-end-of-item ()
6985 "Go to the end of the current hand-formatted item.
6986 If the cursor is not in an item, throw an error."
6987 (interactive)
6988 (let* ((pos (point))
6989 ind1
6990 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
6991 (limit (save-excursion (outline-next-heading) (point)))
6992 (ind (save-excursion
6993 (org-beginning-of-item)
6994 (skip-chars-forward " \t")
6995 (current-column)))
6996 (end (catch 'exit
6997 (while t
6998 (beginning-of-line 2)
6999 (if (eobp) (throw 'exit (point)))
7000 (if (>= (point) limit) (throw 'exit (point-at-bol)))
7001 (if (looking-at "[ \t]*$")
7002 (setq ind1 ind-empty)
7003 (skip-chars-forward " \t")
7004 (setq ind1 (current-column)))
7005 (if (<= ind1 ind)
7006 (throw 'exit (point-at-bol)))))))
7007 (if end
7008 (goto-char end)
7009 (goto-char pos)
7010 (error "Not in an item"))))
7012 (defun org-next-item ()
7013 "Move to the beginning of the next item in the current plain list.
7014 Error if not at a plain list, or if this is the last item in the list."
7015 (interactive)
7016 (let (ind ind1 (pos (point)))
7017 (org-beginning-of-item)
7018 (setq ind (org-get-indentation))
7019 (org-end-of-item)
7020 (setq ind1 (org-get-indentation))
7021 (unless (and (org-at-item-p) (= ind ind1))
7022 (goto-char pos)
7023 (error "On last item"))))
7025 (defun org-previous-item ()
7026 "Move to the beginning of the previous item in the current plain list.
7027 Error if not at a plain list, or if this is the first item in the list."
7028 (interactive)
7029 (let (beg ind ind1 (pos (point)))
7030 (org-beginning-of-item)
7031 (setq beg (point))
7032 (setq ind (org-get-indentation))
7033 (goto-char beg)
7034 (catch 'exit
7035 (while t
7036 (beginning-of-line 0)
7037 (if (looking-at "[ \t]*$")
7039 (if (<= (setq ind1 (org-get-indentation)) ind)
7040 (throw 'exit t)))))
7041 (condition-case nil
7042 (if (or (not (org-at-item-p))
7043 (< ind1 (1- ind)))
7044 (error "")
7045 (org-beginning-of-item))
7046 (error (goto-char pos)
7047 (error "On first item")))))
7049 (defun org-move-item-down ()
7050 "Move the plain list item at point down, i.e. swap with following item.
7051 Subitems (items with larger indentation) are considered part of the item,
7052 so this really moves item trees."
7053 (interactive)
7054 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
7055 (org-beginning-of-item)
7056 (setq beg0 (point))
7057 (save-excursion
7058 (setq ne-beg (org-back-over-empty-lines))
7059 (setq beg (point)))
7060 (goto-char beg0)
7061 (setq ind (org-get-indentation))
7062 (org-end-of-item)
7063 (setq end0 (point))
7064 (setq ind1 (org-get-indentation))
7065 (setq ne-end (org-back-over-empty-lines))
7066 (setq end (point))
7067 (goto-char beg0)
7068 (when (and (org-first-list-item-p) (< ne-end ne-beg))
7069 ;; include less whitespace
7070 (save-excursion
7071 (goto-char beg)
7072 (forward-line (- ne-beg ne-end))
7073 (setq beg (point))))
7074 (goto-char end0)
7075 (if (and (org-at-item-p) (= ind ind1))
7076 (progn
7077 (org-end-of-item)
7078 (org-back-over-empty-lines)
7079 (setq txt (buffer-substring beg end))
7080 (save-excursion
7081 (delete-region beg end))
7082 (setq pos (point))
7083 (insert txt)
7084 (goto-char pos) (org-skip-whitespace)
7085 (org-maybe-renumber-ordered-list))
7086 (goto-char pos)
7087 (error "Cannot move this item further down"))))
7089 (defun org-move-item-up (arg)
7090 "Move the plain list item at point up, i.e. swap with previous item.
7091 Subitems (items with larger indentation) are considered part of the item,
7092 so this really moves item trees."
7093 (interactive "p")
7094 (let (beg beg0 end end0 ind ind1 (pos (point)) txt
7095 ne-beg ne-end ne-ins ins-end)
7096 (org-beginning-of-item)
7097 (setq beg0 (point))
7098 (setq ind (org-get-indentation))
7099 (save-excursion
7100 (setq ne-beg (org-back-over-empty-lines))
7101 (setq beg (point)))
7102 (goto-char beg0)
7103 (org-end-of-item)
7104 (setq ne-end (org-back-over-empty-lines))
7105 (setq end (point))
7106 (goto-char beg0)
7107 (catch 'exit
7108 (while t
7109 (beginning-of-line 0)
7110 (if (looking-at "[ \t]*$")
7111 (if org-empty-line-terminates-plain-lists
7112 (progn
7113 (goto-char pos)
7114 (error "Cannot move this item further up"))
7115 nil)
7116 (if (<= (setq ind1 (org-get-indentation)) ind)
7117 (throw 'exit t)))))
7118 (condition-case nil
7119 (org-beginning-of-item)
7120 (error (goto-char beg)
7121 (error "Cannot move this item further up")))
7122 (setq ind1 (org-get-indentation))
7123 (if (and (org-at-item-p) (= ind ind1))
7124 (progn
7125 (setq ne-ins (org-back-over-empty-lines))
7126 (setq txt (buffer-substring beg end))
7127 (save-excursion
7128 (delete-region beg end))
7129 (setq pos (point))
7130 (insert txt)
7131 (setq ins-end (point))
7132 (goto-char pos) (org-skip-whitespace)
7134 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
7135 ;; Move whitespace back to beginning
7136 (save-excursion
7137 (goto-char ins-end)
7138 (let ((kill-whole-line t))
7139 (kill-line (- ne-ins ne-beg)) (point)))
7140 (insert (make-string (- ne-ins ne-beg) ?\n)))
7142 (org-maybe-renumber-ordered-list))
7143 (goto-char pos)
7144 (error "Cannot move this item further up"))))
7146 (defun org-maybe-renumber-ordered-list ()
7147 "Renumber the ordered list at point if setup allows it.
7148 This tests the user option `org-auto-renumber-ordered-lists' before
7149 doing the renumbering."
7150 (interactive)
7151 (when (and org-auto-renumber-ordered-lists
7152 (org-at-item-p))
7153 (if (match-beginning 3)
7154 (org-renumber-ordered-list 1)
7155 (org-fix-bullet-type))))
7157 (defun org-maybe-renumber-ordered-list-safe ()
7158 (condition-case nil
7159 (save-excursion
7160 (org-maybe-renumber-ordered-list))
7161 (error nil)))
7163 (defun org-cycle-list-bullet (&optional which)
7164 "Cycle through the different itemize/enumerate bullets.
7165 This cycle the entire list level through the sequence:
7167 `-' -> `+' -> `*' -> `1.' -> `1)'
7169 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7170 0 meand `-', 1 means `+' etc."
7171 (interactive "P")
7172 (org-preserve-lc
7173 (org-beginning-of-item-list)
7174 (org-at-item-p)
7175 (beginning-of-line 1)
7176 (let ((current (match-string 0))
7177 (prevp (eq which 'previous))
7178 new)
7179 (setq new (cond
7180 ((and (numberp which)
7181 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7182 ((string-match "-" current) (if prevp "1)" "+"))
7183 ((string-match "\\+" current)
7184 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7185 ((string-match "\\*" current) (if prevp "+" "1."))
7186 ((string-match "\\." current) (if prevp "*" "1)"))
7187 ((string-match ")" current) (if prevp "1." "-"))
7188 (t (error "This should not happen"))))
7189 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7190 (org-fix-bullet-type)
7191 (org-maybe-renumber-ordered-list))))
7193 (defun org-get-string-indentation (s)
7194 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7195 (let ((n -1) (i 0) (w tab-width) c)
7196 (catch 'exit
7197 (while (< (setq n (1+ n)) (length s))
7198 (setq c (aref s n))
7199 (cond ((= c ?\ ) (setq i (1+ i)))
7200 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7201 (t (throw 'exit t)))))
7204 (defun org-renumber-ordered-list (arg)
7205 "Renumber an ordered plain list.
7206 Cursor needs to be in the first line of an item, the line that starts
7207 with something like \"1.\" or \"2)\"."
7208 (interactive "p")
7209 (unless (and (org-at-item-p)
7210 (match-beginning 3))
7211 (error "This is not an ordered list"))
7212 (let ((line (org-current-line))
7213 (col (current-column))
7214 (ind (org-get-string-indentation
7215 (buffer-substring (point-at-bol) (match-beginning 3))))
7216 ;; (term (substring (match-string 3) -1))
7217 ind1 (n (1- arg))
7218 fmt)
7219 ;; find where this list begins
7220 (org-beginning-of-item-list)
7221 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7222 (setq fmt (concat "%d" (match-string 1)))
7223 (beginning-of-line 0)
7224 ;; walk forward and replace these numbers
7225 (catch 'exit
7226 (while t
7227 (catch 'next
7228 (beginning-of-line 2)
7229 (if (eobp) (throw 'exit nil))
7230 (if (looking-at "[ \t]*$") (throw 'next nil))
7231 (skip-chars-forward " \t") (setq ind1 (current-column))
7232 (if (> ind1 ind) (throw 'next t))
7233 (if (< ind1 ind) (throw 'exit t))
7234 (if (not (org-at-item-p)) (throw 'exit nil))
7235 (delete-region (match-beginning 2) (match-end 2))
7236 (goto-char (match-beginning 2))
7237 (insert (format fmt (setq n (1+ n)))))))
7238 (goto-line line)
7239 (move-to-column col)))
7241 (defun org-fix-bullet-type ()
7242 "Make sure all items in this list have the same bullet as the firsst item."
7243 (interactive)
7244 (unless (org-at-item-p) (error "This is not a list"))
7245 (let ((line (org-current-line))
7246 (col (current-column))
7247 (ind (current-indentation))
7248 ind1 bullet)
7249 ;; find where this list begins
7250 (org-beginning-of-item-list)
7251 (beginning-of-line 1)
7252 ;; find out what the bullet type is
7253 (looking-at "[ \t]*\\(\\S-+\\)")
7254 (setq bullet (match-string 1))
7255 ;; walk forward and replace these numbers
7256 (beginning-of-line 0)
7257 (catch 'exit
7258 (while t
7259 (catch 'next
7260 (beginning-of-line 2)
7261 (if (eobp) (throw 'exit nil))
7262 (if (looking-at "[ \t]*$") (throw 'next nil))
7263 (skip-chars-forward " \t") (setq ind1 (current-column))
7264 (if (> ind1 ind) (throw 'next t))
7265 (if (< ind1 ind) (throw 'exit t))
7266 (if (not (org-at-item-p)) (throw 'exit nil))
7267 (skip-chars-forward " \t")
7268 (looking-at "\\S-+")
7269 (replace-match bullet))))
7270 (goto-line line)
7271 (move-to-column col)
7272 (if (string-match "[0-9]" bullet)
7273 (org-renumber-ordered-list 1))))
7275 (defun org-beginning-of-item-list ()
7276 "Go to the beginning of the current item list.
7277 I.e. to the first item in this list."
7278 (interactive)
7279 (org-beginning-of-item)
7280 (let ((pos (point-at-bol))
7281 (ind (org-get-indentation))
7282 ind1)
7283 ;; find where this list begins
7284 (catch 'exit
7285 (while t
7286 (catch 'next
7287 (beginning-of-line 0)
7288 (if (looking-at "[ \t]*$")
7289 (throw (if (bobp) 'exit 'next) t))
7290 (skip-chars-forward " \t") (setq ind1 (current-column))
7291 (if (or (< ind1 ind)
7292 (and (= ind1 ind)
7293 (not (org-at-item-p)))
7294 (bobp))
7295 (throw 'exit t)
7296 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7297 (goto-char pos)))
7300 (defun org-end-of-item-list ()
7301 "Go to the end of the current item list.
7302 I.e. to the text after the last item."
7303 (interactive)
7304 (org-beginning-of-item)
7305 (let ((pos (point-at-bol))
7306 (ind (org-get-indentation))
7307 ind1)
7308 ;; find where this list begins
7309 (catch 'exit
7310 (while t
7311 (catch 'next
7312 (beginning-of-line 2)
7313 (if (looking-at "[ \t]*$")
7314 (throw (if (eobp) 'exit 'next) t))
7315 (skip-chars-forward " \t") (setq ind1 (current-column))
7316 (if (or (< ind1 ind)
7317 (and (= ind1 ind)
7318 (not (org-at-item-p)))
7319 (eobp))
7320 (progn
7321 (setq pos (point-at-bol))
7322 (throw 'exit t))))))
7323 (goto-char pos)))
7326 (defvar org-last-indent-begin-marker (make-marker))
7327 (defvar org-last-indent-end-marker (make-marker))
7329 (defun org-outdent-item (arg)
7330 "Outdent a local list item."
7331 (interactive "p")
7332 (org-indent-item (- arg)))
7334 (defun org-indent-item (arg)
7335 "Indent a local list item."
7336 (interactive "p")
7337 (unless (org-at-item-p)
7338 (error "Not on an item"))
7339 (save-excursion
7340 (let (beg end ind ind1 tmp delta ind-down ind-up)
7341 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7342 (setq beg org-last-indent-begin-marker
7343 end org-last-indent-end-marker)
7344 (org-beginning-of-item)
7345 (setq beg (move-marker org-last-indent-begin-marker (point)))
7346 (org-end-of-item)
7347 (setq end (move-marker org-last-indent-end-marker (point))))
7348 (goto-char beg)
7349 (setq tmp (org-item-indent-positions)
7350 ind (car tmp)
7351 ind-down (nth 2 tmp)
7352 ind-up (nth 1 tmp)
7353 delta (if (> arg 0)
7354 (if ind-down (- ind-down ind) 2)
7355 (if ind-up (- ind-up ind) -2)))
7356 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7357 (while (< (point) end)
7358 (beginning-of-line 1)
7359 (skip-chars-forward " \t") (setq ind1 (current-column))
7360 (delete-region (point-at-bol) (point))
7361 (or (eolp) (indent-to-column (+ ind1 delta)))
7362 (beginning-of-line 2))))
7363 (org-fix-bullet-type)
7364 (org-maybe-renumber-ordered-list-safe)
7365 (save-excursion
7366 (beginning-of-line 0)
7367 (condition-case nil (org-beginning-of-item) (error nil))
7368 (org-maybe-renumber-ordered-list-safe)))
7370 (defun org-item-indent-positions ()
7371 "Return indentation for plain list items.
7372 This returns a list with three values: The current indentation, the
7373 parent indentation and the indentation a child should habe.
7374 Assumes cursor in item line."
7375 (let* ((bolpos (point-at-bol))
7376 (ind (org-get-indentation))
7377 ind-down ind-up pos)
7378 (save-excursion
7379 (org-beginning-of-item-list)
7380 (skip-chars-backward "\n\r \t")
7381 (when (org-in-item-p)
7382 (org-beginning-of-item)
7383 (setq ind-up (org-get-indentation))))
7384 (setq pos (point))
7385 (save-excursion
7386 (cond
7387 ((and (condition-case nil (progn (org-previous-item) t)
7388 (error nil))
7389 (or (forward-char 1) t)
7390 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7391 (setq ind-down (org-get-indentation)))
7392 ((and (goto-char pos)
7393 (org-at-item-p))
7394 (goto-char (match-end 0))
7395 (skip-chars-forward " \t")
7396 (setq ind-down (current-column)))))
7397 (list ind ind-up ind-down)))
7399 ;;; The orgstruct minor mode
7401 ;; Define a minor mode which can be used in other modes in order to
7402 ;; integrate the org-mode structure editing commands.
7404 ;; This is really a hack, because the org-mode structure commands use
7405 ;; keys which normally belong to the major mode. Here is how it
7406 ;; works: The minor mode defines all the keys necessary to operate the
7407 ;; structure commands, but wraps the commands into a function which
7408 ;; tests if the cursor is currently at a headline or a plain list
7409 ;; item. If that is the case, the structure command is used,
7410 ;; temporarily setting many Org-mode variables like regular
7411 ;; expressions for filling etc. However, when any of those keys is
7412 ;; used at a different location, function uses `key-binding' to look
7413 ;; up if the key has an associated command in another currently active
7414 ;; keymap (minor modes, major mode, global), and executes that
7415 ;; command. There might be problems if any of the keys is otherwise
7416 ;; used as a prefix key.
7418 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7419 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7420 ;; addresses this by checking explicitly for both bindings.
7422 (defvar orgstruct-mode-map (make-sparse-keymap)
7423 "Keymap for the minor `orgstruct-mode'.")
7425 (defvar org-local-vars nil
7426 "List of local variables, for use by `orgstruct-mode'")
7428 ;;;###autoload
7429 (define-minor-mode orgstruct-mode
7430 "Toggle the minor more `orgstruct-mode'.
7431 This mode is for using Org-mode structure commands in other modes.
7432 The following key behave as if Org-mode was active, if the cursor
7433 is on a headline, or on a plain list item (both in the definition
7434 of Org-mode).
7436 M-up Move entry/item up
7437 M-down Move entry/item down
7438 M-left Promote
7439 M-right Demote
7440 M-S-up Move entry/item up
7441 M-S-down Move entry/item down
7442 M-S-left Promote subtree
7443 M-S-right Demote subtree
7444 M-q Fill paragraph and items like in Org-mode
7445 C-c ^ Sort entries
7446 C-c - Cycle list bullet
7447 TAB Cycle item visibility
7448 M-RET Insert new heading/item
7449 S-M-RET Insert new TODO heading / Chekbox item
7450 C-c C-c Set tags / toggle checkbox"
7451 nil " OrgStruct" nil
7452 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7454 ;;;###autoload
7455 (defun turn-on-orgstruct ()
7456 "Unconditionally turn on `orgstruct-mode'."
7457 (orgstruct-mode 1))
7459 ;;;###autoload
7460 (defun turn-on-orgstruct++ ()
7461 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7462 In addition to setting orgstruct-mode, this also exports all indentation and
7463 autofilling variables from org-mode into the buffer. Note that turning
7464 off orgstruct-mode will *not* remove these additonal settings."
7465 (orgstruct-mode 1)
7466 (let (var val)
7467 (mapc
7468 (lambda (x)
7469 (when (string-match
7470 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7471 (symbol-name (car x)))
7472 (setq var (car x) val (nth 1 x))
7473 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7474 org-local-vars)))
7476 (defun orgstruct-error ()
7477 "Error when there is no default binding for a structure key."
7478 (interactive)
7479 (error "This key is has no function outside structure elements"))
7481 (defun orgstruct-setup ()
7482 "Setup orgstruct keymaps."
7483 (let ((nfunc 0)
7484 (bindings
7485 (list
7486 '([(meta up)] org-metaup)
7487 '([(meta down)] org-metadown)
7488 '([(meta left)] org-metaleft)
7489 '([(meta right)] org-metaright)
7490 '([(meta shift up)] org-shiftmetaup)
7491 '([(meta shift down)] org-shiftmetadown)
7492 '([(meta shift left)] org-shiftmetaleft)
7493 '([(meta shift right)] org-shiftmetaright)
7494 '([(shift up)] org-shiftup)
7495 '([(shift down)] org-shiftdown)
7496 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7497 '("\M-q" fill-paragraph)
7498 '("\C-c^" org-sort)
7499 '("\C-c-" org-cycle-list-bullet)))
7500 elt key fun cmd)
7501 (while (setq elt (pop bindings))
7502 (setq nfunc (1+ nfunc))
7503 (setq key (org-key (car elt))
7504 fun (nth 1 elt)
7505 cmd (orgstruct-make-binding fun nfunc key))
7506 (org-defkey orgstruct-mode-map key cmd))
7508 ;; Special treatment needed for TAB and RET
7509 (org-defkey orgstruct-mode-map [(tab)]
7510 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7511 (org-defkey orgstruct-mode-map "\C-i"
7512 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7514 (org-defkey orgstruct-mode-map "\M-\C-m"
7515 (orgstruct-make-binding 'org-insert-heading 105
7516 "\M-\C-m" [(meta return)]))
7517 (org-defkey orgstruct-mode-map [(meta return)]
7518 (orgstruct-make-binding 'org-insert-heading 106
7519 [(meta return)] "\M-\C-m"))
7521 (org-defkey orgstruct-mode-map [(shift meta return)]
7522 (orgstruct-make-binding 'org-insert-todo-heading 107
7523 [(meta return)] "\M-\C-m"))
7525 (unless org-local-vars
7526 (setq org-local-vars (org-get-local-variables)))
7530 (defun orgstruct-make-binding (fun n &rest keys)
7531 "Create a function for binding in the structure minor mode.
7532 FUN is the command to call inside a table. N is used to create a unique
7533 command name. KEYS are keys that should be checked in for a command
7534 to execute outside of tables."
7535 (eval
7536 (list 'defun
7537 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7538 '(arg)
7539 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7540 "Outside of structure, run the binding of `"
7541 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7542 "'.")
7543 '(interactive "p")
7544 (list 'if
7545 '(org-context-p 'headline 'item)
7546 (list 'org-run-like-in-org-mode (list 'quote fun))
7547 (list 'let '(orgstruct-mode)
7548 (list 'call-interactively
7549 (append '(or)
7550 (mapcar (lambda (k)
7551 (list 'key-binding k))
7552 keys)
7553 '('orgstruct-error))))))))
7555 (defun org-context-p (&rest contexts)
7556 "Check if local context is and of CONTEXTS.
7557 Possible values in the list of contexts are `table', `headline', and `item'."
7558 (let ((pos (point)))
7559 (goto-char (point-at-bol))
7560 (prog1 (or (and (memq 'table contexts)
7561 (looking-at "[ \t]*|"))
7562 (and (memq 'headline contexts)
7563 (looking-at "\\*+"))
7564 (and (memq 'item contexts)
7565 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
7566 (goto-char pos))))
7568 (defun org-get-local-variables ()
7569 "Return a list of all local variables in an org-mode buffer."
7570 (let (varlist)
7571 (with-current-buffer (get-buffer-create "*Org tmp*")
7572 (erase-buffer)
7573 (org-mode)
7574 (setq varlist (buffer-local-variables)))
7575 (kill-buffer "*Org tmp*")
7576 (delq nil
7577 (mapcar
7578 (lambda (x)
7579 (setq x
7580 (if (symbolp x)
7581 (list x)
7582 (list (car x) (list 'quote (cdr x)))))
7583 (if (string-match
7584 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7585 (symbol-name (car x)))
7586 x nil))
7587 varlist))))
7589 ;;;###autoload
7590 (defun org-run-like-in-org-mode (cmd)
7591 (unless org-local-vars
7592 (setq org-local-vars (org-get-local-variables)))
7593 (eval (list 'let org-local-vars
7594 (list 'call-interactively (list 'quote cmd)))))
7596 ;;;; Archiving
7598 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
7600 (defun org-archive-subtree (&optional find-done)
7601 "Move the current subtree to the archive.
7602 The archive can be a certain top-level heading in the current file, or in
7603 a different file. The tree will be moved to that location, the subtree
7604 heading be marked DONE, and the current time will be added.
7606 When called with prefix argument FIND-DONE, find whole trees without any
7607 open TODO items and archive them (after getting confirmation from the user).
7608 If the cursor is not at a headline when this comand is called, try all level
7609 1 trees. If the cursor is on a headline, only try the direct children of
7610 this heading."
7611 (interactive "P")
7612 (if find-done
7613 (org-archive-all-done)
7614 ;; Save all relevant TODO keyword-relatex variables
7616 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
7617 (tr-org-todo-keywords-1 org-todo-keywords-1)
7618 (tr-org-todo-kwd-alist org-todo-kwd-alist)
7619 (tr-org-done-keywords org-done-keywords)
7620 (tr-org-todo-regexp org-todo-regexp)
7621 (tr-org-todo-line-regexp org-todo-line-regexp)
7622 (tr-org-odd-levels-only org-odd-levels-only)
7623 (this-buffer (current-buffer))
7624 (org-archive-location org-archive-location)
7625 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
7626 ;; start of variables that will be used for saving context
7627 ;; The compiler complains about them - keep them anyway!
7628 (file (abbreviate-file-name (buffer-file-name)))
7629 (time (format-time-string
7630 (substring (cdr org-time-stamp-formats) 1 -1)
7631 (current-time)))
7632 afile heading buffer level newfile-p
7633 category todo priority
7634 ;; start of variables that will be used for savind context
7635 ltags itags prop)
7637 ;; Try to find a local archive location
7638 (save-excursion
7639 (save-restriction
7640 (widen)
7641 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
7642 (if (and prop (string-match "\\S-" prop))
7643 (setq org-archive-location prop)
7644 (if (or (re-search-backward re nil t)
7645 (re-search-forward re nil t))
7646 (setq org-archive-location (match-string 1))))))
7648 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
7649 (progn
7650 (setq afile (format (match-string 1 org-archive-location)
7651 (file-name-nondirectory buffer-file-name))
7652 heading (match-string 2 org-archive-location)))
7653 (error "Invalid `org-archive-location'"))
7654 (if (> (length afile) 0)
7655 (setq newfile-p (not (file-exists-p afile))
7656 buffer (find-file-noselect afile))
7657 (setq buffer (current-buffer)))
7658 (unless buffer
7659 (error "Cannot access file \"%s\"" afile))
7660 (if (and (> (length heading) 0)
7661 (string-match "^\\*+" heading))
7662 (setq level (match-end 0))
7663 (setq heading nil level 0))
7664 (save-excursion
7665 (org-back-to-heading t)
7666 ;; Get context information that will be lost by moving the tree
7667 (org-refresh-category-properties)
7668 (setq category (org-get-category)
7669 todo (and (looking-at org-todo-line-regexp)
7670 (match-string 2))
7671 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
7672 ltags (org-get-tags)
7673 itags (org-delete-all ltags (org-get-tags-at)))
7674 (setq ltags (mapconcat 'identity ltags " ")
7675 itags (mapconcat 'identity itags " "))
7676 ;; We first only copy, in case something goes wrong
7677 ;; we need to protect this-command, to avoid kill-region sets it,
7678 ;; which would lead to duplication of subtrees
7679 (let (this-command) (org-copy-subtree))
7680 (set-buffer buffer)
7681 ;; Enforce org-mode for the archive buffer
7682 (if (not (org-mode-p))
7683 ;; Force the mode for future visits.
7684 (let ((org-insert-mode-line-in-empty-file t)
7685 (org-inhibit-startup t))
7686 (call-interactively 'org-mode)))
7687 (when newfile-p
7688 (goto-char (point-max))
7689 (insert (format "\nArchived entries from file %s\n\n"
7690 (buffer-file-name this-buffer))))
7691 ;; Force the TODO keywords of the original buffer
7692 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
7693 (org-todo-keywords-1 tr-org-todo-keywords-1)
7694 (org-todo-kwd-alist tr-org-todo-kwd-alist)
7695 (org-done-keywords tr-org-done-keywords)
7696 (org-todo-regexp tr-org-todo-regexp)
7697 (org-todo-line-regexp tr-org-todo-line-regexp)
7698 (org-odd-levels-only
7699 (if (local-variable-p 'org-odd-levels-only (current-buffer))
7700 org-odd-levels-only
7701 tr-org-odd-levels-only)))
7702 (goto-char (point-min))
7703 (if heading
7704 (progn
7705 (if (re-search-forward
7706 (concat "^" (regexp-quote heading)
7707 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
7708 nil t)
7709 (goto-char (match-end 0))
7710 ;; Heading not found, just insert it at the end
7711 (goto-char (point-max))
7712 (or (bolp) (insert "\n"))
7713 (insert "\n" heading "\n")
7714 (end-of-line 0))
7715 ;; Make the subtree visible
7716 (show-subtree)
7717 (org-end-of-subtree t)
7718 (skip-chars-backward " \t\r\n")
7719 (and (looking-at "[ \t\r\n]*")
7720 (replace-match "\n\n")))
7721 ;; No specific heading, just go to end of file.
7722 (goto-char (point-max)) (insert "\n"))
7723 ;; Paste
7724 (org-paste-subtree (org-get-legal-level level 1))
7726 ;; Mark the entry as done
7727 (when (and org-archive-mark-done
7728 (looking-at org-todo-line-regexp)
7729 (or (not (match-end 2))
7730 (not (member (match-string 2) org-done-keywords))))
7731 (let (org-log-done)
7732 (org-todo
7733 (car (or (member org-archive-mark-done org-done-keywords)
7734 org-done-keywords)))))
7736 ;; Add the context info
7737 (when org-archive-save-context-info
7738 (let ((l org-archive-save-context-info) e n v)
7739 (while (setq e (pop l))
7740 (when (and (setq v (symbol-value e))
7741 (stringp v) (string-match "\\S-" v))
7742 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
7743 (org-entry-put (point) n v)))))
7745 ;; Save the buffer, if it is not the same buffer.
7746 (if (not (eq this-buffer buffer)) (save-buffer))))
7747 ;; Here we are back in the original buffer. Everything seems to have
7748 ;; worked. So now cut the tree and finish up.
7749 (let (this-command) (org-cut-subtree))
7750 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
7751 (message "Subtree archived %s"
7752 (if (eq this-buffer buffer)
7753 (concat "under heading: " heading)
7754 (concat "in file: " (abbreviate-file-name afile)))))))
7756 (defun org-refresh-category-properties ()
7757 "Refresh category text properties in teh buffer."
7758 (let ((def-cat (cond
7759 ((null org-category)
7760 (if buffer-file-name
7761 (file-name-sans-extension
7762 (file-name-nondirectory buffer-file-name))
7763 "???"))
7764 ((symbolp org-category) (symbol-name org-category))
7765 (t org-category)))
7766 beg end cat pos optionp)
7767 (org-unmodified
7768 (save-excursion
7769 (save-restriction
7770 (widen)
7771 (goto-char (point-min))
7772 (put-text-property (point) (point-max) 'org-category def-cat)
7773 (while (re-search-forward
7774 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7775 (setq pos (match-end 0)
7776 optionp (equal (char-after (match-beginning 0)) ?#)
7777 cat (org-trim (match-string 2)))
7778 (if optionp
7779 (setq beg (point-at-bol) end (point-max))
7780 (org-back-to-heading t)
7781 (setq beg (point) end (org-end-of-subtree t t)))
7782 (put-text-property beg end 'org-category cat)
7783 (goto-char pos)))))))
7785 (defun org-archive-all-done (&optional tag)
7786 "Archive sublevels of the current tree without open TODO items.
7787 If the cursor is not on a headline, try all level 1 trees. If
7788 it is on a headline, try all direct children.
7789 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
7790 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
7791 (rea (concat ".*:" org-archive-tag ":"))
7792 (begm (make-marker))
7793 (endm (make-marker))
7794 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
7795 "Move subtree to archive (no open TODO items)? "))
7796 beg end (cntarch 0))
7797 (if (org-on-heading-p)
7798 (progn
7799 (setq re1 (concat "^" (regexp-quote
7800 (make-string
7801 (1+ (- (match-end 0) (match-beginning 0)))
7802 ?*))
7803 " "))
7804 (move-marker begm (point))
7805 (move-marker endm (org-end-of-subtree t)))
7806 (setq re1 "^* ")
7807 (move-marker begm (point-min))
7808 (move-marker endm (point-max)))
7809 (save-excursion
7810 (goto-char begm)
7811 (while (re-search-forward re1 endm t)
7812 (setq beg (match-beginning 0)
7813 end (save-excursion (org-end-of-subtree t) (point)))
7814 (goto-char beg)
7815 (if (re-search-forward re end t)
7816 (goto-char end)
7817 (goto-char beg)
7818 (if (and (or (not tag) (not (looking-at rea)))
7819 (y-or-n-p question))
7820 (progn
7821 (if tag
7822 (org-toggle-tag org-archive-tag 'on)
7823 (org-archive-subtree))
7824 (setq cntarch (1+ cntarch)))
7825 (goto-char end)))))
7826 (message "%d trees archived" cntarch)))
7828 (defun org-cycle-hide-drawers (state)
7829 "Re-hide all drawers after a visibility state change."
7830 (when (and (org-mode-p)
7831 (not (memq state '(overview folded))))
7832 (save-excursion
7833 (let* ((globalp (memq state '(contents all)))
7834 (beg (if globalp (point-min) (point)))
7835 (end (if globalp (point-max) (org-end-of-subtree t))))
7836 (goto-char beg)
7837 (while (re-search-forward org-drawer-regexp end t)
7838 (org-flag-drawer t))))))
7840 (defun org-flag-drawer (flag)
7841 (save-excursion
7842 (beginning-of-line 1)
7843 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7844 (let ((b (match-end 0)))
7845 (if (re-search-forward
7846 "^[ \t]*:END:"
7847 (save-excursion (outline-next-heading) (point)) t)
7848 (outline-flag-region b (point-at-eol) flag)
7849 (error ":END: line missing"))))))
7851 (defun org-cycle-hide-archived-subtrees (state)
7852 "Re-hide all archived subtrees after a visibility state change."
7853 (when (and (not org-cycle-open-archived-trees)
7854 (not (memq state '(overview folded))))
7855 (save-excursion
7856 (let* ((globalp (memq state '(contents all)))
7857 (beg (if globalp (point-min) (point)))
7858 (end (if globalp (point-max) (org-end-of-subtree t))))
7859 (org-hide-archived-subtrees beg end)
7860 (goto-char beg)
7861 (if (looking-at (concat ".*:" org-archive-tag ":"))
7862 (message "%s" (substitute-command-keys
7863 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
7865 (defun org-force-cycle-archived ()
7866 "Cycle subtree even if it is archived."
7867 (interactive)
7868 (setq this-command 'org-cycle)
7869 (let ((org-cycle-open-archived-trees t))
7870 (call-interactively 'org-cycle)))
7872 (defun org-hide-archived-subtrees (beg end)
7873 "Re-hide all archived subtrees after a visibility state change."
7874 (save-excursion
7875 (let* ((re (concat ":" org-archive-tag ":")))
7876 (goto-char beg)
7877 (while (re-search-forward re end t)
7878 (and (org-on-heading-p) (hide-subtree))
7879 (org-end-of-subtree t)))))
7881 (defun org-toggle-tag (tag &optional onoff)
7882 "Toggle the tag TAG for the current line.
7883 If ONOFF is `on' or `off', don't toggle but set to this state."
7884 (unless (org-on-heading-p t) (error "Not on headling"))
7885 (let (res current)
7886 (save-excursion
7887 (beginning-of-line)
7888 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
7889 (point-at-eol) t)
7890 (progn
7891 (setq current (match-string 1))
7892 (replace-match ""))
7893 (setq current ""))
7894 (setq current (nreverse (org-split-string current ":")))
7895 (cond
7896 ((eq onoff 'on)
7897 (setq res t)
7898 (or (member tag current) (push tag current)))
7899 ((eq onoff 'off)
7900 (or (not (member tag current)) (setq current (delete tag current))))
7901 (t (if (member tag current)
7902 (setq current (delete tag current))
7903 (setq res t)
7904 (push tag current))))
7905 (end-of-line 1)
7906 (if current
7907 (progn
7908 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
7909 (org-set-tags nil t))
7910 (delete-horizontal-space))
7911 (run-hooks 'org-after-tags-change-hook))
7912 res))
7914 (defun org-toggle-archive-tag (&optional arg)
7915 "Toggle the archive tag for the current headline.
7916 With prefix ARG, check all children of current headline and offer tagging
7917 the children that do not contain any open TODO items."
7918 (interactive "P")
7919 (if arg
7920 (org-archive-all-done 'tag)
7921 (let (set)
7922 (save-excursion
7923 (org-back-to-heading t)
7924 (setq set (org-toggle-tag org-archive-tag))
7925 (when set (hide-subtree)))
7926 (and set (beginning-of-line 1))
7927 (message "Subtree %s" (if set "archived" "unarchived")))))
7930 ;;;; Tables
7932 ;;; The table editor
7934 ;; Watch out: Here we are talking about two different kind of tables.
7935 ;; Most of the code is for the tables created with the Org-mode table editor.
7936 ;; Sometimes, we talk about tables created and edited with the table.el
7937 ;; Emacs package. We call the former org-type tables, and the latter
7938 ;; table.el-type tables.
7940 (defun org-before-change-function (beg end)
7941 "Every change indicates that a table might need an update."
7942 (setq org-table-may-need-update t))
7944 (defconst org-table-line-regexp "^[ \t]*|"
7945 "Detects an org-type table line.")
7946 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
7947 "Detects an org-type table line.")
7948 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
7949 "Detects a table line marked for automatic recalculation.")
7950 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
7951 "Detects a table line marked for automatic recalculation.")
7952 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
7953 "Detects a table line marked for automatic recalculation.")
7954 (defconst org-table-hline-regexp "^[ \t]*|-"
7955 "Detects an org-type table hline.")
7956 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
7957 "Detects a table-type table hline.")
7958 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
7959 "Detects an org-type or table-type table.")
7960 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
7961 "Searching from within a table (any type) this finds the first line
7962 outside the table.")
7963 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
7964 "Searching from within a table (any type) this finds the first line
7965 outside the table.")
7967 (defvar org-table-last-highlighted-reference nil)
7968 (defvar org-table-formula-history nil)
7970 (defvar org-table-column-names nil
7971 "Alist with column names, derived from the `!' line.")
7972 (defvar org-table-column-name-regexp nil
7973 "Regular expression matching the current column names.")
7974 (defvar org-table-local-parameters nil
7975 "Alist with parameter names, derived from the `$' line.")
7976 (defvar org-table-named-field-locations nil
7977 "Alist with locations of named fields.")
7979 (defvar org-table-current-line-types nil
7980 "Table row types, non-nil only for the duration of a comand.")
7981 (defvar org-table-current-begin-line nil
7982 "Table begin line, non-nil only for the duration of a comand.")
7983 (defvar org-table-current-begin-pos nil
7984 "Table begin position, non-nil only for the duration of a comand.")
7985 (defvar org-table-dlines nil
7986 "Vector of data line line numbers in the current table.")
7987 (defvar org-table-hlines nil
7988 "Vector of hline line numbers in the current table.")
7990 (defconst org-table-range-regexp
7991 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
7992 ;; 1 2 3 4 5
7993 "Regular expression for matching ranges in formulas.")
7995 (defconst org-table-range-regexp2
7996 (concat
7997 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
7998 "\\.\\."
7999 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8000 "Match a range for reference display.")
8002 (defconst org-table-translate-regexp
8003 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8004 "Match a reference that needs translation, for reference display.")
8006 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8008 (defun org-table-create-with-table.el ()
8009 "Use the table.el package to insert a new table.
8010 If there is already a table at point, convert between Org-mode tables
8011 and table.el tables."
8012 (interactive)
8013 (require 'table)
8014 (cond
8015 ((org-at-table.el-p)
8016 (if (y-or-n-p "Convert table to Org-mode table? ")
8017 (org-table-convert)))
8018 ((org-at-table-p)
8019 (if (y-or-n-p "Convert table to table.el table? ")
8020 (org-table-convert)))
8021 (t (call-interactively 'table-insert))))
8023 (defun org-table-create-or-convert-from-region (arg)
8024 "Convert region to table, or create an empty table.
8025 If there is an active region, convert it to a table, using the function
8026 `org-table-convert-region'. See the documentation of that function
8027 to learn how the prefix argument is interpreted to determine the field
8028 separator.
8029 If there is no such region, create an empty table with `org-table-create'."
8030 (interactive "P")
8031 (if (org-region-active-p)
8032 (org-table-convert-region (region-beginning) (region-end) arg)
8033 (org-table-create arg)))
8035 (defun org-table-create (&optional size)
8036 "Query for a size and insert a table skeleton.
8037 SIZE is a string Columns x Rows like for example \"3x2\"."
8038 (interactive "P")
8039 (unless size
8040 (setq size (read-string
8041 (concat "Table size Columns x Rows [e.g. "
8042 org-table-default-size "]: ")
8043 "" nil org-table-default-size)))
8045 (let* ((pos (point))
8046 (indent (make-string (current-column) ?\ ))
8047 (split (org-split-string size " *x *"))
8048 (rows (string-to-number (nth 1 split)))
8049 (columns (string-to-number (car split)))
8050 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8051 "\n")))
8052 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8053 (point-at-bol) (point)))
8054 (beginning-of-line 1)
8055 (newline))
8056 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8057 (dotimes (i rows) (insert line))
8058 (goto-char pos)
8059 (if (> rows 1)
8060 ;; Insert a hline after the first row.
8061 (progn
8062 (end-of-line 1)
8063 (insert "\n|-")
8064 (goto-char pos)))
8065 (org-table-align)))
8067 (defun org-table-convert-region (beg0 end0 &optional separator)
8068 "Convert region to a table.
8069 The region goes from BEG0 to END0, but these borders will be moved
8070 slightly, to make sure a beginning of line in the first line is included.
8072 SEPARATOR specifies the field separator in the lines. It can have the
8073 following values:
8075 '(4) Use the comma as a field separator
8076 '(16) Use a TAB as field separator
8077 integer When a number, use that many spaces as field separator
8078 nil When nil, the command tries to be smart and figure out the
8079 separator in the following way:
8080 - when each line contains a TAB, assume TAB-separated material
8081 - when each line contains a comme, assume CSV material
8082 - else, assume one or more SPACE charcters as separator."
8083 (interactive "rP")
8084 (let* ((beg (min beg0 end0))
8085 (end (max beg0 end0))
8087 (goto-char beg)
8088 (beginning-of-line 1)
8089 (setq beg (move-marker (make-marker) (point)))
8090 (goto-char end)
8091 (if (bolp) (backward-char 1) (end-of-line 1))
8092 (setq end (move-marker (make-marker) (point)))
8093 ;; Get the right field separator
8094 (unless separator
8095 (goto-char beg)
8096 (setq separator
8097 (cond
8098 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8099 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8100 (t 1))))
8101 (setq re (cond
8102 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8103 ((equal separator '(16)) "^\\|\t")
8104 ((integerp separator)
8105 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8106 (t (error "This should not happen"))))
8107 (goto-char beg)
8108 (while (re-search-forward re end t)
8109 (replace-match "| " t t))
8110 (goto-char beg)
8111 (insert " ")
8112 (org-table-align)))
8114 (defun org-table-import (file arg)
8115 "Import FILE as a table.
8116 The file is assumed to be tab-separated. Such files can be produced by most
8117 spreadsheet and database applications. If no tabs (at least one per line)
8118 are found, lines will be split on whitespace into fields."
8119 (interactive "f\nP")
8120 (or (bolp) (newline))
8121 (let ((beg (point))
8122 (pm (point-max)))
8123 (insert-file-contents file)
8124 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8126 (defun org-table-export ()
8127 "Export table as a tab-separated file.
8128 Such a file can be imported into a spreadsheet program like Excel."
8129 (interactive)
8130 (let* ((beg (org-table-begin))
8131 (end (org-table-end))
8132 (table (buffer-substring beg end))
8133 (file (read-file-name "Export table to: "))
8134 buf)
8135 (unless (or (not (file-exists-p file))
8136 (y-or-n-p (format "Overwrite file %s? " file)))
8137 (error "Abort"))
8138 (with-current-buffer (find-file-noselect file)
8139 (setq buf (current-buffer))
8140 (erase-buffer)
8141 (fundamental-mode)
8142 (insert table)
8143 (goto-char (point-min))
8144 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8145 (replace-match "" t t)
8146 (end-of-line 1))
8147 (goto-char (point-min))
8148 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8149 (replace-match "" t t)
8150 (goto-char (min (1+ (point)) (point-max))))
8151 (goto-char (point-min))
8152 (while (re-search-forward "^-[-+]*$" nil t)
8153 (replace-match "")
8154 (if (looking-at "\n")
8155 (delete-char 1)))
8156 (goto-char (point-min))
8157 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8158 (replace-match "\t" t t))
8159 (save-buffer))
8160 (kill-buffer buf)))
8162 (defvar org-table-aligned-begin-marker (make-marker)
8163 "Marker at the beginning of the table last aligned.
8164 Used to check if cursor still is in that table, to minimize realignment.")
8165 (defvar org-table-aligned-end-marker (make-marker)
8166 "Marker at the end of the table last aligned.
8167 Used to check if cursor still is in that table, to minimize realignment.")
8168 (defvar org-table-last-alignment nil
8169 "List of flags for flushright alignment, from the last re-alignment.
8170 This is being used to correctly align a single field after TAB or RET.")
8171 (defvar org-table-last-column-widths nil
8172 "List of max width of fields in each column.
8173 This is being used to correctly align a single field after TAB or RET.")
8174 (defvar org-table-overlay-coordinates nil
8175 "Overlay coordinates after each align of a table.")
8176 (make-variable-buffer-local 'org-table-overlay-coordinates)
8178 (defvar org-last-recalc-line nil)
8179 (defconst org-narrow-column-arrow "=>"
8180 "Used as display property in narrowed table columns.")
8182 (defun org-table-align ()
8183 "Align the table at point by aligning all vertical bars."
8184 (interactive)
8185 (let* (
8186 ;; Limits of table
8187 (beg (org-table-begin))
8188 (end (org-table-end))
8189 ;; Current cursor position
8190 (linepos (org-current-line))
8191 (colpos (org-table-current-column))
8192 (winstart (window-start))
8193 (winstartline (org-current-line (min winstart (1- (point-max)))))
8194 lines (new "") lengths l typenums ty fields maxfields i
8195 column
8196 (indent "") cnt frac
8197 rfmt hfmt
8198 (spaces '(1 . 1))
8199 (sp1 (car spaces))
8200 (sp2 (cdr spaces))
8201 (rfmt1 (concat
8202 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8203 (hfmt1 (concat
8204 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8205 emptystrings links dates emph narrow fmax f1 len c e)
8206 (untabify beg end)
8207 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8208 ;; Check if we have links or dates
8209 (goto-char beg)
8210 (setq links (re-search-forward org-bracket-link-regexp end t))
8211 (goto-char beg)
8212 (setq emph (and org-hide-emphasis-markers
8213 (re-search-forward org-emph-re end t)))
8214 (goto-char beg)
8215 (setq dates (and org-display-custom-times
8216 (re-search-forward org-ts-regexp-both end t)))
8217 ;; Make sure the link properties are right
8218 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8219 ;; Make sure the date properties are right
8220 (when dates (goto-char beg) (while (org-activate-dates end)))
8221 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8223 ;; Check if we are narrowing any columns
8224 (goto-char beg)
8225 (setq narrow (and org-format-transports-properties-p
8226 (re-search-forward "<[0-9]+>" end t)))
8227 ;; Get the rows
8228 (setq lines (org-split-string
8229 (buffer-substring beg end) "\n"))
8230 ;; Store the indentation of the first line
8231 (if (string-match "^ *" (car lines))
8232 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8233 ;; Mark the hlines by setting the corresponding element to nil
8234 ;; At the same time, we remove trailing space.
8235 (setq lines (mapcar (lambda (l)
8236 (if (string-match "^ *|-" l)
8238 (if (string-match "[ \t]+$" l)
8239 (substring l 0 (match-beginning 0))
8240 l)))
8241 lines))
8242 ;; Get the data fields by splitting the lines.
8243 (setq fields (mapcar
8244 (lambda (l)
8245 (org-split-string l " *| *"))
8246 (delq nil (copy-sequence lines))))
8247 ;; How many fields in the longest line?
8248 (condition-case nil
8249 (setq maxfields (apply 'max (mapcar 'length fields)))
8250 (error
8251 (kill-region beg end)
8252 (org-table-create org-table-default-size)
8253 (error "Empty table - created default table")))
8254 ;; A list of empty strings to fill any short rows on output
8255 (setq emptystrings (make-list maxfields ""))
8256 ;; Check for special formatting.
8257 (setq i -1)
8258 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8259 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8260 ;; Check if there is an explicit width specified
8261 (when narrow
8262 (setq c column fmax nil)
8263 (while c
8264 (setq e (pop c))
8265 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8266 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8267 ;; Find fields that are wider than fmax, and shorten them
8268 (when fmax
8269 (loop for xx in column do
8270 (when (and (stringp xx)
8271 (> (org-string-width xx) fmax))
8272 (org-add-props xx nil
8273 'help-echo
8274 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8275 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8276 (unless (> f1 1)
8277 (error "Cannot narrow field starting with wide link \"%s\""
8278 (match-string 0 xx)))
8279 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8280 (add-text-properties (- f1 2) f1
8281 (list 'display org-narrow-column-arrow)
8282 xx)))))
8283 ;; Get the maximum width for each column
8284 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8285 ;; Get the fraction of numbers, to decide about alignment of the column
8286 (setq cnt 0 frac 0.0)
8287 (loop for x in column do
8288 (if (equal x "")
8290 (setq frac ( / (+ (* frac cnt)
8291 (if (string-match org-table-number-regexp x) 1 0))
8292 (setq cnt (1+ cnt))))))
8293 (push (>= frac org-table-number-fraction) typenums))
8294 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8296 ;; Store the alignment of this table, for later editing of single fields
8297 (setq org-table-last-alignment typenums
8298 org-table-last-column-widths lengths)
8300 ;; With invisible characters, `format' does not get the field width right
8301 ;; So we need to make these fields wide by hand.
8302 (when (or links emph)
8303 (loop for i from 0 upto (1- maxfields) do
8304 (setq len (nth i lengths))
8305 (loop for j from 0 upto (1- (length fields)) do
8306 (setq c (nthcdr i (car (nthcdr j fields))))
8307 (if (and (stringp (car c))
8308 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8309 ; (string-match org-bracket-link-regexp (car c))
8310 (< (org-string-width (car c)) len))
8311 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8313 ;; Compute the formats needed for output of the table
8314 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8315 (while (setq l (pop lengths))
8316 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8317 (setq rfmt (concat rfmt (format rfmt1 ty l))
8318 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8319 (setq rfmt (concat rfmt "\n")
8320 hfmt (concat (substring hfmt 0 -1) "|\n"))
8322 (setq new (mapconcat
8323 (lambda (l)
8324 (if l (apply 'format rfmt
8325 (append (pop fields) emptystrings))
8326 hfmt))
8327 lines ""))
8328 ;; Replace the old one
8329 (delete-region beg end)
8330 (move-marker end nil)
8331 (move-marker org-table-aligned-begin-marker (point))
8332 (insert new)
8333 (move-marker org-table-aligned-end-marker (point))
8334 (when (and orgtbl-mode (not (org-mode-p)))
8335 (goto-char org-table-aligned-begin-marker)
8336 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8337 ;; Try to move to the old location
8338 (goto-line winstartline)
8339 (setq winstart (point-at-bol))
8340 (goto-line linepos)
8341 (set-window-start (selected-window) winstart 'noforce)
8342 (org-table-goto-column colpos)
8343 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8344 (setq org-table-may-need-update nil)
8347 (defun org-string-width (s)
8348 "Compute width of string, ignoring invisible characters.
8349 This ignores character with invisibility property `org-link', and also
8350 characters with property `org-cwidth', because these will become invisible
8351 upon the next fontification round."
8352 (let (b l)
8353 (when (or (eq t buffer-invisibility-spec)
8354 (assq 'org-link buffer-invisibility-spec))
8355 (while (setq b (text-property-any 0 (length s)
8356 'invisible 'org-link s))
8357 (setq s (concat (substring s 0 b)
8358 (substring s (or (next-single-property-change
8359 b 'invisible s) (length s)))))))
8360 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8361 (setq s (concat (substring s 0 b)
8362 (substring s (or (next-single-property-change
8363 b 'org-cwidth s) (length s))))))
8364 (setq l (string-width s) b -1)
8365 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8366 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8369 (defun org-table-begin (&optional table-type)
8370 "Find the beginning of the table and return its position.
8371 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8372 (save-excursion
8373 (if (not (re-search-backward
8374 (if table-type org-table-any-border-regexp
8375 org-table-border-regexp)
8376 nil t))
8377 (progn (goto-char (point-min)) (point))
8378 (goto-char (match-beginning 0))
8379 (beginning-of-line 2)
8380 (point))))
8382 (defun org-table-end (&optional table-type)
8383 "Find the end of the table and return its position.
8384 With argument TABLE-TYPE, go to the end of a table.el-type table."
8385 (save-excursion
8386 (if (not (re-search-forward
8387 (if table-type org-table-any-border-regexp
8388 org-table-border-regexp)
8389 nil t))
8390 (goto-char (point-max))
8391 (goto-char (match-beginning 0)))
8392 (point-marker)))
8394 (defun org-table-justify-field-maybe (&optional new)
8395 "Justify the current field, text to left, number to right.
8396 Optional argument NEW may specify text to replace the current field content."
8397 (cond
8398 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8399 ((org-at-table-hline-p))
8400 ((and (not new)
8401 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8402 (current-buffer)))
8403 (< (point) org-table-aligned-begin-marker)
8404 (>= (point) org-table-aligned-end-marker)))
8405 ;; This is not the same table, force a full re-align
8406 (setq org-table-may-need-update t))
8407 (t ;; realign the current field, based on previous full realign
8408 (let* ((pos (point)) s
8409 (col (org-table-current-column))
8410 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8411 l f n o e)
8412 (when (> col 0)
8413 (skip-chars-backward "^|\n")
8414 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8415 (progn
8416 (setq s (match-string 1)
8417 o (match-string 0)
8418 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8419 e (not (= (match-beginning 2) (match-end 2))))
8420 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8421 l (if e "|" (setq org-table-may-need-update t) ""))
8422 n (format f s))
8423 (if new
8424 (if (<= (length new) l) ;; FIXME: length -> str-width?
8425 (setq n (format f new))
8426 (setq n (concat new "|") org-table-may-need-update t)))
8427 (or (equal n o)
8428 (let (org-table-may-need-update)
8429 (replace-match n t t))))
8430 (setq org-table-may-need-update t))
8431 (goto-char pos))))))
8433 (defun org-table-next-field ()
8434 "Go to the next field in the current table, creating new lines as needed.
8435 Before doing so, re-align the table if necessary."
8436 (interactive)
8437 (org-table-maybe-eval-formula)
8438 (org-table-maybe-recalculate-line)
8439 (if (and org-table-automatic-realign
8440 org-table-may-need-update)
8441 (org-table-align))
8442 (let ((end (org-table-end)))
8443 (if (org-at-table-hline-p)
8444 (end-of-line 1))
8445 (condition-case nil
8446 (progn
8447 (re-search-forward "|" end)
8448 (if (looking-at "[ \t]*$")
8449 (re-search-forward "|" end))
8450 (if (and (looking-at "-")
8451 org-table-tab-jumps-over-hlines
8452 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8453 (goto-char (match-beginning 1)))
8454 (if (looking-at "-")
8455 (progn
8456 (beginning-of-line 0)
8457 (org-table-insert-row 'below))
8458 (if (looking-at " ") (forward-char 1))))
8459 (error
8460 (org-table-insert-row 'below)))))
8462 (defun org-table-previous-field ()
8463 "Go to the previous field in the table.
8464 Before doing so, re-align the table if necessary."
8465 (interactive)
8466 (org-table-justify-field-maybe)
8467 (org-table-maybe-recalculate-line)
8468 (if (and org-table-automatic-realign
8469 org-table-may-need-update)
8470 (org-table-align))
8471 (if (org-at-table-hline-p)
8472 (end-of-line 1))
8473 (re-search-backward "|" (org-table-begin))
8474 (re-search-backward "|" (org-table-begin))
8475 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8476 (re-search-backward "|" (org-table-begin)))
8477 (if (looking-at "| ?")
8478 (goto-char (match-end 0))))
8480 (defun org-table-next-row ()
8481 "Go to the next row (same column) in the current table.
8482 Before doing so, re-align the table if necessary."
8483 (interactive)
8484 (org-table-maybe-eval-formula)
8485 (org-table-maybe-recalculate-line)
8486 (if (or (looking-at "[ \t]*$")
8487 (save-excursion (skip-chars-backward " \t") (bolp)))
8488 (newline)
8489 (if (and org-table-automatic-realign
8490 org-table-may-need-update)
8491 (org-table-align))
8492 (let ((col (org-table-current-column)))
8493 (beginning-of-line 2)
8494 (if (or (not (org-at-table-p))
8495 (org-at-table-hline-p))
8496 (progn
8497 (beginning-of-line 0)
8498 (org-table-insert-row 'below)))
8499 (org-table-goto-column col)
8500 (skip-chars-backward "^|\n\r")
8501 (if (looking-at " ") (forward-char 1)))))
8503 (defun org-table-copy-down (n)
8504 "Copy a field down in the current column.
8505 If the field at the cursor is empty, copy into it the content of the nearest
8506 non-empty field above. With argument N, use the Nth non-empty field.
8507 If the current field is not empty, it is copied down to the next row, and
8508 the cursor is moved with it. Therefore, repeating this command causes the
8509 column to be filled row-by-row.
8510 If the variable `org-table-copy-increment' is non-nil and the field is an
8511 integer or a timestamp, it will be incremented while copying. In the case of
8512 a timestamp, if the cursor is on the year, change the year. If it is on the
8513 month or the day, change that. Point will stay on the current date field
8514 in order to easily repeat the interval."
8515 (interactive "p")
8516 (let* ((colpos (org-table-current-column))
8517 (col (current-column))
8518 (field (org-table-get-field))
8519 (non-empty (string-match "[^ \t]" field))
8520 (beg (org-table-begin))
8521 txt)
8522 (org-table-check-inside-data-field)
8523 (if non-empty
8524 (progn
8525 (setq txt (org-trim field))
8526 (org-table-next-row)
8527 (org-table-blank-field))
8528 (save-excursion
8529 (setq txt
8530 (catch 'exit
8531 (while (progn (beginning-of-line 1)
8532 (re-search-backward org-table-dataline-regexp
8533 beg t))
8534 (org-table-goto-column colpos t)
8535 (if (and (looking-at
8536 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8537 (= (setq n (1- n)) 0))
8538 (throw 'exit (match-string 1))))))))
8539 (if txt
8540 (progn
8541 (if (and org-table-copy-increment
8542 (string-match "^[0-9]+$" txt))
8543 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8544 (insert txt)
8545 (move-to-column col)
8546 (if (and org-table-copy-increment (org-at-timestamp-p t))
8547 (org-timestamp-up 1)
8548 (org-table-maybe-recalculate-line))
8549 (org-table-align)
8550 (move-to-column col))
8551 (error "No non-empty field found"))))
8553 (defun org-table-check-inside-data-field ()
8554 "Is point inside a table data field?
8555 I.e. not on a hline or before the first or after the last column?
8556 This actually throws an error, so it aborts the current command."
8557 (if (or (not (org-at-table-p))
8558 (= (org-table-current-column) 0)
8559 (org-at-table-hline-p)
8560 (looking-at "[ \t]*$"))
8561 (error "Not in table data field")))
8563 (defvar org-table-clip nil
8564 "Clipboard for table regions.")
8566 (defun org-table-blank-field ()
8567 "Blank the current table field or active region."
8568 (interactive)
8569 (org-table-check-inside-data-field)
8570 (if (and (interactive-p) (org-region-active-p))
8571 (let (org-table-clip)
8572 (org-table-cut-region (region-beginning) (region-end)))
8573 (skip-chars-backward "^|")
8574 (backward-char 1)
8575 (if (looking-at "|[^|\n]+")
8576 (let* ((pos (match-beginning 0))
8577 (match (match-string 0))
8578 (len (org-string-width match)))
8579 (replace-match (concat "|" (make-string (1- len) ?\ )))
8580 (goto-char (+ 2 pos))
8581 (substring match 1)))))
8583 (defun org-table-get-field (&optional n replace)
8584 "Return the value of the field in column N of current row.
8585 N defaults to current field.
8586 If REPLACE is a string, replace field with this value. The return value
8587 is always the old value."
8588 (and n (org-table-goto-column n))
8589 (skip-chars-backward "^|\n")
8590 (backward-char 1)
8591 (if (looking-at "|[^|\r\n]*")
8592 (let* ((pos (match-beginning 0))
8593 (val (buffer-substring (1+ pos) (match-end 0))))
8594 (if replace
8595 (replace-match (concat "|" replace) t t))
8596 (goto-char (min (point-at-eol) (+ 2 pos)))
8597 val)
8598 (forward-char 1) ""))
8600 (defun org-table-field-info (arg)
8601 "Show info about the current field, and highlight any reference at point."
8602 (interactive "P")
8603 (org-table-get-specials)
8604 (save-excursion
8605 (let* ((pos (point))
8606 (col (org-table-current-column))
8607 (cname (car (rassoc (int-to-string col) org-table-column-names)))
8608 (name (car (rassoc (list (org-current-line) col)
8609 org-table-named-field-locations)))
8610 (eql (org-table-get-stored-formulas))
8611 (dline (org-table-current-dline))
8612 (ref (format "@%d$%d" dline col))
8613 (ref1 (org-table-convert-refs-to-an ref))
8614 (fequation (or (assoc name eql) (assoc ref eql)))
8615 (cequation (assoc (int-to-string col) eql))
8616 (eqn (or fequation cequation)))
8617 (goto-char pos)
8618 (condition-case nil
8619 (org-table-show-reference 'local)
8620 (error nil))
8621 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
8622 dline col
8623 (if cname (concat " or $" cname) "")
8624 dline col ref1
8625 (if name (concat " or $" name) "")
8626 ;; FIXME: formula info not correct if special table line
8627 (if eqn
8628 (concat ", formula: "
8629 (org-table-formula-to-user
8630 (concat
8631 (if (string-match "^[$@]"(car eqn)) "" "$")
8632 (car eqn) "=" (cdr eqn))))
8633 "")))))
8635 (defun org-table-current-column ()
8636 "Find out which column we are in.
8637 When called interactively, column is also displayed in echo area."
8638 (interactive)
8639 (if (interactive-p) (org-table-check-inside-data-field))
8640 (save-excursion
8641 (let ((cnt 0) (pos (point)))
8642 (beginning-of-line 1)
8643 (while (search-forward "|" pos t)
8644 (setq cnt (1+ cnt)))
8645 (if (interactive-p) (message "This is table column %d" cnt))
8646 cnt)))
8648 (defun org-table-current-dline ()
8649 "Find out what table data line we are in.
8650 Only datalins count for this."
8651 (interactive)
8652 (if (interactive-p) (org-table-check-inside-data-field))
8653 (save-excursion
8654 (let ((cnt 0) (pos (point)))
8655 (goto-char (org-table-begin))
8656 (while (<= (point) pos)
8657 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
8658 (beginning-of-line 2))
8659 (if (interactive-p) (message "This is table line %d" cnt))
8660 cnt)))
8662 (defun org-table-goto-column (n &optional on-delim force)
8663 "Move the cursor to the Nth column in the current table line.
8664 With optional argument ON-DELIM, stop with point before the left delimiter
8665 of the field.
8666 If there are less than N fields, just go to after the last delimiter.
8667 However, when FORCE is non-nil, create new columns if necessary."
8668 (interactive "p")
8669 (let ((pos (point-at-eol)))
8670 (beginning-of-line 1)
8671 (when (> n 0)
8672 (while (and (> (setq n (1- n)) -1)
8673 (or (search-forward "|" pos t)
8674 (and force
8675 (progn (end-of-line 1)
8676 (skip-chars-backward "^|")
8677 (insert " | "))))))
8678 ; (backward-char 2) t)))))
8679 (when (and force (not (looking-at ".*|")))
8680 (save-excursion (end-of-line 1) (insert " | ")))
8681 (if on-delim
8682 (backward-char 1)
8683 (if (looking-at " ") (forward-char 1))))))
8685 (defun org-at-table-p (&optional table-type)
8686 "Return t if the cursor is inside an org-type table.
8687 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8688 (if org-enable-table-editor
8689 (save-excursion
8690 (beginning-of-line 1)
8691 (looking-at (if table-type org-table-any-line-regexp
8692 org-table-line-regexp)))
8693 nil))
8695 (defun org-at-table.el-p ()
8696 "Return t if and only if we are at a table.el table."
8697 (and (org-at-table-p 'any)
8698 (save-excursion
8699 (goto-char (org-table-begin 'any))
8700 (looking-at org-table1-hline-regexp))))
8702 (defun org-table-recognize-table.el ()
8703 "If there is a table.el table nearby, recognize it and move into it."
8704 (if org-table-tab-recognizes-table.el
8705 (if (org-at-table.el-p)
8706 (progn
8707 (beginning-of-line 1)
8708 (if (looking-at org-table-dataline-regexp)
8710 (if (looking-at org-table1-hline-regexp)
8711 (progn
8712 (beginning-of-line 2)
8713 (if (looking-at org-table-any-border-regexp)
8714 (beginning-of-line -1)))))
8715 (if (re-search-forward "|" (org-table-end t) t)
8716 (progn
8717 (require 'table)
8718 (if (table--at-cell-p (point))
8720 (message "recognizing table.el table...")
8721 (table-recognize-table)
8722 (message "recognizing table.el table...done")))
8723 (error "This should not happen..."))
8725 nil)
8726 nil))
8728 (defun org-at-table-hline-p ()
8729 "Return t if the cursor is inside a hline in a table."
8730 (if org-enable-table-editor
8731 (save-excursion
8732 (beginning-of-line 1)
8733 (looking-at org-table-hline-regexp))
8734 nil))
8736 (defun org-table-insert-column ()
8737 "Insert a new column into the table."
8738 (interactive)
8739 (if (not (org-at-table-p))
8740 (error "Not at a table"))
8741 (org-table-find-dataline)
8742 (let* ((col (max 1 (org-table-current-column)))
8743 (beg (org-table-begin))
8744 (end (org-table-end))
8745 ;; Current cursor position
8746 (linepos (org-current-line))
8747 (colpos col))
8748 (goto-char beg)
8749 (while (< (point) end)
8750 (if (org-at-table-hline-p)
8752 (org-table-goto-column col t)
8753 (insert "| "))
8754 (beginning-of-line 2))
8755 (move-marker end nil)
8756 (goto-line linepos)
8757 (org-table-goto-column colpos)
8758 (org-table-align)
8759 (org-table-fix-formulas "$" nil (1- col) 1)))
8761 (defun org-table-find-dataline ()
8762 "Find a dataline in the current table, which is needed for column commands."
8763 (if (and (org-at-table-p)
8764 (not (org-at-table-hline-p)))
8766 (let ((col (current-column))
8767 (end (org-table-end)))
8768 (move-to-column col)
8769 (while (and (< (point) end)
8770 (or (not (= (current-column) col))
8771 (org-at-table-hline-p)))
8772 (beginning-of-line 2)
8773 (move-to-column col))
8774 (if (and (org-at-table-p)
8775 (not (org-at-table-hline-p)))
8777 (error
8778 "Please position cursor in a data line for column operations")))))
8780 (defun org-table-delete-column ()
8781 "Delete a column from the table."
8782 (interactive)
8783 (if (not (org-at-table-p))
8784 (error "Not at a table"))
8785 (org-table-find-dataline)
8786 (org-table-check-inside-data-field)
8787 (let* ((col (org-table-current-column))
8788 (beg (org-table-begin))
8789 (end (org-table-end))
8790 ;; Current cursor position
8791 (linepos (org-current-line))
8792 (colpos col))
8793 (goto-char beg)
8794 (while (< (point) end)
8795 (if (org-at-table-hline-p)
8797 (org-table-goto-column col t)
8798 (and (looking-at "|[^|\n]+|")
8799 (replace-match "|")))
8800 (beginning-of-line 2))
8801 (move-marker end nil)
8802 (goto-line linepos)
8803 (org-table-goto-column colpos)
8804 (org-table-align)
8805 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
8806 col -1 col)))
8808 (defun org-table-move-column-right ()
8809 "Move column to the right."
8810 (interactive)
8811 (org-table-move-column nil))
8812 (defun org-table-move-column-left ()
8813 "Move column to the left."
8814 (interactive)
8815 (org-table-move-column 'left))
8817 (defun org-table-move-column (&optional left)
8818 "Move the current column to the right. With arg LEFT, move to the left."
8819 (interactive "P")
8820 (if (not (org-at-table-p))
8821 (error "Not at a table"))
8822 (org-table-find-dataline)
8823 (org-table-check-inside-data-field)
8824 (let* ((col (org-table-current-column))
8825 (col1 (if left (1- col) col))
8826 (beg (org-table-begin))
8827 (end (org-table-end))
8828 ;; Current cursor position
8829 (linepos (org-current-line))
8830 (colpos (if left (1- col) (1+ col))))
8831 (if (and left (= col 1))
8832 (error "Cannot move column further left"))
8833 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8834 (error "Cannot move column further right"))
8835 (goto-char beg)
8836 (while (< (point) end)
8837 (if (org-at-table-hline-p)
8839 (org-table-goto-column col1 t)
8840 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8841 (replace-match "|\\2|\\1|")))
8842 (beginning-of-line 2))
8843 (move-marker end nil)
8844 (goto-line linepos)
8845 (org-table-goto-column colpos)
8846 (org-table-align)
8847 (org-table-fix-formulas
8848 "$" (list (cons (number-to-string col) (number-to-string colpos))
8849 (cons (number-to-string colpos) (number-to-string col))))))
8851 (defun org-table-move-row-down ()
8852 "Move table row down."
8853 (interactive)
8854 (org-table-move-row nil))
8855 (defun org-table-move-row-up ()
8856 "Move table row up."
8857 (interactive)
8858 (org-table-move-row 'up))
8860 (defun org-table-move-row (&optional up)
8861 "Move the current table line down. With arg UP, move it up."
8862 (interactive "P")
8863 (let* ((col (current-column))
8864 (pos (point))
8865 (hline1p (save-excursion (beginning-of-line 1)
8866 (looking-at org-table-hline-regexp)))
8867 (dline1 (org-table-current-dline))
8868 (dline2 (+ dline1 (if up -1 1)))
8869 (tonew (if up 0 2))
8870 txt hline2p)
8871 (beginning-of-line tonew)
8872 (unless (org-at-table-p)
8873 (goto-char pos)
8874 (error "Cannot move row further"))
8875 (setq hline2p (looking-at org-table-hline-regexp))
8876 (goto-char pos)
8877 (beginning-of-line 1)
8878 (setq pos (point))
8879 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
8880 (delete-region (point) (1+ (point-at-eol)))
8881 (beginning-of-line tonew)
8882 (insert txt)
8883 (beginning-of-line 0)
8884 (move-to-column col)
8885 (unless (or hline1p hline2p)
8886 (org-table-fix-formulas
8887 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
8888 (cons (number-to-string dline2) (number-to-string dline1)))))))
8890 (defun org-table-insert-row (&optional arg)
8891 "Insert a new row above the current line into the table.
8892 With prefix ARG, insert below the current line."
8893 (interactive "P")
8894 (if (not (org-at-table-p))
8895 (error "Not at a table"))
8896 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
8897 (new (org-table-clean-line line)))
8898 ;; Fix the first field if necessary
8899 (if (string-match "^[ \t]*| *[#$] *|" line)
8900 (setq new (replace-match (match-string 0 line) t t new)))
8901 (beginning-of-line (if arg 2 1))
8902 (let (org-table-may-need-update) (insert-before-markers new "\n"))
8903 (beginning-of-line 0)
8904 (re-search-forward "| ?" (point-at-eol) t)
8905 (and (or org-table-may-need-update org-table-overlay-coordinates)
8906 (org-table-align))
8907 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
8909 (defun org-table-insert-hline (&optional above)
8910 "Insert a horizontal-line below the current line into the table.
8911 With prefix ABOVE, insert above the current line."
8912 (interactive "P")
8913 (if (not (org-at-table-p))
8914 (error "Not at a table"))
8915 (let ((line (org-table-clean-line
8916 (buffer-substring (point-at-bol) (point-at-eol))))
8917 (col (current-column)))
8918 (while (string-match "|\\( +\\)|" line)
8919 (setq line (replace-match
8920 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
8921 ?-) "|") t t line)))
8922 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
8923 (beginning-of-line (if above 1 2))
8924 (insert line "\n")
8925 (beginning-of-line (if above 1 -1))
8926 (move-to-column col)
8927 (and org-table-overlay-coordinates (org-table-align))))
8929 (defun org-table-hline-and-move (&optional same-column)
8930 "Insert a hline and move to the row below that line."
8931 (interactive "P")
8932 (let ((col (org-table-current-column)))
8933 (org-table-maybe-eval-formula)
8934 (org-table-maybe-recalculate-line)
8935 (org-table-insert-hline)
8936 (end-of-line 2)
8937 (if (looking-at "\n[ \t]*|-")
8938 (progn (insert "\n|") (org-table-align))
8939 (org-table-next-field))
8940 (if same-column (org-table-goto-column col))))
8942 (defun org-table-clean-line (s)
8943 "Convert a table line S into a string with only \"|\" and space.
8944 In particular, this does handle wide and invisible characters."
8945 (if (string-match "^[ \t]*|-" s)
8946 ;; It's a hline, just map the characters
8947 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
8948 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
8949 (setq s (replace-match
8950 (concat "|" (make-string (org-string-width (match-string 1 s))
8951 ?\ ) "|")
8952 t t s)))
8955 (defun org-table-kill-row ()
8956 "Delete the current row or horizontal line from the table."
8957 (interactive)
8958 (if (not (org-at-table-p))
8959 (error "Not at a table"))
8960 (let ((col (current-column))
8961 (dline (org-table-current-dline)))
8962 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
8963 (if (not (org-at-table-p)) (beginning-of-line 0))
8964 (move-to-column col)
8965 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
8966 dline -1 dline)))
8968 (defun org-table-sort-lines (with-case &optional sorting-type)
8969 "Sort table lines according to the column at point.
8971 The position of point indicates the column to be used for
8972 sorting, and the range of lines is the range between the nearest
8973 horizontal separator lines, or the entire table of no such lines
8974 exist. If point is before the first column, you will be prompted
8975 for the sorting column. If there is an active region, the mark
8976 specifies the first line and the sorting column, while point
8977 should be in the last line to be included into the sorting.
8979 The command then prompts for the sorting type which can be
8980 alphabetically, numerically, or by time (as given in a time stamp
8981 in the field). Sorting in reverse order is also possible.
8983 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
8985 If SORTING-TYPE is specified when this function is called from a Lisp
8986 program, no prompting will take place. SORTING-TYPE must be a character,
8987 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
8988 should be done in reverse order."
8989 (interactive "P")
8990 (let* ((thisline (org-current-line))
8991 (thiscol (org-table-current-column))
8992 beg end bcol ecol tend tbeg column lns pos)
8993 (when (equal thiscol 0)
8994 (if (interactive-p)
8995 (setq thiscol
8996 (string-to-number
8997 (read-string "Use column N for sorting: ")))
8998 (setq thiscol 1))
8999 (org-table-goto-column thiscol))
9000 (org-table-check-inside-data-field)
9001 (if (org-region-active-p)
9002 (progn
9003 (setq beg (region-beginning) end (region-end))
9004 (goto-char beg)
9005 (setq column (org-table-current-column)
9006 beg (point-at-bol))
9007 (goto-char end)
9008 (setq end (point-at-bol 2)))
9009 (setq column (org-table-current-column)
9010 pos (point)
9011 tbeg (org-table-begin)
9012 tend (org-table-end))
9013 (if (re-search-backward org-table-hline-regexp tbeg t)
9014 (setq beg (point-at-bol 2))
9015 (goto-char tbeg)
9016 (setq beg (point-at-bol 1)))
9017 (goto-char pos)
9018 (if (re-search-forward org-table-hline-regexp tend t)
9019 (setq end (point-at-bol 1))
9020 (goto-char tend)
9021 (setq end (point-at-bol))))
9022 (setq beg (move-marker (make-marker) beg)
9023 end (move-marker (make-marker) end))
9024 (untabify beg end)
9025 (goto-char beg)
9026 (org-table-goto-column column)
9027 (skip-chars-backward "^|")
9028 (setq bcol (current-column))
9029 (org-table-goto-column (1+ column))
9030 (skip-chars-backward "^|")
9031 (setq ecol (1- (current-column)))
9032 (org-table-goto-column column)
9033 (setq lns (mapcar (lambda(x) (cons (org-sort-remove-invisible
9034 (org-trim (substring x bcol ecol))) x))
9035 (org-split-string (buffer-substring beg end) "\n")))
9036 (setq lns (org-do-sort lns "Table" with-case sorting-type))
9037 (delete-region beg end)
9038 (move-marker beg nil)
9039 (move-marker end nil)
9040 (insert (mapconcat 'cdr lns "\n") "\n")
9041 (goto-line thisline)
9042 (org-table-goto-column thiscol)
9043 (message "%d lines sorted, based on column %d" (length lns) column)))
9045 ;; FIXME: maybe we will not need this? Table sorting is broken....
9046 (defun org-sort-remove-invisible (s)
9047 (remove-text-properties 0 (length s) org-rm-props s)
9048 (if (string-match org-bracket-link-regexp s)
9049 (setq s (replace-match (if (match-end 2) (match-string 3 s)
9050 (match-string 1 s)))))
9053 (defun org-table-cut-region (beg end)
9054 "Copy region in table to the clipboard and blank all relevant fields."
9055 (interactive "r")
9056 (org-table-copy-region beg end 'cut))
9058 (defun org-table-copy-region (beg end &optional cut)
9059 "Copy rectangular region in table to clipboard.
9060 A special clipboard is used which can only be accessed
9061 with `org-table-paste-rectangle'."
9062 (interactive "rP")
9063 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9064 region cols
9065 (rpl (if cut " " nil)))
9066 (goto-char beg)
9067 (org-table-check-inside-data-field)
9068 (setq l01 (org-current-line)
9069 c01 (org-table-current-column))
9070 (goto-char end)
9071 (org-table-check-inside-data-field)
9072 (setq l02 (org-current-line)
9073 c02 (org-table-current-column))
9074 (setq l1 (min l01 l02) l2 (max l01 l02)
9075 c1 (min c01 c02) c2 (max c01 c02))
9076 (catch 'exit
9077 (while t
9078 (catch 'nextline
9079 (if (> l1 l2) (throw 'exit t))
9080 (goto-line l1)
9081 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9082 (setq cols nil ic1 c1 ic2 c2)
9083 (while (< ic1 (1+ ic2))
9084 (push (org-table-get-field ic1 rpl) cols)
9085 (setq ic1 (1+ ic1)))
9086 (push (nreverse cols) region)
9087 (setq l1 (1+ l1)))))
9088 (setq org-table-clip (nreverse region))
9089 (if cut (org-table-align))
9090 org-table-clip))
9092 (defun org-table-paste-rectangle ()
9093 "Paste a rectangular region into a table.
9094 The upper right corner ends up in the current field. All involved fields
9095 will be overwritten. If the rectangle does not fit into the present table,
9096 the table is enlarged as needed. The process ignores horizontal separator
9097 lines."
9098 (interactive)
9099 (unless (and org-table-clip (listp org-table-clip))
9100 (error "First cut/copy a region to paste!"))
9101 (org-table-check-inside-data-field)
9102 (let* ((clip org-table-clip)
9103 (line (org-current-line))
9104 (col (org-table-current-column))
9105 (org-enable-table-editor t)
9106 (org-table-automatic-realign nil)
9107 c cols field)
9108 (while (setq cols (pop clip))
9109 (while (org-at-table-hline-p) (beginning-of-line 2))
9110 (if (not (org-at-table-p))
9111 (progn (end-of-line 0) (org-table-next-field)))
9112 (setq c col)
9113 (while (setq field (pop cols))
9114 (org-table-goto-column c nil 'force)
9115 (org-table-get-field nil field)
9116 (setq c (1+ c)))
9117 (beginning-of-line 2))
9118 (goto-line line)
9119 (org-table-goto-column col)
9120 (org-table-align)))
9122 (defun org-table-convert ()
9123 "Convert from `org-mode' table to table.el and back.
9124 Obviously, this only works within limits. When an Org-mode table is
9125 converted to table.el, all horizontal separator lines get lost, because
9126 table.el uses these as cell boundaries and has no notion of horizontal lines.
9127 A table.el table can be converted to an Org-mode table only if it does not
9128 do row or column spanning. Multiline cells will become multiple cells.
9129 Beware, Org-mode does not test if the table can be successfully converted - it
9130 blindly applies a recipe that works for simple tables."
9131 (interactive)
9132 (require 'table)
9133 (if (org-at-table.el-p)
9134 ;; convert to Org-mode table
9135 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9136 (end (move-marker (make-marker) (org-table-end t))))
9137 (table-unrecognize-region beg end)
9138 (goto-char beg)
9139 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9140 (replace-match ""))
9141 (goto-char beg))
9142 (if (org-at-table-p)
9143 ;; convert to table.el table
9144 (let ((beg (move-marker (make-marker) (org-table-begin)))
9145 (end (move-marker (make-marker) (org-table-end))))
9146 ;; first, get rid of all horizontal lines
9147 (goto-char beg)
9148 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9149 (replace-match ""))
9150 ;; insert a hline before first
9151 (goto-char beg)
9152 (org-table-insert-hline 'above)
9153 (beginning-of-line -1)
9154 ;; insert a hline after each line
9155 (while (progn (beginning-of-line 3) (< (point) end))
9156 (org-table-insert-hline))
9157 (goto-char beg)
9158 (setq end (move-marker end (org-table-end)))
9159 ;; replace "+" at beginning and ending of hlines
9160 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9161 (replace-match "\\1+-"))
9162 (goto-char beg)
9163 (while (re-search-forward "-|[ \t]*$" end t)
9164 (replace-match "-+"))
9165 (goto-char beg)))))
9167 (defun org-table-wrap-region (arg)
9168 "Wrap several fields in a column like a paragraph.
9169 This is useful if you'd like to spread the contents of a field over several
9170 lines, in order to keep the table compact.
9172 If there is an active region, and both point and mark are in the same column,
9173 the text in the column is wrapped to minimum width for the given number of
9174 lines. Generally, this makes the table more compact. A prefix ARG may be
9175 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9176 formats the selected text to two lines. If the region was longer than two
9177 lines, the remaining lines remain empty. A negative prefix argument reduces
9178 the current number of lines by that amount. The wrapped text is pasted back
9179 into the table. If you formatted it to more lines than it was before, fields
9180 further down in the table get overwritten - so you might need to make space in
9181 the table first.
9183 If there is no region, the current field is split at the cursor position and
9184 the text fragment to the right of the cursor is prepended to the field one
9185 line down.
9187 If there is no region, but you specify a prefix ARG, the current field gets
9188 blank, and the content is appended to the field above."
9189 (interactive "P")
9190 (org-table-check-inside-data-field)
9191 (if (org-region-active-p)
9192 ;; There is a region: fill as a paragraph
9193 (let* ((beg (region-beginning))
9194 (cline (save-excursion (goto-char beg) (org-current-line)))
9195 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9196 nlines)
9197 (org-table-cut-region (region-beginning) (region-end))
9198 (if (> (length (car org-table-clip)) 1)
9199 (error "Region must be limited to single column"))
9200 (setq nlines (if arg
9201 (if (< arg 1)
9202 (+ (length org-table-clip) arg)
9203 arg)
9204 (length org-table-clip)))
9205 (setq org-table-clip
9206 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9207 nil nlines)))
9208 (goto-line cline)
9209 (org-table-goto-column ccol)
9210 (org-table-paste-rectangle))
9211 ;; No region, split the current field at point
9212 (if arg
9213 ;; combine with field above
9214 (let ((s (org-table-blank-field))
9215 (col (org-table-current-column)))
9216 (beginning-of-line 0)
9217 (while (org-at-table-hline-p) (beginning-of-line 0))
9218 (org-table-goto-column col)
9219 (skip-chars-forward "^|")
9220 (skip-chars-backward " ")
9221 (insert " " (org-trim s))
9222 (org-table-align))
9223 ;; split field
9224 (when (looking-at "\\([^|]+\\)+|")
9225 (let ((s (match-string 1)))
9226 (replace-match " |")
9227 (goto-char (match-beginning 0))
9228 (org-table-next-row)
9229 (insert (org-trim s) " ")
9230 (org-table-align))))))
9232 (defvar org-field-marker nil)
9234 (defun org-table-edit-field (arg)
9235 "Edit table field in a different window.
9236 This is mainly useful for fields that contain hidden parts.
9237 When called with a \\[universal-argument] prefix, just make the full field visible so that
9238 it can be edited in place."
9239 (interactive "P")
9240 (if arg
9241 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9242 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9243 (remove-text-properties b e '(org-cwidth t invisible t
9244 display t intangible t))
9245 (if (and (boundp 'font-lock-mode) font-lock-mode)
9246 (font-lock-fontify-block)))
9247 (let ((pos (move-marker (make-marker) (point)))
9248 (field (org-table-get-field))
9249 (cw (current-window-configuration))
9251 (org-switch-to-buffer-other-window "*Org tmp*")
9252 (erase-buffer)
9253 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9254 (let ((org-inhibit-startup t)) (org-mode))
9255 (goto-char (setq p (point-max)))
9256 (insert (org-trim field))
9257 (remove-text-properties p (point-max)
9258 '(invisible t org-cwidth t display t
9259 intangible t))
9260 (goto-char p)
9261 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9262 (org-set-local 'org-window-configuration cw)
9263 (org-set-local 'org-field-marker pos)
9264 (message "Edit and finish with C-c C-c"))))
9266 (defun org-table-finish-edit-field ()
9267 "Finish editing a table data field.
9268 Remove all newline characters, insert the result into the table, realign
9269 the table and kill the editing buffer."
9270 (let ((pos org-field-marker)
9271 (cw org-window-configuration)
9272 (cb (current-buffer))
9273 text)
9274 (goto-char (point-min))
9275 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9276 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9277 (replace-match " "))
9278 (setq text (org-trim (buffer-string)))
9279 (set-window-configuration cw)
9280 (kill-buffer cb)
9281 (select-window (get-buffer-window (marker-buffer pos)))
9282 (goto-char pos)
9283 (move-marker pos nil)
9284 (org-table-check-inside-data-field)
9285 (org-table-get-field nil text)
9286 (org-table-align)
9287 (message "New field value inserted")))
9289 (defun org-trim (s)
9290 "Remove whitespace at beginning and end of string."
9291 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9292 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9295 (defun org-wrap (string &optional width lines)
9296 "Wrap string to either a number of lines, or a width in characters.
9297 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9298 that costs. If there is a word longer than WIDTH, the text is actually
9299 wrapped to the length of that word.
9300 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9301 many lines, whatever width that takes.
9302 The return value is a list of lines, without newlines at the end."
9303 (let* ((words (org-split-string string "[ \t\n]+"))
9304 (maxword (apply 'max (mapcar 'org-string-width words)))
9305 w ll)
9306 (cond (width
9307 (org-do-wrap words (max maxword width)))
9308 (lines
9309 (setq w maxword)
9310 (setq ll (org-do-wrap words maxword))
9311 (if (<= (length ll) lines)
9313 (setq ll words)
9314 (while (> (length ll) lines)
9315 (setq w (1+ w))
9316 (setq ll (org-do-wrap words w)))
9317 ll))
9318 (t (error "Cannot wrap this")))))
9321 (defun org-do-wrap (words width)
9322 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9323 (let (lines line)
9324 (while words
9325 (setq line (pop words))
9326 (while (and words (< (+ (length line) (length (car words))) width))
9327 (setq line (concat line " " (pop words))))
9328 (setq lines (push line lines)))
9329 (nreverse lines)))
9331 (defun org-split-string (string &optional separators)
9332 "Splits STRING into substrings at SEPARATORS.
9333 No empty strings are returned if there are matches at the beginning
9334 and end of string."
9335 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9336 (start 0)
9337 notfirst
9338 (list nil))
9339 (while (and (string-match rexp string
9340 (if (and notfirst
9341 (= start (match-beginning 0))
9342 (< start (length string)))
9343 (1+ start) start))
9344 (< (match-beginning 0) (length string)))
9345 (setq notfirst t)
9346 (or (eq (match-beginning 0) 0)
9347 (and (eq (match-beginning 0) (match-end 0))
9348 (eq (match-beginning 0) start))
9349 (setq list
9350 (cons (substring string start (match-beginning 0))
9351 list)))
9352 (setq start (match-end 0)))
9353 (or (eq start (length string))
9354 (setq list
9355 (cons (substring string start)
9356 list)))
9357 (nreverse list)))
9359 (defun org-table-map-tables (function)
9360 "Apply FUNCTION to the start of all tables in the buffer."
9361 (save-excursion
9362 (save-restriction
9363 (widen)
9364 (goto-char (point-min))
9365 (while (re-search-forward org-table-any-line-regexp nil t)
9366 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9367 (beginning-of-line 1)
9368 (if (looking-at org-table-line-regexp)
9369 (save-excursion (funcall function)))
9370 (re-search-forward org-table-any-border-regexp nil 1))))
9371 (message "Mapping tables: done"))
9373 (defvar org-timecnt) ; dynamically scoped parameter
9375 (defun org-table-sum (&optional beg end nlast)
9376 "Sum numbers in region of current table column.
9377 The result will be displayed in the echo area, and will be available
9378 as kill to be inserted with \\[yank].
9380 If there is an active region, it is interpreted as a rectangle and all
9381 numbers in that rectangle will be summed. If there is no active
9382 region and point is located in a table column, sum all numbers in that
9383 column.
9385 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9386 numbers are assumed to be times as well (in decimal hours) and the
9387 numbers are added as such.
9389 If NLAST is a number, only the NLAST fields will actually be summed."
9390 (interactive)
9391 (save-excursion
9392 (let (col (org-timecnt 0) diff h m s org-table-clip)
9393 (cond
9394 ((and beg end)) ; beg and end given explicitly
9395 ((org-region-active-p)
9396 (setq beg (region-beginning) end (region-end)))
9398 (setq col (org-table-current-column))
9399 (goto-char (org-table-begin))
9400 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9401 (error "No table data"))
9402 (org-table-goto-column col)
9403 (setq beg (point))
9404 (goto-char (org-table-end))
9405 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9406 (error "No table data"))
9407 (org-table-goto-column col)
9408 (setq end (point))))
9409 (let* ((items (apply 'append (org-table-copy-region beg end)))
9410 (items1 (cond ((not nlast) items)
9411 ((>= nlast (length items)) items)
9412 (t (setq items (reverse items))
9413 (setcdr (nthcdr (1- nlast) items) nil)
9414 (nreverse items))))
9415 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9416 items1)))
9417 (res (apply '+ numbers))
9418 (sres (if (= org-timecnt 0)
9419 (format "%g" res)
9420 (setq diff (* 3600 res)
9421 h (floor (/ diff 3600)) diff (mod diff 3600)
9422 m (floor (/ diff 60)) diff (mod diff 60)
9423 s diff)
9424 (format "%d:%02d:%02d" h m s))))
9425 (kill-new sres)
9426 (if (interactive-p)
9427 (message "%s"
9428 (substitute-command-keys
9429 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9430 (length numbers) sres))))
9431 sres))))
9433 (defun org-table-get-number-for-summing (s)
9434 (let (n)
9435 (if (string-match "^ *|? *" s)
9436 (setq s (replace-match "" nil nil s)))
9437 (if (string-match " *|? *$" s)
9438 (setq s (replace-match "" nil nil s)))
9439 (setq n (string-to-number s))
9440 (cond
9441 ((and (string-match "0" s)
9442 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9443 ((string-match "\\`[ \t]+\\'" s) nil)
9444 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9445 (let ((h (string-to-number (or (match-string 1 s) "0")))
9446 (m (string-to-number (or (match-string 2 s) "0")))
9447 (s (string-to-number (or (match-string 4 s) "0"))))
9448 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9449 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9450 ((equal n 0) nil)
9451 (t n))))
9453 (defun org-table-current-field-formula (&optional key noerror)
9454 "Return the formula active for the current field.
9455 Assumes that specials are in place.
9456 If KEY is given, return the key to this formula.
9457 Otherwise return the formula preceeded with \"=\" or \":=\"."
9458 (let* ((name (car (rassoc (list (org-current-line)
9459 (org-table-current-column))
9460 org-table-named-field-locations)))
9461 (col (org-table-current-column))
9462 (scol (int-to-string col))
9463 (ref (format "@%d$%d" (org-table-current-dline) col))
9464 (stored-list (org-table-get-stored-formulas noerror))
9465 (ass (or (assoc name stored-list)
9466 (assoc ref stored-list)
9467 (assoc scol stored-list))))
9468 (if key
9469 (car ass)
9470 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9471 (cdr ass))))))
9473 (defun org-table-get-formula (&optional equation named)
9474 "Read a formula from the minibuffer, offer stored formula as default.
9475 When NAMED is non-nil, look for a named equation."
9476 (let* ((stored-list (org-table-get-stored-formulas))
9477 (name (car (rassoc (list (org-current-line)
9478 (org-table-current-column))
9479 org-table-named-field-locations)))
9480 (ref (format "@%d$%d" (org-table-current-dline)
9481 (org-table-current-column)))
9482 (refass (assoc ref stored-list))
9483 (scol (if named
9484 (if name name ref)
9485 (int-to-string (org-table-current-column))))
9486 (dummy (and (or name refass) (not named)
9487 (not (y-or-n-p "Replace field formula with column formula? " ))
9488 (error "Abort")))
9489 (name (or name ref))
9490 (org-table-may-need-update nil)
9491 (stored (cdr (assoc scol stored-list)))
9492 (eq (cond
9493 ((and stored equation (string-match "^ *=? *$" equation))
9494 stored)
9495 ((stringp equation)
9496 equation)
9497 (t (org-table-formula-from-user
9498 (read-string
9499 (org-table-formula-to-user
9500 (format "%s formula %s%s="
9501 (if named "Field" "Column")
9502 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9503 scol))
9504 (if stored (org-table-formula-to-user stored) "")
9505 'org-table-formula-history
9506 )))))
9507 mustsave)
9508 (when (not (string-match "\\S-" eq))
9509 ;; remove formula
9510 (setq stored-list (delq (assoc scol stored-list) stored-list))
9511 (org-table-store-formulas stored-list)
9512 (error "Formula removed"))
9513 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9514 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9515 (if (and name (not named))
9516 ;; We set the column equation, delete the named one.
9517 (setq stored-list (delq (assoc name stored-list) stored-list)
9518 mustsave t))
9519 (if stored
9520 (setcdr (assoc scol stored-list) eq)
9521 (setq stored-list (cons (cons scol eq) stored-list)))
9522 (if (or mustsave (not (equal stored eq)))
9523 (org-table-store-formulas stored-list))
9524 eq))
9526 (defun org-table-store-formulas (alist)
9527 "Store the list of formulas below the current table."
9528 (setq alist (sort alist 'org-table-formula-less-p))
9529 (save-excursion
9530 (goto-char (org-table-end))
9531 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9532 (progn
9533 ;; don't overwrite TBLFM, we might use text properties to store stuff
9534 (goto-char (match-beginning 2))
9535 (delete-region (match-beginning 2) (match-end 0)))
9536 (insert "#+TBLFM:"))
9537 (insert " "
9538 (mapconcat (lambda (x)
9539 (concat
9540 (if (equal (string-to-char (car x)) ?@) "" "$")
9541 (car x) "=" (cdr x)))
9542 alist "::")
9543 "\n")))
9545 (defsubst org-table-formula-make-cmp-string (a)
9546 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9547 (concat
9548 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9549 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9550 (if (match-end 5) (concat "@@" (match-string 5 a))))))
9552 (defun org-table-formula-less-p (a b)
9553 "Compare two formulas for sorting."
9554 (let ((as (org-table-formula-make-cmp-string (car a)))
9555 (bs (org-table-formula-make-cmp-string (car b))))
9556 (and as bs (string< as bs))))
9558 (defun org-table-get-stored-formulas (&optional noerror)
9559 "Return an alist with the stored formulas directly after current table."
9560 (interactive)
9561 (let (scol eq eq-alist strings string seen)
9562 (save-excursion
9563 (goto-char (org-table-end))
9564 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9565 (setq strings (org-split-string (match-string 2) " *:: *"))
9566 (while (setq string (pop strings))
9567 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
9568 (setq scol (if (match-end 2)
9569 (match-string 2 string)
9570 (match-string 1 string))
9571 eq (match-string 3 string)
9572 eq-alist (cons (cons scol eq) eq-alist))
9573 (if (member scol seen)
9574 (if noerror
9575 (progn
9576 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9577 (ding)
9578 (sit-for 2))
9579 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
9580 (push scol seen))))))
9581 (nreverse eq-alist)))
9583 (defun org-table-fix-formulas (key replace &optional limit delta remove)
9584 "Modify the equations after the table structure has been edited.
9585 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
9586 For all numbers larger than LIMIT, shift them by DELTA."
9587 (save-excursion
9588 (goto-char (org-table-end))
9589 (when (looking-at "#\\+TBLFM:")
9590 (let ((re (concat key "\\([0-9]+\\)"))
9591 (re2
9592 (when remove
9593 (if (equal key "$")
9594 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
9595 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
9596 s n a)
9597 (when remove
9598 (while (re-search-forward re2 (point-at-eol) t)
9599 (replace-match "")))
9600 (while (re-search-forward re (point-at-eol) t)
9601 (setq s (match-string 1) n (string-to-number s))
9602 (cond
9603 ((setq a (assoc s replace))
9604 (replace-match (concat key (cdr a)) t t))
9605 ((and limit (> n limit))
9606 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
9608 (defun org-table-get-specials ()
9609 "Get the column names and local parameters for this table."
9610 (save-excursion
9611 (let ((beg (org-table-begin)) (end (org-table-end))
9612 names name fields fields1 field cnt
9613 c v l line col types dlines hlines)
9614 (setq org-table-column-names nil
9615 org-table-local-parameters nil
9616 org-table-named-field-locations nil
9617 org-table-current-begin-line nil
9618 org-table-current-begin-pos nil
9619 org-table-current-line-types nil)
9620 (goto-char beg)
9621 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9622 (setq names (org-split-string (match-string 1) " *| *")
9623 cnt 1)
9624 (while (setq name (pop names))
9625 (setq cnt (1+ cnt))
9626 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9627 (push (cons name (int-to-string cnt)) org-table-column-names))))
9628 (setq org-table-column-names (nreverse org-table-column-names))
9629 (setq org-table-column-name-regexp
9630 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9631 (goto-char beg)
9632 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9633 (setq fields (org-split-string (match-string 1) " *| *"))
9634 (while (setq field (pop fields))
9635 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9636 (push (cons (match-string 1 field) (match-string 2 field))
9637 org-table-local-parameters))))
9638 (goto-char beg)
9639 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9640 (setq c (match-string 1)
9641 fields (org-split-string (match-string 2) " *| *"))
9642 (save-excursion
9643 (beginning-of-line (if (equal c "_") 2 0))
9644 (setq line (org-current-line) col 1)
9645 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9646 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9647 (while (and fields1 (setq field (pop fields)))
9648 (setq v (pop fields1) col (1+ col))
9649 (when (and (stringp field) (stringp v)
9650 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9651 (push (cons field v) org-table-local-parameters)
9652 (push (list field line col) org-table-named-field-locations))))
9653 ;; Analyse the line types
9654 (goto-char beg)
9655 (setq org-table-current-begin-line (org-current-line)
9656 org-table-current-begin-pos (point)
9657 l org-table-current-begin-line)
9658 (while (looking-at "[ \t]*|\\(-\\)?")
9659 (push (if (match-end 1) 'hline 'dline) types)
9660 (if (match-end 1) (push l hlines) (push l dlines))
9661 (beginning-of-line 2)
9662 (setq l (1+ l)))
9663 (setq org-table-current-line-types (apply 'vector (nreverse types))
9664 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
9665 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
9667 (defun org-table-maybe-eval-formula ()
9668 "Check if the current field starts with \"=\" or \":=\".
9669 If yes, store the formula and apply it."
9670 ;; We already know we are in a table. Get field will only return a formula
9671 ;; when appropriate. It might return a separator line, but no problem.
9672 (when org-table-formula-evaluate-inline
9673 (let* ((field (org-trim (or (org-table-get-field) "")))
9674 named eq)
9675 (when (string-match "^:?=\\(.*\\)" field)
9676 (setq named (equal (string-to-char field) ?:)
9677 eq (match-string 1 field))
9678 (if (or (fboundp 'calc-eval)
9679 (equal (substring eq 0 (min 2 (length eq))) "'("))
9680 (org-table-eval-formula (if named '(4) nil)
9681 (org-table-formula-from-user eq))
9682 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
9684 (defvar org-recalc-commands nil
9685 "List of commands triggering the recalculation of a line.
9686 Will be filled automatically during use.")
9688 (defvar org-recalc-marks
9689 '((" " . "Unmarked: no special line, no automatic recalculation")
9690 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9691 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9692 ("!" . "Column name definition line. Reference in formula as $name.")
9693 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9694 ("_" . "Names for values in row below this one.")
9695 ("^" . "Names for values in row above this one.")))
9697 (defun org-table-rotate-recalc-marks (&optional newchar)
9698 "Rotate the recalculation mark in the first column.
9699 If in any row, the first field is not consistent with a mark,
9700 insert a new column for the markers.
9701 When there is an active region, change all the lines in the region,
9702 after prompting for the marking character.
9703 After each change, a message will be displayed indicating the meaning
9704 of the new mark."
9705 (interactive)
9706 (unless (org-at-table-p) (error "Not at a table"))
9707 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9708 (beg (org-table-begin))
9709 (end (org-table-end))
9710 (l (org-current-line))
9711 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9712 (l2 (if (org-region-active-p) (org-current-line (region-end))))
9713 (have-col
9714 (save-excursion
9715 (goto-char beg)
9716 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
9717 (col (org-table-current-column))
9718 (forcenew (car (assoc newchar org-recalc-marks)))
9719 epos new)
9720 (when l1
9721 (message "Change region to what mark? Type # * ! $ or SPC: ")
9722 (setq newchar (char-to-string (read-char-exclusive))
9723 forcenew (car (assoc newchar org-recalc-marks))))
9724 (if (and newchar (not forcenew))
9725 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
9726 newchar))
9727 (if l1 (goto-line l1))
9728 (save-excursion
9729 (beginning-of-line 1)
9730 (unless (looking-at org-table-dataline-regexp)
9731 (error "Not at a table data line")))
9732 (unless have-col
9733 (org-table-goto-column 1)
9734 (org-table-insert-column)
9735 (org-table-goto-column (1+ col)))
9736 (setq epos (point-at-eol))
9737 (save-excursion
9738 (beginning-of-line 1)
9739 (org-table-get-field
9740 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
9741 (concat " "
9742 (setq new (or forcenew
9743 (cadr (member (match-string 1) marks))))
9744 " ")
9745 " # ")))
9746 (if (and l1 l2)
9747 (progn
9748 (goto-line l1)
9749 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
9750 (and (looking-at org-table-dataline-regexp)
9751 (org-table-get-field 1 (concat " " new " "))))
9752 (goto-line l1)))
9753 (if (not (= epos (point-at-eol))) (org-table-align))
9754 (goto-line l)
9755 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
9757 (defun org-table-maybe-recalculate-line ()
9758 "Recompute the current line if marked for it, and if we haven't just done it."
9759 (interactive)
9760 (and org-table-allow-automatic-line-recalculation
9761 (not (and (memq last-command org-recalc-commands)
9762 (equal org-last-recalc-line (org-current-line))))
9763 (save-excursion (beginning-of-line 1)
9764 (looking-at org-table-auto-recalculate-regexp))
9765 (org-table-recalculate) t))
9767 (defvar org-table-formula-debug nil
9768 "Non-nil means, debug table formulas.
9769 When nil, simply write \"#ERROR\" in corrupted fields.")
9770 (make-variable-buffer-local 'org-table-formula-debug)
9772 (defvar modes)
9773 (defsubst org-set-calc-mode (var &optional value)
9774 (if (stringp var)
9775 (setq var (assoc var '(("D" calc-angle-mode deg)
9776 ("R" calc-angle-mode rad)
9777 ("F" calc-prefer-frac t)
9778 ("S" calc-symbolic-mode t)))
9779 value (nth 2 var) var (nth 1 var)))
9780 (if (memq var modes)
9781 (setcar (cdr (memq var modes)) value)
9782 (cons var (cons value modes)))
9783 modes)
9785 (defun org-table-eval-formula (&optional arg equation
9786 suppress-align suppress-const
9787 suppress-store suppress-analysis)
9788 "Replace the table field value at the cursor by the result of a calculation.
9790 This function makes use of Dave Gillespie's Calc package, in my view the
9791 most exciting program ever written for GNU Emacs. So you need to have Calc
9792 installed in order to use this function.
9794 In a table, this command replaces the value in the current field with the
9795 result of a formula. It also installs the formula as the \"current\" column
9796 formula, by storing it in a special line below the table. When called
9797 with a `C-u' prefix, the current field must ba a named field, and the
9798 formula is installed as valid in only this specific field.
9800 When called with two `C-u' prefixes, insert the active equation
9801 for the field back into the current field, so that it can be
9802 edited there. This is useful in order to use \\[org-table-show-reference]
9803 to check the referenced fields.
9805 When called, the command first prompts for a formula, which is read in
9806 the minibuffer. Previously entered formulas are available through the
9807 history list, and the last used formula is offered as a default.
9808 These stored formulas are adapted correctly when moving, inserting, or
9809 deleting columns with the corresponding commands.
9811 The formula can be any algebraic expression understood by the Calc package.
9812 For details, see the Org-mode manual.
9814 This function can also be called from Lisp programs and offers
9815 additional arguments: EQUATION can be the formula to apply. If this
9816 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
9817 used to speed-up recursive calls by by-passing unnecessary aligns.
9818 SUPPRESS-CONST suppresses the interpretation of constants in the
9819 formula, assuming that this has been done already outside the function.
9820 SUPPRESS-STORE means the formula should not be stored, either because
9821 it is already stored, or because it is a modified equation that should
9822 not overwrite the stored one."
9823 (interactive "P")
9824 (org-table-check-inside-data-field)
9825 (or suppress-analysis (org-table-get-specials))
9826 (if (equal arg '(16))
9827 (let ((eq (org-table-current-field-formula)))
9828 (or eq (error "No equation active for current field"))
9829 (org-table-get-field nil eq)
9830 (org-table-align)
9831 (setq org-table-may-need-update t))
9832 (let* (fields
9833 (ndown (if (integerp arg) arg 1))
9834 (org-table-automatic-realign nil)
9835 (case-fold-search nil)
9836 (down (> ndown 1))
9837 (formula (if (and equation suppress-store)
9838 equation
9839 (org-table-get-formula equation (equal arg '(4)))))
9840 (n0 (org-table-current-column))
9841 (modes (copy-sequence org-calc-default-modes))
9842 (numbers nil) ; was a variable, now fixed default
9843 (keep-empty nil)
9844 n form form0 bw fmt x ev orig c lispp literal)
9845 ;; Parse the format string. Since we have a lot of modes, this is
9846 ;; a lot of work. However, I think calc still uses most of the time.
9847 (if (string-match ";" formula)
9848 (let ((tmp (org-split-string formula ";")))
9849 (setq formula (car tmp)
9850 fmt (concat (cdr (assoc "%" org-table-local-parameters))
9851 (nth 1 tmp)))
9852 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
9853 (setq c (string-to-char (match-string 1 fmt))
9854 n (string-to-number (match-string 2 fmt)))
9855 (if (= c ?p)
9856 (setq modes (org-set-calc-mode 'calc-internal-prec n))
9857 (setq modes (org-set-calc-mode
9858 'calc-float-format
9859 (list (cdr (assoc c '((?n . float) (?f . fix)
9860 (?s . sci) (?e . eng))))
9861 n))))
9862 (setq fmt (replace-match "" t t fmt)))
9863 (if (string-match "[NT]" fmt)
9864 (setq numbers (equal (match-string 0 fmt) "N")
9865 fmt (replace-match "" t t fmt)))
9866 (if (string-match "L" fmt)
9867 (setq literal t
9868 fmt (replace-match "" t t fmt)))
9869 (if (string-match "E" fmt)
9870 (setq keep-empty t
9871 fmt (replace-match "" t t fmt)))
9872 (while (string-match "[DRFS]" fmt)
9873 (setq modes (org-set-calc-mode (match-string 0 fmt)))
9874 (setq fmt (replace-match "" t t fmt)))
9875 (unless (string-match "\\S-" fmt)
9876 (setq fmt nil))))
9877 (if (and (not suppress-const) org-table-formula-use-constants)
9878 (setq formula (org-table-formula-substitute-names formula)))
9879 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
9880 (while (> ndown 0)
9881 (setq fields (org-split-string
9882 (org-no-properties
9883 (buffer-substring (point-at-bol) (point-at-eol)))
9884 " *| *"))
9885 (if (eq numbers t)
9886 (setq fields (mapcar
9887 (lambda (x) (number-to-string (string-to-number x)))
9888 fields)))
9889 (setq ndown (1- ndown))
9890 (setq form (copy-sequence formula)
9891 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
9892 (if (and lispp literal) (setq lispp 'literal))
9893 ;; Check for old vertical references
9894 (setq form (org-rewrite-old-row-references form))
9895 ;; Insert complex ranges
9896 (while (string-match org-table-range-regexp form)
9897 (setq form
9898 (replace-match
9899 (save-match-data
9900 (org-table-make-reference
9901 (org-table-get-range (match-string 0 form) nil n0)
9902 keep-empty numbers lispp))
9903 t t form)))
9904 ;; Insert simple ranges
9905 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
9906 (setq form
9907 (replace-match
9908 (save-match-data
9909 (org-table-make-reference
9910 (org-sublist
9911 fields (string-to-number (match-string 1 form))
9912 (string-to-number (match-string 2 form)))
9913 keep-empty numbers lispp))
9914 t t form)))
9915 (setq form0 form)
9916 ;; Insert the references to fields in same row
9917 (while (string-match "\\$\\([0-9]+\\)" form)
9918 (setq n (string-to-number (match-string 1 form))
9919 x (nth (1- (if (= n 0) n0 n)) fields))
9920 (unless x (error "Invalid field specifier \"%s\""
9921 (match-string 0 form)))
9922 (setq form (replace-match
9923 (save-match-data
9924 (org-table-make-reference x nil numbers lispp))
9925 t t form)))
9927 (if lispp
9928 (setq ev (condition-case nil
9929 (eval (eval (read form)))
9930 (error "#ERROR"))
9931 ev (if (numberp ev) (number-to-string ev) ev))
9932 (or (fboundp 'calc-eval)
9933 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
9934 (setq ev (calc-eval (cons form modes)
9935 (if numbers 'num))))
9937 (when org-table-formula-debug
9938 (with-output-to-temp-buffer "*Substitution History*"
9939 (princ (format "Substitution history of formula
9940 Orig: %s
9941 $xyz-> %s
9942 @r$c-> %s
9943 $1-> %s\n" orig formula form0 form))
9944 (if (listp ev)
9945 (princ (format " %s^\nError: %s"
9946 (make-string (car ev) ?\-) (nth 1 ev)))
9947 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
9948 ev (or fmt "NONE")
9949 (if fmt (format fmt (string-to-number ev)) ev)))))
9950 (setq bw (get-buffer-window "*Substitution History*"))
9951 (shrink-window-if-larger-than-buffer bw)
9952 (unless (and (interactive-p) (not ndown))
9953 (unless (let (inhibit-redisplay)
9954 (y-or-n-p "Debugging Formula. Continue to next? "))
9955 (org-table-align)
9956 (error "Abort"))
9957 (delete-window bw)
9958 (message "")))
9959 (if (listp ev) (setq fmt nil ev "#ERROR"))
9960 (org-table-justify-field-maybe
9961 (if fmt (format fmt (string-to-number ev)) ev))
9962 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
9963 (call-interactively 'org-return)
9964 (setq ndown 0)))
9965 (and down (org-table-maybe-recalculate-line))
9966 (or suppress-align (and org-table-may-need-update
9967 (org-table-align))))))
9969 (defun org-table-put-field-property (prop value)
9970 (save-excursion
9971 (put-text-property (progn (skip-chars-backward "^|") (point))
9972 (progn (skip-chars-forward "^|") (point))
9973 prop value)))
9975 (defun org-table-get-range (desc &optional tbeg col highlight)
9976 "Get a calc vector from a column, accorting to descriptor DESC.
9977 Optional arguments TBEG and COL can give the beginning of the table and
9978 the current column, to avoid unnecessary parsing.
9979 HIGHLIGHT means, just highlight the range."
9980 (if (not (equal (string-to-char desc) ?@))
9981 (setq desc (concat "@" desc)))
9982 (save-excursion
9983 (or tbeg (setq tbeg (org-table-begin)))
9984 (or col (setq col (org-table-current-column)))
9985 (let ((thisline (org-current-line))
9986 beg end c1 c2 r1 r2 rangep tmp)
9987 (unless (string-match org-table-range-regexp desc)
9988 (error "Invalid table range specifier `%s'" desc))
9989 (setq rangep (match-end 3)
9990 r1 (and (match-end 1) (match-string 1 desc))
9991 r2 (and (match-end 4) (match-string 4 desc))
9992 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
9993 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
9995 (and c1 (setq c1 (+ (string-to-number c1)
9996 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
9997 (and c2 (setq c2 (+ (string-to-number c2)
9998 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
9999 (if (equal r1 "") (setq r1 nil))
10000 (if (equal r2 "") (setq r2 nil))
10001 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10002 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10003 ; (setq r2 (or r2 r1) c2 (or c2 c1))
10004 (if (not r1) (setq r1 thisline))
10005 (if (not r2) (setq r2 thisline))
10006 (if (not c1) (setq c1 col))
10007 (if (not c2) (setq c2 col))
10008 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10009 ;; just one field
10010 (progn
10011 (goto-line r1)
10012 (while (not (looking-at org-table-dataline-regexp))
10013 (beginning-of-line 2))
10014 (prog1 (org-trim (org-table-get-field c1))
10015 (if highlight (org-table-highlight-rectangle (point) (point)))))
10016 ;; A range, return a vector
10017 ;; First sort the numbers to get a regular ractangle
10018 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10019 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10020 (goto-line r1)
10021 (while (not (looking-at org-table-dataline-regexp))
10022 (beginning-of-line 2))
10023 (org-table-goto-column c1)
10024 (setq beg (point))
10025 (goto-line r2)
10026 (while (not (looking-at org-table-dataline-regexp))
10027 (beginning-of-line 0))
10028 (org-table-goto-column c2)
10029 (setq end (point))
10030 (if highlight
10031 (org-table-highlight-rectangle
10032 beg (progn (skip-chars-forward "^|\n") (point))))
10033 ;; return string representation of calc vector
10034 (mapcar 'org-trim
10035 (apply 'append (org-table-copy-region beg end)))))))
10037 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10038 "Analyze descriptor DESC and retrieve the corresponding line number.
10039 The cursor is currently in line CLINE, the table begins in line BLINE,
10040 and TABLE is a vector with line types."
10041 (if (string-match "^[0-9]+$" desc)
10042 (aref org-table-dlines (string-to-number desc))
10043 (setq cline (or cline (org-current-line))
10044 bline (or bline org-table-current-begin-line)
10045 table (or table org-table-current-line-types))
10046 (if (or
10047 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10048 ;; 1 2 3 4 5 6
10049 (and (not (match-end 3)) (not (match-end 6)))
10050 (and (match-end 3) (match-end 6) (not (match-end 5))))
10051 (error "invalid row descriptor `%s'" desc))
10052 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10053 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10054 (odir (and (match-end 5) (match-string 5 desc)))
10055 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10056 (i (- cline bline))
10057 (rel (and (match-end 6)
10058 (or (and (match-end 1) (not (match-end 3)))
10059 (match-end 5)))))
10060 (if (and hn (not hdir))
10061 (progn
10062 (setq i 0 hdir "+")
10063 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10064 (if (and (not hn) on (not odir))
10065 (error "should never happen");;(aref org-table-dlines on)
10066 (if (and hn (> hn 0))
10067 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10068 (if on
10069 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10070 (+ bline i)))))
10072 (defun org-find-row-type (table i type backwards relative n)
10073 (let ((l (length table)))
10074 (while (> n 0)
10075 (while (and (setq i (+ i (if backwards -1 1)))
10076 (>= i 0) (< i l)
10077 (not (eq (aref table i) type))
10078 (if (and relative (eq (aref table i) 'hline))
10079 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10080 t)))
10081 (setq n (1- n)))
10082 (if (or (< i 0) (>= i l))
10083 (error "Row descriptior leads outside table")
10084 i)))
10086 (defun org-rewrite-old-row-references (s)
10087 (if (string-match "&[-+0-9I]" s)
10088 (error "Formula contains old &row reference, please rewrite using @-syntax")
10091 (defun org-table-make-reference (elements keep-empty numbers lispp)
10092 "Convert list ELEMENTS to something appropriate to insert into formula.
10093 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10094 NUMBERS indicates that everything should be converted to numbers.
10095 LISPP means to return something appropriate for a Lisp list."
10096 (if (stringp elements) ; just a single val
10097 (if lispp
10098 (if (eq lispp 'literal)
10099 elements
10100 (prin1-to-string (if numbers (string-to-number elements) elements)))
10101 (if (equal elements "") (setq elements "0"))
10102 (if numbers (number-to-string (string-to-number elements)) elements))
10103 (unless keep-empty
10104 (setq elements
10105 (delq nil
10106 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10107 elements))))
10108 (setq elements (or elements '("0")))
10109 (if lispp
10110 (mapconcat
10111 (lambda (x)
10112 (if (eq lispp 'literal)
10114 (prin1-to-string (if numbers (string-to-number x) x))))
10115 elements " ")
10116 (concat "[" (mapconcat
10117 (lambda (x)
10118 (if numbers (number-to-string (string-to-number x)) x))
10119 elements
10120 ",") "]"))))
10122 (defun org-table-recalculate (&optional all noalign)
10123 "Recalculate the current table line by applying all stored formulas.
10124 With prefix arg ALL, do this for all lines in the table."
10125 (interactive "P")
10126 (or (memq this-command org-recalc-commands)
10127 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10128 (unless (org-at-table-p) (error "Not at a table"))
10129 (if (equal all '(16))
10130 (org-table-iterate)
10131 (org-table-get-specials)
10132 (let* ((eqlist (sort (org-table-get-stored-formulas)
10133 (lambda (a b) (string< (car a) (car b)))))
10134 (inhibit-redisplay (not debug-on-error))
10135 (line-re org-table-dataline-regexp)
10136 (thisline (org-current-line))
10137 (thiscol (org-table-current-column))
10138 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10139 ;; Insert constants in all formulas
10140 (setq eqlist
10141 (mapcar (lambda (x)
10142 (setcdr x (org-table-formula-substitute-names (cdr x)))
10144 eqlist))
10145 ;; Split the equation list
10146 (while (setq eq (pop eqlist))
10147 (if (<= (string-to-char (car eq)) ?9)
10148 (push eq eqlnum)
10149 (push eq eqlname)))
10150 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10151 (if all
10152 (progn
10153 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10154 (goto-char (setq beg (org-table-begin)))
10155 (if (re-search-forward org-table-calculate-mark-regexp end t)
10156 ;; This is a table with marked lines, compute selected lines
10157 (setq line-re org-table-recalculate-regexp)
10158 ;; Move forward to the first non-header line
10159 (if (and (re-search-forward org-table-dataline-regexp end t)
10160 (re-search-forward org-table-hline-regexp end t)
10161 (re-search-forward org-table-dataline-regexp end t))
10162 (setq beg (match-beginning 0))
10163 nil))) ;; just leave beg where it is
10164 (setq beg (point-at-bol)
10165 end (move-marker (make-marker) (1+ (point-at-eol)))))
10166 (goto-char beg)
10167 (and all (message "Re-applying formulas to full table..."))
10169 ;; First find the named fields, and mark them untouchanble
10170 (remove-text-properties beg end '(org-untouchable t))
10171 (while (setq eq (pop eqlname))
10172 (setq name (car eq)
10173 a (assoc name org-table-named-field-locations))
10174 (and (not a)
10175 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10176 (setq a (list name
10177 (aref org-table-dlines
10178 (string-to-number (match-string 1 name)))
10179 (string-to-number (match-string 2 name)))))
10180 (when (and a (or all (equal (nth 1 a) thisline)))
10181 (message "Re-applying formula to field: %s" name)
10182 (goto-line (nth 1 a))
10183 (org-table-goto-column (nth 2 a))
10184 (push (append a (list (cdr eq))) eqlname1)
10185 (org-table-put-field-property :org-untouchable t)))
10187 ;; Now evauluate the column formulas, but skip fields covered by
10188 ;; field formulas
10189 (goto-char beg)
10190 (while (re-search-forward line-re end t)
10191 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10192 ;; Unprotected line, recalculate
10193 (and all (message "Re-applying formulas to full table...(line %d)"
10194 (setq cnt (1+ cnt))))
10195 (setq org-last-recalc-line (org-current-line))
10196 (setq eql eqlnum)
10197 (while (setq entry (pop eql))
10198 (goto-line org-last-recalc-line)
10199 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10200 (unless (get-text-property (point) :org-untouchable)
10201 (org-table-eval-formula nil (cdr entry)
10202 'noalign 'nocst 'nostore 'noanalysis)))))
10204 ;; Now evaluate the field formulas
10205 (while (setq eq (pop eqlname1))
10206 (message "Re-applying formula to field: %s" (car eq))
10207 (goto-line (nth 1 eq))
10208 (org-table-goto-column (nth 2 eq))
10209 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10210 'nostore 'noanalysis))
10212 (goto-line thisline)
10213 (org-table-goto-column thiscol)
10214 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10215 (or noalign (and org-table-may-need-update (org-table-align))
10216 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10218 ;; back to initial position
10219 (message "Re-applying formulas...done")
10220 (goto-line thisline)
10221 (org-table-goto-column thiscol)
10222 (or noalign (and org-table-may-need-update (org-table-align))
10223 (and all (message "Re-applying formulas...done"))))))
10225 (defun org-table-iterate (&optional arg)
10226 "Recalculate the table until it does not change anymore."
10227 (interactive "P")
10228 (let ((imax (if arg (prefix-numeric-value arg) 10))
10229 (i 0)
10230 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10231 thistbl)
10232 (catch 'exit
10233 (while (< i imax)
10234 (setq i (1+ i))
10235 (org-table-recalculate 'all)
10236 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10237 (if (not (string= lasttbl thistbl))
10238 (setq lasttbl thistbl)
10239 (if (> i 1)
10240 (message "Convergence after %d iterations" i)
10241 (message "Table was already stable"))
10242 (throw 'exit t)))
10243 (error "No convergence after %d iterations" i))))
10245 (defun org-table-formula-substitute-names (f)
10246 "Replace $const with values in string F."
10247 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10248 ;; First, check for column names
10249 (while (setq start (string-match org-table-column-name-regexp f start))
10250 (setq start (1+ start))
10251 (setq a (assoc (match-string 1 f) org-table-column-names))
10252 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10253 ;; Parameters and constants
10254 (setq start 0)
10255 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10256 (setq start (1+ start))
10257 (if (setq a (save-match-data
10258 (org-table-get-constant (match-string 1 f))))
10259 (setq f (replace-match
10260 (concat (if pp "(") a (if pp ")")) t t f))))
10261 (if org-table-formula-debug
10262 (put-text-property 0 (length f) :orig-formula f1 f))
10265 (defun org-table-get-constant (const)
10266 "Find the value for a parameter or constant in a formula.
10267 Parameters get priority."
10268 (or (cdr (assoc const org-table-local-parameters))
10269 (cdr (assoc const org-table-formula-constants-local))
10270 (cdr (assoc const org-table-formula-constants))
10271 (and (fboundp 'constants-get) (constants-get const))
10272 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10273 (org-entry-get nil (substring const 5) 'inherit))
10274 "#UNDEFINED_NAME"))
10276 (defvar org-table-fedit-map
10277 (let ((map (make-sparse-keymap)))
10278 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10279 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10280 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10281 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10282 (org-defkey map "\C-c?" 'org-table-show-reference)
10283 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10284 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10285 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10286 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10287 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10288 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10289 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10290 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10291 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10292 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10293 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10294 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10295 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10296 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10297 map))
10299 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10300 '("Edit-Formulas"
10301 ["Finish and Install" org-table-fedit-finish t]
10302 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10303 ["Abort" org-table-fedit-abort t]
10304 "--"
10305 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10306 ["Complete Lisp Symbol" lisp-complete-symbol t]
10307 "--"
10308 "Shift Reference at Point"
10309 ["Up" org-table-fedit-ref-up t]
10310 ["Down" org-table-fedit-ref-down t]
10311 ["Left" org-table-fedit-ref-left t]
10312 ["Right" org-table-fedit-ref-right t]
10314 "Change Test Row for Column Formulas"
10315 ["Up" org-table-fedit-line-up t]
10316 ["Down" org-table-fedit-line-down t]
10317 "--"
10318 ["Scroll Table Window" org-table-fedit-scroll t]
10319 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10320 ["Show Table Grid" org-table-fedit-toggle-coordinates
10321 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10322 org-table-overlay-coordinates)]
10323 "--"
10324 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10325 :style toggle :selected org-table-buffer-is-an]))
10327 (defvar org-pos)
10329 (defun org-table-edit-formulas ()
10330 "Edit the formulas of the current table in a separate buffer."
10331 (interactive)
10332 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10333 (beginning-of-line 0))
10334 (unless (org-at-table-p) (error "Not at a table"))
10335 (org-table-get-specials)
10336 (let ((key (org-table-current-field-formula 'key 'noerror))
10337 (eql (sort (org-table-get-stored-formulas 'noerror)
10338 'org-table-formula-less-p))
10339 (pos (move-marker (make-marker) (point)))
10340 (startline 1)
10341 (wc (current-window-configuration))
10342 (titles '((column . "# Column Formulas\n")
10343 (field . "# Field Formulas\n")
10344 (named . "# Named Field Formulas\n")))
10345 entry s type title)
10346 (org-switch-to-buffer-other-window "*Edit Formulas*")
10347 (erase-buffer)
10348 ;; Keep global-font-lock-mode from turning on font-lock-mode
10349 (let ((font-lock-global-modes '(not fundamental-mode)))
10350 (fundamental-mode))
10351 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10352 (org-set-local 'org-pos pos)
10353 (org-set-local 'org-window-configuration wc)
10354 (use-local-map org-table-fedit-map)
10355 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10356 (easy-menu-add org-table-fedit-menu)
10357 (setq startline (org-current-line))
10358 (while (setq entry (pop eql))
10359 (setq type (cond
10360 ((equal (string-to-char (car entry)) ?@) 'field)
10361 ((string-match "^[0-9]" (car entry)) 'column)
10362 (t 'named)))
10363 (when (setq title (assq type titles))
10364 (or (bobp) (insert "\n"))
10365 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10366 (setq titles (delq title titles)))
10367 (if (equal key (car entry)) (setq startline (org-current-line)))
10368 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10369 (car entry) " = " (cdr entry) "\n"))
10370 (remove-text-properties 0 (length s) '(face nil) s)
10371 (insert s))
10372 (if (eq org-table-use-standard-references t)
10373 (org-table-fedit-toggle-ref-type))
10374 (goto-line startline)
10375 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10377 (defun org-table-fedit-post-command ()
10378 (when (not (memq this-command '(lisp-complete-symbol)))
10379 (let ((win (selected-window)))
10380 (save-excursion
10381 (condition-case nil
10382 (org-table-show-reference)
10383 (error nil))
10384 (select-window win)))))
10386 (defun org-table-formula-to-user (s)
10387 "Convert a formula from internal to user representation."
10388 (if (eq org-table-use-standard-references t)
10389 (org-table-convert-refs-to-an s)
10392 (defun org-table-formula-from-user (s)
10393 "Convert a formula from user to internal representation."
10394 (if org-table-use-standard-references
10395 (org-table-convert-refs-to-rc s)
10398 (defun org-table-convert-refs-to-rc (s)
10399 "Convert spreadsheet references from AB7 to @7$28.
10400 Works for single references, but also for entire formulas and even the
10401 full TBLFM line."
10402 (let ((start 0))
10403 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10404 (cond
10405 ((match-end 3)
10406 ;; format match, just advance
10407 (setq start (match-end 0)))
10408 ((and (> (match-beginning 0) 0)
10409 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10410 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10411 ;; 3.e5 or something like this.
10412 (setq start (match-end 0)))
10414 (setq start (match-beginning 0)
10415 s (replace-match
10416 (if (equal (match-string 2 s) "&")
10417 (format "$%d" (org-letters-to-number (match-string 1 s)))
10418 (format "@%d$%d"
10419 (string-to-number (match-string 2 s))
10420 (org-letters-to-number (match-string 1 s))))
10421 t t s)))))
10424 (defun org-table-convert-refs-to-an (s)
10425 "Convert spreadsheet references from to @7$28 to AB7.
10426 Works for single references, but also for entire formulas and even the
10427 full TBLFM line."
10428 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10429 (setq s (replace-match
10430 (format "%s%d"
10431 (org-number-to-letters
10432 (string-to-number (match-string 2 s)))
10433 (string-to-number (match-string 1 s)))
10434 t t s)))
10435 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10436 (setq s (replace-match (concat "\\1"
10437 (org-number-to-letters
10438 (string-to-number (match-string 2 s))) "&")
10439 t nil s)))
10442 (defun org-letters-to-number (s)
10443 "Convert a base 26 number represented by letters into an integer.
10444 For example: AB -> 28."
10445 (let ((n 0))
10446 (setq s (upcase s))
10447 (while (> (length s) 0)
10448 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10449 s (substring s 1)))
10452 (defun org-number-to-letters (n)
10453 "Convert an integer into a base 26 number represented by letters.
10454 For example: 28 -> AB."
10455 (let ((s ""))
10456 (while (> n 0)
10457 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10458 n (/ (1- n) 26)))
10461 (defun org-table-fedit-convert-buffer (function)
10462 "Convert all references in this buffer, using FUNTION."
10463 (let ((line (org-current-line)))
10464 (goto-char (point-min))
10465 (while (not (eobp))
10466 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10467 (delete-region (point) (point-at-eol))
10468 (or (eobp) (forward-char 1)))
10469 (goto-line line)))
10471 (defun org-table-fedit-toggle-ref-type ()
10472 "Convert all references in the buffer from B3 to @3$2 and back."
10473 (interactive)
10474 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10475 (org-table-fedit-convert-buffer
10476 (if org-table-buffer-is-an
10477 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10478 (message "Reference type switched to %s"
10479 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10481 (defun org-table-fedit-ref-up ()
10482 "Shift the reference at point one row/hline up."
10483 (interactive)
10484 (org-table-fedit-shift-reference 'up))
10485 (defun org-table-fedit-ref-down ()
10486 "Shift the reference at point one row/hline down."
10487 (interactive)
10488 (org-table-fedit-shift-reference 'down))
10489 (defun org-table-fedit-ref-left ()
10490 "Shift the reference at point one field to the left."
10491 (interactive)
10492 (org-table-fedit-shift-reference 'left))
10493 (defun org-table-fedit-ref-right ()
10494 "Shift the reference at point one field to the right."
10495 (interactive)
10496 (org-table-fedit-shift-reference 'right))
10498 (defun org-table-fedit-shift-reference (dir)
10499 (cond
10500 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10501 (if (memq dir '(left right))
10502 (org-rematch-and-replace 1 (eq dir 'left))
10503 (error "Cannot shift reference in this direction")))
10504 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10505 ;; A B3-like reference
10506 (if (memq dir '(up down))
10507 (org-rematch-and-replace 2 (eq dir 'up))
10508 (org-rematch-and-replace 1 (eq dir 'left))))
10509 ((org-at-regexp-p
10510 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10511 ;; An internal reference
10512 (if (memq dir '(up down))
10513 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10514 (org-rematch-and-replace 5 (eq dir 'left))))))
10516 (defun org-rematch-and-replace (n &optional decr hline)
10517 "Re-match the group N, and replace it with the shifted refrence."
10518 (or (match-end n) (error "Cannot shift reference in this direction"))
10519 (goto-char (match-beginning n))
10520 (and (looking-at (regexp-quote (match-string n)))
10521 (replace-match (org-shift-refpart (match-string 0) decr hline)
10522 t t)))
10524 (defun org-shift-refpart (ref &optional decr hline)
10525 "Shift a refrence part REF.
10526 If DECR is set, decrease the references row/column, else increase.
10527 If HLINE is set, this may be a hline reference, it certainly is not
10528 a translation reference."
10529 (save-match-data
10530 (let* ((sign (string-match "^[-+]" ref)) n)
10532 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10533 (cond
10534 ((and hline (string-match "^I+" ref))
10535 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10536 (setq n (+ n (if decr -1 1)))
10537 (if (= n 0) (setq n (+ n (if decr -1 1))))
10538 (if sign
10539 (setq sign (if (< n 0) "-" "+") n (abs n))
10540 (setq n (max 1 n)))
10541 (concat sign (make-string n ?I)))
10543 ((string-match "^[0-9]+" ref)
10544 (setq n (string-to-number (concat sign ref)))
10545 (setq n (+ n (if decr -1 1)))
10546 (if sign
10547 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10548 (number-to-string (max 1 n))))
10550 ((string-match "^[a-zA-Z]+" ref)
10551 (org-number-to-letters
10552 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10554 (t (error "Cannot shift reference"))))))
10556 (defun org-table-fedit-toggle-coordinates ()
10557 "Toggle the display of coordinates in the refrenced table."
10558 (interactive)
10559 (let ((pos (marker-position org-pos)))
10560 (with-current-buffer (marker-buffer org-pos)
10561 (save-excursion
10562 (goto-char pos)
10563 (org-table-toggle-coordinate-overlays)))))
10565 (defun org-table-fedit-finish (&optional arg)
10566 "Parse the buffer for formula definitions and install them.
10567 With prefix ARG, apply the new formulas to the table."
10568 (interactive "P")
10569 (org-table-remove-rectangle-highlight)
10570 (if org-table-use-standard-references
10571 (progn
10572 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
10573 (setq org-table-buffer-is-an nil)))
10574 (let ((pos org-pos) eql var form)
10575 (goto-char (point-min))
10576 (while (re-search-forward
10577 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
10578 nil t)
10579 (setq var (if (match-end 2) (match-string 2) (match-string 1))
10580 form (match-string 3))
10581 (setq form (org-trim form))
10582 (when (not (equal form ""))
10583 (while (string-match "[ \t]*\n[ \t]*" form)
10584 (setq form (replace-match " " t t form)))
10585 (when (assoc var eql)
10586 (error "Double formulas for %s" var))
10587 (push (cons var form) eql)))
10588 (setq org-pos nil)
10589 (set-window-configuration org-window-configuration)
10590 (select-window (get-buffer-window (marker-buffer pos)))
10591 (goto-char pos)
10592 (unless (org-at-table-p)
10593 (error "Lost table position - cannot install formulae"))
10594 (org-table-store-formulas eql)
10595 (move-marker pos nil)
10596 (kill-buffer "*Edit Formulas*")
10597 (if arg
10598 (org-table-recalculate 'all)
10599 (message "New formulas installed - press C-u C-c C-c to apply."))))
10601 (defun org-table-fedit-abort ()
10602 "Abort editing formulas, without installing the changes."
10603 (interactive)
10604 (org-table-remove-rectangle-highlight)
10605 (let ((pos org-pos))
10606 (set-window-configuration org-window-configuration)
10607 (select-window (get-buffer-window (marker-buffer pos)))
10608 (goto-char pos)
10609 (move-marker pos nil)
10610 (message "Formula editing aborted without installing changes")))
10612 (defun org-table-fedit-lisp-indent ()
10613 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
10614 (interactive)
10615 (let ((pos (point)) beg end ind)
10616 (beginning-of-line 1)
10617 (cond
10618 ((looking-at "[ \t]")
10619 (goto-char pos)
10620 (call-interactively 'lisp-indent-line))
10621 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
10622 ((not (fboundp 'pp-buffer))
10623 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
10624 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
10625 (goto-char (- (match-end 0) 2))
10626 (setq beg (point))
10627 (setq ind (make-string (current-column) ?\ ))
10628 (condition-case nil (forward-sexp 1)
10629 (error
10630 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
10631 (setq end (point))
10632 (save-restriction
10633 (narrow-to-region beg end)
10634 (if (eq last-command this-command)
10635 (progn
10636 (goto-char (point-min))
10637 (setq this-command nil)
10638 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
10639 (replace-match " ")))
10640 (pp-buffer)
10641 (untabify (point-min) (point-max))
10642 (goto-char (1+ (point-min)))
10643 (while (re-search-forward "^." nil t)
10644 (beginning-of-line 1)
10645 (insert ind))
10646 (goto-char (point-max))
10647 (backward-delete-char 1)))
10648 (goto-char beg))
10649 (t nil))))
10651 (defvar org-show-positions nil)
10653 (defun org-table-show-reference (&optional local)
10654 "Show the location/value of the $ expression at point."
10655 (interactive)
10656 (org-table-remove-rectangle-highlight)
10657 (catch 'exit
10658 (let ((pos (if local (point) org-pos))
10659 (face2 'highlight)
10660 (org-inhibit-highlight-removal t)
10661 (win (selected-window))
10662 (org-show-positions nil)
10663 var name e what match dest)
10664 (if local (org-table-get-specials))
10665 (setq what (cond
10666 ((or (org-at-regexp-p org-table-range-regexp2)
10667 (org-at-regexp-p org-table-translate-regexp)
10668 (org-at-regexp-p org-table-range-regexp))
10669 (setq match
10670 (save-match-data
10671 (org-table-convert-refs-to-rc (match-string 0))))
10672 'range)
10673 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
10674 ((org-at-regexp-p "\\$[0-9]+") 'column)
10675 ((not local) nil)
10676 (t (error "No reference at point")))
10677 match (and what (or match (match-string 0))))
10678 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
10679 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
10680 'secondary-selection))
10681 (org-add-hook 'before-change-functions
10682 'org-table-remove-rectangle-highlight)
10683 (if (eq what 'name) (setq var (substring match 1)))
10684 (when (eq what 'range)
10685 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
10686 (setq match (org-table-formula-substitute-names match)))
10687 (unless local
10688 (save-excursion
10689 (end-of-line 1)
10690 (re-search-backward "^\\S-" nil t)
10691 (beginning-of-line 1)
10692 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
10693 (setq dest
10694 (save-match-data
10695 (org-table-convert-refs-to-rc (match-string 1))))
10696 (org-table-add-rectangle-overlay
10697 (match-beginning 1) (match-end 1) face2))))
10698 (if (and (markerp pos) (marker-buffer pos))
10699 (if (get-buffer-window (marker-buffer pos))
10700 (select-window (get-buffer-window (marker-buffer pos)))
10701 (org-switch-to-buffer-other-window (get-buffer-window
10702 (marker-buffer pos)))))
10703 (goto-char pos)
10704 (org-table-force-dataline)
10705 (when dest
10706 (setq name (substring dest 1))
10707 (cond
10708 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
10709 (setq e (assoc name org-table-named-field-locations))
10710 (goto-line (nth 1 e))
10711 (org-table-goto-column (nth 2 e)))
10712 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
10713 (let ((l (string-to-number (match-string 1 dest)))
10714 (c (string-to-number (match-string 2 dest))))
10715 (goto-line (aref org-table-dlines l))
10716 (org-table-goto-column c)))
10717 (t (org-table-goto-column (string-to-number name))))
10718 (move-marker pos (point))
10719 (org-table-highlight-rectangle nil nil face2))
10720 (cond
10721 ((equal dest match))
10722 ((not match))
10723 ((eq what 'range)
10724 (condition-case nil
10725 (save-excursion
10726 (org-table-get-range match nil nil 'highlight))
10727 (error nil)))
10728 ((setq e (assoc var org-table-named-field-locations))
10729 (goto-line (nth 1 e))
10730 (org-table-goto-column (nth 2 e))
10731 (org-table-highlight-rectangle (point) (point))
10732 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
10733 ((setq e (assoc var org-table-column-names))
10734 (org-table-goto-column (string-to-number (cdr e)))
10735 (org-table-highlight-rectangle (point) (point))
10736 (goto-char (org-table-begin))
10737 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
10738 (org-table-end) t)
10739 (progn
10740 (goto-char (match-beginning 1))
10741 (org-table-highlight-rectangle)
10742 (message "Named column (column %s)" (cdr e)))
10743 (error "Column name not found")))
10744 ((eq what 'column)
10745 ;; column number
10746 (org-table-goto-column (string-to-number (substring match 1)))
10747 (org-table-highlight-rectangle (point) (point))
10748 (message "Column %s" (substring match 1)))
10749 ((setq e (assoc var org-table-local-parameters))
10750 (goto-char (org-table-begin))
10751 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
10752 (progn
10753 (goto-char (match-beginning 1))
10754 (org-table-highlight-rectangle)
10755 (message "Local parameter."))
10756 (error "Parameter not found")))
10758 (cond
10759 ((not var) (error "No reference at point"))
10760 ((setq e (assoc var org-table-formula-constants-local))
10761 (message "Local Constant: $%s=%s in #+CONSTANTS line."
10762 var (cdr e)))
10763 ((setq e (assoc var org-table-formula-constants))
10764 (message "Constant: $%s=%s in `org-table-formula-constants'."
10765 var (cdr e)))
10766 ((setq e (and (fboundp 'constants-get) (constants-get var)))
10767 (message "Constant: $%s=%s, from `constants.el'%s."
10768 var e (format " (%s units)" constants-unit-system)))
10769 (t (error "Undefined name $%s" var)))))
10770 (goto-char pos)
10771 (when (and org-show-positions
10772 (not (memq this-command '(org-table-fedit-scroll
10773 org-table-fedit-scroll-down))))
10774 (push pos org-show-positions)
10775 (push org-table-current-begin-pos org-show-positions)
10776 (let ((min (apply 'min org-show-positions))
10777 (max (apply 'max org-show-positions)))
10778 (goto-char min) (recenter 0)
10779 (goto-char max)
10780 (or (pos-visible-in-window-p max) (recenter -1))))
10781 (select-window win))))
10783 (defun org-table-force-dataline ()
10784 "Make sure the cursor is in a dataline in a table."
10785 (unless (save-excursion
10786 (beginning-of-line 1)
10787 (looking-at org-table-dataline-regexp))
10788 (let* ((re org-table-dataline-regexp)
10789 (p1 (save-excursion (re-search-forward re nil 'move)))
10790 (p2 (save-excursion (re-search-backward re nil 'move))))
10791 (cond ((and p1 p2)
10792 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
10793 p1 p2)))
10794 ((or p1 p2) (goto-char (or p1 p2)))
10795 (t (error "No table dataline around here"))))))
10797 (defun org-table-fedit-line-up ()
10798 "Move cursor one line up in the window showing the table."
10799 (interactive)
10800 (org-table-fedit-move 'previous-line))
10802 (defun org-table-fedit-line-down ()
10803 "Move cursor one line down in the window showing the table."
10804 (interactive)
10805 (org-table-fedit-move 'next-line))
10807 (defun org-table-fedit-move (command)
10808 "Move the cursor in the window shoinw the table.
10809 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
10810 (let ((org-table-allow-automatic-line-recalculation nil)
10811 (pos org-pos) (win (selected-window)) p)
10812 (select-window (get-buffer-window (marker-buffer org-pos)))
10813 (setq p (point))
10814 (call-interactively command)
10815 (while (and (org-at-table-p)
10816 (org-at-table-hline-p))
10817 (call-interactively command))
10818 (or (org-at-table-p) (goto-char p))
10819 (move-marker pos (point))
10820 (select-window win)))
10822 (defun org-table-fedit-scroll (N)
10823 (interactive "p")
10824 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
10825 (scroll-other-window N)))
10827 (defun org-table-fedit-scroll-down (N)
10828 (interactive "p")
10829 (org-table-fedit-scroll (- N)))
10831 (defvar org-table-rectangle-overlays nil)
10833 (defun org-table-add-rectangle-overlay (beg end &optional face)
10834 "Add a new overlay."
10835 (let ((ov (org-make-overlay beg end)))
10836 (org-overlay-put ov 'face (or face 'secondary-selection))
10837 (push ov org-table-rectangle-overlays)))
10839 (defun org-table-highlight-rectangle (&optional beg end face)
10840 "Highlight rectangular region in a table."
10841 (setq beg (or beg (point)) end (or end (point)))
10842 (let ((b (min beg end))
10843 (e (max beg end))
10844 l1 c1 l2 c2 tmp)
10845 (and (boundp 'org-show-positions)
10846 (setq org-show-positions (cons b (cons e org-show-positions))))
10847 (goto-char (min beg end))
10848 (setq l1 (org-current-line)
10849 c1 (org-table-current-column))
10850 (goto-char (max beg end))
10851 (setq l2 (org-current-line)
10852 c2 (org-table-current-column))
10853 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
10854 (goto-line l1)
10855 (beginning-of-line 1)
10856 (loop for line from l1 to l2 do
10857 (when (looking-at org-table-dataline-regexp)
10858 (org-table-goto-column c1)
10859 (skip-chars-backward "^|\n") (setq beg (point))
10860 (org-table-goto-column c2)
10861 (skip-chars-forward "^|\n") (setq end (point))
10862 (org-table-add-rectangle-overlay beg end face))
10863 (beginning-of-line 2))
10864 (goto-char b))
10865 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
10867 (defun org-table-remove-rectangle-highlight (&rest ignore)
10868 "Remove the rectangle overlays."
10869 (unless org-inhibit-highlight-removal
10870 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
10871 (mapc 'org-delete-overlay org-table-rectangle-overlays)
10872 (setq org-table-rectangle-overlays nil)))
10874 (defvar org-table-coordinate-overlays nil
10875 "Collects the cooordinate grid overlays, so that they can be removed.")
10876 (make-variable-buffer-local 'org-table-coordinate-overlays)
10878 (defun org-table-overlay-coordinates ()
10879 "Add overlays to the table at point, to show row/column coordinates."
10880 (interactive)
10881 (mapc 'org-delete-overlay org-table-coordinate-overlays)
10882 (setq org-table-coordinate-overlays nil)
10883 (save-excursion
10884 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
10885 (goto-char (org-table-begin))
10886 (while (org-at-table-p)
10887 (setq eol (point-at-eol))
10888 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
10889 (push ov org-table-coordinate-overlays)
10890 (setq hline (looking-at org-table-hline-regexp))
10891 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
10892 (format "%4d" (setq id (1+ id)))))
10893 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
10894 (when hline
10895 (setq ic 0)
10896 (while (re-search-forward "[+|]\\(-+\\)" eol t)
10897 (setq beg (1+ (match-beginning 0))
10898 ic (1+ ic)
10899 s1 (concat "$" (int-to-string ic))
10900 s2 (org-number-to-letters ic)
10901 str (if (eq org-table-use-standard-references t) s2 s1))
10902 (setq ov (org-make-overlay beg (+ beg (length str))))
10903 (push ov org-table-coordinate-overlays)
10904 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
10905 (beginning-of-line 2)))))
10907 (defun org-table-toggle-coordinate-overlays ()
10908 "Toggle the display of Row/Column numbers in tables."
10909 (interactive)
10910 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
10911 (message "Row/Column number display turned %s"
10912 (if org-table-overlay-coordinates "on" "off"))
10913 (if (and (org-at-table-p) org-table-overlay-coordinates)
10914 (org-table-align))
10915 (unless org-table-overlay-coordinates
10916 (mapc 'org-delete-overlay org-table-coordinate-overlays)
10917 (setq org-table-coordinate-overlays nil)))
10919 (defun org-table-toggle-formula-debugger ()
10920 "Toggle the formula debugger in tables."
10921 (interactive)
10922 (setq org-table-formula-debug (not org-table-formula-debug))
10923 (message "Formula debugging has been turned %s"
10924 (if org-table-formula-debug "on" "off")))
10926 ;;; The orgtbl minor mode
10928 ;; Define a minor mode which can be used in other modes in order to
10929 ;; integrate the org-mode table editor.
10931 ;; This is really a hack, because the org-mode table editor uses several
10932 ;; keys which normally belong to the major mode, for example the TAB and
10933 ;; RET keys. Here is how it works: The minor mode defines all the keys
10934 ;; necessary to operate the table editor, but wraps the commands into a
10935 ;; function which tests if the cursor is currently inside a table. If that
10936 ;; is the case, the table editor command is executed. However, when any of
10937 ;; those keys is used outside a table, the function uses `key-binding' to
10938 ;; look up if the key has an associated command in another currently active
10939 ;; keymap (minor modes, major mode, global), and executes that command.
10940 ;; There might be problems if any of the keys used by the table editor is
10941 ;; otherwise used as a prefix key.
10943 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
10944 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
10945 ;; addresses this by checking explicitly for both bindings.
10947 ;; The optimized version (see variable `orgtbl-optimized') takes over
10948 ;; all keys which are bound to `self-insert-command' in the *global map*.
10949 ;; Some modes bind other commands to simple characters, for example
10950 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
10951 ;; active, this binding is ignored inside tables and replaced with a
10952 ;; modified self-insert.
10954 (defvar orgtbl-mode nil
10955 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
10956 table editor in arbitrary modes.")
10957 (make-variable-buffer-local 'orgtbl-mode)
10959 (defvar orgtbl-mode-map (make-keymap)
10960 "Keymap for `orgtbl-mode'.")
10962 ;;;###autoload
10963 (defun turn-on-orgtbl ()
10964 "Unconditionally turn on `orgtbl-mode'."
10965 (orgtbl-mode 1))
10967 (defvar org-old-auto-fill-inhibit-regexp nil
10968 "Local variable used by `orgtbl-mode'")
10970 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
10971 "Matches a line belonging to an orgtbl.")
10973 (defconst orgtbl-extra-font-lock-keywords
10974 (list (list (concat "^" orgtbl-line-start-regexp ".*")
10975 0 (quote 'org-table) 'prepend))
10976 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
10978 ;;;###autoload
10979 (defun orgtbl-mode (&optional arg)
10980 "The `org-mode' table editor as a minor mode for use in other modes."
10981 (interactive)
10982 (if (org-mode-p)
10983 ;; Exit without error, in case some hook functions calls this
10984 ;; by accident in org-mode.
10985 (message "Orgtbl-mode is not useful in org-mode, command ignored")
10986 (setq orgtbl-mode
10987 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
10988 (if orgtbl-mode
10989 (progn
10990 (and (orgtbl-setup) (defun orgtbl-setup () nil))
10991 ;; Make sure we are first in minor-mode-map-alist
10992 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
10993 (and c (setq minor-mode-map-alist
10994 (cons c (delq c minor-mode-map-alist)))))
10995 (org-set-local (quote org-table-may-need-update) t)
10996 (org-add-hook 'before-change-functions 'org-before-change-function
10997 nil 'local)
10998 (org-set-local 'org-old-auto-fill-inhibit-regexp
10999 auto-fill-inhibit-regexp)
11000 (org-set-local 'auto-fill-inhibit-regexp
11001 (if auto-fill-inhibit-regexp
11002 (concat orgtbl-line-start-regexp "\\|"
11003 auto-fill-inhibit-regexp)
11004 orgtbl-line-start-regexp))
11005 (org-add-to-invisibility-spec '(org-cwidth))
11006 (when (fboundp 'font-lock-add-keywords)
11007 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11008 (org-restart-font-lock))
11009 (easy-menu-add orgtbl-mode-menu)
11010 (run-hooks 'orgtbl-mode-hook))
11011 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11012 (org-cleanup-narrow-column-properties)
11013 (org-remove-from-invisibility-spec '(org-cwidth))
11014 (remove-hook 'before-change-functions 'org-before-change-function t)
11015 (when (fboundp 'font-lock-remove-keywords)
11016 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11017 (org-restart-font-lock))
11018 (easy-menu-remove orgtbl-mode-menu)
11019 (force-mode-line-update 'all))))
11021 (defun org-cleanup-narrow-column-properties ()
11022 "Remove all properties related to narrow-column invisibility."
11023 (let ((s 1))
11024 (while (setq s (text-property-any s (point-max)
11025 'display org-narrow-column-arrow))
11026 (remove-text-properties s (1+ s) '(display t)))
11027 (setq s 1)
11028 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11029 (remove-text-properties s (1+ s) '(org-cwidth t)))
11030 (setq s 1)
11031 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11032 (remove-text-properties s (1+ s) '(invisible t)))))
11034 ;; Install it as a minor mode.
11035 (put 'orgtbl-mode :included t)
11036 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11037 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11039 (defun orgtbl-make-binding (fun n &rest keys)
11040 "Create a function for binding in the table minor mode.
11041 FUN is the command to call inside a table. N is used to create a unique
11042 command name. KEYS are keys that should be checked in for a command
11043 to execute outside of tables."
11044 (eval
11045 (list 'defun
11046 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11047 '(arg)
11048 (concat "In tables, run `" (symbol-name fun) "'.\n"
11049 "Outside of tables, run the binding of `"
11050 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11051 "'.")
11052 '(interactive "p")
11053 (list 'if
11054 '(org-at-table-p)
11055 (list 'call-interactively (list 'quote fun))
11056 (list 'let '(orgtbl-mode)
11057 (list 'call-interactively
11058 (append '(or)
11059 (mapcar (lambda (k)
11060 (list 'key-binding k))
11061 keys)
11062 '('orgtbl-error))))))))
11064 (defun orgtbl-error ()
11065 "Error when there is no default binding for a table key."
11066 (interactive)
11067 (error "This key is has no function outside tables"))
11069 (defun orgtbl-setup ()
11070 "Setup orgtbl keymaps."
11071 (let ((nfunc 0)
11072 (bindings
11073 (list
11074 '([(meta shift left)] org-table-delete-column)
11075 '([(meta left)] org-table-move-column-left)
11076 '([(meta right)] org-table-move-column-right)
11077 '([(meta shift right)] org-table-insert-column)
11078 '([(meta shift up)] org-table-kill-row)
11079 '([(meta shift down)] org-table-insert-row)
11080 '([(meta up)] org-table-move-row-up)
11081 '([(meta down)] org-table-move-row-down)
11082 '("\C-c\C-w" org-table-cut-region)
11083 '("\C-c\M-w" org-table-copy-region)
11084 '("\C-c\C-y" org-table-paste-rectangle)
11085 '("\C-c-" org-table-insert-hline)
11086 '("\C-c}" org-table-toggle-coordinate-overlays)
11087 '("\C-c{" org-table-toggle-formula-debugger)
11088 '("\C-m" org-table-next-row)
11089 '([(shift return)] org-table-copy-down)
11090 '("\C-c\C-q" org-table-wrap-region)
11091 '("\C-c?" org-table-field-info)
11092 '("\C-c " org-table-blank-field)
11093 '("\C-c+" org-table-sum)
11094 '("\C-c=" org-table-eval-formula)
11095 '("\C-c'" org-table-edit-formulas)
11096 '("\C-c`" org-table-edit-field)
11097 '("\C-c*" org-table-recalculate)
11098 '("\C-c|" org-table-create-or-convert-from-region)
11099 '("\C-c^" org-table-sort-lines)
11100 '([(control ?#)] org-table-rotate-recalc-marks)))
11101 elt key fun cmd)
11102 (while (setq elt (pop bindings))
11103 (setq nfunc (1+ nfunc))
11104 (setq key (org-key (car elt))
11105 fun (nth 1 elt)
11106 cmd (orgtbl-make-binding fun nfunc key))
11107 (org-defkey orgtbl-mode-map key cmd))
11109 ;; Special treatment needed for TAB and RET
11110 (org-defkey orgtbl-mode-map [(return)]
11111 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11112 (org-defkey orgtbl-mode-map "\C-m"
11113 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11115 (org-defkey orgtbl-mode-map [(tab)]
11116 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11117 (org-defkey orgtbl-mode-map "\C-i"
11118 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11120 (org-defkey orgtbl-mode-map [(shift tab)]
11121 (orgtbl-make-binding 'org-table-previous-field 104
11122 [(shift tab)] [(tab)] "\C-i"))
11124 (org-defkey orgtbl-mode-map "\M-\C-m"
11125 (orgtbl-make-binding 'org-table-wrap-region 105
11126 "\M-\C-m" [(meta return)]))
11127 (org-defkey orgtbl-mode-map [(meta return)]
11128 (orgtbl-make-binding 'org-table-wrap-region 106
11129 [(meta return)] "\M-\C-m"))
11131 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11132 (when orgtbl-optimized
11133 ;; If the user wants maximum table support, we need to hijack
11134 ;; some standard editing functions
11135 (org-remap orgtbl-mode-map
11136 'self-insert-command 'orgtbl-self-insert-command
11137 'delete-char 'org-delete-char
11138 'delete-backward-char 'org-delete-backward-char)
11139 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11140 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11141 '("OrgTbl"
11142 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11143 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11144 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11145 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11146 "--"
11147 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11148 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11149 ["Copy Field from Above"
11150 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11151 "--"
11152 ("Column"
11153 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11154 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11155 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11156 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11157 ("Row"
11158 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11159 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11160 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11161 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11162 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
11163 "--"
11164 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11165 ("Rectangle"
11166 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11167 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11168 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11169 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11170 "--"
11171 ("Radio tables"
11172 ["Insert table template" orgtbl-insert-radio-table
11173 (assq major-mode orgtbl-radio-table-templates)]
11174 ["Comment/uncomment table" orgtbl-toggle-comment t])
11175 "--"
11176 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11177 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11178 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11179 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11180 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11181 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11182 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11183 ["Sum Column/Rectangle" org-table-sum
11184 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11185 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11186 ["Debug Formulas"
11187 org-table-toggle-formula-debugger :active (org-at-table-p)
11188 :keys "C-c {"
11189 :style toggle :selected org-table-formula-debug]
11190 ["Show Col/Row Numbers"
11191 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11192 :keys "C-c }"
11193 :style toggle :selected org-table-overlay-coordinates]
11197 (defun orgtbl-ctrl-c-ctrl-c (arg)
11198 "If the cursor is inside a table, realign the table.
11199 It it is a table to be sent away to a receiver, do it.
11200 With prefix arg, also recompute table."
11201 (interactive "P")
11202 (let ((pos (point)) action)
11203 (save-excursion
11204 (beginning-of-line 1)
11205 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11206 ((looking-at "[ \t]*|") pos)
11207 ((looking-at "#\\+TBLFM:") 'recalc))))
11208 (cond
11209 ((integerp action)
11210 (goto-char action)
11211 (org-table-maybe-eval-formula)
11212 (if arg
11213 (call-interactively 'org-table-recalculate)
11214 (org-table-maybe-recalculate-line))
11215 (call-interactively 'org-table-align)
11216 (orgtbl-send-table 'maybe))
11217 ((eq action 'recalc)
11218 (save-excursion
11219 (beginning-of-line 1)
11220 (skip-chars-backward " \r\n\t")
11221 (if (org-at-table-p)
11222 (org-call-with-arg 'org-table-recalculate t))))
11223 (t (let (orgtbl-mode)
11224 (call-interactively (key-binding "\C-c\C-c")))))))
11226 (defun orgtbl-tab (arg)
11227 "Justification and field motion for `orgtbl-mode'."
11228 (interactive "P")
11229 (if arg (org-table-edit-field t)
11230 (org-table-justify-field-maybe)
11231 (org-table-next-field)))
11233 (defun orgtbl-ret ()
11234 "Justification and field motion for `orgtbl-mode'."
11235 (interactive)
11236 (org-table-justify-field-maybe)
11237 (org-table-next-row))
11239 (defun orgtbl-self-insert-command (N)
11240 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11241 If the cursor is in a table looking at whitespace, the whitespace is
11242 overwritten, and the table is not marked as requiring realignment."
11243 (interactive "p")
11244 (if (and (org-at-table-p)
11246 (and org-table-auto-blank-field
11247 (member last-command
11248 '(orgtbl-hijacker-command-100
11249 orgtbl-hijacker-command-101
11250 orgtbl-hijacker-command-102
11251 orgtbl-hijacker-command-103
11252 orgtbl-hijacker-command-104
11253 orgtbl-hijacker-command-105))
11254 (org-table-blank-field))
11256 (eq N 1)
11257 (looking-at "[^|\n]* +|"))
11258 (let (org-table-may-need-update)
11259 (goto-char (1- (match-end 0)))
11260 (delete-backward-char 1)
11261 (goto-char (match-beginning 0))
11262 (self-insert-command N))
11263 (setq org-table-may-need-update t)
11264 (let (orgtbl-mode)
11265 (call-interactively (key-binding (vector last-input-event))))))
11267 (defun org-force-self-insert (N)
11268 "Needed to enforce self-insert under remapping."
11269 (interactive "p")
11270 (self-insert-command N))
11272 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11273 "Regula expression matching exponentials as produced by calc.")
11275 (defvar org-table-clean-did-remove-column nil)
11277 (defun orgtbl-export (table target)
11278 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11279 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11280 org-table-last-alignment org-table-last-column-widths
11281 maxcol column)
11282 (if (not (fboundp func))
11283 (error "Cannot export orgtbl table to %s" target))
11284 (setq lines (org-table-clean-before-export lines))
11285 (setq table
11286 (mapcar
11287 (lambda (x)
11288 (if (string-match org-table-hline-regexp x)
11289 'hline
11290 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11291 lines))
11292 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11293 table)))
11294 (loop for i from (1- maxcol) downto 0 do
11295 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11296 (setq column (delq nil column))
11297 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11298 (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))
11299 (funcall func table nil)))
11301 (defun orgtbl-send-table (&optional maybe)
11302 "Send a tranformed version of this table to the receiver position.
11303 With argument MAYBE, fail quietly if no transformation is defined for
11304 this table."
11305 (interactive)
11306 (catch 'exit
11307 (unless (org-at-table-p) (error "Not at a table"))
11308 ;; when non-interactive, we assume align has just happened.
11309 (when (interactive-p) (org-table-align))
11310 (save-excursion
11311 (goto-char (org-table-begin))
11312 (beginning-of-line 0)
11313 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11314 (if maybe
11315 (throw 'exit nil)
11316 (error "Don't know how to transform this table."))))
11317 (let* ((name (match-string 1))
11319 (transform (intern (match-string 2)))
11320 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11321 (skip (plist-get params :skip))
11322 (skipcols (plist-get params :skipcols))
11323 (txt (buffer-substring-no-properties
11324 (org-table-begin) (org-table-end)))
11325 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11326 (lines (org-table-clean-before-export lines))
11327 (i0 (if org-table-clean-did-remove-column 2 1))
11328 (table (mapcar
11329 (lambda (x)
11330 (if (string-match org-table-hline-regexp x)
11331 'hline
11332 (org-remove-by-index
11333 (org-split-string (org-trim x) "\\s-*|\\s-*")
11334 skipcols i0)))
11335 lines))
11336 (fun (if (= i0 2) 'cdr 'identity))
11337 (org-table-last-alignment
11338 (org-remove-by-index (funcall fun org-table-last-alignment)
11339 skipcols i0))
11340 (org-table-last-column-widths
11341 (org-remove-by-index (funcall fun org-table-last-column-widths)
11342 skipcols i0)))
11344 (unless (fboundp transform)
11345 (error "No such transformation function %s" transform))
11346 (setq txt (funcall transform table params))
11347 ;; Find the insertion place
11348 (save-excursion
11349 (goto-char (point-min))
11350 (unless (re-search-forward
11351 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11352 (error "Don't know where to insert translated table"))
11353 (goto-char (match-beginning 0))
11354 (beginning-of-line 2)
11355 (setq beg (point))
11356 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11357 (error "Cannot find end of insertion region"))
11358 (beginning-of-line 1)
11359 (delete-region beg (point))
11360 (goto-char beg)
11361 (insert txt "\n"))
11362 (message "Table converted and installed at receiver location"))))
11364 (defun org-remove-by-index (list indices &optional i0)
11365 "Remove the elements in LIST with indices in INDICES.
11366 First element has index 0, or I0 if given."
11367 (if (not indices)
11368 list
11369 (if (integerp indices) (setq indices (list indices)))
11370 (setq i0 (1- (or i0 0)))
11371 (delq :rm (mapcar (lambda (x)
11372 (setq i0 (1+ i0))
11373 (if (memq i0 indices) :rm x))
11374 list))))
11376 (defun orgtbl-toggle-comment ()
11377 "Comment or uncomment the orgtbl at point."
11378 (interactive)
11379 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11380 (re2 (concat "^" orgtbl-line-start-regexp))
11381 (commented (save-excursion (beginning-of-line 1)
11382 (cond ((looking-at re1) t)
11383 ((looking-at re2) nil)
11384 (t (error "Not at an org table")))))
11385 (re (if commented re1 re2))
11386 beg end)
11387 (save-excursion
11388 (beginning-of-line 1)
11389 (while (looking-at re) (beginning-of-line 0))
11390 (beginning-of-line 2)
11391 (setq beg (point))
11392 (while (looking-at re) (beginning-of-line 2))
11393 (setq end (point)))
11394 (comment-region beg end (if commented '(4) nil))))
11396 (defun orgtbl-insert-radio-table ()
11397 "Insert a radio table template appropriate for this major mode."
11398 (interactive)
11399 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11400 (txt (nth 1 e))
11401 name pos)
11402 (unless e (error "No radio table setup defined for %s" major-mode))
11403 (setq name (read-string "Table name: "))
11404 (while (string-match "%n" txt)
11405 (setq txt (replace-match name t t txt)))
11406 (or (bolp) (insert "\n"))
11407 (setq pos (point))
11408 (insert txt)
11409 (goto-char pos)))
11411 (defun org-get-param (params header i sym &optional hsym)
11412 "Get parameter value for symbol SYM.
11413 If this is a header line, actually get the value for the symbol with an
11414 additional \"h\" inserted after the colon.
11415 If the value is a protperty list, get the element for the current column.
11416 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11417 (let ((val (plist-get params sym)))
11418 (and hsym header (setq val (or (plist-get params hsym) val)))
11419 (if (consp val) (plist-get val i) val)))
11421 (defun orgtbl-to-generic (table params)
11422 "Convert the orgtbl-mode TABLE to some other format.
11423 This generic routine can be used for many standard cases.
11424 TABLE is a list, each entry either the symbol `hline' for a horizontal
11425 separator line, or a list of fields for that line.
11426 PARAMS is a property list of parameters that can influence the conversion.
11427 For the generic converter, some parameters are obligatory: You need to
11428 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11429 :splice, you must have :tstart and :tend.
11431 Valid parameters are
11433 :tstart String to start the table. Ignored when :splice is t.
11434 :tend String to end the table. Ignored when :splice is t.
11436 :splice When set to t, return only table body lines, don't wrap
11437 them into :tstart and :tend. Default is nil.
11439 :hline String to be inserted on horizontal separation lines.
11440 May be nil to ignore hlines.
11442 :lstart String to start a new table line.
11443 :lend String to end a table line
11444 :sep Separator between two fields
11445 :lfmt Format for entire line, with enough %s to capture all fields.
11446 If this is present, :lstart, :lend, and :sep are ignored.
11447 :fmt A format to be used to wrap the field, should contain
11448 %s for the original field value. For example, to wrap
11449 everything in dollars, you could use :fmt \"$%s$\".
11450 This may also be a property list with column numbers and
11451 formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11453 :hlstart :hlend :hlsep :hlfmt :hfmt
11454 Same as above, specific for the header lines in the table.
11455 All lines before the first hline are treated as header.
11456 If any of these is not present, the data line value is used.
11458 :efmt Use this format to print numbers with exponentials.
11459 The format should have %s twice for inserting mantissa
11460 and exponent, for example \"%s\\\\times10^{%s}\". This
11461 may also be a property list with column numbers and
11462 formats. :fmt will still be applied after :efmt.
11464 In addition to this, the parameters :skip and :skipcols are always handled
11465 directly by `orgtbl-send-table'. See manual."
11466 (interactive)
11467 (let* ((p params)
11468 (splicep (plist-get p :splice))
11469 (hline (plist-get p :hline))
11470 rtn line i fm efm lfmt h)
11472 ;; Do we have a header?
11473 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11474 (setq h t))
11476 ;; Put header
11477 (unless splicep
11478 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11480 ;; Now loop over all lines
11481 (while (setq line (pop table))
11482 (if (eq line 'hline)
11483 ;; A horizontal separator line
11484 (progn (if hline (push hline rtn))
11485 (setq h nil)) ; no longer in header
11486 ;; A normal line. Convert the fields, push line onto the result list
11487 (setq i 0)
11488 (setq line
11489 (mapcar
11490 (lambda (f)
11491 (setq i (1+ i)
11492 fm (org-get-param p h i :fmt :hfmt)
11493 efm (org-get-param p h i :efmt))
11494 (if (and efm (string-match orgtbl-exp-regexp f))
11495 (setq f (format
11496 efm (match-string 1 f) (match-string 2 f))))
11497 (if fm (setq f (format fm f)))
11499 line))
11500 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11501 (push (apply 'format lfmt line) rtn)
11502 (push (concat
11503 (org-get-param p h i :lstart :hlstart)
11504 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11505 (org-get-param p h i :lend :hlend))
11506 rtn))))
11508 (unless splicep
11509 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11511 (mapconcat 'identity (nreverse rtn) "\n")))
11513 (defun orgtbl-to-latex (table params)
11514 "Convert the orgtbl-mode TABLE to LaTeX.
11515 TABLE is a list, each entry either the symbol `hline' for a horizontal
11516 separator line, or a list of fields for that line.
11517 PARAMS is a property list of parameters that can influence the conversion.
11518 Supports all parameters from `orgtbl-to-generic'. Most important for
11519 LaTeX are:
11521 :splice When set to t, return only table body lines, don't wrap
11522 them into a tabular environment. Default is nil.
11524 :fmt A format to be used to wrap the field, should contain %s for the
11525 original field value. For example, to wrap everything in dollars,
11526 use :fmt \"$%s$\". This may also be a property list with column
11527 numbers and formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11529 :efmt Format for transforming numbers with exponentials. The format
11530 should have %s twice for inserting mantissa and exponent, for
11531 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11532 This may also be a property list with column numbers and formats.
11534 The general parameters :skip and :skipcols have already been applied when
11535 this function is called."
11536 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11537 org-table-last-alignment ""))
11538 (params2
11539 (list
11540 :tstart (concat "\\begin{tabular}{" alignment "}")
11541 :tend "\\end{tabular}"
11542 :lstart "" :lend " \\\\" :sep " & "
11543 :efmt "%s\\,(%s)" :hline "\\hline")))
11544 (orgtbl-to-generic table (org-combine-plists params2 params))))
11546 (defun orgtbl-to-html (table params)
11547 "Convert the orgtbl-mode TABLE to LaTeX.
11548 TABLE is a list, each entry either the symbol `hline' for a horizontal
11549 separator line, or a list of fields for that line.
11550 PARAMS is a property list of parameters that can influence the conversion.
11551 Currently this function recognizes the following parameters:
11553 :splice When set to t, return only table body lines, don't wrap
11554 them into a <table> environment. Default is nil.
11556 The general parameters :skip and :skipcols have already been applied when
11557 this function is called. The function does *not* use `orgtbl-to-generic',
11558 so you cannot specify parameters for it."
11559 (let* ((splicep (plist-get params :splice))
11560 html)
11561 ;; Just call the formatter we already have
11562 ;; We need to make text lines for it, so put the fields back together.
11563 (setq html (org-format-org-table-html
11564 (mapcar
11565 (lambda (x)
11566 (if (eq x 'hline)
11567 "|----+----|"
11568 (concat "| " (mapconcat 'identity x " | ") " |")))
11569 table)
11570 splicep))
11571 (if (string-match "\n+\\'" html)
11572 (setq html (replace-match "" t t html)))
11573 html))
11575 (defun orgtbl-to-texinfo (table params)
11576 "Convert the orgtbl-mode TABLE to TeXInfo.
11577 TABLE is a list, each entry either the symbol `hline' for a horizontal
11578 separator line, or a list of fields for that line.
11579 PARAMS is a property list of parameters that can influence the conversion.
11580 Supports all parameters from `orgtbl-to-generic'. Most important for
11581 TeXInfo are:
11583 :splice nil/t When set to t, return only table body lines, don't wrap
11584 them into a multitable environment. Default is nil.
11586 :fmt fmt A format to be used to wrap the field, should contain
11587 %s for the original field value. For example, to wrap
11588 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
11589 This may also be a property list with column numbers and
11590 formats. for example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
11592 :cf \"f1 f2..\" The column fractions for the table. Bye default these
11593 are computed automatically from the width of the columns
11594 under org-mode.
11596 The general parameters :skip and :skipcols have already been applied when
11597 this function is called."
11598 (let* ((total (float (apply '+ org-table-last-column-widths)))
11599 (colfrac (or (plist-get params :cf)
11600 (mapconcat
11601 (lambda (x) (format "%.3f" (/ (float x) total)))
11602 org-table-last-column-widths " ")))
11603 (params2
11604 (list
11605 :tstart (concat "@multitable @columnfractions " colfrac)
11606 :tend "@end multitable"
11607 :lstart "@item " :lend "" :sep " @tab "
11608 :hlstart "@headitem ")))
11609 (orgtbl-to-generic table (org-combine-plists params2 params))))
11611 ;;;; Link Stuff
11613 ;;; Link abbreviations
11615 (defun org-link-expand-abbrev (link)
11616 "Apply replacements as defined in `org-link-abbrev-alist."
11617 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
11618 (let* ((key (match-string 1 link))
11619 (as (or (assoc key org-link-abbrev-alist-local)
11620 (assoc key org-link-abbrev-alist)))
11621 (tag (and (match-end 2) (match-string 3 link)))
11622 rpl)
11623 (if (not as)
11624 link
11625 (setq rpl (cdr as))
11626 (cond
11627 ((symbolp rpl) (funcall rpl tag))
11628 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
11629 (t (concat rpl tag)))))
11630 link))
11632 ;;; Storing and inserting links
11634 (defvar org-insert-link-history nil
11635 "Minibuffer history for links inserted with `org-insert-link'.")
11637 (defvar org-stored-links nil
11638 "Contains the links stored with `org-store-link'.")
11640 (defvar org-store-link-plist nil
11641 "Plist with info about the most recently link created with `org-store-link'.")
11643 (defvar org-link-protocols nil
11644 "Link protocols added to Org-mode using `org-add-link-type'.")
11646 (defvar org-store-link-functions nil
11647 "List of functions that are called to create and store a link.
11648 Each function will be called in turn until one returns a non-nil
11649 value. Each function should check if it is responsible for creating
11650 this link (for example by looking at the major mode).
11651 If not, it must exit and return nil.
11652 If yes, it should return a non-nil value after a calling
11653 `org-store-link-props' with a list of properties and values.
11654 Special properties are:
11656 :type The link prefix. like \"http\". This must be given.
11657 :link The link, like \"http://www.astro.uva.nl/~dominik\".
11658 This is obligatory as well.
11659 :description Optional default description for the second pair
11660 of brackets in an Org-mode link. The user can still change
11661 this when inserting this link into an Org-mode buffer.
11663 In addition to these, any additional properties can be specified
11664 and then used in remember templates.")
11666 (defun org-add-link-type (type &optional follow publish)
11667 "Add TYPE to the list of `org-link-types'.
11668 Re-compute all regular expressions depending on `org-link-types'
11669 FOLLOW and PUBLISH are two functions. Both take the link path as
11670 an argument.
11671 FOLLOW should do whatever is necessary to follow the link, for example
11672 to find a file or display a mail message.
11674 PUBLISH takes the path and retuns the string that should be used when
11675 this document is published. FIMXE: This is actually not yet implemented."
11676 (add-to-list 'org-link-types type t)
11677 (org-make-link-regexps)
11678 (add-to-list 'org-link-protocols
11679 (list type follow publish)))
11681 (defun org-add-agenda-custom-command (entry)
11682 "Replace or add a command in `org-agenda-custom-commands'.
11683 This is mostly for hacking and trying a new command - once the command
11684 works you probably want to add it to `org-agenda-custom-commands' for good."
11685 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
11686 (if ass
11687 (setcdr ass (cdr entry))
11688 (push entry org-agenda-custom-commands))))
11690 ;;;###autoload
11691 (defun org-store-link (arg)
11692 "\\<org-mode-map>Store an org-link to the current location.
11693 This link can later be inserted into an org-buffer with
11694 \\[org-insert-link].
11695 For some link types, a prefix arg is interpreted:
11696 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
11697 For file links, arg negates `org-context-in-file-links'."
11698 (interactive "P")
11699 (setq org-store-link-plist nil) ; reset
11700 (let (link cpltxt desc description search txt)
11701 (cond
11703 ((run-hook-with-args-until-success 'org-store-link-functions)
11704 (setq link (plist-get org-store-link-plist :link)
11705 desc (or (plist-get org-store-link-plist :description) link)))
11707 ((eq major-mode 'bbdb-mode)
11708 (let ((name (bbdb-record-name (bbdb-current-record)))
11709 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
11710 (setq cpltxt (concat "bbdb:" (or name company))
11711 link (org-make-link cpltxt))
11712 (org-store-link-props :type "bbdb" :name name :company company)))
11714 ((eq major-mode 'Info-mode)
11715 (setq link (org-make-link "info:"
11716 (file-name-nondirectory Info-current-file)
11717 ":" Info-current-node))
11718 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
11719 ":" Info-current-node))
11720 (org-store-link-props :type "info" :file Info-current-file
11721 :node Info-current-node))
11723 ((eq major-mode 'calendar-mode)
11724 (let ((cd (calendar-cursor-to-date)))
11725 (setq link
11726 (format-time-string
11727 (car org-time-stamp-formats)
11728 (apply 'encode-time
11729 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
11730 nil nil nil))))
11731 (org-store-link-props :type "calendar" :date cd)))
11733 ((or (eq major-mode 'vm-summary-mode)
11734 (eq major-mode 'vm-presentation-mode))
11735 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
11736 (vm-follow-summary-cursor)
11737 (save-excursion
11738 (vm-select-folder-buffer)
11739 (let* ((message (car vm-message-pointer))
11740 (folder buffer-file-name)
11741 (subject (vm-su-subject message))
11742 (to (vm-get-header-contents message "To"))
11743 (from (vm-get-header-contents message "From"))
11744 (message-id (vm-su-message-id message)))
11745 (org-store-link-props :type "vm" :from from :to to :subject subject
11746 :message-id message-id)
11747 (setq message-id (org-remove-angle-brackets message-id))
11748 (setq folder (abbreviate-file-name folder))
11749 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
11750 folder)
11751 (setq folder (replace-match "" t t folder)))
11752 (setq cpltxt (org-email-link-description))
11753 (setq link (org-make-link "vm:" folder "#" message-id)))))
11755 ((eq major-mode 'wl-summary-mode)
11756 (let* ((msgnum (wl-summary-message-number))
11757 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
11758 msgnum 'message-id))
11759 (wl-message-entity
11760 (if (fboundp 'elmo-message-entity)
11761 (elmo-message-entity
11762 wl-summary-buffer-elmo-folder msgnum)
11763 (elmo-msgdb-overview-get-entity
11764 msgnum (wl-summary-buffer-msgdb))))
11765 (from (wl-summary-line-from))
11766 (to (elmo-message-entity-field wl-message-entity 'to))
11767 (subject (let (wl-thr-indent-string wl-parent-message-entity)
11768 (wl-summary-line-subject))))
11769 (org-store-link-props :type "wl" :from from :to to
11770 :subject subject :message-id message-id)
11771 (setq message-id (org-remove-angle-brackets message-id))
11772 (setq cpltxt (org-email-link-description))
11773 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
11774 "#" message-id))))
11776 ((or (equal major-mode 'mh-folder-mode)
11777 (equal major-mode 'mh-show-mode))
11778 (let ((from (org-mhe-get-header "From:"))
11779 (to (org-mhe-get-header "To:"))
11780 (message-id (org-mhe-get-header "Message-Id:"))
11781 (subject (org-mhe-get-header "Subject:")))
11782 (org-store-link-props :type "mh" :from from :to to
11783 :subject subject :message-id message-id)
11784 (setq cpltxt (org-email-link-description))
11785 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
11786 (org-remove-angle-brackets message-id)))))
11788 ((eq major-mode 'rmail-mode)
11789 (save-excursion
11790 (save-restriction
11791 (rmail-narrow-to-non-pruned-header)
11792 (let ((folder buffer-file-name)
11793 (message-id (mail-fetch-field "message-id"))
11794 (from (mail-fetch-field "from"))
11795 (to (mail-fetch-field "to"))
11796 (subject (mail-fetch-field "subject")))
11797 (org-store-link-props
11798 :type "rmail" :from from :to to
11799 :subject subject :message-id message-id)
11800 (setq message-id (org-remove-angle-brackets message-id))
11801 (setq cpltxt (org-email-link-description))
11802 (setq link (org-make-link "rmail:" folder "#" message-id))))))
11804 ((eq major-mode 'gnus-group-mode)
11805 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
11806 (gnus-group-group-name)) ; version
11807 ((fboundp 'gnus-group-name)
11808 (gnus-group-name))
11809 (t "???"))))
11810 (unless group (error "Not on a group"))
11811 (org-store-link-props :type "gnus" :group group)
11812 (setq cpltxt (concat
11813 (if (org-xor arg org-usenet-links-prefer-google)
11814 "http://groups.google.com/groups?group="
11815 "gnus:")
11816 group)
11817 link (org-make-link cpltxt))))
11819 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
11820 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
11821 (let* ((group gnus-newsgroup-name)
11822 (article (gnus-summary-article-number))
11823 (header (gnus-summary-article-header article))
11824 (from (mail-header-from header))
11825 (message-id (mail-header-id header))
11826 (date (mail-header-date header))
11827 (subject (gnus-summary-subject-string)))
11828 (org-store-link-props :type "gnus" :from from :subject subject
11829 :message-id message-id :group group)
11830 (setq cpltxt (org-email-link-description))
11831 (if (org-xor arg org-usenet-links-prefer-google)
11832 (setq link
11833 (concat
11834 cpltxt "\n "
11835 (format "http://groups.google.com/groups?as_umsgid=%s"
11836 (org-fixup-message-id-for-http message-id))))
11837 (setq link (org-make-link "gnus:" group
11838 "#" (number-to-string article))))))
11840 ((eq major-mode 'w3-mode)
11841 (setq cpltxt (url-view-url t)
11842 link (org-make-link cpltxt))
11843 (org-store-link-props :type "w3" :url (url-view-url t)))
11845 ((eq major-mode 'w3m-mode)
11846 (setq cpltxt (or w3m-current-title w3m-current-url)
11847 link (org-make-link w3m-current-url))
11848 (org-store-link-props :type "w3m" :url (url-view-url t)))
11850 ((setq search (run-hook-with-args-until-success
11851 'org-create-file-search-functions))
11852 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
11853 "::" search))
11854 (setq cpltxt (or description link)))
11856 ((eq major-mode 'image-mode)
11857 (setq cpltxt (concat "file:"
11858 (abbreviate-file-name buffer-file-name))
11859 link (org-make-link cpltxt))
11860 (org-store-link-props :type "image" :file buffer-file-name))
11862 ((eq major-mode 'dired-mode)
11863 ;; link to the file in the current line
11864 (setq cpltxt (concat "file:"
11865 (abbreviate-file-name
11866 (expand-file-name
11867 (dired-get-filename nil t))))
11868 link (org-make-link cpltxt)))
11870 ((and buffer-file-name (org-mode-p))
11871 ;; Just link to current headline
11872 (setq cpltxt (concat "file:"
11873 (abbreviate-file-name buffer-file-name)))
11874 ;; Add a context search string
11875 (when (org-xor org-context-in-file-links arg)
11876 ;; Check if we are on a target
11877 (if (org-in-regexp "<<\\(.*?\\)>>")
11878 (setq cpltxt (concat cpltxt "::" (match-string 1)))
11879 (setq txt (cond
11880 ((org-on-heading-p) nil)
11881 ((org-region-active-p)
11882 (buffer-substring (region-beginning) (region-end)))
11883 (t (buffer-substring (point-at-bol) (point-at-eol)))))
11884 (when (or (null txt) (string-match "\\S-" txt))
11885 (setq cpltxt
11886 (concat cpltxt "::" (org-make-org-heading-search-string txt))
11887 desc "NONE"))))
11888 (if (string-match "::\\'" cpltxt)
11889 (setq cpltxt (substring cpltxt 0 -2)))
11890 (setq link (org-make-link cpltxt)))
11892 ((buffer-file-name (buffer-base-buffer))
11893 ;; Just link to this file here.
11894 (setq cpltxt (concat "file:"
11895 (abbreviate-file-name
11896 (buffer-file-name (buffer-base-buffer)))))
11897 ;; Add a context string
11898 (when (org-xor org-context-in-file-links arg)
11899 (setq txt (if (org-region-active-p)
11900 (buffer-substring (region-beginning) (region-end))
11901 (buffer-substring (point-at-bol) (point-at-eol))))
11902 ;; Only use search option if there is some text.
11903 (when (string-match "\\S-" txt)
11904 (setq cpltxt
11905 (concat cpltxt "::" (org-make-org-heading-search-string txt))
11906 desc "NONE")))
11907 (setq link (org-make-link cpltxt)))
11909 ((interactive-p)
11910 (error "Cannot link to a buffer which is not visiting a file"))
11912 (t (setq link nil)))
11914 (if (consp link) (setq cpltxt (car link) link (cdr link)))
11915 (setq link (or link cpltxt)
11916 desc (or desc cpltxt))
11917 (if (equal desc "NONE") (setq desc nil))
11919 (if (and (interactive-p) link)
11920 (progn
11921 (setq org-stored-links
11922 (cons (list link desc) org-stored-links))
11923 (message "Stored: %s" (or desc link)))
11924 (and link (org-make-link-string link desc)))))
11926 (defun org-store-link-props (&rest plist)
11927 "Store link properties, extract names and addresses."
11928 (let (x adr)
11929 (when (setq x (plist-get plist :from))
11930 (setq adr (mail-extract-address-components x))
11931 (plist-put plist :fromname (car adr))
11932 (plist-put plist :fromaddress (nth 1 adr)))
11933 (when (setq x (plist-get plist :to))
11934 (setq adr (mail-extract-address-components x))
11935 (plist-put plist :toname (car adr))
11936 (plist-put plist :toaddress (nth 1 adr))))
11937 (let ((from (plist-get plist :from))
11938 (to (plist-get plist :to)))
11939 (when (and from to org-from-is-user-regexp)
11940 (plist-put plist :fromto
11941 (if (string-match org-from-is-user-regexp from)
11942 (concat "to %t")
11943 (concat "from %f")))))
11944 (setq org-store-link-plist plist))
11946 (defun org-email-link-description (&optional fmt)
11947 "Return the description part of an email link.
11948 This takes information from `org-store-link-plist' and formats it
11949 according to FMT (default from `org-email-link-description-format')."
11950 (setq fmt (or fmt org-email-link-description-format))
11951 (let* ((p org-store-link-plist)
11952 (to (plist-get p :toaddress))
11953 (from (plist-get p :fromaddress))
11954 (table
11955 (list
11956 (cons "%c" (plist-get p :fromto))
11957 (cons "%F" (plist-get p :from))
11958 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
11959 (cons "%T" (plist-get p :to))
11960 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
11961 (cons "%s" (plist-get p :subject))
11962 (cons "%m" (plist-get p :message-id)))))
11963 (when (string-match "%c" fmt)
11964 ;; Check if the user wrote this message
11965 (if (and org-from-is-user-regexp from to
11966 (save-match-data (string-match org-from-is-user-regexp from)))
11967 (setq fmt (replace-match "to %t" t t fmt))
11968 (setq fmt (replace-match "from %f" t t fmt))))
11969 (org-replace-escapes fmt table)))
11971 (defun org-make-org-heading-search-string (&optional string heading)
11972 "Make search string for STRING or current headline."
11973 (interactive)
11974 (let ((s (or string (org-get-heading))))
11975 (unless (and string (not heading))
11976 ;; We are using a headline, clean up garbage in there.
11977 (if (string-match org-todo-regexp s)
11978 (setq s (replace-match "" t t s)))
11979 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
11980 (setq s (replace-match "" t t s)))
11981 (setq s (org-trim s))
11982 (if (string-match (concat "^\\(" org-quote-string "\\|"
11983 org-comment-string "\\)") s)
11984 (setq s (replace-match "" t t s)))
11985 (while (string-match org-ts-regexp s)
11986 (setq s (replace-match "" t t s))))
11987 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
11988 (setq s (replace-match " " t t s)))
11989 (or string (setq s (concat "*" s))) ; Add * for headlines
11990 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
11992 (defun org-make-link (&rest strings)
11993 "Concatenate STRINGS."
11994 (apply 'concat strings))
11996 (defun org-make-link-string (link &optional description)
11997 "Make a link with brackets, consisting of LINK and DESCRIPTION."
11998 (unless (string-match "\\S-" link)
11999 (error "Empty link"))
12000 (when (stringp description)
12001 ;; Remove brackets from the description, they are fatal.
12002 (while (string-match "\\[\\|\\]" description)
12003 (setq description (replace-match "" t t description))))
12004 (when (equal (org-link-escape link) description)
12005 ;; No description needed, it is identical
12006 (setq description nil))
12007 (when (and (not description)
12008 (not (equal link (org-link-escape link))))
12009 (setq description link))
12010 (concat "[[" (org-link-escape link) "]"
12011 (if description (concat "[" description "]") "")
12012 "]"))
12014 (defconst org-link-escape-chars
12015 '((?\ . "%20")
12016 (?\[ . "%5B")
12017 (?\] . "%5d")
12018 (?\340 . "%E0") ; `a
12019 (?\342 . "%E2") ; ^a
12020 (?\347 . "%E7") ; ,c
12021 (?\350 . "%E8") ; `e
12022 (?\351 . "%E9") ; 'e
12023 (?\352 . "%EA") ; ^e
12024 (?\356 . "%EE") ; ^i
12025 (?\364 . "%F4") ; ^o
12026 (?\371 . "%F9") ; `u
12027 (?\373 . "%FB") ; ^u
12028 (?\; . "%3B")
12029 (?? . "%3F")
12030 (?= . "%3D")
12031 (?+ . "%2B")
12033 "Association list of escapes for some characters problematic in links.
12034 This is the list that is used for internal purposes.")
12036 (defconst org-link-escape-chars-browser
12037 '((?\ . "%20")) ; 32 for the SPC char
12039 "Association list of escapes for some characters problematic in links.
12040 This is the list that is used before handing over to the browser.")
12042 (defun org-link-escape (text &optional table)
12043 "Escape charaters in TEXT that are problematic for links."
12044 (setq table (or table org-link-escape-chars))
12045 (when text
12046 (let ((re (mapconcat (lambda (x) (regexp-quote
12047 (char-to-string (car x))))
12048 table "\\|")))
12049 (while (string-match re text)
12050 (setq text
12051 (replace-match
12052 (cdr (assoc (string-to-char (match-string 0 text))
12053 table))
12054 t t text)))
12055 text)))
12057 (defun org-link-unescape (text &optional table)
12058 "Reverse the action of `org-link-escape'."
12059 (setq table (or table org-link-escape-chars))
12060 (when text
12061 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12062 table "\\|")))
12063 (while (string-match re text)
12064 (setq text
12065 (replace-match
12066 (char-to-string (car (rassoc (match-string 0 text) table)))
12067 t t text)))
12068 text)))
12070 (defun org-xor (a b)
12071 "Exclusive or."
12072 (if a (not b) b))
12074 (defun org-get-header (header)
12075 "Find a header field in the current buffer."
12076 (save-excursion
12077 (goto-char (point-min))
12078 (let ((case-fold-search t) s)
12079 (cond
12080 ((eq header 'from)
12081 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12082 (setq s (match-string 1)))
12083 (while (string-match "\"" s)
12084 (setq s (replace-match "" t t s)))
12085 (if (string-match "[<(].*" s)
12086 (setq s (replace-match "" t t s))))
12087 ((eq header 'message-id)
12088 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12089 (setq s (match-string 1))))
12090 ((eq header 'subject)
12091 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12092 (setq s (match-string 1)))))
12093 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12094 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12095 s)))
12098 (defun org-fixup-message-id-for-http (s)
12099 "Replace special characters in a message id, so it can be used in an http query."
12100 (while (string-match "<" s)
12101 (setq s (replace-match "%3C" t t s)))
12102 (while (string-match ">" s)
12103 (setq s (replace-match "%3E" t t s)))
12104 (while (string-match "@" s)
12105 (setq s (replace-match "%40" t t s)))
12108 ;;;###autoload
12109 (defun org-insert-link-global ()
12110 "Insert a link like Org-mode does.
12111 This command can be called in any mode to insert a link in Org-mode syntax."
12112 (interactive)
12113 (org-run-like-in-org-mode 'org-insert-link))
12115 (defun org-insert-link (&optional complete-file)
12116 "Insert a link. At the prompt, enter the link.
12118 Completion can be used to select a link previously stored with
12119 `org-store-link'. When the empty string is entered (i.e. if you just
12120 press RET at the prompt), the link defaults to the most recently
12121 stored link. As SPC triggers completion in the minibuffer, you need to
12122 use M-SPC or C-q SPC to force the insertion of a space character.
12124 You will also be prompted for a description, and if one is given, it will
12125 be displayed in the buffer instead of the link.
12127 If there is already a link at point, this command will allow you to edit link
12128 and description parts.
12130 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12131 selected using completion. The path to the file will be relative to
12132 the current directory if the file is in the current directory or a
12133 subdirectory. Otherwise, the link will be the absolute path as
12134 completed in the minibuffer (i.e. normally ~/path/to/file).
12136 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12137 is in the current directory or below.
12138 With three \\[universal-argument] prefixes, negate the meaning of
12139 `org-keep-stored-link-after-insertion'."
12140 (interactive "P")
12141 (let* ((wcf (current-window-configuration))
12142 (region (if (org-region-active-p)
12143 (buffer-substring (region-beginning) (region-end))))
12144 (remove (and region (list (region-beginning) (region-end))))
12145 (desc region)
12146 tmphist ; byte-compile incorrectly complains about this
12147 link entry file)
12148 (cond
12149 ((org-in-regexp org-bracket-link-regexp 1)
12150 ;; We do have a link at point, and we are going to edit it.
12151 (setq remove (list (match-beginning 0) (match-end 0)))
12152 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12153 (setq link (read-string "Link: "
12154 (org-link-unescape
12155 (org-match-string-no-properties 1)))))
12156 ((or (org-in-regexp org-angle-link-re)
12157 (org-in-regexp org-plain-link-re))
12158 ;; Convert to bracket link
12159 (setq remove (list (match-beginning 0) (match-end 0))
12160 link (read-string "Link: "
12161 (org-remove-angle-brackets (match-string 0)))))
12162 ((equal complete-file '(4))
12163 ;; Completing read for file names.
12164 (setq file (read-file-name "File: "))
12165 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12166 (pwd1 (file-name-as-directory (abbreviate-file-name
12167 (expand-file-name ".")))))
12168 (cond
12169 ((equal complete-file '(16))
12170 (setq link (org-make-link
12171 "file:"
12172 (abbreviate-file-name (expand-file-name file)))))
12173 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12174 (setq link (org-make-link "file:" (match-string 1 file))))
12175 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12176 (expand-file-name file))
12177 (setq link (org-make-link
12178 "file:" (match-string 1 (expand-file-name file)))))
12179 (t (setq link (org-make-link "file:" file))))))
12181 ;; Read link, with completion for stored links.
12182 (with-output-to-temp-buffer "*Org Links*"
12183 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12184 (when org-stored-links
12185 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12186 (princ (mapconcat
12187 (lambda (x)
12188 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12189 (reverse org-stored-links) "\n"))))
12190 (let ((cw (selected-window)))
12191 (select-window (get-buffer-window "*Org Links*"))
12192 (shrink-window-if-larger-than-buffer)
12193 (setq truncate-lines t)
12194 (select-window cw))
12195 ;; Fake a link history, containing the stored links.
12196 (setq tmphist (append (mapcar 'car org-stored-links)
12197 org-insert-link-history))
12198 (unwind-protect
12199 (setq link (org-completing-read
12200 "Link: "
12201 (append
12202 (mapcar (lambda (x) (list (concat (car x) ":")))
12203 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12204 (mapcar (lambda (x) (list (concat x ":")))
12205 org-link-types))
12206 nil nil nil
12207 'tmphist
12208 (or (car (car org-stored-links)))))
12209 (set-window-configuration wcf)
12210 (kill-buffer "*Org Links*"))
12211 (setq entry (assoc link org-stored-links))
12212 (or entry (push link org-insert-link-history))
12213 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12214 (not org-keep-stored-link-after-insertion))
12215 (setq org-stored-links (delq (assoc link org-stored-links)
12216 org-stored-links)))
12217 (setq desc (or desc (nth 1 entry)))))
12219 (if (string-match org-plain-link-re link)
12220 ;; URL-like link, normalize the use of angular brackets.
12221 (setq link (org-make-link (org-remove-angle-brackets link))))
12223 ;; Check if we are linking to the current file with a search option
12224 ;; If yes, simplify the link by using only the search option.
12225 (when (and buffer-file-name
12226 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12227 (let* ((path (match-string 1 link))
12228 (case-fold-search nil)
12229 (search (match-string 2 link)))
12230 (save-match-data
12231 (if (equal (file-truename buffer-file-name) (file-truename path))
12232 ;; We are linking to this same file, with a search option
12233 (setq link search)))))
12235 ;; Check if we can/should use a relative path. If yes, simplify the link
12236 (when (string-match "\\<file:\\(.*\\)" link)
12237 (let* ((path (match-string 1 link))
12238 (origpath path)
12239 (desc-is-link (equal link desc))
12240 (case-fold-search nil))
12241 (cond
12242 ((eq org-link-file-path-type 'absolute)
12243 (setq path (abbreviate-file-name (expand-file-name path))))
12244 ((eq org-link-file-path-type 'noabbrev)
12245 (setq path (expand-file-name path)))
12246 ((eq org-link-file-path-type 'relative)
12247 (setq path (file-relative-name path)))
12249 (save-match-data
12250 (if (string-match (concat "^" (regexp-quote
12251 (file-name-as-directory
12252 (expand-file-name "."))))
12253 (expand-file-name path))
12254 ;; We are linking a file with relative path name.
12255 (setq path (substring (expand-file-name path)
12256 (match-end 0)))))))
12257 (setq link (concat "file:" path))
12258 (if (equal desc origpath)
12259 (setq desc path))))
12261 (setq desc (read-string "Description: " desc))
12262 (unless (string-match "\\S-" desc) (setq desc nil))
12263 (if remove (apply 'delete-region remove))
12264 (insert (org-make-link-string link desc))))
12266 (defun org-completing-read (&rest args)
12267 (let ((minibuffer-local-completion-map
12268 (copy-keymap minibuffer-local-completion-map)))
12269 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12270 (apply 'completing-read args)))
12272 ;;; Opening/following a link
12273 (defvar org-link-search-failed nil)
12275 (defun org-next-link ()
12276 "Move forward to the next link.
12277 If the link is in hidden text, expose it."
12278 (interactive)
12279 (when (and org-link-search-failed (eq this-command last-command))
12280 (goto-char (point-min))
12281 (message "Link search wrapped back to beginning of buffer"))
12282 (setq org-link-search-failed nil)
12283 (let* ((pos (point))
12284 (ct (org-context))
12285 (a (assoc :link ct)))
12286 (if a (goto-char (nth 2 a)))
12287 (if (re-search-forward org-any-link-re nil t)
12288 (progn
12289 (goto-char (match-beginning 0))
12290 (if (org-invisible-p) (org-show-context)))
12291 (goto-char pos)
12292 (setq org-link-search-failed t)
12293 (error "No further link found"))))
12295 (defun org-previous-link ()
12296 "Move backward to the previous link.
12297 If the link is in hidden text, expose it."
12298 (interactive)
12299 (when (and org-link-search-failed (eq this-command last-command))
12300 (goto-char (point-max))
12301 (message "Link search wrapped back to end of buffer"))
12302 (setq org-link-search-failed nil)
12303 (let* ((pos (point))
12304 (ct (org-context))
12305 (a (assoc :link ct)))
12306 (if a (goto-char (nth 1 a)))
12307 (if (re-search-backward org-any-link-re nil t)
12308 (progn
12309 (goto-char (match-beginning 0))
12310 (if (org-invisible-p) (org-show-context)))
12311 (goto-char pos)
12312 (setq org-link-search-failed t)
12313 (error "No further link found"))))
12315 (defun org-find-file-at-mouse (ev)
12316 "Open file link or URL at mouse."
12317 (interactive "e")
12318 (mouse-set-point ev)
12319 (org-open-at-point 'in-emacs))
12321 (defun org-open-at-mouse (ev)
12322 "Open file link or URL at mouse."
12323 (interactive "e")
12324 (mouse-set-point ev)
12325 (org-open-at-point))
12327 (defvar org-window-config-before-follow-link nil
12328 "The window configuration before following a link.
12329 This is saved in case the need arises to restore it.")
12331 (defvar org-open-link-marker (make-marker)
12332 "Marker pointing to the location where `org-open-at-point; was called.")
12334 ;;;###autoload
12335 (defun org-open-at-point-global ()
12336 "Follow a link like Org-mode does.
12337 This command can be called in any mode to follow a link that has
12338 Org-mode syntax."
12339 (interactive)
12340 (org-run-like-in-org-mode 'org-open-at-point))
12342 (defun org-open-at-point (&optional in-emacs)
12343 "Open link at or after point.
12344 If there is no link at point, this function will search forward up to
12345 the end of the current subtree.
12346 Normally, files will be opened by an appropriate application. If the
12347 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12348 (interactive "P")
12349 (catch 'abort
12350 (move-marker org-open-link-marker (point))
12351 (setq org-window-config-before-follow-link (current-window-configuration))
12352 (org-remove-occur-highlights nil nil t)
12353 (if (org-at-timestamp-p t)
12354 (org-follow-timestamp-link)
12355 (let (type path link line search (pos (point)))
12356 (catch 'match
12357 (save-excursion
12358 (skip-chars-forward "^]\n\r")
12359 (when (org-in-regexp org-bracket-link-regexp)
12360 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12361 (while (string-match " *\n *" link)
12362 (setq link (replace-match " " t t link)))
12363 (setq link (org-link-expand-abbrev link))
12364 (if (string-match org-link-re-with-space2 link)
12365 (setq type (match-string 1 link) path (match-string 2 link))
12366 (setq type "thisfile" path link))
12367 (throw 'match t)))
12369 (when (get-text-property (point) 'org-linked-text)
12370 (setq type "thisfile"
12371 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12372 (1+ (point)) (point))
12373 path (buffer-substring
12374 (previous-single-property-change pos 'org-linked-text)
12375 (next-single-property-change pos 'org-linked-text)))
12376 (throw 'match t))
12378 (save-excursion
12379 (when (or (org-in-regexp org-angle-link-re)
12380 (org-in-regexp org-plain-link-re))
12381 (setq type (match-string 1) path (match-string 2))
12382 (throw 'match t)))
12383 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12384 (setq type "tree-match"
12385 path (match-string 1))
12386 (throw 'match t))
12387 (save-excursion
12388 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12389 (setq type "tags"
12390 path (match-string 1))
12391 (while (string-match ":" path)
12392 (setq path (replace-match "+" t t path)))
12393 (throw 'match t))))
12394 (unless path
12395 (error "No link found"))
12396 ;; Remove any trailing spaces in path
12397 (if (string-match " +\\'" path)
12398 (setq path (replace-match "" t t path)))
12400 (cond
12402 ((assoc type org-link-protocols)
12403 (funcall (nth 1 (assoc type org-link-protocols)) path))
12405 ((equal type "mailto")
12406 (let ((cmd (car org-link-mailto-program))
12407 (args (cdr org-link-mailto-program)) args1
12408 (address path) (subject "") a)
12409 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12410 (setq address (match-string 1 path)
12411 subject (org-link-escape (match-string 2 path))))
12412 (while args
12413 (cond
12414 ((not (stringp (car args))) (push (pop args) args1))
12415 (t (setq a (pop args))
12416 (if (string-match "%a" a)
12417 (setq a (replace-match address t t a)))
12418 (if (string-match "%s" a)
12419 (setq a (replace-match subject t t a)))
12420 (push a args1))))
12421 (apply cmd (nreverse args1))))
12423 ((member type '("http" "https" "ftp" "news"))
12424 (browse-url (concat type ":" (org-link-escape
12425 path org-link-escape-chars-browser))))
12427 ((string= type "tags")
12428 (org-tags-view in-emacs path))
12429 ((string= type "thisfile")
12430 (if in-emacs
12431 (switch-to-buffer-other-window
12432 (org-get-buffer-for-internal-link (current-buffer)))
12433 (org-mark-ring-push))
12434 (let ((cmd `(org-link-search
12435 ,path
12436 ,(cond ((equal in-emacs '(4)) 'occur)
12437 ((equal in-emacs '(16)) 'org-occur)
12438 (t nil))
12439 ,pos)))
12440 (condition-case nil (eval cmd)
12441 (error (progn (widen) (eval cmd))))))
12443 ((string= type "tree-match")
12444 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12446 ((string= type "file")
12447 (if (string-match "::\\([0-9]+\\)\\'" path)
12448 (setq line (string-to-number (match-string 1 path))
12449 path (substring path 0 (match-beginning 0)))
12450 (if (string-match "::\\(.+\\)\\'" path)
12451 (setq search (match-string 1 path)
12452 path (substring path 0 (match-beginning 0)))))
12453 (if (string-match "[*?{]" (file-name-nondirectory path))
12454 (dired path)
12455 (org-open-file path in-emacs line search)))
12457 ((string= type "news")
12458 (org-follow-gnus-link path))
12460 ((string= type "bbdb")
12461 (org-follow-bbdb-link path))
12463 ((string= type "info")
12464 (org-follow-info-link path))
12466 ((string= type "gnus")
12467 (let (group article)
12468 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12469 (error "Error in Gnus link"))
12470 (setq group (match-string 1 path)
12471 article (match-string 3 path))
12472 (org-follow-gnus-link group article)))
12474 ((string= type "vm")
12475 (let (folder article)
12476 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12477 (error "Error in VM link"))
12478 (setq folder (match-string 1 path)
12479 article (match-string 3 path))
12480 ;; in-emacs is the prefix arg, will be interpreted as read-only
12481 (org-follow-vm-link folder article in-emacs)))
12483 ((string= type "wl")
12484 (let (folder article)
12485 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12486 (error "Error in Wanderlust link"))
12487 (setq folder (match-string 1 path)
12488 article (match-string 3 path))
12489 (org-follow-wl-link folder article)))
12491 ((string= type "mhe")
12492 (let (folder article)
12493 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12494 (error "Error in MHE link"))
12495 (setq folder (match-string 1 path)
12496 article (match-string 3 path))
12497 (org-follow-mhe-link folder article)))
12499 ((string= type "rmail")
12500 (let (folder article)
12501 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12502 (error "Error in RMAIL link"))
12503 (setq folder (match-string 1 path)
12504 article (match-string 3 path))
12505 (org-follow-rmail-link folder article)))
12507 ((string= type "shell")
12508 (let ((cmd path))
12509 (if (or (not org-confirm-shell-link-function)
12510 (funcall org-confirm-shell-link-function
12511 (format "Execute \"%s\" in shell? "
12512 (org-add-props cmd nil
12513 'face 'org-warning))))
12514 (progn
12515 (message "Executing %s" cmd)
12516 (shell-command cmd))
12517 (error "Abort"))))
12519 ((string= type "elisp")
12520 (let ((cmd path))
12521 (if (or (not org-confirm-elisp-link-function)
12522 (funcall org-confirm-elisp-link-function
12523 (format "Execute \"%s\" as elisp? "
12524 (org-add-props cmd nil
12525 'face 'org-warning))))
12526 (message "%s => %s" cmd (eval (read cmd)))
12527 (error "Abort"))))
12530 (browse-url-at-point)))))
12531 (move-marker org-open-link-marker nil)))
12533 ;;; File search
12535 (defvar org-create-file-search-functions nil
12536 "List of functions to construct the right search string for a file link.
12537 These functions are called in turn with point at the location to
12538 which the link should point.
12540 A function in the hook should first test if it would like to
12541 handle this file type, for example by checking the major-mode or
12542 the file extension. If it decides not to handle this file, it
12543 should just return nil to give other functions a chance. If it
12544 does handle the file, it must return the search string to be used
12545 when following the link. The search string will be part of the
12546 file link, given after a double colon, and `org-open-at-point'
12547 will automatically search for it. If special measures must be
12548 taken to make the search successful, another function should be
12549 added to the companion hook `org-execute-file-search-functions',
12550 which see.
12552 A function in this hook may also use `setq' to set the variable
12553 `description' to provide a suggestion for the descriptive text to
12554 be used for this link when it gets inserted into an Org-mode
12555 buffer with \\[org-insert-link].")
12557 (defvar org-execute-file-search-functions nil
12558 "List of functions to execute a file search triggered by a link.
12560 Functions added to this hook must accept a single argument, the
12561 search string that was part of the file link, the part after the
12562 double colon. The function must first check if it would like to
12563 handle this search, for example by checking the major-mode or the
12564 file extension. If it decides not to handle this search, it
12565 should just return nil to give other functions a chance. If it
12566 does handle the search, it must return a non-nil value to keep
12567 other functions from trying.
12569 Each function can access the current prefix argument through the
12570 variable `current-prefix-argument'. Note that a single prefix is
12571 used to force opening a link in Emacs, so it may be good to only
12572 use a numeric or double prefix to guide the search function.
12574 In case this is needed, a function in this hook can also restore
12575 the window configuration before `org-open-at-point' was called using:
12577 (set-window-configuration org-window-config-before-follow-link)")
12579 (defun org-link-search (s &optional type avoid-pos)
12580 "Search for a link search option.
12581 If S is surrounded by forward slashes, it is interpreted as a
12582 regular expression. In org-mode files, this will create an `org-occur'
12583 sparse tree. In ordinary files, `occur' will be used to list matches.
12584 If the current buffer is in `dired-mode', grep will be used to search
12585 in all files. If AVOID-POS is given, ignore matches near that position."
12586 (let ((case-fold-search t)
12587 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12588 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12589 (append '(("") (" ") ("\t") ("\n"))
12590 org-emphasis-alist)
12591 "\\|") "\\)"))
12592 (pos (point))
12593 (pre "") (post "")
12594 words re0 re1 re2 re3 re4 re5 re2a reall)
12595 (cond
12596 ;; First check if there are any special
12597 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12598 ;; Now try the builtin stuff
12599 ((save-excursion
12600 (goto-char (point-min))
12601 (and
12602 (re-search-forward
12603 (concat "<<" (regexp-quote s0) ">>") nil t)
12604 (setq pos (match-beginning 0))))
12605 ;; There is an exact target for this
12606 (goto-char pos))
12607 ((string-match "^/\\(.*\\)/$" s)
12608 ;; A regular expression
12609 (cond
12610 ((org-mode-p)
12611 (org-occur (match-string 1 s)))
12612 ;;((eq major-mode 'dired-mode)
12613 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12614 (t (org-do-occur (match-string 1 s)))))
12616 ;; A normal search strings
12617 (when (equal (string-to-char s) ?*)
12618 ;; Anchor on headlines, post may include tags.
12619 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
12620 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
12621 s (substring s 1)))
12622 (remove-text-properties
12623 0 (length s)
12624 '(face nil mouse-face nil keymap nil fontified nil) s)
12625 ;; Make a series of regular expressions to find a match
12626 (setq words (org-split-string s "[ \n\r\t]+")
12627 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
12628 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
12629 "\\)" markers)
12630 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
12631 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
12632 re1 (concat pre re2 post)
12633 re3 (concat pre re4 post)
12634 re5 (concat pre ".*" re4)
12635 re2 (concat pre re2)
12636 re2a (concat pre re2a)
12637 re4 (concat pre re4)
12638 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
12639 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
12640 re5 "\\)"
12642 (cond
12643 ((eq type 'org-occur) (org-occur reall))
12644 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
12645 (t (goto-char (point-min))
12646 (if (or (org-search-not-self 1 re0 nil t)
12647 (org-search-not-self 1 re1 nil t)
12648 (org-search-not-self 1 re2 nil t)
12649 (org-search-not-self 1 re2a nil t)
12650 (org-search-not-self 1 re3 nil t)
12651 (org-search-not-self 1 re4 nil t)
12652 (org-search-not-self 1 re5 nil t)
12654 (goto-char (match-beginning 1))
12655 (goto-char pos)
12656 (error "No match")))))
12658 ;; Normal string-search
12659 (goto-char (point-min))
12660 (if (search-forward s nil t)
12661 (goto-char (match-beginning 0))
12662 (error "No match"))))
12663 (and (org-mode-p) (org-show-context 'link-search))))
12665 (defun org-search-not-self (group &rest args)
12666 "Execute `re-search-forward', but only accept matches that do not
12667 enclose the position of `org-open-link-marker'."
12668 (let ((m org-open-link-marker))
12669 (catch 'exit
12670 (while (apply 're-search-forward args)
12671 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
12672 (goto-char (match-end group))
12673 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
12674 (> (match-beginning 0) (marker-position m))
12675 (< (match-end 0) (marker-position m)))
12676 (save-match-data
12677 (or (not (org-in-regexp
12678 org-bracket-link-analytic-regexp 1))
12679 (not (match-end 4)) ; no description
12680 (and (<= (match-beginning 4) (point))
12681 (>= (match-end 4) (point))))))
12682 (throw 'exit (point))))))))
12684 (defun org-get-buffer-for-internal-link (buffer)
12685 "Return a buffer to be used for displaying the link target of internal links."
12686 (cond
12687 ((not org-display-internal-link-with-indirect-buffer)
12688 buffer)
12689 ((string-match "(Clone)$" (buffer-name buffer))
12690 (message "Buffer is already a clone, not making another one")
12691 ;; we also do not modify visibility in this case
12692 buffer)
12693 (t ; make a new indirect buffer for displaying the link
12694 (let* ((bn (buffer-name buffer))
12695 (ibn (concat bn "(Clone)"))
12696 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
12697 (with-current-buffer ib (org-overview))
12698 ib))))
12700 (defun org-do-occur (regexp &optional cleanup)
12701 "Call the Emacs command `occur'.
12702 If CLEANUP is non-nil, remove the printout of the regular expression
12703 in the *Occur* buffer. This is useful if the regex is long and not useful
12704 to read."
12705 (occur regexp)
12706 (when cleanup
12707 (let ((cwin (selected-window)) win beg end)
12708 (when (setq win (get-buffer-window "*Occur*"))
12709 (select-window win))
12710 (goto-char (point-min))
12711 (when (re-search-forward "match[a-z]+" nil t)
12712 (setq beg (match-end 0))
12713 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
12714 (setq end (1- (match-beginning 0)))))
12715 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
12716 (goto-char (point-min))
12717 (select-window cwin))))
12719 ;;; The mark ring for links jumps
12721 (defvar org-mark-ring nil
12722 "Mark ring for positions before jumps in Org-mode.")
12723 (defvar org-mark-ring-last-goto nil
12724 "Last position in the mark ring used to go back.")
12725 ;; Fill and close the ring
12726 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
12727 (loop for i from 1 to org-mark-ring-length do
12728 (push (make-marker) org-mark-ring))
12729 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
12730 org-mark-ring)
12732 (defun org-mark-ring-push (&optional pos buffer)
12733 "Put the current position or POS into the mark ring and rotate it."
12734 (interactive)
12735 (setq pos (or pos (point)))
12736 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
12737 (move-marker (car org-mark-ring)
12738 (or pos (point))
12739 (or buffer (current-buffer)))
12740 (message "%s"
12741 (substitute-command-keys
12742 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
12744 (defun org-mark-ring-goto (&optional n)
12745 "Jump to the previous position in the mark ring.
12746 With prefix arg N, jump back that many stored positions. When
12747 called several times in succession, walk through the entire ring.
12748 Org-mode commands jumping to a different position in the current file,
12749 or to another Org-mode file, automatically push the old position
12750 onto the ring."
12751 (interactive "p")
12752 (let (p m)
12753 (if (eq last-command this-command)
12754 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
12755 (setq p org-mark-ring))
12756 (setq org-mark-ring-last-goto p)
12757 (setq m (car p))
12758 (switch-to-buffer (marker-buffer m))
12759 (goto-char m)
12760 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
12762 (defun org-remove-angle-brackets (s)
12763 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
12764 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
12766 (defun org-add-angle-brackets (s)
12767 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
12768 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
12771 ;;; Following specific links
12773 (defun org-follow-timestamp-link ()
12774 (cond
12775 ((org-at-date-range-p t)
12776 (let ((org-agenda-start-on-weekday)
12777 (t1 (match-string 1))
12778 (t2 (match-string 2)))
12779 (setq t1 (time-to-days (org-time-string-to-time t1))
12780 t2 (time-to-days (org-time-string-to-time t2)))
12781 (org-agenda-list nil t1 (1+ (- t2 t1)))))
12782 ((org-at-timestamp-p t)
12783 (org-agenda-list nil (time-to-days (org-time-string-to-time
12784 (substring (match-string 1) 0 10)))
12786 (t (error "This should not happen"))))
12789 (defun org-follow-bbdb-link (name)
12790 "Follow a BBDB link to NAME."
12791 (require 'bbdb)
12792 (let ((inhibit-redisplay (not debug-on-error))
12793 (bbdb-electric-p nil))
12794 (catch 'exit
12795 ;; Exact match on name
12796 (bbdb-name (concat "\\`" name "\\'") nil)
12797 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12798 ;; Exact match on name
12799 (bbdb-company (concat "\\`" name "\\'") nil)
12800 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12801 ;; Partial match on name
12802 (bbdb-name name nil)
12803 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12804 ;; Partial match on company
12805 (bbdb-company name nil)
12806 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12807 ;; General match including network address and notes
12808 (bbdb name nil)
12809 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
12810 (delete-window (get-buffer-window "*BBDB*"))
12811 (error "No matching BBDB record")))))
12813 (defun org-follow-info-link (name)
12814 "Follow an info file & node link to NAME."
12815 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
12816 (string-match "\\(.*\\)" name))
12817 (progn
12818 (require 'info)
12819 (if (match-string 2 name) ; If there isn't a node, choose "Top"
12820 (Info-find-node (match-string 1 name) (match-string 2 name))
12821 (Info-find-node (match-string 1 name) "Top")))
12822 (message "Could not open: %s" name)))
12824 (defun org-follow-gnus-link (&optional group article)
12825 "Follow a Gnus link to GROUP and ARTICLE."
12826 (require 'gnus)
12827 (funcall (cdr (assq 'gnus org-link-frame-setup)))
12828 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
12829 (cond ((and group article)
12830 (gnus-group-read-group 1 nil group)
12831 (gnus-summary-goto-article (string-to-number article) nil t))
12832 (group (gnus-group-jump-to-group group))))
12834 (defun org-follow-vm-link (&optional folder article readonly)
12835 "Follow a VM link to FOLDER and ARTICLE."
12836 (require 'vm)
12837 (setq article (org-add-angle-brackets article))
12838 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
12839 ;; ange-ftp or efs or tramp access
12840 (let ((user (or (match-string 1 folder) (user-login-name)))
12841 (host (match-string 2 folder))
12842 (file (match-string 3 folder)))
12843 (cond
12844 ((featurep 'tramp)
12845 ;; use tramp to access the file
12846 (if (featurep 'xemacs)
12847 (setq folder (format "[%s@%s]%s" user host file))
12848 (setq folder (format "/%s@%s:%s" user host file))))
12850 ;; use ange-ftp or efs
12851 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
12852 (setq folder (format "/%s@%s:%s" user host file))))))
12853 (when folder
12854 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
12855 (sit-for 0.1)
12856 (when article
12857 (vm-select-folder-buffer)
12858 (widen)
12859 (let ((case-fold-search t))
12860 (goto-char (point-min))
12861 (if (not (re-search-forward
12862 (concat "^" "message-id: *" (regexp-quote article))))
12863 (error "Could not find the specified message in this folder"))
12864 (vm-isearch-update)
12865 (vm-isearch-narrow)
12866 (vm-beginning-of-message)
12867 (vm-summarize)))))
12869 (defun org-follow-wl-link (folder article)
12870 "Follow a Wanderlust link to FOLDER and ARTICLE."
12871 (if (and (string= folder "%")
12872 article
12873 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
12874 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
12875 ;; Thus, we recompose folder and article ids.
12876 (setq folder (format "%s#%s" folder (match-string 1 article))
12877 article (match-string 3 article)))
12878 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
12879 (error "No such folder: %s" folder))
12880 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
12881 (and article
12882 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
12883 (wl-summary-redisplay)))
12885 (defun org-follow-rmail-link (folder article)
12886 "Follow an RMAIL link to FOLDER and ARTICLE."
12887 (setq article (org-add-angle-brackets article))
12888 (let (message-number)
12889 (save-excursion
12890 (save-window-excursion
12891 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
12892 (setq message-number
12893 (save-restriction
12894 (widen)
12895 (goto-char (point-max))
12896 (if (re-search-backward
12897 (concat "^Message-ID:\\s-+" (regexp-quote
12898 (or article "")))
12899 nil t)
12900 (rmail-what-message))))))
12901 (if message-number
12902 (progn
12903 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
12904 (rmail-show-message message-number)
12905 message-number)
12906 (error "Message not found"))))
12908 ;;; mh-e integration based on planner-mode
12909 (defun org-mhe-get-message-real-folder ()
12910 "Return the name of the current message real folder, so if you use
12911 sequences, it will now work."
12912 (save-excursion
12913 (let* ((folder
12914 (if (equal major-mode 'mh-folder-mode)
12915 mh-current-folder
12916 ;; Refer to the show buffer
12917 mh-show-folder-buffer))
12918 (end-index
12919 (if (boundp 'mh-index-folder)
12920 (min (length mh-index-folder) (length folder))))
12922 ;; a simple test on mh-index-data does not work, because
12923 ;; mh-index-data is always nil in a show buffer.
12924 (if (and (boundp 'mh-index-folder)
12925 (string= mh-index-folder (substring folder 0 end-index)))
12926 (if (equal major-mode 'mh-show-mode)
12927 (save-window-excursion
12928 (let (pop-up-frames)
12929 (when (buffer-live-p (get-buffer folder))
12930 (progn
12931 (pop-to-buffer folder)
12932 (org-mhe-get-message-folder-from-index)
12935 (org-mhe-get-message-folder-from-index)
12937 folder
12941 (defun org-mhe-get-message-folder-from-index ()
12942 "Returns the name of the message folder in a index folder buffer."
12943 (save-excursion
12944 (mh-index-previous-folder)
12945 (re-search-forward "^\\(+.*\\)$" nil t)
12946 (message "%s" (match-string 1))))
12948 (defun org-mhe-get-message-folder ()
12949 "Return the name of the current message folder. Be careful if you
12950 use sequences."
12951 (save-excursion
12952 (if (equal major-mode 'mh-folder-mode)
12953 mh-current-folder
12954 ;; Refer to the show buffer
12955 mh-show-folder-buffer)))
12957 (defun org-mhe-get-message-num ()
12958 "Return the number of the current message. Be careful if you
12959 use sequences."
12960 (save-excursion
12961 (if (equal major-mode 'mh-folder-mode)
12962 (mh-get-msg-num nil)
12963 ;; Refer to the show buffer
12964 (mh-show-buffer-message-number))))
12966 (defun org-mhe-get-header (header)
12967 "Return a header of the message in folder mode. This will create a
12968 show buffer for the corresponding message. If you have a more clever
12969 idea..."
12970 (let* ((folder (org-mhe-get-message-folder))
12971 (num (org-mhe-get-message-num))
12972 (buffer (get-buffer-create (concat "show-" folder)))
12973 (header-field))
12974 (with-current-buffer buffer
12975 (mh-display-msg num folder)
12976 (if (equal major-mode 'mh-folder-mode)
12977 (mh-header-display)
12978 (mh-show-header-display))
12979 (set-buffer buffer)
12980 (setq header-field (mh-get-header-field header))
12981 (if (equal major-mode 'mh-folder-mode)
12982 (mh-show)
12983 (mh-show-show))
12984 header-field)))
12986 (defun org-follow-mhe-link (folder article)
12987 "Follow an MHE link to FOLDER and ARTICLE.
12988 If ARTICLE is nil FOLDER is shown. If the configuration variable
12989 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
12990 ARTICLE is searched in all folders. Indexed searches (swish++,
12991 namazu, and others supported by MH-E) will always search in all
12992 folders."
12993 (require 'mh-e)
12994 (require 'mh-search)
12995 (require 'mh-utils)
12996 (mh-find-path)
12997 (if (not article)
12998 (mh-visit-folder (mh-normalize-folder-name folder))
12999 (setq article (org-add-angle-brackets article))
13000 (mh-search-choose)
13001 (if (equal mh-searcher 'pick)
13002 (progn
13003 (mh-search folder (list "--message-id" article))
13004 (when (and org-mhe-search-all-folders
13005 (not (org-mhe-get-message-real-folder)))
13006 (kill-this-buffer)
13007 (mh-search "+" (list "--message-id" article))))
13008 (mh-search "+" article))
13009 (if (org-mhe-get-message-real-folder)
13010 (mh-show-msg 1)
13011 (kill-this-buffer)
13012 (error "Message not found"))))
13014 ;;; BibTeX links
13016 ;; Use the custom search meachnism to construct and use search strings for
13017 ;; file links to BibTeX database entries.
13019 (defun org-create-file-search-in-bibtex ()
13020 "Create the search string and description for a BibTeX database entry."
13021 (when (eq major-mode 'bibtex-mode)
13022 ;; yes, we want to construct this search string.
13023 ;; Make a good description for this entry, using names, year and the title
13024 ;; Put it into the `description' variable which is dynamically scoped.
13025 (let ((bibtex-autokey-names 1)
13026 (bibtex-autokey-names-stretch 1)
13027 (bibtex-autokey-name-case-convert-function 'identity)
13028 (bibtex-autokey-name-separator " & ")
13029 (bibtex-autokey-additional-names " et al.")
13030 (bibtex-autokey-year-length 4)
13031 (bibtex-autokey-name-year-separator " ")
13032 (bibtex-autokey-titlewords 3)
13033 (bibtex-autokey-titleword-separator " ")
13034 (bibtex-autokey-titleword-case-convert-function 'identity)
13035 (bibtex-autokey-titleword-length 'infty)
13036 (bibtex-autokey-year-title-separator ": "))
13037 (setq description (bibtex-generate-autokey)))
13038 ;; Now parse the entry, get the key and return it.
13039 (save-excursion
13040 (bibtex-beginning-of-entry)
13041 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13043 (defun org-execute-file-search-in-bibtex (s)
13044 "Find the link search string S as a key for a database entry."
13045 (when (eq major-mode 'bibtex-mode)
13046 ;; Yes, we want to do the search in this file.
13047 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13048 (goto-char (point-min))
13049 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13050 (regexp-quote s) "[ \t\n]*,") nil t)
13051 (goto-char (match-beginning 0)))
13052 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13053 ;; Use double prefix to indicate that any web link should be browsed
13054 (let ((b (current-buffer)) (p (point)))
13055 ;; Restore the window configuration because we just use the web link
13056 (set-window-configuration org-window-config-before-follow-link)
13057 (save-excursion (set-buffer b) (goto-char p)
13058 (bibtex-url)))
13059 (recenter 0)) ; Move entry start to beginning of window
13060 ;; return t to indicate that the search is done.
13063 ;; Finally add the functions to the right hooks.
13064 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13065 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13067 ;; end of Bibtex link setup
13069 ;;; Following file links
13071 (defun org-open-file (path &optional in-emacs line search)
13072 "Open the file at PATH.
13073 First, this expands any special file name abbreviations. Then the
13074 configuration variable `org-file-apps' is checked if it contains an
13075 entry for this file type, and if yes, the corresponding command is launched.
13076 If no application is found, Emacs simply visits the file.
13077 With optional argument IN-EMACS, Emacs will visit the file.
13078 Optional LINE specifies a line to go to, optional SEARCH a string to
13079 search for. If LINE or SEARCH is given, the file will always be
13080 opened in Emacs.
13081 If the file does not exist, an error is thrown."
13082 (setq in-emacs (or in-emacs line search))
13083 (let* ((file (if (equal path "")
13084 buffer-file-name
13085 (substitute-in-file-name (expand-file-name path))))
13086 (apps (append org-file-apps (org-default-apps)))
13087 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13088 (dirp (if remp nil (file-directory-p file)))
13089 (dfile (downcase file))
13090 (old-buffer (current-buffer))
13091 (old-pos (point))
13092 (old-mode major-mode)
13093 ext cmd)
13094 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13095 (setq ext (match-string 1 dfile))
13096 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13097 (setq ext (match-string 1 dfile))))
13098 (if in-emacs
13099 (setq cmd 'emacs)
13100 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13101 (and dirp (cdr (assoc 'directory apps)))
13102 (cdr (assoc ext apps))
13103 (cdr (assoc t apps)))))
13104 (when (eq cmd 'mailcap)
13105 (require 'mailcap)
13106 (mailcap-parse-mailcaps)
13107 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13108 (command (mailcap-mime-info mime-type)))
13109 (if (stringp command)
13110 (setq cmd command)
13111 (setq cmd 'emacs))))
13112 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13113 (not (file-exists-p file))
13114 (not org-open-non-existing-files))
13115 (error "No such file: %s" file))
13116 (cond
13117 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13118 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13119 (if (string-match "['\"]%s['\"]" cmd)
13120 (setq cmd (replace-match "%s" t t cmd)))
13121 (setq cmd (format cmd (shell-quote-argument file)))
13122 (save-window-excursion
13123 (start-process-shell-command cmd nil cmd)))
13124 ((or (stringp cmd)
13125 (eq cmd 'emacs))
13126 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13127 (widen)
13128 (if line (goto-line line)
13129 (if search (org-link-search search))))
13130 ((consp cmd)
13131 (eval cmd))
13132 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13133 (and (org-mode-p) (eq old-mode 'org-mode)
13134 (or (not (equal old-buffer (current-buffer)))
13135 (not (equal old-pos (point))))
13136 (org-mark-ring-push old-pos old-buffer))))
13138 (defun org-default-apps ()
13139 "Return the default applications for this operating system."
13140 (cond
13141 ((eq system-type 'darwin)
13142 org-file-apps-defaults-macosx)
13143 ((eq system-type 'windows-nt)
13144 org-file-apps-defaults-windowsnt)
13145 (t org-file-apps-defaults-gnu)))
13147 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13148 (defun org-file-remote-p (file)
13149 "Test whether FILE specifies a location on a remote system.
13150 Return non-nil if the location is indeed remote.
13152 For example, the filename \"/user@host:/foo\" specifies a location
13153 on the system \"/user@host:\"."
13154 (cond ((fboundp 'file-remote-p)
13155 (file-remote-p file))
13156 ((fboundp 'tramp-handle-file-remote-p)
13157 (tramp-handle-file-remote-p file))
13158 ((and (boundp 'ange-ftp-name-format)
13159 (string-match (car ange-ftp-name-format) file))
13161 (t nil)))
13164 ;;;; Hooks for remember.el, and refiling
13166 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13167 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13169 ;;;###autoload
13170 (defun org-remember-insinuate ()
13171 "Setup remember.el for use wiht Org-mode."
13172 (require 'remember)
13173 (setq remember-annotation-functions '(org-remember-annotation))
13174 (setq remember-handler-functions '(org-remember-handler))
13175 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13177 ;;;###autoload
13178 (defun org-remember-annotation ()
13179 "Return a link to the current location as an annotation for remember.el.
13180 If you are using Org-mode files as target for data storage with
13181 remember.el, then the annotations should include a link compatible with the
13182 conventions in Org-mode. This function returns such a link."
13183 (org-store-link nil))
13185 (defconst org-remember-help
13186 "Select a destination location for the note.
13187 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13188 RET on headline -> Store as sublevel entry to current headline
13189 RET at beg-of-buf -> Append to file as level 2 headline
13190 <left>/<right> -> before/after current headline, same headings level")
13192 (defvar org-remember-previous-location nil)
13193 (defvar org-force-remember-template-char) ;; dynamically scoped
13195 (defun org-select-remember-template (&optional use-char)
13196 (when org-remember-templates
13197 (let* ((templates (mapcar (lambda (x)
13198 (if (stringp (car x))
13199 (append (list (nth 1 x) (car x)) (cddr x))
13200 (append (list (car x) "") (cdr x))))
13201 org-remember-templates))
13202 (char (or use-char
13203 (cond
13204 ((= (length templates) 1)
13205 (caar templates))
13206 ((and (boundp 'org-force-remember-template-char)
13207 org-force-remember-template-char)
13208 (if (stringp org-force-remember-template-char)
13209 (string-to-char org-force-remember-template-char)
13210 org-force-remember-template-char))
13212 (message "Select template: %s"
13213 (mapconcat
13214 (lambda (x)
13215 (cond
13216 ((not (string-match "\\S-" (nth 1 x)))
13217 (format "[%c]" (car x)))
13218 ((equal (downcase (car x))
13219 (downcase (aref (nth 1 x) 0)))
13220 (format "[%c]%s" (car x)
13221 (substring (nth 1 x) 1)))
13222 (t (format "[%c]%s" (car x) (nth 1 x)))))
13223 templates " "))
13224 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13225 (when (equal char0 ?\C-g)
13226 (jump-to-register remember-register)
13227 (kill-buffer remember-buffer))
13228 char0))))))
13229 (cddr (assoc char templates)))))
13231 (defvar x-last-selected-text)
13232 (defvar x-last-selected-text-primary)
13234 ;;;###autoload
13235 (defun org-remember-apply-template (&optional use-char skip-interactive)
13236 "Initialize *remember* buffer with template, invoke `org-mode'.
13237 This function should be placed into `remember-mode-hook' and in fact requires
13238 to be run from that hook to function properly."
13239 (unless (fboundp 'remember-finalize)
13240 (defalias 'remember-finalize 'remember-buffer))
13241 (if org-remember-templates
13242 (let* ((entry (org-select-remember-template use-char))
13243 (tpl (car entry))
13244 (plist-p (if org-store-link-plist t nil))
13245 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13246 (string-match "\\S-" (nth 1 entry)))
13247 (nth 1 entry)
13248 org-default-notes-file))
13249 (headline (nth 2 entry))
13250 (v-c (or (and (eq window-system 'x)
13251 (fboundp 'x-cut-buffer-or-selection-value)
13252 (x-cut-buffer-or-selection-value))
13253 (org-bound-and-true-p x-last-selected-text)
13254 (org-bound-and-true-p x-last-selected-text-primary)
13255 (and (> (length kill-ring) 0) (current-kill 0))))
13256 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13257 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13258 (v-u (concat "[" (substring v-t 1 -1) "]"))
13259 (v-U (concat "[" (substring v-T 1 -1) "]"))
13260 ;; `initial' and `annotation' are bound in `remember'
13261 (v-i (if (boundp 'initial) initial))
13262 (v-a (if (and (boundp 'annotation) annotation)
13263 (if (equal annotation "[[]]") "" annotation)
13264 ""))
13265 (v-A (if (and v-a
13266 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13267 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13268 v-a))
13269 (v-n user-full-name)
13270 (org-startup-folded nil)
13271 org-time-was-given org-end-time-was-given x
13272 prompt completions char time pos default histvar)
13273 (setq org-store-link-plist
13274 (append (list :annotation v-a :initial v-i)
13275 org-store-link-plist))
13276 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13277 (erase-buffer)
13278 (insert (substitute-command-keys
13279 (format
13280 "## Filing location: Select interactively, default, or last used:
13281 ## %s to select file and header location interactively.
13282 ## %s \"%s\" -> \"* %s\"
13283 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13284 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13285 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13286 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13287 (abbreviate-file-name (or file org-default-notes-file))
13288 (or headline "")
13289 (or (car org-remember-previous-location) "???")
13290 (or (cdr org-remember-previous-location) "???"))))
13291 (insert tpl) (goto-char (point-min))
13292 ;; Simple %-escapes
13293 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13294 (when (and initial (equal (match-string 0) "%i"))
13295 (save-match-data
13296 (let* ((lead (buffer-substring
13297 (point-at-bol) (match-beginning 0))))
13298 (setq v-i (mapconcat 'identity
13299 (org-split-string initial "\n")
13300 (concat "\n" lead))))))
13301 (replace-match
13302 (or (eval (intern (concat "v-" (match-string 1)))) "")
13303 t t))
13305 ;; %[] Insert contents of a file.
13306 (goto-char (point-min))
13307 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13308 (let ((start (match-beginning 0))
13309 (end (match-end 0))
13310 (filename (expand-file-name (match-string 1))))
13311 (goto-char start)
13312 (delete-region start end)
13313 (condition-case error
13314 (insert-file-contents filename)
13315 (error (insert (format "%%![Couldn't insert %s: %s]"
13316 filename error))))))
13317 ;; %() embedded elisp
13318 (goto-char (point-min))
13319 (while (re-search-forward "%\\((.+)\\)" nil t)
13320 (goto-char (match-beginning 0))
13321 (let ((template-start (point)))
13322 (forward-char 1)
13323 (let ((result
13324 (condition-case error
13325 (eval (read (current-buffer)))
13326 (error (format "%%![Error: %s]" error)))))
13327 (delete-region template-start (point))
13328 (insert result))))
13330 ;; From the property list
13331 (when plist-p
13332 (goto-char (point-min))
13333 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13334 (and (setq x (or (plist-get org-store-link-plist
13335 (intern (match-string 1))) ""))
13336 (replace-match x t t))))
13338 ;; Turn on org-mode in the remember buffer, set local variables
13339 (org-mode)
13340 (org-set-local 'org-finish-function 'remember-finalize)
13341 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13342 (org-set-local 'org-default-notes-file file))
13343 (if (and headline (stringp headline) (string-match "\\S-" headline))
13344 (org-set-local 'org-remember-default-headline headline))
13345 ;; Interactive template entries
13346 (goto-char (point-min))
13347 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([guUtT]\\)?" nil t)
13348 (setq char (if (match-end 3) (match-string 3))
13349 prompt (if (match-end 2) (match-string 2)))
13350 (goto-char (match-beginning 0))
13351 (replace-match "")
13352 (setq completions nil default nil)
13353 (when prompt
13354 (setq completions (org-split-string prompt "|")
13355 prompt (pop completions)
13356 default (car completions)
13357 histvar (intern (concat
13358 "org-remember-template-prompt-history::"
13359 (or prompt "")))
13360 completions (mapcar 'list completions)))
13361 (cond
13362 ((member char '("G" "g"))
13363 (let* ((org-last-tags-completion-table
13364 (org-global-tags-completion-table
13365 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13366 (org-add-colon-after-tag-completion t)
13367 (ins (completing-read
13368 (if prompt (concat prompt ": ") "Tags: ")
13369 'org-tags-completion-function nil nil nil
13370 'org-tags-history)))
13371 (setq ins (mapconcat 'identity
13372 (org-split-string ins (org-re "[^[:alnum:]]+"))
13373 ":"))
13374 (when (string-match "\\S-" ins)
13375 (or (equal (char-before) ?:) (insert ":"))
13376 (insert ins)
13377 (or (equal (char-after) ?:) (insert ":")))))
13378 (char
13379 (setq org-time-was-given (equal (upcase char) char))
13380 (setq time (org-read-date (equal (upcase char) "U") t nil
13381 prompt))
13382 (org-insert-time-stamp time org-time-was-given
13383 (member char '("u" "U"))
13384 nil nil (list org-end-time-was-given)))
13386 (insert (completing-read
13387 (concat (if prompt prompt "Enter string")
13388 (if default (concat " [" default "]"))
13389 ": ")
13390 completions nil nil nil histvar default)))))
13391 (goto-char (point-min))
13392 (if (re-search-forward "%\\?" nil t)
13393 (replace-match "")
13394 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13395 (org-mode)
13396 (org-set-local 'org-finish-function 'remember-finalize))
13397 (when (save-excursion
13398 (goto-char (point-min))
13399 (re-search-forward "%!" nil t))
13400 (replace-match "")
13401 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13403 (defun org-remember-finish-immediately ()
13404 "File remember note immediately.
13405 This should be run in `post-command-hook' and will remove itself
13406 from that hook."
13407 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13408 (when org-finish-function
13409 (funcall org-finish-function)))
13412 ;;;###autoload
13413 (defun org-remember (&optional goto org-force-remember-template-char)
13414 "Call `remember'. If this is already a remember buffer, re-apply template.
13415 If there is an active region, make sure remember uses it as initial content
13416 of the remember buffer.
13418 When called interactively with a `C-u' prefix argument GOTO, don't remember
13419 anything, just go to the file/headline where the selected templated usually
13420 stores its notes. With a double prefix arg `C-u C-u', got to the last
13421 note stored by remember.
13423 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13424 associated with a template in `org-remember-tempates'."
13425 (interactive "P")
13426 (cond
13427 ((equal goto '(4)) (org-go-to-remember-target))
13428 ((equal goto '(16)) (org-remember-goto-last-stored))
13430 (if (eq org-finish-function 'remember-buffer)
13431 (progn
13432 (when (< (length org-remember-templates) 2)
13433 (error "No other template available"))
13434 (erase-buffer)
13435 (let ((annotation (plist-get org-store-link-plist :annotation))
13436 (initial (plist-get org-store-link-plist :initial)))
13437 (org-remember-apply-template))
13438 (message "Press C-c C-c to remember data"))
13439 (if (org-region-active-p)
13440 (remember (buffer-substring (point) (mark)))
13441 (call-interactively 'remember))))))
13443 (defun org-remember-goto-last-stored ()
13444 "Go to the location where the last remember note was stored."
13445 (interactive)
13446 (bookmark-jump "org-remember-last-stored")
13447 (message "This is the last note stored by remember"))
13449 (defun org-go-to-remember-target (&optional template-key)
13450 "Go to the target location of a remember template.
13451 The user is queried for the template."
13452 (interactive)
13453 (let* ((entry (org-select-remember-template template-key))
13454 (file (nth 1 entry))
13455 (heading (nth 2 entry))
13456 visiting)
13457 (unless (and file (stringp file) (string-match "\\S-" file))
13458 (setq file org-default-notes-file))
13459 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13460 (setq heading org-remember-default-headline))
13461 (setq visiting (org-find-base-buffer-visiting file))
13462 (if (not visiting) (find-file-noselect file))
13463 (switch-to-buffer (or visiting (get-file-buffer file)))
13464 (widen)
13465 (goto-char (point-min))
13466 (if (re-search-forward
13467 (concat "^\\*+[ \t]+" (regexp-quote heading)
13468 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13469 nil t)
13470 (goto-char (match-beginning 0))
13471 (error "Target headline not found: %s" heading))))
13473 (defvar org-note-abort nil) ; dynamically scoped
13475 ;;;###autoload
13476 (defun org-remember-handler ()
13477 "Store stuff from remember.el into an org file.
13478 First prompts for an org file. If the user just presses return, the value
13479 of `org-default-notes-file' is used.
13480 Then the command offers the headings tree of the selected file in order to
13481 file the text at a specific location.
13482 You can either immediately press RET to get the note appended to the
13483 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13484 find a better place. Then press RET or <left> or <right> in insert the note.
13486 Key Cursor position Note gets inserted
13487 -----------------------------------------------------------------------------
13488 RET buffer-start as level 1 heading at end of file
13489 RET on headline as sublevel of the heading at cursor
13490 RET no heading at cursor position, level taken from context.
13491 Or use prefix arg to specify level manually.
13492 <left> on headline as same level, before current heading
13493 <right> on headline as same level, after current heading
13495 So the fastest way to store the note is to press RET RET to append it to
13496 the default file. This way your current train of thought is not
13497 interrupted, in accordance with the principles of remember.el.
13498 You can also get the fast execution without prompting by using
13499 C-u C-c C-c to exit the remember buffer. See also the variable
13500 `org-remember-store-without-prompt'.
13502 Before being stored away, the function ensures that the text has a
13503 headline, i.e. a first line that starts with a \"*\". If not, a headline
13504 is constructed from the current date and some additional data.
13506 If the variable `org-adapt-indentation' is non-nil, the entire text is
13507 also indented so that it starts in the same column as the headline
13508 \(i.e. after the stars).
13510 See also the variable `org-reverse-note-order'."
13511 (goto-char (point-min))
13512 (while (looking-at "^[ \t]*\n\\|^##.*\n")
13513 (replace-match ""))
13514 (goto-char (point-max))
13515 (catch 'quit
13516 (if org-note-abort (throw 'quit nil))
13517 (let* ((txt (buffer-substring (point-min) (point-max)))
13518 (fastp (org-xor (equal current-prefix-arg '(4))
13519 org-remember-store-without-prompt))
13520 (file (if fastp org-default-notes-file (org-get-org-file)))
13521 (heading org-remember-default-headline)
13522 (visiting (org-find-base-buffer-visiting file))
13523 (org-startup-folded nil)
13524 (org-startup-align-all-tables nil)
13525 (org-goto-start-pos 1)
13526 spos exitcmd level indent reversed)
13527 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
13528 (setq file (car org-remember-previous-location)
13529 heading (cdr org-remember-previous-location)))
13530 (setq current-prefix-arg nil)
13531 ;; Modify text so that it becomes a nice subtree which can be inserted
13532 ;; into an org tree.
13533 (let* ((lines (split-string txt "\n"))
13534 first)
13535 (setq first (car lines) lines (cdr lines))
13536 (if (string-match "^\\*+ " first)
13537 ;; Is already a headline
13538 (setq indent nil)
13539 ;; We need to add a headline: Use time and first buffer line
13540 (setq lines (cons first lines)
13541 first (concat "* " (current-time-string)
13542 " (" (remember-buffer-desc) ")")
13543 indent " "))
13544 (if (and org-adapt-indentation indent)
13545 (setq lines (mapcar
13546 (lambda (x)
13547 (if (string-match "\\S-" x)
13548 (concat indent x) x))
13549 lines)))
13550 (setq txt (concat first "\n"
13551 (mapconcat 'identity lines "\n"))))
13552 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
13553 (setq txt (replace-match "\n\n" t t txt))
13554 (if (string-match "[ \t\n]*\\'" txt)
13555 (setq txt (replace-match "\n" t t txt))))
13556 ;; Find the file
13557 (if (not visiting) (find-file-noselect file))
13558 (with-current-buffer (or visiting (get-file-buffer file))
13559 (unless (org-mode-p)
13560 (error "Target files for remember notes must be in Org-mode"))
13561 (save-excursion
13562 (save-restriction
13563 (widen)
13564 (and (goto-char (point-min))
13565 (not (re-search-forward "^\\* " nil t))
13566 (insert "\n* " (or heading "Notes") "\n"))
13567 (setq reversed (org-notes-order-reversed-p))
13569 ;; Find the default location
13570 (when (and heading (stringp heading) (string-match "\\S-" heading))
13571 (goto-char (point-min))
13572 (if (re-search-forward
13573 (concat "^\\*+[ \t]+" (regexp-quote heading)
13574 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13575 nil t)
13576 (setq org-goto-start-pos (match-beginning 0))
13577 (when fastp
13578 (goto-char (point-max))
13579 (unless (bolp) (newline))
13580 (insert "* " heading "\n")
13581 (setq org-goto-start-pos (point-at-bol 0)))))
13583 ;; Ask the User for a location
13584 (if fastp
13585 (setq spos org-goto-start-pos
13586 exitcmd 'return)
13587 (setq spos (org-get-location (current-buffer) org-remember-help)
13588 exitcmd (cdr spos)
13589 spos (car spos)))
13590 (if (not spos) (throw 'quit nil)) ; return nil to show we did
13591 ; not handle this note
13592 (goto-char spos)
13593 (cond ((org-on-heading-p t)
13594 (org-back-to-heading t)
13595 (setq level (funcall outline-level))
13596 (cond
13597 ((eq exitcmd 'return)
13598 ;; sublevel of current
13599 (setq org-remember-previous-location
13600 (cons (abbreviate-file-name file)
13601 (org-get-heading 'notags)))
13602 (if reversed
13603 (outline-next-heading)
13604 (org-end-of-subtree)
13605 (if (not (bolp))
13606 (if (looking-at "[ \t]*\n")
13607 (beginning-of-line 2)
13608 (end-of-line 1)
13609 (insert "\n"))))
13610 (bookmark-set "org-remember-last-stored")
13611 (org-paste-subtree (org-get-legal-level level 1) txt))
13612 ((eq exitcmd 'left)
13613 ;; before current
13614 (bookmark-set "org-remember-last-stored")
13615 (org-paste-subtree level txt))
13616 ((eq exitcmd 'right)
13617 ;; after current
13618 (org-end-of-subtree t)
13619 (bookmark-set "org-remember-last-stored")
13620 (org-paste-subtree level txt))
13621 (t (error "This should not happen"))))
13623 ((and (bobp) (not reversed))
13624 ;; Put it at the end, one level below level 1
13625 (save-restriction
13626 (widen)
13627 (goto-char (point-max))
13628 (if (not (bolp)) (newline))
13629 (bookmark-set "org-remember-last-stored")
13630 (org-paste-subtree (org-get-legal-level 1 1) txt)))
13632 ((and (bobp) reversed)
13633 ;; Put it at the start, as level 1
13634 (save-restriction
13635 (widen)
13636 (goto-char (point-min))
13637 (re-search-forward "^\\*+ " nil t)
13638 (beginning-of-line 1)
13639 (bookmark-set "org-remember-last-stored")
13640 (org-paste-subtree 1 txt)))
13642 ;; Put it right there, with automatic level determined by
13643 ;; org-paste-subtree or from prefix arg
13644 (bookmark-set "org-remember-last-stored")
13645 (org-paste-subtree
13646 (if (numberp current-prefix-arg) current-prefix-arg)
13647 txt)))
13648 (when remember-save-after-remembering
13649 (save-buffer)
13650 (if (not visiting) (kill-buffer (current-buffer)))))))))
13651 t) ;; return t to indicate that we took care of this note.
13653 (defun org-get-org-file ()
13654 "Read a filename, with default directory `org-directory'."
13655 (let ((default (or org-default-notes-file remember-data-file)))
13656 (read-file-name (format "File name [%s]: " default)
13657 (file-name-as-directory org-directory)
13658 default)))
13660 (defun org-notes-order-reversed-p ()
13661 "Check if the current file should receive notes in reversed order."
13662 (cond
13663 ((not org-reverse-note-order) nil)
13664 ((eq t org-reverse-note-order) t)
13665 ((not (listp org-reverse-note-order)) nil)
13666 (t (catch 'exit
13667 (let ((all org-reverse-note-order)
13668 entry)
13669 (while (setq entry (pop all))
13670 (if (string-match (car entry) buffer-file-name)
13671 (throw 'exit (cdr entry))))
13672 nil)))))
13674 ;;; Refiling
13676 (defvar org-refile-target-table nil
13677 "The list of refile targets, created by `org-refile'.")
13679 (defvar org-agenda-new-buffers nil
13680 "Buffers created to visit agenda files.")
13682 (defun org-get-refile-targets ()
13683 "Produce a table with refile targets."
13684 (let ((entries org-refile-targets)
13685 org-agenda-new-files targets txt re files f desc descre)
13686 (while (setq entry (pop entries))
13687 (setq files (car entry) desc (cdr entry))
13688 (cond
13689 ((null files) (setq files (list (current-buffer))))
13690 ((eq files 'org-agenda-files)
13691 (setq files (org-agenda-files 'unrestricted)))
13692 ((and (symbolp files) (fboundp files))
13693 (setq files (funcall files)))
13694 ((and (symbolp files) (boundp files))
13695 (setq files (symbol-value files))))
13696 (if (stringp files) (setq files (list files)))
13697 (cond
13698 ((eq (car desc) :tag)
13699 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
13700 ((eq (car desc) :todo)
13701 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
13702 ((eq (car desc) :regexp)
13703 (setq descre (cdr desc)))
13704 ((eq (car desc) :level)
13705 (setq descre (concat "^\\*\\{" (number-to-string
13706 (if org-odd-levels-only
13707 (1- (* 2 (cdr desc)))
13708 (cdr desc)))
13709 "\\}[ \t]")))
13710 ((eq (car desc) :maxlevel)
13711 (setq descre (concat "^\\*\\{1," (number-to-string
13712 (if org-odd-levels-only
13713 (1- (* 2 (cdr desc)))
13714 (cdr desc)))
13715 "\\}[ \t]")))
13716 (t (error "Bad refiling target description %s" desc)))
13717 (while (setq f (pop files))
13718 (save-excursion
13719 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
13720 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
13721 (save-excursion
13722 (save-restriction
13723 (widen)
13724 (goto-char (point-min))
13725 (while (re-search-forward descre nil t)
13726 (goto-char (point-at-bol))
13727 (when (looking-at org-complex-heading-regexp)
13728 (setq txt (match-string 4)
13729 re (concat "^" (regexp-quote
13730 (buffer-substring (match-beginning 1)
13731 (match-end 4)))))
13732 (if (match-end 5) (setq re (concat re "[ \t]+"
13733 (regexp-quote
13734 (match-string 5)))))
13735 (setq re (concat re "[ \t]*$"))
13736 (when org-refile-use-outline-path
13737 (setq txt (mapconcat 'identity
13738 (append (org-get-outline-path)
13739 (list txt))
13740 "/")))
13741 (push (list txt f re (point)) targets))
13742 (goto-char (point-at-eol))))))))
13743 (org-release-buffers org-agenda-new-buffers)
13744 (nreverse targets)))
13746 (defun org-get-outline-path ()
13747 (let (rtn)
13748 (save-excursion
13749 (while (org-up-heading-safe)
13750 (when (looking-at org-complex-heading-regexp)
13751 (push (org-match-string-no-properties 4) rtn)))
13752 rtn)))
13754 (defun org-refile (&optional reversed-or-update)
13755 "Move the entry at point to another heading.
13756 The list of target headings is compiled using the information in
13757 `org-refile-targets', which see. This list is created upon first use, and
13758 you can update it by calling this command with a double prefix (`C-u C-u').
13760 At the target location, the entry is filed as a subitem of the target heading.
13761 Depending on `org-reverse-note-order', the new subitem will either be the
13762 first of the last subitem. A single C-u prefix will toggle the value of this
13763 variable for the duration of the command."
13764 (interactive "P")
13765 (if (equal reversed-or-update '(16))
13766 (progn
13767 (setq org-refile-target-table (org-get-refile-targets))
13768 (message "Refile targets updated (%d targets)"
13769 (length org-refile-target-table)))
13770 (when (or (not org-refile-target-table)
13771 (and (= (length org-refile-targets) 1)
13772 (not (caar org-refile-targets))))
13773 (setq org-refile-target-table (org-get-refile-targets)))
13774 (unless org-refile-target-table
13775 (error "No refile targets"))
13776 (let* ((cbuf (current-buffer))
13777 (filename (buffer-file-name (buffer-base-buffer cbuf)))
13778 (fname (and filename (file-truename filename)))
13779 (tbl (mapcar
13780 (lambda (x)
13781 (if (not (equal fname (file-truename (nth 1 x))))
13782 (cons (concat (car x) " (" (file-name-nondirectory
13783 (nth 1 x)) ")")
13784 (cdr x))
13786 org-refile-target-table))
13787 (completion-ignore-case t)
13788 pos it nbuf file re level reversed)
13789 (when (setq it (completing-read "Refile to: " tbl
13790 nil t nil 'org-refile-history))
13791 (setq it (assoc it tbl)
13792 file (nth 1 it)
13793 re (nth 2 it))
13794 (org-copy-special)
13795 (save-excursion
13796 (set-buffer (setq nbuf (or (find-buffer-visiting file)
13797 (find-file-noselect file))))
13798 (setq reversed (org-notes-order-reversed-p))
13799 (if (equal reversed-or-update '(16)) (setq reversed (not reversed)))
13800 (save-excursion
13801 (save-restriction
13802 (widen)
13803 (goto-char (point-min))
13804 (unless (re-search-forward re nil t)
13805 (error "Cannot find target location - try again with `C-u' prefix."))
13806 (goto-char (match-beginning 0))
13807 (looking-at outline-regexp)
13808 (setq level (org-get-legal-level (funcall outline-level) 1))
13809 (goto-char (or (save-excursion
13810 (if reversed
13811 (outline-next-heading)
13812 (outline-get-next-sibling)))
13813 (point-max)))
13814 (org-paste-subtree level))))
13815 (org-cut-special)
13816 (message "Entry refiled to \"%s\"" (car it))))))
13818 ;;;; Dynamic blocks
13820 (defun org-find-dblock (name)
13821 "Find the first dynamic block with name NAME in the buffer.
13822 If not found, stay at current position and return nil."
13823 (let (pos)
13824 (save-excursion
13825 (goto-char (point-min))
13826 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
13827 nil t)
13828 (match-beginning 0))))
13829 (if pos (goto-char pos))
13830 pos))
13832 (defconst org-dblock-start-re
13833 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
13834 "Matches the startline of a dynamic block, with parameters.")
13836 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
13837 "Matches the end of a dyhamic block.")
13839 (defun org-create-dblock (plist)
13840 "Create a dynamic block section, with parameters taken from PLIST.
13841 PLIST must containe a :name entry which is used as name of the block."
13842 (unless (bolp) (newline))
13843 (let ((name (plist-get plist :name)))
13844 (insert "#+BEGIN: " name)
13845 (while plist
13846 (if (eq (car plist) :name)
13847 (setq plist (cddr plist))
13848 (insert " " (prin1-to-string (pop plist)))))
13849 (insert "\n\n#+END:\n")
13850 (beginning-of-line -2)))
13852 (defun org-prepare-dblock ()
13853 "Prepare dynamic block for refresh.
13854 This empties the block, puts the cursor at the insert position and returns
13855 the property list including an extra property :name with the block name."
13856 (unless (looking-at org-dblock-start-re)
13857 (error "Not at a dynamic block"))
13858 (let* ((begdel (1+ (match-end 0)))
13859 (name (org-no-properties (match-string 1)))
13860 (params (append (list :name name)
13861 (read (concat "(" (match-string 3) ")")))))
13862 (unless (re-search-forward org-dblock-end-re nil t)
13863 (error "Dynamic block not terminated"))
13864 (delete-region begdel (match-beginning 0))
13865 (goto-char begdel)
13866 (open-line 1)
13867 params))
13869 (defun org-map-dblocks (&optional command)
13870 "Apply COMMAND to all dynamic blocks in the current buffer.
13871 If COMMAND is not given, use `org-update-dblock'."
13872 (let ((cmd (or command 'org-update-dblock))
13873 pos)
13874 (save-excursion
13875 (goto-char (point-min))
13876 (while (re-search-forward org-dblock-start-re nil t)
13877 (goto-char (setq pos (match-beginning 0)))
13878 (condition-case nil
13879 (funcall cmd)
13880 (error (message "Error during update of dynamic block")))
13881 (goto-char pos)
13882 (unless (re-search-forward org-dblock-end-re nil t)
13883 (error "Dynamic block not terminated"))))))
13885 (defun org-dblock-update (&optional arg)
13886 "User command for updating dynamic blocks.
13887 Update the dynamic block at point. With prefix ARG, update all dynamic
13888 blocks in the buffer."
13889 (interactive "P")
13890 (if arg
13891 (org-update-all-dblocks)
13892 (or (looking-at org-dblock-start-re)
13893 (org-beginning-of-dblock))
13894 (org-update-dblock)))
13896 (defun org-update-dblock ()
13897 "Update the dynamic block at point
13898 This means to empty the block, parse for parameters and then call
13899 the correct writing function."
13900 (save-window-excursion
13901 (let* ((pos (point))
13902 (line (org-current-line))
13903 (params (org-prepare-dblock))
13904 (name (plist-get params :name))
13905 (cmd (intern (concat "org-dblock-write:" name))))
13906 (message "Updating dynamic block `%s' at line %d..." name line)
13907 (funcall cmd params)
13908 (message "Updating dynamic block `%s' at line %d...done" name line)
13909 (goto-char pos))))
13911 (defun org-beginning-of-dblock ()
13912 "Find the beginning of the dynamic block at point.
13913 Error if there is no scuh block at point."
13914 (let ((pos (point))
13915 beg)
13916 (end-of-line 1)
13917 (if (and (re-search-backward org-dblock-start-re nil t)
13918 (setq beg (match-beginning 0))
13919 (re-search-forward org-dblock-end-re nil t)
13920 (> (match-end 0) pos))
13921 (goto-char beg)
13922 (goto-char pos)
13923 (error "Not in a dynamic block"))))
13925 (defun org-update-all-dblocks ()
13926 "Update all dynamic blocks in the buffer.
13927 This function can be used in a hook."
13928 (when (org-mode-p)
13929 (org-map-dblocks 'org-update-dblock)))
13932 ;;;; Completion
13934 (defconst org-additional-option-like-keywords
13935 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
13936 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
13937 "BEGIN_EXAMPLE" "END_EXAMPLE"))
13939 (defun org-complete (&optional arg)
13940 "Perform completion on word at point.
13941 At the beginning of a headline, this completes TODO keywords as given in
13942 `org-todo-keywords'.
13943 If the current word is preceded by a backslash, completes the TeX symbols
13944 that are supported for HTML support.
13945 If the current word is preceded by \"#+\", completes special words for
13946 setting file options.
13947 In the line after \"#+STARTUP:, complete valid keywords.\"
13948 At all other locations, this simply calls the value of
13949 `org-completion-fallback-command'."
13950 (interactive "P")
13951 (org-without-partial-completion
13952 (catch 'exit
13953 (let* ((end (point))
13954 (beg1 (save-excursion
13955 (skip-chars-backward (org-re "[:alnum:]_@"))
13956 (point)))
13957 (beg (save-excursion
13958 (skip-chars-backward "a-zA-Z0-9_:$")
13959 (point)))
13960 (confirm (lambda (x) (stringp (car x))))
13961 (searchhead (equal (char-before beg) ?*))
13962 (tag (and (equal (char-before beg1) ?:)
13963 (equal (char-after (point-at-bol)) ?*)))
13964 (prop (and (equal (char-before beg1) ?:)
13965 (not (equal (char-after (point-at-bol)) ?*))))
13966 (texp (equal (char-before beg) ?\\))
13967 (link (equal (char-before beg) ?\[))
13968 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
13969 beg)
13970 "#+"))
13971 (startup (string-match "^#\\+STARTUP:.*"
13972 (buffer-substring (point-at-bol) (point))))
13973 (completion-ignore-case opt)
13974 (type nil)
13975 (tbl nil)
13976 (table (cond
13977 (opt
13978 (setq type :opt)
13979 (append
13980 (mapcar
13981 (lambda (x)
13982 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
13983 (cons (match-string 2 x) (match-string 1 x)))
13984 (org-split-string (org-get-current-options) "\n"))
13985 (mapcar 'list org-additional-option-like-keywords)))
13986 (startup
13987 (setq type :startup)
13988 org-startup-options)
13989 (link (append org-link-abbrev-alist-local
13990 org-link-abbrev-alist))
13991 (texp
13992 (setq type :tex)
13993 org-html-entities)
13994 ((string-match "\\`\\*+[ \t]+\\'"
13995 (buffer-substring (point-at-bol) beg))
13996 (setq type :todo)
13997 (mapcar 'list org-todo-keywords-1))
13998 (searchhead
13999 (setq type :searchhead)
14000 (save-excursion
14001 (goto-char (point-min))
14002 (while (re-search-forward org-todo-line-regexp nil t)
14003 (push (list
14004 (org-make-org-heading-search-string
14005 (match-string 3) t))
14006 tbl)))
14007 tbl)
14008 (tag (setq type :tag beg beg1)
14009 (or org-tag-alist (org-get-buffer-tags)))
14010 (prop (setq type :prop beg beg1)
14011 (mapcar 'list (org-buffer-property-keys)))
14012 (t (progn
14013 (call-interactively org-completion-fallback-command)
14014 (throw 'exit nil)))))
14015 (pattern (buffer-substring-no-properties beg end))
14016 (completion (try-completion pattern table confirm)))
14017 (cond ((eq completion t)
14018 (if (not (assoc (upcase pattern) table))
14019 (message "Already complete")
14020 (if (equal type :opt)
14021 (insert (substring (cdr (assoc (upcase pattern) table))
14022 (length pattern)))
14023 (if (memq type '(:tag :prop)) (insert ":")))))
14024 ((null completion)
14025 (message "Can't find completion for \"%s\"" pattern)
14026 (ding))
14027 ((not (string= pattern completion))
14028 (delete-region beg end)
14029 (if (string-match " +$" completion)
14030 (setq completion (replace-match "" t t completion)))
14031 (insert completion)
14032 (if (get-buffer-window "*Completions*")
14033 (delete-window (get-buffer-window "*Completions*")))
14034 (if (assoc completion table)
14035 (if (eq type :todo) (insert " ")
14036 (if (memq type '(:tag :prop)) (insert ":"))))
14037 (if (and (equal type :opt) (assoc completion table))
14038 (message "%s" (substitute-command-keys
14039 "Press \\[org-complete] again to insert example settings"))))
14041 (message "Making completion list...")
14042 (let ((list (sort (all-completions pattern table confirm)
14043 'string<)))
14044 (with-output-to-temp-buffer "*Completions*"
14045 (condition-case nil
14046 ;; Protection needed for XEmacs and emacs 21
14047 (display-completion-list list pattern)
14048 (error (display-completion-list list)))))
14049 (message "Making completion list...%s" "done")))))))
14051 ;;;; TODO, DEADLINE, Comments
14053 (defun org-toggle-comment ()
14054 "Change the COMMENT state of an entry."
14055 (interactive)
14056 (save-excursion
14057 (org-back-to-heading)
14058 (let (case-fold-search)
14059 (if (looking-at (concat outline-regexp
14060 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14061 (replace-match "" t t nil 1)
14062 (if (looking-at outline-regexp)
14063 (progn
14064 (goto-char (match-end 0))
14065 (insert org-comment-string " ")))))))
14067 (defvar org-last-todo-state-is-todo nil
14068 "This is non-nil when the last TODO state change led to a TODO state.
14069 If the last change removed the TODO tag or switched to DONE, then
14070 this is nil.")
14072 (defvar org-setting-tags nil) ; dynamically skiped
14074 ;; FIXME: better place
14075 (defun org-property-or-variable-value (var &optional inherit)
14076 "Check if there is a property fixing the value of VAR.
14077 If yes, return this value. If not, return the current value of the variable."
14078 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14079 (if (and prop (stringp prop) (string-match "\\S-" prop))
14080 (read prop)
14081 (symbol-value var))))
14083 (defun org-parse-local-options (string var)
14084 "Parse STRING for startup setting relevant for variable VAR."
14085 (let ((rtn (symbol-value var))
14086 e opts)
14087 (save-match-data
14088 (if (or (not string) (not (string-match "\\S-" string)))
14090 (setq opts (delq nil (mapcar (lambda (x)
14091 (setq e (assoc x org-startup-options))
14092 (if (eq (nth 1 e) var) e nil))
14093 (org-split-string string "[ \t]+"))))
14094 (if (not opts)
14096 (setq rtn nil)
14097 (while (setq e (pop opts))
14098 (if (not (nth 3 e))
14099 (setq rtn (nth 2 e))
14100 (if (not (listp rtn)) (setq rtn nil))
14101 (push (nth 2 e) rtn)))
14102 rtn)))))
14104 (defvar org-blocker-hook nil
14105 "Hook for functions that are allowed to block a state change.
14107 Each function gets as its single argument a property list, see
14108 `org-trigger-hook' for more information about this list.
14110 If any of the functions in this hook returns nil, the state change
14111 is blocked.")
14113 (defvar org-trigger-hook nil
14114 "Hook for functions that are triggered by a state change.
14116 Each function gets as its single argument a property list with at least
14117 the following elements:
14119 (:type type-of-change :position pos-at-entry-start
14120 :from old-state :to new-state)
14122 Depending on the type, more properties may be present.
14124 This mechanism is currently implemented for:
14126 TODO state changes
14127 ------------------
14128 :type todo-state-change
14129 :from previous state (keyword as a string), or nil
14130 :to new state (keyword as a string), or nil")
14133 (defun org-todo (&optional arg)
14134 "Change the TODO state of an item.
14135 The state of an item is given by a keyword at the start of the heading,
14136 like
14137 *** TODO Write paper
14138 *** DONE Call mom
14140 The different keywords are specified in the variable `org-todo-keywords'.
14141 By default the available states are \"TODO\" and \"DONE\".
14142 So for this example: when the item starts with TODO, it is changed to DONE.
14143 When it starts with DONE, the DONE is removed. And when neither TODO nor
14144 DONE are present, add TODO at the beginning of the heading.
14146 With C-u prefix arg, use completion to determine the new state.
14147 With numeric prefix arg, switch to that state.
14149 For calling through lisp, arg is also interpreted in the following way:
14150 'none -> empty state
14151 \"\"(empty string) -> switch to empty state
14152 'done -> switch to DONE
14153 'nextset -> switch to the next set of keywords
14154 'previousset -> switch to the previous set of keywords
14155 \"WAITING\" -> switch to the specified keyword, but only if it
14156 really is a member of `org-todo-keywords'."
14157 (interactive "P")
14158 (save-excursion
14159 (catch 'exit
14160 (org-back-to-heading)
14161 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14162 (or (looking-at (concat " +" org-todo-regexp " *"))
14163 (looking-at " *"))
14164 (let* ((match-data (match-data))
14165 (startpos (point-at-bol))
14166 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14167 (org-log-done (org-parse-local-options logging 'org-log-done))
14168 (org-log-repeat (org-parse-local-options logging 'org-log-repeat))
14169 (this (match-string 1))
14170 (hl-pos (match-beginning 0))
14171 (head (org-get-todo-sequence-head this))
14172 (ass (assoc head org-todo-kwd-alist))
14173 (interpret (nth 1 ass))
14174 (done-word (nth 3 ass))
14175 (final-done-word (nth 4 ass))
14176 (last-state (or this ""))
14177 (completion-ignore-case t)
14178 (member (member this org-todo-keywords-1))
14179 (tail (cdr member))
14180 (state (cond
14181 ((and org-todo-key-trigger
14182 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14183 (and (not arg) org-use-fast-todo-selection
14184 (not (eq org-use-fast-todo-selection 'prefix)))))
14185 ;; Use fast selection
14186 (org-fast-todo-selection))
14187 ((and (equal arg '(4))
14188 (or (not org-use-fast-todo-selection)
14189 (not org-todo-key-trigger)))
14190 ;; Read a state with completion
14191 (completing-read "State: " (mapcar (lambda(x) (list x))
14192 org-todo-keywords-1)
14193 nil t))
14194 ((eq arg 'right)
14195 (if this
14196 (if tail (car tail) nil)
14197 (car org-todo-keywords-1)))
14198 ((eq arg 'left)
14199 (if (equal member org-todo-keywords-1)
14201 (if this
14202 (nth (- (length org-todo-keywords-1) (length tail) 2)
14203 org-todo-keywords-1)
14204 (org-last org-todo-keywords-1))))
14205 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14206 (setq arg nil))) ; hack to fall back to cycling
14207 (arg
14208 ;; user or caller requests a specific state
14209 (cond
14210 ((equal arg "") nil)
14211 ((eq arg 'none) nil)
14212 ((eq arg 'done) (or done-word (car org-done-keywords)))
14213 ((eq arg 'nextset)
14214 (or (car (cdr (member head org-todo-heads)))
14215 (car org-todo-heads)))
14216 ((eq arg 'previousset)
14217 (let ((org-todo-heads (reverse org-todo-heads)))
14218 (or (car (cdr (member head org-todo-heads)))
14219 (car org-todo-heads))))
14220 ((car (member arg org-todo-keywords-1)))
14221 ((nth (1- (prefix-numeric-value arg))
14222 org-todo-keywords-1))))
14223 ((null member) (or head (car org-todo-keywords-1)))
14224 ((equal this final-done-word) nil) ;; -> make empty
14225 ((null tail) nil) ;; -> first entry
14226 ((eq interpret 'sequence)
14227 (car tail))
14228 ((memq interpret '(type priority))
14229 (if (eq this-command last-command)
14230 (car tail)
14231 (if (> (length tail) 0)
14232 (or done-word (car org-done-keywords))
14233 nil)))
14234 (t nil)))
14235 (next (if state (concat " " state " ") " "))
14236 (change-plist (list :type 'todo-state-change :from this :to state
14237 :position startpos))
14238 dostates)
14239 (when org-blocker-hook
14240 (unless (save-excursion
14241 (save-match-data
14242 (run-hook-with-args-until-failure
14243 'org-blocker-hook change-plist)))
14244 (if (interactive-p)
14245 (error "TODO state change from %s to %s blocked" this state)
14246 ;; fail silently
14247 (message "TODO state change from %s to %s blocked" this state)
14248 (throw 'exit nil))))
14249 (store-match-data match-data)
14250 (replace-match next t t)
14251 (unless (pos-visible-in-window-p hl-pos)
14252 (message "TODO state changed to %s" (org-trim next)))
14253 (unless head
14254 (setq head (org-get-todo-sequence-head state)
14255 ass (assoc head org-todo-kwd-alist)
14256 interpret (nth 1 ass)
14257 done-word (nth 3 ass)
14258 final-done-word (nth 4 ass)))
14259 (when (memq arg '(nextset previousset))
14260 (message "Keyword-Set %d/%d: %s"
14261 (- (length org-todo-sets) -1
14262 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14263 (length org-todo-sets)
14264 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14265 (setq org-last-todo-state-is-todo
14266 (not (member state org-done-keywords)))
14267 (when (and org-log-done (not (memq arg '(nextset previousset))))
14268 (setq dostates (and (listp org-log-done) (memq 'state org-log-done)
14269 (or (not org-todo-log-states)
14270 (member state org-todo-log-states))))
14272 (cond
14273 ((and state (member state org-not-done-keywords)
14274 (not (member this org-not-done-keywords)))
14275 ;; This is now a todo state and was not one before
14276 ;; Remove any CLOSED timestamp, and possibly log the state change
14277 (org-add-planning-info nil nil 'closed)
14278 (and dostates (org-add-log-maybe 'state state 'findpos)))
14279 ((and state dostates)
14280 ;; This is a non-nil state, and we need to log it
14281 (org-add-log-maybe 'state state 'findpos))
14282 ((and (member state org-done-keywords)
14283 (not (member this org-done-keywords)))
14284 ;; It is now done, and it was not done before
14285 (org-add-planning-info 'closed (org-current-time))
14286 (org-add-log-maybe 'done state 'findpos))))
14287 ;; Fixup tag positioning
14288 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14289 (run-hooks 'org-after-todo-state-change-hook)
14290 (and (member state org-done-keywords) (org-auto-repeat-maybe))
14291 (if (and arg (not (member state org-done-keywords)))
14292 (setq head (org-get-todo-sequence-head state)))
14293 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14294 ;; Fixup cursor location if close to the keyword
14295 (if (and (outline-on-heading-p)
14296 (not (bolp))
14297 (save-excursion (beginning-of-line 1)
14298 (looking-at org-todo-line-regexp))
14299 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14300 (progn
14301 (goto-char (or (match-end 2) (match-end 1)))
14302 (just-one-space)))
14303 (when org-trigger-hook
14304 (save-excursion
14305 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14307 (defun org-get-todo-sequence-head (kwd)
14308 "Return the head of the TODO sequence to which KWD belongs.
14309 If KWD is not set, check if there is a text property remembering the
14310 right sequence."
14311 (let (p)
14312 (cond
14313 ((not kwd)
14314 (or (get-text-property (point-at-bol) 'org-todo-head)
14315 (progn
14316 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14317 nil (point-at-eol)))
14318 (get-text-property p 'org-todo-head))))
14319 ((not (member kwd org-todo-keywords-1))
14320 (car org-todo-keywords-1))
14321 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14323 (defun org-fast-todo-selection ()
14324 "Fast TODO keyword selection with single keys.
14325 Returns the new TODO keyword, or nil if no state change should occur."
14326 (let* ((fulltable org-todo-key-alist)
14327 (done-keywords org-done-keywords) ;; needed for the faces.
14328 (maxlen (apply 'max (mapcar
14329 (lambda (x)
14330 (if (stringp (car x)) (string-width (car x)) 0))
14331 fulltable)))
14332 (expert nil)
14333 (fwidth (+ maxlen 3 1 3))
14334 (ncol (/ (- (window-width) 4) fwidth))
14335 tg cnt e c tbl
14336 groups ingroup)
14337 (save-window-excursion
14338 (if expert
14339 (set-buffer (get-buffer-create " *Org todo*"))
14340 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14341 (erase-buffer)
14342 (org-set-local 'org-done-keywords done-keywords)
14343 (setq tbl fulltable cnt 0)
14344 (while (setq e (pop tbl))
14345 (cond
14346 ((equal e '(:startgroup))
14347 (push '() groups) (setq ingroup t)
14348 (when (not (= cnt 0))
14349 (setq cnt 0)
14350 (insert "\n"))
14351 (insert "{ "))
14352 ((equal e '(:endgroup))
14353 (setq ingroup nil cnt 0)
14354 (insert "}\n"))
14356 (setq tg (car e) c (cdr e))
14357 (if ingroup (push tg (car groups)))
14358 (setq tg (org-add-props tg nil 'face
14359 (org-get-todo-face tg)))
14360 (if (and (= cnt 0) (not ingroup)) (insert " "))
14361 (insert "[" c "] " tg (make-string
14362 (- fwidth 4 (length tg)) ?\ ))
14363 (when (= (setq cnt (1+ cnt)) ncol)
14364 (insert "\n")
14365 (if ingroup (insert " "))
14366 (setq cnt 0)))))
14367 (insert "\n")
14368 (goto-char (point-min))
14369 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14370 (fit-window-to-buffer))
14371 (message "[a-z..]:Set [SPC]:clear")
14372 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14373 (cond
14374 ((or (= c ?\C-g)
14375 (and (= c ?q) (not (rassoc c fulltable))))
14376 (setq quit-flag t))
14377 ((= c ?\ ) nil)
14378 ((setq e (rassoc c fulltable) tg (car e))
14380 (t (setq quit-flag t))))))
14382 (defun org-get-repeat ()
14383 "Check if tere is a deadline/schedule with repeater in this entry."
14384 (save-match-data
14385 (save-excursion
14386 (org-back-to-heading t)
14387 (if (re-search-forward
14388 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
14389 (match-string 1)))))
14391 (defvar org-last-changed-timestamp)
14392 (defvar org-log-post-message)
14393 (defun org-auto-repeat-maybe ()
14394 "Check if the current headline contains a repeated deadline/schedule.
14395 If yes, set TODO state back to what it was and change the base date
14396 of repeating deadline/scheduled time stamps to new date.
14397 This function should be run in the `org-after-todo-state-change-hook'."
14398 ;; last-state is dynamically scoped into this function
14399 (let* ((repeat (org-get-repeat))
14400 (aa (assoc last-state org-todo-kwd-alist))
14401 (interpret (nth 1 aa))
14402 (head (nth 2 aa))
14403 (done-word (nth 3 aa))
14404 (whata '(("d" . day) ("m" . month) ("y" . year)))
14405 (msg "Entry repeats: ")
14406 (org-log-done)
14407 re type n what ts)
14408 (when repeat
14409 (org-todo (if (eq interpret 'type) last-state head))
14410 (when (and org-log-repeat
14411 (not (memq 'org-add-log-note
14412 (default-value 'post-command-hook))))
14413 ;; Make sure a note is taken
14414 (let ((org-log-done '(done)))
14415 (org-add-log-maybe 'done (or done-word (car org-done-keywords))
14416 'findpos)))
14417 (org-back-to-heading t)
14418 (org-add-planning-info nil nil 'closed)
14419 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
14420 org-deadline-time-regexp "\\)"))
14421 (while (re-search-forward
14422 re (save-excursion (outline-next-heading) (point)) t)
14423 (setq type (if (match-end 1) org-scheduled-string org-deadline-string)
14424 ts (match-string (if (match-end 2) 2 4)))
14425 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
14426 (setq n (string-to-number (match-string 1 ts))
14427 what (match-string 2 ts))
14428 (if (equal what "w") (setq n (* n 7) what "d"))
14429 (org-timestamp-change n (cdr (assoc what whata))))
14430 (setq msg (concat msg type org-last-changed-timestamp " ")))
14431 (setq org-log-post-message msg)
14432 (message "%s" msg))))
14434 (defun org-show-todo-tree (arg)
14435 "Make a compact tree which shows all headlines marked with TODO.
14436 The tree will show the lines where the regexp matches, and all higher
14437 headlines above the match.
14438 With \\[universal-argument] prefix, also show the DONE entries.
14439 With a numeric prefix N, construct a sparse tree for the Nth element
14440 of `org-todo-keywords-1'."
14441 (interactive "P")
14442 (let ((case-fold-search nil)
14443 (kwd-re
14444 (cond ((null arg) org-not-done-regexp)
14445 ((equal arg '(4))
14446 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
14447 (mapcar 'list org-todo-keywords-1))))
14448 (concat "\\("
14449 (mapconcat 'identity (org-split-string kwd "|") "\\|")
14450 "\\)\\>")))
14451 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
14452 (regexp-quote (nth (1- (prefix-numeric-value arg))
14453 org-todo-keywords-1)))
14454 (t (error "Invalid prefix argument: %s" arg)))))
14455 (message "%d TODO entries found"
14456 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
14458 (defun org-deadline (&optional remove)
14459 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
14460 With argument REMOVE, remove any deadline from the item."
14461 (interactive "P")
14462 (if remove
14463 (progn
14464 (org-add-planning-info nil nil 'deadline)
14465 (message "Item no longer has a deadline."))
14466 (org-add-planning-info 'deadline nil 'closed)))
14468 (defun org-schedule (&optional remove)
14469 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
14470 With argument REMOVE, remove any scheduling date from the item."
14471 (interactive "P")
14472 (if remove
14473 (progn
14474 (org-add-planning-info nil nil 'scheduled)
14475 (message "Item is no longer scheduled."))
14476 (org-add-planning-info 'scheduled nil 'closed)))
14478 (defun org-add-planning-info (what &optional time &rest remove)
14479 "Insert new timestamp with keyword in the line directly after the headline.
14480 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
14481 If non is given, the user is prompted for a date.
14482 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
14483 be removed."
14484 (interactive)
14485 (let (org-time-was-given org-end-time-was-given)
14486 (when what (setq time (or time (org-read-date nil 'to-time))))
14487 (when (and org-insert-labeled-timestamps-at-point
14488 (member what '(scheduled deadline)))
14489 (insert
14490 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
14491 (org-insert-time-stamp time org-time-was-given
14492 nil nil nil (list org-end-time-was-given))
14493 (setq what nil))
14494 (save-excursion
14495 (save-restriction
14496 (let (col list elt ts buffer-invisibility-spec)
14497 (org-back-to-heading t)
14498 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
14499 (goto-char (match-end 1))
14500 (setq col (current-column))
14501 (goto-char (match-end 0))
14502 (if (eobp) (insert "\n") (forward-char 1))
14503 (if (and (not (looking-at outline-regexp))
14504 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
14505 "[^\r\n]*"))
14506 (not (equal (match-string 1) org-clock-string)))
14507 (narrow-to-region (match-beginning 0) (match-end 0))
14508 (insert-before-markers "\n")
14509 (backward-char 1)
14510 (narrow-to-region (point) (point))
14511 (indent-to-column col))
14512 ;; Check if we have to remove something.
14513 (setq list (cons what remove))
14514 (while list
14515 (setq elt (pop list))
14516 (goto-char (point-min))
14517 (when (or (and (eq elt 'scheduled)
14518 (re-search-forward org-scheduled-time-regexp nil t))
14519 (and (eq elt 'deadline)
14520 (re-search-forward org-deadline-time-regexp nil t))
14521 (and (eq elt 'closed)
14522 (re-search-forward org-closed-time-regexp nil t)))
14523 (replace-match "")
14524 (if (looking-at "--+<[^>]+>") (replace-match ""))
14525 (if (looking-at " +") (replace-match ""))))
14526 (goto-char (point-max))
14527 (when what
14528 (insert
14529 (if (not (equal (char-before) ?\ )) " " "")
14530 (cond ((eq what 'scheduled) org-scheduled-string)
14531 ((eq what 'deadline) org-deadline-string)
14532 ((eq what 'closed) org-closed-string))
14533 " ")
14534 (setq ts (org-insert-time-stamp
14535 time
14536 (or org-time-was-given
14537 (and (eq what 'closed) org-log-done-with-time))
14538 (eq what 'closed)
14539 nil nil (list org-end-time-was-given)))
14540 (end-of-line 1))
14541 (goto-char (point-min))
14542 (widen)
14543 (if (looking-at "[ \t]+\r?\n")
14544 (replace-match ""))
14545 ts)))))
14547 (defvar org-log-note-marker (make-marker))
14548 (defvar org-log-note-purpose nil)
14549 (defvar org-log-note-state nil)
14550 (defvar org-log-note-window-configuration nil)
14551 (defvar org-log-note-return-to (make-marker))
14552 (defvar org-log-post-message nil
14553 "Message to be displayed after a log note has been stored.
14554 The auto-repeater uses this.")
14556 (defun org-add-log-maybe (&optional purpose state findpos)
14557 "Set up the post command hook to take a note."
14558 (save-excursion
14559 (when (and (listp org-log-done)
14560 (memq purpose org-log-done))
14561 (when findpos
14562 (org-back-to-heading t)
14563 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
14564 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
14565 "[^\r\n]*\\)?"))
14566 (goto-char (match-end 0))
14567 (unless org-log-states-order-reversed
14568 (and (= (char-after) ?\n) (forward-char 1))
14569 (org-skip-over-state-notes)
14570 (skip-chars-backward " \t\n\r")))
14571 (move-marker org-log-note-marker (point))
14572 (setq org-log-note-purpose purpose)
14573 (setq org-log-note-state state)
14574 (add-hook 'post-command-hook 'org-add-log-note 'append))))
14576 (defun org-skip-over-state-notes ()
14577 "Skip past the list of State notes in an entry."
14578 (if (looking-at "\n[ \t]*- State") (forward-char 1))
14579 (while (looking-at "[ \t]*- State")
14580 (condition-case nil
14581 (org-next-item)
14582 (error (org-end-of-item)))))
14584 (defun org-add-log-note (&optional purpose)
14585 "Pop up a window for taking a note, and add this note later at point."
14586 (remove-hook 'post-command-hook 'org-add-log-note)
14587 (setq org-log-note-window-configuration (current-window-configuration))
14588 (delete-other-windows)
14589 (move-marker org-log-note-return-to (point))
14590 (switch-to-buffer (marker-buffer org-log-note-marker))
14591 (goto-char org-log-note-marker)
14592 (org-switch-to-buffer-other-window "*Org Note*")
14593 (erase-buffer)
14594 (let ((org-inhibit-startup t)) (org-mode))
14595 (insert (format "# Insert note for %s.
14596 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
14597 (cond
14598 ((eq org-log-note-purpose 'clock-out) "stopped clock")
14599 ((eq org-log-note-purpose 'done) "closed todo item")
14600 ((eq org-log-note-purpose 'state)
14601 (format "state change to \"%s\"" org-log-note-state))
14602 (t (error "This should not happen")))))
14603 (org-set-local 'org-finish-function 'org-store-log-note))
14605 (defun org-store-log-note ()
14606 "Finish taking a log note, and insert it to where it belongs."
14607 (let ((txt (buffer-string))
14608 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
14609 lines ind)
14610 (kill-buffer (current-buffer))
14611 (while (string-match "\\`#.*\n[ \t\n]*" txt)
14612 (setq txt (replace-match "" t t txt)))
14613 (if (string-match "\\s-+\\'" txt)
14614 (setq txt (replace-match "" t t txt)))
14615 (setq lines (org-split-string txt "\n"))
14616 (when (and note (string-match "\\S-" note))
14617 (setq note
14618 (org-replace-escapes
14619 note
14620 (list (cons "%u" (user-login-name))
14621 (cons "%U" user-full-name)
14622 (cons "%t" (format-time-string
14623 (org-time-stamp-format 'long 'inactive)
14624 (current-time)))
14625 (cons "%s" (if org-log-note-state
14626 (concat "\"" org-log-note-state "\"")
14627 "")))))
14628 (if lines (setq note (concat note " \\\\")))
14629 (push note lines))
14630 (when (or current-prefix-arg org-note-abort) (setq lines nil))
14631 (when lines
14632 (save-excursion
14633 (set-buffer (marker-buffer org-log-note-marker))
14634 (save-excursion
14635 (goto-char org-log-note-marker)
14636 (move-marker org-log-note-marker nil)
14637 (end-of-line 1)
14638 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
14639 (indent-relative nil)
14640 (insert "- " (pop lines))
14641 (org-indent-line-function)
14642 (beginning-of-line 1)
14643 (looking-at "[ \t]*")
14644 (setq ind (concat (match-string 0) " "))
14645 (end-of-line 1)
14646 (while lines (insert "\n" ind (pop lines)))))))
14647 (set-window-configuration org-log-note-window-configuration)
14648 (with-current-buffer (marker-buffer org-log-note-return-to)
14649 (goto-char org-log-note-return-to))
14650 (move-marker org-log-note-return-to nil)
14651 (and org-log-post-message (message "%s" org-log-post-message)))
14653 ;; FIXME: what else would be useful?
14654 ;; - priority
14655 ;; - date
14657 (defun org-sparse-tree (&optional arg)
14658 "Create a sparse tree, prompt for the details.
14659 This command can create sparse trees. You first need to select the type
14660 of match used to create the tree:
14662 t Show entries with a specific TODO keyword.
14663 T Show entries selected by a tags match.
14664 p Enter a property name and its value (both with completion on existing
14665 names/values) and show entries with that property.
14666 r Show entries matching a regular expression
14667 d Show deadlines due within `org-deadline-warning-days'."
14668 (interactive "P")
14669 (let (ans kwd value)
14670 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
14671 (setq ans (read-char-exclusive))
14672 (cond
14673 ((equal ans ?d)
14674 (call-interactively 'org-check-deadlines))
14675 ((equal ans ?b)
14676 (call-interactively 'org-check-before-date))
14677 ((equal ans ?t)
14678 (org-show-todo-tree '(4)))
14679 ((equal ans ?T)
14680 (call-interactively 'org-tags-sparse-tree))
14681 ((member ans '(?p ?P))
14682 (setq kwd (completing-read "Property: "
14683 (mapcar 'list (org-buffer-property-keys))))
14684 (setq value (completing-read "Value: "
14685 (mapcar 'list (org-property-values kwd))))
14686 (unless (string-match "\\`{.*}\\'" value)
14687 (setq value (concat "\"" value "\"")))
14688 (org-tags-sparse-tree arg (concat kwd "=" value)))
14689 ((member ans '(?r ?R ?/))
14690 (call-interactively 'org-occur))
14691 (t (error "No such sparse tree command \"%c\"" ans)))))
14693 (defvar org-occur-highlights nil)
14694 (make-variable-buffer-local 'org-occur-highlights)
14696 (defun org-occur (regexp &optional keep-previous callback)
14697 "Make a compact tree which shows all matches of REGEXP.
14698 The tree will show the lines where the regexp matches, and all higher
14699 headlines above the match. It will also show the heading after the match,
14700 to make sure editing the matching entry is easy.
14701 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
14702 call to `org-occur' will be kept, to allow stacking of calls to this
14703 command.
14704 If CALLBACK is non-nil, it is a function which is called to confirm
14705 that the match should indeed be shown."
14706 (interactive "sRegexp: \nP")
14707 (or keep-previous (org-remove-occur-highlights nil nil t))
14708 (let ((cnt 0))
14709 (save-excursion
14710 (goto-char (point-min))
14711 (if (or (not keep-previous) ; do not want to keep
14712 (not org-occur-highlights)) ; no previous matches
14713 ;; hide everything
14714 (org-overview))
14715 (while (re-search-forward regexp nil t)
14716 (when (or (not callback)
14717 (save-match-data (funcall callback)))
14718 (setq cnt (1+ cnt))
14719 (when org-highlight-sparse-tree-matches
14720 (org-highlight-new-match (match-beginning 0) (match-end 0)))
14721 (org-show-context 'occur-tree))))
14722 (when org-remove-highlights-with-change
14723 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
14724 nil 'local))
14725 (unless org-sparse-tree-open-archived-trees
14726 (org-hide-archived-subtrees (point-min) (point-max)))
14727 (run-hooks 'org-occur-hook)
14728 (if (interactive-p)
14729 (message "%d match(es) for regexp %s" cnt regexp))
14730 cnt))
14732 (defun org-show-context (&optional key)
14733 "Make sure point and context and visible.
14734 How much context is shown depends upon the variables
14735 `org-show-hierarchy-above', `org-show-following-heading'. and
14736 `org-show-siblings'."
14737 (let ((heading-p (org-on-heading-p t))
14738 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
14739 (following-p (org-get-alist-option org-show-following-heading key))
14740 (entry-p (org-get-alist-option org-show-entry-below key))
14741 (siblings-p (org-get-alist-option org-show-siblings key)))
14742 (catch 'exit
14743 ;; Show heading or entry text
14744 (if (and heading-p (not entry-p))
14745 (org-flag-heading nil) ; only show the heading
14746 (and (or entry-p (org-invisible-p) (org-invisible-p2))
14747 (org-show-hidden-entry))) ; show entire entry
14748 (when following-p
14749 ;; Show next sibling, or heading below text
14750 (save-excursion
14751 (and (if heading-p (org-goto-sibling) (outline-next-heading))
14752 (org-flag-heading nil))))
14753 (when siblings-p (org-show-siblings))
14754 (when hierarchy-p
14755 ;; show all higher headings, possibly with siblings
14756 (save-excursion
14757 (while (and (condition-case nil
14758 (progn (org-up-heading-all 1) t)
14759 (error nil))
14760 (not (bobp)))
14761 (org-flag-heading nil)
14762 (when siblings-p (org-show-siblings))))))))
14764 (defun org-reveal (&optional siblings)
14765 "Show current entry, hierarchy above it, and the following headline.
14766 This can be used to show a consistent set of context around locations
14767 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
14768 not t for the search context.
14770 With optional argument SIBLINGS, on each level of the hierarchy all
14771 siblings are shown. This repairs the tree structure to what it would
14772 look like when opened with hierarchical calls to `org-cycle'."
14773 (interactive "P")
14774 (let ((org-show-hierarchy-above t)
14775 (org-show-following-heading t)
14776 (org-show-siblings (if siblings t org-show-siblings)))
14777 (org-show-context nil)))
14779 (defun org-highlight-new-match (beg end)
14780 "Highlight from BEG to END and mark the highlight is an occur headline."
14781 (let ((ov (org-make-overlay beg end)))
14782 (org-overlay-put ov 'face 'secondary-selection)
14783 (push ov org-occur-highlights)))
14785 (defun org-remove-occur-highlights (&optional beg end noremove)
14786 "Remove the occur highlights from the buffer.
14787 BEG and END are ignored. If NOREMOVE is nil, remove this function
14788 from the `before-change-functions' in the current buffer."
14789 (interactive)
14790 (unless org-inhibit-highlight-removal
14791 (mapc 'org-delete-overlay org-occur-highlights)
14792 (setq org-occur-highlights nil)
14793 (unless noremove
14794 (remove-hook 'before-change-functions
14795 'org-remove-occur-highlights 'local))))
14797 ;;;; Priorities
14799 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14800 "Regular expression matching the priority indicator.")
14802 (defvar org-remove-priority-next-time nil)
14804 (defun org-priority-up ()
14805 "Increase the priority of the current item."
14806 (interactive)
14807 (org-priority 'up))
14809 (defun org-priority-down ()
14810 "Decrease the priority of the current item."
14811 (interactive)
14812 (org-priority 'down))
14814 (defun org-priority (&optional action)
14815 "Change the priority of an item by ARG.
14816 ACTION can be `set', `up', `down', or a character."
14817 (interactive)
14818 (setq action (or action 'set))
14819 (let (current new news have remove)
14820 (save-excursion
14821 (org-back-to-heading)
14822 (if (looking-at org-priority-regexp)
14823 (setq current (string-to-char (match-string 2))
14824 have t)
14825 (setq current org-default-priority))
14826 (cond
14827 ((or (eq action 'set) (integerp action))
14828 (if (integerp action)
14829 (setq new action)
14830 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
14831 (setq new (read-char-exclusive)))
14832 (if (and (= (upcase org-highest-priority) org-highest-priority)
14833 (= (upcase org-lowest-priority) org-lowest-priority))
14834 (setq new (upcase new)))
14835 (cond ((equal new ?\ ) (setq remove t))
14836 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14837 (error "Priority must be between `%c' and `%c'"
14838 org-highest-priority org-lowest-priority))))
14839 ((eq action 'up)
14840 (if (and (not have) (eq last-command this-command))
14841 (setq new org-lowest-priority)
14842 (setq new (if (and org-priority-start-cycle-with-default (not have))
14843 org-default-priority (1- current)))))
14844 ((eq action 'down)
14845 (if (and (not have) (eq last-command this-command))
14846 (setq new org-highest-priority)
14847 (setq new (if (and org-priority-start-cycle-with-default (not have))
14848 org-default-priority (1+ current)))))
14849 (t (error "Invalid action")))
14850 (if (or (< (upcase new) org-highest-priority)
14851 (> (upcase new) org-lowest-priority))
14852 (setq remove t))
14853 (setq news (format "%c" new))
14854 (if have
14855 (if remove
14856 (replace-match "" t t nil 1)
14857 (replace-match news t t nil 2))
14858 (if remove
14859 (error "No priority cookie found in line")
14860 (looking-at org-todo-line-regexp)
14861 (if (match-end 2)
14862 (progn
14863 (goto-char (match-end 2))
14864 (insert " [#" news "]"))
14865 (goto-char (match-beginning 3))
14866 (insert "[#" news "] ")))))
14867 (org-preserve-lc (org-set-tags nil 'align))
14868 (if remove
14869 (message "Priority removed")
14870 (message "Priority of current item set to %s" news))))
14873 (defun org-get-priority (s)
14874 "Find priority cookie and return priority."
14875 (save-match-data
14876 (if (not (string-match org-priority-regexp s))
14877 (* 1000 (- org-lowest-priority org-default-priority))
14878 (* 1000 (- org-lowest-priority
14879 (string-to-char (match-string 2 s)))))))
14881 ;;;; Tags
14883 (defun org-scan-tags (action matcher &optional todo-only)
14884 "Scan headline tags with inheritance and produce output ACTION.
14885 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
14886 evaluated, testing if a given set of tags qualifies a headline for
14887 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
14888 are included in the output."
14889 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
14890 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14891 (org-re
14892 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
14893 (props (list 'face nil
14894 'done-face 'org-done
14895 'undone-face nil
14896 'mouse-face 'highlight
14897 'org-not-done-regexp org-not-done-regexp
14898 'org-todo-regexp org-todo-regexp
14899 'keymap org-agenda-keymap
14900 'help-echo
14901 (format "mouse-2 or RET jump to org file %s"
14902 (abbreviate-file-name
14903 (or (buffer-file-name (buffer-base-buffer))
14904 (buffer-name (buffer-base-buffer)))))))
14905 (case-fold-search nil)
14906 lspos
14907 tags tags-list tags-alist (llast 0) rtn level category i txt
14908 todo marker entry priority)
14909 (save-excursion
14910 (goto-char (point-min))
14911 (when (eq action 'sparse-tree)
14912 (org-overview)
14913 (org-remove-occur-highlights))
14914 (while (re-search-forward re nil t)
14915 (catch :skip
14916 (setq todo (if (match-end 1) (match-string 2))
14917 tags (if (match-end 4) (match-string 4)))
14918 (goto-char (setq lspos (1+ (match-beginning 0))))
14919 (setq level (org-reduced-level (funcall outline-level))
14920 category (org-get-category))
14921 (setq i llast llast level)
14922 ;; remove tag lists from same and sublevels
14923 (while (>= i level)
14924 (when (setq entry (assoc i tags-alist))
14925 (setq tags-alist (delete entry tags-alist)))
14926 (setq i (1- i)))
14927 ;; add the nex tags
14928 (when tags
14929 (setq tags (mapcar 'downcase (org-split-string tags ":"))
14930 tags-alist
14931 (cons (cons level tags) tags-alist)))
14932 ;; compile tags for current headline
14933 (setq tags-list
14934 (if org-use-tag-inheritance
14935 (apply 'append (mapcar 'cdr tags-alist))
14936 tags))
14937 (when (and (or (not todo-only) (member todo org-not-done-keywords))
14938 (eval matcher)
14939 (or (not org-agenda-skip-archived-trees)
14940 (not (member org-archive-tag tags-list))))
14941 (and (eq action 'agenda) (org-agenda-skip))
14942 ;; list this headline
14944 (if (eq action 'sparse-tree)
14945 (progn
14946 (and org-highlight-sparse-tree-matches
14947 (org-get-heading) (match-end 0)
14948 (org-highlight-new-match
14949 (match-beginning 0) (match-beginning 1)))
14950 (org-show-context 'tags-tree))
14951 (setq txt (org-format-agenda-item
14953 (concat
14954 (if org-tags-match-list-sublevels
14955 (make-string (1- level) ?.) "")
14956 (org-get-heading))
14957 category tags-list)
14958 priority (org-get-priority txt))
14959 (goto-char lspos)
14960 (setq marker (org-agenda-new-marker))
14961 (org-add-props txt props
14962 'org-marker marker 'org-hd-marker marker 'org-category category
14963 'priority priority 'type "tagsmatch")
14964 (push txt rtn))
14965 ;; if we are to skip sublevels, jump to end of subtree
14966 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
14967 (when (and (eq action 'sparse-tree)
14968 (not org-sparse-tree-open-archived-trees))
14969 (org-hide-archived-subtrees (point-min) (point-max)))
14970 (nreverse rtn)))
14972 (defvar todo-only) ;; dynamically scoped
14974 (defun org-tags-sparse-tree (&optional todo-only match)
14975 "Create a sparse tree according to tags string MATCH.
14976 MATCH can contain positive and negative selection of tags, like
14977 \"+WORK+URGENT-WITHBOSS\".
14978 If optional argument TODO_ONLY is non-nil, only select lines that are
14979 also TODO lines."
14980 (interactive "P")
14981 (org-prepare-agenda-buffers (list (current-buffer)))
14982 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14984 (defvar org-cached-props nil)
14985 (defun org-cached-entry-get (pom property)
14986 (if (or (eq t org-use-property-inheritance)
14987 (member property org-use-property-inheritance))
14988 ;; Caching is not possible, check it directly
14989 (org-entry-get pom property 'inherit)
14990 ;; Get all properties, so that we can do complicated checks easily
14991 (cdr (assoc property (or org-cached-props
14992 (setq org-cached-props
14993 (org-entry-properties pom)))))))
14995 (defun org-global-tags-completion-table (&optional files)
14996 "Return the list of all tags in all agenda buffer/files."
14997 (save-excursion
14998 (org-uniquify
14999 (apply 'append
15000 (mapcar
15001 (lambda (file)
15002 (set-buffer (find-file-noselect file))
15003 (org-get-buffer-tags))
15004 (if (and files (car files))
15005 files
15006 (org-agenda-files)))))))
15008 (defun org-make-tags-matcher (match)
15009 "Create the TAGS//TODO matcher form for the selection string MATCH."
15010 ;; todo-only is scoped dynamically into this function, and the function
15011 ;; may change it it the matcher asksk for it.
15012 (unless match
15013 ;; Get a new match request, with completion
15014 (let ((org-last-tags-completion-table
15015 (org-global-tags-completion-table)))
15016 (setq match (completing-read
15017 "Match: " 'org-tags-completion-function nil nil nil
15018 'org-tags-history))))
15020 ;; Parse the string and create a lisp form
15021 (let ((match0 match)
15022 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]+\"\\)\\|[[:alnum:]_@]+\\)"))
15023 minus tag mm
15024 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15025 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15026 (if (string-match "/+" match)
15027 ;; match contains also a todo-matching request
15028 (progn
15029 (setq tagsmatch (substring match 0 (match-beginning 0))
15030 todomatch (substring match (match-end 0)))
15031 (if (string-match "^!" todomatch)
15032 (setq todo-only t todomatch (substring todomatch 1)))
15033 (if (string-match "^\\s-*$" todomatch)
15034 (setq todomatch nil)))
15035 ;; only matching tags
15036 (setq tagsmatch match todomatch nil))
15038 ;; Make the tags matcher
15039 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15040 (setq tagsmatcher t)
15041 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15042 (while (setq term (pop orterms))
15043 (while (and (equal (substring term -1) "\\") orterms)
15044 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15045 (while (string-match re term)
15046 (setq minus (and (match-end 1)
15047 (equal (match-string 1 term) "-"))
15048 tag (match-string 2 term)
15049 re-p (equal (string-to-char tag) ?{)
15050 level-p (match-end 3)
15051 prop-p (match-end 4)
15052 mm (cond
15053 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15054 (level-p `(= level ,(string-to-number
15055 (match-string 3 term))))
15056 (prop-p
15057 (setq pn (match-string 4 term)
15058 pv (match-string 5 term)
15059 cat-p (equal pn "CATEGORY")
15060 re-p (equal (string-to-char pv) ?{)
15061 pv (substring pv 1 -1))
15062 (if (equal pn "CATEGORY")
15063 (setq gv '(get-text-property (point) 'org-category))
15064 (setq gv `(org-cached-entry-get nil ,pn)))
15065 (if re-p
15066 `(string-match ,pv (or ,gv ""))
15067 `(equal ,pv ,gv)))
15068 (t `(member ,(downcase tag) tags-list)))
15069 mm (if minus (list 'not mm) mm)
15070 term (substring term (match-end 0)))
15071 (push mm tagsmatcher))
15072 (push (if (> (length tagsmatcher) 1)
15073 (cons 'and tagsmatcher)
15074 (car tagsmatcher))
15075 orlist)
15076 (setq tagsmatcher nil))
15077 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15078 (setq tagsmatcher
15079 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15081 ;; Make the todo matcher
15082 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15083 (setq todomatcher t)
15084 (setq orterms (org-split-string todomatch "|") orlist nil)
15085 (while (setq term (pop orterms))
15086 (while (string-match re term)
15087 (setq minus (and (match-end 1)
15088 (equal (match-string 1 term) "-"))
15089 kwd (match-string 2 term)
15090 re-p (equal (string-to-char kwd) ?{)
15091 term (substring term (match-end 0))
15092 mm (if re-p
15093 `(string-match ,(substring kwd 1 -1) todo)
15094 (list 'equal 'todo kwd))
15095 mm (if minus (list 'not mm) mm))
15096 (push mm todomatcher))
15097 (push (if (> (length todomatcher) 1)
15098 (cons 'and todomatcher)
15099 (car todomatcher))
15100 orlist)
15101 (setq todomatcher nil))
15102 (setq todomatcher (if (> (length orlist) 1)
15103 (cons 'or orlist) (car orlist))))
15105 ;; Return the string and lisp forms of the matcher
15106 (setq matcher (if todomatcher
15107 (list 'and tagsmatcher todomatcher)
15108 tagsmatcher))
15109 (cons match0 matcher)))
15111 (defun org-match-any-p (re list)
15112 "Does re match any element of list?"
15113 (setq list (mapcar (lambda (x) (string-match re x)) list))
15114 (delq nil list))
15116 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15117 (defvar org-tags-overlay (org-make-overlay 1 1))
15118 (org-detach-overlay org-tags-overlay)
15120 (defun org-align-tags-here (to-col)
15121 ;; Assumes that this is a headline
15122 (let ((pos (point)) (col (current-column)) tags)
15123 (beginning-of-line 1)
15124 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15125 (< pos (match-beginning 2)))
15126 (progn
15127 (setq tags (match-string 2))
15128 (goto-char (match-beginning 1))
15129 (insert " ")
15130 (delete-region (point) (1+ (match-end 0)))
15131 (backward-char 1)
15132 (move-to-column
15133 (max (1+ (current-column))
15134 (1+ col)
15135 (if (> to-col 0)
15136 to-col
15137 (- (abs to-col) (length tags))))
15139 (insert tags)
15140 (move-to-column (min (current-column) col) t))
15141 (goto-char pos))))
15143 (defun org-set-tags (&optional arg just-align)
15144 "Set the tags for the current headline.
15145 With prefix ARG, realign all tags in headings in the current buffer."
15146 (interactive "P")
15147 (let* ((re (concat "^" outline-regexp))
15148 (current (org-get-tags-string))
15149 (col (current-column))
15150 (org-setting-tags t)
15151 table current-tags inherited-tags ; computed below when needed
15152 tags p0 c0 c1 rpl)
15153 (if arg
15154 (save-excursion
15155 (goto-char (point-min))
15156 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15157 (while (re-search-forward re nil t)
15158 (org-set-tags nil t)
15159 (end-of-line 1)))
15160 (message "All tags realigned to column %d" org-tags-column))
15161 (if just-align
15162 (setq tags current)
15163 ;; Get a new set of tags from the user
15164 (save-excursion
15165 (setq table (or org-tag-alist (org-get-buffer-tags))
15166 org-last-tags-completion-table table
15167 current-tags (org-split-string current ":")
15168 inherited-tags (nreverse
15169 (nthcdr (length current-tags)
15170 (nreverse (org-get-tags-at))))
15171 tags
15172 (if (or (eq t org-use-fast-tag-selection)
15173 (and org-use-fast-tag-selection
15174 (delq nil (mapcar 'cdr table))))
15175 (org-fast-tag-selection
15176 current-tags inherited-tags table
15177 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15178 (let ((org-add-colon-after-tag-completion t))
15179 (org-trim
15180 (org-without-partial-completion
15181 (completing-read "Tags: " 'org-tags-completion-function
15182 nil nil current 'org-tags-history)))))))
15183 (while (string-match "[-+&]+" tags)
15184 ;; No boolean logic, just a list
15185 (setq tags (replace-match ":" t t tags))))
15187 (if (string-match "\\`[\t ]*\\'" tags)
15188 (setq tags "")
15189 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15190 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15192 ;; Insert new tags at the correct column
15193 (beginning-of-line 1)
15194 (cond
15195 ((and (equal current "") (equal tags "")))
15196 ((re-search-forward
15197 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15198 (point-at-eol) t)
15199 (if (equal tags "")
15200 (setq rpl "")
15201 (goto-char (match-beginning 0))
15202 (setq c0 (current-column) p0 (point)
15203 c1 (max (1+ c0) (if (> org-tags-column 0)
15204 org-tags-column
15205 (- (- org-tags-column) (length tags))))
15206 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15207 (replace-match rpl t t)
15208 (and (not (featurep 'xemacs)) c0 (tabify p0 (point)))
15209 tags)
15210 (t (error "Tags alignment failed")))
15211 (move-to-column col)
15212 (unless just-align
15213 (run-hooks 'org-after-tags-change-hook)))))
15215 (defun org-change-tag-in-region (beg end tag off)
15216 "Add or remove TAG for each entry in the region.
15217 This works in the agenda, and also in an org-mode buffer."
15218 (interactive
15219 (list (region-beginning) (region-end)
15220 (let ((org-last-tags-completion-table
15221 (if (org-mode-p)
15222 (org-get-buffer-tags)
15223 (org-global-tags-completion-table))))
15224 (completing-read
15225 "Tag: " 'org-tags-completion-function nil nil nil
15226 'org-tags-history))
15227 (progn
15228 (message "[s]et or [r]emove? ")
15229 (equal (read-char-exclusive) ?r))))
15230 (if (fboundp 'deactivate-mark) (deactivate-mark))
15231 (let ((agendap (equal major-mode 'org-agenda-mode))
15232 l1 l2 m buf pos newhead (cnt 0))
15233 (goto-char end)
15234 (setq l2 (1- (org-current-line)))
15235 (goto-char beg)
15236 (setq l1 (org-current-line))
15237 (loop for l from l1 to l2 do
15238 (goto-line l)
15239 (setq m (get-text-property (point) 'org-hd-marker))
15240 (when (or (and (org-mode-p) (org-on-heading-p))
15241 (and agendap m))
15242 (setq buf (if agendap (marker-buffer m) (current-buffer))
15243 pos (if agendap m (point)))
15244 (with-current-buffer buf
15245 (save-excursion
15246 (save-restriction
15247 (goto-char pos)
15248 (setq cnt (1+ cnt))
15249 (org-toggle-tag tag (if off 'off 'on))
15250 (setq newhead (org-get-heading)))))
15251 (and agendap (org-agenda-change-all-lines newhead m))))
15252 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15254 (defun org-tags-completion-function (string predicate &optional flag)
15255 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15256 (confirm (lambda (x) (stringp (car x)))))
15257 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15258 (setq s1 (match-string 1 string)
15259 s2 (match-string 2 string))
15260 (setq s1 "" s2 string))
15261 (cond
15262 ((eq flag nil)
15263 ;; try completion
15264 (setq rtn (try-completion s2 ctable confirm))
15265 (if (stringp rtn)
15266 (setq rtn
15267 (concat s1 s2 (substring rtn (length s2))
15268 (if (and org-add-colon-after-tag-completion
15269 (assoc rtn ctable))
15270 ":" ""))))
15271 rtn)
15272 ((eq flag t)
15273 ;; all-completions
15274 (all-completions s2 ctable confirm)
15276 ((eq flag 'lambda)
15277 ;; exact match?
15278 (assoc s2 ctable)))
15281 (defun org-fast-tag-insert (kwd tags face &optional end)
15282 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15283 (insert (format "%-12s" (concat kwd ":"))
15284 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15285 (or end "")))
15287 (defun org-fast-tag-show-exit (flag)
15288 (save-excursion
15289 (goto-line 3)
15290 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15291 (replace-match ""))
15292 (when flag
15293 (end-of-line 1)
15294 (move-to-column (- (window-width) 19) t)
15295 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15297 (defun org-set-current-tags-overlay (current prefix)
15298 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15299 (if (featurep 'xemacs)
15300 (org-overlay-display org-tags-overlay (concat prefix s)
15301 'secondary-selection)
15302 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15303 (org-overlay-display org-tags-overlay (concat prefix s)))))
15305 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15306 "Fast tag selection with single keys.
15307 CURRENT is the current list of tags in the headline, INHERITED is the
15308 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15309 possibly with grouping information. TODO-TABLE is a similar table with
15310 TODO keywords, should these have keys assigned to them.
15311 If the keys are nil, a-z are automatically assigned.
15312 Returns the new tags string, or nil to not change the current settings."
15313 (let* ((fulltable (append table todo-table))
15314 (maxlen (apply 'max (mapcar
15315 (lambda (x)
15316 (if (stringp (car x)) (string-width (car x)) 0))
15317 fulltable)))
15318 (buf (current-buffer))
15319 (expert (eq org-fast-tag-selection-single-key 'expert))
15320 (buffer-tags nil)
15321 (fwidth (+ maxlen 3 1 3))
15322 (ncol (/ (- (window-width) 4) fwidth))
15323 (i-face 'org-done)
15324 (c-face 'org-todo)
15325 tg cnt e c char c1 c2 ntable tbl rtn
15326 ov-start ov-end ov-prefix
15327 (exit-after-next org-fast-tag-selection-single-key)
15328 (done-keywords org-done-keywords)
15329 groups ingroup)
15330 (save-excursion
15331 (beginning-of-line 1)
15332 (if (looking-at
15333 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15334 (setq ov-start (match-beginning 1)
15335 ov-end (match-end 1)
15336 ov-prefix "")
15337 (setq ov-start (1- (point-at-eol))
15338 ov-end (1+ ov-start))
15339 (skip-chars-forward "^\n\r")
15340 (setq ov-prefix
15341 (concat
15342 (buffer-substring (1- (point)) (point))
15343 (if (> (current-column) org-tags-column)
15345 (make-string (- org-tags-column (current-column)) ?\ ))))))
15346 (org-move-overlay org-tags-overlay ov-start ov-end)
15347 (save-window-excursion
15348 (if expert
15349 (set-buffer (get-buffer-create " *Org tags*"))
15350 (delete-other-windows)
15351 (split-window-vertically)
15352 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
15353 (erase-buffer)
15354 (org-set-local 'org-done-keywords done-keywords)
15355 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15356 (org-fast-tag-insert "Current" current c-face "\n\n")
15357 (org-fast-tag-show-exit exit-after-next)
15358 (org-set-current-tags-overlay current ov-prefix)
15359 (setq tbl fulltable char ?a cnt 0)
15360 (while (setq e (pop tbl))
15361 (cond
15362 ((equal e '(:startgroup))
15363 (push '() groups) (setq ingroup t)
15364 (when (not (= cnt 0))
15365 (setq cnt 0)
15366 (insert "\n"))
15367 (insert "{ "))
15368 ((equal e '(:endgroup))
15369 (setq ingroup nil cnt 0)
15370 (insert "}\n"))
15372 (setq tg (car e) c2 nil)
15373 (if (cdr e)
15374 (setq c (cdr e))
15375 ;; automatically assign a character.
15376 (setq c1 (string-to-char
15377 (downcase (substring
15378 tg (if (= (string-to-char tg) ?@) 1 0)))))
15379 (if (or (rassoc c1 ntable) (rassoc c1 table))
15380 (while (or (rassoc char ntable) (rassoc char table))
15381 (setq char (1+ char)))
15382 (setq c2 c1))
15383 (setq c (or c2 char)))
15384 (if ingroup (push tg (car groups)))
15385 (setq tg (org-add-props tg nil 'face
15386 (cond
15387 ((not (assoc tg table))
15388 (org-get-todo-face tg))
15389 ((member tg current) c-face)
15390 ((member tg inherited) i-face)
15391 (t nil))))
15392 (if (and (= cnt 0) (not ingroup)) (insert " "))
15393 (insert "[" c "] " tg (make-string
15394 (- fwidth 4 (length tg)) ?\ ))
15395 (push (cons tg c) ntable)
15396 (when (= (setq cnt (1+ cnt)) ncol)
15397 (insert "\n")
15398 (if ingroup (insert " "))
15399 (setq cnt 0)))))
15400 (setq ntable (nreverse ntable))
15401 (insert "\n")
15402 (goto-char (point-min))
15403 (if (and (not expert) (fboundp 'fit-window-to-buffer))
15404 (fit-window-to-buffer))
15405 (setq rtn
15406 (catch 'exit
15407 (while t
15408 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
15409 (if groups " [!] no groups" " [!]groups")
15410 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15411 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15412 (cond
15413 ((= c ?\r) (throw 'exit t))
15414 ((= c ?!)
15415 (setq groups (not groups))
15416 (goto-char (point-min))
15417 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15418 ((= c ?\C-c)
15419 (if (not expert)
15420 (org-fast-tag-show-exit
15421 (setq exit-after-next (not exit-after-next)))
15422 (setq expert nil)
15423 (delete-other-windows)
15424 (split-window-vertically)
15425 (org-switch-to-buffer-other-window " *Org tags*")
15426 (and (fboundp 'fit-window-to-buffer)
15427 (fit-window-to-buffer))))
15428 ((or (= c ?\C-g)
15429 (and (= c ?q) (not (rassoc c ntable))))
15430 (org-detach-overlay org-tags-overlay)
15431 (setq quit-flag t))
15432 ((= c ?\ )
15433 (setq current nil)
15434 (if exit-after-next (setq exit-after-next 'now)))
15435 ((= c ?\t)
15436 (condition-case nil
15437 (setq tg (completing-read
15438 "Tag: "
15439 (or buffer-tags
15440 (with-current-buffer buf
15441 (org-get-buffer-tags)))))
15442 (quit (setq tg "")))
15443 (when (string-match "\\S-" tg)
15444 (add-to-list 'buffer-tags (list tg))
15445 (if (member tg current)
15446 (setq current (delete tg current))
15447 (push tg current)))
15448 (if exit-after-next (setq exit-after-next 'now)))
15449 ((setq e (rassoc c todo-table) tg (car e))
15450 (with-current-buffer buf
15451 (save-excursion (org-todo tg)))
15452 (if exit-after-next (setq exit-after-next 'now)))
15453 ((setq e (rassoc c ntable) tg (car e))
15454 (if (member tg current)
15455 (setq current (delete tg current))
15456 (loop for g in groups do
15457 (if (member tg g)
15458 (mapc (lambda (x)
15459 (setq current (delete x current)))
15460 g)))
15461 (push tg current))
15462 (if exit-after-next (setq exit-after-next 'now))))
15464 ;; Create a sorted list
15465 (setq current
15466 (sort current
15467 (lambda (a b)
15468 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15469 (if (eq exit-after-next 'now) (throw 'exit t))
15470 (goto-char (point-min))
15471 (beginning-of-line 2)
15472 (delete-region (point) (point-at-eol))
15473 (org-fast-tag-insert "Current" current c-face)
15474 (org-set-current-tags-overlay current ov-prefix)
15475 (while (re-search-forward
15476 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
15477 (setq tg (match-string 1))
15478 (add-text-properties
15479 (match-beginning 1) (match-end 1)
15480 (list 'face
15481 (cond
15482 ((member tg current) c-face)
15483 ((member tg inherited) i-face)
15484 (t (get-text-property (match-beginning 1) 'face))))))
15485 (goto-char (point-min)))))
15486 (org-detach-overlay org-tags-overlay)
15487 (if rtn
15488 (mapconcat 'identity current ":")
15489 nil))))
15491 (defun org-get-tags-string ()
15492 "Get the TAGS string in the current headline."
15493 (unless (org-on-heading-p t)
15494 (error "Not on a heading"))
15495 (save-excursion
15496 (beginning-of-line 1)
15497 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15498 (org-match-string-no-properties 1)
15499 "")))
15501 (defun org-get-tags ()
15502 "Get the list of tags specified in the current headline."
15503 (org-split-string (org-get-tags-string) ":"))
15505 (defun org-get-buffer-tags ()
15506 "Get a table of all tags used in the buffer, for completion."
15507 (let (tags)
15508 (save-excursion
15509 (goto-char (point-min))
15510 (while (re-search-forward
15511 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
15512 (when (equal (char-after (point-at-bol 0)) ?*)
15513 (mapc (lambda (x) (add-to-list 'tags x))
15514 (org-split-string (org-match-string-no-properties 1) ":")))))
15515 (mapcar 'list tags)))
15518 ;;;; Properties
15520 ;;; Setting and retrieving properties
15522 (defconst org-special-properties
15523 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
15524 "TIMESTAMP" "TIMESTAMP_IA")
15525 "The special properties valid in Org-mode.
15527 These are properties that are not defined in the property drawer,
15528 but in some other way.")
15530 (defconst org-default-properties
15531 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
15532 "LOCATION" "LOGGING" "COLUMNS")
15533 "Some properties that are used by Org-mode for various purposes.
15534 Being in this list makes sure that they are offered for completion.")
15536 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15537 "Regular expression matching the first line of a property drawer.")
15539 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15540 "Regular expression matching the first line of a property drawer.")
15542 (defun org-property-action ()
15543 "Do an action on properties."
15544 (interactive)
15545 (let (c)
15546 (org-at-property-p)
15547 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15548 (setq c (read-char-exclusive))
15549 (cond
15550 ((equal c ?s)
15551 (call-interactively 'org-set-property))
15552 ((equal c ?d)
15553 (call-interactively 'org-delete-property))
15554 ((equal c ?D)
15555 (call-interactively 'org-delete-property-globally))
15556 ((equal c ?c)
15557 (call-interactively 'org-compute-property-at-point))
15558 (t (error "No such property action %c" c)))))
15560 (defun org-at-property-p ()
15561 "Is the cursor in a property line?"
15562 ;; FIXME: Does not check if we are actually in the drawer.
15563 ;; FIXME: also returns true on any drawers.....
15564 ;; This is used by C-c C-c for property action.
15565 (save-excursion
15566 (beginning-of-line 1)
15567 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
15569 (defmacro org-with-point-at (pom &rest body)
15570 "Move to buffer and point of point-or-marker POM for the duration of BODY."
15571 (declare (indent 1) (debug t))
15572 `(save-excursion
15573 (if (markerp pom) (set-buffer (marker-buffer pom)))
15574 (save-excursion
15575 (goto-char (or pom (point)))
15576 ,@body)))
15578 (defun org-get-property-block (&optional beg end force)
15579 "Return the (beg . end) range of the body of the property drawer.
15580 BEG and END can be beginning and end of subtree, if not given
15581 they will be found.
15582 If the drawer does not exist and FORCE is non-nil, create the drawer."
15583 (catch 'exit
15584 (save-excursion
15585 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
15586 (end (or end (progn (outline-next-heading) (point)))))
15587 (goto-char beg)
15588 (if (re-search-forward org-property-start-re end t)
15589 (setq beg (1+ (match-end 0)))
15590 (if force
15591 (save-excursion
15592 (org-insert-property-drawer)
15593 (setq end (progn (outline-next-heading) (point))))
15594 (throw 'exit nil))
15595 (goto-char beg)
15596 (if (re-search-forward org-property-start-re end t)
15597 (setq beg (1+ (match-end 0)))))
15598 (if (re-search-forward org-property-end-re end t)
15599 (setq end (match-beginning 0))
15600 (or force (throw 'exit nil))
15601 (goto-char beg)
15602 (setq end beg)
15603 (org-indent-line-function)
15604 (insert ":END:\n"))
15605 (cons beg end)))))
15607 (defun org-entry-properties (&optional pom which)
15608 "Get all properties of the entry at point-or-marker POM.
15609 This includes the TODO keyword, the tags, time strings for deadline,
15610 scheduled, and clocking, and any additional properties defined in the
15611 entry. The return value is an alist, keys may occur multiple times
15612 if the property key was used several times.
15613 POM may also be nil, in which case the current entry is used.
15614 If WHICH is nil or `all', get all properties. If WHICH is
15615 `special' or `standard', only get that subclass."
15616 (setq which (or which 'all))
15617 (org-with-point-at pom
15618 (let ((clockstr (substring org-clock-string 0 -1))
15619 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
15620 beg end range props sum-props key value string)
15621 (save-excursion
15622 (when (condition-case nil (org-back-to-heading t) (error nil))
15623 (setq beg (point))
15624 (setq sum-props (get-text-property (point) 'org-summaries))
15625 (outline-next-heading)
15626 (setq end (point))
15627 (when (memq which '(all special))
15628 ;; Get the special properties, like TODO and tags
15629 (goto-char beg)
15630 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15631 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15632 (when (looking-at org-priority-regexp)
15633 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15634 (when (and (setq value (org-get-tags-string))
15635 (string-match "\\S-" value))
15636 (push (cons "TAGS" value) props))
15637 (when (setq value (org-get-tags-at))
15638 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
15639 props))
15640 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15641 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
15642 string (if (equal key clockstr)
15643 (org-no-properties
15644 (org-trim
15645 (buffer-substring
15646 (match-beginning 3) (goto-char (point-at-eol)))))
15647 (substring (org-match-string-no-properties 3) 1 -1)))
15648 (unless key
15649 (if (= (char-after (match-beginning 3)) ?\[)
15650 (setq key "TIMESTAMP_IA")
15651 (setq key "TIMESTAMP")))
15652 (when (or (equal key clockstr) (not (assoc key props)))
15653 (push (cons key string) props)))
15657 (when (memq which '(all standard))
15658 ;; Get the standard properties, like :PORP: ...
15659 (setq range (org-get-property-block beg end))
15660 (when range
15661 (goto-char (car range))
15662 (while (re-search-forward
15663 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15664 (cdr range) t)
15665 (setq key (org-match-string-no-properties 1)
15666 value (org-trim (or (org-match-string-no-properties 2) "")))
15667 (unless (member key excluded)
15668 (push (cons key (or value "")) props)))))
15669 (append sum-props (nreverse props)))))))
15671 (defun org-entry-get (pom property &optional inherit)
15672 "Get value of PROPERTY for entry at point-or-marker POM.
15673 If INHERIT is non-nil and the entry does not have the property,
15674 then also check higher levels of the hierarchy.
15675 If the property is present but empty, the return value is the empty string.
15676 If the property is not present at all, nil is returned."
15677 (org-with-point-at pom
15678 (if inherit
15679 (org-entry-get-with-inheritance property)
15680 (if (member property org-special-properties)
15681 ;; We need a special property. Use brute force, get all properties.
15682 (cdr (assoc property (org-entry-properties nil 'special)))
15683 (let ((range (org-get-property-block)))
15684 (if (and range
15685 (goto-char (car range))
15686 (re-search-forward
15687 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
15688 (cdr range) t))
15689 ;; Found the property, return it.
15690 (if (match-end 1)
15691 (org-match-string-no-properties 1)
15692 "")))))))
15694 (defun org-entry-delete (pom property)
15695 "Delete the property PROPERTY from entry at point-or-marker POM."
15696 (org-with-point-at pom
15697 (if (member property org-special-properties)
15698 nil ; cannot delete these properties.
15699 (let ((range (org-get-property-block)))
15700 (if (and range
15701 (goto-char (car range))
15702 (re-search-forward
15703 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
15704 (cdr range) t))
15705 (progn
15706 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15708 nil)))))
15710 ;; Multi-values properties are properties that contain multiple values
15711 ;; These values are assumed to be single words, separated by whitespace.
15712 (defun org-entry-add-to-multivalued-property (pom property value)
15713 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15714 (let* ((old (org-entry-get pom property))
15715 (values (and old (org-split-string old "[ \t]"))))
15716 (unless (member value values)
15717 (setq values (cons value values))
15718 (org-entry-put pom property
15719 (mapconcat 'identity values " ")))))
15721 (defun org-entry-remove-from-multivalued-property (pom property value)
15722 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15723 (let* ((old (org-entry-get pom property))
15724 (values (and old (org-split-string old "[ \t]"))))
15725 (when (member value values)
15726 (setq values (delete value values))
15727 (org-entry-put pom property
15728 (mapconcat 'identity values " ")))))
15730 (defun org-entry-member-in-multivalued-property (pom property value)
15731 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15732 (let* ((old (org-entry-get pom property))
15733 (values (and old (org-split-string old "[ \t]"))))
15734 (member value values)))
15736 (defvar org-entry-property-inherited-from (make-marker))
15738 (defun org-entry-get-with-inheritance (property)
15739 "Get entry property, and search higher levels if not present."
15740 (let (tmp)
15741 (save-excursion
15742 (save-restriction
15743 (widen)
15744 (catch 'ex
15745 (while t
15746 (when (setq tmp (org-entry-get nil property))
15747 (org-back-to-heading t)
15748 (move-marker org-entry-property-inherited-from (point))
15749 (throw 'ex tmp))
15750 (or (org-up-heading-safe) (throw 'ex nil)))))
15751 (or tmp (cdr (assoc property org-local-properties))
15752 (cdr (assoc property org-global-properties))))))
15754 (defun org-entry-put (pom property value)
15755 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15756 (org-with-point-at pom
15757 (org-back-to-heading t)
15758 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15759 range)
15760 (cond
15761 ((equal property "TODO")
15762 (when (and (stringp value) (string-match "\\S-" value)
15763 (not (member value org-todo-keywords-1)))
15764 (error "\"%s\" is not a valid TODO state" value))
15765 (if (or (not value)
15766 (not (string-match "\\S-" value)))
15767 (setq value 'none))
15768 (org-todo value)
15769 (org-set-tags nil 'align))
15770 ((equal property "PRIORITY")
15771 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15772 (string-to-char value) ?\ ))
15773 (org-set-tags nil 'align))
15774 ((equal property "SCHEDULED")
15775 (if (re-search-forward org-scheduled-time-regexp end t)
15776 (cond
15777 ((eq value 'earlier) (org-timestamp-change -1 'day))
15778 ((eq value 'later) (org-timestamp-change 1 'day))
15779 (t (call-interactively 'org-schedule)))
15780 (call-interactively 'org-schedule)))
15781 ((equal property "DEADLINE")
15782 (if (re-search-forward org-deadline-time-regexp end t)
15783 (cond
15784 ((eq value 'earlier) (org-timestamp-change -1 'day))
15785 ((eq value 'later) (org-timestamp-change 1 'day))
15786 (t (call-interactively 'org-deadline)))
15787 (call-interactively 'org-deadline)))
15788 ((member property org-special-properties)
15789 (error "The %s property can not yet be set with `org-entry-put'"
15790 property))
15791 (t ; a non-special property
15792 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15793 (setq range (org-get-property-block beg end 'force))
15794 (goto-char (car range))
15795 (if (re-search-forward
15796 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
15797 (progn
15798 (delete-region (match-beginning 1) (match-end 1))
15799 (goto-char (match-beginning 1)))
15800 (goto-char (cdr range))
15801 (insert "\n")
15802 (backward-char 1)
15803 (org-indent-line-function)
15804 (insert ":" property ":"))
15805 (and value (insert " " value))
15806 (org-indent-line-function)))))))
15808 (defun org-buffer-property-keys (&optional include-specials include-defaults)
15809 "Get all property keys in the current buffer.
15810 With INCLUDE-SPECIALS, also list the special properties that relect things
15811 like tags and TODO state.
15812 With INCLUDE-DEFAULTS, also include properties that has special meaning
15813 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING."
15814 (let (rtn range)
15815 (save-excursion
15816 (save-restriction
15817 (widen)
15818 (goto-char (point-min))
15819 (while (re-search-forward org-property-start-re nil t)
15820 (setq range (org-get-property-block))
15821 (goto-char (car range))
15822 (while (re-search-forward
15823 (org-re "^[ \t]*:\\([[:alnum:]_-]+\\):")
15824 (cdr range) t)
15825 (add-to-list 'rtn (org-match-string-no-properties 1)))
15826 (outline-next-heading))))
15828 (when include-specials
15829 (setq rtn (append org-special-properties rtn)))
15831 (when include-defaults
15832 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
15834 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15836 (defun org-property-values (key)
15837 "Return a list of all values of property KEY."
15838 (save-excursion
15839 (save-restriction
15840 (widen)
15841 (goto-char (point-min))
15842 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
15843 values)
15844 (while (re-search-forward re nil t)
15845 (add-to-list 'values (org-trim (match-string 1))))
15846 (delete "" values)))))
15848 (defun org-insert-property-drawer ()
15849 "Insert a property drawer into the current entry."
15850 (interactive)
15851 (org-back-to-heading t)
15852 (looking-at outline-regexp)
15853 (let ((indent (- (match-end 0)(match-beginning 0)))
15854 (beg (point))
15855 (re (concat "^[ \t]*" org-keyword-time-regexp))
15856 end hiddenp)
15857 (outline-next-heading)
15858 (setq end (point))
15859 (goto-char beg)
15860 (while (re-search-forward re end t))
15861 (setq hiddenp (org-invisible-p))
15862 (end-of-line 1)
15863 (and (equal (char-after) ?\n) (forward-char 1))
15864 (org-skip-over-state-notes)
15865 (skip-chars-backward " \t\n\r")
15866 (if (eq (char-before) ?*) (forward-char 1))
15867 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15868 (beginning-of-line 0)
15869 (indent-to-column indent)
15870 (beginning-of-line 2)
15871 (indent-to-column indent)
15872 (beginning-of-line 0)
15873 (if hiddenp
15874 (save-excursion
15875 (org-back-to-heading t)
15876 (hide-entry))
15877 (org-flag-drawer t))))
15879 (defun org-set-property (property value)
15880 "In the current entry, set PROPERTY to VALUE.
15881 When called interactively, this will prompt for a property name, offering
15882 completion on existing and default properties. And then it will prompt
15883 for a value, offering competion either on allowed values (via an inherited
15884 xxx_ALL property) or on existing values in other instances of this property
15885 in the current file."
15886 (interactive
15887 (let* ((prop (completing-read
15888 "Property: " (mapcar 'list (org-buffer-property-keys nil t))))
15889 (cur (org-entry-get nil prop))
15890 (allowed (org-property-get-allowed-values nil prop 'table))
15891 (existing (mapcar 'list (org-property-values prop)))
15892 (val (if allowed
15893 (completing-read "Value: " allowed nil 'req-match)
15894 (completing-read
15895 (concat "Value" (if (and cur (string-match "\\S-" cur))
15896 (concat "[" cur "]") "")
15897 ": ")
15898 existing nil nil "" nil cur))))
15899 (list prop (if (equal val "") cur val))))
15900 (unless (equal (org-entry-get nil property) value)
15901 (org-entry-put nil property value)))
15903 (defun org-delete-property (property)
15904 "In the current entry, delete PROPERTY."
15905 (interactive
15906 (let* ((prop (completing-read
15907 "Property: " (org-entry-properties nil 'standard))))
15908 (list prop)))
15909 (message "Property %s %s" property
15910 (if (org-entry-delete nil property)
15911 "deleted"
15912 "was not present in the entry")))
15914 (defun org-delete-property-globally (property)
15915 "Remove PROPERTY globally, from all entries."
15916 (interactive
15917 (let* ((prop (completing-read
15918 "Globally remove property: "
15919 (mapcar 'list (org-buffer-property-keys)))))
15920 (list prop)))
15921 (save-excursion
15922 (save-restriction
15923 (widen)
15924 (goto-char (point-min))
15925 (let ((cnt 0))
15926 (while (re-search-forward
15927 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
15928 nil t)
15929 (setq cnt (1+ cnt))
15930 (replace-match ""))
15931 (message "Property \"%s\" removed from %d entries" property cnt)))))
15933 (defvar org-columns-current-fmt-compiled) ; defined below
15935 (defun org-compute-property-at-point ()
15936 "Compute the property at point.
15937 This looks for an enclosing column format, extracts the operator and
15938 then applies it to the proerty in the column format's scope."
15939 (interactive)
15940 (unless (org-at-property-p)
15941 (error "Not at a property"))
15942 (let ((prop (org-match-string-no-properties 2)))
15943 (org-columns-get-format-and-top-level)
15944 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15945 (error "No operator defined for property %s" prop))
15946 (org-columns-compute prop)))
15948 (defun org-property-get-allowed-values (pom property &optional table)
15949 "Get allowed values for the property PROPERTY.
15950 When TABLE is non-nil, return an alist that can directly be used for
15951 completion."
15952 (let (vals)
15953 (cond
15954 ((equal property "TODO")
15955 (setq vals (org-with-point-at pom
15956 (append org-todo-keywords-1 '("")))))
15957 ((equal property "PRIORITY")
15958 (let ((n org-lowest-priority))
15959 (while (>= n org-highest-priority)
15960 (push (char-to-string n) vals)
15961 (setq n (1- n)))))
15962 ((member property org-special-properties))
15964 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15966 (when (and vals (string-match "\\S-" vals))
15967 (setq vals (car (read-from-string (concat "(" vals ")"))))
15968 (setq vals (mapcar (lambda (x)
15969 (cond ((stringp x) x)
15970 ((numberp x) (number-to-string x))
15971 ((symbolp x) (symbol-name x))
15972 (t "???")))
15973 vals)))))
15974 (if table (mapcar 'list vals) vals)))
15976 (defun org-property-previous-allowed-value (&optional previous)
15977 "Switch to the next allowed value for this property."
15978 (interactive)
15979 (org-property-next-allowed-value t))
15981 (defun org-property-next-allowed-value (&optional previous)
15982 "Switch to the next allowed value for this property."
15983 (interactive)
15984 (unless (org-at-property-p)
15985 (error "Not at a property"))
15986 (let* ((key (match-string 2))
15987 (value (match-string 3))
15988 (allowed (or (org-property-get-allowed-values (point) key)
15989 (and (member value '("[ ]" "[-]" "[X]"))
15990 '("[ ]" "[X]"))))
15991 nval)
15992 (unless allowed
15993 (error "Allowed values for this property have not been defined"))
15994 (if previous (setq allowed (reverse allowed)))
15995 (if (member value allowed)
15996 (setq nval (car (cdr (member value allowed)))))
15997 (setq nval (or nval (car allowed)))
15998 (if (equal nval value)
15999 (error "Only one allowed value for this property"))
16000 (org-at-property-p)
16001 (replace-match (concat " :" key ": " nval) t t)
16002 (org-indent-line-function)
16003 (beginning-of-line 1)
16004 (skip-chars-forward " \t")))
16006 (defun org-find-entry-with-id (ident)
16007 "Locate the entry that contains the ID property with exact value IDENT.
16008 IDENT can be a string, a symbol or a number, this function will search for
16009 the string representation of it.
16010 Return the position where this entry starts, or nil if there is no such entry."
16011 (let ((id (cond
16012 ((stringp ident) ident)
16013 ((symbol-name ident) (symbol-name ident))
16014 ((numberp ident) (number-to-string ident))
16015 (t (error "IDENT %s must be a string, symbol or number" ident))))
16016 (case-fold-search nil))
16017 (save-excursion
16018 (save-restriction
16019 (goto-char (point-min))
16020 (when (re-search-forward
16021 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16022 nil t)
16023 (org-back-to-heading)
16024 (point))))))
16026 ;;; Column View
16028 (defvar org-columns-overlays nil
16029 "Holds the list of current column overlays.")
16031 (defvar org-columns-current-fmt nil
16032 "Local variable, holds the currently active column format.")
16033 (defvar org-columns-current-fmt-compiled nil
16034 "Local variable, holds the currently active column format.
16035 This is the compiled version of the format.")
16036 (defvar org-columns-current-widths nil
16037 "Loval variable, holds the currently widths of fields.")
16038 (defvar org-columns-current-maxwidths nil
16039 "Loval variable, holds the currently active maximum column widths.")
16040 (defvar org-columns-begin-marker (make-marker)
16041 "Points to the position where last a column creation command was called.")
16042 (defvar org-columns-top-level-marker (make-marker)
16043 "Points to the position where current columns region starts.")
16045 (defvar org-columns-map (make-sparse-keymap)
16046 "The keymap valid in column display.")
16048 (defun org-columns-content ()
16049 "Switch to contents view while in columns view."
16050 (interactive)
16051 (org-overview)
16052 (org-content))
16054 (org-defkey org-columns-map "c" 'org-columns-content)
16055 (org-defkey org-columns-map "o" 'org-overview)
16056 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16057 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16058 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16059 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16060 (org-defkey org-columns-map "v" 'org-columns-show-value)
16061 (org-defkey org-columns-map "q" 'org-columns-quit)
16062 (org-defkey org-columns-map "r" 'org-columns-redo)
16063 (org-defkey org-columns-map [left] 'backward-char)
16064 (org-defkey org-columns-map "\M-b" 'backward-char)
16065 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16066 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16067 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16068 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16069 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16070 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16071 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16072 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16073 (org-defkey org-columns-map "<" 'org-columns-narrow)
16074 (org-defkey org-columns-map ">" 'org-columns-widen)
16075 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16076 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16077 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16078 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16080 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16081 '("Column"
16082 ["Edit property" org-columns-edit-value t]
16083 ["Next allowed value" org-columns-next-allowed-value t]
16084 ["Previous allowed value" org-columns-previous-allowed-value t]
16085 ["Show full value" org-columns-show-value t]
16086 ["Edit allowed values" org-columns-edit-allowed t]
16087 "--"
16088 ["Edit column attributes" org-columns-edit-attributes t]
16089 ["Increase column width" org-columns-widen t]
16090 ["Decrease column width" org-columns-narrow t]
16091 "--"
16092 ["Move column right" org-columns-move-right t]
16093 ["Move column left" org-columns-move-left t]
16094 ["Add column" org-columns-new t]
16095 ["Delete column" org-columns-delete t]
16096 "--"
16097 ["CONTENTS" org-columns-content t]
16098 ["OVERVIEW" org-overview t]
16099 ["Refresh columns display" org-columns-redo t]
16100 "--"
16101 ["Open link" org-columns-open-link t]
16102 "--"
16103 ["Quit" org-columns-quit t]))
16105 (defun org-columns-new-overlay (beg end &optional string face)
16106 "Create a new column overlay and add it to the list."
16107 (let ((ov (org-make-overlay beg end)))
16108 (org-overlay-put ov 'face (or face 'secondary-selection))
16109 (org-overlay-display ov string face)
16110 (push ov org-columns-overlays)
16111 ov))
16113 (defun org-columns-display-here (&optional props)
16114 "Overlay the current line with column display."
16115 (interactive)
16116 (let* ((fmt org-columns-current-fmt-compiled)
16117 (beg (point-at-bol))
16118 (level-face (save-excursion
16119 (beginning-of-line 1)
16120 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16121 (org-get-level-face 2))))
16122 (color (list :foreground
16123 (face-attribute (or level-face 'default) :foreground)))
16124 props pom property ass width f string ov column val modval)
16125 ;; Check if the entry is in another buffer.
16126 (unless props
16127 (if (eq major-mode 'org-agenda-mode)
16128 (setq pom (or (get-text-property (point) 'org-hd-marker)
16129 (get-text-property (point) 'org-marker))
16130 props (if pom (org-entry-properties pom) nil))
16131 (setq props (org-entry-properties nil))))
16132 ;; Walk the format
16133 (while (setq column (pop fmt))
16134 (setq property (car column)
16135 ass (if (equal property "ITEM")
16136 (cons "ITEM"
16137 (save-match-data
16138 (org-no-properties
16139 (org-remove-tabs
16140 (buffer-substring-no-properties
16141 (point-at-bol) (point-at-eol))))))
16142 (assoc property props))
16143 width (or (cdr (assoc property org-columns-current-maxwidths))
16144 (nth 2 column)
16145 (length property))
16146 f (format "%%-%d.%ds | " width width)
16147 val (or (cdr ass) "")
16148 modval (if (equal property "ITEM")
16149 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16150 string (format f (or modval val)))
16151 ;; Create the overlay
16152 (org-unmodified
16153 (setq ov (org-columns-new-overlay
16154 beg (setq beg (1+ beg)) string
16155 (list color 'org-column)))
16156 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16157 (org-overlay-put ov 'keymap org-columns-map)
16158 (org-overlay-put ov 'org-columns-key property)
16159 (org-overlay-put ov 'org-columns-value (cdr ass))
16160 (org-overlay-put ov 'org-columns-value-modified modval)
16161 (org-overlay-put ov 'org-columns-pom pom)
16162 (org-overlay-put ov 'org-columns-format f))
16163 (if (or (not (char-after beg))
16164 (equal (char-after beg) ?\n))
16165 (let ((inhibit-read-only t))
16166 (save-excursion
16167 (goto-char beg)
16168 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16169 ;; Make the rest of the line disappear.
16170 (org-unmodified
16171 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16172 (org-overlay-put ov 'invisible t)
16173 (org-overlay-put ov 'keymap org-columns-map)
16174 (org-overlay-put ov 'intangible t)
16175 (push ov org-columns-overlays)
16176 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16177 (org-overlay-put ov 'keymap org-columns-map)
16178 (push ov org-columns-overlays)
16179 (let ((inhibit-read-only t))
16180 (put-text-property (max (point-min) (1- (point-at-bol)))
16181 (min (point-max) (1+ (point-at-eol)))
16182 'read-only "Type `e' to edit property")))))
16184 (defvar org-previous-header-line-format nil
16185 "The header line format before column view was turned on.")
16186 (defvar org-columns-inhibit-recalculation nil
16187 "Inhibit recomputing of columns on column view startup.")
16190 (defvar header-line-format)
16191 (defun org-columns-display-here-title ()
16192 "Overlay the newline before the current line with the table title."
16193 (interactive)
16194 (let ((fmt org-columns-current-fmt-compiled)
16195 string (title "")
16196 property width f column str widths)
16197 (while (setq column (pop fmt))
16198 (setq property (car column)
16199 str (or (nth 1 column) property)
16200 width (or (cdr (assoc property org-columns-current-maxwidths))
16201 (nth 2 column)
16202 (length str))
16203 widths (push width widths)
16204 f (format "%%-%d.%ds | " width width)
16205 string (format f str)
16206 title (concat title string)))
16207 (setq title (concat
16208 (org-add-props " " nil 'display '(space :align-to 0))
16209 (org-add-props title nil 'face '(:weight bold :underline t))))
16210 (org-set-local 'org-previous-header-line-format header-line-format)
16211 (org-set-local 'org-columns-current-widths (nreverse widths))
16212 (setq header-line-format title)))
16214 (defun org-columns-remove-overlays ()
16215 "Remove all currently active column overlays."
16216 (interactive)
16217 (when (marker-buffer org-columns-begin-marker)
16218 (with-current-buffer (marker-buffer org-columns-begin-marker)
16219 (when (local-variable-p 'org-previous-header-line-format)
16220 (setq header-line-format org-previous-header-line-format)
16221 (kill-local-variable 'org-previous-header-line-format))
16222 (move-marker org-columns-begin-marker nil)
16223 (move-marker org-columns-top-level-marker nil)
16224 (org-unmodified
16225 (mapc 'org-delete-overlay org-columns-overlays)
16226 (setq org-columns-overlays nil)
16227 (let ((inhibit-read-only t))
16228 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16230 (defun org-columns-cleanup-item (item fmt)
16231 "Remove from ITEM what is a column in the format FMT."
16232 (if (not org-complex-heading-regexp)
16233 item
16234 (when (string-match org-complex-heading-regexp item)
16235 (concat
16236 (org-add-props (concat (match-string 1 item) " ") nil
16237 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16238 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16239 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16240 " " (match-string 4 item)
16241 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16243 (defun org-columns-show-value ()
16244 "Show the full value of the property."
16245 (interactive)
16246 (let ((value (get-char-property (point) 'org-columns-value)))
16247 (message "Value is: %s" (or value ""))))
16249 (defun org-columns-quit ()
16250 "Remove the column overlays and in this way exit column editing."
16251 (interactive)
16252 (org-unmodified
16253 (org-columns-remove-overlays)
16254 (let ((inhibit-read-only t))
16255 (remove-text-properties (point-min) (point-max) '(read-only t))))
16256 (when (eq major-mode 'org-agenda-mode)
16257 (message
16258 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16260 (defun org-columns-check-computed ()
16261 "Check if this column value is computed.
16262 If yes, throw an error indicating that changing it does not make sense."
16263 (let ((val (get-char-property (point) 'org-columns-value)))
16264 (when (and (stringp val)
16265 (get-char-property 0 'org-computed val))
16266 (error "This value is computed from the entry's children"))))
16268 (defun org-columns-todo (&optional arg)
16269 "Change the TODO state during column view."
16270 (interactive "P")
16271 (org-columns-edit-value "TODO"))
16273 (defun org-columns-set-tags-or-toggle (&optional arg)
16274 "Toggle checkbox at point, or set tags for current headline."
16275 (interactive "P")
16276 (if (string-match "\\`\\[[ xX-]\\]\\'"
16277 (get-char-property (point) 'org-columns-value))
16278 (org-columns-next-allowed-value)
16279 (org-columns-edit-value "TAGS")))
16281 (defun org-columns-edit-value (&optional key)
16282 "Edit the value of the property at point in column view.
16283 Where possible, use the standard interface for changing this line."
16284 (interactive)
16285 (org-columns-check-computed)
16286 (let* ((external-key key)
16287 (col (current-column))
16288 (key (or key (get-char-property (point) 'org-columns-key)))
16289 (value (get-char-property (point) 'org-columns-value))
16290 (bol (point-at-bol)) (eol (point-at-eol))
16291 (pom (or (get-text-property bol 'org-hd-marker)
16292 (point))) ; keep despite of compiler waring
16293 (line-overlays
16294 (delq nil (mapcar (lambda (x)
16295 (and (eq (overlay-buffer x) (current-buffer))
16296 (>= (overlay-start x) bol)
16297 (<= (overlay-start x) eol)
16299 org-columns-overlays)))
16300 nval eval allowed)
16301 (cond
16302 ((equal key "ITEM")
16303 (setq eval '(org-with-point-at pom
16304 (org-edit-headline))))
16305 ((equal key "TODO")
16306 (setq eval '(org-with-point-at pom
16307 (let ((current-prefix-arg
16308 (if external-key current-prefix-arg '(4))))
16309 (call-interactively 'org-todo)))))
16310 ((equal key "PRIORITY")
16311 (setq eval '(org-with-point-at pom
16312 (call-interactively 'org-priority))))
16313 ((equal key "TAGS")
16314 (setq eval '(org-with-point-at pom
16315 (let ((org-fast-tag-selection-single-key
16316 (if (eq org-fast-tag-selection-single-key 'expert)
16317 t org-fast-tag-selection-single-key)))
16318 (call-interactively 'org-set-tags)))))
16319 ((equal key "DEADLINE")
16320 (setq eval '(org-with-point-at pom
16321 (call-interactively 'org-deadline))))
16322 ((equal key "SCHEDULED")
16323 (setq eval '(org-with-point-at pom
16324 (call-interactively 'org-schedule))))
16326 (setq allowed (org-property-get-allowed-values pom key 'table))
16327 (if allowed
16328 (setq nval (completing-read "Value: " allowed nil t))
16329 (setq nval (read-string "Edit: " value)))
16330 (setq nval (org-trim nval))
16331 (when (not (equal nval value))
16332 (setq eval '(org-entry-put pom key nval)))))
16333 (when eval
16334 (let ((inhibit-read-only t))
16335 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
16336 (unwind-protect
16337 (progn
16338 (setq org-columns-overlays
16339 (org-delete-all line-overlays org-columns-overlays))
16340 (mapc 'org-delete-overlay line-overlays)
16341 (org-columns-eval eval))
16342 (org-columns-display-here))))
16343 (move-to-column col)
16344 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
16345 (org-columns-update key))))
16347 (defun org-edit-headline () ; FIXME: this is not columns specific
16348 "Edit the current headline, the part without TODO keyword, TAGS."
16349 (org-back-to-heading)
16350 (when (looking-at org-todo-line-regexp)
16351 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
16352 (txt (match-string 3))
16353 (post "")
16354 txt2)
16355 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
16356 (setq post (match-string 0 txt)
16357 txt (substring txt 0 (match-beginning 0))))
16358 (setq txt2 (read-string "Edit: " txt))
16359 (when (not (equal txt txt2))
16360 (beginning-of-line 1)
16361 (insert pre txt2 post)
16362 (delete-region (point) (point-at-eol))
16363 (org-set-tags nil t)))))
16365 (defun org-columns-edit-allowed ()
16366 "Edit the list of allowed values for the current property."
16367 (interactive)
16368 (let* ((key (get-char-property (point) 'org-columns-key))
16369 (key1 (concat key "_ALL"))
16370 (allowed (org-entry-get (point) key1 t))
16371 nval)
16372 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
16373 (setq nval (read-string "Allowed: " allowed))
16374 (org-entry-put
16375 (cond ((marker-position org-entry-property-inherited-from)
16376 org-entry-property-inherited-from)
16377 ((marker-position org-columns-top-level-marker)
16378 org-columns-top-level-marker))
16379 key1 nval)))
16381 (defmacro org-no-warnings (&rest body)
16382 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
16384 (defun org-columns-eval (form)
16385 (let (hidep)
16386 (save-excursion
16387 (beginning-of-line 1)
16388 ;; `next-line' is needed here, because it skips invisible line.
16389 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
16390 (setq hidep (org-on-heading-p 1)))
16391 (eval form)
16392 (and hidep (hide-entry))))
16394 (defun org-columns-previous-allowed-value ()
16395 "Switch to the previous allowed value for this column."
16396 (interactive)
16397 (org-columns-next-allowed-value t))
16399 (defun org-columns-next-allowed-value (&optional previous)
16400 "Switch to the next allowed value for this column."
16401 (interactive)
16402 (org-columns-check-computed)
16403 (let* ((col (current-column))
16404 (key (get-char-property (point) 'org-columns-key))
16405 (value (get-char-property (point) 'org-columns-value))
16406 (bol (point-at-bol)) (eol (point-at-eol))
16407 (pom (or (get-text-property bol 'org-hd-marker)
16408 (point))) ; keep despite of compiler waring
16409 (line-overlays
16410 (delq nil (mapcar (lambda (x)
16411 (and (eq (overlay-buffer x) (current-buffer))
16412 (>= (overlay-start x) bol)
16413 (<= (overlay-start x) eol)
16415 org-columns-overlays)))
16416 (allowed (or (org-property-get-allowed-values pom key)
16417 (and (equal
16418 (nth 4 (assoc key org-columns-current-fmt-compiled))
16419 'checkbox) '("[ ]" "[X]"))))
16420 nval)
16421 (when (equal key "ITEM")
16422 (error "Cannot edit item headline from here"))
16423 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
16424 (error "Allowed values for this property have not been defined"))
16425 (if (member key '("SCHEDULED" "DEADLINE"))
16426 (setq nval (if previous 'earlier 'later))
16427 (if previous (setq allowed (reverse allowed)))
16428 (if (member value allowed)
16429 (setq nval (car (cdr (member value allowed)))))
16430 (setq nval (or nval (car allowed)))
16431 (if (equal nval value)
16432 (error "Only one allowed value for this property")))
16433 (let ((inhibit-read-only t))
16434 (remove-text-properties (1- bol) eol '(read-only t))
16435 (unwind-protect
16436 (progn
16437 (setq org-columns-overlays
16438 (org-delete-all line-overlays org-columns-overlays))
16439 (mapc 'org-delete-overlay line-overlays)
16440 (org-columns-eval '(org-entry-put pom key nval)))
16441 (org-columns-display-here)))
16442 (move-to-column col)
16443 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
16444 (org-columns-update key))))
16446 (defun org-verify-version (task)
16447 (cond
16448 ((eq task 'columns)
16449 (if (or (featurep 'xemacs)
16450 (< emacs-major-version 22))
16451 (error "Emacs 22 is required for the columns feature")))))
16453 (defun org-columns-open-link (&optional arg)
16454 (interactive "P")
16455 (let ((key (get-char-property (point) 'org-columns-key))
16456 (value (get-char-property (point) 'org-columns-value)))
16457 (org-open-link-from-string arg)))
16459 (defun org-open-link-from-string (s &optional arg)
16460 "Open a link in the string S, as if it was in Org-mode."
16461 (interactive)
16462 (with-temp-buffer
16463 (let ((org-inhibit-startup t))
16464 (org-mode)
16465 (insert s)
16466 (goto-char (point-min))
16467 (org-open-at-point arg))))
16469 (defun org-columns-get-format-and-top-level ()
16470 (let (fmt)
16471 (when (condition-case nil (org-back-to-heading) (error nil))
16472 (move-marker org-entry-property-inherited-from nil)
16473 (setq fmt (org-entry-get nil "COLUMNS" t)))
16474 (setq fmt (or fmt org-columns-default-format))
16475 (org-set-local 'org-columns-current-fmt fmt)
16476 (org-columns-compile-format fmt)
16477 (if (marker-position org-entry-property-inherited-from)
16478 (move-marker org-columns-top-level-marker
16479 org-entry-property-inherited-from)
16480 (move-marker org-columns-top-level-marker (point)))
16481 fmt))
16483 (defun org-columns ()
16484 "Turn on column view on an org-mode file."
16485 (interactive)
16486 (org-verify-version 'columns)
16487 (org-columns-remove-overlays)
16488 (move-marker org-columns-begin-marker (point))
16489 (let (beg end fmt cache maxwidths)
16490 (setq fmt (org-columns-get-format-and-top-level))
16491 (save-excursion
16492 (goto-char org-columns-top-level-marker)
16493 (setq beg (point))
16494 (unless org-columns-inhibit-recalculation
16495 (org-columns-compute-all))
16496 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
16497 (point-max)))
16498 (goto-char beg)
16499 ;; Get and cache the properties
16500 (while (re-search-forward (concat "^" outline-regexp) end t)
16501 (push (cons (org-current-line) (org-entry-properties)) cache))
16502 (when cache
16503 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16504 (org-set-local 'org-columns-current-maxwidths maxwidths)
16505 (org-columns-display-here-title)
16506 (mapc (lambda (x)
16507 (goto-line (car x))
16508 (org-columns-display-here (cdr x)))
16509 cache)))))
16511 (defun org-columns-new (&optional prop title width op fmt)
16512 "Insert a new column, to the leeft o the current column."
16513 (interactive)
16514 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
16515 cell)
16516 (setq prop (completing-read
16517 "Property: " (mapcar 'list (org-buffer-property-keys t))
16518 nil nil prop))
16519 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
16520 (setq width (read-string "Column width: " (if width (number-to-string width))))
16521 (if (string-match "\\S-" width)
16522 (setq width (string-to-number width))
16523 (setq width nil))
16524 (setq fmt (completing-read "Summary [none]: "
16525 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox"))
16526 nil t))
16527 (if (string-match "\\S-" fmt)
16528 (setq fmt (intern fmt))
16529 (setq fmt nil))
16530 (if (eq fmt 'none) (setq fmt nil))
16531 (if editp
16532 (progn
16533 (setcar editp prop)
16534 (setcdr editp (list title width nil fmt)))
16535 (setq cell (nthcdr (1- (current-column))
16536 org-columns-current-fmt-compiled))
16537 (setcdr cell (cons (list prop title width nil fmt)
16538 (cdr cell))))
16539 (org-columns-store-format)
16540 (org-columns-redo)))
16542 (defun org-columns-delete ()
16543 "Delete the column at point from columns view."
16544 (interactive)
16545 (let* ((n (current-column))
16546 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
16547 (when (y-or-n-p
16548 (format "Are you sure you want to remove column \"%s\"? " title))
16549 (setq org-columns-current-fmt-compiled
16550 (delq (nth n org-columns-current-fmt-compiled)
16551 org-columns-current-fmt-compiled))
16552 (org-columns-store-format)
16553 (org-columns-redo)
16554 (if (>= (current-column) (length org-columns-current-fmt-compiled))
16555 (backward-char 1)))))
16557 (defun org-columns-edit-attributes ()
16558 "Edit the attributes of the current column."
16559 (interactive)
16560 (let* ((n (current-column))
16561 (info (nth n org-columns-current-fmt-compiled)))
16562 (apply 'org-columns-new info)))
16564 (defun org-columns-widen (arg)
16565 "Make the column wider by ARG characters."
16566 (interactive "p")
16567 (let* ((n (current-column))
16568 (entry (nth n org-columns-current-fmt-compiled))
16569 (width (or (nth 2 entry)
16570 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
16571 (setq width (max 1 (+ width arg)))
16572 (setcar (nthcdr 2 entry) width)
16573 (org-columns-store-format)
16574 (org-columns-redo)))
16576 (defun org-columns-narrow (arg)
16577 "Make the column nrrower by ARG characters."
16578 (interactive "p")
16579 (org-columns-widen (- arg)))
16581 (defun org-columns-move-right ()
16582 "Swap this column with the one to the right."
16583 (interactive)
16584 (let* ((n (current-column))
16585 (cell (nthcdr n org-columns-current-fmt-compiled))
16587 (when (>= n (1- (length org-columns-current-fmt-compiled)))
16588 (error "Cannot shift this column further to the right"))
16589 (setq e (car cell))
16590 (setcar cell (car (cdr cell)))
16591 (setcdr cell (cons e (cdr (cdr cell))))
16592 (org-columns-store-format)
16593 (org-columns-redo)
16594 (forward-char 1)))
16596 (defun org-columns-move-left ()
16597 "Swap this column with the one to the left."
16598 (interactive)
16599 (let* ((n (current-column)))
16600 (when (= n 0)
16601 (error "Cannot shift this column further to the left"))
16602 (backward-char 1)
16603 (org-columns-move-right)
16604 (backward-char 1)))
16606 (defun org-columns-store-format ()
16607 "Store the text version of the current columns format in appropriate place.
16608 This is either in the COLUMNS property of the node starting the current column
16609 display, or in the #+COLUMNS line of the current buffer."
16610 (let (fmt (cnt 0))
16611 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
16612 (org-set-local 'org-columns-current-fmt fmt)
16613 (if (marker-position org-columns-top-level-marker)
16614 (save-excursion
16615 (goto-char org-columns-top-level-marker)
16616 (if (and (org-at-heading-p)
16617 (org-entry-get nil "COLUMNS"))
16618 (org-entry-put nil "COLUMNS" fmt)
16619 (goto-char (point-min))
16620 ;; Overwrite all #+COLUMNS lines....
16621 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
16622 (setq cnt (1+ cnt))
16623 (replace-match (concat "#+COLUMNS: " fmt) t t))
16624 (unless (> cnt 0)
16625 (goto-char (point-min))
16626 (or (org-on-heading-p t) (outline-next-heading))
16627 (let ((inhibit-read-only t))
16628 (insert-before-markers "#+COLUMNS: " fmt "\n")))
16629 (org-set-local 'org-columns-default-format fmt))))))
16631 (defvar org-overriding-columns-format nil
16632 "When set, overrides any other definition.")
16633 (defvar org-agenda-view-columns-initially nil
16634 "When set, switch to columns view immediately after creating the agenda.")
16636 (defun org-agenda-columns ()
16637 "Turn on column view in the agenda."
16638 (interactive)
16639 (org-verify-version 'columns)
16640 (org-columns-remove-overlays)
16641 (move-marker org-columns-begin-marker (point))
16642 (let (fmt cache maxwidths m)
16643 (cond
16644 ((and (local-variable-p 'org-overriding-columns-format)
16645 org-overriding-columns-format)
16646 (setq fmt org-overriding-columns-format))
16647 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
16648 (setq fmt (org-entry-get m "COLUMNS" t)))
16649 ((and (boundp 'org-columns-current-fmt)
16650 (local-variable-p 'org-columns-current-fmt)
16651 org-columns-current-fmt)
16652 (setq fmt org-columns-current-fmt))
16653 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
16654 (setq m (get-text-property m 'org-hd-marker))
16655 (setq fmt (org-entry-get m "COLUMNS" t))))
16656 (setq fmt (or fmt org-columns-default-format))
16657 (org-set-local 'org-columns-current-fmt fmt)
16658 (org-columns-compile-format fmt)
16659 (save-excursion
16660 ;; Get and cache the properties
16661 (goto-char (point-min))
16662 (while (not (eobp))
16663 (when (setq m (or (get-text-property (point) 'org-hd-marker)
16664 (get-text-property (point) 'org-marker)))
16665 (push (cons (org-current-line) (org-entry-properties m)) cache))
16666 (beginning-of-line 2))
16667 (when cache
16668 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16669 (org-set-local 'org-columns-current-maxwidths maxwidths)
16670 (org-columns-display-here-title)
16671 (mapc (lambda (x)
16672 (goto-line (car x))
16673 (org-columns-display-here (cdr x)))
16674 cache)))))
16676 (defun org-columns-get-autowidth-alist (s cache)
16677 "Derive the maximum column widths from the format and the cache."
16678 (let ((start 0) rtn)
16679 (while (string-match (org-re "%\\([[:alpha:]]\\S-*\\)") s start)
16680 (push (cons (match-string 1 s) 1) rtn)
16681 (setq start (match-end 0)))
16682 (mapc (lambda (x)
16683 (setcdr x (apply 'max
16684 (mapcar
16685 (lambda (y)
16686 (length (or (cdr (assoc (car x) (cdr y))) " ")))
16687 cache))))
16688 rtn)
16689 rtn))
16691 (defun org-columns-compute-all ()
16692 "Compute all columns that have operators defined."
16693 (org-unmodified
16694 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
16695 (let ((columns org-columns-current-fmt-compiled) col)
16696 (while (setq col (pop columns))
16697 (when (nth 3 col)
16698 (save-excursion
16699 (org-columns-compute (car col)))))))
16701 (defun org-columns-update (property)
16702 "Recompute PROPERTY, and update the columns display for it."
16703 (org-columns-compute property)
16704 (let (fmt val pos)
16705 (save-excursion
16706 (mapc (lambda (ov)
16707 (when (equal (org-overlay-get ov 'org-columns-key) property)
16708 (setq pos (org-overlay-start ov))
16709 (goto-char pos)
16710 (when (setq val (cdr (assoc property
16711 (get-text-property
16712 (point-at-bol) 'org-summaries))))
16713 (setq fmt (org-overlay-get ov 'org-columns-format))
16714 (org-overlay-put ov 'org-columns-value val)
16715 (org-overlay-put ov 'display (format fmt val)))))
16716 org-columns-overlays))))
16718 (defun org-columns-compute (property)
16719 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
16720 (interactive)
16721 (let* ((re (concat "^" outline-regexp))
16722 (lmax 30) ; Does anyone use deeper levels???
16723 (lsum (make-vector lmax 0))
16724 (lflag (make-vector lmax nil))
16725 (level 0)
16726 (ass (assoc property org-columns-current-fmt-compiled))
16727 (format (nth 4 ass))
16728 (printf (nth 5 ass))
16729 (beg org-columns-top-level-marker)
16730 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
16731 (save-excursion
16732 ;; Find the region to compute
16733 (goto-char beg)
16734 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
16735 (goto-char end)
16736 ;; Walk the tree from the back and do the computations
16737 (while (re-search-backward re beg t)
16738 (setq sumpos (match-beginning 0)
16739 last-level level
16740 level (org-outline-level)
16741 val (org-entry-get nil property)
16742 valflag (and val (string-match "\\S-" val)))
16743 (cond
16744 ((< level last-level)
16745 ;; put the sum of lower levels here as a property
16746 (setq sum (aref lsum last-level) ; current sum
16747 flag (aref lflag last-level) ; any valid entries from children?
16748 str (org-column-number-to-string sum format printf)
16749 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
16750 useval (if flag str1 (if valflag val ""))
16751 sum-alist (get-text-property sumpos 'org-summaries))
16752 (if (assoc property sum-alist)
16753 (setcdr (assoc property sum-alist) useval)
16754 (push (cons property useval) sum-alist)
16755 (org-unmodified
16756 (add-text-properties sumpos (1+ sumpos)
16757 (list 'org-summaries sum-alist))))
16758 (when val
16759 (org-entry-put nil property (if flag str val)))
16760 ;; add current to current level accumulator
16761 (when (or flag valflag)
16762 (aset lsum level (+ (aref lsum level)
16763 (if flag sum (org-column-string-to-number
16764 (if flag str val) format))))
16765 (aset lflag level t))
16766 ;; clear accumulators for deeper levels
16767 (loop for l from (1+ level) to (1- lmax) do
16768 (aset lsum l 0)
16769 (aset lflag l nil)))
16770 ((>= level last-level)
16771 ;; add what we have here to the accumulator for this level
16772 (aset lsum level (+ (aref lsum level)
16773 (org-column-string-to-number (or val "0") format)))
16774 (and valflag (aset lflag level t)))
16775 (t (error "This should not happen")))))))
16777 (defun org-columns-redo ()
16778 "Construct the column display again."
16779 (interactive)
16780 (message "Recomputing columns...")
16781 (save-excursion
16782 (if (marker-position org-columns-begin-marker)
16783 (goto-char org-columns-begin-marker))
16784 (org-columns-remove-overlays)
16785 (if (org-mode-p)
16786 (call-interactively 'org-columns)
16787 (call-interactively 'org-agenda-columns)))
16788 (message "Recomputing columns...done"))
16790 (defun org-columns-not-in-agenda ()
16791 (if (eq major-mode 'org-agenda-mode)
16792 (error "This command is only allowed in Org-mode buffers")))
16795 (defun org-string-to-number (s)
16796 "Convert string to number, and interpret hh:mm:ss."
16797 (if (not (string-match ":" s))
16798 (string-to-number s)
16799 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
16800 (while l
16801 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
16802 sum)))
16804 (defun org-column-number-to-string (n fmt printf)
16805 "Convert a computed column number to a string value, according to FMT."
16806 (cond
16807 ((eq fmt 'add_times)
16808 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
16809 (format "%d:%02d" h m)))
16810 ((eq fmt 'checkbox)
16811 (cond ((= n (floor n)) "[X]")
16812 ((> n 1.) "[-]")
16813 (t "[ ]")))
16814 (printf (format printf n))
16815 ((eq fmt 'currency)
16816 (format "%.2f" n))
16817 (t (number-to-string n))))
16819 (defun org-column-string-to-number (s fmt)
16820 "Convert a column value to a number that can be used for column computing."
16821 (cond
16822 ((string-match ":" s)
16823 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
16824 (while l
16825 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
16826 sum))
16827 ((eq fmt 'checkbox)
16828 (if (equal s "[X]") 1. 0.000001))
16829 (t (string-to-number s))))
16831 (defun org-columns-uncompile-format (cfmt)
16832 "Turn the compiled columns format back into a string representation."
16833 (let ((rtn "") e s prop title op width fmt printf)
16834 (while (setq e (pop cfmt))
16835 (setq prop (car e)
16836 title (nth 1 e)
16837 width (nth 2 e)
16838 op (nth 3 e)
16839 fmt (nth 4 e)
16840 printf (nth 5 e))
16841 (cond
16842 ((eq fmt 'add_times) (setq op ":"))
16843 ((eq fmt 'checkbox) (setq op "X"))
16844 ((eq fmt 'add_numbers) (setq op "+"))
16845 ((eq fmt 'currency) (setq op "$")))
16846 (if (and op printf) (setq op (concat op ";" printf)))
16847 (if (equal title prop) (setq title nil))
16848 (setq s (concat "%" (if width (number-to-string width))
16849 prop
16850 (if title (concat "(" title ")"))
16851 (if op (concat "{" op "}"))))
16852 (setq rtn (concat rtn " " s)))
16853 (org-trim rtn)))
16855 (defun org-columns-compile-format (fmt)
16856 "Turn a column format string into an alist of specifications.
16857 The alist has one entry for each column in the format. The elements of
16858 that list are:
16859 property the property
16860 title the title field for the columns
16861 width the column width in characters, can be nil for automatic
16862 operator the operator if any
16863 format the output format for computed results, derived from operator
16864 printf a printf format for computed values"
16865 (let ((start 0) width prop title op f printf)
16866 (setq org-columns-current-fmt-compiled nil)
16867 (while (string-match
16868 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
16869 fmt start)
16870 (setq start (match-end 0)
16871 width (match-string 1 fmt)
16872 prop (match-string 2 fmt)
16873 title (or (match-string 3 fmt) prop)
16874 op (match-string 4 fmt)
16875 f nil
16876 printf nil)
16877 (if width (setq width (string-to-number width)))
16878 (when (and op (string-match ";" op))
16879 (setq printf (substring op (match-end 0))
16880 op (substring op 0 (match-beginning 0))))
16881 (cond
16882 ((equal op "+") (setq f 'add_numbers))
16883 ((equal op "$") (setq f 'currency))
16884 ((equal op ":") (setq f 'add_times))
16885 ((equal op "X") (setq f 'checkbox)))
16886 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
16887 (setq org-columns-current-fmt-compiled
16888 (nreverse org-columns-current-fmt-compiled))))
16891 ;;; Dynamic block for Column view
16893 (defun org-columns-capture-view ()
16894 "Get the column view of the current buffer and return it as a list.
16895 The list will contains the title row and all other rows. Each row is
16896 a list of fields."
16897 (save-excursion
16898 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
16899 (n (length title)) row tbl)
16900 (goto-char (point-min))
16901 (while (re-search-forward "^\\*+ " nil t)
16902 (when (get-char-property (match-beginning 0) 'org-columns-key)
16903 (setq row nil)
16904 (loop for i from 0 to (1- n) do
16905 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
16906 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
16908 row))
16909 (setq row (nreverse row))
16910 (push row tbl)))
16911 (append (list title 'hline) (nreverse tbl)))))
16913 (defun org-dblock-write:columnview (params)
16914 "Write the column view table.
16915 PARAMS is a property list of parameters:
16917 :width enforce same column widths with <N> specifiers.
16918 :id the :ID: property of the entry where the columns view
16919 should be built, as a string. When `local', call locally.
16920 When `global' call column view with the cursor at the beginning
16921 of the buffer (usually this means that the whole buffer switches
16922 to column view).
16923 :hlines When t, insert a hline before each item. When a number, insert
16924 a hline before each level <= that number.
16925 :vlines When t, make each column a colgroup to enforce vertical lines."
16926 (let ((pos (move-marker (make-marker) (point)))
16927 (hlines (plist-get params :hlines))
16928 (vlines (plist-get params :vlines))
16929 tbl id idpos nfields tmp)
16930 (save-excursion
16931 (save-restriction
16932 (when (setq id (plist-get params :id))
16933 (cond ((not id) nil)
16934 ((eq id 'global) (goto-char (point-min)))
16935 ((eq id 'local) nil)
16936 ((setq idpos (org-find-entry-with-id id))
16937 (goto-char idpos))
16938 (t (error "Cannot find entry with :ID: %s" id))))
16939 (org-columns)
16940 (setq tbl (org-columns-capture-view))
16941 (setq nfields (length (car tbl)))
16942 (org-columns-quit)))
16943 (goto-char pos)
16944 (move-marker pos nil)
16945 (when tbl
16946 (when (plist-get params :hlines)
16947 (setq tmp nil)
16948 (while tbl
16949 (if (eq (car tbl) 'hline)
16950 (push (pop tbl) tmp)
16951 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
16952 (if (and (not (eq (car tmp) 'hline))
16953 (or (eq hlines t)
16954 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
16955 (push 'hline tmp)))
16956 (push (pop tbl) tmp)))
16957 (setq tbl (nreverse tmp)))
16958 (when vlines
16959 (setq tbl (mapcar (lambda (x)
16960 (if (eq 'hline x) x (cons "" x)))
16961 tbl))
16962 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
16963 (setq pos (point))
16964 (insert (org-listtable-to-string tbl))
16965 (when (plist-get params :width)
16966 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
16967 org-columns-current-widths "|")))
16968 (goto-char pos)
16969 (org-table-align))))
16971 (defun org-listtable-to-string (tbl)
16972 "Convert a listtable TBL to a string that contains the Org-mode table.
16973 The table still need to be alligned. The resulting string has no leading
16974 and tailing newline characters."
16975 (mapconcat
16976 (lambda (x)
16977 (cond
16978 ((listp x)
16979 (concat "|" (mapconcat 'identity x "|") "|"))
16980 ((eq x 'hline) "|-|")
16981 (t (error "Garbage in listtable: %s" x))))
16982 tbl "\n"))
16984 (defun org-insert-columns-dblock ()
16985 "Create a dynamic block capturing a column view table."
16986 (interactive)
16987 (let ((defaults '(:name "columnview" :hlines 1))
16988 (id (completing-read
16989 "Capture columns (local, global, entry with :ID: property) [local]: "
16990 (append '(("global") ("local"))
16991 (mapcar 'list (org-property-values "ID"))))))
16992 (if (equal id "") (setq id 'local))
16993 (if (equal id "global") (setq id 'global))
16994 (setq defaults (append defaults (list :id id)))
16995 (org-create-dblock defaults)
16996 (org-update-dblock)))
16998 ;;;; Timestamps
17000 (defvar org-last-changed-timestamp nil)
17001 (defvar org-time-was-given) ; dynamically scoped parameter
17002 (defvar org-end-time-was-given) ; dynamically scoped parameter
17003 (defvar org-ts-what) ; dynamically scoped parameter
17005 (defun org-time-stamp (arg)
17006 "Prompt for a date/time and insert a time stamp.
17007 If the user specifies a time like HH:MM, or if this command is called
17008 with a prefix argument, the time stamp will contain date and time.
17009 Otherwise, only the date will be included. All parts of a date not
17010 specified by the user will be filled in from the current date/time.
17011 So if you press just return without typing anything, the time stamp
17012 will represent the current date/time. If there is already a timestamp
17013 at the cursor, it will be modified."
17014 (interactive "P")
17015 (let* ((ts nil)
17016 (default-time
17017 ;; Default time is either today, or, when entering a range,
17018 ;; the range start.
17019 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17020 (save-excursion
17021 (re-search-backward
17022 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17023 (- (point) 20) t)))
17024 (apply 'encode-time (org-parse-time-string (match-string 1)))
17025 (current-time)))
17026 (default-input (and ts (org-get-compact-tod ts)))
17027 org-time-was-given org-end-time-was-given time)
17028 (cond
17029 ((and (org-at-timestamp-p)
17030 (eq last-command 'org-time-stamp)
17031 (eq this-command 'org-time-stamp))
17032 (insert "--")
17033 (setq time (let ((this-command this-command))
17034 (org-read-date arg 'totime nil nil default-time default-input)))
17035 (org-insert-time-stamp time (or org-time-was-given arg)))
17036 ((org-at-timestamp-p)
17037 (setq time (let ((this-command this-command))
17038 (org-read-date arg 'totime nil nil default-time default-input)))
17039 (when (org-at-timestamp-p) ; just to get the match data
17040 (replace-match "")
17041 (setq org-last-changed-timestamp
17042 (org-insert-time-stamp
17043 time (or org-time-was-given arg)
17044 nil nil nil (list org-end-time-was-given))))
17045 (message "Timestamp updated"))
17047 (setq time (let ((this-command this-command))
17048 (org-read-date arg 'totime nil nil default-time default-input)))
17049 (org-insert-time-stamp time (or org-time-was-given arg)
17050 nil nil nil (list org-end-time-was-given))))))
17052 ;; FIXME: can we use this for something else????
17053 ;; like computing time differences?????
17054 (defun org-get-compact-tod (s)
17055 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17056 (let* ((t1 (match-string 1 s))
17057 (h1 (string-to-number (match-string 2 s)))
17058 (m1 (string-to-number (match-string 3 s)))
17059 (t2 (and (match-end 4) (match-string 5 s)))
17060 (h2 (and t2 (string-to-number (match-string 6 s))))
17061 (m2 (and t2 (string-to-number (match-string 7 s))))
17062 dh dm)
17063 (if (not t2)
17065 (setq dh (- h2 h1) dm (- m2 m1))
17066 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17067 (concat t1 "+" (number-to-string dh)
17068 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17070 (defun org-time-stamp-inactive (&optional arg)
17071 "Insert an inactive time stamp.
17072 An inactive time stamp is enclosed in square brackets instead of angle
17073 brackets. It is inactive in the sense that it does not trigger agenda entries,
17074 does not link to the calendar and cannot be changed with the S-cursor keys.
17075 So these are more for recording a certain time/date."
17076 (interactive "P")
17077 (let (org-time-was-given org-end-time-was-given time)
17078 (setq time (org-read-date arg 'totime))
17079 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17080 nil nil (list org-end-time-was-given))))
17082 (defvar org-date-ovl (org-make-overlay 1 1))
17083 (org-overlay-put org-date-ovl 'face 'org-warning)
17084 (org-detach-overlay org-date-ovl)
17086 (defvar org-ans1) ; dynamically scoped parameter
17087 (defvar org-ans2) ; dynamically scoped parameter
17089 (defvar org-plain-time-of-day-regexp) ; defined below
17091 (defvar org-read-date-overlay nil)
17092 (defvar org-dcst nil) ; dynamically scoped
17094 (defun org-read-date (&optional with-time to-time from-string prompt
17095 default-time default-input)
17096 "Read a date, possibly a time, and make things smooth for the user.
17097 The prompt will suggest to enter an ISO date, but you can also enter anything
17098 which will at least partially be understood by `parse-time-string'.
17099 Unrecognized parts of the date will default to the current day, month, year,
17100 hour and minute. If this command is called to replace a timestamp at point,
17101 of to enter the second timestamp of a range, the default time is taken from the
17102 existing stamp. For example,
17103 3-2-5 --> 2003-02-05
17104 feb 15 --> currentyear-02-15
17105 sep 12 9 --> 2009-09-12
17106 12:45 --> today 12:45
17107 22 sept 0:34 --> currentyear-09-22 0:34
17108 12 --> currentyear-currentmonth-12
17109 Fri --> nearest Friday (today or later)
17110 etc.
17112 Furthermore you can specify a relative date by giving, as the *first* thing
17113 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17114 change in days weeks, months, years.
17115 With a single plus or minus, the date is relative to today. With a double
17116 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17117 +4d --> four days from today
17118 +4 --> same as above
17119 +2w --> two weeks from today
17120 ++5 --> five days from default date
17122 The function understands only English month and weekday abbreviations,
17123 but this can be configured with the variables `parse-time-months' and
17124 `parse-time-weekdays'.
17126 While prompting, a calendar is popped up - you can also select the
17127 date with the mouse (button 1). The calendar shows a period of three
17128 months. To scroll it to other months, use the keys `>' and `<'.
17129 If you don't like the calendar, turn it off with
17130 \(setq org-read-date-popup-calendar nil)
17132 With optional argument TO-TIME, the date will immediately be converted
17133 to an internal time.
17134 With an optional argument WITH-TIME, the prompt will suggest to also
17135 insert a time. Note that when WITH-TIME is not set, you can still
17136 enter a time, and this function will inform the calling routine about
17137 this change. The calling routine may then choose to change the format
17138 used to insert the time stamp into the buffer to include the time.
17139 With optional argument FROM-STRING, read from this string instead from
17140 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17141 the time/date that is used for everything that is not specified by the
17142 user."
17143 (require 'parse-time)
17144 (let* ((org-time-stamp-rounding-minutes
17145 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
17146 (org-dcst org-display-custom-times)
17147 (ct (org-current-time))
17148 (def (or default-time ct))
17149 (defdecode (decode-time def))
17150 (dummy (progn
17151 (when (< (nth 2 defdecode) org-extend-today-until)
17152 (setcar (nthcdr 2 defdecode) -1)
17153 (setcar (nthcdr 1 defdecode) 59)
17154 (setq def (apply 'encode-time defdecode)
17155 defdecode (decode-time def)))))
17156 (calendar-move-hook nil)
17157 (view-diary-entries-initially nil)
17158 (view-calendar-holidays-initially nil)
17159 (timestr (format-time-string
17160 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17161 (prompt (concat (if prompt (concat prompt " ") "")
17162 (format "Date+time [%s]: " timestr)))
17163 ans (org-ans0 "") org-ans1 org-ans2 final)
17165 (cond
17166 (from-string (setq ans from-string))
17167 (org-read-date-popup-calendar
17168 (save-excursion
17169 (save-window-excursion
17170 (calendar)
17171 (calendar-forward-day (- (time-to-days def)
17172 (calendar-absolute-from-gregorian
17173 (calendar-current-date))))
17174 (org-eval-in-calendar nil t)
17175 (let* ((old-map (current-local-map))
17176 (map (copy-keymap calendar-mode-map))
17177 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17178 (org-defkey map (kbd "RET") 'org-calendar-select)
17179 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17180 'org-calendar-select-mouse)
17181 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17182 'org-calendar-select-mouse)
17183 (org-defkey minibuffer-local-map [(meta shift left)]
17184 (lambda () (interactive)
17185 (org-eval-in-calendar '(calendar-backward-month 1))))
17186 (org-defkey minibuffer-local-map [(meta shift right)]
17187 (lambda () (interactive)
17188 (org-eval-in-calendar '(calendar-forward-month 1))))
17189 (org-defkey minibuffer-local-map [(meta shift up)]
17190 (lambda () (interactive)
17191 (org-eval-in-calendar '(calendar-backward-year 1))))
17192 (org-defkey minibuffer-local-map [(meta shift down)]
17193 (lambda () (interactive)
17194 (org-eval-in-calendar '(calendar-forward-year 1))))
17195 (org-defkey minibuffer-local-map [(shift up)]
17196 (lambda () (interactive)
17197 (org-eval-in-calendar '(calendar-backward-week 1))))
17198 (org-defkey minibuffer-local-map [(shift down)]
17199 (lambda () (interactive)
17200 (org-eval-in-calendar '(calendar-forward-week 1))))
17201 (org-defkey minibuffer-local-map [(shift left)]
17202 (lambda () (interactive)
17203 (org-eval-in-calendar '(calendar-backward-day 1))))
17204 (org-defkey minibuffer-local-map [(shift right)]
17205 (lambda () (interactive)
17206 (org-eval-in-calendar '(calendar-forward-day 1))))
17207 (org-defkey minibuffer-local-map ">"
17208 (lambda () (interactive)
17209 (org-eval-in-calendar '(scroll-calendar-left 1))))
17210 (org-defkey minibuffer-local-map "<"
17211 (lambda () (interactive)
17212 (org-eval-in-calendar '(scroll-calendar-right 1))))
17213 (unwind-protect
17214 (progn
17215 (use-local-map map)
17216 (add-hook 'post-command-hook 'org-read-date-display)
17217 (setq org-ans0 (read-string prompt default-input nil nil))
17218 ;; org-ans0: from prompt
17219 ;; org-ans1: from mouse click
17220 ;; org-ans2: from calendar motion
17221 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17222 (remove-hook 'post-command-hook 'org-read-date-display)
17223 (use-local-map old-map)
17224 (when org-read-date-overlay
17225 (org-delete-overlay org-read-date-overlay)
17226 (setq org-read-date-overlay nil)))))))
17228 (t ; Naked prompt only
17229 (unwind-protect
17230 (setq ans (read-string prompt default-input nil timestr))
17231 (when org-read-date-overlay
17232 (org-delete-overlay org-read-date-overlay)
17233 (setq org-read-date-overlay nil)))))
17235 (setq final (org-read-date-analyze ans def defdecode))
17237 (if to-time
17238 (apply 'encode-time final)
17239 (if (and (boundp 'org-time-was-given) org-time-was-given)
17240 (format "%04d-%02d-%02d %02d:%02d"
17241 (nth 5 final) (nth 4 final) (nth 3 final)
17242 (nth 2 final) (nth 1 final))
17243 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17244 (defvar def)
17245 (defvar defdecode)
17246 (defvar with-time)
17247 (defun org-read-date-display ()
17248 "Display the currrent date prompt interpretation in the minibuffer."
17249 (when org-read-date-display-live
17250 (when org-read-date-overlay
17251 (org-delete-overlay org-read-date-overlay))
17252 (let ((p (point)))
17253 (end-of-line 1)
17254 (while (not (equal (buffer-substring
17255 (max (point-min) (- (point) 4)) (point))
17256 " "))
17257 (insert " "))
17258 (goto-char p))
17259 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17260 " " (or org-ans1 org-ans2)))
17261 (org-end-time-was-given nil)
17262 (f (org-read-date-analyze ans def defdecode))
17263 (fmts (if org-dcst
17264 org-time-stamp-custom-formats
17265 org-time-stamp-formats))
17266 (fmt (if (or with-time
17267 (and (boundp 'org-time-was-given) org-time-was-given))
17268 (cdr fmts)
17269 (car fmts)))
17270 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
17271 (when (and org-end-time-was-given
17272 (string-match org-plain-time-of-day-regexp txt))
17273 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17274 org-end-time-was-given
17275 (substring txt (match-end 0)))))
17276 (setq org-read-date-overlay
17277 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17278 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
17280 (defun org-read-date-analyze (ans def defdecode)
17281 "Analyze the combined answer of the date prompt."
17282 ;; FIXME: cleanup and comment
17283 (let (delta deltan deltaw deltadef year month day
17284 hour minute second wday pm h2 m2 tl wday1)
17286 (when (setq delta (org-read-date-get-relative ans (current-time) def))
17287 (setq ans (replace-match "" t t ans)
17288 deltan (car delta)
17289 deltaw (nth 1 delta)
17290 deltadef (nth 2 delta)))
17292 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
17293 (when (string-match
17294 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17295 (setq year (if (match-end 2)
17296 (string-to-number (match-string 2 ans))
17297 (string-to-number (format-time-string "%Y")))
17298 month (string-to-number (match-string 3 ans))
17299 day (string-to-number (match-string 4 ans)))
17300 (if (< year 100) (setq year (+ 2000 year)))
17301 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17302 t nil ans)))
17303 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17304 ;; If there is a time with am/pm, and *no* time without it, we convert
17305 ;; so that matching will be successful.
17306 (loop for i from 1 to 2 do ; twice, for end time as well
17307 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17308 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17309 (setq hour (string-to-number (match-string 1 ans))
17310 minute (if (match-end 3)
17311 (string-to-number (match-string 3 ans))
17313 pm (equal ?p
17314 (string-to-char (downcase (match-string 4 ans)))))
17315 (if (and (= hour 12) (not pm))
17316 (setq hour 0)
17317 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17318 (setq ans (replace-match (format "%02d:%02d" hour minute)
17319 t t ans))))
17321 ;; Check if a time range is given as a duration
17322 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17323 (setq hour (string-to-number (match-string 1 ans))
17324 h2 (+ hour (string-to-number (match-string 3 ans)))
17325 minute (string-to-number (match-string 2 ans))
17326 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
17327 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17328 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
17330 ;; Check if there is a time range
17331 (when (boundp 'org-end-time-was-given)
17332 (setq org-time-was-given nil)
17333 (when (and (string-match org-plain-time-of-day-regexp ans)
17334 (match-end 8))
17335 (setq org-end-time-was-given (match-string 8 ans))
17336 (setq ans (concat (substring ans 0 (match-beginning 7))
17337 (substring ans (match-end 7))))))
17339 (setq tl (parse-time-string ans)
17340 day (or (nth 3 tl) (nth 3 defdecode))
17341 month (or (nth 4 tl)
17342 (if (and org-read-date-prefer-future
17343 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
17344 (1+ (nth 4 defdecode))
17345 (nth 4 defdecode)))
17346 year (or (nth 5 tl)
17347 (if (and org-read-date-prefer-future
17348 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
17349 (1+ (nth 5 defdecode))
17350 (nth 5 defdecode)))
17351 hour (or (nth 2 tl) (nth 2 defdecode))
17352 minute (or (nth 1 tl) (nth 1 defdecode))
17353 second (or (nth 0 tl) 0)
17354 wday (nth 6 tl))
17355 (when deltan
17356 (unless deltadef
17357 (let ((now (decode-time (current-time))))
17358 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17359 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17360 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17361 ((equal deltaw "m") (setq month (+ month deltan)))
17362 ((equal deltaw "y") (setq year (+ year deltan)))))
17363 (when (and wday (not (nth 3 tl)))
17364 ;; Weekday was given, but no day, so pick that day in the week
17365 ;; on or after the derived date.
17366 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17367 (unless (equal wday wday1)
17368 (setq day (+ day (% (- wday wday1 -7) 7)))))
17369 (if (and (boundp 'org-time-was-given)
17370 (nth 2 tl))
17371 (setq org-time-was-given t))
17372 (if (< year 100) (setq year (+ 2000 year)))
17373 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
17374 (list second minute hour day month year)))
17376 (defvar parse-time-weekdays)
17378 (defun org-read-date-get-relative (s today default)
17379 "Check string S for special relative date string.
17380 TODAY and DEFAULT are internal times, for today and for a default.
17381 Return shift list (N what def-flag)
17382 WHAT is \"d\", \"w\", \"m\", or \"y\" for day. week, month, year.
17383 N is the number if WHATs to shift
17384 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17385 the DEFAULT date rather than TODAY."
17386 (when (string-match
17387 (concat
17388 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
17389 "\\([0-9]+\\)?"
17390 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17391 "\\([ \t]\\|$\\)") s)
17392 (let* ((dir (if (match-end 1)
17393 (string-to-char (substring (match-string 1 s) -1))
17394 ?+))
17395 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17396 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17397 (what (if (match-end 3) (match-string 3 s) "d"))
17398 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17399 (date (if rel default today))
17400 (wday (nth 6 (decode-time date)))
17401 delta)
17402 (if wday1
17403 (progn
17404 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17405 (if (= dir ?-) (setq delta (- delta 7)))
17406 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17407 (list delta "d" rel))
17408 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17410 (defun org-eval-in-calendar (form &optional keepdate)
17411 "Eval FORM in the calendar window and return to current window.
17412 Also, store the cursor date in variable org-ans2."
17413 (let ((sw (selected-window)))
17414 (select-window (get-buffer-window "*Calendar*"))
17415 (eval form)
17416 (when (and (not keepdate) (calendar-cursor-to-date))
17417 (let* ((date (calendar-cursor-to-date))
17418 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17419 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17420 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17421 (select-window sw)))
17423 ; ;; Update the prompt to show new default date
17424 ; (save-excursion
17425 ; (goto-char (point-min))
17426 ; (when (and org-ans2
17427 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
17428 ; (get-text-property (match-end 0) 'field))
17429 ; (let ((inhibit-read-only t))
17430 ; (replace-match (concat "[" org-ans2 "]") t t)
17431 ; (add-text-properties (point-min) (1+ (match-end 0))
17432 ; (text-properties-at (1+ (point-min)))))))))
17434 (defun org-calendar-select ()
17435 "Return to `org-read-date' with the date currently selected.
17436 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17437 (interactive)
17438 (when (calendar-cursor-to-date)
17439 (let* ((date (calendar-cursor-to-date))
17440 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17441 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17442 (if (active-minibuffer-window) (exit-minibuffer))))
17444 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17445 "Insert a date stamp for the date given by the internal TIME.
17446 WITH-HM means, use the stamp format that includes the time of the day.
17447 INACTIVE means use square brackets instead of angular ones, so that the
17448 stamp will not contribute to the agenda.
17449 PRE and POST are optional strings to be inserted before and after the
17450 stamp.
17451 The command returns the inserted time stamp."
17452 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17453 stamp)
17454 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17455 (insert-before-markers (or pre ""))
17456 (insert-before-markers (setq stamp (format-time-string fmt time)))
17457 (when (listp extra)
17458 (setq extra (car extra))
17459 (if (and (stringp extra)
17460 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17461 (setq extra (format "-%02d:%02d"
17462 (string-to-number (match-string 1 extra))
17463 (string-to-number (match-string 2 extra))))
17464 (setq extra nil)))
17465 (when extra
17466 (backward-char 1)
17467 (insert-before-markers extra)
17468 (forward-char 1))
17469 (insert-before-markers (or post ""))
17470 stamp))
17472 (defun org-toggle-time-stamp-overlays ()
17473 "Toggle the use of custom time stamp formats."
17474 (interactive)
17475 (setq org-display-custom-times (not org-display-custom-times))
17476 (unless org-display-custom-times
17477 (let ((p (point-min)) (bmp (buffer-modified-p)))
17478 (while (setq p (next-single-property-change p 'display))
17479 (if (and (get-text-property p 'display)
17480 (eq (get-text-property p 'face) 'org-date))
17481 (remove-text-properties
17482 p (setq p (next-single-property-change p 'display))
17483 '(display t))))
17484 (set-buffer-modified-p bmp)))
17485 (if (featurep 'xemacs)
17486 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17487 (org-restart-font-lock)
17488 (setq org-table-may-need-update t)
17489 (if org-display-custom-times
17490 (message "Time stamps are overlayed with custom format")
17491 (message "Time stamp overlays removed")))
17493 (defun org-display-custom-time (beg end)
17494 "Overlay modified time stamp format over timestamp between BED and END."
17495 (let* ((ts (buffer-substring beg end))
17496 t1 w1 with-hm tf time str w2 (off 0))
17497 (save-match-data
17498 (setq t1 (org-parse-time-string ts t))
17499 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
17500 (setq off (- (match-end 0) (match-beginning 0)))))
17501 (setq end (- end off))
17502 (setq w1 (- end beg)
17503 with-hm (and (nth 1 t1) (nth 2 t1))
17504 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17505 time (org-fix-decoded-time t1)
17506 str (org-add-props
17507 (format-time-string
17508 (substring tf 1 -1) (apply 'encode-time time))
17509 nil 'mouse-face 'highlight)
17510 w2 (length str))
17511 (if (not (= w2 w1))
17512 (add-text-properties (1+ beg) (+ 2 beg)
17513 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17514 (if (featurep 'xemacs)
17515 (progn
17516 (put-text-property beg end 'invisible t)
17517 (put-text-property beg end 'end-glyph (make-glyph str)))
17518 (put-text-property beg end 'display str))))
17520 (defun org-translate-time (string)
17521 "Translate all timestamps in STRING to custom format.
17522 But do this only if the variable `org-display-custom-times' is set."
17523 (when org-display-custom-times
17524 (save-match-data
17525 (let* ((start 0)
17526 (re org-ts-regexp-both)
17527 t1 with-hm inactive tf time str beg end)
17528 (while (setq start (string-match re string start))
17529 (setq beg (match-beginning 0)
17530 end (match-end 0)
17531 t1 (save-match-data
17532 (org-parse-time-string (substring string beg end) t))
17533 with-hm (and (nth 1 t1) (nth 2 t1))
17534 inactive (equal (substring string beg (1+ beg)) "[")
17535 tf (funcall (if with-hm 'cdr 'car)
17536 org-time-stamp-custom-formats)
17537 time (org-fix-decoded-time t1)
17538 str (format-time-string
17539 (concat
17540 (if inactive "[" "<") (substring tf 1 -1)
17541 (if inactive "]" ">"))
17542 (apply 'encode-time time))
17543 string (replace-match str t t string)
17544 start (+ start (length str)))))))
17545 string)
17547 (defun org-fix-decoded-time (time)
17548 "Set 0 instead of nil for the first 6 elements of time.
17549 Don't touch the rest."
17550 (let ((n 0))
17551 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17553 (defun org-days-to-time (timestamp-string)
17554 "Difference between TIMESTAMP-STRING and now in days."
17555 (- (time-to-days (org-time-string-to-time timestamp-string))
17556 (time-to-days (current-time))))
17558 (defun org-deadline-close (timestamp-string &optional ndays)
17559 "Is the time in TIMESTAMP-STRING close to the current date?"
17560 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17561 (and (< (org-days-to-time timestamp-string) ndays)
17562 (not (org-entry-is-done-p))))
17564 (defun org-get-wdays (ts)
17565 "Get the deadline lead time appropriate for timestring TS."
17566 (cond
17567 ((<= org-deadline-warning-days 0)
17568 ;; 0 or negative, enforce this value no matter what
17569 (- org-deadline-warning-days))
17570 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
17571 ;; lead time is specified.
17572 (floor (* (string-to-number (match-string 1 ts))
17573 (cdr (assoc (match-string 2 ts)
17574 '(("d" . 1) ("w" . 7)
17575 ("m" . 30.4) ("y" . 365.25)))))))
17576 ;; go for the default.
17577 (t org-deadline-warning-days)))
17579 (defun org-calendar-select-mouse (ev)
17580 "Return to `org-read-date' with the date currently selected.
17581 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17582 (interactive "e")
17583 (mouse-set-point ev)
17584 (when (calendar-cursor-to-date)
17585 (let* ((date (calendar-cursor-to-date))
17586 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17587 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17588 (if (active-minibuffer-window) (exit-minibuffer))))
17590 (defun org-check-deadlines (ndays)
17591 "Check if there are any deadlines due or past due.
17592 A deadline is considered due if it happens within `org-deadline-warning-days'
17593 days from today's date. If the deadline appears in an entry marked DONE,
17594 it is not shown. The prefix arg NDAYS can be used to test that many
17595 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17596 (interactive "P")
17597 (let* ((org-warn-days
17598 (cond
17599 ((equal ndays '(4)) 100000)
17600 (ndays (prefix-numeric-value ndays))
17601 (t (abs org-deadline-warning-days))))
17602 (case-fold-search nil)
17603 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17604 (callback
17605 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17607 (message "%d deadlines past-due or due within %d days"
17608 (org-occur regexp nil callback)
17609 org-warn-days)))
17611 (defun org-check-before-date (date)
17612 "Check if there are deadlines or scheduled entries before DATE."
17613 (interactive (list (org-read-date)))
17614 (let ((case-fold-search nil)
17615 (regexp (concat "\\<\\(" org-deadline-string
17616 "\\|" org-scheduled-string
17617 "\\) *<\\([^>]+\\)>"))
17618 (callback
17619 (lambda () (time-less-p
17620 (org-time-string-to-time (match-string 2))
17621 (org-time-string-to-time date)))))
17622 (message "%d entries before %s"
17623 (org-occur regexp nil callback) date)))
17625 (defun org-evaluate-time-range (&optional to-buffer)
17626 "Evaluate a time range by computing the difference between start and end.
17627 Normally the result is just printed in the echo area, but with prefix arg
17628 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17629 If the time range is actually in a table, the result is inserted into the
17630 next column.
17631 For time difference computation, a year is assumed to be exactly 365
17632 days in order to avoid rounding problems."
17633 (interactive "P")
17635 (org-clock-update-time-maybe)
17636 (save-excursion
17637 (unless (org-at-date-range-p t)
17638 (goto-char (point-at-bol))
17639 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17640 (if (not (org-at-date-range-p t))
17641 (error "Not at a time-stamp range, and none found in current line")))
17642 (let* ((ts1 (match-string 1))
17643 (ts2 (match-string 2))
17644 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17645 (match-end (match-end 0))
17646 (time1 (org-time-string-to-time ts1))
17647 (time2 (org-time-string-to-time ts2))
17648 (t1 (time-to-seconds time1))
17649 (t2 (time-to-seconds time2))
17650 (diff (abs (- t2 t1)))
17651 (negative (< (- t2 t1) 0))
17652 ;; (ys (floor (* 365 24 60 60)))
17653 (ds (* 24 60 60))
17654 (hs (* 60 60))
17655 (fy "%dy %dd %02d:%02d")
17656 (fy1 "%dy %dd")
17657 (fd "%dd %02d:%02d")
17658 (fd1 "%dd")
17659 (fh "%02d:%02d")
17660 y d h m align)
17661 (if havetime
17662 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17664 d (floor (/ diff ds)) diff (mod diff ds)
17665 h (floor (/ diff hs)) diff (mod diff hs)
17666 m (floor (/ diff 60)))
17667 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17669 d (floor (+ (/ diff ds) 0.5))
17670 h 0 m 0))
17671 (if (not to-buffer)
17672 (message "%s" (org-make-tdiff-string y d h m))
17673 (if (org-at-table-p)
17674 (progn
17675 (goto-char match-end)
17676 (setq align t)
17677 (and (looking-at " *|") (goto-char (match-end 0))))
17678 (goto-char match-end))
17679 (if (looking-at
17680 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17681 (replace-match ""))
17682 (if negative (insert " -"))
17683 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17684 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17685 (insert " " (format fh h m))))
17686 (if align (org-table-align))
17687 (message "Time difference inserted")))))
17689 (defun org-make-tdiff-string (y d h m)
17690 (let ((fmt "")
17691 (l nil))
17692 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17693 l (push y l)))
17694 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17695 l (push d l)))
17696 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17697 l (push h l)))
17698 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17699 l (push m l)))
17700 (apply 'format fmt (nreverse l))))
17702 (defun org-time-string-to-time (s)
17703 (apply 'encode-time (org-parse-time-string s)))
17705 (defun org-time-string-to-absolute (s &optional daynr)
17706 "Convert a time stamp to an absolute day number.
17707 If there is a specifyer for a cyclic time stamp, get the closest date to
17708 DAYNR."
17709 (cond
17710 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17711 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17712 daynr
17713 (+ daynr 1000)))
17714 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
17715 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17716 (time-to-days (current-time))) (match-string 0 s)))
17717 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
17719 (defun org-time-from-absolute (d)
17720 "Return the time corresponding to date D.
17721 D may be an absolute day number, or a calendar-type list (month day year)."
17722 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17723 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17725 (defun org-calendar-holiday ()
17726 "List of holidays, for Diary display in Org-mode."
17727 (require 'holidays)
17728 (let ((hl (funcall
17729 (if (fboundp 'calendar-check-holidays)
17730 'calendar-check-holidays 'check-calendar-holidays) date)))
17731 (if hl (mapconcat 'identity hl "; "))))
17733 (defun org-diary-sexp-entry (sexp entry date)
17734 "Process a SEXP diary ENTRY for DATE."
17735 (require 'diary-lib)
17736 (let ((result (if calendar-debug-sexp
17737 (let ((stack-trace-on-error t))
17738 (eval (car (read-from-string sexp))))
17739 (condition-case nil
17740 (eval (car (read-from-string sexp)))
17741 (error
17742 (beep)
17743 (message "Bad sexp at line %d in %s: %s"
17744 (org-current-line)
17745 (buffer-file-name) sexp)
17746 (sleep-for 2))))))
17747 (cond ((stringp result) result)
17748 ((and (consp result)
17749 (stringp (cdr result))) (cdr result))
17750 (result entry)
17751 (t nil))))
17753 (defun org-diary-to-ical-string (frombuf)
17754 "Get iCalendar entries from diary entries in buffer FROMBUF.
17755 This uses the icalendar.el library."
17756 (let* ((tmpdir (if (featurep 'xemacs)
17757 (temp-directory)
17758 temporary-file-directory))
17759 (tmpfile (make-temp-name
17760 (expand-file-name "orgics" tmpdir)))
17761 buf rtn b e)
17762 (save-excursion
17763 (set-buffer frombuf)
17764 (icalendar-export-region (point-min) (point-max) tmpfile)
17765 (setq buf (find-buffer-visiting tmpfile))
17766 (set-buffer buf)
17767 (goto-char (point-min))
17768 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17769 (setq b (match-beginning 0)))
17770 (goto-char (point-max))
17771 (if (re-search-backward "^END:VEVENT" nil t)
17772 (setq e (match-end 0)))
17773 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17774 (kill-buffer buf)
17775 (kill-buffer frombuf)
17776 (delete-file tmpfile)
17777 rtn))
17779 (defun org-closest-date (start current change)
17780 "Find the date closest to CURRENT that is consistent with START and CHANGE."
17781 ;; Make the proper lists from the dates
17782 (catch 'exit
17783 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
17784 dn dw sday cday n1 n2
17785 d m y y1 y2 date1 date2 nmonths nm ny m2)
17787 (setq start (org-date-to-gregorian start)
17788 current (org-date-to-gregorian
17789 (if org-agenda-repeating-timestamp-show-all
17790 current
17791 (time-to-days (current-time))))
17792 sday (calendar-absolute-from-gregorian start)
17793 cday (calendar-absolute-from-gregorian current))
17795 (if (<= cday sday) (throw 'exit sday))
17797 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
17798 (setq dn (string-to-number (match-string 1 change))
17799 dw (cdr (assoc (match-string 2 change) a1)))
17800 (error "Invalid change specifyer: %s" change))
17801 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17802 (cond
17803 ((eq dw 'day)
17804 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17805 n2 (+ n1 dn)))
17806 ((eq dw 'year)
17807 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17808 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17809 (setq date1 (list m d y1)
17810 n1 (calendar-absolute-from-gregorian date1)
17811 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17812 n2 (calendar-absolute-from-gregorian date2)))
17813 ((eq dw 'month)
17814 ;; approx number of month between the tow dates
17815 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17816 ;; How often does dn fit in there?
17817 (setq d (nth 1 start) m (car start) y (nth 2 start)
17818 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17819 m (+ m nm)
17820 ny (floor (/ m 12))
17821 y (+ y ny)
17822 m (- m (* ny 12)))
17823 (while (> m 12) (setq m (- m 12) y (1+ y)))
17824 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17825 (setq m2 (+ m dn) y2 y)
17826 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17827 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17828 (while (< n2 cday)
17829 (setq n1 n2 m m2 y y2)
17830 (setq m2 (+ m dn) y2 y)
17831 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17832 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17834 (if org-agenda-repeating-timestamp-show-all
17835 (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)
17836 (if (= cday n1) n1 n2)))))
17838 (defun org-date-to-gregorian (date)
17839 "Turn any specification of DATE into a gregorian date for the calendar."
17840 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17841 ((and (listp date) (= (length date) 3)) date)
17842 ((stringp date)
17843 (setq date (org-parse-time-string date))
17844 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17845 ((listp date)
17846 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17848 (defun org-parse-time-string (s &optional nodefault)
17849 "Parse the standard Org-mode time string.
17850 This should be a lot faster than the normal `parse-time-string'.
17851 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17852 hour and minute fields will be nil if not given."
17853 (if (string-match org-ts-regexp0 s)
17854 (list 0
17855 (if (or (match-beginning 8) (not nodefault))
17856 (string-to-number (or (match-string 8 s) "0")))
17857 (if (or (match-beginning 7) (not nodefault))
17858 (string-to-number (or (match-string 7 s) "0")))
17859 (string-to-number (match-string 4 s))
17860 (string-to-number (match-string 3 s))
17861 (string-to-number (match-string 2 s))
17862 nil nil nil)
17863 (make-list 9 0)))
17865 (defun org-timestamp-up (&optional arg)
17866 "Increase the date item at the cursor by one.
17867 If the cursor is on the year, change the year. If it is on the month or
17868 the day, change that.
17869 With prefix ARG, change by that many units."
17870 (interactive "p")
17871 (org-timestamp-change (prefix-numeric-value arg)))
17873 (defun org-timestamp-down (&optional arg)
17874 "Decrease the date item at the cursor by one.
17875 If the cursor is on the year, change the year. If it is on the month or
17876 the day, change that.
17877 With prefix ARG, change by that many units."
17878 (interactive "p")
17879 (org-timestamp-change (- (prefix-numeric-value arg))))
17881 (defun org-timestamp-up-day (&optional arg)
17882 "Increase the date in the time stamp by one day.
17883 With prefix ARG, change that many days."
17884 (interactive "p")
17885 (if (and (not (org-at-timestamp-p t))
17886 (org-on-heading-p))
17887 (org-todo 'up)
17888 (org-timestamp-change (prefix-numeric-value arg) 'day)))
17890 (defun org-timestamp-down-day (&optional arg)
17891 "Decrease the date in the time stamp by one day.
17892 With prefix ARG, change that many days."
17893 (interactive "p")
17894 (if (and (not (org-at-timestamp-p t))
17895 (org-on-heading-p))
17896 (org-todo 'down)
17897 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
17899 (defsubst org-pos-in-match-range (pos n)
17900 (and (match-beginning n)
17901 (<= (match-beginning n) pos)
17902 (>= (match-end n) pos)))
17904 (defun org-at-timestamp-p (&optional inactive-ok)
17905 "Determine if the cursor is in or at a timestamp."
17906 (interactive)
17907 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17908 (pos (point))
17909 (ans (or (looking-at tsr)
17910 (save-excursion
17911 (skip-chars-backward "^[<\n\r\t")
17912 (if (> (point) (point-min)) (backward-char 1))
17913 (and (looking-at tsr)
17914 (> (- (match-end 0) pos) -1))))))
17915 (and ans
17916 (boundp 'org-ts-what)
17917 (setq org-ts-what
17918 (cond
17919 ((= pos (match-beginning 0)) 'bracket)
17920 ((= pos (1- (match-end 0))) 'bracket)
17921 ((org-pos-in-match-range pos 2) 'year)
17922 ((org-pos-in-match-range pos 3) 'month)
17923 ((org-pos-in-match-range pos 7) 'hour)
17924 ((org-pos-in-match-range pos 8) 'minute)
17925 ((or (org-pos-in-match-range pos 4)
17926 (org-pos-in-match-range pos 5)) 'day)
17927 ((and (> pos (or (match-end 8) (match-end 5)))
17928 (< pos (match-end 0)))
17929 (- pos (or (match-end 8) (match-end 5))))
17930 (t 'day))))
17931 ans))
17933 (defun org-toggle-timestamp-type ()
17935 (interactive)
17936 (when (org-at-timestamp-p t)
17937 (save-excursion
17938 (goto-char (match-beginning 0))
17939 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
17940 (goto-char (1- (match-end 0)))
17941 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
17942 (message "Timestamp is now %sactive"
17943 (if (equal (char-before) ?>) "in" ""))))
17945 (defun org-timestamp-change (n &optional what)
17946 "Change the date in the time stamp at point.
17947 The date will be changed by N times WHAT. WHAT can be `day', `month',
17948 `year', `minute', `second'. If WHAT is not given, the cursor position
17949 in the timestamp determines what will be changed."
17950 (let ((pos (point))
17951 with-hm inactive
17952 org-ts-what
17953 extra
17954 ts time time0)
17955 (if (not (org-at-timestamp-p t))
17956 (error "Not at a timestamp"))
17957 (if (and (not what) (eq org-ts-what 'bracket))
17958 (org-toggle-timestamp-type)
17959 (if (and (not what) (not (eq org-ts-what 'day))
17960 org-display-custom-times
17961 (get-text-property (point) 'display)
17962 (not (get-text-property (1- (point)) 'display)))
17963 (setq org-ts-what 'day))
17964 (setq org-ts-what (or what org-ts-what)
17965 inactive (= (char-after (match-beginning 0)) ?\[)
17966 ts (match-string 0))
17967 (replace-match "")
17968 (if (string-match
17969 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
17971 (setq extra (match-string 1 ts)))
17972 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17973 (setq with-hm t))
17974 (setq time0 (org-parse-time-string ts))
17975 (setq time
17976 (encode-time (or (car time0) 0)
17977 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17978 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17979 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17980 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17981 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17982 (nthcdr 6 time0)))
17983 (when (integerp org-ts-what)
17984 (setq extra (org-modify-ts-extra extra org-ts-what n)))
17985 (if (eq what 'calendar)
17986 (let ((cal-date (org-get-date-from-calendar)))
17987 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17988 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17989 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17990 (setcar time0 (or (car time0) 0))
17991 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17992 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17993 (setq time (apply 'encode-time time0))))
17994 (setq org-last-changed-timestamp
17995 (org-insert-time-stamp time with-hm inactive nil nil extra))
17996 (org-clock-update-time-maybe)
17997 (goto-char pos)
17998 ;; Try to recenter the calendar window, if any
17999 (if (and org-calendar-follow-timestamp-change
18000 (get-buffer-window "*Calendar*" t)
18001 (memq org-ts-what '(day month year)))
18002 (org-recenter-calendar (time-to-days time))))))
18004 ;; FIXME: does not yet work for lead times
18005 (defun org-modify-ts-extra (s pos n)
18006 "Change the different parts of the lead-time and repeat fields in timestamp."
18007 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18008 ng h m new)
18009 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18010 (cond
18011 ((or (org-pos-in-match-range pos 2)
18012 (org-pos-in-match-range pos 3))
18013 (setq m (string-to-number (match-string 3 s))
18014 h (string-to-number (match-string 2 s)))
18015 (if (org-pos-in-match-range pos 2)
18016 (setq h (+ h n))
18017 (setq m (+ m n)))
18018 (if (< m 0) (setq m (+ m 60) h (1- h)))
18019 (if (> m 59) (setq m (- m 60) h (1+ h)))
18020 (setq h (min 24 (max 0 h)))
18021 (setq ng 1 new (format "-%02d:%02d" h m)))
18022 ((org-pos-in-match-range pos 6)
18023 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18024 ((org-pos-in-match-range pos 5)
18025 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
18027 (when ng
18028 (setq s (concat
18029 (substring s 0 (match-beginning ng))
18031 (substring s (match-end ng))))))
18034 (defun org-recenter-calendar (date)
18035 "If the calendar is visible, recenter it to DATE."
18036 (let* ((win (selected-window))
18037 (cwin (get-buffer-window "*Calendar*" t))
18038 (calendar-move-hook nil))
18039 (when cwin
18040 (select-window cwin)
18041 (calendar-goto-date (if (listp date) date
18042 (calendar-gregorian-from-absolute date)))
18043 (select-window win))))
18045 (defun org-goto-calendar (&optional arg)
18046 "Go to the Emacs calendar at the current date.
18047 If there is a time stamp in the current line, go to that date.
18048 A prefix ARG can be used to force the current date."
18049 (interactive "P")
18050 (let ((tsr org-ts-regexp) diff
18051 (calendar-move-hook nil)
18052 (view-calendar-holidays-initially nil)
18053 (view-diary-entries-initially nil))
18054 (if (or (org-at-timestamp-p)
18055 (save-excursion
18056 (beginning-of-line 1)
18057 (looking-at (concat ".*" tsr))))
18058 (let ((d1 (time-to-days (current-time)))
18059 (d2 (time-to-days
18060 (org-time-string-to-time (match-string 1)))))
18061 (setq diff (- d2 d1))))
18062 (calendar)
18063 (calendar-goto-today)
18064 (if (and diff (not arg)) (calendar-forward-day diff))))
18066 (defun org-get-date-from-calendar ()
18067 "Return a list (month day year) of date at point in calendar."
18068 (with-current-buffer "*Calendar*"
18069 (save-match-data
18070 (calendar-cursor-to-date))))
18072 (defun org-date-from-calendar ()
18073 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18074 If there is already a time stamp at the cursor position, update it."
18075 (interactive)
18076 (if (org-at-timestamp-p t)
18077 (org-timestamp-change 0 'calendar)
18078 (let ((cal-date (org-get-date-from-calendar)))
18079 (org-insert-time-stamp
18080 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18082 ;; Make appt aware of appointments from the agenda
18083 ;;;###autoload
18084 (defun org-agenda-to-appt (&optional filter)
18085 "Activate appointments found in `org-agenda-files'.
18086 When prefixed, prompt for a regular expression and use it as a
18087 filter: only add entries if they match this regular expression.
18089 FILTER can be a string. In this case, use this string as a
18090 regular expression to filter results.
18092 FILTER can also be an alist, with the car of each cell being
18093 either 'headline or 'category. For example:
18095 '((headline \"IMPORTANT\")
18096 (category \"Work\"))
18098 will only add headlines containing IMPORTANT or headlines
18099 belonging to the category \"Work\"."
18100 (interactive "P")
18101 (require 'calendar)
18102 (if (equal filter '(4))
18103 (setq filter (read-from-minibuffer "Regexp filter: ")))
18104 (let* ((cnt 0) ; count added events
18105 (org-agenda-new-buffers nil)
18106 (today (org-date-to-gregorian
18107 (time-to-days (current-time))))
18108 (files (org-agenda-files)) entries file)
18109 ;; Get all entries which may contain an appt
18110 (while (setq file (pop files))
18111 (setq entries
18112 (append entries
18113 (org-agenda-get-day-entries
18114 file today
18115 :timestamp :scheduled :deadline))))
18116 (setq entries (delq nil entries))
18117 ;; Map thru entries and find if they pass thru the filter
18118 (mapc
18119 (lambda(x)
18120 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18121 (cat (get-text-property 1 'org-category x))
18122 (tod (get-text-property 1 'time-of-day x))
18123 (ok (or (null filter)
18124 (and (stringp filter) (string-match filter evt))
18125 (and (listp filter)
18126 (or (string-match
18127 (cadr (assoc 'category filter)) cat)
18128 (string-match
18129 (cadr (assoc 'headline filter)) evt))))))
18130 ;; FIXME: Shall we remove text-properties for the appt text?
18131 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18132 (when (and ok tod)
18133 (setq tod (number-to-string tod)
18134 tod (when (string-match
18135 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18136 (concat (match-string 1 tod) ":"
18137 (match-string 2 tod))))
18138 (appt-add tod evt)
18139 (setq cnt (1+ cnt))))) entries)
18140 (org-release-buffers org-agenda-new-buffers)
18141 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" ""))))
18143 ;;; The clock for measuring work time.
18145 (defvar org-mode-line-string "")
18146 (put 'org-mode-line-string 'risky-local-variable t)
18148 (defvar org-mode-line-timer nil)
18149 (defvar org-clock-heading "")
18150 (defvar org-clock-start-time "")
18152 (defun org-update-mode-line ()
18153 (let* ((delta (- (time-to-seconds (current-time))
18154 (time-to-seconds org-clock-start-time)))
18155 (h (floor delta 3600))
18156 (m (floor (- delta (* 3600 h)) 60)))
18157 (setq org-mode-line-string
18158 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18159 'help-echo "Org-mode clock is running"))
18160 (force-mode-line-update)))
18162 (defvar org-clock-marker (make-marker)
18163 "Marker recording the last clock-in.")
18164 (defvar org-clock-mode-line-entry nil
18165 "Information for the modeline about the running clock.")
18167 (defun org-clock-in ()
18168 "Start the clock on the current item.
18169 If necessary, clock-out of the currently active clock."
18170 (interactive)
18171 (org-clock-out t)
18172 (let (ts)
18173 (save-excursion
18174 (org-back-to-heading t)
18175 (if (and org-clock-heading-function
18176 (functionp org-clock-heading-function))
18177 (setq org-clock-heading (funcall org-clock-heading-function))
18178 (if (looking-at org-complex-heading-regexp)
18179 (setq org-clock-heading (match-string 4))
18180 (setq org-clock-heading "???")))
18181 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18182 (org-clock-find-position)
18184 (insert "\n") (backward-char 1)
18185 (indent-relative)
18186 (insert org-clock-string " ")
18187 (setq org-clock-start-time (current-time))
18188 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18189 (move-marker org-clock-marker (point) (buffer-base-buffer))
18190 (or global-mode-string (setq global-mode-string '("")))
18191 (or (memq 'org-mode-line-string global-mode-string)
18192 (setq global-mode-string
18193 (append global-mode-string '(org-mode-line-string))))
18194 (org-update-mode-line)
18195 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18196 (message "Clock started at %s" ts))))
18198 (defun org-clock-find-position ()
18199 "Find the location where the next clock line should be inserted."
18200 (org-back-to-heading t)
18201 (catch 'exit
18202 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
18203 (re (concat "^[ \t]*" org-clock-string))
18204 (cnt 0)
18205 first last)
18206 (goto-char beg)
18207 (when (eobp) (newline) (setq end (max (point) end)))
18208 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
18209 ;; we seem to have a CLOCK drawer, so go there.
18210 (beginning-of-line 2)
18211 (throw 'exit t))
18212 ;; Lets count the CLOCK lines
18213 (goto-char beg)
18214 (while (re-search-forward re end t)
18215 (setq first (or first (match-beginning 0))
18216 last (match-beginning 0)
18217 cnt (1+ cnt)))
18218 (when (and (integerp org-clock-into-drawer)
18219 (>= (1+ cnt) org-clock-into-drawer))
18220 ;; Wrap current entries into a new drawer
18221 (goto-char last)
18222 (beginning-of-line 2)
18223 (if (org-at-item-p) (org-end-of-item))
18224 (insert ":END:\n")
18225 (beginning-of-line 0)
18226 (org-indent-line-function)
18227 (goto-char first)
18228 (insert ":CLOCK:\n")
18229 (beginning-of-line 0)
18230 (org-indent-line-function)
18231 (org-flag-drawer t)
18232 (beginning-of-line 2)
18233 (throw 'exit nil))
18235 (goto-char beg)
18236 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18237 (not (equal (match-string 1) org-clock-string)))
18238 ;; Planning info, skip to after it
18239 (beginning-of-line 2)
18240 (or (bolp) (newline)))
18241 (when (eq t org-clock-into-drawer)
18242 (insert ":CLOCK:\n:END:\n")
18243 (beginning-of-line -1)
18244 (org-indent-line-function)
18245 (org-flag-drawer t)
18246 (beginning-of-line 2)
18247 (org-indent-line-function)))))
18249 (defun org-clock-out (&optional fail-quietly)
18250 "Stop the currently running clock.
18251 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
18252 (interactive)
18253 (catch 'exit
18254 (if (not (marker-buffer org-clock-marker))
18255 (if fail-quietly (throw 'exit t) (error "No active clock")))
18256 (let (ts te s h m)
18257 (save-excursion
18258 (set-buffer (marker-buffer org-clock-marker))
18259 (goto-char org-clock-marker)
18260 (beginning-of-line 1)
18261 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18262 (equal (match-string 1) org-clock-string))
18263 (setq ts (match-string 2))
18264 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
18265 (goto-char (match-end 0))
18266 (delete-region (point) (point-at-eol))
18267 (insert "--")
18268 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18269 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
18270 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
18271 h (floor (/ s 3600))
18272 s (- s (* 3600 h))
18273 m (floor (/ s 60))
18274 s (- s (* 60 s)))
18275 (insert " => " (format "%2d:%02d" h m))
18276 (move-marker org-clock-marker nil)
18277 (let* ((logging (save-match-data (org-entry-get nil "LOGGING" t)))
18278 (org-log-done (org-parse-local-options logging 'org-log-done))
18279 (org-log-repeat (org-parse-local-options logging 'org-log-repeat)))
18280 (org-add-log-maybe 'clock-out))
18281 (when org-mode-line-timer
18282 (cancel-timer org-mode-line-timer)
18283 (setq org-mode-line-timer nil))
18284 (setq global-mode-string
18285 (delq 'org-mode-line-string global-mode-string))
18286 (force-mode-line-update)
18287 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
18289 (defun org-clock-cancel ()
18290 "Cancel the running clock be removing the start timestamp."
18291 (interactive)
18292 (if (not (marker-buffer org-clock-marker))
18293 (error "No active clock"))
18294 (save-excursion
18295 (set-buffer (marker-buffer org-clock-marker))
18296 (goto-char org-clock-marker)
18297 (delete-region (1- (point-at-bol)) (point-at-eol)))
18298 (setq global-mode-string
18299 (delq 'org-mode-line-string global-mode-string))
18300 (force-mode-line-update)
18301 (message "Clock canceled"))
18303 (defun org-clock-goto (&optional delete-windows)
18304 "Go to the currently clocked-in entry."
18305 (interactive "P")
18306 (if (not (marker-buffer org-clock-marker))
18307 (error "No active clock"))
18308 (switch-to-buffer-other-window
18309 (marker-buffer org-clock-marker))
18310 (if delete-windows (delete-other-windows))
18311 (goto-char org-clock-marker)
18312 (org-show-entry)
18313 (org-back-to-heading)
18314 (recenter))
18316 (defvar org-clock-file-total-minutes nil
18317 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
18318 (make-variable-buffer-local 'org-clock-file-total-minutes)
18320 (defun org-clock-sum (&optional tstart tend)
18321 "Sum the times for each subtree.
18322 Puts the resulting times in minutes as a text property on each headline."
18323 (interactive)
18324 (let* ((bmp (buffer-modified-p))
18325 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
18326 org-clock-string
18327 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
18328 (lmax 30)
18329 (ltimes (make-vector lmax 0))
18330 (t1 0)
18331 (level 0)
18332 ts te dt
18333 time)
18334 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
18335 (save-excursion
18336 (goto-char (point-max))
18337 (while (re-search-backward re nil t)
18338 (cond
18339 ((match-end 2)
18340 ;; Two time stamps
18341 (setq ts (match-string 2)
18342 te (match-string 3)
18343 ts (time-to-seconds
18344 (apply 'encode-time (org-parse-time-string ts)))
18345 te (time-to-seconds
18346 (apply 'encode-time (org-parse-time-string te)))
18347 ts (if tstart (max ts tstart) ts)
18348 te (if tend (min te tend) te)
18349 dt (- te ts)
18350 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
18351 ((match-end 4)
18352 ;; A naket time
18353 (setq t1 (+ t1 (string-to-number (match-string 5))
18354 (* 60 (string-to-number (match-string 4))))))
18355 (t ;; A headline
18356 (setq level (- (match-end 1) (match-beginning 1)))
18357 (when (or (> t1 0) (> (aref ltimes level) 0))
18358 (loop for l from 0 to level do
18359 (aset ltimes l (+ (aref ltimes l) t1)))
18360 (setq t1 0 time (aref ltimes level))
18361 (loop for l from level to (1- lmax) do
18362 (aset ltimes l 0))
18363 (goto-char (match-beginning 0))
18364 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
18365 (setq org-clock-file-total-minutes (aref ltimes 0)))
18366 (set-buffer-modified-p bmp)))
18368 (defun org-clock-display (&optional total-only)
18369 "Show subtree times in the entire buffer.
18370 If TOTAL-ONLY is non-nil, only show the total time for the entire file
18371 in the echo area."
18372 (interactive)
18373 (org-remove-clock-overlays)
18374 (let (time h m p)
18375 (org-clock-sum)
18376 (unless total-only
18377 (save-excursion
18378 (goto-char (point-min))
18379 (while (or (and (equal (setq p (point)) (point-min))
18380 (get-text-property p :org-clock-minutes))
18381 (setq p (next-single-property-change
18382 (point) :org-clock-minutes)))
18383 (goto-char p)
18384 (when (setq time (get-text-property p :org-clock-minutes))
18385 (org-put-clock-overlay time (funcall outline-level))))
18386 (setq h (/ org-clock-file-total-minutes 60)
18387 m (- org-clock-file-total-minutes (* 60 h)))
18388 ;; Arrange to remove the overlays upon next change.
18389 (when org-remove-highlights-with-change
18390 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
18391 nil 'local))))
18392 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
18394 (defvar org-clock-overlays nil)
18395 (make-variable-buffer-local 'org-clock-overlays)
18397 (defun org-put-clock-overlay (time &optional level)
18398 "Put an overlays on the current line, displaying TIME.
18399 If LEVEL is given, prefix time with a corresponding number of stars.
18400 This creates a new overlay and stores it in `org-clock-overlays', so that it
18401 will be easy to remove."
18402 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
18403 (l (if level (org-get-legal-level level 0) 0))
18404 (off 0)
18405 ov tx)
18406 (move-to-column c)
18407 (unless (eolp) (skip-chars-backward "^ \t"))
18408 (skip-chars-backward " \t")
18409 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
18410 tx (concat (buffer-substring (1- (point)) (point))
18411 (make-string (+ off (max 0 (- c (current-column)))) ?.)
18412 (org-add-props (format "%s %2d:%02d%s"
18413 (make-string l ?*) h m
18414 (make-string (- 10 l) ?\ ))
18415 '(face secondary-selection))
18416 ""))
18417 (if (not (featurep 'xemacs))
18418 (org-overlay-put ov 'display tx)
18419 (org-overlay-put ov 'invisible t)
18420 (org-overlay-put ov 'end-glyph (make-glyph tx)))
18421 (push ov org-clock-overlays)))
18423 (defun org-remove-clock-overlays (&optional beg end noremove)
18424 "Remove the occur highlights from the buffer.
18425 BEG and END are ignored. If NOREMOVE is nil, remove this function
18426 from the `before-change-functions' in the current buffer."
18427 (interactive)
18428 (unless org-inhibit-highlight-removal
18429 (mapc 'org-delete-overlay org-clock-overlays)
18430 (setq org-clock-overlays nil)
18431 (unless noremove
18432 (remove-hook 'before-change-functions
18433 'org-remove-clock-overlays 'local))))
18435 (defun org-clock-out-if-current ()
18436 "Clock out if the current entry contains the running clock.
18437 This is used to stop the clock after a TODO entry is marked DONE,
18438 and is only done if the variable `org-clock-out-when-done' is not nil."
18439 (when (and org-clock-out-when-done
18440 (member state org-done-keywords)
18441 (equal (marker-buffer org-clock-marker) (current-buffer))
18442 (< (point) org-clock-marker)
18443 (> (save-excursion (outline-next-heading) (point))
18444 org-clock-marker))
18445 ;; Clock out, but don't accept a logging message for this.
18446 (let ((org-log-done (if (and (listp org-log-done)
18447 (member 'clock-out org-log-done))
18448 '(done)
18449 org-log-done)))
18450 (org-clock-out))))
18452 (add-hook 'org-after-todo-state-change-hook
18453 'org-clock-out-if-current)
18455 (defun org-check-running-clock ()
18456 "Check if the current buffer contains the running clock.
18457 If yes, offer to stop it and to save the buffer with the changes."
18458 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
18459 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
18460 (buffer-name))))
18461 (org-clock-out)
18462 (when (y-or-n-p "Save changed buffer?")
18463 (save-buffer))))
18465 (defun org-clock-report (&optional arg)
18466 "Create a table containing a report about clocked time.
18467 If the cursor is inside an existing clocktable block, then the table
18468 will be updated. If not, a new clocktable will be inserted.
18469 When called with a prefix argument, move to the first clock table in the
18470 buffer and update it."
18471 (interactive "P")
18472 (org-remove-clock-overlays)
18473 (when arg (org-find-dblock "clocktable"))
18474 (if (org-in-clocktable-p)
18475 (goto-char (org-in-clocktable-p))
18476 (org-create-dblock (list :name "clocktable"
18477 :maxlevel 2 :scope 'file)))
18478 (org-update-dblock))
18480 (defun org-in-clocktable-p ()
18481 "Check if the cursor is in a clocktable."
18482 (let ((pos (point)) start)
18483 (save-excursion
18484 (end-of-line 1)
18485 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
18486 (setq start (match-beginning 0))
18487 (re-search-forward "^#\\+END:.*" nil t)
18488 (>= (match-end 0) pos)
18489 start))))
18491 (defun org-clock-update-time-maybe ()
18492 "If this is a CLOCK line, update it and return t.
18493 Otherwise, return nil."
18494 (interactive)
18495 (save-excursion
18496 (beginning-of-line 1)
18497 (skip-chars-forward " \t")
18498 (when (looking-at org-clock-string)
18499 (let ((re (concat "[ \t]*" org-clock-string
18500 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
18501 "\\([ \t]*=>.*\\)?"))
18502 ts te h m s)
18503 (if (not (looking-at re))
18505 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
18506 (end-of-line 1)
18507 (setq ts (match-string 1)
18508 te (match-string 2))
18509 (setq s (- (time-to-seconds
18510 (apply 'encode-time (org-parse-time-string te)))
18511 (time-to-seconds
18512 (apply 'encode-time (org-parse-time-string ts))))
18513 h (floor (/ s 3600))
18514 s (- s (* 3600 h))
18515 m (floor (/ s 60))
18516 s (- s (* 60 s)))
18517 (insert " => " (format "%2d:%02d" h m))
18518 t)))))
18520 (defun org-clock-special-range (key &optional time as-strings)
18521 "Return two times bordering a special time range.
18522 Key is a symbol specifying the range and can be one of `today', `yesterday',
18523 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
18524 A week starts Monday 0:00 and ends Sunday 24:00.
18525 The range is determined relative to TIME. TIME defaults to the current time.
18526 The return value is a cons cell with two internal times like the ones
18527 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
18528 the returned times will be formatted strings."
18529 (let* ((tm (decode-time (or time (current-time))))
18530 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
18531 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
18532 (dow (nth 6 tm))
18533 s1 m1 h1 d1 month1 y1 diff ts te fm)
18534 (cond
18535 ((eq key 'today)
18536 (setq h 0 m 0 h1 24 m1 0))
18537 ((eq key 'yesterday)
18538 (setq d (1- d) h 0 m 0 h1 24 m1 0))
18539 ((eq key 'thisweek)
18540 (setq diff (if (= dow 0) 6 (1- dow))
18541 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18542 ((eq key 'lastweek)
18543 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
18544 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18545 ((eq key 'thismonth)
18546 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
18547 ((eq key 'lastmonth)
18548 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
18549 ((eq key 'thisyear)
18550 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
18551 ((eq key 'lastyear)
18552 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
18553 (t (error "No such time block %s" key)))
18554 (setq ts (encode-time s m h d month y)
18555 te (encode-time (or s1 s) (or m1 m) (or h1 h)
18556 (or d1 d) (or month1 month) (or y1 y)))
18557 (setq fm (cdr org-time-stamp-formats))
18558 (if as-strings
18559 (cons (format-time-string fm ts) (format-time-string fm te))
18560 (cons ts te))))
18562 (defun org-dblock-write:clocktable (params)
18563 "Write the standard clocktable."
18564 (let ((hlchars '((1 . "*") (2 . "/")))
18565 (emph nil)
18566 (ins (make-marker))
18567 (total-time nil)
18568 ipos time h m p level hlc hdl maxlevel
18569 ts te cc block beg end pos scope tbl tostring multifile)
18570 (setq scope (plist-get params :scope)
18571 tostring (plist-get params :tostring)
18572 multifile (plist-get params :multifile)
18573 maxlevel (or (plist-get params :maxlevel) 3)
18574 emph (plist-get params :emphasize)
18575 ts (plist-get params :tstart)
18576 te (plist-get params :tend)
18577 block (plist-get params :block))
18578 (when block
18579 (setq cc (org-clock-special-range block nil t)
18580 ts (car cc) te (cdr cc)))
18581 (if ts (setq ts (time-to-seconds
18582 (apply 'encode-time (org-parse-time-string ts)))))
18583 (if te (setq te (time-to-seconds
18584 (apply 'encode-time (org-parse-time-string te)))))
18585 (move-marker ins (point))
18586 (setq ipos (point))
18588 ;; Get the right scope
18589 (setq pos (point))
18590 (save-restriction
18591 (cond
18592 ((not scope))
18593 ((eq scope 'file) (widen))
18594 ((eq scope 'subtree) (org-narrow-to-subtree))
18595 ((eq scope 'tree)
18596 (while (org-up-heading-safe))
18597 (org-narrow-to-subtree))
18598 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
18599 (symbol-name scope)))
18600 (setq level (string-to-number (match-string 1 (symbol-name scope))))
18601 (catch 'exit
18602 (while (org-up-heading-safe)
18603 (looking-at outline-regexp)
18604 (if (<= (org-reduced-level (funcall outline-level)) level)
18605 (throw 'exit nil))))
18606 (org-narrow-to-subtree))
18607 ((or (listp scope) (eq scope 'agenda))
18608 (let* ((files (if (listp scope) scope (org-agenda-files)))
18609 (scope 'agenda)
18610 (p1 (copy-sequence params))
18611 file)
18612 (plist-put p1 :tostring t)
18613 (plist-put p1 :multifile t)
18614 (plist-put p1 :scope 'file)
18615 (org-prepare-agenda-buffers files)
18616 (while (setq file (pop files))
18617 (with-current-buffer (find-buffer-visiting file)
18618 (push (org-clocktable-add-file
18619 file (org-dblock-write:clocktable p1)) tbl)
18620 (setq total-time (+ (or total-time 0)
18621 org-clock-file-total-minutes)))))))
18622 (goto-char pos)
18624 (unless (eq scope 'agenda)
18625 (org-clock-sum ts te)
18626 (goto-char (point-min))
18627 (while (setq p (next-single-property-change (point) :org-clock-minutes))
18628 (goto-char p)
18629 (when (setq time (get-text-property p :org-clock-minutes))
18630 (save-excursion
18631 (beginning-of-line 1)
18632 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
18633 (setq level (org-reduced-level
18634 (- (match-end 1) (match-beginning 1))))
18635 (<= level maxlevel))
18636 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
18637 hdl (match-string 2)
18638 h (/ time 60)
18639 m (- time (* 60 h)))
18640 (if (and (not multifile) (= level 1)) (push "|-" tbl))
18641 (push (concat
18642 "| " (int-to-string level) "|" hlc hdl hlc " |"
18643 (make-string (1- level) ?|)
18644 hlc (format "%d:%02d" h m) hlc
18645 " |") tbl))))))
18646 (setq tbl (nreverse tbl))
18647 (if tostring
18648 (if tbl (mapconcat 'identity tbl "\n") nil)
18649 (goto-char ins)
18650 (insert-before-markers
18651 "Clock summary at ["
18652 (substring
18653 (format-time-string (cdr org-time-stamp-formats))
18654 1 -1)
18655 "]."
18656 (if block
18657 (format " Considered range is /%s/." block)
18659 "\n\n"
18660 (if (eq scope 'agenda) "|File" "")
18661 "|L|Headline|Time|\n")
18662 (setq total-time (or total-time org-clock-file-total-minutes)
18663 h (/ total-time 60)
18664 m (- total-time (* 60 h)))
18665 (insert-before-markers
18666 "|-\n|"
18667 (if (eq scope 'agenda) "|" "")
18669 "*Total time*| "
18670 (format "*%d:%02d*" h m)
18671 "|\n|-\n")
18672 (setq tbl (delq nil tbl))
18673 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
18674 (equal (substring (car tbl) 0 2) "|-"))
18675 (pop tbl))
18676 (insert-before-markers (mapconcat
18677 'identity (delq nil tbl)
18678 (if (eq scope 'agenda) "\n|-\n" "\n")))
18679 (backward-delete-char 1)
18680 (goto-char ipos)
18681 (skip-chars-forward "^|")
18682 (org-table-align)))))
18684 (defun org-clocktable-add-file (file table)
18685 (if table
18686 (let ((lines (org-split-string table "\n"))
18687 (ff (file-name-nondirectory file)))
18688 (mapconcat 'identity
18689 (mapcar (lambda (x)
18690 (if (string-match org-table-dataline-regexp x)
18691 (concat "|" ff x)
18693 lines)
18694 "\n"))))
18696 ;; FIXME: I don't think anybody uses this, ask David
18697 (defun org-collect-clock-time-entries ()
18698 "Return an internal list with clocking information.
18699 This list has one entry for each CLOCK interval.
18700 FIXME: describe the elements."
18701 (interactive)
18702 (let ((re (concat "^[ \t]*" org-clock-string
18703 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
18704 rtn beg end next cont level title total closedp leafp
18705 clockpos titlepos h m donep)
18706 (save-excursion
18707 (org-clock-sum)
18708 (goto-char (point-min))
18709 (while (re-search-forward re nil t)
18710 (setq clockpos (match-beginning 0)
18711 beg (match-string 1) end (match-string 2)
18712 cont (match-end 0))
18713 (setq beg (apply 'encode-time (org-parse-time-string beg))
18714 end (apply 'encode-time (org-parse-time-string end)))
18715 (org-back-to-heading t)
18716 (setq donep (org-entry-is-done-p))
18717 (setq titlepos (point)
18718 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
18719 h (/ total 60) m (- total (* 60 h))
18720 total (cons h m))
18721 (looking-at "\\(\\*+\\) +\\(.*\\)")
18722 (setq level (- (match-end 1) (match-beginning 1))
18723 title (org-match-string-no-properties 2))
18724 (save-excursion (outline-next-heading) (setq next (point)))
18725 (setq closedp (re-search-forward org-closed-time-regexp next t))
18726 (goto-char next)
18727 (setq leafp (and (looking-at "^\\*+ ")
18728 (<= (- (match-end 0) (point)) level)))
18729 (push (list beg end clockpos closedp donep
18730 total title titlepos level leafp)
18731 rtn)
18732 (goto-char cont)))
18733 (nreverse rtn)))
18735 ;;;; Agenda, and Diary Integration
18737 ;;; Define the Org-agenda-mode
18739 (defvar org-agenda-mode-map (make-sparse-keymap)
18740 "Keymap for `org-agenda-mode'.")
18742 (defvar org-agenda-menu) ; defined later in this file.
18743 (defvar org-agenda-follow-mode nil)
18744 (defvar org-agenda-show-log nil)
18745 (defvar org-agenda-redo-command nil)
18746 (defvar org-agenda-mode-hook nil)
18747 (defvar org-agenda-type nil)
18748 (defvar org-agenda-force-single-file nil)
18750 (defun org-agenda-mode ()
18751 "Mode for time-sorted view on action items in Org-mode files.
18753 The following commands are available:
18755 \\{org-agenda-mode-map}"
18756 (interactive)
18757 (kill-all-local-variables)
18758 (setq org-agenda-undo-list nil
18759 org-agenda-pending-undo-list nil)
18760 (setq major-mode 'org-agenda-mode)
18761 ;; Keep global-font-lock-mode from turning on font-lock-mode
18762 (org-set-local 'font-lock-global-modes (list 'not major-mode))
18763 (setq mode-name "Org-Agenda")
18764 (use-local-map org-agenda-mode-map)
18765 (easy-menu-add org-agenda-menu)
18766 (if org-startup-truncated (setq truncate-lines t))
18767 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
18768 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
18769 ;; Make sure properties are removed when copying text
18770 (when (boundp 'buffer-substring-filters)
18771 (org-set-local 'buffer-substring-filters
18772 (cons (lambda (x)
18773 (set-text-properties 0 (length x) nil x) x)
18774 buffer-substring-filters)))
18775 (unless org-agenda-keep-modes
18776 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
18777 org-agenda-show-log nil))
18778 (easy-menu-change
18779 '("Agenda") "Agenda Files"
18780 (append
18781 (list
18782 (vector
18783 (if (get 'org-agenda-files 'org-restrict)
18784 "Restricted to single file"
18785 "Edit File List")
18786 '(org-edit-agenda-file-list)
18787 (not (get 'org-agenda-files 'org-restrict)))
18788 "--")
18789 (mapcar 'org-file-menu-entry (org-agenda-files))))
18790 (org-agenda-set-mode-name)
18791 (apply
18792 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
18793 (list 'org-agenda-mode-hook)))
18795 (substitute-key-definition 'undo 'org-agenda-undo
18796 org-agenda-mode-map global-map)
18797 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
18798 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
18799 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
18800 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
18801 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
18802 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
18803 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
18804 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
18805 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
18806 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
18807 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
18808 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
18809 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
18810 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
18811 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
18812 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
18813 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
18814 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
18815 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
18816 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
18817 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
18818 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
18819 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
18820 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
18821 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
18822 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
18823 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
18824 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
18825 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
18827 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
18828 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
18829 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
18830 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
18831 (while l (org-defkey org-agenda-mode-map
18832 (int-to-string (pop l)) 'digit-argument)))
18834 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
18835 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
18836 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
18837 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
18838 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
18839 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
18840 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
18841 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
18842 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
18843 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
18844 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
18845 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
18846 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
18847 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
18848 (org-defkey org-agenda-mode-map "n" 'next-line)
18849 (org-defkey org-agenda-mode-map "p" 'previous-line)
18850 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
18851 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
18852 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
18853 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
18854 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
18855 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
18856 (eval-after-load "calendar"
18857 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
18858 'org-calendar-goto-agenda))
18859 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
18860 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
18861 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
18862 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
18863 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
18864 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
18865 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
18866 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
18867 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
18868 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
18869 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
18870 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18871 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
18872 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
18873 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
18874 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
18875 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
18876 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
18877 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
18878 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
18879 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
18880 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
18882 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
18883 "Local keymap for agenda entries from Org-mode.")
18885 (org-defkey org-agenda-keymap
18886 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
18887 (org-defkey org-agenda-keymap
18888 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
18889 (when org-agenda-mouse-1-follows-link
18890 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
18891 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
18892 '("Agenda"
18893 ("Agenda Files")
18894 "--"
18895 ["Show" org-agenda-show t]
18896 ["Go To (other window)" org-agenda-goto t]
18897 ["Go To (this window)" org-agenda-switch-to t]
18898 ["Follow Mode" org-agenda-follow-mode
18899 :style toggle :selected org-agenda-follow-mode :active t]
18900 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
18901 "--"
18902 ["Cycle TODO" org-agenda-todo t]
18903 ["Archive subtree" org-agenda-archive t]
18904 ["Delete subtree" org-agenda-kill t]
18905 "--"
18906 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
18907 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
18908 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
18909 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
18910 "--"
18911 ("Tags and Properties"
18912 ["Show all Tags" org-agenda-show-tags t]
18913 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
18914 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
18915 "--"
18916 ["Column View" org-columns t])
18917 ("Date/Schedule"
18918 ["Schedule" org-agenda-schedule t]
18919 ["Set Deadline" org-agenda-deadline t]
18920 "--"
18921 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
18922 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
18923 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
18924 ("Clock"
18925 ["Clock in" org-agenda-clock-in t]
18926 ["Clock out" org-agenda-clock-out t]
18927 ["Clock cancel" org-agenda-clock-cancel t]
18928 ["Goto running clock" org-clock-goto t])
18929 ("Priority"
18930 ["Set Priority" org-agenda-priority t]
18931 ["Increase Priority" org-agenda-priority-up t]
18932 ["Decrease Priority" org-agenda-priority-down t]
18933 ["Show Priority" org-agenda-show-priority t])
18934 ("Calendar/Diary"
18935 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
18936 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
18937 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
18938 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
18939 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
18940 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
18941 "--"
18942 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
18943 "--"
18944 ("View"
18945 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
18946 :style radio :selected (equal org-agenda-ndays 1)]
18947 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
18948 :style radio :selected (equal org-agenda-ndays 7)]
18949 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
18950 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
18951 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
18952 :style radio :selected (member org-agenda-ndays '(365 366))]
18953 "--"
18954 ["Show Logbook entries" org-agenda-log-mode
18955 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
18956 ["Include Diary" org-agenda-toggle-diary
18957 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
18958 ["Use Time Grid" org-agenda-toggle-time-grid
18959 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
18960 ["Write view to file" org-write-agenda t]
18961 ["Rebuild buffer" org-agenda-redo t]
18962 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
18963 "--"
18964 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
18965 "--"
18966 ["Quit" org-agenda-quit t]
18967 ["Exit and Release Buffers" org-agenda-exit t]
18970 ;;; Agenda undo
18972 (defvar org-agenda-allow-remote-undo t
18973 "Non-nil means, allow remote undo from the agenda buffer.")
18974 (defvar org-agenda-undo-list nil
18975 "List of undoable operations in the agenda since last refresh.")
18976 (defvar org-agenda-undo-has-started-in nil
18977 "Buffers that have already seen `undo-start' in the current undo sequence.")
18978 (defvar org-agenda-pending-undo-list nil
18979 "In a series of undo commands, this is the list of remaning undo items.")
18981 (defmacro org-if-unprotected (&rest body)
18982 "Execute BODY if there is no `org-protected' text property at point."
18983 (declare (debug t))
18984 `(unless (get-text-property (point) 'org-protected)
18985 ,@body))
18987 (defmacro org-with-remote-undo (_buffer &rest _body)
18988 "Execute BODY while recording undo information in two buffers."
18989 (declare (indent 1) (debug t))
18990 `(let ((_cline (org-current-line))
18991 (_cmd this-command)
18992 (_buf1 (current-buffer))
18993 (_buf2 ,_buffer)
18994 (_undo1 buffer-undo-list)
18995 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
18996 _c1 _c2)
18997 ,@_body
18998 (when org-agenda-allow-remote-undo
18999 (setq _c1 (org-verify-change-for-undo
19000 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19001 _c2 (org-verify-change-for-undo
19002 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19003 (when (or _c1 _c2)
19004 ;; make sure there are undo boundaries
19005 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19006 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19007 ;; remember which buffer to undo
19008 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19009 org-agenda-undo-list)))))
19011 (defun org-agenda-undo ()
19012 "Undo a remote editing step in the agenda.
19013 This undoes changes both in the agenda buffer and in the remote buffer
19014 that have been changed along."
19015 (interactive)
19016 (or org-agenda-allow-remote-undo
19017 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19018 (if (not (eq this-command last-command))
19019 (setq org-agenda-undo-has-started-in nil
19020 org-agenda-pending-undo-list org-agenda-undo-list))
19021 (if (not org-agenda-pending-undo-list)
19022 (error "No further undo information"))
19023 (let* ((entry (pop org-agenda-pending-undo-list))
19024 buf line cmd rembuf)
19025 (setq cmd (pop entry) line (pop entry))
19026 (setq rembuf (nth 2 entry))
19027 (org-with-remote-undo rembuf
19028 (while (bufferp (setq buf (pop entry)))
19029 (if (pop entry)
19030 (with-current-buffer buf
19031 (let ((last-undo-buffer buf)
19032 (inhibit-read-only t))
19033 (unless (memq buf org-agenda-undo-has-started-in)
19034 (push buf org-agenda-undo-has-started-in)
19035 (make-local-variable 'pending-undo-list)
19036 (undo-start))
19037 (while (and pending-undo-list
19038 (listp pending-undo-list)
19039 (not (car pending-undo-list)))
19040 (pop pending-undo-list))
19041 (undo-more 1))))))
19042 (goto-line line)
19043 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19045 (defun org-verify-change-for-undo (l1 l2)
19046 "Verify that a real change occurred between the undo lists L1 and L2."
19047 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19048 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19049 (not (eq l1 l2)))
19051 ;;; Agenda dispatch
19053 (defvar org-agenda-restrict nil)
19054 (defvar org-agenda-restrict-begin (make-marker))
19055 (defvar org-agenda-restrict-end (make-marker))
19056 (defvar org-agenda-last-dispatch-buffer nil)
19057 (defvar org-agenda-overriding-restriction nil)
19059 ;;;###autoload
19060 (defun org-agenda (arg &optional keys restriction)
19061 "Dispatch agenda commands to collect entries to the agenda buffer.
19062 Prompts for a command to execute. Any prefix arg will be passed
19063 on to the selected command. The default selections are:
19065 a Call `org-agenda-list' to display the agenda for current day or week.
19066 t Call `org-todo-list' to display the global todo list.
19067 T Call `org-todo-list' to display the global todo list, select only
19068 entries with a specific TODO keyword (the user gets a prompt).
19069 m Call `org-tags-view' to display headlines with tags matching
19070 a condition (the user is prompted for the condition).
19071 M Like `m', but select only TODO entries, no ordinary headlines.
19072 L Create a timeline for the current buffer.
19073 e Export views to associated files.
19075 More commands can be added by configuring the variable
19076 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19077 searches can be pre-defined in this way.
19079 If the current buffer is in Org-mode and visiting a file, you can also
19080 first press `<' once to indicate that the agenda should be temporarily
19081 \(until the next use of \\[org-agenda]) restricted to the current file.
19082 Pressing `<' twice means to restrict to the current subtree or region
19083 \(if active)."
19084 (interactive "P")
19085 (catch 'exit
19086 (let* ((prefix-descriptions nil)
19087 (org-agenda-custom-commands
19088 ;; normalize different versions
19089 (delq nil
19090 (mapcar
19091 (lambda (x)
19092 (cond ((stringp (cdr x))
19093 (push x prefix-descriptions)
19094 nil)
19095 ((stringp (nth 1 x)) x)
19096 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19097 (t (cons (car x) (cons "" (cdr x))))))
19098 org-agenda-custom-commands)))
19099 (buf (current-buffer))
19100 (bfn (buffer-file-name (buffer-base-buffer)))
19101 entry key type match lprops ans)
19102 ;; Turn off restriction unless there is an overriding one
19103 (unless org-agenda-overriding-restriction
19104 (put 'org-agenda-files 'org-restrict nil)
19105 (setq org-agenda-restrict nil)
19106 (move-marker org-agenda-restrict-begin nil)
19107 (move-marker org-agenda-restrict-end nil))
19108 ;; Delete old local properties
19109 (put 'org-agenda-redo-command 'org-lprops nil)
19110 ;; Remember where this call originated
19111 (setq org-agenda-last-dispatch-buffer (current-buffer))
19112 (unless keys
19113 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19114 keys (car ans)
19115 restriction (cdr ans)))
19116 ;; Estabish the restriction, if any
19117 (when (and (not org-agenda-overriding-restriction) restriction)
19118 (put 'org-agenda-files 'org-restrict (list bfn))
19119 (cond
19120 ((eq restriction 'region)
19121 (setq org-agenda-restrict t)
19122 (move-marker org-agenda-restrict-begin (region-beginning))
19123 (move-marker org-agenda-restrict-end (region-end)))
19124 ((eq restriction 'subtree)
19125 (save-excursion
19126 (setq org-agenda-restrict t)
19127 (org-back-to-heading t)
19128 (move-marker org-agenda-restrict-begin (point))
19129 (move-marker org-agenda-restrict-end
19130 (progn (org-end-of-subtree t)))))))
19132 (require 'calendar) ; FIXME: can we avoid this for some commands?
19133 ;; For example the todo list should not need it (but does...)
19134 (cond
19135 ((setq entry (assoc keys org-agenda-custom-commands))
19136 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19137 (progn
19138 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19139 (put 'org-agenda-redo-command 'org-lprops lprops)
19140 (cond
19141 ((eq type 'agenda)
19142 (org-let lprops '(org-agenda-list current-prefix-arg)))
19143 ((eq type 'alltodo)
19144 (org-let lprops '(org-todo-list current-prefix-arg)))
19145 ((eq type 'stuck)
19146 (org-let lprops '(org-agenda-list-stuck-projects
19147 current-prefix-arg)))
19148 ((eq type 'tags)
19149 (org-let lprops '(org-tags-view current-prefix-arg match)))
19150 ((eq type 'tags-todo)
19151 (org-let lprops '(org-tags-view '(4) match)))
19152 ((eq type 'todo)
19153 (org-let lprops '(org-todo-list match)))
19154 ((eq type 'tags-tree)
19155 (org-check-for-org-mode)
19156 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
19157 ((eq type 'todo-tree)
19158 (org-check-for-org-mode)
19159 (org-let lprops
19160 '(org-occur (concat "^" outline-regexp "[ \t]*"
19161 (regexp-quote match) "\\>"))))
19162 ((eq type 'occur-tree)
19163 (org-check-for-org-mode)
19164 (org-let lprops '(org-occur match)))
19165 ((functionp type)
19166 (org-let lprops '(funcall type match)))
19167 ((fboundp type)
19168 (org-let lprops '(funcall type match)))
19169 (t (error "Invalid custom agenda command type %s" type))))
19170 (org-run-agenda-series (nth 1 entry) (cddr entry))))
19171 ((equal keys "C") (customize-variable 'org-agenda-custom-commands))
19172 ((equal keys "a") (call-interactively 'org-agenda-list))
19173 ((equal keys "t") (call-interactively 'org-todo-list))
19174 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
19175 ((equal keys "m") (call-interactively 'org-tags-view))
19176 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
19177 ((equal keys "e") (call-interactively 'org-store-agenda-views))
19178 ((equal keys "L")
19179 (unless (org-mode-p)
19180 (error "This is not an Org-mode file"))
19181 (unless restriction
19182 (put 'org-agenda-files 'org-restrict (list bfn))
19183 (org-call-with-arg 'org-timeline arg)))
19184 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
19185 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
19186 ((equal keys "!") (customize-variable 'org-stuck-projects))
19187 (t (error "Invalid agenda key"))))))
19189 (defun org-agenda-normalize-custom-commands (cmds)
19190 (delq nil
19191 (mapcar
19192 (lambda (x)
19193 (cond ((stringp (cdr x)) nil)
19194 ((stringp (nth 1 x)) x)
19195 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19196 (t (cons (car x) (cons "" (cdr x))))))
19197 cmds)))
19199 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
19200 "The user interface for selecting an agenda command."
19201 (catch 'exit
19202 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
19203 (restrict-ok (and bfn (org-mode-p)))
19204 (region-p (org-region-active-p))
19205 (custom org-agenda-custom-commands)
19206 (selstring "")
19207 restriction second-time
19208 c entry key type match prefixes rmheader header-end custom1 desc)
19209 (save-window-excursion
19210 (delete-other-windows)
19211 (org-switch-to-buffer-other-window " *Agenda Commands*")
19212 (erase-buffer)
19213 (insert (eval-when-compile
19214 (let ((header
19216 Press key for an agenda command: < Buffer,subtree/region restriction
19217 -------------------------------- > Remove restriction
19218 a Agenda for current week or day e Export agenda views
19219 t List of all TODO entries T Entries with special TODO kwd
19220 m Match a TAGS query M Like m, but only TODO entries
19221 L Timeline for current buffer # List stuck projects (!=configure)
19222 / Multi-occur C Configure custom agenda commands
19224 (start 0))
19225 (while (string-match
19226 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
19227 header start)
19228 (setq start (match-end 0))
19229 (add-text-properties (match-beginning 2) (match-end 2)
19230 '(face bold) header))
19231 header)))
19232 (setq header-end (move-marker (make-marker) (point)))
19233 (while t
19234 (setq custom1 custom)
19235 (when (eq rmheader t)
19236 (goto-line 1)
19237 (re-search-forward ":" nil t)
19238 (delete-region (match-end 0) (point-at-eol))
19239 (forward-char 1)
19240 (looking-at "-+")
19241 (delete-region (match-end 0) (point-at-eol))
19242 (move-marker header-end (match-end 0)))
19243 (goto-char header-end)
19244 (delete-region (point) (point-max))
19245 (while (setq entry (pop custom1))
19246 (setq key (car entry) desc (nth 1 entry)
19247 type (nth 2 entry) match (nth 3 entry))
19248 (if (> (length key) 1)
19249 (add-to-list 'prefixes (string-to-char key))
19250 (insert
19251 (format
19252 "\n%-4s%-14s: %s"
19253 (org-add-props (copy-sequence key)
19254 '(face bold))
19255 (cond
19256 ((string-match "\\S-" desc) desc)
19257 ((eq type 'agenda) "Agenda for current week or day")
19258 ((eq type 'alltodo) "List of all TODO entries")
19259 ((eq type 'stuck) "List of stuck projects")
19260 ((eq type 'todo) "TODO keyword")
19261 ((eq type 'tags) "Tags query")
19262 ((eq type 'tags-todo) "Tags (TODO)")
19263 ((eq type 'tags-tree) "Tags tree")
19264 ((eq type 'todo-tree) "TODO kwd tree")
19265 ((eq type 'occur-tree) "Occur tree")
19266 ((functionp type) (if (symbolp type)
19267 (symbol-name type)
19268 "Lambda expression"))
19269 (t "???"))
19270 (cond
19271 ((stringp match)
19272 (org-add-props match nil 'face 'org-warning))
19273 (match
19274 (format "set of %d commands" (length match)))
19275 (t ""))))))
19276 (when prefixes
19277 (mapc (lambda (x)
19278 (insert
19279 (format "\n%s %s"
19280 (org-add-props (char-to-string x)
19281 nil 'face 'bold)
19282 (or (cdr (assoc (concat selstring (char-to-string x))
19283 prefix-descriptions))
19284 "Prefix key"))))
19285 prefixes))
19286 (goto-char (point-min))
19287 (when (fboundp 'fit-window-to-buffer)
19288 (if second-time
19289 (if (not (pos-visible-in-window-p (point-max)))
19290 (fit-window-to-buffer))
19291 (setq second-time t)
19292 (fit-window-to-buffer)))
19293 (message "Press key for agenda command%s:"
19294 (if (or restrict-ok org-agenda-overriding-restriction)
19295 (if org-agenda-overriding-restriction
19296 " (restriction lock active)"
19297 (if restriction
19298 (format " (restricted to %s)" restriction)
19299 " (unrestricted)"))
19300 ""))
19301 (setq c (read-char-exclusive))
19302 (message "")
19303 (cond
19304 ((assoc (char-to-string c) custom)
19305 (setq selstring (concat selstring (char-to-string c)))
19306 (throw 'exit (cons selstring restriction)))
19307 ((memq c prefixes)
19308 (setq selstring (concat selstring (char-to-string c))
19309 prefixes nil
19310 rmheader (or rmheader t)
19311 custom (delq nil (mapcar
19312 (lambda (x)
19313 (if (or (= (length (car x)) 1)
19314 (/= (string-to-char (car x)) c))
19316 (cons (substring (car x) 1) (cdr x))))
19317 custom))))
19318 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
19319 (message "Restriction is only possible in Org-mode buffers")
19320 (ding) (sit-for 1))
19321 ((eq c ?1)
19322 (org-agenda-remove-restriction-lock 'noupdate)
19323 (setq restriction 'buffer))
19324 ((eq c ?0)
19325 (org-agenda-remove-restriction-lock 'noupdate)
19326 (setq restriction (if region-p 'region 'subtree)))
19327 ((eq c ?<)
19328 (org-agenda-remove-restriction-lock 'noupdate)
19329 (setq restriction
19330 (cond
19331 ((eq restriction 'buffer)
19332 (if region-p 'region 'subtree))
19333 ((memq restriction '(subtree region))
19334 nil)
19335 (t 'buffer))))
19336 ((eq c ?>)
19337 (org-agenda-remove-restriction-lock 'noupdate)
19338 (setq restriction nil))
19339 ((and (equal selstring "") (memq c '(?a ?t ?m ?L ?C ?e ?T ?M ?# ?/)))
19340 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
19341 ((equal c ?q) (error "Abort"))
19342 (t (error "Invalid key %c" c))))))))
19344 (defun org-run-agenda-series (name series)
19345 (org-prepare-agenda name)
19346 (let* ((org-agenda-multi t)
19347 (redo (list 'org-run-agenda-series name (list 'quote series)))
19348 (cmds (car series))
19349 (gprops (nth 1 series))
19350 match ;; The byte compiler incorrectly complains about this. Keep it!
19351 cmd type lprops)
19352 (while (setq cmd (pop cmds))
19353 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
19354 (cond
19355 ((eq type 'agenda)
19356 (org-let2 gprops lprops
19357 '(call-interactively 'org-agenda-list)))
19358 ((eq type 'alltodo)
19359 (org-let2 gprops lprops
19360 '(call-interactively 'org-todo-list)))
19361 ((eq type 'stuck)
19362 (org-let2 gprops lprops
19363 '(call-interactively 'org-agenda-list-stuck-projects)))
19364 ((eq type 'tags)
19365 (org-let2 gprops lprops
19366 '(org-tags-view current-prefix-arg match)))
19367 ((eq type 'tags-todo)
19368 (org-let2 gprops lprops
19369 '(org-tags-view '(4) match)))
19370 ((eq type 'todo)
19371 (org-let2 gprops lprops
19372 '(org-todo-list match)))
19373 ((fboundp type)
19374 (org-let2 gprops lprops
19375 '(funcall type match)))
19376 (t (error "Invalid type in command series"))))
19377 (widen)
19378 (setq org-agenda-redo-command redo)
19379 (goto-char (point-min)))
19380 (org-finalize-agenda))
19382 ;;;###autoload
19383 (defmacro org-batch-agenda (cmd-key &rest parameters)
19384 "Run an agenda command in batch mode and send the result to STDOUT.
19385 If CMD-KEY is a string of length 1, it is used as a key in
19386 `org-agenda-custom-commands' and triggers this command. If it is a
19387 longer string is is used as a tags/todo match string.
19388 Paramters are alternating variable names and values that will be bound
19389 before running the agenda command."
19390 (let (pars)
19391 (while parameters
19392 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19393 (if (> (length cmd-key) 2)
19394 (eval (list 'let (nreverse pars)
19395 (list 'org-tags-view nil cmd-key)))
19396 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19397 (set-buffer org-agenda-buffer-name)
19398 (princ (org-encode-for-stdout (buffer-string)))))
19400 (defun org-encode-for-stdout (string)
19401 (if (fboundp 'encode-coding-string)
19402 (encode-coding-string string buffer-file-coding-system)
19403 string))
19405 (defvar org-agenda-info nil)
19407 ;;;###autoload
19408 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
19409 "Run an agenda command in batch mode and send the result to STDOUT.
19410 If CMD-KEY is a string of length 1, it is used as a key in
19411 `org-agenda-custom-commands' and triggers this command. If it is a
19412 longer string is is used as a tags/todo match string.
19413 Paramters are alternating variable names and values that will be bound
19414 before running the agenda command.
19416 The output gives a line for each selected agenda item. Each
19417 item is a list of comma-separated values, like this:
19419 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
19421 category The category of the item
19422 head The headline, without TODO kwd, TAGS and PRIORITY
19423 type The type of the agenda entry, can be
19424 todo selected in TODO match
19425 tagsmatch selected in tags match
19426 diary imported from diary
19427 deadline a deadline on given date
19428 scheduled scheduled on given date
19429 timestamp entry has timestamp on given date
19430 closed entry was closed on given date
19431 upcoming-deadline warning about deadline
19432 past-scheduled forwarded scheduled item
19433 block entry has date block including g. date
19434 todo The todo keyword, if any
19435 tags All tags including inherited ones, separated by colons
19436 date The relevant date, like 2007-2-14
19437 time The time, like 15:00-16:50
19438 extra Sting with extra planning info
19439 priority-l The priority letter if any was given
19440 priority-n The computed numerical priority
19441 agenda-day The day in the agenda where this is listed"
19443 (let (pars)
19444 (while parameters
19445 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19446 (push (list 'org-agenda-remove-tags t) pars)
19447 (if (> (length cmd-key) 2)
19448 (eval (list 'let (nreverse pars)
19449 (list 'org-tags-view nil cmd-key)))
19450 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19451 (set-buffer org-agenda-buffer-name)
19452 (let* ((lines (org-split-string (buffer-string) "\n"))
19453 line)
19454 (while (setq line (pop lines))
19455 (catch 'next
19456 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
19457 (setq org-agenda-info
19458 (org-fix-agenda-info (text-properties-at 0 line)))
19459 (princ
19460 (org-encode-for-stdout
19461 (mapconcat 'org-agenda-export-csv-mapper
19462 '(org-category txt type todo tags date time-of-day extra
19463 priority-letter priority agenda-day)
19464 ",")))
19465 (princ "\n"))))))
19467 (defun org-fix-agenda-info (props)
19468 "Make sure all properties on an agenda item have a canonical form,
19469 so the the export commands caneasily use it."
19470 (let (tmp re)
19471 (when (setq tmp (plist-get props 'tags))
19472 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
19473 (when (setq tmp (plist-get props 'date))
19474 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19475 (let ((calendar-date-display-form '(year "-" month "-" day)))
19476 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
19478 (setq tmp (calendar-date-string tmp)))
19479 (setq props (plist-put props 'date tmp)))
19480 (when (setq tmp (plist-get props 'day))
19481 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19482 (let ((calendar-date-display-form '(year "-" month "-" day)))
19483 (setq tmp (calendar-date-string tmp)))
19484 (setq props (plist-put props 'day tmp))
19485 (setq props (plist-put props 'agenda-day tmp)))
19486 (when (setq tmp (plist-get props 'txt))
19487 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
19488 (plist-put props 'priority-letter (match-string 1 tmp))
19489 (setq tmp (replace-match "" t t tmp)))
19490 (when (and (setq re (plist-get props 'org-todo-regexp))
19491 (setq re (concat "\\`\\.*" re " ?"))
19492 (string-match re tmp))
19493 (plist-put props 'todo (match-string 1 tmp))
19494 (setq tmp (replace-match "" t t tmp)))
19495 (plist-put props 'txt tmp)))
19496 props)
19498 (defun org-agenda-export-csv-mapper (prop)
19499 (let ((res (plist-get org-agenda-info prop)))
19500 (setq res
19501 (cond
19502 ((not res) "")
19503 ((stringp res) res)
19504 (t (prin1-to-string res))))
19505 (while (string-match "," res)
19506 (setq res (replace-match ";" t t res)))
19507 (org-trim res)))
19510 ;;;###autoload
19511 (defun org-store-agenda-views (&rest parameters)
19512 (interactive)
19513 (eval (list 'org-batch-store-agenda-views)))
19515 ;; FIXME, why is this a macro?????
19516 ;;;###autoload
19517 (defmacro org-batch-store-agenda-views (&rest parameters)
19518 "Run all custom agenda commands that have a file argument."
19519 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
19520 (pop-up-frames nil)
19521 (dir default-directory)
19522 pars cmd thiscmdkey files opts)
19523 (while parameters
19524 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19525 (setq pars (reverse pars))
19526 (save-window-excursion
19527 (while cmds
19528 (setq cmd (pop cmds)
19529 thiscmdkey (car cmd)
19530 opts (nth 4 cmd)
19531 files (nth 5 cmd))
19532 (if (stringp files) (setq files (list files)))
19533 (when files
19534 (eval (list 'let (append org-agenda-exporter-settings opts pars)
19535 (list 'org-agenda nil thiscmdkey)))
19536 (set-buffer org-agenda-buffer-name)
19537 (while files
19538 (eval (list 'let (append org-agenda-exporter-settings opts pars)
19539 (list 'org-write-agenda
19540 (expand-file-name (pop files) dir) t))))
19541 (and (get-buffer org-agenda-buffer-name)
19542 (kill-buffer org-agenda-buffer-name)))))))
19544 (defun org-write-agenda (file &optional nosettings)
19545 "Write the current buffer (an agenda view) as a file.
19546 Depending on the extension of the file name, plain text (.txt),
19547 HTML (.html or .htm) or Postscript (.ps) is produced.
19548 If NOSETTINGS is given, do not scope the settings of
19549 `org-agenda-exporter-settings' into the export commands. This is used when
19550 the settings have already been scoped and we do not wish to overrule other,
19551 higher priority settings."
19552 (interactive "FWrite agenda to file: ")
19553 (if (not (file-writable-p file))
19554 (error "Cannot write agenda to file %s" file))
19555 (cond
19556 ((string-match "\\.html?\\'" file) (require 'htmlize))
19557 ((string-match "\\.ps\\'" file) (require 'ps-print)))
19558 (org-let (if nosettings nil org-agenda-exporter-settings)
19559 '(save-excursion
19560 (save-window-excursion
19561 (cond
19562 ((string-match "\\.html?\\'" file)
19563 (set-buffer (htmlize-buffer (current-buffer)))
19565 (when (and org-agenda-export-html-style
19566 (string-match "<style>" org-agenda-export-html-style))
19567 ;; replace <style> section with org-agenda-export-html-style
19568 (goto-char (point-min))
19569 (kill-region (- (search-forward "<style") 6)
19570 (search-forward "</style>"))
19571 (insert org-agenda-export-html-style))
19572 (write-file file)
19573 (kill-buffer (current-buffer))
19574 (message "HTML written to %s" file))
19575 ((string-match "\\.ps\\'" file)
19576 (ps-print-buffer-with-faces file)
19577 (message "Postscript written to %s" file))
19579 (let ((bs (buffer-string)))
19580 (find-file file)
19581 (insert bs)
19582 (save-buffer 0)
19583 (kill-buffer (current-buffer))
19584 (message "Plain text written to %s" file))))))
19585 (set-buffer org-agenda-buffer-name)))
19587 (defmacro org-no-read-only (&rest body)
19588 "Inhibit read-only for BODY."
19589 `(let ((inhibit-read-only t)) ,@body))
19591 (defun org-check-for-org-mode ()
19592 "Make sure current buffer is in org-mode. Error if not."
19593 (or (org-mode-p)
19594 (error "Cannot execute org-mode agenda command on buffer in %s."
19595 major-mode)))
19597 (defun org-fit-agenda-window ()
19598 "Fit the window to the buffer size."
19599 (and (memq org-agenda-window-setup '(reorganize-frame))
19600 (fboundp 'fit-window-to-buffer)
19601 (fit-window-to-buffer
19603 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
19604 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
19606 ;;; Agenda file list
19608 (defun org-agenda-files (&optional unrestricted)
19609 "Get the list of agenda files.
19610 Optional UNRESTRICTED means return the full list even if a restriction
19611 is currently in place."
19612 (let ((files
19613 (cond
19614 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
19615 ((stringp org-agenda-files) (org-read-agenda-file-list))
19616 ((listp org-agenda-files) org-agenda-files)
19617 (t (error "Invalid value of `org-agenda-files'")))))
19618 (setq files (apply 'append
19619 (mapcar (lambda (f)
19620 (if (file-directory-p f)
19621 (directory-files f t "\\.org\\'")
19622 (list f)))
19623 files)))
19624 (if org-agenda-skip-unavailable-files
19625 (delq nil
19626 (mapcar (function
19627 (lambda (file)
19628 (and (file-readable-p file) file)))
19629 files))
19630 files))) ; `org-check-agenda-file' will remove them from the list
19632 (defun org-edit-agenda-file-list ()
19633 "Edit the list of agenda files.
19634 Depending on setup, this either uses customize to edit the variable
19635 `org-agenda-files', or it visits the file that is holding the list. In the
19636 latter case, the buffer is set up in a way that saving it automatically kills
19637 the buffer and restores the previous window configuration."
19638 (interactive)
19639 (if (stringp org-agenda-files)
19640 (let ((cw (current-window-configuration)))
19641 (find-file org-agenda-files)
19642 (org-set-local 'org-window-configuration cw)
19643 (org-add-hook 'after-save-hook
19644 (lambda ()
19645 (set-window-configuration
19646 (prog1 org-window-configuration
19647 (kill-buffer (current-buffer))))
19648 (org-install-agenda-files-menu)
19649 (message "New agenda file list installed"))
19650 nil 'local)
19651 (message "%s" (substitute-command-keys
19652 "Edit list and finish with \\[save-buffer]")))
19653 (customize-variable 'org-agenda-files)))
19655 (defun org-store-new-agenda-file-list (list)
19656 "Set new value for the agenda file list and save it correcly."
19657 (if (stringp org-agenda-files)
19658 (let ((f org-agenda-files) b)
19659 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
19660 (with-temp-file f
19661 (insert (mapconcat 'identity list "\n") "\n")))
19662 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
19663 (setq org-agenda-files list)
19664 (customize-save-variable 'org-agenda-files org-agenda-files))))
19666 (defun org-read-agenda-file-list ()
19667 "Read the list of agenda files from a file."
19668 (when (stringp org-agenda-files)
19669 (with-temp-buffer
19670 (insert-file-contents org-agenda-files)
19671 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
19674 ;;;###autoload
19675 (defun org-cycle-agenda-files ()
19676 "Cycle through the files in `org-agenda-files'.
19677 If the current buffer visits an agenda file, find the next one in the list.
19678 If the current buffer does not, find the first agenda file."
19679 (interactive)
19680 (let* ((fs (org-agenda-files t))
19681 (files (append fs (list (car fs))))
19682 (tcf (if buffer-file-name (file-truename buffer-file-name)))
19683 file)
19684 (unless files (error "No agenda files"))
19685 (catch 'exit
19686 (while (setq file (pop files))
19687 (if (equal (file-truename file) tcf)
19688 (when (car files)
19689 (find-file (car files))
19690 (throw 'exit t))))
19691 (find-file (car fs)))
19692 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
19694 (defun org-agenda-file-to-front (&optional to-end)
19695 "Move/add the current file to the top of the agenda file list.
19696 If the file is not present in the list, it is added to the front. If it is
19697 present, it is moved there. With optional argument TO-END, add/move to the
19698 end of the list."
19699 (interactive "P")
19700 (let ((org-agenda-skip-unavailable-files nil)
19701 (file-alist (mapcar (lambda (x)
19702 (cons (file-truename x) x))
19703 (org-agenda-files t)))
19704 (ctf (file-truename buffer-file-name))
19705 x had)
19706 (setq x (assoc ctf file-alist) had x)
19708 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
19709 (if to-end
19710 (setq file-alist (append (delq x file-alist) (list x)))
19711 (setq file-alist (cons x (delq x file-alist))))
19712 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
19713 (org-install-agenda-files-menu)
19714 (message "File %s to %s of agenda file list"
19715 (if had "moved" "added") (if to-end "end" "front"))))
19717 (defun org-remove-file (&optional file)
19718 "Remove current file from the list of files in variable `org-agenda-files'.
19719 These are the files which are being checked for agenda entries.
19720 Optional argument FILE means, use this file instead of the current."
19721 (interactive)
19722 (let* ((org-agenda-skip-unavailable-files nil)
19723 (file (or file buffer-file-name))
19724 (true-file (file-truename file))
19725 (afile (abbreviate-file-name file))
19726 (files (delq nil (mapcar
19727 (lambda (x)
19728 (if (equal true-file
19729 (file-truename x))
19730 nil x))
19731 (org-agenda-files t)))))
19732 (if (not (= (length files) (length (org-agenda-files t))))
19733 (progn
19734 (org-store-new-agenda-file-list files)
19735 (org-install-agenda-files-menu)
19736 (message "Removed file: %s" afile))
19737 (message "File was not in list: %s" afile))))
19739 (defun org-file-menu-entry (file)
19740 (vector file (list 'find-file file) t))
19742 (defun org-check-agenda-file (file)
19743 "Make sure FILE exists. If not, ask user what to do."
19744 (when (not (file-exists-p file))
19745 (message "non-existent file %s. [R]emove from list or [A]bort?"
19746 (abbreviate-file-name file))
19747 (let ((r (downcase (read-char-exclusive))))
19748 (cond
19749 ((equal r ?r)
19750 (org-remove-file file)
19751 (throw 'nextfile t))
19752 (t (error "Abort"))))))
19754 ;;; Agenda prepare and finalize
19756 (defvar org-agenda-multi nil) ; dynammically scoped
19757 (defvar org-agenda-buffer-name "*Org Agenda*")
19758 (defvar org-pre-agenda-window-conf nil)
19759 (defvar org-agenda-name nil)
19760 (defun org-prepare-agenda (&optional name)
19761 (setq org-todo-keywords-for-agenda nil)
19762 (setq org-done-keywords-for-agenda nil)
19763 (if org-agenda-multi
19764 (progn
19765 (setq buffer-read-only nil)
19766 (goto-char (point-max))
19767 (unless (or (bobp) org-agenda-compact-blocks)
19768 (insert "\n" (make-string (window-width) ?=) "\n"))
19769 (narrow-to-region (point) (point-max)))
19770 (org-agenda-maybe-reset-markers 'force)
19771 (org-prepare-agenda-buffers (org-agenda-files))
19772 (setq org-todo-keywords-for-agenda
19773 (org-uniquify org-todo-keywords-for-agenda))
19774 (setq org-done-keywords-for-agenda
19775 (org-uniquify org-done-keywords-for-agenda))
19776 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
19777 (awin (get-buffer-window abuf)))
19778 (cond
19779 ((equal (current-buffer) abuf) nil)
19780 (awin (select-window awin))
19781 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
19782 ((equal org-agenda-window-setup 'current-window)
19783 (switch-to-buffer abuf))
19784 ((equal org-agenda-window-setup 'other-window)
19785 (org-switch-to-buffer-other-window abuf))
19786 ((equal org-agenda-window-setup 'other-frame)
19787 (switch-to-buffer-other-frame abuf))
19788 ((equal org-agenda-window-setup 'reorganize-frame)
19789 (delete-other-windows)
19790 (org-switch-to-buffer-other-window abuf))))
19791 (setq buffer-read-only nil)
19792 (erase-buffer)
19793 (org-agenda-mode)
19794 (and name (not org-agenda-name)
19795 (org-set-local 'org-agenda-name name)))
19796 (setq buffer-read-only nil))
19798 (defun org-finalize-agenda ()
19799 "Finishing touch for the agenda buffer, called just before displaying it."
19800 (unless org-agenda-multi
19801 (save-excursion
19802 (let ((inhibit-read-only t))
19803 (goto-char (point-min))
19804 (while (org-activate-bracket-links (point-max))
19805 (add-text-properties (match-beginning 0) (match-end 0)
19806 '(face org-link)))
19807 (org-agenda-align-tags)
19808 (unless org-agenda-with-colors
19809 (remove-text-properties (point-min) (point-max) '(face nil))))
19810 (if (and (boundp 'org-overriding-columns-format)
19811 org-overriding-columns-format)
19812 (org-set-local 'org-overriding-columns-format
19813 org-overriding-columns-format))
19814 (if (and (boundp 'org-agenda-view-columns-initially)
19815 org-agenda-view-columns-initially)
19816 (org-agenda-columns))
19817 (when org-agenda-fontify-priorities
19818 (org-fontify-priorities))
19819 (run-hooks 'org-finalize-agenda-hook))))
19821 (defun org-fontify-priorities ()
19822 "Make highest priority lines bold, and lowest italic."
19823 (interactive)
19824 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
19825 (org-delete-overlay o)))
19826 (org-overlays-in (point-min) (point-max)))
19827 (save-excursion
19828 (let ((inhibit-read-only t)
19829 b e p ov h l)
19830 (goto-char (point-min))
19831 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
19832 (setq h (or (get-char-property (point) 'org-highest-priority)
19833 org-highest-priority)
19834 l (or (get-char-property (point) 'org-lowest-priority)
19835 org-lowest-priority)
19836 p (string-to-char (match-string 1))
19837 b (match-beginning 0) e (point-at-eol)
19838 ov (org-make-overlay b e))
19839 (org-overlay-put
19840 ov 'face
19841 (cond ((listp org-agenda-fontify-priorities)
19842 (cdr (assoc p org-agenda-fontify-priorities)))
19843 ((equal p l) 'italic)
19844 ((equal p h) 'bold)))
19845 (org-overlay-put ov 'org-type 'org-priority)))))
19847 (defun org-prepare-agenda-buffers (files)
19848 "Create buffers for all agenda files, protect archived trees and comments."
19849 (interactive)
19850 (let ((pa '(:org-archived t))
19851 (pc '(:org-comment t))
19852 (pall '(:org-archived t :org-comment t))
19853 (inhibit-read-only t)
19854 (rea (concat ":" org-archive-tag ":"))
19855 bmp file re)
19856 (save-excursion
19857 (save-restriction
19858 (while (setq file (pop files))
19859 (if (bufferp file)
19860 (set-buffer file)
19861 (org-check-agenda-file file)
19862 (set-buffer (org-get-agenda-file-buffer file)))
19863 (widen)
19864 (setq bmp (buffer-modified-p))
19865 (org-refresh-category-properties)
19866 (setq org-todo-keywords-for-agenda
19867 (append org-todo-keywords-for-agenda org-todo-keywords-1))
19868 (setq org-done-keywords-for-agenda
19869 (append org-done-keywords-for-agenda org-done-keywords))
19870 (save-excursion
19871 (remove-text-properties (point-min) (point-max) pall)
19872 (when org-agenda-skip-archived-trees
19873 (goto-char (point-min))
19874 (while (re-search-forward rea nil t)
19875 (if (org-on-heading-p t)
19876 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
19877 (goto-char (point-min))
19878 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
19879 (while (re-search-forward re nil t)
19880 (add-text-properties
19881 (match-beginning 0) (org-end-of-subtree t) pc)))
19882 (set-buffer-modified-p bmp))))))
19884 (defvar org-agenda-skip-function nil
19885 "Function to be called at each match during agenda construction.
19886 If this function returns nil, the current match should not be skipped.
19887 Otherwise, the function must return a position from where the search
19888 should be continued.
19889 This may also be a Lisp form, it will be evaluated.
19890 Never set this variable using `setq' or so, because then it will apply
19891 to all future agenda commands. Instead, bind it with `let' to scope
19892 it dynamically into the agenda-constructing command. A good way to set
19893 it is through options in org-agenda-custom-commands.")
19895 (defun org-agenda-skip ()
19896 "Throw to `:skip' in places that should be skipped.
19897 Also moves point to the end of the skipped region, so that search can
19898 continue from there."
19899 (let ((p (point-at-bol)) to fp)
19900 (and org-agenda-skip-archived-trees
19901 (get-text-property p :org-archived)
19902 (org-end-of-subtree t)
19903 (throw :skip t))
19904 (and (get-text-property p :org-comment)
19905 (org-end-of-subtree t)
19906 (throw :skip t))
19907 (if (equal (char-after p) ?#) (throw :skip t))
19908 (when (and (or (setq fp (functionp org-agenda-skip-function))
19909 (consp org-agenda-skip-function))
19910 (setq to (save-excursion
19911 (save-match-data
19912 (if fp
19913 (funcall org-agenda-skip-function)
19914 (eval org-agenda-skip-function))))))
19915 (goto-char to)
19916 (throw :skip t))))
19918 (defvar org-agenda-markers nil
19919 "List of all currently active markers created by `org-agenda'.")
19920 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
19921 "Creation time of the last agenda marker.")
19923 (defun org-agenda-new-marker (&optional pos)
19924 "Return a new agenda marker.
19925 Org-mode keeps a list of these markers and resets them when they are
19926 no longer in use."
19927 (let ((m (copy-marker (or pos (point)))))
19928 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
19929 (push m org-agenda-markers)
19932 (defun org-agenda-maybe-reset-markers (&optional force)
19933 "Reset markers created by `org-agenda'. But only if they are old enough."
19934 (if (or (and force (not org-agenda-multi))
19935 (> (- (time-to-seconds (current-time))
19936 org-agenda-last-marker-time)
19938 (while org-agenda-markers
19939 (move-marker (pop org-agenda-markers) nil))))
19941 (defun org-get-agenda-file-buffer (file)
19942 "Get a buffer visiting FILE. If the buffer needs to be created, add
19943 it to the list of buffers which might be released later."
19944 (let ((buf (org-find-base-buffer-visiting file)))
19945 (if buf
19946 buf ; just return it
19947 ;; Make a new buffer and remember it
19948 (setq buf (find-file-noselect file))
19949 (if buf (push buf org-agenda-new-buffers))
19950 buf)))
19952 (defun org-release-buffers (blist)
19953 "Release all buffers in list, asking the user for confirmation when needed.
19954 When a buffer is unmodified, it is just killed. When modified, it is saved
19955 \(if the user agrees) and then killed."
19956 (let (buf file)
19957 (while (setq buf (pop blist))
19958 (setq file (buffer-file-name buf))
19959 (when (and (buffer-modified-p buf)
19960 file
19961 (y-or-n-p (format "Save file %s? " file)))
19962 (with-current-buffer buf (save-buffer)))
19963 (kill-buffer buf))))
19965 (defun org-get-category (&optional pos)
19966 "Get the category applying to position POS."
19967 (get-text-property (or pos (point)) 'org-category))
19969 ;;; Agenda timeline
19971 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
19973 (defun org-timeline (&optional include-all)
19974 "Show a time-sorted view of the entries in the current org file.
19975 Only entries with a time stamp of today or later will be listed. With
19976 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
19977 under the current date.
19978 If the buffer contains an active region, only check the region for
19979 dates."
19980 (interactive "P")
19981 (require 'calendar)
19982 (org-compile-prefix-format 'timeline)
19983 (org-set-sorting-strategy 'timeline)
19984 (let* ((dopast t)
19985 (dotodo include-all)
19986 (doclosed org-agenda-show-log)
19987 (entry buffer-file-name)
19988 (date (calendar-current-date))
19989 (beg (if (org-region-active-p) (region-beginning) (point-min)))
19990 (end (if (org-region-active-p) (region-end) (point-max)))
19991 (day-numbers (org-get-all-dates beg end 'no-ranges
19992 t doclosed ; always include today
19993 org-timeline-show-empty-dates))
19994 (org-deadline-warning-days 0)
19995 (org-agenda-only-exact-dates t)
19996 (today (time-to-days (current-time)))
19997 (past t)
19998 args
19999 s e rtn d emptyp)
20000 (setq org-agenda-redo-command
20001 (list 'progn
20002 (list 'org-switch-to-buffer-other-window (current-buffer))
20003 (list 'org-timeline (list 'quote include-all))))
20004 (if (not dopast)
20005 ;; Remove past dates from the list of dates.
20006 (setq day-numbers (delq nil (mapcar (lambda(x)
20007 (if (>= x today) x nil))
20008 day-numbers))))
20009 (org-prepare-agenda (concat "Timeline "
20010 (file-name-nondirectory buffer-file-name)))
20011 (if doclosed (push :closed args))
20012 (push :timestamp args)
20013 (push :deadline args)
20014 (push :scheduled args)
20015 (push :sexp args)
20016 (if dotodo (push :todo args))
20017 (while (setq d (pop day-numbers))
20018 (if (and (listp d) (eq (car d) :omitted))
20019 (progn
20020 (setq s (point))
20021 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20022 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20023 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20024 (if (and (>= d today)
20025 dopast
20026 past)
20027 (progn
20028 (setq past nil)
20029 (insert (make-string 79 ?-) "\n")))
20030 (setq date (calendar-gregorian-from-absolute d))
20031 (setq s (point))
20032 (setq rtn (and (not emptyp)
20033 (apply 'org-agenda-get-day-entries entry
20034 date args)))
20035 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20036 (progn
20037 (insert
20038 (if (stringp org-agenda-format-date)
20039 (format-time-string org-agenda-format-date
20040 (org-time-from-absolute date))
20041 (funcall org-agenda-format-date date))
20042 "\n")
20043 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20044 (put-text-property s (1- (point)) 'org-date-line t)
20045 (if (equal d today)
20046 (put-text-property s (1- (point)) 'org-today t))
20047 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20048 (put-text-property s (1- (point)) 'day d)))))
20049 (goto-char (point-min))
20050 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20051 (point-min)))
20052 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20053 (org-finalize-agenda)
20054 (setq buffer-read-only t)))
20056 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
20057 "Return a list of all relevant day numbers from BEG to END buffer positions.
20058 If NO-RANGES is non-nil, include only the start and end dates of a range,
20059 not every single day in the range. If FORCE-TODAY is non-nil, make
20060 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20061 inactive time stamps (those in square brackets) are included.
20062 When EMPTY is non-nil, also include days without any entries."
20063 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
20064 dates dates1 date day day1 day2 ts1 ts2)
20065 (if force-today
20066 (setq dates (list (time-to-days (current-time)))))
20067 (save-excursion
20068 (goto-char beg)
20069 (while (re-search-forward re end t)
20070 (setq day (time-to-days (org-time-string-to-time
20071 (substring (match-string 1) 0 10))))
20072 (or (memq day dates) (push day dates)))
20073 (unless no-ranges
20074 (goto-char beg)
20075 (while (re-search-forward org-tr-regexp end t)
20076 (setq ts1 (substring (match-string 1) 0 10)
20077 ts2 (substring (match-string 2) 0 10)
20078 day1 (time-to-days (org-time-string-to-time ts1))
20079 day2 (time-to-days (org-time-string-to-time ts2)))
20080 (while (< (setq day1 (1+ day1)) day2)
20081 (or (memq day1 dates) (push day1 dates)))))
20082 (setq dates (sort dates '<))
20083 (when empty
20084 (while (setq day (pop dates))
20085 (setq day2 (car dates))
20086 (push day dates1)
20087 (when (and day2 empty)
20088 (if (or (eq empty t)
20089 (and (numberp empty) (<= (- day2 day) empty)))
20090 (while (< (setq day (1+ day)) day2)
20091 (push (list day) dates1))
20092 (push (cons :omitted (- day2 day)) dates1))))
20093 (setq dates (nreverse dates1)))
20094 dates)))
20096 ;;; Agenda Daily/Weekly
20098 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
20099 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
20100 (defvar org-agenda-last-arguments nil
20101 "The arguments of the previous call to org-agenda")
20102 (defvar org-starting-day nil) ; local variable in the agenda buffer
20103 (defvar org-agenda-span nil) ; local variable in the agenda buffer
20104 (defvar org-include-all-loc nil) ; local variable
20105 (defvar org-agenda-remove-date nil) ; dynamically scoped
20107 ;;;###autoload
20108 (defun org-agenda-list (&optional include-all start-day ndays)
20109 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
20110 The view will be for the current day or week, but from the overview buffer
20111 you will be able to go to other days/weeks.
20113 With one \\[universal-argument] prefix argument INCLUDE-ALL,
20114 all unfinished TODO items will also be shown, before the agenda.
20115 This feature is considered obsolete, please use the TODO list or a block
20116 agenda instead.
20118 With a numeric prefix argument in an interactive call, the agenda will
20119 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
20120 the number of days. NDAYS defaults to `org-agenda-ndays'.
20122 START-DAY defaults to TODAY, or to the most recent match for the weekday
20123 given in `org-agenda-start-on-weekday'."
20124 (interactive "P")
20125 (if (and (integerp include-all) (> include-all 0))
20126 (setq ndays include-all include-all nil))
20127 (setq ndays (or ndays org-agenda-ndays)
20128 start-day (or start-day org-agenda-start-day))
20129 (if org-agenda-overriding-arguments
20130 (setq include-all (car org-agenda-overriding-arguments)
20131 start-day (nth 1 org-agenda-overriding-arguments)
20132 ndays (nth 2 org-agenda-overriding-arguments)))
20133 (if (stringp start-day)
20134 ;; Convert to an absolute day number
20135 (setq start-day (time-to-days (org-read-date nil t start-day))))
20136 (setq org-agenda-last-arguments (list include-all start-day ndays))
20137 (org-compile-prefix-format 'agenda)
20138 (org-set-sorting-strategy 'agenda)
20139 (require 'calendar)
20140 (let* ((org-agenda-start-on-weekday
20141 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
20142 org-agenda-start-on-weekday nil))
20143 (thefiles (org-agenda-files))
20144 (files thefiles)
20145 (today (time-to-days
20146 (time-subtract (current-time)
20147 (list 0 (* 3600 org-extend-today-until) 0))))
20148 (sd (or start-day today))
20149 (start (if (or (null org-agenda-start-on-weekday)
20150 (< org-agenda-ndays 7))
20152 (let* ((nt (calendar-day-of-week
20153 (calendar-gregorian-from-absolute sd)))
20154 (n1 org-agenda-start-on-weekday)
20155 (d (- nt n1)))
20156 (- sd (+ (if (< d 0) 7 0) d)))))
20157 (day-numbers (list start))
20158 (day-cnt 0)
20159 (inhibit-redisplay (not debug-on-error))
20160 s e rtn rtnall file date d start-pos end-pos todayp nd)
20161 (setq org-agenda-redo-command
20162 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
20163 ;; Make the list of days
20164 (setq ndays (or ndays org-agenda-ndays)
20165 nd ndays)
20166 (while (> ndays 1)
20167 (push (1+ (car day-numbers)) day-numbers)
20168 (setq ndays (1- ndays)))
20169 (setq day-numbers (nreverse day-numbers))
20170 (org-prepare-agenda "Day/Week")
20171 (org-set-local 'org-starting-day (car day-numbers))
20172 (org-set-local 'org-include-all-loc include-all)
20173 (org-set-local 'org-agenda-span
20174 (org-agenda-ndays-to-span nd))
20175 (when (and (or include-all org-agenda-include-all-todo)
20176 (member today day-numbers))
20177 (setq files thefiles
20178 rtnall nil)
20179 (while (setq file (pop files))
20180 (catch 'nextfile
20181 (org-check-agenda-file file)
20182 (setq date (calendar-gregorian-from-absolute today)
20183 rtn (org-agenda-get-day-entries
20184 file date :todo))
20185 (setq rtnall (append rtnall rtn))))
20186 (when rtnall
20187 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
20188 (add-text-properties (point-min) (1- (point))
20189 (list 'face 'org-agenda-structure))
20190 (insert (org-finalize-agenda-entries rtnall) "\n")))
20191 (unless org-agenda-compact-blocks
20192 (setq s (point))
20193 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
20194 "-agenda:\n")
20195 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
20196 'org-date-line t)))
20197 (while (setq d (pop day-numbers))
20198 (setq date (calendar-gregorian-from-absolute d)
20199 s (point))
20200 (if (or (setq todayp (= d today))
20201 (and (not start-pos) (= d sd)))
20202 (setq start-pos (point))
20203 (if (and start-pos (not end-pos))
20204 (setq end-pos (point))))
20205 (setq files thefiles
20206 rtnall nil)
20207 (while (setq file (pop files))
20208 (catch 'nextfile
20209 (org-check-agenda-file file)
20210 (if org-agenda-show-log
20211 (setq rtn (org-agenda-get-day-entries
20212 file date
20213 :deadline :scheduled :timestamp :sexp :closed))
20214 (setq rtn (org-agenda-get-day-entries
20215 file date
20216 :deadline :scheduled :sexp :timestamp)))
20217 (setq rtnall (append rtnall rtn))))
20218 (if org-agenda-include-diary
20219 (progn
20220 (require 'diary-lib)
20221 (setq rtn (org-get-entries-from-diary date))
20222 (setq rtnall (append rtnall rtn))))
20223 (if (or rtnall org-agenda-show-all-dates)
20224 (progn
20225 (setq day-cnt (1+ day-cnt))
20226 (insert
20227 (if (stringp org-agenda-format-date)
20228 (format-time-string org-agenda-format-date
20229 (org-time-from-absolute date))
20230 (funcall org-agenda-format-date date))
20231 "\n")
20232 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20233 (put-text-property s (1- (point)) 'org-date-line t)
20234 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
20235 (if todayp (put-text-property s (1- (point)) 'org-today t))
20236 (if rtnall (insert
20237 (org-finalize-agenda-entries
20238 (org-agenda-add-time-grid-maybe
20239 rtnall nd todayp))
20240 "\n"))
20241 (put-text-property s (1- (point)) 'day d)
20242 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
20243 (goto-char (point-min))
20244 (org-fit-agenda-window)
20245 (unless (and (pos-visible-in-window-p (point-min))
20246 (pos-visible-in-window-p (point-max)))
20247 (goto-char (1- (point-max)))
20248 (recenter -1)
20249 (if (not (pos-visible-in-window-p (or start-pos 1)))
20250 (progn
20251 (goto-char (or start-pos 1))
20252 (recenter 1))))
20253 (goto-char (or start-pos 1))
20254 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
20255 (org-finalize-agenda)
20256 (setq buffer-read-only t)
20257 (message "")))
20259 (defun org-agenda-ndays-to-span (n)
20260 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
20262 ;;; Agenda TODO list
20264 (defvar org-select-this-todo-keyword nil)
20265 (defvar org-last-arg nil)
20267 ;;;###autoload
20268 (defun org-todo-list (arg)
20269 "Show all TODO entries from all agenda file in a single list.
20270 The prefix arg can be used to select a specific TODO keyword and limit
20271 the list to these. When using \\[universal-argument], you will be prompted
20272 for a keyword. A numeric prefix directly selects the Nth keyword in
20273 `org-todo-keywords-1'."
20274 (interactive "P")
20275 (require 'calendar)
20276 (org-compile-prefix-format 'todo)
20277 (org-set-sorting-strategy 'todo)
20278 (org-prepare-agenda "TODO")
20279 (let* ((today (time-to-days (current-time)))
20280 (date (calendar-gregorian-from-absolute today))
20281 (kwds org-todo-keywords-for-agenda)
20282 (completion-ignore-case t)
20283 (org-select-this-todo-keyword
20284 (if (stringp arg) arg
20285 (and arg (integerp arg) (> arg 0)
20286 (nth (1- arg) kwds))))
20287 rtn rtnall files file pos)
20288 (when (equal arg '(4))
20289 (setq org-select-this-todo-keyword
20290 (completing-read "Keyword (or KWD1|K2D2|...): "
20291 (mapcar 'list kwds) nil nil)))
20292 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
20293 (org-set-local 'org-last-arg arg)
20294 (setq org-agenda-redo-command
20295 '(org-todo-list (or current-prefix-arg org-last-arg)))
20296 (setq files (org-agenda-files)
20297 rtnall nil)
20298 (while (setq file (pop files))
20299 (catch 'nextfile
20300 (org-check-agenda-file file)
20301 (setq rtn (org-agenda-get-day-entries file date :todo))
20302 (setq rtnall (append rtnall rtn))))
20303 (if org-agenda-overriding-header
20304 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20305 nil 'face 'org-agenda-structure) "\n")
20306 (insert "Global list of TODO items of type: ")
20307 (add-text-properties (point-min) (1- (point))
20308 (list 'face 'org-agenda-structure))
20309 (setq pos (point))
20310 (insert (or org-select-this-todo-keyword "ALL") "\n")
20311 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20312 (setq pos (point))
20313 (unless org-agenda-multi
20314 (insert "Available with `N r': (0)ALL")
20315 (let ((n 0) s)
20316 (mapc (lambda (x)
20317 (setq s (format "(%d)%s" (setq n (1+ n)) x))
20318 (if (> (+ (current-column) (string-width s) 1) (frame-width))
20319 (insert "\n "))
20320 (insert " " s))
20321 kwds))
20322 (insert "\n"))
20323 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20324 (when rtnall
20325 (insert (org-finalize-agenda-entries rtnall) "\n"))
20326 (goto-char (point-min))
20327 (org-fit-agenda-window)
20328 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
20329 (org-finalize-agenda)
20330 (setq buffer-read-only t)))
20332 ;;; Agenda tags match
20334 ;;;###autoload
20335 (defun org-tags-view (&optional todo-only match)
20336 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
20337 The prefix arg TODO-ONLY limits the search to TODO entries."
20338 (interactive "P")
20339 (org-compile-prefix-format 'tags)
20340 (org-set-sorting-strategy 'tags)
20341 (let* ((org-tags-match-list-sublevels
20342 (if todo-only t org-tags-match-list-sublevels))
20343 (completion-ignore-case t)
20344 rtn rtnall files file pos matcher
20345 buffer)
20346 (setq matcher (org-make-tags-matcher match)
20347 match (car matcher) matcher (cdr matcher))
20348 (org-prepare-agenda (concat "TAGS " match))
20349 (setq org-agenda-redo-command
20350 (list 'org-tags-view (list 'quote todo-only)
20351 (list 'if 'current-prefix-arg nil match)))
20352 (setq files (org-agenda-files)
20353 rtnall nil)
20354 (while (setq file (pop files))
20355 (catch 'nextfile
20356 (org-check-agenda-file file)
20357 (setq buffer (if (file-exists-p file)
20358 (org-get-agenda-file-buffer file)
20359 (error "No such file %s" file)))
20360 (if (not buffer)
20361 ;; If file does not exist, merror message to agenda
20362 (setq rtn (list
20363 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
20364 rtnall (append rtnall rtn))
20365 (with-current-buffer buffer
20366 (unless (org-mode-p)
20367 (error "Agenda file %s is not in `org-mode'" file))
20368 (save-excursion
20369 (save-restriction
20370 (if org-agenda-restrict
20371 (narrow-to-region org-agenda-restrict-begin
20372 org-agenda-restrict-end)
20373 (widen))
20374 (setq rtn (org-scan-tags 'agenda matcher todo-only))
20375 (setq rtnall (append rtnall rtn))))))))
20376 (if org-agenda-overriding-header
20377 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20378 nil 'face 'org-agenda-structure) "\n")
20379 (insert "Headlines with TAGS match: ")
20380 (add-text-properties (point-min) (1- (point))
20381 (list 'face 'org-agenda-structure))
20382 (setq pos (point))
20383 (insert match "\n")
20384 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20385 (setq pos (point))
20386 (unless org-agenda-multi
20387 (insert "Press `C-u r' to search again with new search string\n"))
20388 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20389 (when rtnall
20390 (insert (org-finalize-agenda-entries rtnall) "\n"))
20391 (goto-char (point-min))
20392 (org-fit-agenda-window)
20393 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
20394 (org-finalize-agenda)
20395 (setq buffer-read-only t)))
20397 ;;; Agenda Finding stuck projects
20399 (defvar org-agenda-skip-regexp nil
20400 "Regular expression used in skipping subtrees for the agenda.
20401 This is basically a temporary global variable that can be set and then
20402 used by user-defined selections using `org-agenda-skip-function'.")
20404 (defvar org-agenda-overriding-header nil
20405 "When this is set during todo and tags searches, will replace header.")
20407 (defun org-agenda-skip-subtree-when-regexp-matches ()
20408 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
20409 If yes, it returns the end position of this tree, causing agenda commands
20410 to skip this subtree. This is a function that can be put into
20411 `org-agenda-skip-function' for the duration of a command."
20412 (let ((end (save-excursion (org-end-of-subtree t)))
20413 skip)
20414 (save-excursion
20415 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
20416 (and skip end)))
20418 (defun org-agenda-skip-entry-if (&rest conditions)
20419 "Skip entry if any of CONDITIONS is true.
20420 See `org-agenda-skip-if for details."
20421 (org-agenda-skip-if nil conditions))
20423 (defun org-agenda-skip-subtree-if (&rest conditions)
20424 "Skip entry if any of CONDITIONS is true.
20425 See `org-agenda-skip-if for details."
20426 (org-agenda-skip-if t conditions))
20428 (defun org-agenda-skip-if (subtree conditions)
20429 "Checks current entity for CONDITIONS.
20430 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
20431 the entry, i.e. the text before the next heading is checked.
20433 CONDITIONS is a list of symbols, boolean OR is used to combine the results
20434 from different tests. Valid conditions are:
20436 scheduled Check if there is a scheduled cookie
20437 notscheduled Check if there is no scheduled cookie
20438 deadline Check if there is a deadline
20439 notdeadline Check if there is no deadline
20440 regexp Check if regexp matches
20441 notregexp Check if regexp does not match.
20443 The regexp is taken from the conditions list, it must com right after the
20444 `regexp' of `notregexp' element.
20446 If any of these conditions is met, this function returns the end point of
20447 the entity, causing the search to continue from there. This is a function
20448 that can be put into `org-agenda-skip-function' for the duration of a command."
20449 (let (beg end m)
20450 (org-back-to-heading t)
20451 (setq beg (point)
20452 end (if subtree
20453 (progn (org-end-of-subtree t) (point))
20454 (progn (outline-next-heading) (1- (point)))))
20455 (goto-char beg)
20456 (and
20458 (and (memq 'scheduled conditions)
20459 (re-search-forward org-scheduled-time-regexp end t))
20460 (and (memq 'notscheduled conditions)
20461 (not (re-search-forward org-scheduled-time-regexp end t)))
20462 (and (memq 'deadline conditions)
20463 (re-search-forward org-deadline-time-regexp end t))
20464 (and (memq 'notdeadline conditions)
20465 (not (re-search-forward org-deadline-time-regexp end t)))
20466 (and (setq m (memq 'regexp conditions))
20467 (stringp (nth 1 m))
20468 (re-search-forward (nth 1 m) end t))
20469 (and (setq m (memq 'notregexp conditions))
20470 (stringp (nth 1 m))
20471 (not (re-search-forward (nth 1 m) end t))))
20472 end)))
20474 ;;;###autoload
20475 (defun org-agenda-list-stuck-projects (&rest ignore)
20476 "Create agenda view for projects that are stuck.
20477 Stuck projects are project that have no next actions. For the definitions
20478 of what a project is and how to check if it stuck, customize the variable
20479 `org-stuck-projects'.
20480 MATCH is being ignored."
20481 (interactive)
20482 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
20483 ;; FIXME: we could have used org-agenda-skip-if here.
20484 (org-agenda-overriding-header "List of stuck projects: ")
20485 (matcher (nth 0 org-stuck-projects))
20486 (todo (nth 1 org-stuck-projects))
20487 (todo-wds (if (member "*" todo)
20488 (progn
20489 (org-prepare-agenda-buffers (org-agenda-files))
20490 (org-delete-all
20491 org-done-keywords-for-agenda
20492 (copy-sequence org-todo-keywords-for-agenda)))
20493 todo))
20494 (todo-re (concat "^\\*+[ \t]+\\("
20495 (mapconcat 'identity todo-wds "\\|")
20496 "\\)\\>"))
20497 (tags (nth 2 org-stuck-projects))
20498 (tags-re (if (member "*" tags)
20499 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
20500 (concat "^\\*+ .*:\\("
20501 (mapconcat 'identity tags "\\|")
20502 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
20503 (gen-re (nth 3 org-stuck-projects))
20504 (re-list
20505 (delq nil
20506 (list
20507 (if todo todo-re)
20508 (if tags tags-re)
20509 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
20510 gen-re)))))
20511 (setq org-agenda-skip-regexp
20512 (if re-list
20513 (mapconcat 'identity re-list "\\|")
20514 (error "No information how to identify unstuck projects")))
20515 (org-tags-view nil matcher)
20516 (with-current-buffer org-agenda-buffer-name
20517 (setq org-agenda-redo-command
20518 '(org-agenda-list-stuck-projects
20519 (or current-prefix-arg org-last-arg))))))
20521 ;;; Diary integration
20523 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
20525 (defun org-get-entries-from-diary (date)
20526 "Get the (Emacs Calendar) diary entries for DATE."
20527 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
20528 (diary-display-hook '(fancy-diary-display))
20529 (pop-up-frames nil)
20530 (list-diary-entries-hook
20531 (cons 'org-diary-default-entry list-diary-entries-hook))
20532 (diary-file-name-prefix-function nil) ; turn this feature off
20533 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
20534 entries
20535 (org-disable-agenda-to-diary t))
20536 (save-excursion
20537 (save-window-excursion
20538 (funcall (if (fboundp 'diary-list-entries)
20539 'diary-list-entries 'list-diary-entries)
20540 date 1)))
20541 (if (not (get-buffer fancy-diary-buffer))
20542 (setq entries nil)
20543 (with-current-buffer fancy-diary-buffer
20544 (setq buffer-read-only nil)
20545 (if (zerop (buffer-size))
20546 ;; No entries
20547 (setq entries nil)
20548 ;; Omit the date and other unnecessary stuff
20549 (org-agenda-cleanup-fancy-diary)
20550 ;; Add prefix to each line and extend the text properties
20551 (if (zerop (buffer-size))
20552 (setq entries nil)
20553 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
20554 (set-buffer-modified-p nil)
20555 (kill-buffer fancy-diary-buffer)))
20556 (when entries
20557 (setq entries (org-split-string entries "\n"))
20558 (setq entries
20559 (mapcar
20560 (lambda (x)
20561 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
20562 ;; Extend the text properties to the beginning of the line
20563 (org-add-props x (text-properties-at (1- (length x)) x)
20564 'type "diary" 'date date))
20565 entries)))))
20567 (defun org-agenda-cleanup-fancy-diary ()
20568 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
20569 This gets rid of the date, the underline under the date, and
20570 the dummy entry installed by `org-mode' to ensure non-empty diary for each
20571 date. It also removes lines that contain only whitespace."
20572 (goto-char (point-min))
20573 (if (looking-at ".*?:[ \t]*")
20574 (progn
20575 (replace-match "")
20576 (re-search-forward "\n=+$" nil t)
20577 (replace-match "")
20578 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
20579 (re-search-forward "\n=+$" nil t)
20580 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
20581 (goto-char (point-min))
20582 (while (re-search-forward "^ +\n" nil t)
20583 (replace-match ""))
20584 (goto-char (point-min))
20585 (if (re-search-forward "^Org-mode dummy\n?" nil t)
20586 (replace-match "")))
20588 ;; Make sure entries from the diary have the right text properties.
20589 (eval-after-load "diary-lib"
20590 '(if (boundp 'diary-modify-entry-list-string-function)
20591 ;; We can rely on the hook, nothing to do
20593 ;; Hook not avaiable, must use advice to make this work
20594 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
20595 "Make the position visible."
20596 (if (and org-disable-agenda-to-diary ;; called from org-agenda
20597 (stringp string)
20598 buffer-file-name)
20599 (setq string (org-modify-diary-entry-string string))))))
20601 (defun org-modify-diary-entry-string (string)
20602 "Add text properties to string, allowing org-mode to act on it."
20603 (org-add-props string nil
20604 'mouse-face 'highlight
20605 'keymap org-agenda-keymap
20606 'help-echo (if buffer-file-name
20607 (format "mouse-2 or RET jump to diary file %s"
20608 (abbreviate-file-name buffer-file-name))
20610 'org-agenda-diary-link t
20611 'org-marker (org-agenda-new-marker (point-at-bol))))
20613 (defun org-diary-default-entry ()
20614 "Add a dummy entry to the diary.
20615 Needed to avoid empty dates which mess up holiday display."
20616 ;; Catch the error if dealing with the new add-to-diary-alist
20617 (when org-disable-agenda-to-diary
20618 (condition-case nil
20619 (add-to-diary-list original-date "Org-mode dummy" "")
20620 (error
20621 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
20623 ;;;###autoload
20624 (defun org-diary (&rest args)
20625 "Return diary information from org-files.
20626 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
20627 It accesses org files and extracts information from those files to be
20628 listed in the diary. The function accepts arguments specifying what
20629 items should be listed. The following arguments are allowed:
20631 :timestamp List the headlines of items containing a date stamp or
20632 date range matching the selected date. Deadlines will
20633 also be listed, on the expiration day.
20635 :sexp List entries resulting from diary-like sexps.
20637 :deadline List any deadlines past due, or due within
20638 `org-deadline-warning-days'. The listing occurs only
20639 in the diary for *today*, not at any other date. If
20640 an entry is marked DONE, it is no longer listed.
20642 :scheduled List all items which are scheduled for the given date.
20643 The diary for *today* also contains items which were
20644 scheduled earlier and are not yet marked DONE.
20646 :todo List all TODO items from the org-file. This may be a
20647 long list - so this is not turned on by default.
20648 Like deadlines, these entries only show up in the
20649 diary for *today*, not at any other date.
20651 The call in the diary file should look like this:
20653 &%%(org-diary) ~/path/to/some/orgfile.org
20655 Use a separate line for each org file to check. Or, if you omit the file name,
20656 all files listed in `org-agenda-files' will be checked automatically:
20658 &%%(org-diary)
20660 If you don't give any arguments (as in the example above), the default
20661 arguments (:deadline :scheduled :timestamp :sexp) are used.
20662 So the example above may also be written as
20664 &%%(org-diary :deadline :timestamp :sexp :scheduled)
20666 The function expects the lisp variables `entry' and `date' to be provided
20667 by the caller, because this is how the calendar works. Don't use this
20668 function from a program - use `org-agenda-get-day-entries' instead."
20669 (org-agenda-maybe-reset-markers)
20670 (org-compile-prefix-format 'agenda)
20671 (org-set-sorting-strategy 'agenda)
20672 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
20673 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
20674 (list entry)
20675 (org-agenda-files t)))
20676 file rtn results)
20677 (org-prepare-agenda-buffers files)
20678 ;; If this is called during org-agenda, don't return any entries to
20679 ;; the calendar. Org Agenda will list these entries itself.
20680 (if org-disable-agenda-to-diary (setq files nil))
20681 (while (setq file (pop files))
20682 (setq rtn (apply 'org-agenda-get-day-entries file date args))
20683 (setq results (append results rtn)))
20684 (if results
20685 (concat (org-finalize-agenda-entries results) "\n"))))
20687 ;;; Agenda entry finders
20689 (defun org-agenda-get-day-entries (file date &rest args)
20690 "Does the work for `org-diary' and `org-agenda'.
20691 FILE is the path to a file to be checked for entries. DATE is date like
20692 the one returned by `calendar-current-date'. ARGS are symbols indicating
20693 which kind of entries should be extracted. For details about these, see
20694 the documentation of `org-diary'."
20695 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
20696 (let* ((org-startup-folded nil)
20697 (org-startup-align-all-tables nil)
20698 (buffer (if (file-exists-p file)
20699 (org-get-agenda-file-buffer file)
20700 (error "No such file %s" file)))
20701 arg results rtn)
20702 (if (not buffer)
20703 ;; If file does not exist, make sure an error message ends up in diary
20704 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
20705 (with-current-buffer buffer
20706 (unless (org-mode-p)
20707 (error "Agenda file %s is not in `org-mode'" file))
20708 (let ((case-fold-search nil))
20709 (save-excursion
20710 (save-restriction
20711 (if org-agenda-restrict
20712 (narrow-to-region org-agenda-restrict-begin
20713 org-agenda-restrict-end)
20714 (widen))
20715 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
20716 (while (setq arg (pop args))
20717 (cond
20718 ((and (eq arg :todo)
20719 (equal date (calendar-current-date)))
20720 (setq rtn (org-agenda-get-todos))
20721 (setq results (append results rtn)))
20722 ((eq arg :timestamp)
20723 (setq rtn (org-agenda-get-blocks))
20724 (setq results (append results rtn))
20725 (setq rtn (org-agenda-get-timestamps))
20726 (setq results (append results rtn)))
20727 ((eq arg :sexp)
20728 (setq rtn (org-agenda-get-sexps))
20729 (setq results (append results rtn)))
20730 ((eq arg :scheduled)
20731 (setq rtn (org-agenda-get-scheduled))
20732 (setq results (append results rtn)))
20733 ((eq arg :closed)
20734 (setq rtn (org-agenda-get-closed))
20735 (setq results (append results rtn)))
20736 ((eq arg :deadline)
20737 (setq rtn (org-agenda-get-deadlines))
20738 (setq results (append results rtn))))))))
20739 results))))
20741 (defun org-entry-is-todo-p ()
20742 (member (org-get-todo-state) org-not-done-keywords))
20744 (defun org-entry-is-done-p ()
20745 (member (org-get-todo-state) org-done-keywords))
20747 (defun org-get-todo-state ()
20748 (save-excursion
20749 (org-back-to-heading t)
20750 (and (looking-at org-todo-line-regexp)
20751 (match-end 2)
20752 (match-string 2))))
20754 (defun org-at-date-range-p (&optional inactive-ok)
20755 "Is the cursor inside a date range?"
20756 (interactive)
20757 (save-excursion
20758 (catch 'exit
20759 (let ((pos (point)))
20760 (skip-chars-backward "^[<\r\n")
20761 (skip-chars-backward "<[")
20762 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
20763 (>= (match-end 0) pos)
20764 (throw 'exit t))
20765 (skip-chars-backward "^<[\r\n")
20766 (skip-chars-backward "<[")
20767 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
20768 (>= (match-end 0) pos)
20769 (throw 'exit t)))
20770 nil)))
20772 (defun org-agenda-get-todos ()
20773 "Return the TODO information for agenda display."
20774 (let* ((props (list 'face nil
20775 'done-face 'org-done
20776 'org-not-done-regexp org-not-done-regexp
20777 'org-todo-regexp org-todo-regexp
20778 'mouse-face 'highlight
20779 'keymap org-agenda-keymap
20780 'help-echo
20781 (format "mouse-2 or RET jump to org file %s"
20782 (abbreviate-file-name buffer-file-name))))
20783 ;; FIXME: get rid of the \n at some point but watch out
20784 (regexp (concat "^\\*+[ \t]+\\("
20785 (if org-select-this-todo-keyword
20786 (if (equal org-select-this-todo-keyword "*")
20787 org-todo-regexp
20788 (concat "\\<\\("
20789 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
20790 "\\)\\>"))
20791 org-not-done-regexp)
20792 "[^\n\r]*\\)"))
20793 marker priority category tags
20794 ee txt beg end)
20795 (goto-char (point-min))
20796 (while (re-search-forward regexp nil t)
20797 (catch :skip
20798 (save-match-data
20799 (beginning-of-line)
20800 (setq beg (point) end (progn (outline-next-heading) (point)))
20801 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
20802 (re-search-forward org-ts-regexp end t))
20803 (and org-agenda-todo-ignore-scheduled (goto-char beg)
20804 (re-search-forward org-scheduled-time-regexp end t))
20805 (and org-agenda-todo-ignore-deadlines (goto-char beg)
20806 (re-search-forward org-deadline-time-regexp end t)
20807 (org-deadline-close (match-string 1))))
20808 (goto-char (1+ beg))
20809 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
20810 (throw :skip nil)))
20811 (goto-char beg)
20812 (org-agenda-skip)
20813 (goto-char (match-beginning 1))
20814 (setq marker (org-agenda-new-marker (match-beginning 0))
20815 category (org-get-category)
20816 tags (org-get-tags-at (point))
20817 txt (org-format-agenda-item "" (match-string 1) category tags)
20818 priority (1+ (org-get-priority txt)))
20819 (org-add-props txt props
20820 'org-marker marker 'org-hd-marker marker
20821 'priority priority 'org-category category
20822 'type "todo")
20823 (push txt ee)
20824 (if org-agenda-todo-list-sublevels
20825 (goto-char (match-end 1))
20826 (org-end-of-subtree 'invisible))))
20827 (nreverse ee)))
20829 (defconst org-agenda-no-heading-message
20830 "No heading for this item in buffer or region.")
20832 (defun org-agenda-get-timestamps ()
20833 "Return the date stamp information for agenda display."
20834 (let* ((props (list 'face nil
20835 'org-not-done-regexp org-not-done-regexp
20836 'org-todo-regexp org-todo-regexp
20837 'mouse-face 'highlight
20838 'keymap org-agenda-keymap
20839 'help-echo
20840 (format "mouse-2 or RET jump to org file %s"
20841 (abbreviate-file-name buffer-file-name))))
20842 (d1 (calendar-absolute-from-gregorian date))
20843 (remove-re
20844 (concat
20845 (regexp-quote
20846 (format-time-string
20847 "<%Y-%m-%d"
20848 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20849 ".*?>"))
20850 (regexp
20851 (concat
20852 (regexp-quote
20853 (substring
20854 (format-time-string
20855 (car org-time-stamp-formats)
20856 (apply 'encode-time ; DATE bound by calendar
20857 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
20858 0 11))
20859 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
20860 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
20861 marker hdmarker deadlinep scheduledp donep tmp priority category
20862 ee txt timestr tags b0 b3 e3 head)
20863 (goto-char (point-min))
20864 (while (re-search-forward regexp nil t)
20865 (setq b0 (match-beginning 0)
20866 b3 (match-beginning 3) e3 (match-end 3))
20867 (catch :skip
20868 (and (org-at-date-range-p) (throw :skip nil))
20869 (org-agenda-skip)
20870 (if (and (match-end 1)
20871 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
20872 (throw :skip nil))
20873 (if (and e3
20874 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
20875 (throw :skip nil))
20876 (setq marker (org-agenda-new-marker b0)
20877 category (org-get-category b0)
20878 tmp (buffer-substring (max (point-min)
20879 (- b0 org-ds-keyword-length))
20881 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
20882 deadlinep (string-match org-deadline-regexp tmp)
20883 scheduledp (string-match org-scheduled-regexp tmp)
20884 donep (org-entry-is-done-p))
20885 (if (or scheduledp deadlinep) (throw :skip t))
20886 (if (string-match ">" timestr)
20887 ;; substring should only run to end of time stamp
20888 (setq timestr (substring timestr 0 (match-end 0))))
20889 (save-excursion
20890 (if (re-search-backward "^\\*+ " nil t)
20891 (progn
20892 (goto-char (match-beginning 0))
20893 (setq hdmarker (org-agenda-new-marker)
20894 tags (org-get-tags-at))
20895 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
20896 (setq head (match-string 1))
20897 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
20898 (setq txt (org-format-agenda-item
20899 nil head category tags timestr nil
20900 remove-re)))
20901 (setq txt org-agenda-no-heading-message))
20902 (setq priority (org-get-priority txt))
20903 (org-add-props txt props
20904 'org-marker marker 'org-hd-marker hdmarker)
20905 (org-add-props txt nil 'priority priority
20906 'org-category category 'date date
20907 'type "timestamp")
20908 (push txt ee))
20909 (outline-next-heading)))
20910 (nreverse ee)))
20912 (defun org-agenda-get-sexps ()
20913 "Return the sexp information for agenda display."
20914 (require 'diary-lib)
20915 (let* ((props (list 'face nil
20916 'mouse-face 'highlight
20917 'keymap org-agenda-keymap
20918 'help-echo
20919 (format "mouse-2 or RET jump to org file %s"
20920 (abbreviate-file-name buffer-file-name))))
20921 (regexp "^&?%%(")
20922 marker category ee txt tags entry result beg b sexp sexp-entry)
20923 (goto-char (point-min))
20924 (while (re-search-forward regexp nil t)
20925 (catch :skip
20926 (org-agenda-skip)
20927 (setq beg (match-beginning 0))
20928 (goto-char (1- (match-end 0)))
20929 (setq b (point))
20930 (forward-sexp 1)
20931 (setq sexp (buffer-substring b (point)))
20932 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
20933 (org-trim (match-string 1))
20934 ""))
20935 (setq result (org-diary-sexp-entry sexp sexp-entry date))
20936 (when result
20937 (setq marker (org-agenda-new-marker beg)
20938 category (org-get-category beg))
20940 (if (string-match "\\S-" result)
20941 (setq txt result)
20942 (setq txt "SEXP entry returned empty string"))
20944 (setq txt (org-format-agenda-item
20945 "" txt category tags 'time))
20946 (org-add-props txt props 'org-marker marker)
20947 (org-add-props txt nil
20948 'org-category category 'date date
20949 'type "sexp")
20950 (push txt ee))))
20951 (nreverse ee)))
20953 (defun org-agenda-get-closed ()
20954 "Return the logged TODO entries for agenda display."
20955 (let* ((props (list 'mouse-face 'highlight
20956 'org-not-done-regexp org-not-done-regexp
20957 'org-todo-regexp org-todo-regexp
20958 'keymap org-agenda-keymap
20959 'help-echo
20960 (format "mouse-2 or RET jump to org file %s"
20961 (abbreviate-file-name buffer-file-name))))
20962 (regexp (concat
20963 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
20964 (regexp-quote
20965 (substring
20966 (format-time-string
20967 (car org-time-stamp-formats)
20968 (apply 'encode-time ; DATE bound by calendar
20969 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
20970 1 11))))
20971 marker hdmarker priority category tags closedp
20972 ee txt timestr)
20973 (goto-char (point-min))
20974 (while (re-search-forward regexp nil t)
20975 (catch :skip
20976 (org-agenda-skip)
20977 (setq marker (org-agenda-new-marker (match-beginning 0))
20978 closedp (equal (match-string 1) org-closed-string)
20979 category (org-get-category (match-beginning 0))
20980 timestr (buffer-substring (match-beginning 0) (point-at-eol))
20981 ;; donep (org-entry-is-done-p)
20983 (if (string-match "\\]" timestr)
20984 ;; substring should only run to end of time stamp
20985 (setq timestr (substring timestr 0 (match-end 0))))
20986 (save-excursion
20987 (if (re-search-backward "^\\*+ " nil t)
20988 (progn
20989 (goto-char (match-beginning 0))
20990 (setq hdmarker (org-agenda-new-marker)
20991 tags (org-get-tags-at))
20992 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
20993 (setq txt (org-format-agenda-item
20994 (if closedp "Closed: " "Clocked: ")
20995 (match-string 1) category tags timestr)))
20996 (setq txt org-agenda-no-heading-message))
20997 (setq priority 100000)
20998 (org-add-props txt props
20999 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
21000 'priority priority 'org-category category
21001 'type "closed" 'date date
21002 'undone-face 'org-warning 'done-face 'org-done)
21003 (push txt ee))
21004 (outline-next-heading)))
21005 (nreverse ee)))
21007 (defun org-agenda-get-deadlines ()
21008 "Return the deadline information for agenda display."
21009 (let* ((props (list 'mouse-face 'highlight
21010 'org-not-done-regexp org-not-done-regexp
21011 'org-todo-regexp org-todo-regexp
21012 'keymap org-agenda-keymap
21013 'help-echo
21014 (format "mouse-2 or RET jump to org file %s"
21015 (abbreviate-file-name buffer-file-name))))
21016 (regexp org-deadline-time-regexp)
21017 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21018 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21019 d2 diff dfrac wdays pos pos1 category tags
21020 ee txt head face s upcomingp donep timestr)
21021 (goto-char (point-min))
21022 (while (re-search-forward regexp nil t)
21023 (catch :skip
21024 (org-agenda-skip)
21025 (setq s (match-string 1)
21026 pos (1- (match-beginning 1))
21027 d2 (org-time-string-to-absolute (match-string 1) d1)
21028 diff (- d2 d1)
21029 wdays (org-get-wdays s)
21030 dfrac (/ (* 1.0 (- wdays diff)) wdays)
21031 upcomingp (and todayp (> diff 0)))
21032 ;; When to show a deadline in the calendar:
21033 ;; If the expiration is within wdays warning time.
21034 ;; Past-due deadlines are only shown on the current date
21035 (if (or (and (<= diff wdays)
21036 (and todayp (not org-agenda-only-exact-dates)))
21037 (= diff 0))
21038 (save-excursion
21039 (setq category (org-get-category))
21040 (if (re-search-backward "^\\*+[ \t]+" nil t)
21041 (progn
21042 (goto-char (match-end 0))
21043 (setq pos1 (match-beginning 0))
21044 (setq tags (org-get-tags-at pos1))
21045 (setq head (buffer-substring-no-properties
21046 (point)
21047 (progn (skip-chars-forward "^\r\n")
21048 (point))))
21049 (setq donep (string-match org-looking-at-done-regexp head))
21050 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21051 (setq timestr
21052 (concat (substring s (match-beginning 1)) " "))
21053 (setq timestr 'time))
21054 (if (and donep
21055 (or org-agenda-skip-deadline-if-done
21056 (not (= diff 0))))
21057 (setq txt nil)
21058 (setq txt (org-format-agenda-item
21059 (if (= diff 0)
21060 (car org-agenda-deadline-leaders)
21061 (format (nth 1 org-agenda-deadline-leaders)
21062 diff))
21063 head category tags timestr))))
21064 (setq txt org-agenda-no-heading-message))
21065 (when txt
21066 (setq face (org-agenda-deadline-face dfrac))
21067 (org-add-props txt props
21068 'org-marker (org-agenda-new-marker pos)
21069 'org-hd-marker (org-agenda-new-marker pos1)
21070 'priority (+ (if upcomingp (floor (* dfrac 10.)) 100)
21071 (org-get-priority txt))
21072 'org-category category
21073 'type (if upcomingp "upcoming-deadline" "deadline")
21074 'date (if upcomingp date d2)
21075 'face (if donep 'org-done face)
21076 'undone-face face 'done-face 'org-done)
21077 (push txt ee))))))
21078 (nreverse ee)))
21080 (defun org-agenda-deadline-face (fraction)
21081 "Return the face to displaying a deadline item.
21082 FRACTION is what fraction of the head-warning time has passed."
21083 (let ((faces org-agenda-deadline-faces) f)
21084 (catch 'exit
21085 (while (setq f (pop faces))
21086 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
21088 (defun org-agenda-get-scheduled ()
21089 "Return the scheduled information for agenda display."
21090 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
21091 'org-todo-regexp org-todo-regexp
21092 'done-face 'org-done
21093 'mouse-face 'highlight
21094 'keymap org-agenda-keymap
21095 'help-echo
21096 (format "mouse-2 or RET jump to org file %s"
21097 (abbreviate-file-name buffer-file-name))))
21098 (regexp org-scheduled-time-regexp)
21099 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21100 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21101 d2 diff pos pos1 category tags
21102 ee txt head pastschedp donep face timestr s)
21103 (goto-char (point-min))
21104 (while (re-search-forward regexp nil t)
21105 (catch :skip
21106 (org-agenda-skip)
21107 (setq s (match-string 1)
21108 pos (1- (match-beginning 1))
21109 d2 (org-time-string-to-absolute (match-string 1) d1)
21110 diff (- d2 d1))
21111 (setq pastschedp (and todayp (< diff 0)))
21112 ;; When to show a scheduled item in the calendar:
21113 ;; If it is on or past the date.
21114 (if (or (and (< diff 0)
21115 (and todayp (not org-agenda-only-exact-dates)))
21116 (= diff 0))
21117 (save-excursion
21118 (setq category (org-get-category))
21119 (if (re-search-backward "^\\*+[ \t]+" nil t)
21120 (progn
21121 (goto-char (match-end 0))
21122 (setq pos1 (match-beginning 0))
21123 (setq tags (org-get-tags-at))
21124 (setq head (buffer-substring-no-properties
21125 (point)
21126 (progn (skip-chars-forward "^\r\n") (point))))
21127 (setq donep (string-match org-looking-at-done-regexp head))
21128 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21129 (setq timestr
21130 (concat (substring s (match-beginning 1)) " "))
21131 (setq timestr 'time))
21132 (if (and donep
21133 (or org-agenda-skip-scheduled-if-done
21134 (not (= diff 0))))
21135 (setq txt nil)
21136 (setq txt (org-format-agenda-item
21137 (if (= diff 0)
21138 (car org-agenda-scheduled-leaders)
21139 (format (nth 1 org-agenda-scheduled-leaders)
21140 (- 1 diff)))
21141 head category tags timestr))))
21142 (setq txt org-agenda-no-heading-message))
21143 (when txt
21144 (setq face (if pastschedp
21145 'org-scheduled-previously
21146 'org-scheduled-today))
21147 (org-add-props txt props
21148 'undone-face face
21149 'face (if donep 'org-done face)
21150 'org-marker (org-agenda-new-marker pos)
21151 'org-hd-marker (org-agenda-new-marker pos1)
21152 'type (if pastschedp "past-scheduled" "scheduled")
21153 'date (if pastschedp d2 date)
21154 'priority (+ 94 (- 5 diff) (org-get-priority txt))
21155 'org-category category)
21156 (push txt ee))))))
21157 (nreverse ee)))
21159 (defun org-agenda-get-blocks ()
21160 "Return the date-range information for agenda display."
21161 (let* ((props (list 'face nil
21162 'org-not-done-regexp org-not-done-regexp
21163 'org-todo-regexp org-todo-regexp
21164 'mouse-face 'highlight
21165 'keymap org-agenda-keymap
21166 'help-echo
21167 (format "mouse-2 or RET jump to org file %s"
21168 (abbreviate-file-name buffer-file-name))))
21169 (regexp org-tr-regexp)
21170 (d0 (calendar-absolute-from-gregorian date))
21171 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
21172 donep head)
21173 (goto-char (point-min))
21174 (while (re-search-forward regexp nil t)
21175 (catch :skip
21176 (org-agenda-skip)
21177 (setq pos (point))
21178 (setq timestr (match-string 0)
21179 s1 (match-string 1)
21180 s2 (match-string 2)
21181 d1 (time-to-days (org-time-string-to-time s1))
21182 d2 (time-to-days (org-time-string-to-time s2)))
21183 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
21184 ;; Only allow days between the limits, because the normal
21185 ;; date stamps will catch the limits.
21186 (save-excursion
21187 (setq marker (org-agenda-new-marker (point)))
21188 (setq category (org-get-category))
21189 (if (re-search-backward "^\\*+ " nil t)
21190 (progn
21191 (goto-char (match-beginning 0))
21192 (setq hdmarker (org-agenda-new-marker (point)))
21193 (setq tags (org-get-tags-at))
21194 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21195 (setq head (match-string 1))
21196 (and org-agenda-skip-timestamp-if-done
21197 (org-entry-is-done-p)
21198 (throw :skip t))
21199 (setq txt (org-format-agenda-item
21200 (format (if (= d1 d2) "" "(%d/%d): ")
21201 (1+ (- d0 d1)) (1+ (- d2 d1)))
21202 head category tags
21203 (if (= d0 d1) timestr))))
21204 (setq txt org-agenda-no-heading-message))
21205 (org-add-props txt props
21206 'org-marker marker 'org-hd-marker hdmarker
21207 'type "block" 'date date
21208 'priority (org-get-priority txt) 'org-category category)
21209 (push txt ee)))
21210 (goto-char pos)))
21211 ;; Sort the entries by expiration date.
21212 (nreverse ee)))
21214 ;;; Agenda presentation and sorting
21216 (defconst org-plain-time-of-day-regexp
21217 (concat
21218 "\\(\\<[012]?[0-9]"
21219 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21220 "\\(--?"
21221 "\\(\\<[012]?[0-9]"
21222 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21223 "\\)?")
21224 "Regular expression to match a plain time or time range.
21225 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
21226 groups carry important information:
21227 0 the full match
21228 1 the first time, range or not
21229 8 the second time, if it is a range.")
21231 (defconst org-plain-time-extension-regexp
21232 (concat
21233 "\\(\\<[012]?[0-9]"
21234 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21235 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
21236 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
21237 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
21238 groups carry important information:
21239 0 the full match
21240 7 hours of duration
21241 9 minutes of duration")
21243 (defconst org-stamp-time-of-day-regexp
21244 (concat
21245 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
21246 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
21247 "\\(--?"
21248 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
21249 "Regular expression to match a timestamp time or time range.
21250 After a match, the following groups carry important information:
21251 0 the full match
21252 1 date plus weekday, for backreferencing to make sure both times on same day
21253 2 the first time, range or not
21254 4 the second time, if it is a range.")
21256 (defvar org-prefix-has-time nil
21257 "A flag, set by `org-compile-prefix-format'.
21258 The flag is set if the currently compiled format contains a `%t'.")
21259 (defvar org-prefix-has-tag nil
21260 "A flag, set by `org-compile-prefix-format'.
21261 The flag is set if the currently compiled format contains a `%T'.")
21263 (defun org-format-agenda-item (extra txt &optional category tags dotime
21264 noprefix remove-re)
21265 "Format TXT to be inserted into the agenda buffer.
21266 In particular, it adds the prefix and corresponding text properties. EXTRA
21267 must be a string and replaces the `%s' specifier in the prefix format.
21268 CATEGORY (string, symbol or nil) may be used to overrule the default
21269 category taken from local variable or file name. It will replace the `%c'
21270 specifier in the format. DOTIME, when non-nil, indicates that a
21271 time-of-day should be extracted from TXT for sorting of this entry, and for
21272 the `%t' specifier in the format. When DOTIME is a string, this string is
21273 searched for a time before TXT is. NOPREFIX is a flag and indicates that
21274 only the correctly processes TXT should be returned - this is used by
21275 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
21276 Any match of REMOVE-RE will be removed from TXT."
21277 (save-match-data
21278 ;; Diary entries sometimes have extra whitespace at the beginning
21279 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
21280 (let* ((category (or category
21281 org-category
21282 (if buffer-file-name
21283 (file-name-sans-extension
21284 (file-name-nondirectory buffer-file-name))
21285 "")))
21286 (tag (if tags (nth (1- (length tags)) tags) ""))
21287 time ; time and tag are needed for the eval of the prefix format
21288 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
21289 (time-of-day (and dotime (org-get-time-of-day ts)))
21290 stamp plain s0 s1 s2 rtn srp)
21291 (when (and dotime time-of-day org-prefix-has-time)
21292 ;; Extract starting and ending time and move them to prefix
21293 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
21294 (setq plain (string-match org-plain-time-of-day-regexp ts)))
21295 (setq s0 (match-string 0 ts)
21296 srp (and stamp (match-end 3))
21297 s1 (match-string (if plain 1 2) ts)
21298 s2 (match-string (if plain 8 (if srp 4 6)) ts))
21300 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
21301 ;; them, we might want to remove them there to avoid duplication.
21302 ;; The user can turn this off with a variable.
21303 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
21304 (string-match (concat (regexp-quote s0) " *") txt)
21305 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
21306 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
21307 (= (match-beginning 0) 0)
21309 (setq txt (replace-match "" nil nil txt))))
21310 ;; Normalize the time(s) to 24 hour
21311 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
21312 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
21314 (when (and s1 (not s2) org-agenda-default-appointment-duration
21315 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
21316 (let ((m (+ (string-to-number (match-string 2 s1))
21317 (* 60 (string-to-number (match-string 1 s1)))
21318 org-agenda-default-appointment-duration))
21320 (setq h (/ m 60) m (- m (* h 60)))
21321 (setq s2 (format "%02d:%02d" h m))))
21323 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
21324 txt)
21325 ;; Tags are in the string
21326 (if (or (eq org-agenda-remove-tags t)
21327 (and org-agenda-remove-tags
21328 org-prefix-has-tag))
21329 (setq txt (replace-match "" t t txt))
21330 (setq txt (replace-match
21331 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
21332 (match-string 2 txt))
21333 t t txt))))
21335 (when remove-re
21336 (while (string-match remove-re txt)
21337 (setq txt (replace-match "" t t txt))))
21339 ;; Create the final string
21340 (if noprefix
21341 (setq rtn txt)
21342 ;; Prepare the variables needed in the eval of the compiled format
21343 (setq time (cond (s2 (concat s1 "-" s2))
21344 (s1 (concat s1 "......"))
21345 (t ""))
21346 extra (or extra "")
21347 category (if (symbolp category) (symbol-name category) category))
21348 ;; Evaluate the compiled format
21349 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
21351 ;; And finally add the text properties
21352 (org-add-props rtn nil
21353 'org-category (downcase category) 'tags tags
21354 'org-highest-priority org-highest-priority
21355 'org-lowest-priority org-lowest-priority
21356 'prefix-length (- (length rtn) (length txt))
21357 'time-of-day time-of-day
21358 'txt txt
21359 'time time
21360 'extra extra
21361 'dotime dotime))))
21363 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
21364 (defvar org-agenda-sorting-strategy-selected nil)
21366 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
21367 (catch 'exit
21368 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
21369 ((and todayp (member 'today (car org-agenda-time-grid))))
21370 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
21371 ((member 'weekly (car org-agenda-time-grid)))
21372 (t (throw 'exit list)))
21373 (let* ((have (delq nil (mapcar
21374 (lambda (x) (get-text-property 1 'time-of-day x))
21375 list)))
21376 (string (nth 1 org-agenda-time-grid))
21377 (gridtimes (nth 2 org-agenda-time-grid))
21378 (req (car org-agenda-time-grid))
21379 (remove (member 'remove-match req))
21380 new time)
21381 (if (and (member 'require-timed req) (not have))
21382 ;; don't show empty grid
21383 (throw 'exit list))
21384 (while (setq time (pop gridtimes))
21385 (unless (and remove (member time have))
21386 (setq time (int-to-string time))
21387 (push (org-format-agenda-item
21388 nil string "" nil
21389 (concat (substring time 0 -2) ":" (substring time -2)))
21390 new)
21391 (put-text-property
21392 1 (length (car new)) 'face 'org-time-grid (car new))))
21393 (if (member 'time-up org-agenda-sorting-strategy-selected)
21394 (append new list)
21395 (append list new)))))
21397 (defun org-compile-prefix-format (key)
21398 "Compile the prefix format into a Lisp form that can be evaluated.
21399 The resulting form is returned and stored in the variable
21400 `org-prefix-format-compiled'."
21401 (setq org-prefix-has-time nil org-prefix-has-tag nil)
21402 (let ((s (cond
21403 ((stringp org-agenda-prefix-format)
21404 org-agenda-prefix-format)
21405 ((assq key org-agenda-prefix-format)
21406 (cdr (assq key org-agenda-prefix-format)))
21407 (t " %-12:c%?-12t% s")))
21408 (start 0)
21409 varform vars var e c f opt)
21410 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
21411 s start)
21412 (setq var (cdr (assoc (match-string 4 s)
21413 '(("c" . category) ("t" . time) ("s" . extra)
21414 ("T" . tag))))
21415 c (or (match-string 3 s) "")
21416 opt (match-beginning 1)
21417 start (1+ (match-beginning 0)))
21418 (if (equal var 'time) (setq org-prefix-has-time t))
21419 (if (equal var 'tag) (setq org-prefix-has-tag t))
21420 (setq f (concat "%" (match-string 2 s) "s"))
21421 (if opt
21422 (setq varform
21423 `(if (equal "" ,var)
21425 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
21426 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
21427 (setq s (replace-match "%s" t nil s))
21428 (push varform vars))
21429 (setq vars (nreverse vars))
21430 (setq org-prefix-format-compiled `(format ,s ,@vars))))
21432 (defun org-set-sorting-strategy (key)
21433 (if (symbolp (car org-agenda-sorting-strategy))
21434 ;; the old format
21435 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
21436 (setq org-agenda-sorting-strategy-selected
21437 (or (cdr (assq key org-agenda-sorting-strategy))
21438 (cdr (assq 'agenda org-agenda-sorting-strategy))
21439 '(time-up category-keep priority-down)))))
21441 (defun org-get-time-of-day (s &optional string mod24)
21442 "Check string S for a time of day.
21443 If found, return it as a military time number between 0 and 2400.
21444 If not found, return nil.
21445 The optional STRING argument forces conversion into a 5 character wide string
21446 HH:MM."
21447 (save-match-data
21448 (when
21449 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
21450 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
21451 (let* ((h (string-to-number (match-string 1 s)))
21452 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
21453 (ampm (if (match-end 4) (downcase (match-string 4 s))))
21454 (am-p (equal ampm "am"))
21455 (h1 (cond ((not ampm) h)
21456 ((= h 12) (if am-p 0 12))
21457 (t (+ h (if am-p 0 12)))))
21458 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
21459 (mod h1 24) h1))
21460 (t0 (+ (* 100 h2) m))
21461 (t1 (concat (if (>= h1 24) "+" " ")
21462 (if (< t0 100) "0" "")
21463 (if (< t0 10) "0" "")
21464 (int-to-string t0))))
21465 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
21467 (defun org-finalize-agenda-entries (list &optional nosort)
21468 "Sort and concatenate the agenda items."
21469 (setq list (mapcar 'org-agenda-highlight-todo list))
21470 (if nosort
21471 list
21472 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
21474 (defun org-agenda-highlight-todo (x)
21475 (let (re pl)
21476 (if (eq x 'line)
21477 (save-excursion
21478 (beginning-of-line 1)
21479 (setq re (get-text-property (point) 'org-todo-regexp))
21480 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
21481 (and (looking-at (concat "[ \t]*\\.*" re))
21482 (add-text-properties (match-beginning 0) (match-end 0)
21483 (list 'face (org-get-todo-face 0)))))
21484 (setq re (concat (get-text-property 0 'org-todo-regexp x))
21485 pl (get-text-property 0 'prefix-length x))
21486 (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
21487 (add-text-properties
21488 (or (match-end 1) (match-end 0)) (match-end 0)
21489 (list 'face (org-get-todo-face (match-string 2 x)))
21491 x)))
21493 (defsubst org-cmp-priority (a b)
21494 "Compare the priorities of string A and B."
21495 (let ((pa (or (get-text-property 1 'priority a) 0))
21496 (pb (or (get-text-property 1 'priority b) 0)))
21497 (cond ((> pa pb) +1)
21498 ((< pa pb) -1)
21499 (t nil))))
21501 (defsubst org-cmp-category (a b)
21502 "Compare the string values of categories of strings A and B."
21503 (let ((ca (or (get-text-property 1 'org-category a) ""))
21504 (cb (or (get-text-property 1 'org-category b) "")))
21505 (cond ((string-lessp ca cb) -1)
21506 ((string-lessp cb ca) +1)
21507 (t nil))))
21509 (defsubst org-cmp-tag (a b)
21510 "Compare the string values of categories of strings A and B."
21511 (let ((ta (car (last (get-text-property 1 'tags a))))
21512 (tb (car (last (get-text-property 1 'tags b)))))
21513 (cond ((not ta) +1)
21514 ((not tb) -1)
21515 ((string-lessp ta tb) -1)
21516 ((string-lessp tb ta) +1)
21517 (t nil))))
21519 (defsubst org-cmp-time (a b)
21520 "Compare the time-of-day values of strings A and B."
21521 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
21522 (ta (or (get-text-property 1 'time-of-day a) def))
21523 (tb (or (get-text-property 1 'time-of-day b) def)))
21524 (cond ((< ta tb) -1)
21525 ((< tb ta) +1)
21526 (t nil))))
21528 (defun org-entries-lessp (a b)
21529 "Predicate for sorting agenda entries."
21530 ;; The following variables will be used when the form is evaluated.
21531 ;; So even though the compiler complains, keep them.
21532 (let* ((time-up (org-cmp-time a b))
21533 (time-down (if time-up (- time-up) nil))
21534 (priority-up (org-cmp-priority a b))
21535 (priority-down (if priority-up (- priority-up) nil))
21536 (category-up (org-cmp-category a b))
21537 (category-down (if category-up (- category-up) nil))
21538 (category-keep (if category-up +1 nil))
21539 (tag-up (org-cmp-tag a b))
21540 (tag-down (if tag-up (- tag-up) nil)))
21541 (cdr (assoc
21542 (eval (cons 'or org-agenda-sorting-strategy-selected))
21543 '((-1 . t) (1 . nil) (nil . nil))))))
21545 ;;; Agenda restriction lock
21547 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
21548 "Overlay to mark the headline to which arenda commands are restricted.")
21549 (org-overlay-put org-agenda-restriction-lock-overlay
21550 'face 'org-agenda-restriction-lock)
21551 (org-overlay-put org-agenda-restriction-lock-overlay
21552 'help-echo "Agendas are currently limited to this subtree.")
21553 (org-detach-overlay org-agenda-restriction-lock-overlay)
21554 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
21555 "Overlay marking the agenda restriction line in speedbar.")
21556 (org-overlay-put org-speedbar-restriction-lock-overlay
21557 'face 'org-agenda-restriction-lock)
21558 (org-overlay-put org-speedbar-restriction-lock-overlay
21559 'help-echo "Agendas are currently limited to this item.")
21560 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21562 (defun org-agenda-set-restriction-lock (&optional type)
21563 "Set restriction lock for agenda, to current subtree or file.
21564 Restriction will be the file if TYPE is `file', or if type is the
21565 universal prefix '(4), or if the cursor is before the first headline
21566 in the file. Otherwise, restriction will be to the current subtree."
21567 (interactive "P")
21568 (and (equal type '(4)) (setq type 'file))
21569 (setq type (cond
21570 (type type)
21571 ((org-at-heading-p) 'subtree)
21572 ((condition-case nil (org-back-to-heading t) (error nil))
21573 'subtree)
21574 (t 'file)))
21575 (if (eq type 'subtree)
21576 (progn
21577 (setq org-agenda-restrict t)
21578 (setq org-agenda-overriding-restriction 'subtree)
21579 (put 'org-agenda-files 'org-restrict
21580 (list (buffer-file-name (buffer-base-buffer))))
21581 (org-back-to-heading t)
21582 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
21583 (move-marker org-agenda-restrict-begin (point))
21584 (move-marker org-agenda-restrict-end
21585 (save-excursion (org-end-of-subtree t)))
21586 (message "Locking agenda restriction to subtree"))
21587 (put 'org-agenda-files 'org-restrict
21588 (list (buffer-file-name (buffer-base-buffer))))
21589 (setq org-agenda-restrict nil)
21590 (setq org-agenda-overriding-restriction 'file)
21591 (move-marker org-agenda-restrict-begin nil)
21592 (move-marker org-agenda-restrict-end nil)
21593 (message "Locking agenda restriction to file"))
21594 (setq current-prefix-arg nil)
21595 (org-agenda-maybe-redo))
21597 (defun org-agenda-remove-restriction-lock (&optional noupdate)
21598 "Remove the agenda restriction lock."
21599 (interactive "P")
21600 (org-detach-overlay org-agenda-restriction-lock-overlay)
21601 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21602 (setq org-agenda-overriding-restriction nil)
21603 (setq org-agenda-restrict nil)
21604 (put 'org-agenda-files 'org-restrict nil)
21605 (move-marker org-agenda-restrict-begin nil)
21606 (move-marker org-agenda-restrict-end nil)
21607 (setq current-prefix-arg nil)
21608 (message "Agenda restriction lock removed")
21609 (or noupdate (org-agenda-maybe-redo)))
21611 (defun org-agenda-maybe-redo ()
21612 "If there is any window showing the agenda view, update it."
21613 (let ((w (get-buffer-window org-agenda-buffer-name t))
21614 (w0 (selected-window)))
21615 (when w
21616 (select-window w)
21617 (org-agenda-redo)
21618 (select-window w0)
21619 (if org-agenda-overriding-restriction
21620 (message "Agenda view shifted to new %s restriction"
21621 org-agenda-overriding-restriction)
21622 (message "Agenda restriction lock removed")))))
21624 ;;; Agenda commands
21626 (defun org-agenda-check-type (error &rest types)
21627 "Check if agenda buffer is of allowed type.
21628 If ERROR is non-nil, throw an error, otherwise just return nil."
21629 (if (memq org-agenda-type types)
21631 (if error
21632 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
21633 nil)))
21635 (defun org-agenda-quit ()
21636 "Exit agenda by removing the window or the buffer."
21637 (interactive)
21638 (let ((buf (current-buffer)))
21639 (if (not (one-window-p)) (delete-window))
21640 (kill-buffer buf)
21641 (org-agenda-maybe-reset-markers 'force)
21642 (org-columns-remove-overlays))
21643 ;; Maybe restore the pre-agenda window configuration.
21644 (and org-agenda-restore-windows-after-quit
21645 (not (eq org-agenda-window-setup 'other-frame))
21646 org-pre-agenda-window-conf
21647 (set-window-configuration org-pre-agenda-window-conf)))
21649 (defun org-agenda-exit ()
21650 "Exit agenda by removing the window or the buffer.
21651 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
21652 Org-mode buffers visited directly by the user will not be touched."
21653 (interactive)
21654 (org-release-buffers org-agenda-new-buffers)
21655 (setq org-agenda-new-buffers nil)
21656 (org-agenda-quit))
21658 (defun org-agenda-execute (arg)
21659 "Execute another agenda command, keeping same window.\\<global-map>
21660 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
21661 (interactive "P")
21662 (let ((org-agenda-window-setup 'current-window))
21663 (org-agenda arg)))
21665 (defun org-save-all-org-buffers ()
21666 "Save all Org-mode buffers without user confirmation."
21667 (interactive)
21668 (message "Saving all Org-mode buffers...")
21669 (save-some-buffers t 'org-mode-p)
21670 (message "Saving all Org-mode buffers... done"))
21672 (defun org-agenda-redo ()
21673 "Rebuild Agenda.
21674 When this is the global TODO list, a prefix argument will be interpreted."
21675 (interactive)
21676 (let* ((org-agenda-keep-modes t)
21677 (line (org-current-line))
21678 (window-line (- line (org-current-line (window-start))))
21679 (lprops (get 'org-agenda-redo-command 'org-lprops)))
21680 (message "Rebuilding agenda buffer...")
21681 (org-let lprops '(eval org-agenda-redo-command))
21682 (setq org-agenda-undo-list nil
21683 org-agenda-pending-undo-list nil)
21684 (message "Rebuilding agenda buffer...done")
21685 (goto-line line)
21686 (recenter window-line)))
21688 (defun org-agenda-goto-date (date)
21689 "Jump to DATE in agenda."
21690 (interactive (list (org-read-date)))
21691 (org-agenda-list nil date))
21693 (defun org-agenda-goto-today ()
21694 "Go to today."
21695 (interactive)
21696 (org-agenda-check-type t 'timeline 'agenda)
21697 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
21698 (cond
21699 (tdpos (goto-char tdpos))
21700 ((eq org-agenda-type 'agenda)
21701 (let* ((sd (time-to-days
21702 (time-subtract (current-time)
21703 (list 0 (* 3600 org-extend-today-until) 0))))
21704 (comp (org-agenda-compute-time-span sd org-agenda-span))
21705 (org-agenda-overriding-arguments org-agenda-last-arguments))
21706 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
21707 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
21708 (org-agenda-redo)
21709 (org-agenda-find-same-or-today-or-agenda)))
21710 (t (error "Cannot find today")))))
21712 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
21713 (goto-char
21714 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
21715 (text-property-any (point-min) (point-max) 'org-today t)
21716 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
21717 (point-min))))
21719 (defun org-agenda-later (arg)
21720 "Go forward in time by thee current span.
21721 With prefix ARG, go forward that many times the current span."
21722 (interactive "p")
21723 (org-agenda-check-type t 'agenda)
21724 (let* ((span org-agenda-span)
21725 (sd org-starting-day)
21726 (greg (calendar-gregorian-from-absolute sd))
21727 (cnt (get-text-property (point) 'org-day-cnt))
21728 greg2 nd)
21729 (cond
21730 ((eq span 'day)
21731 (setq sd (+ arg sd) nd 1))
21732 ((eq span 'week)
21733 (setq sd (+ (* 7 arg) sd) nd 7))
21734 ((eq span 'month)
21735 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
21736 sd (calendar-absolute-from-gregorian greg2))
21737 (setcar greg2 (1+ (car greg2)))
21738 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
21739 ((eq span 'year)
21740 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
21741 sd (calendar-absolute-from-gregorian greg2))
21742 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
21743 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
21744 (let ((org-agenda-overriding-arguments
21745 (list (car org-agenda-last-arguments) sd nd t)))
21746 (org-agenda-redo)
21747 (org-agenda-find-same-or-today-or-agenda cnt))))
21749 (defun org-agenda-earlier (arg)
21750 "Go backward in time by the current span.
21751 With prefix ARG, go backward that many times the current span."
21752 (interactive "p")
21753 (org-agenda-later (- arg)))
21755 (defun org-agenda-day-view ()
21756 "Switch to daily view for agenda."
21757 (interactive)
21758 (setq org-agenda-ndays 1)
21759 (org-agenda-change-time-span 'day))
21760 (defun org-agenda-week-view ()
21761 "Switch to daily view for agenda."
21762 (interactive)
21763 (setq org-agenda-ndays 7)
21764 (org-agenda-change-time-span 'week))
21765 (defun org-agenda-month-view ()
21766 "Switch to daily view for agenda."
21767 (interactive)
21768 (org-agenda-change-time-span 'month))
21769 (defun org-agenda-year-view ()
21770 "Switch to daily view for agenda."
21771 (interactive)
21772 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
21773 (org-agenda-change-time-span 'year)
21774 (error "Abort")))
21776 (defun org-agenda-change-time-span (span)
21777 "Change the agenda view to SPAN.
21778 SPAN may be `day', `week', `month', `year'."
21779 (org-agenda-check-type t 'agenda)
21780 (if (equal org-agenda-span span)
21781 (error "Viewing span is already \"%s\"" span))
21782 (let* ((sd (or (get-text-property (point) 'day)
21783 org-starting-day))
21784 (computed (org-agenda-compute-time-span sd span))
21785 (org-agenda-overriding-arguments
21786 (list (car org-agenda-last-arguments)
21787 (car computed) (cdr computed) t)))
21788 (org-agenda-redo)
21789 (org-agenda-find-same-or-today-or-agenda))
21790 (org-agenda-set-mode-name)
21791 (message "Switched to %s view" span))
21793 (defun org-agenda-compute-time-span (sd span)
21794 "Compute starting date and number of days for agenda.
21795 SPAN may be `day', `week', `month', `year'. The return value
21796 is a cons cell with the starting date and the number of days,
21797 so that the date SD will be in that range."
21798 (let* ((greg (calendar-gregorian-from-absolute sd))
21800 (cond
21801 ((eq span 'day)
21802 (setq nd 1))
21803 ((eq span 'week)
21804 (let* ((nt (calendar-day-of-week
21805 (calendar-gregorian-from-absolute sd)))
21806 (d (if org-agenda-start-on-weekday
21807 (- nt org-agenda-start-on-weekday)
21808 0)))
21809 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
21810 (setq nd 7)))
21811 ((eq span 'month)
21812 (setq sd (calendar-absolute-from-gregorian
21813 (list (car greg) 1 (nth 2 greg)))
21814 nd (- (calendar-absolute-from-gregorian
21815 (list (1+ (car greg)) 1 (nth 2 greg)))
21816 sd)))
21817 ((eq span 'year)
21818 (setq sd (calendar-absolute-from-gregorian
21819 (list 1 1 (nth 2 greg)))
21820 nd (- (calendar-absolute-from-gregorian
21821 (list 1 1 (1+ (nth 2 greg))))
21822 sd))))
21823 (cons sd nd)))
21825 ;; FIXME: does not work if user makes date format that starts with a blank
21826 (defun org-agenda-next-date-line (&optional arg)
21827 "Jump to the next line indicating a date in agenda buffer."
21828 (interactive "p")
21829 (org-agenda-check-type t 'agenda 'timeline)
21830 (beginning-of-line 1)
21831 (if (looking-at "^\\S-") (forward-char 1))
21832 (if (not (re-search-forward "^\\S-" nil t arg))
21833 (progn
21834 (backward-char 1)
21835 (error "No next date after this line in this buffer")))
21836 (goto-char (match-beginning 0)))
21838 (defun org-agenda-previous-date-line (&optional arg)
21839 "Jump to the previous line indicating a date in agenda buffer."
21840 (interactive "p")
21841 (org-agenda-check-type t 'agenda 'timeline)
21842 (beginning-of-line 1)
21843 (if (not (re-search-backward "^\\S-" nil t arg))
21844 (error "No previous date before this line in this buffer")))
21846 ;; Initialize the highlight
21847 (defvar org-hl (org-make-overlay 1 1))
21848 (org-overlay-put org-hl 'face 'highlight)
21850 (defun org-highlight (begin end &optional buffer)
21851 "Highlight a region with overlay."
21852 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
21853 org-hl begin end (or buffer (current-buffer))))
21855 (defun org-unhighlight ()
21856 "Detach overlay INDEX."
21857 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
21859 ;; FIXME this is currently not used.
21860 (defun org-highlight-until-next-command (beg end &optional buffer)
21861 (org-highlight beg end buffer)
21862 (add-hook 'pre-command-hook 'org-unhighlight-once))
21863 (defun org-unhighlight-once ()
21864 (remove-hook 'pre-command-hook 'org-unhighlight-once)
21865 (org-unhighlight))
21867 (defun org-agenda-follow-mode ()
21868 "Toggle follow mode in an agenda buffer."
21869 (interactive)
21870 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
21871 (org-agenda-set-mode-name)
21872 (message "Follow mode is %s"
21873 (if org-agenda-follow-mode "on" "off")))
21875 (defun org-agenda-log-mode ()
21876 "Toggle log mode in an agenda buffer."
21877 (interactive)
21878 (org-agenda-check-type t 'agenda 'timeline)
21879 (setq org-agenda-show-log (not org-agenda-show-log))
21880 (org-agenda-set-mode-name)
21881 (org-agenda-redo)
21882 (message "Log mode is %s"
21883 (if org-agenda-show-log "on" "off")))
21885 (defun org-agenda-toggle-diary ()
21886 "Toggle diary inclusion in an agenda buffer."
21887 (interactive)
21888 (org-agenda-check-type t 'agenda)
21889 (setq org-agenda-include-diary (not org-agenda-include-diary))
21890 (org-agenda-redo)
21891 (org-agenda-set-mode-name)
21892 (message "Diary inclusion turned %s"
21893 (if org-agenda-include-diary "on" "off")))
21895 (defun org-agenda-toggle-time-grid ()
21896 "Toggle time grid in an agenda buffer."
21897 (interactive)
21898 (org-agenda-check-type t 'agenda)
21899 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
21900 (org-agenda-redo)
21901 (org-agenda-set-mode-name)
21902 (message "Time-grid turned %s"
21903 (if org-agenda-use-time-grid "on" "off")))
21905 (defun org-agenda-set-mode-name ()
21906 "Set the mode name to indicate all the small mode settings."
21907 (setq mode-name
21908 (concat "Org-Agenda"
21909 (if (equal org-agenda-ndays 1) " Day" "")
21910 (if (equal org-agenda-ndays 7) " Week" "")
21911 (if org-agenda-follow-mode " Follow" "")
21912 (if org-agenda-include-diary " Diary" "")
21913 (if org-agenda-use-time-grid " Grid" "")
21914 (if org-agenda-show-log " Log" "")))
21915 (force-mode-line-update))
21917 (defun org-agenda-post-command-hook ()
21918 (and (eolp) (not (bolp)) (backward-char 1))
21919 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
21920 (if (and org-agenda-follow-mode
21921 (get-text-property (point) 'org-marker))
21922 (org-agenda-show)))
21924 (defun org-agenda-show-priority ()
21925 "Show the priority of the current item.
21926 This priority is composed of the main priority given with the [#A] cookies,
21927 and by additional input from the age of a schedules or deadline entry."
21928 (interactive)
21929 (let* ((pri (get-text-property (point-at-bol) 'priority)))
21930 (message "Priority is %d" (if pri pri -1000))))
21932 (defun org-agenda-show-tags ()
21933 "Show the tags applicable to the current item."
21934 (interactive)
21935 (let* ((tags (get-text-property (point-at-bol) 'tags)))
21936 (if tags
21937 (message "Tags are :%s:"
21938 (org-no-properties (mapconcat 'identity tags ":")))
21939 (message "No tags associated with this line"))))
21941 (defun org-agenda-goto (&optional highlight)
21942 "Go to the Org-mode file which contains the item at point."
21943 (interactive)
21944 (let* ((marker (or (get-text-property (point) 'org-marker)
21945 (org-agenda-error)))
21946 (buffer (marker-buffer marker))
21947 (pos (marker-position marker)))
21948 (switch-to-buffer-other-window buffer)
21949 (widen)
21950 (goto-char pos)
21951 (when (org-mode-p)
21952 (org-show-context 'agenda)
21953 (save-excursion
21954 (and (outline-next-heading)
21955 (org-flag-heading nil)))) ; show the next heading
21956 (run-hooks 'org-agenda-after-show-hook)
21957 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
21959 (defvar org-agenda-after-show-hook nil
21960 "Normal hook run after an item has been shown from the agenda.
21961 Point is in the buffer where the item originated.")
21963 (defun org-agenda-kill ()
21964 "Kill the entry or subtree belonging to the current agenda entry."
21965 (interactive)
21966 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
21967 (let* ((marker (or (get-text-property (point) 'org-marker)
21968 (org-agenda-error)))
21969 (buffer (marker-buffer marker))
21970 (pos (marker-position marker))
21971 (type (get-text-property (point) 'type))
21972 dbeg dend (n 0) conf)
21973 (org-with-remote-undo buffer
21974 (with-current-buffer buffer
21975 (save-excursion
21976 (goto-char pos)
21977 (if (and (org-mode-p) (not (member type '("sexp"))))
21978 (setq dbeg (progn (org-back-to-heading t) (point))
21979 dend (org-end-of-subtree t t))
21980 (setq dbeg (point-at-bol)
21981 dend (min (point-max) (1+ (point-at-eol)))))
21982 (goto-char dbeg)
21983 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
21984 (setq conf (or (eq t org-agenda-confirm-kill)
21985 (and (numberp org-agenda-confirm-kill)
21986 (> n org-agenda-confirm-kill))))
21987 (and conf
21988 (not (y-or-n-p
21989 (format "Delete entry with %d lines in buffer \"%s\"? "
21990 n (buffer-name buffer))))
21991 (error "Abort"))
21992 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
21993 (with-current-buffer buffer (delete-region dbeg dend))
21994 (message "Agenda item and source killed"))))
21996 (defun org-agenda-archive ()
21997 "Kill the entry or subtree belonging to the current agenda entry."
21998 (interactive)
21999 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22000 (let* ((marker (or (get-text-property (point) 'org-marker)
22001 (org-agenda-error)))
22002 (buffer (marker-buffer marker))
22003 (pos (marker-position marker)))
22004 (org-with-remote-undo buffer
22005 (with-current-buffer buffer
22006 (if (org-mode-p)
22007 (save-excursion
22008 (goto-char pos)
22009 (org-remove-subtree-entries-from-agenda)
22010 (org-back-to-heading t)
22011 (org-archive-subtree))
22012 (error "Archiving works only in Org-mode files"))))))
22014 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
22015 "Remove all lines in the agenda that correspond to a given subtree.
22016 The subtree is the one in buffer BUF, starting at BEG and ending at END.
22017 If this information is not given, the function uses the tree at point."
22018 (let ((buf (or buf (current-buffer))) m p)
22019 (save-excursion
22020 (unless (and beg end)
22021 (org-back-to-heading t)
22022 (setq beg (point))
22023 (org-end-of-subtree t)
22024 (setq end (point)))
22025 (set-buffer (get-buffer org-agenda-buffer-name))
22026 (save-excursion
22027 (goto-char (point-max))
22028 (beginning-of-line 1)
22029 (while (not (bobp))
22030 (when (and (setq m (get-text-property (point) 'org-marker))
22031 (equal buf (marker-buffer m))
22032 (setq p (marker-position m))
22033 (>= p beg)
22034 (<= p end))
22035 (let ((inhibit-read-only t))
22036 (delete-region (point-at-bol) (1+ (point-at-eol)))))
22037 (beginning-of-line 0))))))
22039 (defun org-agenda-open-link ()
22040 "Follow the link in the current line, if any."
22041 (interactive)
22042 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
22043 (save-excursion
22044 (save-restriction
22045 (narrow-to-region (point-at-bol) (point-at-eol))
22046 (org-open-at-point))))
22048 (defun org-agenda-copy-local-variable (var)
22049 "Get a variable from a referenced buffer and install it here."
22050 (let ((m (get-text-property (point) 'org-marker)))
22051 (when (and m (buffer-live-p (marker-buffer m)))
22052 (org-set-local var (with-current-buffer (marker-buffer m)
22053 (symbol-value var))))))
22055 (defun org-agenda-switch-to (&optional delete-other-windows)
22056 "Go to the Org-mode file which contains the item at point."
22057 (interactive)
22058 (let* ((marker (or (get-text-property (point) 'org-marker)
22059 (org-agenda-error)))
22060 (buffer (marker-buffer marker))
22061 (pos (marker-position marker)))
22062 (switch-to-buffer buffer)
22063 (and delete-other-windows (delete-other-windows))
22064 (widen)
22065 (goto-char pos)
22066 (when (org-mode-p)
22067 (org-show-context 'agenda)
22068 (save-excursion
22069 (and (outline-next-heading)
22070 (org-flag-heading nil)))))) ; show the next heading
22072 (defun org-agenda-goto-mouse (ev)
22073 "Go to the Org-mode file which contains the item at the mouse click."
22074 (interactive "e")
22075 (mouse-set-point ev)
22076 (org-agenda-goto))
22078 (defun org-agenda-show ()
22079 "Display the Org-mode file which contains the item at point."
22080 (interactive)
22081 (let ((win (selected-window)))
22082 (org-agenda-goto t)
22083 (select-window win)))
22085 (defun org-agenda-recenter (arg)
22086 "Display the Org-mode file which contains the item at point and recenter."
22087 (interactive "P")
22088 (let ((win (selected-window)))
22089 (org-agenda-goto t)
22090 (recenter arg)
22091 (select-window win)))
22093 (defun org-agenda-show-mouse (ev)
22094 "Display the Org-mode file which contains the item at the mouse click."
22095 (interactive "e")
22096 (mouse-set-point ev)
22097 (org-agenda-show))
22099 (defun org-agenda-check-no-diary ()
22100 "Check if the entry is a diary link and abort if yes."
22101 (if (get-text-property (point) 'org-agenda-diary-link)
22102 (org-agenda-error)))
22104 (defun org-agenda-error ()
22105 (error "Command not allowed in this line"))
22107 (defun org-agenda-tree-to-indirect-buffer ()
22108 "Show the subtree corresponding to the current entry in an indirect buffer.
22109 This calls the command `org-tree-to-indirect-buffer' from the original
22110 Org-mode buffer.
22111 With numerical prefix arg ARG, go up to this level and then take that tree.
22112 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
22113 dedicated frame)."
22114 (interactive)
22115 (org-agenda-check-no-diary)
22116 (let* ((marker (or (get-text-property (point) 'org-marker)
22117 (org-agenda-error)))
22118 (buffer (marker-buffer marker))
22119 (pos (marker-position marker)))
22120 (with-current-buffer buffer
22121 (save-excursion
22122 (goto-char pos)
22123 (call-interactively 'org-tree-to-indirect-buffer)))))
22125 (defvar org-last-heading-marker (make-marker)
22126 "Marker pointing to the headline that last changed its TODO state
22127 by a remote command from the agenda.")
22129 (defun org-agenda-todo-nextset ()
22130 "Switch TODO entry to next sequence."
22131 (interactive)
22132 (org-agenda-todo 'nextset))
22134 (defun org-agenda-todo-previousset ()
22135 "Switch TODO entry to previous sequence."
22136 (interactive)
22137 (org-agenda-todo 'previousset))
22139 (defun org-agenda-todo (&optional arg)
22140 "Cycle TODO state of line at point, also in Org-mode file.
22141 This changes the line at point, all other lines in the agenda referring to
22142 the same tree node, and the headline of the tree node in the Org-mode file."
22143 (interactive "P")
22144 (org-agenda-check-no-diary)
22145 (let* ((col (current-column))
22146 (marker (or (get-text-property (point) 'org-marker)
22147 (org-agenda-error)))
22148 (buffer (marker-buffer marker))
22149 (pos (marker-position marker))
22150 (hdmarker (get-text-property (point) 'org-hd-marker))
22151 (inhibit-read-only t)
22152 newhead)
22153 (org-with-remote-undo buffer
22154 (with-current-buffer buffer
22155 (widen)
22156 (goto-char pos)
22157 (org-show-context 'agenda)
22158 (save-excursion
22159 (and (outline-next-heading)
22160 (org-flag-heading nil))) ; show the next heading
22161 (org-todo arg)
22162 (and (bolp) (forward-char 1))
22163 (setq newhead (org-get-heading))
22164 (save-excursion
22165 (org-back-to-heading)
22166 (move-marker org-last-heading-marker (point))))
22167 (beginning-of-line 1)
22168 (save-excursion
22169 (org-agenda-change-all-lines newhead hdmarker 'fixface))
22170 (move-to-column col))))
22172 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
22173 "Change all lines in the agenda buffer which match HDMARKER.
22174 The new content of the line will be NEWHEAD (as modified by
22175 `org-format-agenda-item'). HDMARKER is checked with
22176 `equal' against all `org-hd-marker' text properties in the file.
22177 If FIXFACE is non-nil, the face of each item is modified acording to
22178 the new TODO state."
22179 (let* ((inhibit-read-only t)
22180 props m pl undone-face done-face finish new dotime cat tags)
22181 (save-excursion
22182 (goto-char (point-max))
22183 (beginning-of-line 1)
22184 (while (not finish)
22185 (setq finish (bobp))
22186 (when (and (setq m (get-text-property (point) 'org-hd-marker))
22187 (equal m hdmarker))
22188 (setq props (text-properties-at (point))
22189 dotime (get-text-property (point) 'dotime)
22190 cat (get-text-property (point) 'org-category)
22191 tags (get-text-property (point) 'tags)
22192 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
22193 pl (get-text-property (point) 'prefix-length)
22194 undone-face (get-text-property (point) 'undone-face)
22195 done-face (get-text-property (point) 'done-face))
22196 (move-to-column pl)
22197 (cond
22198 ((equal new "")
22199 (beginning-of-line 1)
22200 (and (looking-at ".*\n?") (replace-match "")))
22201 ((looking-at ".*")
22202 (replace-match new t t)
22203 (beginning-of-line 1)
22204 (add-text-properties (point-at-bol) (point-at-eol) props)
22205 (when fixface
22206 (add-text-properties
22207 (point-at-bol) (point-at-eol)
22208 (list 'face
22209 (if org-last-todo-state-is-todo
22210 undone-face done-face))))
22211 (org-agenda-highlight-todo 'line)
22212 (beginning-of-line 1))
22213 (t (error "Line update did not work"))))
22214 (beginning-of-line 0)))
22215 (org-finalize-agenda)))
22217 (defun org-agenda-align-tags (&optional line)
22218 "Align all tags in agenda items to `org-agenda-tags-column'."
22219 (let ((inhibit-read-only t) l c)
22220 (save-excursion
22221 (goto-char (if line (point-at-bol) (point-min)))
22222 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22223 (if line (point-at-eol) nil) t)
22224 (add-text-properties
22225 (match-beginning 2) (match-end 2)
22226 (list 'face (list 'org-tag (get-text-property
22227 (match-beginning 2) 'face))))
22228 (setq l (- (match-end 2) (match-beginning 2))
22229 c (if (< org-agenda-tags-column 0)
22230 (- (abs org-agenda-tags-column) l)
22231 org-agenda-tags-column))
22232 (delete-region (match-beginning 1) (match-end 1))
22233 (goto-char (match-beginning 1))
22234 (insert (org-add-props
22235 (make-string (max 1 (- c (current-column))) ?\ )
22236 (text-properties-at (point))))))))
22238 (defun org-agenda-priority-up ()
22239 "Increase the priority of line at point, also in Org-mode file."
22240 (interactive)
22241 (org-agenda-priority 'up))
22243 (defun org-agenda-priority-down ()
22244 "Decrease the priority of line at point, also in Org-mode file."
22245 (interactive)
22246 (org-agenda-priority 'down))
22248 (defun org-agenda-priority (&optional force-direction)
22249 "Set the priority of line at point, also in Org-mode file.
22250 This changes the line at point, all other lines in the agenda referring to
22251 the same tree node, and the headline of the tree node in the Org-mode file."
22252 (interactive)
22253 (org-agenda-check-no-diary)
22254 (let* ((marker (or (get-text-property (point) 'org-marker)
22255 (org-agenda-error)))
22256 (hdmarker (get-text-property (point) 'org-hd-marker))
22257 (buffer (marker-buffer hdmarker))
22258 (pos (marker-position hdmarker))
22259 (inhibit-read-only t)
22260 newhead)
22261 (org-with-remote-undo buffer
22262 (with-current-buffer buffer
22263 (widen)
22264 (goto-char pos)
22265 (org-show-context 'agenda)
22266 (save-excursion
22267 (and (outline-next-heading)
22268 (org-flag-heading nil))) ; show the next heading
22269 (funcall 'org-priority force-direction)
22270 (end-of-line 1)
22271 (setq newhead (org-get-heading)))
22272 (org-agenda-change-all-lines newhead hdmarker)
22273 (beginning-of-line 1))))
22275 (defun org-get-tags-at (&optional pos)
22276 "Get a list of all headline tags applicable at POS.
22277 POS defaults to point. If tags are inherited, the list contains
22278 the targets in the same sequence as the headlines appear, i.e.
22279 the tags of the current headline come last."
22280 (interactive)
22281 (let (tags lastpos)
22282 (save-excursion
22283 (save-restriction
22284 (widen)
22285 (goto-char (or pos (point)))
22286 (save-match-data
22287 (org-back-to-heading t)
22288 (condition-case nil
22289 (while (not (equal lastpos (point)))
22290 (setq lastpos (point))
22291 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
22292 (setq tags (append (org-split-string
22293 (org-match-string-no-properties 1) ":")
22294 tags)))
22295 (or org-use-tag-inheritance (error ""))
22296 (org-up-heading-all 1))
22297 (error nil))))
22298 tags)))
22300 ;; FIXME: should fix the tags property of the agenda line.
22301 (defun org-agenda-set-tags ()
22302 "Set tags for the current headline."
22303 (interactive)
22304 (org-agenda-check-no-diary)
22305 (if (and (org-region-active-p) (interactive-p))
22306 (call-interactively 'org-change-tag-in-region)
22307 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22308 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22309 (org-agenda-error)))
22310 (buffer (marker-buffer hdmarker))
22311 (pos (marker-position hdmarker))
22312 (inhibit-read-only t)
22313 newhead)
22314 (org-with-remote-undo buffer
22315 (with-current-buffer buffer
22316 (widen)
22317 (goto-char pos)
22318 (save-excursion
22319 (org-show-context 'agenda))
22320 (save-excursion
22321 (and (outline-next-heading)
22322 (org-flag-heading nil))) ; show the next heading
22323 (goto-char pos)
22324 (call-interactively 'org-set-tags)
22325 (end-of-line 1)
22326 (setq newhead (org-get-heading)))
22327 (org-agenda-change-all-lines newhead hdmarker)
22328 (beginning-of-line 1)))))
22330 (defun org-agenda-toggle-archive-tag ()
22331 "Toggle the archive tag for the current entry."
22332 (interactive)
22333 (org-agenda-check-no-diary)
22334 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22335 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22336 (org-agenda-error)))
22337 (buffer (marker-buffer hdmarker))
22338 (pos (marker-position hdmarker))
22339 (inhibit-read-only t)
22340 newhead)
22341 (org-with-remote-undo buffer
22342 (with-current-buffer buffer
22343 (widen)
22344 (goto-char pos)
22345 (org-show-context 'agenda)
22346 (save-excursion
22347 (and (outline-next-heading)
22348 (org-flag-heading nil))) ; show the next heading
22349 (call-interactively 'org-toggle-archive-tag)
22350 (end-of-line 1)
22351 (setq newhead (org-get-heading)))
22352 (org-agenda-change-all-lines newhead hdmarker)
22353 (beginning-of-line 1))))
22355 (defun org-agenda-date-later (arg &optional what)
22356 "Change the date of this item to one day later."
22357 (interactive "p")
22358 (org-agenda-check-type t 'agenda 'timeline)
22359 (org-agenda-check-no-diary)
22360 (let* ((marker (or (get-text-property (point) 'org-marker)
22361 (org-agenda-error)))
22362 (buffer (marker-buffer marker))
22363 (pos (marker-position marker)))
22364 (org-with-remote-undo buffer
22365 (with-current-buffer buffer
22366 (widen)
22367 (goto-char pos)
22368 (if (not (org-at-timestamp-p))
22369 (error "Cannot find time stamp"))
22370 (org-timestamp-change arg (or what 'day)))
22371 (org-agenda-show-new-time marker org-last-changed-timestamp))
22372 (message "Time stamp changed to %s" org-last-changed-timestamp)))
22374 (defun org-agenda-date-earlier (arg &optional what)
22375 "Change the date of this item to one day earlier."
22376 (interactive "p")
22377 (org-agenda-date-later (- arg) what))
22379 (defun org-agenda-show-new-time (marker stamp &optional prefix)
22380 "Show new date stamp via text properties."
22381 ;; We use text properties to make this undoable
22382 (let ((inhibit-read-only t))
22383 (setq stamp (concat " " prefix " => " stamp))
22384 (save-excursion
22385 (goto-char (point-max))
22386 (while (not (bobp))
22387 (when (equal marker (get-text-property (point) 'org-marker))
22388 (move-to-column (- (window-width) (length stamp)) t)
22389 (if (featurep 'xemacs)
22390 ;; Use `duplicable' property to trigger undo recording
22391 (let ((ex (make-extent nil nil))
22392 (gl (make-glyph stamp)))
22393 (set-glyph-face gl 'secondary-selection)
22394 (set-extent-properties
22395 ex (list 'invisible t 'end-glyph gl 'duplicable t))
22396 (insert-extent ex (1- (point)) (point-at-eol)))
22397 (add-text-properties
22398 (1- (point)) (point-at-eol)
22399 (list 'display (org-add-props stamp nil
22400 'face 'secondary-selection))))
22401 (beginning-of-line 1))
22402 (beginning-of-line 0)))))
22404 (defun org-agenda-date-prompt (arg)
22405 "Change the date of this item. Date is prompted for, with default today.
22406 The prefix ARG is passed to the `org-time-stamp' command and can therefore
22407 be used to request time specification in the time stamp."
22408 (interactive "P")
22409 (org-agenda-check-type t 'agenda 'timeline)
22410 (org-agenda-check-no-diary)
22411 (let* ((marker (or (get-text-property (point) 'org-marker)
22412 (org-agenda-error)))
22413 (buffer (marker-buffer marker))
22414 (pos (marker-position marker)))
22415 (org-with-remote-undo buffer
22416 (with-current-buffer buffer
22417 (widen)
22418 (goto-char pos)
22419 (if (not (org-at-timestamp-p))
22420 (error "Cannot find time stamp"))
22421 (org-time-stamp arg)
22422 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
22424 (defun org-agenda-schedule (arg)
22425 "Schedule the item at point."
22426 (interactive "P")
22427 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22428 (org-agenda-check-no-diary)
22429 (let* ((marker (or (get-text-property (point) 'org-marker)
22430 (org-agenda-error)))
22431 (buffer (marker-buffer marker))
22432 (pos (marker-position marker))
22433 (org-insert-labeled-timestamps-at-point nil)
22435 (org-with-remote-undo buffer
22436 (with-current-buffer buffer
22437 (widen)
22438 (goto-char pos)
22439 (setq ts (org-schedule arg)))
22440 (org-agenda-show-new-time marker ts "S"))
22441 (message "Item scheduled for %s" ts)))
22443 (defun org-agenda-deadline (arg)
22444 "Schedule the item at point."
22445 (interactive "P")
22446 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22447 (org-agenda-check-no-diary)
22448 (let* ((marker (or (get-text-property (point) 'org-marker)
22449 (org-agenda-error)))
22450 (buffer (marker-buffer marker))
22451 (pos (marker-position marker))
22452 (org-insert-labeled-timestamps-at-point nil)
22454 (org-with-remote-undo buffer
22455 (with-current-buffer buffer
22456 (widen)
22457 (goto-char pos)
22458 (setq ts (org-deadline arg)))
22459 (org-agenda-show-new-time marker ts "S"))
22460 (message "Deadline for this item set to %s" ts)))
22462 (defun org-get-heading (&optional no-tags)
22463 "Return the heading of the current entry, without the stars."
22464 (save-excursion
22465 (org-back-to-heading t)
22466 (if (looking-at
22467 (if no-tags
22468 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
22469 "\\*+[ \t]+\\([^\r\n]*\\)"))
22470 (match-string 1) "")))
22472 (defun org-agenda-clock-in (&optional arg)
22473 "Start the clock on the currently selected item."
22474 (interactive "P")
22475 (org-agenda-check-no-diary)
22476 (let* ((marker (or (get-text-property (point) 'org-marker)
22477 (org-agenda-error)))
22478 (pos (marker-position marker)))
22479 (org-with-remote-undo (marker-buffer marker)
22480 (with-current-buffer (marker-buffer marker)
22481 (widen)
22482 (goto-char pos)
22483 (org-clock-in)))))
22485 (defun org-agenda-clock-out (&optional arg)
22486 "Stop the currently running clock."
22487 (interactive "P")
22488 (unless (marker-buffer org-clock-marker)
22489 (error "No running clock"))
22490 (org-with-remote-undo (marker-buffer org-clock-marker)
22491 (org-clock-out)))
22493 (defun org-agenda-clock-cancel (&optional arg)
22494 "Cancel the currently running clock."
22495 (interactive "P")
22496 (unless (marker-buffer org-clock-marker)
22497 (error "No running clock"))
22498 (org-with-remote-undo (marker-buffer org-clock-marker)
22499 (org-clock-cancel)))
22501 (defun org-agenda-diary-entry ()
22502 "Make a diary entry, like the `i' command from the calendar.
22503 All the standard commands work: block, weekly etc."
22504 (interactive)
22505 (org-agenda-check-type t 'agenda 'timeline)
22506 (require 'diary-lib)
22507 (let* ((char (progn
22508 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
22509 (read-char-exclusive)))
22510 (cmd (cdr (assoc char
22511 '((?d . insert-diary-entry)
22512 (?w . insert-weekly-diary-entry)
22513 (?m . insert-monthly-diary-entry)
22514 (?y . insert-yearly-diary-entry)
22515 (?a . insert-anniversary-diary-entry)
22516 (?b . insert-block-diary-entry)
22517 (?c . insert-cyclic-diary-entry)))))
22518 (oldf (symbol-function 'calendar-cursor-to-date))
22519 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
22520 (point (point))
22521 (mark (or (mark t) (point))))
22522 (unless cmd
22523 (error "No command associated with <%c>" char))
22524 (unless (and (get-text-property point 'day)
22525 (or (not (equal ?b char))
22526 (get-text-property mark 'day)))
22527 (error "Don't know which date to use for diary entry"))
22528 ;; We implement this by hacking the `calendar-cursor-to-date' function
22529 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
22530 (let ((calendar-mark-ring
22531 (list (calendar-gregorian-from-absolute
22532 (or (get-text-property mark 'day)
22533 (get-text-property point 'day))))))
22534 (unwind-protect
22535 (progn
22536 (fset 'calendar-cursor-to-date
22537 (lambda (&optional error)
22538 (calendar-gregorian-from-absolute
22539 (get-text-property point 'day))))
22540 (call-interactively cmd))
22541 (fset 'calendar-cursor-to-date oldf)))))
22544 (defun org-agenda-execute-calendar-command (cmd)
22545 "Execute a calendar command from the agenda, with the date associated to
22546 the cursor position."
22547 (org-agenda-check-type t 'agenda 'timeline)
22548 (require 'diary-lib)
22549 (unless (get-text-property (point) 'day)
22550 (error "Don't know which date to use for calendar command"))
22551 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
22552 (point (point))
22553 (date (calendar-gregorian-from-absolute
22554 (get-text-property point 'day)))
22555 ;; the following 3 vars are needed in the calendar
22556 (displayed-day (extract-calendar-day date))
22557 (displayed-month (extract-calendar-month date))
22558 (displayed-year (extract-calendar-year date)))
22559 (unwind-protect
22560 (progn
22561 (fset 'calendar-cursor-to-date
22562 (lambda (&optional error)
22563 (calendar-gregorian-from-absolute
22564 (get-text-property point 'day))))
22565 (call-interactively cmd))
22566 (fset 'calendar-cursor-to-date oldf))))
22568 (defun org-agenda-phases-of-moon ()
22569 "Display the phases of the moon for the 3 months around the cursor date."
22570 (interactive)
22571 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
22573 (defun org-agenda-holidays ()
22574 "Display the holidays for the 3 months around the cursor date."
22575 (interactive)
22576 (org-agenda-execute-calendar-command 'list-calendar-holidays))
22578 (defun org-agenda-sunrise-sunset (arg)
22579 "Display sunrise and sunset for the cursor date.
22580 Latitude and longitude can be specified with the variables
22581 `calendar-latitude' and `calendar-longitude'. When called with prefix
22582 argument, latitude and longitude will be prompted for."
22583 (interactive "P")
22584 (let ((calendar-longitude (if arg nil calendar-longitude))
22585 (calendar-latitude (if arg nil calendar-latitude))
22586 (calendar-location-name
22587 (if arg "the given coordinates" calendar-location-name)))
22588 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
22590 (defun org-agenda-goto-calendar ()
22591 "Open the Emacs calendar with the date at the cursor."
22592 (interactive)
22593 (org-agenda-check-type t 'agenda 'timeline)
22594 (let* ((day (or (get-text-property (point) 'day)
22595 (error "Don't know which date to open in calendar")))
22596 (date (calendar-gregorian-from-absolute day))
22597 (calendar-move-hook nil)
22598 (view-calendar-holidays-initially nil)
22599 (view-diary-entries-initially nil))
22600 (calendar)
22601 (calendar-goto-date date)))
22603 (defun org-calendar-goto-agenda ()
22604 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
22605 This is a command that has to be installed in `calendar-mode-map'."
22606 (interactive)
22607 (org-agenda-list nil (calendar-absolute-from-gregorian
22608 (calendar-cursor-to-date))
22609 nil))
22611 (defun org-agenda-convert-date ()
22612 (interactive)
22613 (org-agenda-check-type t 'agenda 'timeline)
22614 (let ((day (get-text-property (point) 'day))
22615 date s)
22616 (unless day
22617 (error "Don't know which date to convert"))
22618 (setq date (calendar-gregorian-from-absolute day))
22619 (setq s (concat
22620 "Gregorian: " (calendar-date-string date) "\n"
22621 "ISO: " (calendar-iso-date-string date) "\n"
22622 "Day of Yr: " (calendar-day-of-year-string date) "\n"
22623 "Julian: " (calendar-julian-date-string date) "\n"
22624 "Astron. JD: " (calendar-astro-date-string date)
22625 " (Julian date number at noon UTC)\n"
22626 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
22627 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
22628 "French: " (calendar-french-date-string date) "\n"
22629 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
22630 "Mayan: " (calendar-mayan-date-string date) "\n"
22631 "Coptic: " (calendar-coptic-date-string date) "\n"
22632 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
22633 "Persian: " (calendar-persian-date-string date) "\n"
22634 "Chinese: " (calendar-chinese-date-string date) "\n"))
22635 (with-output-to-temp-buffer "*Dates*"
22636 (princ s))
22637 (if (fboundp 'fit-window-to-buffer)
22638 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
22641 ;;;; Embedded LaTeX
22643 (defvar org-cdlatex-mode-map (make-sparse-keymap)
22644 "Keymap for the minor `org-cdlatex-mode'.")
22646 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
22647 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
22648 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
22649 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
22650 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
22652 (defvar org-cdlatex-texmathp-advice-is-done nil
22653 "Flag remembering if we have applied the advice to texmathp already.")
22655 (define-minor-mode org-cdlatex-mode
22656 "Toggle the minor `org-cdlatex-mode'.
22657 This mode supports entering LaTeX environment and math in LaTeX fragments
22658 in Org-mode.
22659 \\{org-cdlatex-mode-map}"
22660 nil " OCDL" nil
22661 (when org-cdlatex-mode (require 'cdlatex))
22662 (unless org-cdlatex-texmathp-advice-is-done
22663 (setq org-cdlatex-texmathp-advice-is-done t)
22664 (defadvice texmathp (around org-math-always-on activate)
22665 "Always return t in org-mode buffers.
22666 This is because we want to insert math symbols without dollars even outside
22667 the LaTeX math segments. If Orgmode thinks that point is actually inside
22668 en embedded LaTeX fragement, let texmathp do its job.
22669 \\[org-cdlatex-mode-map]"
22670 (interactive)
22671 (let (p)
22672 (cond
22673 ((not (org-mode-p)) ad-do-it)
22674 ((eq this-command 'cdlatex-math-symbol)
22675 (setq ad-return-value t
22676 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
22678 (let ((p (org-inside-LaTeX-fragment-p)))
22679 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
22680 (setq ad-return-value t
22681 texmathp-why '("Org-mode embedded math" . 0))
22682 (if p ad-do-it)))))))))
22684 (defun turn-on-org-cdlatex ()
22685 "Unconditionally turn on `org-cdlatex-mode'."
22686 (org-cdlatex-mode 1))
22688 (defun org-inside-LaTeX-fragment-p ()
22689 "Test if point is inside a LaTeX fragment.
22690 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
22691 sequence appearing also before point.
22692 Even though the matchers for math are configurable, this function assumes
22693 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
22694 delimiters are skipped when they have been removed by customization.
22695 The return value is nil, or a cons cell with the delimiter and
22696 and the position of this delimiter.
22698 This function does a reasonably good job, but can locally be fooled by
22699 for example currency specifications. For example it will assume being in
22700 inline math after \"$22.34\". The LaTeX fragment formatter will only format
22701 fragments that are properly closed, but during editing, we have to live
22702 with the uncertainty caused by missing closing delimiters. This function
22703 looks only before point, not after."
22704 (catch 'exit
22705 (let ((pos (point))
22706 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
22707 (lim (progn
22708 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
22709 (point)))
22710 dd-on str (start 0) m re)
22711 (goto-char pos)
22712 (when dodollar
22713 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
22714 re (nth 1 (assoc "$" org-latex-regexps)))
22715 (while (string-match re str start)
22716 (cond
22717 ((= (match-end 0) (length str))
22718 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
22719 ((= (match-end 0) (- (length str) 5))
22720 (throw 'exit nil))
22721 (t (setq start (match-end 0))))))
22722 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
22723 (goto-char pos)
22724 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
22725 (and (match-beginning 2) (throw 'exit nil))
22726 ;; count $$
22727 (while (re-search-backward "\\$\\$" lim t)
22728 (setq dd-on (not dd-on)))
22729 (goto-char pos)
22730 (if dd-on (cons "$$" m))))))
22733 (defun org-try-cdlatex-tab ()
22734 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
22735 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
22736 - inside a LaTeX fragment, or
22737 - after the first word in a line, where an abbreviation expansion could
22738 insert a LaTeX environment."
22739 (when org-cdlatex-mode
22740 (cond
22741 ((save-excursion
22742 (skip-chars-backward "a-zA-Z0-9*")
22743 (skip-chars-backward " \t")
22744 (bolp))
22745 (cdlatex-tab) t)
22746 ((org-inside-LaTeX-fragment-p)
22747 (cdlatex-tab) t)
22748 (t nil))))
22750 (defun org-cdlatex-underscore-caret (&optional arg)
22751 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
22752 Revert to the normal definition outside of these fragments."
22753 (interactive "P")
22754 (if (org-inside-LaTeX-fragment-p)
22755 (call-interactively 'cdlatex-sub-superscript)
22756 (let (org-cdlatex-mode)
22757 (call-interactively (key-binding (vector last-input-event))))))
22759 (defun org-cdlatex-math-modify (&optional arg)
22760 "Execute `cdlatex-math-modify' in LaTeX fragments.
22761 Revert to the normal definition outside of these fragments."
22762 (interactive "P")
22763 (if (org-inside-LaTeX-fragment-p)
22764 (call-interactively 'cdlatex-math-modify)
22765 (let (org-cdlatex-mode)
22766 (call-interactively (key-binding (vector last-input-event))))))
22768 (defvar org-latex-fragment-image-overlays nil
22769 "List of overlays carrying the images of latex fragments.")
22770 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
22772 (defun org-remove-latex-fragment-image-overlays ()
22773 "Remove all overlays with LaTeX fragment images in current buffer."
22774 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
22775 (setq org-latex-fragment-image-overlays nil))
22777 (defun org-preview-latex-fragment (&optional subtree)
22778 "Preview the LaTeX fragment at point, or all locally or globally.
22779 If the cursor is in a LaTeX fragment, create the image and overlay
22780 it over the source code. If there is no fragment at point, display
22781 all fragments in the current text, from one headline to the next. With
22782 prefix SUBTREE, display all fragments in the current subtree. With a
22783 double prefix `C-u C-u', or when the cursor is before the first headline,
22784 display all fragments in the buffer.
22785 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
22786 (interactive "P")
22787 (org-remove-latex-fragment-image-overlays)
22788 (save-excursion
22789 (save-restriction
22790 (let (beg end at msg)
22791 (cond
22792 ((or (equal subtree '(16))
22793 (not (save-excursion
22794 (re-search-backward (concat "^" outline-regexp) nil t))))
22795 (setq beg (point-min) end (point-max)
22796 msg "Creating images for buffer...%s"))
22797 ((equal subtree '(4))
22798 (org-back-to-heading)
22799 (setq beg (point) end (org-end-of-subtree t)
22800 msg "Creating images for subtree...%s"))
22802 (if (setq at (org-inside-LaTeX-fragment-p))
22803 (goto-char (max (point-min) (- (cdr at) 2)))
22804 (org-back-to-heading))
22805 (setq beg (point) end (progn (outline-next-heading) (point))
22806 msg (if at "Creating image...%s"
22807 "Creating images for entry...%s"))))
22808 (message msg "")
22809 (narrow-to-region beg end)
22810 (goto-char beg)
22811 (org-format-latex
22812 (concat "ltxpng/" (file-name-sans-extension
22813 (file-name-nondirectory
22814 buffer-file-name)))
22815 default-directory 'overlays msg at 'forbuffer)
22816 (message msg "done. Use `C-c C-c' to remove images.")))))
22818 (defvar org-latex-regexps
22819 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
22820 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
22821 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
22822 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
22823 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
22824 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
22825 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
22826 "Regular expressions for matching embedded LaTeX.")
22828 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
22829 "Replace LaTeX fragments with links to an image, and produce images."
22830 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
22831 (let* ((prefixnodir (file-name-nondirectory prefix))
22832 (absprefix (expand-file-name prefix dir))
22833 (todir (file-name-directory absprefix))
22834 (opt org-format-latex-options)
22835 (matchers (plist-get opt :matchers))
22836 (re-list org-latex-regexps)
22837 (cnt 0) txt link beg end re e checkdir
22838 m n block linkfile movefile ov)
22839 ;; Check if there are old images files with this prefix, and remove them
22840 (when (file-directory-p todir)
22841 (mapc 'delete-file
22842 (directory-files
22843 todir 'full
22844 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
22845 ;; Check the different regular expressions
22846 (while (setq e (pop re-list))
22847 (setq m (car e) re (nth 1 e) n (nth 2 e)
22848 block (if (nth 3 e) "\n\n" ""))
22849 (when (member m matchers)
22850 (goto-char (point-min))
22851 (while (re-search-forward re nil t)
22852 (when (or (not at) (equal (cdr at) (match-beginning n)))
22853 (setq txt (match-string n)
22854 beg (match-beginning n) end (match-end n)
22855 cnt (1+ cnt)
22856 linkfile (format "%s_%04d.png" prefix cnt)
22857 movefile (format "%s_%04d.png" absprefix cnt)
22858 link (concat block "[[file:" linkfile "]]" block))
22859 (if msg (message msg cnt))
22860 (goto-char beg)
22861 (unless checkdir ; make sure the directory exists
22862 (setq checkdir t)
22863 (or (file-directory-p todir) (make-directory todir)))
22864 (org-create-formula-image
22865 txt movefile opt forbuffer)
22866 (if overlays
22867 (progn
22868 (setq ov (org-make-overlay beg end))
22869 (if (featurep 'xemacs)
22870 (progn
22871 (org-overlay-put ov 'invisible t)
22872 (org-overlay-put
22873 ov 'end-glyph
22874 (make-glyph (vector 'png :file movefile))))
22875 (org-overlay-put
22876 ov 'display
22877 (list 'image :type 'png :file movefile :ascent 'center)))
22878 (push ov org-latex-fragment-image-overlays)
22879 (goto-char end))
22880 (delete-region beg end)
22881 (insert link))))))))
22883 ;; This function borrows from Ganesh Swami's latex2png.el
22884 (defun org-create-formula-image (string tofile options buffer)
22885 (let* ((tmpdir (if (featurep 'xemacs)
22886 (temp-directory)
22887 temporary-file-directory))
22888 (texfilebase (make-temp-name
22889 (expand-file-name "orgtex" tmpdir)))
22890 (texfile (concat texfilebase ".tex"))
22891 (dvifile (concat texfilebase ".dvi"))
22892 (pngfile (concat texfilebase ".png"))
22893 (fnh (face-attribute 'default :height nil))
22894 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
22895 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
22896 (fg (or (plist-get options (if buffer :foreground :html-foreground))
22897 "Black"))
22898 (bg (or (plist-get options (if buffer :background :html-background))
22899 "Transparent")))
22900 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
22901 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
22902 (with-temp-file texfile
22903 (insert org-format-latex-header
22904 "\n\\begin{document}\n" string "\n\\end{document}\n"))
22905 (let ((dir default-directory))
22906 (condition-case nil
22907 (progn
22908 (cd tmpdir)
22909 (call-process "latex" nil nil nil texfile))
22910 (error nil))
22911 (cd dir))
22912 (if (not (file-exists-p dvifile))
22913 (progn (message "Failed to create dvi file from %s" texfile) nil)
22914 (call-process "dvipng" nil nil nil
22915 "-E" "-fg" fg "-bg" bg
22916 "-D" dpi
22917 ;;"-x" scale "-y" scale
22918 "-T" "tight"
22919 "-o" pngfile
22920 dvifile)
22921 (if (not (file-exists-p pngfile))
22922 (progn (message "Failed to create png file from %s" texfile) nil)
22923 ;; Use the requested file name and clean up
22924 (copy-file pngfile tofile 'replace)
22925 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
22926 (delete-file (concat texfilebase e)))
22927 pngfile))))
22929 (defun org-dvipng-color (attr)
22930 "Return an rgb color specification for dvipng."
22931 (apply 'format "rgb %s %s %s"
22932 (mapcar 'org-normalize-color
22933 (color-values (face-attribute 'default attr nil)))))
22935 (defun org-normalize-color (value)
22936 "Return string to be used as color value for an RGB component."
22937 (format "%g" (/ value 65535.0)))
22939 ;;;; Exporting
22941 ;;; Variables, constants, and parameter plists
22943 (defconst org-level-max 20)
22945 (defvar org-export-html-preamble nil
22946 "Preamble, to be inserted just after <body>. Set by publishing functions.")
22947 (defvar org-export-html-postamble nil
22948 "Preamble, to be inserted just before </body>. Set by publishing functions.")
22949 (defvar org-export-html-auto-preamble t
22950 "Should default preamble be inserted? Set by publishing functions.")
22951 (defvar org-export-html-auto-postamble t
22952 "Should default postamble be inserted? Set by publishing functions.")
22953 (defvar org-current-export-file nil) ; dynamically scoped parameter
22954 (defvar org-current-export-dir nil) ; dynamically scoped parameter
22957 (defconst org-export-plist-vars
22958 '((:language . org-export-default-language)
22959 (:customtime . org-display-custom-times)
22960 (:headline-levels . org-export-headline-levels)
22961 (:section-numbers . org-export-with-section-numbers)
22962 (:table-of-contents . org-export-with-toc)
22963 (:preserve-breaks . org-export-preserve-breaks)
22964 (:archived-trees . org-export-with-archived-trees)
22965 (:emphasize . org-export-with-emphasize)
22966 (:sub-superscript . org-export-with-sub-superscripts)
22967 (:special-strings . org-export-with-special-strings)
22968 (:footnotes . org-export-with-footnotes)
22969 (:drawers . org-export-with-drawers)
22970 (:tags . org-export-with-tags)
22971 (:TeX-macros . org-export-with-TeX-macros)
22972 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
22973 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
22974 (:fixed-width . org-export-with-fixed-width)
22975 (:timestamps . org-export-with-timestamps)
22976 (:author-info . org-export-author-info)
22977 (:time-stamp-file . org-export-time-stamp-file)
22978 (:tables . org-export-with-tables)
22979 (:table-auto-headline . org-export-highlight-first-table-line)
22980 (:style . org-export-html-style)
22981 (:agenda-style . org-agenda-export-html-style)
22982 (:convert-org-links . org-export-html-link-org-files-as-html)
22983 (:inline-images . org-export-html-inline-images)
22984 (:html-extension . org-export-html-extension)
22985 (:html-table-tag . org-export-html-table-tag)
22986 (:expand-quoted-html . org-export-html-expand)
22987 (:timestamp . org-export-html-with-timestamp)
22988 (:publishing-directory . org-export-publishing-directory)
22989 (:preamble . org-export-html-preamble)
22990 (:postamble . org-export-html-postamble)
22991 (:auto-preamble . org-export-html-auto-preamble)
22992 (:auto-postamble . org-export-html-auto-postamble)
22993 (:author . user-full-name)
22994 (:email . user-mail-address)))
22996 (defun org-default-export-plist ()
22997 "Return the property list with default settings for the export variables."
22998 (let ((l org-export-plist-vars) rtn e)
22999 (while (setq e (pop l))
23000 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
23001 rtn))
23003 (defun org-infile-export-plist ()
23004 "Return the property list with file-local settings for export."
23005 (save-excursion
23006 (goto-char 0)
23007 (let ((re (org-make-options-regexp
23008 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
23009 p key val text options)
23010 (while (re-search-forward re nil t)
23011 (setq key (org-match-string-no-properties 1)
23012 val (org-match-string-no-properties 2))
23013 (cond
23014 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
23015 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
23016 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
23017 ((string-equal key "DATE") (setq p (plist-put p :date val)))
23018 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
23019 ((string-equal key "TEXT")
23020 (setq text (if text (concat text "\n" val) val)))
23021 ((string-equal key "OPTIONS") (setq options val))))
23022 (setq p (plist-put p :text text))
23023 (when options
23024 (let ((op '(("H" . :headline-levels)
23025 ("num" . :section-numbers)
23026 ("toc" . :table-of-contents)
23027 ("\\n" . :preserve-breaks)
23028 ("@" . :expand-quoted-html)
23029 (":" . :fixed-width)
23030 ("|" . :tables)
23031 ("^" . :sub-superscript)
23032 ("-" . :special-strings)
23033 ("f" . :footnotes)
23034 ("d" . :drawers)
23035 ("tags" . :tags)
23036 ("*" . :emphasize)
23037 ("TeX" . :TeX-macros)
23038 ("LaTeX" . :LaTeX-fragments)
23039 ("skip" . :skip-before-1st-heading)
23040 ("author" . :author-info)
23041 ("timestamp" . :time-stamp-file)))
23043 (while (setq o (pop op))
23044 (if (string-match (concat (regexp-quote (car o))
23045 ":\\([^ \t\n\r;,.]*\\)")
23046 options)
23047 (setq p (plist-put p (cdr o)
23048 (car (read-from-string
23049 (match-string 1 options)))))))))
23050 p)))
23052 (defun org-export-directory (type plist)
23053 (let* ((val (plist-get plist :publishing-directory))
23054 (dir (if (listp val)
23055 (or (cdr (assoc type val)) ".")
23056 val)))
23057 dir))
23059 (defun org-skip-comments (lines)
23060 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
23061 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
23062 (re2 "^\\(\\*+\\)[ \t\n\r]")
23063 (case-fold-search nil)
23064 rtn line level)
23065 (while (setq line (pop lines))
23066 (cond
23067 ((and (string-match re1 line)
23068 (setq level (- (match-end 1) (match-beginning 1))))
23069 ;; Beginning of a COMMENT subtree. Skip it.
23070 (while (and (setq line (pop lines))
23071 (or (not (string-match re2 line))
23072 (> (- (match-end 1) (match-beginning 1)) level))))
23073 (setq lines (cons line lines)))
23074 ((string-match "^#" line)
23075 ;; an ordinary comment line
23077 ((and org-export-table-remove-special-lines
23078 (string-match "^[ \t]*|" line)
23079 (or (string-match "^[ \t]*| *[!_^] *|" line)
23080 (and (string-match "| *<[0-9]+> *|" line)
23081 (not (string-match "| *[^ <|]" line)))))
23082 ;; a special table line that should be removed
23084 (t (setq rtn (cons line rtn)))))
23085 (nreverse rtn)))
23087 (defun org-export (&optional arg)
23088 (interactive)
23089 (let ((help "[t] insert the export option template
23090 \[v] limit export to visible part of outline tree
23092 \[a] export as ASCII
23094 \[h] export as HTML
23095 \[H] export as HTML to temporary buffer
23096 \[R] export region as HTML
23097 \[b] export as HTML and browse immediately
23098 \[x] export as XOXO
23100 \[l] export as LaTeX
23101 \[L] export as LaTeX to temporary buffer
23103 \[i] export current file as iCalendar file
23104 \[I] export all agenda files as iCalendar files
23105 \[c] export agenda files into combined iCalendar file
23107 \[F] publish current file
23108 \[P] publish current project
23109 \[X] publish... (project will be prompted for)
23110 \[A] publish all projects")
23111 (cmds
23112 '((?t . org-insert-export-options-template)
23113 (?v . org-export-visible)
23114 (?a . org-export-as-ascii)
23115 (?h . org-export-as-html)
23116 (?b . org-export-as-html-and-open)
23117 (?H . org-export-as-html-to-buffer)
23118 (?R . org-export-region-as-html)
23119 (?x . org-export-as-xoxo)
23120 (?l . org-export-as-latex)
23121 (?L . org-export-as-latex-to-buffer)
23122 (?i . org-export-icalendar-this-file)
23123 (?I . org-export-icalendar-all-agenda-files)
23124 (?c . org-export-icalendar-combine-agenda-files)
23125 (?F . org-publish-current-file)
23126 (?P . org-publish-current-project)
23127 (?X . org-publish)
23128 (?A . org-publish-all)))
23129 r1 r2 ass)
23130 (save-window-excursion
23131 (delete-other-windows)
23132 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
23133 (princ help))
23134 (message "Select command: ")
23135 (setq r1 (read-char-exclusive)))
23136 (setq r2 (if (< r1 27) (+ r1 96) r1))
23137 (if (setq ass (assq r2 cmds))
23138 (call-interactively (cdr ass))
23139 (error "No command associated with key %c" r1))))
23141 (defconst org-html-entities
23142 '(("nbsp")
23143 ("iexcl")
23144 ("cent")
23145 ("pound")
23146 ("curren")
23147 ("yen")
23148 ("brvbar")
23149 ("vert" . "&#124;")
23150 ("sect")
23151 ("uml")
23152 ("copy")
23153 ("ordf")
23154 ("laquo")
23155 ("not")
23156 ("shy")
23157 ("reg")
23158 ("macr")
23159 ("deg")
23160 ("plusmn")
23161 ("sup2")
23162 ("sup3")
23163 ("acute")
23164 ("micro")
23165 ("para")
23166 ("middot")
23167 ("odot"."o")
23168 ("star"."*")
23169 ("cedil")
23170 ("sup1")
23171 ("ordm")
23172 ("raquo")
23173 ("frac14")
23174 ("frac12")
23175 ("frac34")
23176 ("iquest")
23177 ("Agrave")
23178 ("Aacute")
23179 ("Acirc")
23180 ("Atilde")
23181 ("Auml")
23182 ("Aring") ("AA"."&Aring;")
23183 ("AElig")
23184 ("Ccedil")
23185 ("Egrave")
23186 ("Eacute")
23187 ("Ecirc")
23188 ("Euml")
23189 ("Igrave")
23190 ("Iacute")
23191 ("Icirc")
23192 ("Iuml")
23193 ("ETH")
23194 ("Ntilde")
23195 ("Ograve")
23196 ("Oacute")
23197 ("Ocirc")
23198 ("Otilde")
23199 ("Ouml")
23200 ("times")
23201 ("Oslash")
23202 ("Ugrave")
23203 ("Uacute")
23204 ("Ucirc")
23205 ("Uuml")
23206 ("Yacute")
23207 ("THORN")
23208 ("szlig")
23209 ("agrave")
23210 ("aacute")
23211 ("acirc")
23212 ("atilde")
23213 ("auml")
23214 ("aring")
23215 ("aelig")
23216 ("ccedil")
23217 ("egrave")
23218 ("eacute")
23219 ("ecirc")
23220 ("euml")
23221 ("igrave")
23222 ("iacute")
23223 ("icirc")
23224 ("iuml")
23225 ("eth")
23226 ("ntilde")
23227 ("ograve")
23228 ("oacute")
23229 ("ocirc")
23230 ("otilde")
23231 ("ouml")
23232 ("divide")
23233 ("oslash")
23234 ("ugrave")
23235 ("uacute")
23236 ("ucirc")
23237 ("uuml")
23238 ("yacute")
23239 ("thorn")
23240 ("yuml")
23241 ("fnof")
23242 ("Alpha")
23243 ("Beta")
23244 ("Gamma")
23245 ("Delta")
23246 ("Epsilon")
23247 ("Zeta")
23248 ("Eta")
23249 ("Theta")
23250 ("Iota")
23251 ("Kappa")
23252 ("Lambda")
23253 ("Mu")
23254 ("Nu")
23255 ("Xi")
23256 ("Omicron")
23257 ("Pi")
23258 ("Rho")
23259 ("Sigma")
23260 ("Tau")
23261 ("Upsilon")
23262 ("Phi")
23263 ("Chi")
23264 ("Psi")
23265 ("Omega")
23266 ("alpha")
23267 ("beta")
23268 ("gamma")
23269 ("delta")
23270 ("epsilon")
23271 ("varepsilon"."&epsilon;")
23272 ("zeta")
23273 ("eta")
23274 ("theta")
23275 ("iota")
23276 ("kappa")
23277 ("lambda")
23278 ("mu")
23279 ("nu")
23280 ("xi")
23281 ("omicron")
23282 ("pi")
23283 ("rho")
23284 ("sigmaf") ("varsigma"."&sigmaf;")
23285 ("sigma")
23286 ("tau")
23287 ("upsilon")
23288 ("phi")
23289 ("chi")
23290 ("psi")
23291 ("omega")
23292 ("thetasym") ("vartheta"."&thetasym;")
23293 ("upsih")
23294 ("piv")
23295 ("bull") ("bullet"."&bull;")
23296 ("hellip") ("dots"."&hellip;")
23297 ("prime")
23298 ("Prime")
23299 ("oline")
23300 ("frasl")
23301 ("weierp")
23302 ("image")
23303 ("real")
23304 ("trade")
23305 ("alefsym")
23306 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
23307 ("uarr") ("uparrow"."&uarr;")
23308 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
23309 ("darr")("downarrow"."&darr;")
23310 ("harr") ("leftrightarrow"."&harr;")
23311 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
23312 ("lArr") ("Leftarrow"."&lArr;")
23313 ("uArr") ("Uparrow"."&uArr;")
23314 ("rArr") ("Rightarrow"."&rArr;")
23315 ("dArr") ("Downarrow"."&dArr;")
23316 ("hArr") ("Leftrightarrow"."&hArr;")
23317 ("forall")
23318 ("part") ("partial"."&part;")
23319 ("exist") ("exists"."&exist;")
23320 ("empty") ("emptyset"."&empty;")
23321 ("nabla")
23322 ("isin") ("in"."&isin;")
23323 ("notin")
23324 ("ni")
23325 ("prod")
23326 ("sum")
23327 ("minus")
23328 ("lowast") ("ast"."&lowast;")
23329 ("radic")
23330 ("prop") ("proptp"."&prop;")
23331 ("infin") ("infty"."&infin;")
23332 ("ang") ("angle"."&ang;")
23333 ("and") ("wedge"."&and;")
23334 ("or") ("vee"."&or;")
23335 ("cap")
23336 ("cup")
23337 ("int")
23338 ("there4")
23339 ("sim")
23340 ("cong") ("simeq"."&cong;")
23341 ("asymp")("approx"."&asymp;")
23342 ("ne") ("neq"."&ne;")
23343 ("equiv")
23344 ("le")
23345 ("ge")
23346 ("sub") ("subset"."&sub;")
23347 ("sup") ("supset"."&sup;")
23348 ("nsub")
23349 ("sube")
23350 ("supe")
23351 ("oplus")
23352 ("otimes")
23353 ("perp")
23354 ("sdot") ("cdot"."&sdot;")
23355 ("lceil")
23356 ("rceil")
23357 ("lfloor")
23358 ("rfloor")
23359 ("lang")
23360 ("rang")
23361 ("loz") ("Diamond"."&loz;")
23362 ("spades") ("spadesuit"."&spades;")
23363 ("clubs") ("clubsuit"."&clubs;")
23364 ("hearts") ("diamondsuit"."&hearts;")
23365 ("diams") ("diamondsuit"."&diams;")
23366 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
23367 ("quot")
23368 ("amp")
23369 ("lt")
23370 ("gt")
23371 ("OElig")
23372 ("oelig")
23373 ("Scaron")
23374 ("scaron")
23375 ("Yuml")
23376 ("circ")
23377 ("tilde")
23378 ("ensp")
23379 ("emsp")
23380 ("thinsp")
23381 ("zwnj")
23382 ("zwj")
23383 ("lrm")
23384 ("rlm")
23385 ("ndash")
23386 ("mdash")
23387 ("lsquo")
23388 ("rsquo")
23389 ("sbquo")
23390 ("ldquo")
23391 ("rdquo")
23392 ("bdquo")
23393 ("dagger")
23394 ("Dagger")
23395 ("permil")
23396 ("lsaquo")
23397 ("rsaquo")
23398 ("euro")
23400 ("arccos"."arccos")
23401 ("arcsin"."arcsin")
23402 ("arctan"."arctan")
23403 ("arg"."arg")
23404 ("cos"."cos")
23405 ("cosh"."cosh")
23406 ("cot"."cot")
23407 ("coth"."coth")
23408 ("csc"."csc")
23409 ("deg"."deg")
23410 ("det"."det")
23411 ("dim"."dim")
23412 ("exp"."exp")
23413 ("gcd"."gcd")
23414 ("hom"."hom")
23415 ("inf"."inf")
23416 ("ker"."ker")
23417 ("lg"."lg")
23418 ("lim"."lim")
23419 ("liminf"."liminf")
23420 ("limsup"."limsup")
23421 ("ln"."ln")
23422 ("log"."log")
23423 ("max"."max")
23424 ("min"."min")
23425 ("Pr"."Pr")
23426 ("sec"."sec")
23427 ("sin"."sin")
23428 ("sinh"."sinh")
23429 ("sup"."sup")
23430 ("tan"."tan")
23431 ("tanh"."tanh")
23433 "Entities for TeX->HTML translation.
23434 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
23435 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
23436 In that case, \"\\ent\" will be translated to \"&other;\".
23437 The list contains HTML entities for Latin-1, Greek and other symbols.
23438 It is supplemented by a number of commonly used TeX macros with appropriate
23439 translations. There is currently no way for users to extend this.")
23441 ;;; General functions for all backends
23443 (defun org-cleaned-string-for-export (string &rest parameters)
23444 "Cleanup a buffer STRING so that links can be created safely."
23445 (interactive)
23446 (let* ((re-radio (and org-target-link-regexp
23447 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
23448 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
23449 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
23450 (re-archive (concat ":" org-archive-tag ":"))
23451 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
23452 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
23453 (htmlp (plist-get parameters :for-html))
23454 (asciip (plist-get parameters :for-ascii))
23455 (latexp (plist-get parameters :for-LaTeX))
23456 (commentsp (plist-get parameters :comments))
23457 (archived-trees (plist-get parameters :archived-trees))
23458 (inhibit-read-only t)
23459 (drawers org-drawers)
23460 (exp-drawers (plist-get parameters :drawers))
23461 (outline-regexp "\\*+ ")
23462 a b xx
23463 rtn p)
23464 (with-current-buffer (get-buffer-create " org-mode-tmp")
23465 (erase-buffer)
23466 (insert string)
23467 ;; Remove license-to-kill stuff
23468 (while (setq p (text-property-any (point-min) (point-max)
23469 :org-license-to-kill t))
23470 (delete-region p (next-single-property-change p :org-license-to-kill)))
23472 (let ((org-inhibit-startup t)) (org-mode))
23473 (untabify (point-min) (point-max))
23475 ;; Get the correct stuff before the first headline
23476 (when (plist-get parameters :skip-before-1st-heading)
23477 (goto-char (point-min))
23478 (when (re-search-forward "^\\*+[ \t]" nil t)
23479 (delete-region (point-min) (match-beginning 0))
23480 (goto-char (point-min))
23481 (insert "\n")))
23482 (when (plist-get parameters :add-text)
23483 (goto-char (point-min))
23484 (insert (plist-get parameters :add-text) "\n"))
23486 ;; Get rid of archived trees
23487 (when (not (eq archived-trees t))
23488 (goto-char (point-min))
23489 (while (re-search-forward re-archive nil t)
23490 (if (not (org-on-heading-p t))
23491 (org-end-of-subtree t)
23492 (beginning-of-line 1)
23493 (setq a (if archived-trees
23494 (1+ (point-at-eol)) (point))
23495 b (org-end-of-subtree t))
23496 (if (> b a) (delete-region a b)))))
23498 ;; Get rid of drawers
23499 (unless (eq t exp-drawers)
23500 (goto-char (point-min))
23501 (let ((re (concat "^[ \t]*:\\("
23502 (mapconcat
23503 'identity
23504 (org-delete-all exp-drawers
23505 (copy-sequence drawers))
23506 "\\|")
23507 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
23508 (while (re-search-forward re nil t)
23509 (replace-match ""))))
23511 ;; Find targets in comments and move them out of comments,
23512 ;; but mark them as targets that should be invisible
23513 (goto-char (point-min))
23514 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
23515 (replace-match "\\1(INVISIBLE)"))
23517 ;; Protect backend specific stuff, throw away the others.
23518 (let ((formatters
23519 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
23520 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
23521 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
23522 fmt)
23523 (goto-char (point-min))
23524 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
23525 (goto-char (match-end 0))
23526 (while (not (looking-at "#\\+END_EXAMPLE"))
23527 (insert ": ")
23528 (beginning-of-line 2)))
23529 (goto-char (point-min))
23530 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
23531 (add-text-properties (match-beginning 0) (match-end 0)
23532 '(org-protected t)))
23533 (while formatters
23534 (setq fmt (pop formatters))
23535 (when (car fmt)
23536 (goto-char (point-min))
23537 (while (re-search-forward (concat "^#\\+" (cadr fmt)
23538 ":[ \t]*\\(.*\\)") nil t)
23539 (replace-match "\\1" t)
23540 (add-text-properties
23541 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
23542 '(org-protected t))))
23543 (goto-char (point-min))
23544 (while (re-search-forward
23545 (concat "^#\\+"
23546 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
23547 (cadddr fmt) "\\>.*\n?") nil t)
23548 (if (car fmt)
23549 (add-text-properties (match-beginning 1) (1+ (match-end 1))
23550 '(org-protected t))
23551 (delete-region (match-beginning 0) (match-end 0))))))
23553 ;; Protect quoted subtrees
23554 (goto-char (point-min))
23555 (while (re-search-forward re-quote nil t)
23556 (goto-char (match-beginning 0))
23557 (end-of-line 1)
23558 (add-text-properties (point) (org-end-of-subtree t)
23559 '(org-protected t)))
23561 ;; Protect verbatim elements
23562 (goto-char (point-min))
23563 (while (re-search-forward org-verbatim-re nil t)
23564 (add-text-properties (match-beginning 4) (match-end 4)
23565 '(org-protected t))
23566 (goto-char (1+ (match-end 4))))
23568 ;; Remove subtrees that are commented
23569 (goto-char (point-min))
23570 (while (re-search-forward re-commented nil t)
23571 (goto-char (match-beginning 0))
23572 (delete-region (point) (org-end-of-subtree t)))
23574 ;; Remove special table lines
23575 (when org-export-table-remove-special-lines
23576 (goto-char (point-min))
23577 (while (re-search-forward "^[ \t]*|" nil t)
23578 (beginning-of-line 1)
23579 (if (or (looking-at "[ \t]*| *[!_^] *|")
23580 (and (looking-at ".*?| *<[0-9]+> *|")
23581 (not (looking-at ".*?| *[^ <|]"))))
23582 (delete-region (max (point-min) (1- (point-at-bol)))
23583 (point-at-eol))
23584 (end-of-line 1))))
23586 ;; Specific LaTeX stuff
23587 (when latexp
23588 (require 'org-export-latex nil)
23589 (org-export-latex-cleaned-string))
23591 (when asciip
23592 (org-export-ascii-clean-string))
23594 ;; Specific HTML stuff
23595 (when htmlp
23596 ;; Convert LaTeX fragments to images
23597 (when (plist-get parameters :LaTeX-fragments)
23598 (org-format-latex
23599 (concat "ltxpng/" (file-name-sans-extension
23600 (file-name-nondirectory
23601 org-current-export-file)))
23602 org-current-export-dir nil "Creating LaTeX image %s"))
23603 (message "Exporting..."))
23605 ;; Remove or replace comments
23606 (goto-char (point-min))
23607 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
23608 (if commentsp
23609 (progn (add-text-properties
23610 (match-beginning 0) (match-end 0) '(org-protected t))
23611 (replace-match (format commentsp (match-string 1)) t t))
23612 (replace-match "")))
23614 ;; Find matches for radio targets and turn them into internal links
23615 (goto-char (point-min))
23616 (when re-radio
23617 (while (re-search-forward re-radio nil t)
23618 (org-if-unprotected
23619 (replace-match "\\1[[\\2]]"))))
23621 ;; Find all links that contain a newline and put them into a single line
23622 (goto-char (point-min))
23623 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
23624 (org-if-unprotected
23625 (replace-match "\\1 \\3")
23626 (goto-char (match-beginning 0))))
23629 ;; Normalize links: Convert angle and plain links into bracket links
23630 ;; Expand link abbreviations
23631 (goto-char (point-min))
23632 (while (re-search-forward re-plain-link nil t)
23633 (goto-char (1- (match-end 0)))
23634 (org-if-unprotected
23635 (let* ((s (concat (match-string 1) "[[" (match-string 2)
23636 ":" (match-string 3) "]]")))
23637 ;; added 'org-link face to links
23638 (put-text-property 0 (length s) 'face 'org-link s)
23639 (replace-match s t t))))
23640 (goto-char (point-min))
23641 (while (re-search-forward re-angle-link nil t)
23642 (goto-char (1- (match-end 0)))
23643 (org-if-unprotected
23644 (let* ((s (concat (match-string 1) "[[" (match-string 2)
23645 ":" (match-string 3) "]]")))
23646 (put-text-property 0 (length s) 'face 'org-link s)
23647 (replace-match s t t))))
23648 (goto-char (point-min))
23649 (while (re-search-forward org-bracket-link-regexp nil t)
23650 (org-if-unprotected
23651 (let* ((s (concat "[[" (setq xx (save-match-data
23652 (org-link-expand-abbrev (match-string 1))))
23654 (if (match-end 3)
23655 (match-string 2)
23656 (concat "[" xx "]"))
23657 "]")))
23658 (put-text-property 0 (length s) 'face 'org-link s)
23659 (replace-match s t t))))
23661 ;; Find multiline emphasis and put them into single line
23662 (when (plist-get parameters :emph-multiline)
23663 (goto-char (point-min))
23664 (while (re-search-forward org-emph-re nil t)
23665 (if (not (= (char-after (match-beginning 3))
23666 (char-after (match-beginning 4))))
23667 (org-if-unprotected
23668 (subst-char-in-region (match-beginning 0) (match-end 0)
23669 ?\n ?\ t)
23670 (goto-char (1- (match-end 0))))
23671 (goto-char (1+ (match-beginning 0))))))
23673 (setq rtn (buffer-string)))
23674 (kill-buffer " org-mode-tmp")
23675 rtn))
23677 (defun org-export-grab-title-from-buffer ()
23678 "Get a title for the current document, from looking at the buffer."
23679 (let ((inhibit-read-only t))
23680 (save-excursion
23681 (goto-char (point-min))
23682 (let ((end (save-excursion (outline-next-heading) (point))))
23683 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
23684 ;; Mark the line so that it will not be exported as normal text.
23685 (org-unmodified
23686 (add-text-properties (match-beginning 0) (match-end 0)
23687 (list :org-license-to-kill t)))
23688 ;; Return the title string
23689 (org-trim (match-string 0)))))))
23691 (defun org-export-get-title-from-subtree ()
23692 "Return subtree title and exclude it from export."
23693 (let (title (m (mark)))
23694 (save-excursion
23695 (goto-char (region-beginning))
23696 (when (and (org-at-heading-p)
23697 (>= (org-end-of-subtree t t) (region-end)))
23698 ;; This is a subtree, we take the title from the first heading
23699 (goto-char (region-beginning))
23700 (looking-at org-todo-line-regexp)
23701 (setq title (match-string 3))
23702 (org-unmodified
23703 (add-text-properties (point) (1+ (point-at-eol))
23704 (list :org-license-to-kill t)))))
23705 title))
23707 (defun org-solidify-link-text (s &optional alist)
23708 "Take link text and make a safe target out of it."
23709 (save-match-data
23710 (let* ((rtn
23711 (mapconcat
23712 'identity
23713 (org-split-string s "[ \t\r\n]+") "--"))
23714 (a (assoc rtn alist)))
23715 (or (cdr a) rtn))))
23717 (defun org-get-min-level (lines)
23718 "Get the minimum level in LINES."
23719 (let ((re "^\\(\\*+\\) ") l min)
23720 (catch 'exit
23721 (while (setq l (pop lines))
23722 (if (string-match re l)
23723 (throw 'exit (org-tr-level (length (match-string 1 l))))))
23724 1)))
23726 ;; Variable holding the vector with section numbers
23727 (defvar org-section-numbers (make-vector org-level-max 0))
23729 (defun org-init-section-numbers ()
23730 "Initialize the vector for the section numbers."
23731 (let* ((level -1)
23732 (numbers (nreverse (org-split-string "" "\\.")))
23733 (depth (1- (length org-section-numbers)))
23734 (i depth) number-string)
23735 (while (>= i 0)
23736 (if (> i level)
23737 (aset org-section-numbers i 0)
23738 (setq number-string (or (car numbers) "0"))
23739 (if (string-match "\\`[A-Z]\\'" number-string)
23740 (aset org-section-numbers i
23741 (- (string-to-char number-string) ?A -1))
23742 (aset org-section-numbers i (string-to-number number-string)))
23743 (pop numbers))
23744 (setq i (1- i)))))
23746 (defun org-section-number (&optional level)
23747 "Return a string with the current section number.
23748 When LEVEL is non-nil, increase section numbers on that level."
23749 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
23750 (when level
23751 (when (> level -1)
23752 (aset org-section-numbers
23753 level (1+ (aref org-section-numbers level))))
23754 (setq idx (1+ level))
23755 (while (<= idx depth)
23756 (if (not (= idx 1))
23757 (aset org-section-numbers idx 0))
23758 (setq idx (1+ idx))))
23759 (setq idx 0)
23760 (while (<= idx depth)
23761 (setq n (aref org-section-numbers idx))
23762 (setq string (concat string (if (not (string= string "")) "." "")
23763 (int-to-string n)))
23764 (setq idx (1+ idx)))
23765 (save-match-data
23766 (if (string-match "\\`\\([@0]\\.\\)+" string)
23767 (setq string (replace-match "" t nil string)))
23768 (if (string-match "\\(\\.0\\)+\\'" string)
23769 (setq string (replace-match "" t nil string))))
23770 string))
23772 ;;; ASCII export
23774 (defvar org-last-level nil) ; dynamically scoped variable
23775 (defvar org-min-level nil) ; dynamically scoped variable
23776 (defvar org-levels-open nil) ; dynamically scoped parameter
23777 (defvar org-ascii-current-indentation nil) ; For communication
23779 (defun org-export-as-ascii (arg)
23780 "Export the outline as a pretty ASCII file.
23781 If there is an active region, export only the region.
23782 The prefix ARG specifies how many levels of the outline should become
23783 underlined headlines. The default is 3."
23784 (interactive "P")
23785 (setq-default org-todo-line-regexp org-todo-line-regexp)
23786 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
23787 (org-infile-export-plist)))
23788 (region-p (org-region-active-p))
23789 (subtree-p
23790 (when region-p
23791 (save-excursion
23792 (goto-char (region-beginning))
23793 (and (org-at-heading-p)
23794 (>= (org-end-of-subtree t t) (region-end))))))
23795 (custom-times org-display-custom-times)
23796 (org-ascii-current-indentation '(0 . 0))
23797 (level 0) line txt
23798 (umax nil)
23799 (umax-toc nil)
23800 (case-fold-search nil)
23801 (filename (concat (file-name-as-directory
23802 (org-export-directory :ascii opt-plist))
23803 (file-name-sans-extension
23804 (or (and subtree-p
23805 (org-entry-get (region-beginning)
23806 "EXPORT_FILE_NAME" t))
23807 (file-name-nondirectory buffer-file-name)))
23808 ".txt"))
23809 (filename (if (equal (file-truename filename)
23810 (file-truename buffer-file-name))
23811 (concat filename ".txt")
23812 filename))
23813 (buffer (find-file-noselect filename))
23814 (org-levels-open (make-vector org-level-max nil))
23815 (odd org-odd-levels-only)
23816 (date (plist-get opt-plist :date))
23817 (author (plist-get opt-plist :author))
23818 (title (or (and subtree-p (org-export-get-title-from-subtree))
23819 (plist-get opt-plist :title)
23820 (and (not
23821 (plist-get opt-plist :skip-before-1st-heading))
23822 (org-export-grab-title-from-buffer))
23823 (file-name-sans-extension
23824 (file-name-nondirectory buffer-file-name))))
23825 (email (plist-get opt-plist :email))
23826 (language (plist-get opt-plist :language))
23827 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
23828 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
23829 (todo nil)
23830 (lang-words nil)
23831 (region
23832 (buffer-substring
23833 (if (org-region-active-p) (region-beginning) (point-min))
23834 (if (org-region-active-p) (region-end) (point-max))))
23835 (lines (org-split-string
23836 (org-cleaned-string-for-export
23837 region
23838 :for-ascii t
23839 :skip-before-1st-heading
23840 (plist-get opt-plist :skip-before-1st-heading)
23841 :drawers (plist-get opt-plist :drawers)
23842 :verbatim-multiline t
23843 :archived-trees
23844 (plist-get opt-plist :archived-trees)
23845 :add-text (plist-get opt-plist :text))
23846 "\n"))
23847 thetoc have-headings first-heading-pos
23848 table-open table-buffer)
23850 (let ((inhibit-read-only t))
23851 (org-unmodified
23852 (remove-text-properties (point-min) (point-max)
23853 '(:org-license-to-kill t))))
23855 (setq org-min-level (org-get-min-level lines))
23856 (setq org-last-level org-min-level)
23857 (org-init-section-numbers)
23859 (find-file-noselect filename)
23861 (setq lang-words (or (assoc language org-export-language-setup)
23862 (assoc "en" org-export-language-setup)))
23863 (switch-to-buffer-other-window buffer)
23864 (erase-buffer)
23865 (fundamental-mode)
23866 ;; create local variables for all options, to make sure all called
23867 ;; functions get the correct information
23868 (mapc (lambda (x)
23869 (set (make-local-variable (cdr x))
23870 (plist-get opt-plist (car x))))
23871 org-export-plist-vars)
23872 (org-set-local 'org-odd-levels-only odd)
23873 (setq umax (if arg (prefix-numeric-value arg)
23874 org-export-headline-levels))
23875 (setq umax-toc (if (integerp org-export-with-toc)
23876 (min org-export-with-toc umax)
23877 umax))
23879 ;; File header
23880 (if title (org-insert-centered title ?=))
23881 (insert "\n")
23882 (if (and (or author email)
23883 org-export-author-info)
23884 (insert (concat (nth 1 lang-words) ": " (or author "")
23885 (if email (concat " <" email ">") "")
23886 "\n")))
23888 (cond
23889 ((and date (string-match "%" date))
23890 (setq date (format-time-string date (current-time))))
23891 (date)
23892 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
23894 (if (and date org-export-time-stamp-file)
23895 (insert (concat (nth 2 lang-words) ": " date"\n")))
23897 (insert "\n\n")
23899 (if org-export-with-toc
23900 (progn
23901 (push (concat (nth 3 lang-words) "\n") thetoc)
23902 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
23903 (mapc '(lambda (line)
23904 (if (string-match org-todo-line-regexp
23905 line)
23906 ;; This is a headline
23907 (progn
23908 (setq have-headings t)
23909 (setq level (- (match-end 1) (match-beginning 1))
23910 level (org-tr-level level)
23911 txt (match-string 3 line)
23912 todo
23913 (or (and org-export-mark-todo-in-toc
23914 (match-beginning 2)
23915 (not (member (match-string 2 line)
23916 org-done-keywords)))
23917 ; TODO, not DONE
23918 (and org-export-mark-todo-in-toc
23919 (= level umax-toc)
23920 (org-search-todo-below
23921 line lines level))))
23922 (setq txt (org-html-expand-for-ascii txt))
23924 (while (string-match org-bracket-link-regexp txt)
23925 (setq txt
23926 (replace-match
23927 (match-string (if (match-end 2) 3 1) txt)
23928 t t txt)))
23930 (if (and (memq org-export-with-tags '(not-in-toc nil))
23931 (string-match
23932 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
23933 txt))
23934 (setq txt (replace-match "" t t txt)))
23935 (if (string-match quote-re0 txt)
23936 (setq txt (replace-match "" t t txt)))
23938 (if org-export-with-section-numbers
23939 (setq txt (concat (org-section-number level)
23940 " " txt)))
23941 (if (<= level umax-toc)
23942 (progn
23943 (push
23944 (concat
23945 (make-string
23946 (* (max 0 (- level org-min-level)) 4) ?\ )
23947 (format (if todo "%s (*)\n" "%s\n") txt))
23948 thetoc)
23949 (setq org-last-level level))
23950 ))))
23951 lines)
23952 (setq thetoc (if have-headings (nreverse thetoc) nil))))
23954 (org-init-section-numbers)
23955 (while (setq line (pop lines))
23956 ;; Remove the quoted HTML tags.
23957 (setq line (org-html-expand-for-ascii line))
23958 ;; Remove targets
23959 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
23960 (setq line (replace-match "" t t line)))
23961 ;; Replace internal links
23962 (while (string-match org-bracket-link-regexp line)
23963 (setq line (replace-match
23964 (if (match-end 3) "[\\3]" "[\\1]")
23965 t nil line)))
23966 (when custom-times
23967 (setq line (org-translate-time line)))
23968 (cond
23969 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
23970 ;; a Headline
23971 (setq first-heading-pos (or first-heading-pos (point)))
23972 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
23973 txt (match-string 2 line))
23974 (org-ascii-level-start level txt umax lines))
23976 ((and org-export-with-tables
23977 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
23978 (if (not table-open)
23979 ;; New table starts
23980 (setq table-open t table-buffer nil))
23981 ;; Accumulate lines
23982 (setq table-buffer (cons line table-buffer))
23983 (when (or (not lines)
23984 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
23985 (car lines))))
23986 (setq table-open nil
23987 table-buffer (nreverse table-buffer))
23988 (insert (mapconcat
23989 (lambda (x)
23990 (org-fix-indentation x org-ascii-current-indentation))
23991 (org-format-table-ascii table-buffer)
23992 "\n") "\n")))
23994 (setq line (org-fix-indentation line org-ascii-current-indentation))
23995 (if (and org-export-with-fixed-width
23996 (string-match "^\\([ \t]*\\)\\(:\\)" line))
23997 (setq line (replace-match "\\1" nil nil line)))
23998 (insert line "\n"))))
24000 (normal-mode)
24002 ;; insert the table of contents
24003 (when thetoc
24004 (goto-char (point-min))
24005 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
24006 (progn
24007 (goto-char (match-beginning 0))
24008 (replace-match ""))
24009 (goto-char first-heading-pos))
24010 (mapc 'insert thetoc)
24011 (or (looking-at "[ \t]*\n[ \t]*\n")
24012 (insert "\n\n")))
24014 ;; Convert whitespace place holders
24015 (goto-char (point-min))
24016 (let (beg end)
24017 (while (setq beg (next-single-property-change (point) 'org-whitespace))
24018 (setq end (next-single-property-change beg 'org-whitespace))
24019 (goto-char beg)
24020 (delete-region beg end)
24021 (insert (make-string (- end beg) ?\ ))))
24023 (save-buffer)
24024 ;; remove display and invisible chars
24025 (let (beg end)
24026 (goto-char (point-min))
24027 (while (setq beg (next-single-property-change (point) 'display))
24028 (setq end (next-single-property-change beg 'display))
24029 (delete-region beg end)
24030 (goto-char beg)
24031 (insert "=>"))
24032 (goto-char (point-min))
24033 (while (setq beg (next-single-property-change (point) 'org-cwidth))
24034 (setq end (next-single-property-change beg 'org-cwidth))
24035 (delete-region beg end)
24036 (goto-char beg)))
24037 (goto-char (point-min))))
24039 (defun org-export-ascii-clean-string ()
24040 "Do extra work for ASCII export"
24041 (goto-char (point-min))
24042 (while (re-search-forward org-verbatim-re nil t)
24043 (goto-char (match-end 2))
24044 (backward-delete-char 1) (insert "'")
24045 (goto-char (match-beginning 2))
24046 (delete-char 1) (insert "`")
24047 (goto-char (match-end 2))))
24049 (defun org-search-todo-below (line lines level)
24050 "Search the subtree below LINE for any TODO entries."
24051 (let ((rest (cdr (memq line lines)))
24052 (re org-todo-line-regexp)
24053 line lv todo)
24054 (catch 'exit
24055 (while (setq line (pop rest))
24056 (if (string-match re line)
24057 (progn
24058 (setq lv (- (match-end 1) (match-beginning 1))
24059 todo (and (match-beginning 2)
24060 (not (member (match-string 2 line)
24061 org-done-keywords))))
24062 ; TODO, not DONE
24063 (if (<= lv level) (throw 'exit nil))
24064 (if todo (throw 'exit t))))))))
24066 (defun org-html-expand-for-ascii (line)
24067 "Handle quoted HTML for ASCII export."
24068 (if org-export-html-expand
24069 (while (string-match "@<[^<>\n]*>" line)
24070 ;; We just remove the tags for now.
24071 (setq line (replace-match "" nil nil line))))
24072 line)
24074 (defun org-insert-centered (s &optional underline)
24075 "Insert the string S centered and underline it with character UNDERLINE."
24076 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
24077 (insert (make-string ind ?\ ) s "\n")
24078 (if underline
24079 (insert (make-string ind ?\ )
24080 (make-string (string-width s) underline)
24081 "\n"))))
24083 (defun org-ascii-level-start (level title umax &optional lines)
24084 "Insert a new level in ASCII export."
24085 (let (char (n (- level umax 1)) (ind 0))
24086 (if (> level umax)
24087 (progn
24088 (insert (make-string (* 2 n) ?\ )
24089 (char-to-string (nth (% n (length org-export-ascii-bullets))
24090 org-export-ascii-bullets))
24091 " " title "\n")
24092 ;; find the indentation of the next non-empty line
24093 (catch 'stop
24094 (while lines
24095 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
24096 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
24097 (throw 'stop (setq ind (org-get-indentation (car lines)))))
24098 (pop lines)))
24099 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
24100 (if (or (not (equal (char-before) ?\n))
24101 (not (equal (char-before (1- (point))) ?\n)))
24102 (insert "\n"))
24103 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
24104 (unless org-export-with-tags
24105 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
24106 (setq title (replace-match "" t t title))))
24107 (if org-export-with-section-numbers
24108 (setq title (concat (org-section-number level) " " title)))
24109 (insert title "\n" (make-string (string-width title) char) "\n")
24110 (setq org-ascii-current-indentation '(0 . 0)))))
24112 (defun org-export-visible (type arg)
24113 "Create a copy of the visible part of the current buffer, and export it.
24114 The copy is created in a temporary buffer and removed after use.
24115 TYPE is the final key (as a string) that also select the export command in
24116 the `C-c C-e' export dispatcher.
24117 As a special case, if the you type SPC at the prompt, the temporary
24118 org-mode file will not be removed but presented to you so that you can
24119 continue to use it. The prefix arg ARG is passed through to the exporting
24120 command."
24121 (interactive
24122 (list (progn
24123 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
24124 (read-char-exclusive))
24125 current-prefix-arg))
24126 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
24127 (error "Invalid export key"))
24128 (let* ((binding (cdr (assoc type
24129 '((?a . org-export-as-ascii)
24130 (?\C-a . org-export-as-ascii)
24131 (?b . org-export-as-html-and-open)
24132 (?\C-b . org-export-as-html-and-open)
24133 (?h . org-export-as-html)
24134 (?H . org-export-as-html-to-buffer)
24135 (?R . org-export-region-as-html)
24136 (?x . org-export-as-xoxo)))))
24137 (keepp (equal type ?\ ))
24138 (file buffer-file-name)
24139 (buffer (get-buffer-create "*Org Export Visible*"))
24140 s e)
24141 ;; Need to hack the drawers here.
24142 (save-excursion
24143 (goto-char (point-min))
24144 (while (re-search-forward org-drawer-regexp nil t)
24145 (goto-char (match-beginning 1))
24146 (or (org-invisible-p) (org-flag-drawer nil))))
24147 (with-current-buffer buffer (erase-buffer))
24148 (save-excursion
24149 (setq s (goto-char (point-min)))
24150 (while (not (= (point) (point-max)))
24151 (goto-char (org-find-invisible))
24152 (append-to-buffer buffer s (point))
24153 (setq s (goto-char (org-find-visible))))
24154 (org-cycle-hide-drawers 'all)
24155 (goto-char (point-min))
24156 (unless keepp
24157 ;; Copy all comment lines to the end, to make sure #+ settings are
24158 ;; still available for the second export step. Kind of a hack, but
24159 ;; does do the trick.
24160 (if (looking-at "#[^\r\n]*")
24161 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
24162 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
24163 (append-to-buffer buffer (1+ (match-beginning 0))
24164 (min (point-max) (1+ (match-end 0))))))
24165 (set-buffer buffer)
24166 (let ((buffer-file-name file)
24167 (org-inhibit-startup t))
24168 (org-mode)
24169 (show-all)
24170 (unless keepp (funcall binding arg))))
24171 (if (not keepp)
24172 (kill-buffer buffer)
24173 (switch-to-buffer-other-window buffer)
24174 (goto-char (point-min)))))
24176 (defun org-find-visible ()
24177 (let ((s (point)))
24178 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24179 (get-char-property s 'invisible)))
24181 (defun org-find-invisible ()
24182 (let ((s (point)))
24183 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24184 (not (get-char-property s 'invisible))))
24187 ;;; HTML export
24189 (defun org-get-current-options ()
24190 "Return a string with current options as keyword options.
24191 Does include HTML export options as well as TODO and CATEGORY stuff."
24192 (format
24193 "#+TITLE: %s
24194 #+AUTHOR: %s
24195 #+EMAIL: %s
24196 #+LANGUAGE: %s
24197 #+TEXT: Some descriptive text to be emitted. Several lines OK.
24198 #+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
24199 #+CATEGORY: %s
24200 #+SEQ_TODO: %s
24201 #+TYP_TODO: %s
24202 #+PRIORITIES: %c %c %c
24203 #+DRAWERS: %s
24204 #+STARTUP: %s %s %s %s %s
24205 #+TAGS: %s
24206 #+ARCHIVE: %s
24207 #+LINK: %s
24209 (buffer-name) (user-full-name) user-mail-address org-export-default-language
24210 org-export-headline-levels
24211 org-export-with-section-numbers
24212 org-export-with-toc
24213 org-export-preserve-breaks
24214 org-export-html-expand
24215 org-export-with-fixed-width
24216 org-export-with-tables
24217 org-export-with-sub-superscripts
24218 org-export-with-special-strings
24219 org-export-with-footnotes
24220 org-export-with-emphasize
24221 org-export-with-TeX-macros
24222 org-export-with-LaTeX-fragments
24223 org-export-skip-text-before-1st-heading
24224 org-export-with-drawers
24225 org-export-with-tags
24226 (file-name-nondirectory buffer-file-name)
24227 "TODO FEEDBACK VERIFY DONE"
24228 "Me Jason Marie DONE"
24229 org-highest-priority org-lowest-priority org-default-priority
24230 (mapconcat 'identity org-drawers " ")
24231 (cdr (assoc org-startup-folded
24232 '((nil . "showall") (t . "overview") (content . "content"))))
24233 (if org-odd-levels-only "odd" "oddeven")
24234 (if org-hide-leading-stars "hidestars" "showstars")
24235 (if org-startup-align-all-tables "align" "noalign")
24236 (cond ((eq t org-log-done) "logdone")
24237 ((not org-log-done) "nologging")
24238 ((listp org-log-done)
24239 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
24240 org-log-done " ")))
24241 (or (mapconcat (lambda (x)
24242 (cond
24243 ((equal '(:startgroup) x) "{")
24244 ((equal '(:endgroup) x) "}")
24245 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
24246 (t (car x))))
24247 (or org-tag-alist (org-get-buffer-tags)) " ") "")
24248 org-archive-location
24249 "org file:~/org/%s.org"
24252 (defun org-insert-export-options-template ()
24253 "Insert into the buffer a template with information for exporting."
24254 (interactive)
24255 (if (not (bolp)) (newline))
24256 (let ((s (org-get-current-options)))
24257 (and (string-match "#\\+CATEGORY" s)
24258 (setq s (substring s 0 (match-beginning 0))))
24259 (insert s)))
24261 (defun org-toggle-fixed-width-section (arg)
24262 "Toggle the fixed-width export.
24263 If there is no active region, the QUOTE keyword at the current headline is
24264 inserted or removed. When present, it causes the text between this headline
24265 and the next to be exported as fixed-width text, and unmodified.
24266 If there is an active region, this command adds or removes a colon as the
24267 first character of this line. If the first character of a line is a colon,
24268 this line is also exported in fixed-width font."
24269 (interactive "P")
24270 (let* ((cc 0)
24271 (regionp (org-region-active-p))
24272 (beg (if regionp (region-beginning) (point)))
24273 (end (if regionp (region-end)))
24274 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
24275 (case-fold-search nil)
24276 (re "[ \t]*\\(:\\)")
24277 off)
24278 (if regionp
24279 (save-excursion
24280 (goto-char beg)
24281 (setq cc (current-column))
24282 (beginning-of-line 1)
24283 (setq off (looking-at re))
24284 (while (> nlines 0)
24285 (setq nlines (1- nlines))
24286 (beginning-of-line 1)
24287 (cond
24288 (arg
24289 (move-to-column cc t)
24290 (insert ":\n")
24291 (forward-line -1))
24292 ((and off (looking-at re))
24293 (replace-match "" t t nil 1))
24294 ((not off) (move-to-column cc t) (insert ":")))
24295 (forward-line 1)))
24296 (save-excursion
24297 (org-back-to-heading)
24298 (if (looking-at (concat outline-regexp
24299 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
24300 (replace-match "" t t nil 1)
24301 (if (looking-at outline-regexp)
24302 (progn
24303 (goto-char (match-end 0))
24304 (insert org-quote-string " "))))))))
24306 (defun org-export-as-html-and-open (arg)
24307 "Export the outline as HTML and immediately open it with a browser.
24308 If there is an active region, export only the region.
24309 The prefix ARG specifies how many levels of the outline should become
24310 headlines. The default is 3. Lower levels will become bulleted lists."
24311 (interactive "P")
24312 (org-export-as-html arg 'hidden)
24313 (org-open-file buffer-file-name))
24315 (defun org-export-as-html-batch ()
24316 "Call `org-export-as-html', may be used in batch processing as
24317 emacs --batch
24318 --load=$HOME/lib/emacs/org.el
24319 --eval \"(setq org-export-headline-levels 2)\"
24320 --visit=MyFile --funcall org-export-as-html-batch"
24321 (org-export-as-html org-export-headline-levels 'hidden))
24323 (defun org-export-as-html-to-buffer (arg)
24324 "Call `org-exort-as-html` with output to a temporary buffer.
24325 No file is created. The prefix ARG is passed through to `org-export-as-html'."
24326 (interactive "P")
24327 (org-export-as-html arg nil nil "*Org HTML Export*")
24328 (switch-to-buffer-other-window "*Org HTML Export*"))
24330 (defun org-replace-region-by-html (beg end)
24331 "Assume the current region has org-mode syntax, and convert it to HTML.
24332 This can be used in any buffer. For example, you could write an
24333 itemized list in org-mode syntax in an HTML buffer and then use this
24334 command to convert it."
24335 (interactive "r")
24336 (let (reg html buf pop-up-frames)
24337 (save-window-excursion
24338 (if (org-mode-p)
24339 (setq html (org-export-region-as-html
24340 beg end t 'string))
24341 (setq reg (buffer-substring beg end)
24342 buf (get-buffer-create "*Org tmp*"))
24343 (with-current-buffer buf
24344 (erase-buffer)
24345 (insert reg)
24346 (org-mode)
24347 (setq html (org-export-region-as-html
24348 (point-min) (point-max) t 'string)))
24349 (kill-buffer buf)))
24350 (delete-region beg end)
24351 (insert html)))
24353 (defun org-export-region-as-html (beg end &optional body-only buffer)
24354 "Convert region from BEG to END in org-mode buffer to HTML.
24355 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
24356 contents, and only produce the region of converted text, useful for
24357 cut-and-paste operations.
24358 If BUFFER is a buffer or a string, use/create that buffer as a target
24359 of the converted HTML. If BUFFER is the symbol `string', return the
24360 produced HTML as a string and leave not buffer behind. For example,
24361 a Lisp program could call this function in the following way:
24363 (setq html (org-export-region-as-html beg end t 'string))
24365 When called interactively, the output buffer is selected, and shown
24366 in a window. A non-interactive call will only retunr the buffer."
24367 (interactive "r\nP")
24368 (when (interactive-p)
24369 (setq buffer "*Org HTML Export*"))
24370 (let ((transient-mark-mode t) (zmacs-regions t)
24371 rtn)
24372 (goto-char end)
24373 (set-mark (point)) ;; to activate the region
24374 (goto-char beg)
24375 (setq rtn (org-export-as-html
24376 nil nil nil
24377 buffer body-only))
24378 (if (fboundp 'deactivate-mark) (deactivate-mark))
24379 (if (and (interactive-p) (bufferp rtn))
24380 (switch-to-buffer-other-window rtn)
24381 rtn)))
24383 (defvar html-table-tag nil) ; dynamically scoped into this.
24384 (defun org-export-as-html (arg &optional hidden ext-plist
24385 to-buffer body-only)
24386 "Export the outline as a pretty HTML file.
24387 If there is an active region, export only the region. The prefix
24388 ARG specifies how many levels of the outline should become
24389 headlines. The default is 3. Lower levels will become bulleted
24390 lists. When HIDDEN is non-nil, don't display the HTML buffer.
24391 EXT-PLIST is a property list with external parameters overriding
24392 org-mode's default settings, but still inferior to file-local
24393 settings. When TO-BUFFER is non-nil, create a buffer with that
24394 name and export to that buffer. If TO-BUFFER is the symbol `string',
24395 don't leave any buffer behind but just return the resulting HTML as
24396 a string. When BODY-ONLY is set, don't produce the file header and footer,
24397 simply return the content of <body>...</body>, without even
24398 the body tags themselves."
24399 (interactive "P")
24401 ;; Make sure we have a file name when we need it.
24402 (when (and (not (or to-buffer body-only))
24403 (not buffer-file-name))
24404 (if (buffer-base-buffer)
24405 (org-set-local 'buffer-file-name
24406 (with-current-buffer (buffer-base-buffer)
24407 buffer-file-name))
24408 (error "Need a file name to be able to export.")))
24410 (message "Exporting...")
24411 (setq-default org-todo-line-regexp org-todo-line-regexp)
24412 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
24413 (setq-default org-done-keywords org-done-keywords)
24414 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
24415 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24416 ext-plist
24417 (org-infile-export-plist)))
24419 (style (plist-get opt-plist :style))
24420 (link-validate (plist-get opt-plist :link-validation-function))
24421 valid thetoc have-headings first-heading-pos
24422 (odd org-odd-levels-only)
24423 (region-p (org-region-active-p))
24424 (subtree-p
24425 (when region-p
24426 (save-excursion
24427 (goto-char (region-beginning))
24428 (and (org-at-heading-p)
24429 (>= (org-end-of-subtree t t) (region-end))))))
24430 ;; The following two are dynamically scoped into other
24431 ;; routines below.
24432 (org-current-export-dir (org-export-directory :html opt-plist))
24433 (org-current-export-file buffer-file-name)
24434 (level 0) (line "") (origline "") txt todo
24435 (umax nil)
24436 (umax-toc nil)
24437 (filename (if to-buffer nil
24438 (concat (file-name-as-directory
24439 (org-export-directory :html opt-plist))
24440 (file-name-sans-extension
24441 (or (and subtree-p
24442 (org-entry-get (region-beginning)
24443 "EXPORT_FILE_NAME" t))
24444 (file-name-nondirectory buffer-file-name)))
24445 "." org-export-html-extension)))
24446 (current-dir (if buffer-file-name
24447 (file-name-directory buffer-file-name)
24448 default-directory))
24449 (buffer (if to-buffer
24450 (cond
24451 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
24452 (t (get-buffer-create to-buffer)))
24453 (find-file-noselect filename)))
24454 (org-levels-open (make-vector org-level-max nil))
24455 (date (plist-get opt-plist :date))
24456 (author (plist-get opt-plist :author))
24457 (title (or (and subtree-p (org-export-get-title-from-subtree))
24458 (plist-get opt-plist :title)
24459 (and (not
24460 (plist-get opt-plist :skip-before-1st-heading))
24461 (org-export-grab-title-from-buffer))
24462 (and buffer-file-name
24463 (file-name-sans-extension
24464 (file-name-nondirectory buffer-file-name)))
24465 "UNTITLED"))
24466 (html-table-tag (plist-get opt-plist :html-table-tag))
24467 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24468 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
24469 (inquote nil)
24470 (infixed nil)
24471 (in-local-list nil)
24472 (local-list-num nil)
24473 (local-list-indent nil)
24474 (llt org-plain-list-ordered-item-terminator)
24475 (email (plist-get opt-plist :email))
24476 (language (plist-get opt-plist :language))
24477 (lang-words nil)
24478 (target-alist nil) tg
24479 (head-count 0) cnt
24480 (start 0)
24481 (coding-system (and (boundp 'buffer-file-coding-system)
24482 buffer-file-coding-system))
24483 (coding-system-for-write (or org-export-html-coding-system
24484 coding-system))
24485 (save-buffer-coding-system (or org-export-html-coding-system
24486 coding-system))
24487 (charset (and coding-system-for-write
24488 (fboundp 'coding-system-get)
24489 (coding-system-get coding-system-for-write
24490 'mime-charset)))
24491 (region
24492 (buffer-substring
24493 (if region-p (region-beginning) (point-min))
24494 (if region-p (region-end) (point-max))))
24495 (lines
24496 (org-split-string
24497 (org-cleaned-string-for-export
24498 region
24499 :emph-multiline t
24500 :for-html t
24501 :skip-before-1st-heading
24502 (plist-get opt-plist :skip-before-1st-heading)
24503 :drawers (plist-get opt-plist :drawers)
24504 :archived-trees
24505 (plist-get opt-plist :archived-trees)
24506 :add-text
24507 (plist-get opt-plist :text)
24508 :LaTeX-fragments
24509 (plist-get opt-plist :LaTeX-fragments))
24510 "[\r\n]"))
24511 table-open type
24512 table-buffer table-orig-buffer
24513 ind start-is-num starter didclose
24514 rpl path desc descp desc1 desc2 link
24517 (let ((inhibit-read-only t))
24518 (org-unmodified
24519 (remove-text-properties (point-min) (point-max)
24520 '(:org-license-to-kill t))))
24522 (message "Exporting...")
24524 (setq org-min-level (org-get-min-level lines))
24525 (setq org-last-level org-min-level)
24526 (org-init-section-numbers)
24528 (cond
24529 ((and date (string-match "%" date))
24530 (setq date (format-time-string date (current-time))))
24531 (date)
24532 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24534 ;; Get the language-dependent settings
24535 (setq lang-words (or (assoc language org-export-language-setup)
24536 (assoc "en" org-export-language-setup)))
24538 ;; Switch to the output buffer
24539 (set-buffer buffer)
24540 (erase-buffer)
24541 (fundamental-mode)
24543 (and (fboundp 'set-buffer-file-coding-system)
24544 (set-buffer-file-coding-system coding-system-for-write))
24546 (let ((case-fold-search nil)
24547 (org-odd-levels-only odd))
24548 ;; create local variables for all options, to make sure all called
24549 ;; functions get the correct information
24550 (mapc (lambda (x)
24551 (set (make-local-variable (cdr x))
24552 (plist-get opt-plist (car x))))
24553 org-export-plist-vars)
24554 (setq umax (if arg (prefix-numeric-value arg)
24555 org-export-headline-levels))
24556 (setq umax-toc (if (integerp org-export-with-toc)
24557 (min org-export-with-toc umax)
24558 umax))
24559 (unless body-only
24560 ;; File header
24561 (insert (format
24562 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
24563 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
24564 <html xmlns=\"http://www.w3.org/1999/xhtml\"
24565 lang=\"%s\" xml:lang=\"%s\">
24566 <head>
24567 <title>%s</title>
24568 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
24569 <meta name=\"generator\" content=\"Org-mode\"/>
24570 <meta name=\"generated\" content=\"%s\"/>
24571 <meta name=\"author\" content=\"%s\"/>
24573 </head><body>
24575 language language (org-html-expand title)
24576 (or charset "iso-8859-1") date author style))
24578 (insert (or (plist-get opt-plist :preamble) ""))
24580 (when (plist-get opt-plist :auto-preamble)
24581 (if title (insert (format org-export-html-title-format
24582 (org-html-expand title))))))
24584 (if (and org-export-with-toc (not body-only))
24585 (progn
24586 (push (format "<h%d>%s</h%d>\n"
24587 org-export-html-toplevel-hlevel
24588 (nth 3 lang-words)
24589 org-export-html-toplevel-hlevel)
24590 thetoc)
24591 (push "<ul>\n<li>" thetoc)
24592 (setq lines
24593 (mapcar '(lambda (line)
24594 (if (string-match org-todo-line-regexp line)
24595 ;; This is a headline
24596 (progn
24597 (setq have-headings t)
24598 (setq level (- (match-end 1) (match-beginning 1))
24599 level (org-tr-level level)
24600 txt (save-match-data
24601 (org-html-expand
24602 (org-export-cleanup-toc-line
24603 (match-string 3 line))))
24604 todo
24605 (or (and org-export-mark-todo-in-toc
24606 (match-beginning 2)
24607 (not (member (match-string 2 line)
24608 org-done-keywords)))
24609 ; TODO, not DONE
24610 (and org-export-mark-todo-in-toc
24611 (= level umax-toc)
24612 (org-search-todo-below
24613 line lines level))))
24614 (if (string-match
24615 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
24616 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
24617 (if (string-match quote-re0 txt)
24618 (setq txt (replace-match "" t t txt)))
24619 (if org-export-with-section-numbers
24620 (setq txt (concat (org-section-number level)
24621 " " txt)))
24622 (if (<= level (max umax umax-toc))
24623 (setq head-count (+ head-count 1)))
24624 (if (<= level umax-toc)
24625 (progn
24626 (if (> level org-last-level)
24627 (progn
24628 (setq cnt (- level org-last-level))
24629 (while (>= (setq cnt (1- cnt)) 0)
24630 (push "\n<ul>\n<li>" thetoc))
24631 (push "\n" thetoc)))
24632 (if (< level org-last-level)
24633 (progn
24634 (setq cnt (- org-last-level level))
24635 (while (>= (setq cnt (1- cnt)) 0)
24636 (push "</li>\n</ul>" thetoc))
24637 (push "\n" thetoc)))
24638 ;; Check for targets
24639 (while (string-match org-target-regexp line)
24640 (setq tg (match-string 1 line)
24641 line (replace-match
24642 (concat "@<span class=\"target\">" tg "@</span> ")
24643 t t line))
24644 (push (cons (org-solidify-link-text tg)
24645 (format "sec-%d" head-count))
24646 target-alist))
24647 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
24648 (setq txt (replace-match "" t t txt)))
24649 (push
24650 (format
24651 (if todo
24652 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
24653 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
24654 head-count txt) thetoc)
24656 (setq org-last-level level))
24658 line)
24659 lines))
24660 (while (> org-last-level (1- org-min-level))
24661 (setq org-last-level (1- org-last-level))
24662 (push "</li>\n</ul>\n" thetoc))
24663 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24665 (setq head-count 0)
24666 (org-init-section-numbers)
24668 (while (setq line (pop lines) origline line)
24669 (catch 'nextline
24671 ;; end of quote section?
24672 (when (and inquote (string-match "^\\*+ " line))
24673 (insert "</pre>\n")
24674 (setq inquote nil))
24675 ;; inside a quote section?
24676 (when inquote
24677 (insert (org-html-protect line) "\n")
24678 (throw 'nextline nil))
24680 ;; verbatim lines
24681 (when (and org-export-with-fixed-width
24682 (string-match "^[ \t]*:\\(.*\\)" line))
24683 (when (not infixed)
24684 (setq infixed t)
24685 (insert "<pre>\n"))
24686 (insert (org-html-protect (match-string 1 line)) "\n")
24687 (when (and lines
24688 (not (string-match "^[ \t]*\\(:.*\\)"
24689 (car lines))))
24690 (setq infixed nil)
24691 (insert "</pre>\n"))
24692 (throw 'nextline nil))
24694 ;; Protected HTML
24695 (when (get-text-property 0 'org-protected line)
24696 (let (par)
24697 (when (re-search-backward
24698 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
24699 (setq par (match-string 1))
24700 (replace-match "\\2\n"))
24701 (insert line "\n")
24702 (while (and lines
24703 (or (= (length (car lines)) 0)
24704 (get-text-property 0 'org-protected (car lines))))
24705 (insert (pop lines) "\n"))
24706 (and par (insert "<p>\n")))
24707 (throw 'nextline nil))
24709 ;; Horizontal line
24710 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
24711 (insert "\n<hr/>\n")
24712 (throw 'nextline nil))
24714 ;; make targets to anchors
24715 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
24716 (cond
24717 ((match-end 2)
24718 (setq line (replace-match
24719 (concat "@<a name=\""
24720 (org-solidify-link-text (match-string 1 line))
24721 "\">\\nbsp@</a>")
24722 t t line)))
24723 ((and org-export-with-toc (equal (string-to-char line) ?*))
24724 (setq line (replace-match
24725 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
24726 ; (concat "@<i>" (match-string 1 line) "@</i> ")
24727 t t line)))
24729 (setq line (replace-match
24730 (concat "@<a name=\""
24731 (org-solidify-link-text (match-string 1 line))
24732 "\" class=\"target\">" (match-string 1 line) "@</a> ")
24733 t t line)))))
24735 (setq line (org-html-handle-time-stamps line))
24737 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
24738 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
24739 ;; Also handle sub_superscripts and checkboxes
24740 (or (string-match org-table-hline-regexp line)
24741 (setq line (org-html-expand line)))
24743 ;; Format the links
24744 (setq start 0)
24745 (while (string-match org-bracket-link-analytic-regexp line start)
24746 (setq start (match-beginning 0))
24747 (setq type (if (match-end 2) (match-string 2 line) "internal"))
24748 (setq path (match-string 3 line))
24749 (setq desc1 (if (match-end 5) (match-string 5 line))
24750 desc2 (if (match-end 2) (concat type ":" path) path)
24751 descp (and desc1 (not (equal desc1 desc2)))
24752 desc (or desc1 desc2))
24753 ;; Make an image out of the description if that is so wanted
24754 (when (and descp (org-file-image-p desc))
24755 (save-match-data
24756 (if (string-match "^file:" desc)
24757 (setq desc (substring desc (match-end 0)))))
24758 (setq desc (concat "<img src=\"" desc "\"/>")))
24759 ;; FIXME: do we need to unescape here somewhere?
24760 (cond
24761 ((equal type "internal")
24762 (setq rpl
24763 (concat
24764 "<a href=\"#"
24765 (org-solidify-link-text
24766 (save-match-data (org-link-unescape path)) target-alist)
24767 "\">" desc "</a>")))
24768 ((member type '("http" "https"))
24769 ;; standard URL, just check if we need to inline an image
24770 (if (and (or (eq t org-export-html-inline-images)
24771 (and org-export-html-inline-images (not descp)))
24772 (org-file-image-p path))
24773 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
24774 (setq link (concat type ":" path))
24775 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
24776 ((member type '("ftp" "mailto" "news"))
24777 ;; standard URL
24778 (setq link (concat type ":" path))
24779 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
24780 ((string= type "file")
24781 ;; FILE link
24782 (let* ((filename path)
24783 (abs-p (file-name-absolute-p filename))
24784 thefile file-is-image-p search)
24785 (save-match-data
24786 (if (string-match "::\\(.*\\)" filename)
24787 (setq search (match-string 1 filename)
24788 filename (replace-match "" t nil filename)))
24789 (setq valid
24790 (if (functionp link-validate)
24791 (funcall link-validate filename current-dir)
24793 (setq file-is-image-p (org-file-image-p filename))
24794 (setq thefile (if abs-p (expand-file-name filename) filename))
24795 (when (and org-export-html-link-org-files-as-html
24796 (string-match "\\.org$" thefile))
24797 (setq thefile (concat (substring thefile 0
24798 (match-beginning 0))
24799 "." org-export-html-extension))
24800 (if (and search
24801 ;; make sure this is can be used as target search
24802 (not (string-match "^[0-9]*$" search))
24803 (not (string-match "^\\*" search))
24804 (not (string-match "^/.*/$" search)))
24805 (setq thefile (concat thefile "#"
24806 (org-solidify-link-text
24807 (org-link-unescape search)))))
24808 (when (string-match "^file:" desc)
24809 (setq desc (replace-match "" t t desc))
24810 (if (string-match "\\.org$" desc)
24811 (setq desc (replace-match "" t t desc))))))
24812 (setq rpl (if (and file-is-image-p
24813 (or (eq t org-export-html-inline-images)
24814 (and org-export-html-inline-images
24815 (not descp))))
24816 (concat "<img src=\"" thefile "\"/>")
24817 (concat "<a href=\"" thefile "\">" desc "</a>")))
24818 (if (not valid) (setq rpl desc))))
24819 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
24820 (setq rpl (concat "<i>&lt;" type ":"
24821 (save-match-data (org-link-unescape path))
24822 "&gt;</i>"))))
24823 (setq line (replace-match rpl t t line)
24824 start (+ start (length rpl))))
24826 ;; TODO items
24827 (if (and (string-match org-todo-line-regexp line)
24828 (match-beginning 2))
24830 (setq line
24831 (concat (substring line 0 (match-beginning 2))
24832 "<span class=\""
24833 (if (member (match-string 2 line)
24834 org-done-keywords)
24835 "done" "todo")
24836 "\">" (match-string 2 line)
24837 "</span>" (substring line (match-end 2)))))
24839 ;; Does this contain a reference to a footnote?
24840 (when org-export-with-footnotes
24841 (setq start 0)
24842 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
24843 (if (get-text-property (match-beginning 2) 'org-protected line)
24844 (setq start (match-end 2))
24845 (let ((n (match-string 2 line)))
24846 (setq line
24847 (replace-match
24848 (format
24849 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
24850 (match-string 1 line) n n n)
24851 t t line))))))
24853 (cond
24854 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24855 ;; This is a headline
24856 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24857 txt (match-string 2 line))
24858 (if (string-match quote-re0 txt)
24859 (setq txt (replace-match "" t t txt)))
24860 (if (<= level (max umax umax-toc))
24861 (setq head-count (+ head-count 1)))
24862 (when in-local-list
24863 ;; Close any local lists before inserting a new header line
24864 (while local-list-num
24865 (org-close-li)
24866 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
24867 (pop local-list-num))
24868 (setq local-list-indent nil
24869 in-local-list nil))
24870 (setq first-heading-pos (or first-heading-pos (point)))
24871 (org-html-level-start level txt umax
24872 (and org-export-with-toc (<= level umax))
24873 head-count)
24874 ;; QUOTES
24875 (when (string-match quote-re line)
24876 (insert "<pre>")
24877 (setq inquote t)))
24879 ((and org-export-with-tables
24880 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24881 (if (not table-open)
24882 ;; New table starts
24883 (setq table-open t table-buffer nil table-orig-buffer nil))
24884 ;; Accumulate lines
24885 (setq table-buffer (cons line table-buffer)
24886 table-orig-buffer (cons origline table-orig-buffer))
24887 (when (or (not lines)
24888 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24889 (car lines))))
24890 (setq table-open nil
24891 table-buffer (nreverse table-buffer)
24892 table-orig-buffer (nreverse table-orig-buffer))
24893 (org-close-par-maybe)
24894 (insert (org-format-table-html table-buffer table-orig-buffer))))
24896 ;; Normal lines
24897 (when (string-match
24898 (cond
24899 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
24900 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
24901 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
24902 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
24903 line)
24904 (setq ind (org-get-string-indentation line)
24905 start-is-num (match-beginning 4)
24906 starter (if (match-beginning 2)
24907 (substring (match-string 2 line) 0 -1))
24908 line (substring line (match-beginning 5)))
24909 (unless (string-match "[^ \t]" line)
24910 ;; empty line. Pretend indentation is large.
24911 (setq ind (if org-empty-line-terminates-plain-lists
24913 (1+ (or (car local-list-indent) 1)))))
24914 (setq didclose nil)
24915 (while (and in-local-list
24916 (or (and (= ind (car local-list-indent))
24917 (not starter))
24918 (< ind (car local-list-indent))))
24919 (setq didclose t)
24920 (org-close-li)
24921 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
24922 (pop local-list-num) (pop local-list-indent)
24923 (setq in-local-list local-list-indent))
24924 (cond
24925 ((and starter
24926 (or (not in-local-list)
24927 (> ind (car local-list-indent))))
24928 ;; Start new (level of) list
24929 (org-close-par-maybe)
24930 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
24931 (push start-is-num local-list-num)
24932 (push ind local-list-indent)
24933 (setq in-local-list t))
24934 (starter
24935 ;; continue current list
24936 (org-close-li)
24937 (insert "<li>\n"))
24938 (didclose
24939 ;; we did close a list, normal text follows: need <p>
24940 (org-open-par)))
24941 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
24942 (setq line
24943 (replace-match
24944 (if (equal (match-string 1 line) "X")
24945 "<b>[X]</b>"
24946 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
24947 t t line))))
24949 ;; Empty lines start a new paragraph. If hand-formatted lists
24950 ;; are not fully interpreted, lines starting with "-", "+", "*"
24951 ;; also start a new paragraph.
24952 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
24954 ;; Is this the start of a footnote?
24955 (when org-export-with-footnotes
24956 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
24957 (org-close-par-maybe)
24958 (let ((n (match-string 1 line)))
24959 (setq line (replace-match
24960 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
24962 ;; Check if the line break needs to be conserved
24963 (cond
24964 ((string-match "\\\\\\\\[ \t]*$" line)
24965 (setq line (replace-match "<br/>" t t line)))
24966 (org-export-preserve-breaks
24967 (setq line (concat line "<br/>"))))
24969 (insert line "\n")))))
24971 ;; Properly close all local lists and other lists
24972 (when inquote (insert "</pre>\n"))
24973 (when in-local-list
24974 ;; Close any local lists before inserting a new header line
24975 (while local-list-num
24976 (org-close-li)
24977 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
24978 (pop local-list-num))
24979 (setq local-list-indent nil
24980 in-local-list nil))
24981 (org-html-level-start 1 nil umax
24982 (and org-export-with-toc (<= level umax))
24983 head-count)
24985 (unless body-only
24986 (when (plist-get opt-plist :auto-postamble)
24987 (insert "<div id=\"postamble\">")
24988 (when (and org-export-author-info author)
24989 (insert "<p class=\"author\"> "
24990 (nth 1 lang-words) ": " author "\n")
24991 (when email
24992 (if (listp (split-string email ",+ *"))
24993 (mapc (lambda(e)
24994 (insert "<a href=\"mailto:" e "\">&lt;"
24995 e "&gt;</a>\n"))
24996 (split-string email ",+ *"))
24997 (insert "<a href=\"mailto:" email "\">&lt;"
24998 email "&gt;</a>\n")))
24999 (insert "</p>\n"))
25000 (when (and date org-export-time-stamp-file)
25001 (insert "<p class=\"date\"> "
25002 (nth 2 lang-words) ": "
25003 date "</p>\n"))
25004 (insert "</div>"))
25006 (if org-export-html-with-timestamp
25007 (insert org-export-html-html-helper-timestamp))
25008 (insert (or (plist-get opt-plist :postamble) ""))
25009 (insert "</body>\n</html>\n"))
25011 (normal-mode)
25012 (if (eq major-mode default-major-mode) (html-mode))
25014 ;; insert the table of contents
25015 (goto-char (point-min))
25016 (when thetoc
25017 (if (or (re-search-forward
25018 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
25019 (re-search-forward
25020 "\\[TABLE-OF-CONTENTS\\]" nil t))
25021 (progn
25022 (goto-char (match-beginning 0))
25023 (replace-match ""))
25024 (goto-char first-heading-pos)
25025 (when (looking-at "\\s-*</p>")
25026 (goto-char (match-end 0))
25027 (insert "\n")))
25028 (insert "<div id=\"table-of-contents\">\n")
25029 (mapc 'insert thetoc)
25030 (insert "</div>\n"))
25031 ;; remove empty paragraphs and lists
25032 (goto-char (point-min))
25033 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
25034 (replace-match ""))
25035 (goto-char (point-min))
25036 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
25037 (replace-match ""))
25038 ;; Convert whitespace place holders
25039 (goto-char (point-min))
25040 (let (beg end n)
25041 (while (setq beg (next-single-property-change (point) 'org-whitespace))
25042 (setq n (get-text-property beg 'org-whitespace)
25043 end (next-single-property-change beg 'org-whitespace))
25044 (goto-char beg)
25045 (delete-region beg end)
25046 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
25047 (make-string n ?x)))))
25049 (or to-buffer (save-buffer))
25050 (goto-char (point-min))
25051 (message "Exporting... done")
25052 (if (eq to-buffer 'string)
25053 (prog1 (buffer-substring (point-min) (point-max))
25054 (kill-buffer (current-buffer)))
25055 (current-buffer)))))
25057 (defvar org-table-colgroup-info nil)
25058 (defun org-format-table-ascii (lines)
25059 "Format a table for ascii export."
25060 (if (stringp lines)
25061 (setq lines (org-split-string lines "\n")))
25062 (if (not (string-match "^[ \t]*|" (car lines)))
25063 ;; Table made by table.el - test for spanning
25064 lines
25066 ;; A normal org table
25067 ;; Get rid of hlines at beginning and end
25068 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25069 (setq lines (nreverse lines))
25070 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25071 (setq lines (nreverse lines))
25072 (when org-export-table-remove-special-lines
25073 ;; Check if the table has a marking column. If yes remove the
25074 ;; column and the special lines
25075 (setq lines (org-table-clean-before-export lines)))
25076 ;; Get rid of the vertical lines except for grouping
25077 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
25078 rtn line vl1 start)
25079 (while (setq line (pop lines))
25080 (if (string-match org-table-hline-regexp line)
25081 (and (string-match "|\\(.*\\)|" line)
25082 (setq line (replace-match " \\1" t nil line)))
25083 (setq start 0 vl1 vl)
25084 (while (string-match "|" line start)
25085 (setq start (match-end 0))
25086 (or (pop vl1) (setq line (replace-match " " t t line)))))
25087 (push line rtn))
25088 (nreverse rtn))))
25090 (defun org-colgroup-info-to-vline-list (info)
25091 (let (vl new last)
25092 (while info
25093 (setq last new new (pop info))
25094 (if (or (memq last '(:end :startend))
25095 (memq new '(:start :startend)))
25096 (push t vl)
25097 (push nil vl)))
25098 (setq vl (nreverse vl))
25099 (and vl (setcar vl nil))
25100 vl))
25102 (defun org-format-table-html (lines olines)
25103 "Find out which HTML converter to use and return the HTML code."
25104 (if (stringp lines)
25105 (setq lines (org-split-string lines "\n")))
25106 (if (string-match "^[ \t]*|" (car lines))
25107 ;; A normal org table
25108 (org-format-org-table-html lines)
25109 ;; Table made by table.el - test for spanning
25110 (let* ((hlines (delq nil (mapcar
25111 (lambda (x)
25112 (if (string-match "^[ \t]*\\+-" x) x
25113 nil))
25114 lines)))
25115 (first (car hlines))
25116 (ll (and (string-match "\\S-+" first)
25117 (match-string 0 first)))
25118 (re (concat "^[ \t]*" (regexp-quote ll)))
25119 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
25120 hlines))))
25121 (if (and (not spanning)
25122 (not org-export-prefer-native-exporter-for-tables))
25123 ;; We can use my own converter with HTML conversions
25124 (org-format-table-table-html lines)
25125 ;; Need to use the code generator in table.el, with the original text.
25126 (org-format-table-table-html-using-table-generate-source olines)))))
25128 (defun org-format-org-table-html (lines &optional splice)
25129 "Format a table into HTML."
25130 ;; Get rid of hlines at beginning and end
25131 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25132 (setq lines (nreverse lines))
25133 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25134 (setq lines (nreverse lines))
25135 (when org-export-table-remove-special-lines
25136 ;; Check if the table has a marking column. If yes remove the
25137 ;; column and the special lines
25138 (setq lines (org-table-clean-before-export lines)))
25140 (let ((head (and org-export-highlight-first-table-line
25141 (delq nil (mapcar
25142 (lambda (x) (string-match "^[ \t]*|-" x))
25143 (cdr lines)))))
25144 (nlines 0) fnum i
25145 tbopen line fields html gr colgropen)
25146 (if splice (setq head nil))
25147 (unless splice (push (if head "<thead>" "<tbody>") html))
25148 (setq tbopen t)
25149 (while (setq line (pop lines))
25150 (catch 'next-line
25151 (if (string-match "^[ \t]*|-" line)
25152 (progn
25153 (unless splice
25154 (push (if head "</thead>" "</tbody>") html)
25155 (if lines (push "<tbody>" html) (setq tbopen nil)))
25156 (setq head nil) ;; head ends here, first time around
25157 ;; ignore this line
25158 (throw 'next-line t)))
25159 ;; Break the line into fields
25160 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25161 (unless fnum (setq fnum (make-vector (length fields) 0)))
25162 (setq nlines (1+ nlines) i -1)
25163 (push (concat "<tr>"
25164 (mapconcat
25165 (lambda (x)
25166 (setq i (1+ i))
25167 (if (and (< i nlines)
25168 (string-match org-table-number-regexp x))
25169 (incf (aref fnum i)))
25170 (if head
25171 (concat (car org-export-table-header-tags) x
25172 (cdr org-export-table-header-tags))
25173 (concat (car org-export-table-data-tags) x
25174 (cdr org-export-table-data-tags))))
25175 fields "")
25176 "</tr>")
25177 html)))
25178 (unless splice (if tbopen (push "</tbody>" html)))
25179 (unless splice (push "</table>\n" html))
25180 (setq html (nreverse html))
25181 (unless splice
25182 ;; Put in col tags with the alignment (unfortuntely often ignored...)
25183 (push (mapconcat
25184 (lambda (x)
25185 (setq gr (pop org-table-colgroup-info))
25186 (format "%s<col align=\"%s\"></col>%s"
25187 (if (memq gr '(:start :startend))
25188 (prog1
25189 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
25190 (setq colgropen t))
25192 (if (> (/ (float x) nlines) org-table-number-fraction)
25193 "right" "left")
25194 (if (memq gr '(:end :startend))
25195 (progn (setq colgropen nil) "</colgroup>")
25196 "")))
25197 fnum "")
25198 html)
25199 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
25200 (push html-table-tag html))
25201 (concat (mapconcat 'identity html "\n") "\n")))
25203 (defun org-table-clean-before-export (lines)
25204 "Check if the table has a marking column.
25205 If yes remove the column and the special lines."
25206 (setq org-table-colgroup-info nil)
25207 (if (memq nil
25208 (mapcar
25209 (lambda (x) (or (string-match "^[ \t]*|-" x)
25210 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
25211 lines))
25212 (progn
25213 (setq org-table-clean-did-remove-column nil)
25214 (delq nil
25215 (mapcar
25216 (lambda (x)
25217 (cond
25218 ((string-match "^[ \t]*| */ *|" x)
25219 (setq org-table-colgroup-info
25220 (mapcar (lambda (x)
25221 (cond ((member x '("<" "&lt;")) :start)
25222 ((member x '(">" "&gt;")) :end)
25223 ((member x '("<>" "&lt;&gt;")) :startend)
25224 (t nil)))
25225 (org-split-string x "[ \t]*|[ \t]*")))
25226 nil)
25227 (t x)))
25228 lines)))
25229 (setq org-table-clean-did-remove-column t)
25230 (delq nil
25231 (mapcar
25232 (lambda (x)
25233 (cond
25234 ((string-match "^[ \t]*| */ *|" x)
25235 (setq org-table-colgroup-info
25236 (mapcar (lambda (x)
25237 (cond ((member x '("<" "&lt;")) :start)
25238 ((member x '(">" "&gt;")) :end)
25239 ((member x '("<>" "&lt;&gt;")) :startend)
25240 (t nil)))
25241 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
25242 nil)
25243 ((string-match "^[ \t]*| *[!_^/] *|" x)
25244 nil) ; ignore this line
25245 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
25246 (string-match "^\\([ \t]*\\)|[^|]*|" x))
25247 ;; remove the first column
25248 (replace-match "\\1|" t nil x))))
25249 lines))))
25251 (defun org-format-table-table-html (lines)
25252 "Format a table generated by table.el into HTML.
25253 This conversion does *not* use `table-generate-source' from table.el.
25254 This has the advantage that Org-mode's HTML conversions can be used.
25255 But it has the disadvantage, that no cell- or row-spanning is allowed."
25256 (let (line field-buffer
25257 (head org-export-highlight-first-table-line)
25258 fields html empty)
25259 (setq html (concat html-table-tag "\n"))
25260 (while (setq line (pop lines))
25261 (setq empty "&nbsp;")
25262 (catch 'next-line
25263 (if (string-match "^[ \t]*\\+-" line)
25264 (progn
25265 (if field-buffer
25266 (progn
25267 (setq
25268 html
25269 (concat
25270 html
25271 "<tr>"
25272 (mapconcat
25273 (lambda (x)
25274 (if (equal x "") (setq x empty))
25275 (if head
25276 (concat (car org-export-table-header-tags) x
25277 (cdr org-export-table-header-tags))
25278 (concat (car org-export-table-data-tags) x
25279 (cdr org-export-table-data-tags))))
25280 field-buffer "\n")
25281 "</tr>\n"))
25282 (setq head nil)
25283 (setq field-buffer nil)))
25284 ;; Ignore this line
25285 (throw 'next-line t)))
25286 ;; Break the line into fields and store the fields
25287 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25288 (if field-buffer
25289 (setq field-buffer (mapcar
25290 (lambda (x)
25291 (concat x "<br/>" (pop fields)))
25292 field-buffer))
25293 (setq field-buffer fields))))
25294 (setq html (concat html "</table>\n"))
25295 html))
25297 (defun org-format-table-table-html-using-table-generate-source (lines)
25298 "Format a table into html, using `table-generate-source' from table.el.
25299 This has the advantage that cell- or row-spanning is allowed.
25300 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
25301 (require 'table)
25302 (with-current-buffer (get-buffer-create " org-tmp1 ")
25303 (erase-buffer)
25304 (insert (mapconcat 'identity lines "\n"))
25305 (goto-char (point-min))
25306 (if (not (re-search-forward "|[^+]" nil t))
25307 (error "Error processing table"))
25308 (table-recognize-table)
25309 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
25310 (table-generate-source 'html " org-tmp2 ")
25311 (set-buffer " org-tmp2 ")
25312 (buffer-substring (point-min) (point-max))))
25314 (defun org-html-handle-time-stamps (s)
25315 "Format time stamps in string S, or remove them."
25316 (catch 'exit
25317 (let (r b)
25318 (while (string-match org-maybe-keyword-time-regexp s)
25319 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
25320 ;; never export CLOCK
25321 (throw 'exit ""))
25322 (or b (setq b (substring s 0 (match-beginning 0))))
25323 (if (not org-export-with-timestamps)
25324 (setq r (concat r (substring s 0 (match-beginning 0)))
25325 s (substring s (match-end 0)))
25326 (setq r (concat
25327 r (substring s 0 (match-beginning 0))
25328 (if (match-end 1)
25329 (format "@<span class=\"timestamp-kwd\">%s @</span>"
25330 (match-string 1 s)))
25331 (format " @<span class=\"timestamp\">%s@</span>"
25332 (substring
25333 (org-translate-time (match-string 3 s)) 1 -1)))
25334 s (substring s (match-end 0)))))
25335 ;; Line break if line started and ended with time stamp stuff
25336 (if (not r)
25338 (setq r (concat r s))
25339 (unless (string-match "\\S-" (concat b s))
25340 (setq r (concat r "@<br/>")))
25341 r))))
25343 (defun org-html-protect (s)
25344 ;; convert & to &amp;, < to &lt; and > to &gt;
25345 (let ((start 0))
25346 (while (string-match "&" s start)
25347 (setq s (replace-match "&amp;" t t s)
25348 start (1+ (match-beginning 0))))
25349 (while (string-match "<" s)
25350 (setq s (replace-match "&lt;" t t s)))
25351 (while (string-match ">" s)
25352 (setq s (replace-match "&gt;" t t s))))
25355 (defun org-export-cleanup-toc-line (s)
25356 "Remove tags and time staps from lines going into the toc."
25357 (when (memq org-export-with-tags '(not-in-toc nil))
25358 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
25359 (setq s (replace-match "" t t s))))
25360 (when org-export-remove-timestamps-from-toc
25361 (while (string-match org-maybe-keyword-time-regexp s)
25362 (setq s (replace-match "" t t s))))
25363 (while (string-match org-bracket-link-regexp s)
25364 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
25365 t t s)))
25368 (defun org-html-expand (string)
25369 "Prepare STRING for HTML export. Applies all active conversions.
25370 If there are links in the string, don't modify these."
25371 (let* ((re (concat org-bracket-link-regexp "\\|"
25372 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
25373 m s l res)
25374 (while (setq m (string-match re string))
25375 (setq s (substring string 0 m)
25376 l (match-string 0 string)
25377 string (substring string (match-end 0)))
25378 (push (org-html-do-expand s) res)
25379 (push l res))
25380 (push (org-html-do-expand string) res)
25381 (apply 'concat (nreverse res))))
25383 (defun org-html-do-expand (s)
25384 "Apply all active conversions to translate special ASCII to HTML."
25385 (setq s (org-html-protect s))
25386 (if org-export-html-expand
25387 (let ((start 0))
25388 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
25389 (setq s (replace-match "<\\1>" t nil s)))))
25390 (if org-export-with-emphasize
25391 (setq s (org-export-html-convert-emphasize s)))
25392 (if org-export-with-special-strings
25393 (setq s (org-export-html-convert-special-strings s)))
25394 (if org-export-with-sub-superscripts
25395 (setq s (org-export-html-convert-sub-super s)))
25396 (if org-export-with-TeX-macros
25397 (let ((start 0) wd ass)
25398 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
25399 (if (get-text-property (match-beginning 0) 'org-protected s)
25400 (setq start (match-end 0))
25401 (setq wd (match-string 1 s))
25402 (if (setq ass (assoc wd org-html-entities))
25403 (setq s (replace-match (or (cdr ass)
25404 (concat "&" (car ass) ";"))
25405 t t s))
25406 (setq start (+ start (length wd))))))))
25409 (defun org-create-multibrace-regexp (left right n)
25410 "Create a regular expression which will match a balanced sexp.
25411 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
25412 as single character strings.
25413 The regexp returned will match the entire expression including the
25414 delimiters. It will also define a single group which contains the
25415 match except for the outermost delimiters. The maximum depth of
25416 stacked delimiters is N. Escaping delimiters is not possible."
25417 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
25418 (or "\\|")
25419 (re nothing)
25420 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
25421 (while (> n 1)
25422 (setq n (1- n)
25423 re (concat re or next)
25424 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
25425 (concat left "\\(" re "\\)" right)))
25427 (defvar org-match-substring-regexp
25428 (concat
25429 "\\([^\\]\\)\\([_^]\\)\\("
25430 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
25431 "\\|"
25432 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
25433 "\\|"
25434 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
25435 "The regular expression matching a sub- or superscript.")
25437 (defvar org-match-substring-with-braces-regexp
25438 (concat
25439 "\\([^\\]\\)\\([_^]\\)\\("
25440 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
25441 "\\)")
25442 "The regular expression matching a sub- or superscript, forcing braces.")
25444 (defconst org-export-html-special-string-regexps
25445 '(("\\\\-" . "&shy;")
25446 ("---\\([^-]\\)" . "&mdash;\\1")
25447 ("--\\([^-]\\)" . "&ndash;\\1")
25448 ("\\.\\.\\." . "&hellip;"))
25449 "Regular expressions for special string conversion.")
25451 (defun org-export-html-convert-special-strings (string)
25452 "Convert special characters in STRING to HTML."
25453 (let ((all org-export-html-special-string-regexps)
25454 e a re rpl start)
25455 (while (setq a (pop all))
25456 (setq re (car a) rpl (cdr a) start 0)
25457 (while (string-match re string start)
25458 (if (get-text-property (match-beginning 0) 'org-protected string)
25459 (setq start (match-end 0))
25460 (setq string (replace-match rpl t nil string)))))
25461 string))
25463 (defun org-export-html-convert-sub-super (string)
25464 "Convert sub- and superscripts in STRING to HTML."
25465 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
25466 (while (string-match org-match-substring-regexp string s)
25467 (cond
25468 ((and requireb (match-end 8)) (setq s (match-end 2)))
25469 ((get-text-property (match-beginning 2) 'org-protected string)
25470 (setq s (match-end 2)))
25472 (setq s (match-end 1)
25473 key (if (string= (match-string 2 string) "_") "sub" "sup")
25474 c (or (match-string 8 string)
25475 (match-string 6 string)
25476 (match-string 5 string))
25477 string (replace-match
25478 (concat (match-string 1 string)
25479 "<" key ">" c "</" key ">")
25480 t t string)))))
25481 (while (string-match "\\\\\\([_^]\\)" string)
25482 (setq string (replace-match (match-string 1 string) t t string)))
25483 string))
25485 (defun org-export-html-convert-emphasize (string)
25486 "Apply emphasis."
25487 (let ((s 0) rpl)
25488 (while (string-match org-emph-re string s)
25489 (if (not (equal
25490 (substring string (match-beginning 3) (1+ (match-beginning 3)))
25491 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
25492 (setq s (match-beginning 0)
25494 (concat
25495 (match-string 1 string)
25496 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
25497 (match-string 4 string)
25498 (nth 3 (assoc (match-string 3 string)
25499 org-emphasis-alist))
25500 (match-string 5 string))
25501 string (replace-match rpl t t string)
25502 s (+ s (- (length rpl) 2)))
25503 (setq s (1+ s))))
25504 string))
25506 (defvar org-par-open nil)
25507 (defun org-open-par ()
25508 "Insert <p>, but first close previous paragraph if any."
25509 (org-close-par-maybe)
25510 (insert "\n<p>")
25511 (setq org-par-open t))
25512 (defun org-close-par-maybe ()
25513 "Close paragraph if there is one open."
25514 (when org-par-open
25515 (insert "</p>")
25516 (setq org-par-open nil)))
25517 (defun org-close-li ()
25518 "Close <li> if necessary."
25519 (org-close-par-maybe)
25520 (insert "</li>\n"))
25522 (defvar body-only) ; dynamically scoped into this.
25523 (defun org-html-level-start (level title umax with-toc head-count)
25524 "Insert a new level in HTML export.
25525 When TITLE is nil, just close all open levels."
25526 (org-close-par-maybe)
25527 (let ((l org-level-max))
25528 (while (>= l level)
25529 (if (aref org-levels-open (1- l))
25530 (progn
25531 (org-html-level-close l umax)
25532 (aset org-levels-open (1- l) nil)))
25533 (setq l (1- l)))
25534 (when title
25535 ;; If title is nil, this means this function is called to close
25536 ;; all levels, so the rest is done only if title is given
25537 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
25538 (setq title (replace-match
25539 (if org-export-with-tags
25540 (save-match-data
25541 (concat
25542 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
25543 (mapconcat 'identity (org-split-string
25544 (match-string 1 title) ":")
25545 "&nbsp;")
25546 "</span>"))
25548 t t title)))
25549 (if (> level umax)
25550 (progn
25551 (if (aref org-levels-open (1- level))
25552 (progn
25553 (org-close-li)
25554 (insert "<li>" title "<br/>\n"))
25555 (aset org-levels-open (1- level) t)
25556 (org-close-par-maybe)
25557 (insert "<ul>\n<li>" title "<br/>\n")))
25558 (aset org-levels-open (1- level) t)
25559 (if (and org-export-with-section-numbers (not body-only))
25560 (setq title (concat (org-section-number level) " " title)))
25561 (setq level (+ level org-export-html-toplevel-hlevel -1))
25562 (if with-toc
25563 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
25564 level level head-count title level))
25565 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
25566 (org-open-par)))))
25568 (defun org-html-level-close (level max-outline-level)
25569 "Terminate one level in HTML export."
25570 (if (<= level max-outline-level)
25571 (insert "</div>\n")
25572 (org-close-li)
25573 (insert "</ul>\n")))
25575 ;;; iCalendar export
25577 ;;;###autoload
25578 (defun org-export-icalendar-this-file ()
25579 "Export current file as an iCalendar file.
25580 The iCalendar file will be located in the same directory as the Org-mode
25581 file, but with extension `.ics'."
25582 (interactive)
25583 (org-export-icalendar nil buffer-file-name))
25585 ;;;###autoload
25586 (defun org-export-icalendar-all-agenda-files ()
25587 "Export all files in `org-agenda-files' to iCalendar .ics files.
25588 Each iCalendar file will be located in the same directory as the Org-mode
25589 file, but with extension `.ics'."
25590 (interactive)
25591 (apply 'org-export-icalendar nil (org-agenda-files t)))
25593 ;;;###autoload
25594 (defun org-export-icalendar-combine-agenda-files ()
25595 "Export all files in `org-agenda-files' to a single combined iCalendar file.
25596 The file is stored under the name `org-combined-agenda-icalendar-file'."
25597 (interactive)
25598 (apply 'org-export-icalendar t (org-agenda-files t)))
25600 (defun org-export-icalendar (combine &rest files)
25601 "Create iCalendar files for all elements of FILES.
25602 If COMBINE is non-nil, combine all calendar entries into a single large
25603 file and store it under the name `org-combined-agenda-icalendar-file'."
25604 (save-excursion
25605 (org-prepare-agenda-buffers files)
25606 (let* ((dir (org-export-directory
25607 :ical (list :publishing-directory
25608 org-export-publishing-directory)))
25609 file ical-file ical-buffer category started org-agenda-new-buffers)
25611 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
25612 (when combine
25613 (setq ical-file
25614 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
25615 org-combined-agenda-icalendar-file
25616 (expand-file-name org-combined-agenda-icalendar-file dir))
25617 ical-buffer (org-get-agenda-file-buffer ical-file))
25618 (set-buffer ical-buffer) (erase-buffer))
25619 (while (setq file (pop files))
25620 (catch 'nextfile
25621 (org-check-agenda-file file)
25622 (set-buffer (org-get-agenda-file-buffer file))
25623 (unless combine
25624 (setq ical-file (concat (file-name-as-directory dir)
25625 (file-name-sans-extension
25626 (file-name-nondirectory buffer-file-name))
25627 ".ics"))
25628 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
25629 (with-current-buffer ical-buffer (erase-buffer)))
25630 (setq category (or org-category
25631 (file-name-sans-extension
25632 (file-name-nondirectory buffer-file-name))))
25633 (if (symbolp category) (setq category (symbol-name category)))
25634 (let ((standard-output ical-buffer))
25635 (if combine
25636 (and (not started) (setq started t)
25637 (org-start-icalendar-file org-icalendar-combined-name))
25638 (org-start-icalendar-file category))
25639 (org-print-icalendar-entries combine)
25640 (when (or (and combine (not files)) (not combine))
25641 (org-finish-icalendar-file)
25642 (set-buffer ical-buffer)
25643 (save-buffer)
25644 (run-hooks 'org-after-save-iCalendar-file-hook)))))
25645 (org-release-buffers org-agenda-new-buffers))))
25647 (defvar org-after-save-iCalendar-file-hook nil
25648 "Hook run after an iCalendar file has been saved.
25649 The iCalendar buffer is still current when this hook is run.
25650 A good way to use this is to tell a desktop calenndar application to re-read
25651 the iCalendar file.")
25653 (defun org-print-icalendar-entries (&optional combine)
25654 "Print iCalendar entries for the current Org-mode file to `standard-output'.
25655 When COMBINE is non nil, add the category to each line."
25656 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
25657 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
25658 (dts (org-ical-ts-to-string
25659 (format-time-string (cdr org-time-stamp-formats) (current-time))
25660 "DTSTART"))
25661 hd ts ts2 state status (inc t) pos b sexp rrule
25662 scheduledp deadlinep tmp pri category entry location summary desc
25663 (sexp-buffer (get-buffer-create "*ical-tmp*")))
25664 (org-refresh-category-properties)
25665 (save-excursion
25666 (goto-char (point-min))
25667 (while (re-search-forward re1 nil t)
25668 (catch :skip
25669 (org-agenda-skip)
25670 (setq pos (match-beginning 0)
25671 ts (match-string 0)
25672 inc t
25673 hd (org-get-heading)
25674 summary (org-icalendar-cleanup-string
25675 (org-entry-get nil "SUMMARY"))
25676 desc (org-icalendar-cleanup-string
25677 (or (org-entry-get nil "DESCRIPTION")
25678 (and org-icalendar-include-body (org-get-entry)))
25679 t org-icalendar-include-body)
25680 location (org-icalendar-cleanup-string
25681 (org-entry-get nil "LOCATION"))
25682 category (org-get-category))
25683 (if (looking-at re2)
25684 (progn
25685 (goto-char (match-end 0))
25686 (setq ts2 (match-string 1) inc nil))
25687 (setq tmp (buffer-substring (max (point-min)
25688 (- pos org-ds-keyword-length))
25689 pos)
25690 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
25691 (progn
25692 (setq inc nil)
25693 (replace-match "\\1" t nil ts))
25695 deadlinep (string-match org-deadline-regexp tmp)
25696 scheduledp (string-match org-scheduled-regexp tmp)
25697 ;; donep (org-entry-is-done-p)
25699 (if (or (string-match org-tr-regexp hd)
25700 (string-match org-ts-regexp hd))
25701 (setq hd (replace-match "" t t hd)))
25702 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
25703 (setq rrule
25704 (concat "\nRRULE:FREQ="
25705 (cdr (assoc
25706 (match-string 2 ts)
25707 '(("d" . "DAILY")("w" . "WEEKLY")
25708 ("m" . "MONTHLY")("y" . "YEARLY"))))
25709 ";INTERVAL=" (match-string 1 ts)))
25710 (setq rrule ""))
25711 (setq summary (or summary hd))
25712 (if (string-match org-bracket-link-regexp summary)
25713 (setq summary
25714 (replace-match (if (match-end 3)
25715 (match-string 3 summary)
25716 (match-string 1 summary))
25717 t t summary)))
25718 (if deadlinep (setq summary (concat "DL: " summary)))
25719 (if scheduledp (setq summary (concat "S: " summary)))
25720 (if (string-match "\\`<%%" ts)
25721 (with-current-buffer sexp-buffer
25722 (insert (substring ts 1 -1) " " summary "\n"))
25723 (princ (format "BEGIN:VEVENT
25725 %s%s
25726 SUMMARY:%s%s%s
25727 CATEGORIES:%s
25728 END:VEVENT\n"
25729 (org-ical-ts-to-string ts "DTSTART")
25730 (org-ical-ts-to-string ts2 "DTEND" inc)
25731 rrule summary
25732 (if (and desc (string-match "\\S-" desc))
25733 (concat "\nDESCRIPTION: " desc) "")
25734 (if (and location (string-match "\\S-" location))
25735 (concat "\nLOCATION: " location) "")
25736 category)))))
25738 (when (and org-icalendar-include-sexps
25739 (condition-case nil (require 'icalendar) (error nil))
25740 (fboundp 'icalendar-export-region))
25741 ;; Get all the literal sexps
25742 (goto-char (point-min))
25743 (while (re-search-forward "^&?%%(" nil t)
25744 (catch :skip
25745 (org-agenda-skip)
25746 (setq b (match-beginning 0))
25747 (goto-char (1- (match-end 0)))
25748 (forward-sexp 1)
25749 (end-of-line 1)
25750 (setq sexp (buffer-substring b (point)))
25751 (with-current-buffer sexp-buffer
25752 (insert sexp "\n"))
25753 (princ (org-diary-to-ical-string sexp-buffer)))))
25755 (when org-icalendar-include-todo
25756 (goto-char (point-min))
25757 (while (re-search-forward org-todo-line-regexp nil t)
25758 (catch :skip
25759 (org-agenda-skip)
25760 (setq state (match-string 2))
25761 (setq status (if (member state org-done-keywords)
25762 "COMPLETED" "NEEDS-ACTION"))
25763 (when (and state
25764 (or (not (member state org-done-keywords))
25765 (eq org-icalendar-include-todo 'all))
25766 (not (member org-archive-tag (org-get-tags-at)))
25768 (setq hd (match-string 3)
25769 summary (org-icalendar-cleanup-string
25770 (org-entry-get nil "SUMMARY"))
25771 desc (org-icalendar-cleanup-string
25772 (or (org-entry-get nil "DESCRIPTION")
25773 (and org-icalendar-include-body (org-get-entry)))
25774 t org-icalendar-include-body)
25775 location (org-icalendar-cleanup-string
25776 (org-entry-get nil "LOCATION")))
25777 (if (string-match org-bracket-link-regexp hd)
25778 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
25779 (match-string 1 hd))
25780 t t hd)))
25781 (if (string-match org-priority-regexp hd)
25782 (setq pri (string-to-char (match-string 2 hd))
25783 hd (concat (substring hd 0 (match-beginning 1))
25784 (substring hd (match-end 1))))
25785 (setq pri org-default-priority))
25786 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
25787 (- org-lowest-priority org-highest-priority))))))
25789 (princ (format "BEGIN:VTODO
25791 SUMMARY:%s%s%s
25792 CATEGORIES:%s
25793 SEQUENCE:1
25794 PRIORITY:%d
25795 STATUS:%s
25796 END:VTODO\n"
25798 (or summary hd)
25799 (if (and location (string-match "\\S-" location))
25800 (concat "\nLOCATION: " location) "")
25801 (if (and desc (string-match "\\S-" desc))
25802 (concat "\nDESCRIPTION: " desc) "")
25803 category pri status)))))))))
25805 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
25806 "Take out stuff and quote what needs to be quoted.
25807 When IS-BODY is non-nil, assume that this is the body of an item, clean up
25808 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
25809 characters."
25810 (if (not s)
25812 (when is-body
25813 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
25814 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
25815 (while (string-match re s) (setq s (replace-match "" t t s)))
25816 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
25817 (let ((start 0))
25818 (while (string-match "\\([,;\\]\\)" s start)
25819 (setq start (+ (match-beginning 0) 2)
25820 s (replace-match "\\\\\\1" nil nil s))))
25821 (when is-body
25822 (while (string-match "[ \t]*\n[ \t]*" s)
25823 (setq s (replace-match "\\n" t t s))))
25824 (setq s (org-trim s))
25825 (if is-body
25826 (if maxlength
25827 (if (and (numberp maxlength)
25828 (> (length s) maxlength))
25829 (setq s (substring s 0 maxlength)))))
25832 (defun org-get-entry ()
25833 "Clean-up description string."
25834 (save-excursion
25835 (org-back-to-heading t)
25836 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
25838 (defun org-start-icalendar-file (name)
25839 "Start an iCalendar file by inserting the header."
25840 (let ((user user-full-name)
25841 (name (or name "unknown"))
25842 (timezone (cadr (current-time-zone))))
25843 (princ
25844 (format "BEGIN:VCALENDAR
25845 VERSION:2.0
25846 X-WR-CALNAME:%s
25847 PRODID:-//%s//Emacs with Org-mode//EN
25848 X-WR-TIMEZONE:%s
25849 CALSCALE:GREGORIAN\n" name user timezone))))
25851 (defun org-finish-icalendar-file ()
25852 "Finish an iCalendar file by inserting the END statement."
25853 (princ "END:VCALENDAR\n"))
25855 (defun org-ical-ts-to-string (s keyword &optional inc)
25856 "Take a time string S and convert it to iCalendar format.
25857 KEYWORD is added in front, to make a complete line like DTSTART....
25858 When INC is non-nil, increase the hour by two (if time string contains
25859 a time), or the day by one (if it does not contain a time)."
25860 (let ((t1 (org-parse-time-string s 'nodefault))
25861 t2 fmt have-time time)
25862 (if (and (car t1) (nth 1 t1) (nth 2 t1))
25863 (setq t2 t1 have-time t)
25864 (setq t2 (org-parse-time-string s)))
25865 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
25866 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
25867 (when inc
25868 (if have-time
25869 (if org-agenda-default-appointment-duration
25870 (setq mi (+ org-agenda-default-appointment-duration mi))
25871 (setq h (+ 2 h)))
25872 (setq d (1+ d))))
25873 (setq time (encode-time s mi h d m y)))
25874 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
25875 (concat keyword (format-time-string fmt time))))
25877 ;;; XOXO export
25879 (defun org-export-as-xoxo-insert-into (buffer &rest output)
25880 (with-current-buffer buffer
25881 (apply 'insert output)))
25882 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
25884 (defun org-export-as-xoxo (&optional buffer)
25885 "Export the org buffer as XOXO.
25886 The XOXO buffer is named *xoxo-<source buffer name>*"
25887 (interactive (list (current-buffer)))
25888 ;; A quickie abstraction
25890 ;; Output everything as XOXO
25891 (with-current-buffer (get-buffer buffer)
25892 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
25893 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
25894 (org-infile-export-plist)))
25895 (filename (concat (file-name-as-directory
25896 (org-export-directory :xoxo opt-plist))
25897 (file-name-sans-extension
25898 (file-name-nondirectory buffer-file-name))
25899 ".html"))
25900 (out (find-file-noselect filename))
25901 (last-level 1)
25902 (hanging-li nil))
25903 ;; Check the output buffer is empty.
25904 (with-current-buffer out (erase-buffer))
25905 ;; Kick off the output
25906 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
25907 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
25908 (let* ((hd (match-string-no-properties 1))
25909 (level (length hd))
25910 (text (concat
25911 (match-string-no-properties 2)
25912 (save-excursion
25913 (goto-char (match-end 0))
25914 (let ((str ""))
25915 (catch 'loop
25916 (while 't
25917 (forward-line)
25918 (if (looking-at "^[ \t]\\(.*\\)")
25919 (setq str (concat str (match-string-no-properties 1)))
25920 (throw 'loop str)))))))))
25922 ;; Handle level rendering
25923 (cond
25924 ((> level last-level)
25925 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
25927 ((< level last-level)
25928 (dotimes (- (- last-level level) 1)
25929 (if hanging-li
25930 (org-export-as-xoxo-insert-into out "</li>\n"))
25931 (org-export-as-xoxo-insert-into out "</ol>\n"))
25932 (when hanging-li
25933 (org-export-as-xoxo-insert-into out "</li>\n")
25934 (setq hanging-li nil)))
25936 ((equal level last-level)
25937 (if hanging-li
25938 (org-export-as-xoxo-insert-into out "</li>\n")))
25941 (setq last-level level)
25943 ;; And output the new li
25944 (setq hanging-li 't)
25945 (if (equal ?+ (elt text 0))
25946 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
25947 (org-export-as-xoxo-insert-into out "<li>" text))))
25949 ;; Finally finish off the ol
25950 (dotimes (- last-level 1)
25951 (if hanging-li
25952 (org-export-as-xoxo-insert-into out "</li>\n"))
25953 (org-export-as-xoxo-insert-into out "</ol>\n"))
25955 ;; Finish the buffer off and clean it up.
25956 (switch-to-buffer-other-window out)
25957 (indent-region (point-min) (point-max) nil)
25958 (save-buffer)
25959 (goto-char (point-min))
25963 ;;;; Key bindings
25965 ;; Make `C-c C-x' a prefix key
25966 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
25968 ;; TAB key with modifiers
25969 (org-defkey org-mode-map "\C-i" 'org-cycle)
25970 (org-defkey org-mode-map [(tab)] 'org-cycle)
25971 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
25972 (org-defkey org-mode-map [(meta tab)] 'org-complete)
25973 (org-defkey org-mode-map "\M-\t" 'org-complete)
25974 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
25975 ;; The following line is necessary under Suse GNU/Linux
25976 (unless (featurep 'xemacs)
25977 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
25978 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
25979 (define-key org-mode-map [backtab] 'org-shifttab)
25981 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
25982 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
25983 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
25985 ;; Cursor keys with modifiers
25986 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
25987 (org-defkey org-mode-map [(meta right)] 'org-metaright)
25988 (org-defkey org-mode-map [(meta up)] 'org-metaup)
25989 (org-defkey org-mode-map [(meta down)] 'org-metadown)
25991 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
25992 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
25993 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
25994 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
25996 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
25997 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
25998 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
25999 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
26001 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
26002 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
26004 ;;; Extra keys for tty access.
26005 ;; We only set them when really needed because otherwise the
26006 ;; menus don't show the simple keys
26008 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
26009 (not window-system))
26010 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
26011 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
26012 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
26013 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
26014 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
26015 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
26016 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
26017 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
26018 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
26019 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
26020 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
26021 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
26022 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
26023 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
26024 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
26025 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
26026 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
26027 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
26028 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
26029 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
26030 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
26031 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
26033 ;; All the other keys
26035 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
26036 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
26037 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
26038 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
26039 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
26040 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
26041 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
26042 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
26043 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
26044 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
26045 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
26046 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
26047 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
26048 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
26049 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
26050 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
26051 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
26052 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
26053 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
26054 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
26055 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
26056 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
26057 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
26058 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
26059 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
26060 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
26061 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
26062 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
26063 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
26064 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
26065 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
26066 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
26067 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
26068 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
26069 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
26070 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
26071 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
26072 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
26073 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
26074 (org-defkey org-mode-map "\C-c^" 'org-sort)
26075 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
26076 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
26077 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
26078 (org-defkey org-mode-map "\C-m" 'org-return)
26079 (org-defkey org-mode-map "\C-j" 'org-return-indent)
26080 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
26081 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
26082 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
26083 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
26084 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
26085 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
26086 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
26087 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
26088 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
26089 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
26090 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
26091 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
26092 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
26093 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
26094 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
26095 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
26097 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
26098 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
26099 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
26100 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
26102 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
26103 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
26104 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
26105 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
26106 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
26107 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
26108 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
26109 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
26110 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
26111 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
26112 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
26113 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
26115 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
26117 (when (featurep 'xemacs)
26118 (org-defkey org-mode-map 'button3 'popup-mode-menu))
26120 (defsubst org-table-p () (org-at-table-p))
26122 (defun org-self-insert-command (N)
26123 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
26124 If the cursor is in a table looking at whitespace, the whitespace is
26125 overwritten, and the table is not marked as requiring realignment."
26126 (interactive "p")
26127 (if (and (org-table-p)
26128 (progn
26129 ;; check if we blank the field, and if that triggers align
26130 (and org-table-auto-blank-field
26131 (member last-command
26132 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
26133 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
26134 ;; got extra space, this field does not determine column width
26135 (let (org-table-may-need-update) (org-table-blank-field))
26136 ;; no extra space, this field may determine column width
26137 (org-table-blank-field)))
26139 (eq N 1)
26140 (looking-at "[^|\n]* |"))
26141 (let (org-table-may-need-update)
26142 (goto-char (1- (match-end 0)))
26143 (delete-backward-char 1)
26144 (goto-char (match-beginning 0))
26145 (self-insert-command N))
26146 (setq org-table-may-need-update t)
26147 (self-insert-command N)
26148 (org-fix-tags-on-the-fly)))
26150 (defun org-fix-tags-on-the-fly ()
26151 (when (and (equal (char-after (point-at-bol)) ?*)
26152 (org-on-heading-p))
26153 (org-align-tags-here org-tags-column)))
26155 (defun org-delete-backward-char (N)
26156 "Like `delete-backward-char', insert whitespace at field end in tables.
26157 When deleting backwards, in tables this function will insert whitespace in
26158 front of the next \"|\" separator, to keep the table aligned. The table will
26159 still be marked for re-alignment if the field did fill the entire column,
26160 because, in this case the deletion might narrow the column."
26161 (interactive "p")
26162 (if (and (org-table-p)
26163 (eq N 1)
26164 (string-match "|" (buffer-substring (point-at-bol) (point)))
26165 (looking-at ".*?|"))
26166 (let ((pos (point))
26167 (noalign (looking-at "[^|\n\r]* |"))
26168 (c org-table-may-need-update))
26169 (backward-delete-char N)
26170 (skip-chars-forward "^|")
26171 (insert " ")
26172 (goto-char (1- pos))
26173 ;; noalign: if there were two spaces at the end, this field
26174 ;; does not determine the width of the column.
26175 (if noalign (setq org-table-may-need-update c)))
26176 (backward-delete-char N)
26177 (org-fix-tags-on-the-fly)))
26179 (defun org-delete-char (N)
26180 "Like `delete-char', but insert whitespace at field end in tables.
26181 When deleting characters, in tables this function will insert whitespace in
26182 front of the next \"|\" separator, to keep the table aligned. The table will
26183 still be marked for re-alignment if the field did fill the entire column,
26184 because, in this case the deletion might narrow the column."
26185 (interactive "p")
26186 (if (and (org-table-p)
26187 (not (bolp))
26188 (not (= (char-after) ?|))
26189 (eq N 1))
26190 (if (looking-at ".*?|")
26191 (let ((pos (point))
26192 (noalign (looking-at "[^|\n\r]* |"))
26193 (c org-table-may-need-update))
26194 (replace-match (concat
26195 (substring (match-string 0) 1 -1)
26196 " |"))
26197 (goto-char pos)
26198 ;; noalign: if there were two spaces at the end, this field
26199 ;; does not determine the width of the column.
26200 (if noalign (setq org-table-may-need-update c)))
26201 (delete-char N))
26202 (delete-char N)
26203 (org-fix-tags-on-the-fly)))
26205 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
26206 (put 'org-self-insert-command 'delete-selection t)
26207 (put 'orgtbl-self-insert-command 'delete-selection t)
26208 (put 'org-delete-char 'delete-selection 'supersede)
26209 (put 'org-delete-backward-char 'delete-selection 'supersede)
26211 ;; Make `flyspell-mode' delay after some commands
26212 (put 'org-self-insert-command 'flyspell-delayed t)
26213 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
26214 (put 'org-delete-char 'flyspell-delayed t)
26215 (put 'org-delete-backward-char 'flyspell-delayed t)
26217 ;; Make pabbrev-mode expand after org-mode commands
26218 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
26219 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
26221 ;; How to do this: Measure non-white length of current string
26222 ;; If equal to column width, we should realign.
26224 (defun org-remap (map &rest commands)
26225 "In MAP, remap the functions given in COMMANDS.
26226 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
26227 (let (new old)
26228 (while commands
26229 (setq old (pop commands) new (pop commands))
26230 (if (fboundp 'command-remapping)
26231 (org-defkey map (vector 'remap old) new)
26232 (substitute-key-definition old new map global-map)))))
26234 (when (eq org-enable-table-editor 'optimized)
26235 ;; If the user wants maximum table support, we need to hijack
26236 ;; some standard editing functions
26237 (org-remap org-mode-map
26238 'self-insert-command 'org-self-insert-command
26239 'delete-char 'org-delete-char
26240 'delete-backward-char 'org-delete-backward-char)
26241 (org-defkey org-mode-map "|" 'org-force-self-insert))
26243 (defun org-shiftcursor-error ()
26244 "Throw an error because Shift-Cursor command was applied in wrong context."
26245 (error "This command is active in special context like tables, headlines or timestamps"))
26247 (defun org-shifttab (&optional arg)
26248 "Global visibility cycling or move to previous table field.
26249 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
26250 on context.
26251 See the individual commands for more information."
26252 (interactive "P")
26253 (cond
26254 ((org-at-table-p) (call-interactively 'org-table-previous-field))
26255 (arg (message "Content view to level: ")
26256 (org-content (prefix-numeric-value arg))
26257 (setq org-cycle-global-status 'overview))
26258 (t (call-interactively 'org-global-cycle))))
26260 (defun org-shiftmetaleft ()
26261 "Promote subtree or delete table column.
26262 Calls `org-promote-subtree', `org-outdent-item',
26263 or `org-table-delete-column', depending on context.
26264 See the individual commands for more information."
26265 (interactive)
26266 (cond
26267 ((org-at-table-p) (call-interactively 'org-table-delete-column))
26268 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
26269 ((org-at-item-p) (call-interactively 'org-outdent-item))
26270 (t (org-shiftcursor-error))))
26272 (defun org-shiftmetaright ()
26273 "Demote subtree or insert table column.
26274 Calls `org-demote-subtree', `org-indent-item',
26275 or `org-table-insert-column', depending on context.
26276 See the individual commands for more information."
26277 (interactive)
26278 (cond
26279 ((org-at-table-p) (call-interactively 'org-table-insert-column))
26280 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
26281 ((org-at-item-p) (call-interactively 'org-indent-item))
26282 (t (org-shiftcursor-error))))
26284 (defun org-shiftmetaup (&optional arg)
26285 "Move subtree up or kill table row.
26286 Calls `org-move-subtree-up' or `org-table-kill-row' or
26287 `org-move-item-up' depending on context. See the individual commands
26288 for more information."
26289 (interactive "P")
26290 (cond
26291 ((org-at-table-p) (call-interactively 'org-table-kill-row))
26292 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26293 ((org-at-item-p) (call-interactively 'org-move-item-up))
26294 (t (org-shiftcursor-error))))
26295 (defun org-shiftmetadown (&optional arg)
26296 "Move subtree down or insert table row.
26297 Calls `org-move-subtree-down' or `org-table-insert-row' or
26298 `org-move-item-down', depending on context. See the individual
26299 commands for more information."
26300 (interactive "P")
26301 (cond
26302 ((org-at-table-p) (call-interactively 'org-table-insert-row))
26303 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26304 ((org-at-item-p) (call-interactively 'org-move-item-down))
26305 (t (org-shiftcursor-error))))
26307 (defun org-metaleft (&optional arg)
26308 "Promote heading or move table column to left.
26309 Calls `org-do-promote' or `org-table-move-column', depending on context.
26310 With no specific context, calls the Emacs default `backward-word'.
26311 See the individual commands for more information."
26312 (interactive "P")
26313 (cond
26314 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
26315 ((or (org-on-heading-p) (org-region-active-p))
26316 (call-interactively 'org-do-promote))
26317 ((org-at-item-p) (call-interactively 'org-outdent-item))
26318 (t (call-interactively 'backward-word))))
26320 (defun org-metaright (&optional arg)
26321 "Demote subtree or move table column to right.
26322 Calls `org-do-demote' or `org-table-move-column', depending on context.
26323 With no specific context, calls the Emacs default `forward-word'.
26324 See the individual commands for more information."
26325 (interactive "P")
26326 (cond
26327 ((org-at-table-p) (call-interactively 'org-table-move-column))
26328 ((or (org-on-heading-p) (org-region-active-p))
26329 (call-interactively 'org-do-demote))
26330 ((org-at-item-p) (call-interactively 'org-indent-item))
26331 (t (call-interactively 'forward-word))))
26333 (defun org-metaup (&optional arg)
26334 "Move subtree up or move table row up.
26335 Calls `org-move-subtree-up' or `org-table-move-row' or
26336 `org-move-item-up', depending on context. See the individual commands
26337 for more information."
26338 (interactive "P")
26339 (cond
26340 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
26341 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26342 ((org-at-item-p) (call-interactively 'org-move-item-up))
26343 (t (transpose-lines 1) (beginning-of-line -1))))
26345 (defun org-metadown (&optional arg)
26346 "Move subtree down or move table row down.
26347 Calls `org-move-subtree-down' or `org-table-move-row' or
26348 `org-move-item-down', depending on context. See the individual
26349 commands for more information."
26350 (interactive "P")
26351 (cond
26352 ((org-at-table-p) (call-interactively 'org-table-move-row))
26353 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26354 ((org-at-item-p) (call-interactively 'org-move-item-down))
26355 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
26357 (defun org-shiftup (&optional arg)
26358 "Increase item in timestamp or increase priority of current headline.
26359 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
26360 depending on context. See the individual commands for more information."
26361 (interactive "P")
26362 (cond
26363 ((org-at-timestamp-p t)
26364 (call-interactively (if org-edit-timestamp-down-means-later
26365 'org-timestamp-down 'org-timestamp-up)))
26366 ((org-on-heading-p) (call-interactively 'org-priority-up))
26367 ((org-at-item-p) (call-interactively 'org-previous-item))
26368 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
26370 (defun org-shiftdown (&optional arg)
26371 "Decrease item in timestamp or decrease priority of current headline.
26372 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
26373 depending on context. See the individual commands for more information."
26374 (interactive "P")
26375 (cond
26376 ((org-at-timestamp-p t)
26377 (call-interactively (if org-edit-timestamp-down-means-later
26378 'org-timestamp-up 'org-timestamp-down)))
26379 ((org-on-heading-p) (call-interactively 'org-priority-down))
26380 (t (call-interactively 'org-next-item))))
26382 (defun org-shiftright ()
26383 "Next TODO keyword or timestamp one day later, depending on context."
26384 (interactive)
26385 (cond
26386 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
26387 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
26388 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
26389 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
26390 (t (org-shiftcursor-error))))
26392 (defun org-shiftleft ()
26393 "Previous TODO keyword or timestamp one day earlier, depending on context."
26394 (interactive)
26395 (cond
26396 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
26397 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
26398 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
26399 ((org-at-property-p)
26400 (call-interactively 'org-property-previous-allowed-value))
26401 (t (org-shiftcursor-error))))
26403 (defun org-shiftcontrolright ()
26404 "Switch to next TODO set."
26405 (interactive)
26406 (cond
26407 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
26408 (t (org-shiftcursor-error))))
26410 (defun org-shiftcontrolleft ()
26411 "Switch to previous TODO set."
26412 (interactive)
26413 (cond
26414 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
26415 (t (org-shiftcursor-error))))
26417 (defun org-ctrl-c-ret ()
26418 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
26419 (interactive)
26420 (cond
26421 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
26422 (t (call-interactively 'org-insert-heading))))
26424 (defun org-copy-special ()
26425 "Copy region in table or copy current subtree.
26426 Calls `org-table-copy' or `org-copy-subtree', depending on context.
26427 See the individual commands for more information."
26428 (interactive)
26429 (call-interactively
26430 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
26432 (defun org-cut-special ()
26433 "Cut region in table or cut current subtree.
26434 Calls `org-table-copy' or `org-cut-subtree', depending on context.
26435 See the individual commands for more information."
26436 (interactive)
26437 (call-interactively
26438 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
26440 (defun org-paste-special (arg)
26441 "Paste rectangular region into table, or past subtree relative to level.
26442 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
26443 See the individual commands for more information."
26444 (interactive "P")
26445 (if (org-at-table-p)
26446 (org-table-paste-rectangle)
26447 (org-paste-subtree arg)))
26449 (defun org-ctrl-c-ctrl-c (&optional arg)
26450 "Set tags in headline, or update according to changed information at point.
26452 This command does many different things, depending on context:
26454 - If the cursor is in a headline, prompt for tags and insert them
26455 into the current line, aligned to `org-tags-column'. When called
26456 with prefix arg, realign all tags in the current buffer.
26458 - If the cursor is in one of the special #+KEYWORD lines, this
26459 triggers scanning the buffer for these lines and updating the
26460 information.
26462 - If the cursor is inside a table, realign the table. This command
26463 works even if the automatic table editor has been turned off.
26465 - If the cursor is on a #+TBLFM line, re-apply the formulas to
26466 the entire table.
26468 - If the cursor is a the beginning of a dynamic block, update it.
26470 - If the cursor is inside a table created by the table.el package,
26471 activate that table.
26473 - If the current buffer is a remember buffer, close note and file it.
26474 with a prefix argument, file it without further interaction to the default
26475 location.
26477 - If the cursor is on a <<<target>>>, update radio targets and corresponding
26478 links in this buffer.
26480 - If the cursor is on a numbered item in a plain list, renumber the
26481 ordered list.
26483 - If the cursor is on a checkbox, toggle it."
26484 (interactive "P")
26485 (let ((org-enable-table-editor t))
26486 (cond
26487 ((or org-clock-overlays
26488 org-occur-highlights
26489 org-latex-fragment-image-overlays)
26490 (org-remove-clock-overlays)
26491 (org-remove-occur-highlights)
26492 (org-remove-latex-fragment-image-overlays)
26493 (message "Temporary highlights/overlays removed from current buffer"))
26494 ((and (local-variable-p 'org-finish-function (current-buffer))
26495 (fboundp org-finish-function))
26496 (funcall org-finish-function))
26497 ((org-at-property-p)
26498 (call-interactively 'org-property-action))
26499 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
26500 ((org-on-heading-p) (call-interactively 'org-set-tags))
26501 ((org-at-table.el-p)
26502 (require 'table)
26503 (beginning-of-line 1)
26504 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
26505 (call-interactively 'table-recognize-table))
26506 ((org-at-table-p)
26507 (org-table-maybe-eval-formula)
26508 (if arg
26509 (call-interactively 'org-table-recalculate)
26510 (org-table-maybe-recalculate-line))
26511 (call-interactively 'org-table-align))
26512 ((org-at-item-checkbox-p)
26513 (call-interactively 'org-toggle-checkbox))
26514 ((org-at-item-p)
26515 (call-interactively 'org-maybe-renumber-ordered-list))
26516 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
26517 ;; Dynamic block
26518 (beginning-of-line 1)
26519 (org-update-dblock))
26520 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
26521 (cond
26522 ((equal (match-string 1) "TBLFM")
26523 ;; Recalculate the table before this line
26524 (save-excursion
26525 (beginning-of-line 1)
26526 (skip-chars-backward " \r\n\t")
26527 (if (org-at-table-p)
26528 (org-call-with-arg 'org-table-recalculate t))))
26530 (call-interactively 'org-mode-restart))))
26531 (t (error "C-c C-c can do nothing useful at this location.")))))
26533 (defun org-mode-restart ()
26534 "Restart Org-mode, to scan again for special lines.
26535 Also updates the keyword regular expressions."
26536 (interactive)
26537 (let ((org-inhibit-startup t)) (org-mode))
26538 (message "Org-mode restarted to refresh keyword and special line setup"))
26540 (defun org-kill-note-or-show-branches ()
26541 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
26542 (interactive)
26543 (if (not org-finish-function)
26544 (call-interactively 'show-branches)
26545 (let ((org-note-abort t))
26546 (funcall org-finish-function))))
26548 (defun org-return (&optional indent)
26549 "Goto next table row or insert a newline.
26550 Calls `org-table-next-row' or `newline', depending on context.
26551 See the individual commands for more information."
26552 (interactive)
26553 (cond
26554 ((bobp) (if indent (newline-and-indent) (newline)))
26555 ((org-at-table-p)
26556 (org-table-justify-field-maybe)
26557 (call-interactively 'org-table-next-row))
26558 (t (if indent (newline-and-indent) (newline)))))
26560 (defun org-return-indent ()
26561 (interactive)
26562 "Goto next table row or insert a newline and indent.
26563 Calls `org-table-next-row' or `newline-and-indent', depending on
26564 context. See the individual commands for more information."
26565 (org-return t))
26567 (defun org-ctrl-c-minus ()
26568 "Insert separator line in table or modify bullet type in list.
26569 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
26570 depending on context."
26571 (interactive)
26572 (cond
26573 ((org-at-table-p)
26574 (call-interactively 'org-table-insert-hline))
26575 ((org-on-heading-p)
26576 ;; Convert to item
26577 (save-excursion
26578 (beginning-of-line 1)
26579 (if (looking-at "\\*+ ")
26580 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
26581 ((org-in-item-p)
26582 (call-interactively 'org-cycle-list-bullet))
26583 (t (error "`C-c -' does have no function here."))))
26585 (defun org-meta-return (&optional arg)
26586 "Insert a new heading or wrap a region in a table.
26587 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
26588 See the individual commands for more information."
26589 (interactive "P")
26590 (cond
26591 ((org-at-table-p)
26592 (call-interactively 'org-table-wrap-region))
26593 (t (call-interactively 'org-insert-heading))))
26595 ;;; Menu entries
26597 ;; Define the Org-mode menus
26598 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
26599 '("Tbl"
26600 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
26601 ["Next Field" org-cycle (org-at-table-p)]
26602 ["Previous Field" org-shifttab (org-at-table-p)]
26603 ["Next Row" org-return (org-at-table-p)]
26604 "--"
26605 ["Blank Field" org-table-blank-field (org-at-table-p)]
26606 ["Edit Field" org-table-edit-field (org-at-table-p)]
26607 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
26608 "--"
26609 ("Column"
26610 ["Move Column Left" org-metaleft (org-at-table-p)]
26611 ["Move Column Right" org-metaright (org-at-table-p)]
26612 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
26613 ["Insert Column" org-shiftmetaright (org-at-table-p)])
26614 ("Row"
26615 ["Move Row Up" org-metaup (org-at-table-p)]
26616 ["Move Row Down" org-metadown (org-at-table-p)]
26617 ["Delete Row" org-shiftmetaup (org-at-table-p)]
26618 ["Insert Row" org-shiftmetadown (org-at-table-p)]
26619 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
26620 "--"
26621 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
26622 ("Rectangle"
26623 ["Copy Rectangle" org-copy-special (org-at-table-p)]
26624 ["Cut Rectangle" org-cut-special (org-at-table-p)]
26625 ["Paste Rectangle" org-paste-special (org-at-table-p)]
26626 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
26627 "--"
26628 ("Calculate"
26629 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
26630 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
26631 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
26632 "--"
26633 ["Recalculate line" org-table-recalculate (org-at-table-p)]
26634 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
26635 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
26636 "--"
26637 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
26638 "--"
26639 ["Sum Column/Rectangle" org-table-sum
26640 (or (org-at-table-p) (org-region-active-p))]
26641 ["Which Column?" org-table-current-column (org-at-table-p)])
26642 ["Debug Formulas"
26643 org-table-toggle-formula-debugger
26644 :style toggle :selected org-table-formula-debug]
26645 ["Show Col/Row Numbers"
26646 org-table-toggle-coordinate-overlays
26647 :style toggle :selected org-table-overlay-coordinates]
26648 "--"
26649 ["Create" org-table-create (and (not (org-at-table-p))
26650 org-enable-table-editor)]
26651 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
26652 ["Import from File" org-table-import (not (org-at-table-p))]
26653 ["Export to File" org-table-export (org-at-table-p)]
26654 "--"
26655 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
26657 (easy-menu-define org-org-menu org-mode-map "Org menu"
26658 '("Org"
26659 ("Show/Hide"
26660 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
26661 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
26662 ["Sparse Tree" org-occur t]
26663 ["Reveal Context" org-reveal t]
26664 ["Show All" show-all t]
26665 "--"
26666 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
26667 "--"
26668 ["New Heading" org-insert-heading t]
26669 ("Navigate Headings"
26670 ["Up" outline-up-heading t]
26671 ["Next" outline-next-visible-heading t]
26672 ["Previous" outline-previous-visible-heading t]
26673 ["Next Same Level" outline-forward-same-level t]
26674 ["Previous Same Level" outline-backward-same-level t]
26675 "--"
26676 ["Jump" org-goto t])
26677 ("Edit Structure"
26678 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
26679 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
26680 "--"
26681 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
26682 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
26683 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
26684 "--"
26685 ["Promote Heading" org-metaleft (not (org-at-table-p))]
26686 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
26687 ["Demote Heading" org-metaright (not (org-at-table-p))]
26688 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
26689 "--"
26690 ["Sort Region/Children" org-sort (not (org-at-table-p))]
26691 "--"
26692 ["Convert to odd levels" org-convert-to-odd-levels t]
26693 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
26694 ("Editing"
26695 ["Emphasis..." org-emphasize t])
26696 ("Archive"
26697 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
26698 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
26699 ; :active t :keys "C-u C-c C-x C-a"]
26700 ["Sparse trees open ARCHIVE trees"
26701 (setq org-sparse-tree-open-archived-trees
26702 (not org-sparse-tree-open-archived-trees))
26703 :style toggle :selected org-sparse-tree-open-archived-trees]
26704 ["Cycling opens ARCHIVE trees"
26705 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
26706 :style toggle :selected org-cycle-open-archived-trees]
26707 ["Agenda includes ARCHIVE trees"
26708 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
26709 :style toggle :selected (not org-agenda-skip-archived-trees)]
26710 "--"
26711 ["Move Subtree to Archive" org-advertized-archive-subtree t]
26712 ; ["Check and Move Children" (org-archive-subtree '(4))
26713 ; :active t :keys "C-u C-c C-x C-s"]
26715 "--"
26716 ("TODO Lists"
26717 ["TODO/DONE/-" org-todo t]
26718 ("Select keyword"
26719 ["Next keyword" org-shiftright (org-on-heading-p)]
26720 ["Previous keyword" org-shiftleft (org-on-heading-p)]
26721 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
26722 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
26723 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
26724 ["Show TODO Tree" org-show-todo-tree t]
26725 ["Global TODO list" org-todo-list t]
26726 "--"
26727 ["Set Priority" org-priority t]
26728 ["Priority Up" org-shiftup t]
26729 ["Priority Down" org-shiftdown t])
26730 ("TAGS and Properties"
26731 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
26732 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
26733 "--"
26734 ["Set property" 'org-set-property t]
26735 ["Column view of properties" org-columns t]
26736 ["Insert Column View DBlock" org-insert-columns-dblock t])
26737 ("Dates and Scheduling"
26738 ["Timestamp" org-time-stamp t]
26739 ["Timestamp (inactive)" org-time-stamp-inactive t]
26740 ("Change Date"
26741 ["1 Day Later" org-shiftright t]
26742 ["1 Day Earlier" org-shiftleft t]
26743 ["1 ... Later" org-shiftup t]
26744 ["1 ... Earlier" org-shiftdown t])
26745 ["Compute Time Range" org-evaluate-time-range t]
26746 ["Schedule Item" org-schedule t]
26747 ["Deadline" org-deadline t]
26748 "--"
26749 ["Custom time format" org-toggle-time-stamp-overlays
26750 :style radio :selected org-display-custom-times]
26751 "--"
26752 ["Goto Calendar" org-goto-calendar t]
26753 ["Date from Calendar" org-date-from-calendar t])
26754 ("Logging work"
26755 ["Clock in" org-clock-in t]
26756 ["Clock out" org-clock-out t]
26757 ["Clock cancel" org-clock-cancel t]
26758 ["Goto running clock" org-clock-goto t]
26759 ["Display times" org-clock-display t]
26760 ["Create clock table" org-clock-report t]
26761 "--"
26762 ["Record DONE time"
26763 (progn (setq org-log-done (not org-log-done))
26764 (message "Switching to %s will %s record a timestamp"
26765 (car org-done-keywords)
26766 (if org-log-done "automatically" "not")))
26767 :style toggle :selected org-log-done])
26768 "--"
26769 ["Agenda Command..." org-agenda t]
26770 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
26771 ("File List for Agenda")
26772 ("Special views current file"
26773 ["TODO Tree" org-show-todo-tree t]
26774 ["Check Deadlines" org-check-deadlines t]
26775 ["Timeline" org-timeline t]
26776 ["Tags Tree" org-tags-sparse-tree t])
26777 "--"
26778 ("Hyperlinks"
26779 ["Store Link (Global)" org-store-link t]
26780 ["Insert Link" org-insert-link t]
26781 ["Follow Link" org-open-at-point t]
26782 "--"
26783 ["Next link" org-next-link t]
26784 ["Previous link" org-previous-link t]
26785 "--"
26786 ["Descriptive Links"
26787 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
26788 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
26789 ["Literal Links"
26790 (progn
26791 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
26792 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
26793 "--"
26794 ["Export/Publish..." org-export t]
26795 ("LaTeX"
26796 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
26797 :selected org-cdlatex-mode]
26798 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
26799 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
26800 ["Modify math symbol" org-cdlatex-math-modify
26801 (org-inside-LaTeX-fragment-p)]
26802 ["Export LaTeX fragments as images"
26803 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
26804 :style toggle :selected org-export-with-LaTeX-fragments])
26805 "--"
26806 ("Documentation"
26807 ["Show Version" org-version t]
26808 ["Info Documentation" org-info t])
26809 ("Customize"
26810 ["Browse Org Group" org-customize t]
26811 "--"
26812 ["Expand This Menu" org-create-customize-menu
26813 (fboundp 'customize-menu-create)])
26814 "--"
26815 ["Refresh setup" org-mode-restart t]
26818 (defun org-info (&optional node)
26819 "Read documentation for Org-mode in the info system.
26820 With optional NODE, go directly to that node."
26821 (interactive)
26822 (require 'info)
26823 (Info-goto-node (format "(org)%s" (or node ""))))
26825 (defun org-install-agenda-files-menu ()
26826 (let ((bl (buffer-list)))
26827 (save-excursion
26828 (while bl
26829 (set-buffer (pop bl))
26830 (if (org-mode-p) (setq bl nil)))
26831 (when (org-mode-p)
26832 (easy-menu-change
26833 '("Org") "File List for Agenda"
26834 (append
26835 (list
26836 ["Edit File List" (org-edit-agenda-file-list) t]
26837 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
26838 ["Remove Current File from List" org-remove-file t]
26839 ["Cycle through agenda files" org-cycle-agenda-files t]
26840 ["Occur in all agenda files" org-occur-in-agenda-files t]
26841 "--")
26842 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
26844 ;;;; Documentation
26846 (defun org-customize ()
26847 "Call the customize function with org as argument."
26848 (interactive)
26849 (customize-browse 'org))
26851 (defun org-create-customize-menu ()
26852 "Create a full customization menu for Org-mode, insert it into the menu."
26853 (interactive)
26854 (if (fboundp 'customize-menu-create)
26855 (progn
26856 (easy-menu-change
26857 '("Org") "Customize"
26858 `(["Browse Org group" org-customize t]
26859 "--"
26860 ,(customize-menu-create 'org)
26861 ["Set" Custom-set t]
26862 ["Save" Custom-save t]
26863 ["Reset to Current" Custom-reset-current t]
26864 ["Reset to Saved" Custom-reset-saved t]
26865 ["Reset to Standard Settings" Custom-reset-standard t]))
26866 (message "\"Org\"-menu now contains full customization menu"))
26867 (error "Cannot expand menu (outdated version of cus-edit.el)")))
26869 ;;;; Miscellaneous stuff
26872 ;;; Generally useful functions
26874 (defun org-context ()
26875 "Return a list of contexts of the current cursor position.
26876 If several contexts apply, all are returned.
26877 Each context entry is a list with a symbol naming the context, and
26878 two positions indicating start and end of the context. Possible
26879 contexts are:
26881 :headline anywhere in a headline
26882 :headline-stars on the leading stars in a headline
26883 :todo-keyword on a TODO keyword (including DONE) in a headline
26884 :tags on the TAGS in a headline
26885 :priority on the priority cookie in a headline
26886 :item on the first line of a plain list item
26887 :item-bullet on the bullet/number of a plain list item
26888 :checkbox on the checkbox in a plain list item
26889 :table in an org-mode table
26890 :table-special on a special filed in a table
26891 :table-table in a table.el table
26892 :link on a hyperlink
26893 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
26894 :target on a <<target>>
26895 :radio-target on a <<<radio-target>>>
26896 :latex-fragment on a LaTeX fragment
26897 :latex-preview on a LaTeX fragment with overlayed preview image
26899 This function expects the position to be visible because it uses font-lock
26900 faces as a help to recognize the following contexts: :table-special, :link,
26901 and :keyword."
26902 (let* ((f (get-text-property (point) 'face))
26903 (faces (if (listp f) f (list f)))
26904 (p (point)) clist o)
26905 ;; First the large context
26906 (cond
26907 ((org-on-heading-p t)
26908 (push (list :headline (point-at-bol) (point-at-eol)) clist)
26909 (when (progn
26910 (beginning-of-line 1)
26911 (looking-at org-todo-line-tags-regexp))
26912 (push (org-point-in-group p 1 :headline-stars) clist)
26913 (push (org-point-in-group p 2 :todo-keyword) clist)
26914 (push (org-point-in-group p 4 :tags) clist))
26915 (goto-char p)
26916 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
26917 (if (looking-at "\\[#[A-Z0-9]\\]")
26918 (push (org-point-in-group p 0 :priority) clist)))
26920 ((org-at-item-p)
26921 (push (org-point-in-group p 2 :item-bullet) clist)
26922 (push (list :item (point-at-bol)
26923 (save-excursion (org-end-of-item) (point)))
26924 clist)
26925 (and (org-at-item-checkbox-p)
26926 (push (org-point-in-group p 0 :checkbox) clist)))
26928 ((org-at-table-p)
26929 (push (list :table (org-table-begin) (org-table-end)) clist)
26930 (if (memq 'org-formula faces)
26931 (push (list :table-special
26932 (previous-single-property-change p 'face)
26933 (next-single-property-change p 'face)) clist)))
26934 ((org-at-table-p 'any)
26935 (push (list :table-table) clist)))
26936 (goto-char p)
26938 ;; Now the small context
26939 (cond
26940 ((org-at-timestamp-p)
26941 (push (org-point-in-group p 0 :timestamp) clist))
26942 ((memq 'org-link faces)
26943 (push (list :link
26944 (previous-single-property-change p 'face)
26945 (next-single-property-change p 'face)) clist))
26946 ((memq 'org-special-keyword faces)
26947 (push (list :keyword
26948 (previous-single-property-change p 'face)
26949 (next-single-property-change p 'face)) clist))
26950 ((org-on-target-p)
26951 (push (org-point-in-group p 0 :target) clist)
26952 (goto-char (1- (match-beginning 0)))
26953 (if (looking-at org-radio-target-regexp)
26954 (push (org-point-in-group p 0 :radio-target) clist))
26955 (goto-char p))
26956 ((setq o (car (delq nil
26957 (mapcar
26958 (lambda (x)
26959 (if (memq x org-latex-fragment-image-overlays) x))
26960 (org-overlays-at (point))))))
26961 (push (list :latex-fragment
26962 (org-overlay-start o) (org-overlay-end o)) clist)
26963 (push (list :latex-preview
26964 (org-overlay-start o) (org-overlay-end o)) clist))
26965 ((org-inside-LaTeX-fragment-p)
26966 ;; FIXME: positions wrong.
26967 (push (list :latex-fragment (point) (point)) clist)))
26969 (setq clist (nreverse (delq nil clist)))
26970 clist))
26972 ;; FIXME: Compare with at-regexp-p Do we need both?
26973 (defun org-in-regexp (re &optional nlines visually)
26974 "Check if point is inside a match of regexp.
26975 Normally only the current line is checked, but you can include NLINES extra
26976 lines both before and after point into the search.
26977 If VISUALLY is set, require that the cursor is not after the match but
26978 really on, so that the block visually is on the match."
26979 (catch 'exit
26980 (let ((pos (point))
26981 (eol (point-at-eol (+ 1 (or nlines 0))))
26982 (inc (if visually 1 0)))
26983 (save-excursion
26984 (beginning-of-line (- 1 (or nlines 0)))
26985 (while (re-search-forward re eol t)
26986 (if (and (<= (match-beginning 0) pos)
26987 (>= (+ inc (match-end 0)) pos))
26988 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
26990 (defun org-at-regexp-p (regexp)
26991 "Is point inside a match of REGEXP in the current line?"
26992 (catch 'exit
26993 (save-excursion
26994 (let ((pos (point)) (end (point-at-eol)))
26995 (beginning-of-line 1)
26996 (while (re-search-forward regexp end t)
26997 (if (and (<= (match-beginning 0) pos)
26998 (>= (match-end 0) pos))
26999 (throw 'exit t)))
27000 nil))))
27002 (defun org-occur-in-agenda-files (regexp &optional nlines)
27003 "Call `multi-occur' with buffers for all agenda files."
27004 (interactive "sOrg-files matching: \np")
27005 (let* ((files (org-agenda-files))
27006 (tnames (mapcar 'file-truename files))
27007 (extra org-agenda-multi-occur-extra-files)
27009 (while (setq f (pop extra))
27010 (unless (member (file-truename f) tnames)
27011 (add-to-list 'files f 'append)
27012 (add-to-list 'tnames (file-truename f) 'append)))
27013 (multi-occur
27014 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
27015 regexp)))
27017 (defun org-uniquify (list)
27018 "Remove duplicate elements from LIST."
27019 (let (res)
27020 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
27021 res))
27023 (defun org-delete-all (elts list)
27024 "Remove all elements in ELTS from LIST."
27025 (while elts
27026 (setq list (delete (pop elts) list)))
27027 list)
27029 (defun org-back-over-empty-lines ()
27030 "Move backwards over witespace, to the beginning of the first empty line.
27031 Returns the number o empty lines passed."
27032 (let ((pos (point)))
27033 (skip-chars-backward " \t\n\r")
27034 (beginning-of-line 2)
27035 (count-lines (point) pos)))
27037 (defun org-skip-whitespace ()
27038 (skip-chars-forward " \t\n\r"))
27040 (defun org-point-in-group (point group &optional context)
27041 "Check if POINT is in match-group GROUP.
27042 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
27043 match. If the match group does ot exist or point is not inside it,
27044 return nil."
27045 (and (match-beginning group)
27046 (>= point (match-beginning group))
27047 (<= point (match-end group))
27048 (if context
27049 (list context (match-beginning group) (match-end group))
27050 t)))
27052 (defun org-switch-to-buffer-other-window (&rest args)
27053 "Switch to buffer in a second window on the current frame.
27054 In particular, do not allow pop-up frames."
27055 (let (pop-up-frames special-display-buffer-names special-display-regexps
27056 special-display-function)
27057 (apply 'switch-to-buffer-other-window args)))
27059 (defun org-combine-plists (&rest plists)
27060 "Create a single property list from all plists in PLISTS.
27061 The process starts by copying the first list, and then setting properties
27062 from the other lists. Settings in the last list are the most significant
27063 ones and overrule settings in the other lists."
27064 (let ((rtn (copy-sequence (pop plists)))
27065 p v ls)
27066 (while plists
27067 (setq ls (pop plists))
27068 (while ls
27069 (setq p (pop ls) v (pop ls))
27070 (setq rtn (plist-put rtn p v))))
27071 rtn))
27073 (defun org-move-line-down (arg)
27074 "Move the current line down. With prefix argument, move it past ARG lines."
27075 (interactive "p")
27076 (let ((col (current-column))
27077 beg end pos)
27078 (beginning-of-line 1) (setq beg (point))
27079 (beginning-of-line 2) (setq end (point))
27080 (beginning-of-line (+ 1 arg))
27081 (setq pos (move-marker (make-marker) (point)))
27082 (insert (delete-and-extract-region beg end))
27083 (goto-char pos)
27084 (move-to-column col)))
27086 (defun org-move-line-up (arg)
27087 "Move the current line up. With prefix argument, move it past ARG lines."
27088 (interactive "p")
27089 (let ((col (current-column))
27090 beg end pos)
27091 (beginning-of-line 1) (setq beg (point))
27092 (beginning-of-line 2) (setq end (point))
27093 (beginning-of-line (- arg))
27094 (setq pos (move-marker (make-marker) (point)))
27095 (insert (delete-and-extract-region beg end))
27096 (goto-char pos)
27097 (move-to-column col)))
27099 (defun org-replace-escapes (string table)
27100 "Replace %-escapes in STRING with values in TABLE.
27101 TABLE is an association list with keys like \"%a\" and string values.
27102 The sequences in STRING may contain normal field width and padding information,
27103 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
27104 so values can contain further %-escapes if they are define later in TABLE."
27105 (let ((case-fold-search nil)
27106 e re rpl)
27107 (while (setq e (pop table))
27108 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
27109 (while (string-match re string)
27110 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
27111 (cdr e)))
27112 (setq string (replace-match rpl t t string))))
27113 string))
27116 (defun org-sublist (list start end)
27117 "Return a section of LIST, from START to END.
27118 Counting starts at 1."
27119 (let (rtn (c start))
27120 (setq list (nthcdr (1- start) list))
27121 (while (and list (<= c end))
27122 (push (pop list) rtn)
27123 (setq c (1+ c)))
27124 (nreverse rtn)))
27126 (defun org-find-base-buffer-visiting (file)
27127 "Like `find-buffer-visiting' but alway return the base buffer and
27128 not an indirect buffer"
27129 (let ((buf (find-buffer-visiting file)))
27130 (if buf
27131 (or (buffer-base-buffer buf) buf)
27132 nil)))
27134 (defun org-image-file-name-regexp ()
27135 "Return regexp matching the file names of images."
27136 (if (fboundp 'image-file-name-regexp)
27137 (image-file-name-regexp)
27138 (let ((image-file-name-extensions
27139 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
27140 "xbm" "xpm" "pbm" "pgm" "ppm")))
27141 (concat "\\."
27142 (regexp-opt (nconc (mapcar 'upcase
27143 image-file-name-extensions)
27144 image-file-name-extensions)
27146 "\\'"))))
27148 (defun org-file-image-p (file)
27149 "Return non-nil if FILE is an image."
27150 (save-match-data
27151 (string-match (org-image-file-name-regexp) file)))
27153 ;;; Paragraph filling stuff.
27154 ;; We want this to be just right, so use the full arsenal.
27156 (defun org-indent-line-function ()
27157 "Indent line like previous, but further if previous was headline or item."
27158 (interactive)
27159 (let* ((pos (point))
27160 (itemp (org-at-item-p))
27161 column bpos bcol tpos tcol bullet btype bullet-type)
27162 ;; Find the previous relevant line
27163 (beginning-of-line 1)
27164 (cond
27165 ((looking-at "#") (setq column 0))
27166 ((looking-at "\\*+ ") (setq column 0))
27168 (beginning-of-line 0)
27169 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
27170 (beginning-of-line 0))
27171 (cond
27172 ((looking-at "\\*+[ \t]+")
27173 (goto-char (match-end 0))
27174 (setq column (current-column)))
27175 ((org-in-item-p)
27176 (org-beginning-of-item)
27177 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
27178 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
27179 (setq bpos (match-beginning 1) tpos (match-end 0)
27180 bcol (progn (goto-char bpos) (current-column))
27181 tcol (progn (goto-char tpos) (current-column))
27182 bullet (match-string 1)
27183 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
27184 (if (not itemp)
27185 (setq column tcol)
27186 (goto-char pos)
27187 (beginning-of-line 1)
27188 (if (looking-at "\\S-")
27189 (progn
27190 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
27191 (setq bullet (match-string 1)
27192 btype (if (string-match "[0-9]" bullet) "n" bullet))
27193 (setq column (if (equal btype bullet-type) bcol tcol)))
27194 (setq column (org-get-indentation)))))
27195 (t (setq column (org-get-indentation))))))
27196 (goto-char pos)
27197 (if (<= (current-column) (current-indentation))
27198 (indent-line-to column)
27199 (save-excursion (indent-line-to column)))
27200 (setq column (current-column))
27201 (beginning-of-line 1)
27202 (if (looking-at
27203 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
27204 (replace-match (concat "\\1" (format org-property-format
27205 (match-string 2) (match-string 3)))
27206 t nil))
27207 (move-to-column column)))
27209 (defun org-set-autofill-regexps ()
27210 (interactive)
27211 ;; In the paragraph separator we include headlines, because filling
27212 ;; text in a line directly attached to a headline would otherwise
27213 ;; fill the headline as well.
27214 (org-set-local 'comment-start-skip "^#+[ \t]*")
27215 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
27216 ;; The paragraph starter includes hand-formatted lists.
27217 (org-set-local 'paragraph-start
27218 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
27219 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
27220 ;; But only if the user has not turned off tables or fixed-width regions
27221 (org-set-local
27222 'auto-fill-inhibit-regexp
27223 (concat "\\*+ \\|#\\+"
27224 "\\|[ \t]*" org-keyword-time-regexp
27225 (if (or org-enable-table-editor org-enable-fixed-width-editor)
27226 (concat
27227 "\\|[ \t]*["
27228 (if org-enable-table-editor "|" "")
27229 (if org-enable-fixed-width-editor ":" "")
27230 "]"))))
27231 ;; We use our own fill-paragraph function, to make sure that tables
27232 ;; and fixed-width regions are not wrapped. That function will pass
27233 ;; through to `fill-paragraph' when appropriate.
27234 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
27235 ; Adaptive filling: To get full control, first make sure that
27236 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
27237 (org-set-local 'adaptive-fill-regexp "\000")
27238 (org-set-local 'adaptive-fill-function
27239 'org-adaptive-fill-function))
27241 (defun org-fill-paragraph (&optional justify)
27242 "Re-align a table, pass through to fill-paragraph if no table."
27243 (let ((table-p (org-at-table-p))
27244 (table.el-p (org-at-table.el-p)))
27245 (cond ((and (equal (char-after (point-at-bol)) ?*)
27246 (save-excursion (goto-char (point-at-bol))
27247 (looking-at outline-regexp)))
27248 t) ; skip headlines
27249 (table.el-p t) ; skip table.el tables
27250 (table-p (org-table-align) t) ; align org-mode tables
27251 (t nil)))) ; call paragraph-fill
27253 ;; For reference, this is the default value of adaptive-fill-regexp
27254 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
27256 (defun org-adaptive-fill-function ()
27257 "Return a fill prefix for org-mode files.
27258 In particular, this makes sure hanging paragraphs for hand-formatted lists
27259 work correctly."
27260 (cond ((looking-at "#[ \t]+")
27261 (match-string 0))
27262 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
27263 (save-excursion
27264 (goto-char (match-end 0))
27265 (make-string (current-column) ?\ )))
27266 (t nil)))
27268 ;;;; Functions extending outline functionality
27270 (defun org-beginning-of-line (&optional arg)
27271 "Go to the beginning of the current line. If that is invisible, continue
27272 to a visible line beginning. This makes the function of C-a more intuitive.
27273 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27274 first attempt, and only move to after the tags when the cursor is already
27275 beyond the end of the headline."
27276 (interactive "P")
27277 (let ((pos (point)))
27278 (beginning-of-line 1)
27279 (if (bobp)
27281 (backward-char 1)
27282 (if (org-invisible-p)
27283 (while (and (not (bobp)) (org-invisible-p))
27284 (backward-char 1)
27285 (beginning-of-line 1))
27286 (forward-char 1)))
27287 (when org-special-ctrl-a/e
27288 (cond
27289 ((and (looking-at org-todo-line-regexp)
27290 (= (char-after (match-end 1)) ?\ ))
27291 (goto-char
27292 (if (eq org-special-ctrl-a/e t)
27293 (cond ((> pos (match-beginning 3)) (match-beginning 3))
27294 ((= pos (point)) (match-beginning 3))
27295 (t (point)))
27296 (cond ((> pos (point)) (point))
27297 ((not (eq last-command this-command)) (point))
27298 (t (match-beginning 3))))))
27299 ((org-at-item-p)
27300 (goto-char
27301 (if (eq org-special-ctrl-a/e t)
27302 (cond ((> pos (match-end 4)) (match-end 4))
27303 ((= pos (point)) (match-end 4))
27304 (t (point)))
27305 (cond ((> pos (point)) (point))
27306 ((not (eq last-command this-command)) (point))
27307 (t (match-end 4))))))))))
27309 (defun org-end-of-line (&optional arg)
27310 "Go to the end of the line.
27311 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27312 first attempt, and only move to after the tags when the cursor is already
27313 beyond the end of the headline."
27314 (interactive "P")
27315 (if (or (not org-special-ctrl-a/e)
27316 (not (org-on-heading-p)))
27317 (end-of-line arg)
27318 (let ((pos (point)))
27319 (beginning-of-line 1)
27320 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
27321 (if (eq org-special-ctrl-a/e t)
27322 (if (or (< pos (match-beginning 1))
27323 (= pos (match-end 0)))
27324 (goto-char (match-beginning 1))
27325 (goto-char (match-end 0)))
27326 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
27327 (goto-char (match-end 0))
27328 (goto-char (match-beginning 1))))
27329 (end-of-line arg)))))
27331 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
27332 (define-key org-mode-map "\C-e" 'org-end-of-line)
27334 (defun org-invisible-p ()
27335 "Check if point is at a character currently not visible."
27336 ;; Early versions of noutline don't have `outline-invisible-p'.
27337 (if (fboundp 'outline-invisible-p)
27338 (outline-invisible-p)
27339 (get-char-property (point) 'invisible)))
27341 (defun org-invisible-p2 ()
27342 "Check if point is at a character currently not visible."
27343 (save-excursion
27344 (if (and (eolp) (not (bobp))) (backward-char 1))
27345 ;; Early versions of noutline don't have `outline-invisible-p'.
27346 (if (fboundp 'outline-invisible-p)
27347 (outline-invisible-p)
27348 (get-char-property (point) 'invisible))))
27350 (defalias 'org-back-to-heading 'outline-back-to-heading)
27351 (defalias 'org-on-heading-p 'outline-on-heading-p)
27352 (defalias 'org-at-heading-p 'outline-on-heading-p)
27353 (defun org-at-heading-or-item-p ()
27354 (or (org-on-heading-p) (org-at-item-p)))
27356 (defun org-on-target-p ()
27357 (or (org-in-regexp org-radio-target-regexp)
27358 (org-in-regexp org-target-regexp)))
27360 (defun org-up-heading-all (arg)
27361 "Move to the heading line of which the present line is a subheading.
27362 This function considers both visible and invisible heading lines.
27363 With argument, move up ARG levels."
27364 (if (fboundp 'outline-up-heading-all)
27365 (outline-up-heading-all arg) ; emacs 21 version of outline.el
27366 (outline-up-heading arg t))) ; emacs 22 version of outline.el
27368 (defun org-up-heading-safe ()
27369 "Move to the heading line of which the present line is a subheading.
27370 This version will not throw an error. It will return the level of the
27371 headline found, or nil if no higher level is found."
27372 (let ((pos (point)) start-level level
27373 (re (concat "^" outline-regexp)))
27374 (catch 'exit
27375 (outline-back-to-heading t)
27376 (setq start-level (funcall outline-level))
27377 (if (equal start-level 1) (throw 'exit nil))
27378 (while (re-search-backward re nil t)
27379 (setq level (funcall outline-level))
27380 (if (< level start-level) (throw 'exit level)))
27381 nil)))
27383 (defun org-first-sibling-p ()
27384 "Is this heading the first child of its parents?"
27385 (interactive)
27386 (let ((re (concat "^" outline-regexp))
27387 level l)
27388 (unless (org-at-heading-p t)
27389 (error "Not at a heading"))
27390 (setq level (funcall outline-level))
27391 (save-excursion
27392 (if (not (re-search-backward re nil t))
27394 (setq l (funcall outline-level))
27395 (< l level)))))
27397 (defun org-goto-sibling (&optional previous)
27398 "Goto the next sibling, even if it is invisible.
27399 When PREVIOUS is set, go to the previous sibling instead. Returns t
27400 when a sibling was found. When none is found, return nil and don't
27401 move point."
27402 (let ((fun (if previous 're-search-backward 're-search-forward))
27403 (pos (point))
27404 (re (concat "^" outline-regexp))
27405 level l)
27406 (when (condition-case nil (org-back-to-heading t) (error nil))
27407 (setq level (funcall outline-level))
27408 (catch 'exit
27409 (or previous (forward-char 1))
27410 (while (funcall fun re nil t)
27411 (setq l (funcall outline-level))
27412 (when (< l level) (goto-char pos) (throw 'exit nil))
27413 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
27414 (goto-char pos)
27415 nil))))
27417 (defun org-show-siblings ()
27418 "Show all siblings of the current headline."
27419 (save-excursion
27420 (while (org-goto-sibling) (org-flag-heading nil)))
27421 (save-excursion
27422 (while (org-goto-sibling 'previous)
27423 (org-flag-heading nil))))
27425 (defun org-show-hidden-entry ()
27426 "Show an entry where even the heading is hidden."
27427 (save-excursion
27428 (org-show-entry)))
27430 (defun org-flag-heading (flag &optional entry)
27431 "Flag the current heading. FLAG non-nil means make invisible.
27432 When ENTRY is non-nil, show the entire entry."
27433 (save-excursion
27434 (org-back-to-heading t)
27435 ;; Check if we should show the entire entry
27436 (if entry
27437 (progn
27438 (org-show-entry)
27439 (save-excursion
27440 (and (outline-next-heading)
27441 (org-flag-heading nil))))
27442 (outline-flag-region (max (point-min) (1- (point)))
27443 (save-excursion (outline-end-of-heading) (point))
27444 flag))))
27446 (defun org-end-of-subtree (&optional invisible-OK to-heading)
27447 ;; This is an exact copy of the original function, but it uses
27448 ;; `org-back-to-heading', to make it work also in invisible
27449 ;; trees. And is uses an invisible-OK argument.
27450 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
27451 (org-back-to-heading invisible-OK)
27452 (let ((first t)
27453 (level (funcall outline-level)))
27454 (while (and (not (eobp))
27455 (or first (> (funcall outline-level) level)))
27456 (setq first nil)
27457 (outline-next-heading))
27458 (unless to-heading
27459 (if (memq (preceding-char) '(?\n ?\^M))
27460 (progn
27461 ;; Go to end of line before heading
27462 (forward-char -1)
27463 (if (memq (preceding-char) '(?\n ?\^M))
27464 ;; leave blank line before heading
27465 (forward-char -1))))))
27466 (point))
27468 (defun org-show-subtree ()
27469 "Show everything after this heading at deeper levels."
27470 (outline-flag-region
27471 (point)
27472 (save-excursion
27473 (outline-end-of-subtree) (outline-next-heading) (point))
27474 nil))
27476 (defun org-show-entry ()
27477 "Show the body directly following this heading.
27478 Show the heading too, if it is currently invisible."
27479 (interactive)
27480 (save-excursion
27481 (condition-case nil
27482 (progn
27483 (org-back-to-heading t)
27484 (outline-flag-region
27485 (max (point-min) (1- (point)))
27486 (save-excursion
27487 (re-search-forward
27488 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
27489 (or (match-beginning 1) (point-max)))
27490 nil))
27491 (error nil))))
27493 (defun org-make-options-regexp (kwds)
27494 "Make a regular expression for keyword lines."
27495 (concat
27497 "#?[ \t]*\\+\\("
27498 (mapconcat 'regexp-quote kwds "\\|")
27499 "\\):[ \t]*"
27500 "\\(.+\\)"))
27502 ;; Make isearch reveal the necessary context
27503 (defun org-isearch-end ()
27504 "Reveal context after isearch exits."
27505 (when isearch-success ; only if search was successful
27506 (if (featurep 'xemacs)
27507 ;; Under XEmacs, the hook is run in the correct place,
27508 ;; we directly show the context.
27509 (org-show-context 'isearch)
27510 ;; In Emacs the hook runs *before* restoring the overlays.
27511 ;; So we have to use a one-time post-command-hook to do this.
27512 ;; (Emacs 22 has a special variable, see function `org-mode')
27513 (unless (and (boundp 'isearch-mode-end-hook-quit)
27514 isearch-mode-end-hook-quit)
27515 ;; Only when the isearch was not quitted.
27516 (org-add-hook 'post-command-hook 'org-isearch-post-command
27517 'append 'local)))))
27519 (defun org-isearch-post-command ()
27520 "Remove self from hook, and show context."
27521 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
27522 (org-show-context 'isearch))
27525 ;;;; Integration with and fixes for other packages
27527 ;;; Imenu support
27529 (defvar org-imenu-markers nil
27530 "All markers currently used by Imenu.")
27531 (make-variable-buffer-local 'org-imenu-markers)
27533 (defun org-imenu-new-marker (&optional pos)
27534 "Return a new marker for use by Imenu, and remember the marker."
27535 (let ((m (make-marker)))
27536 (move-marker m (or pos (point)))
27537 (push m org-imenu-markers)
27540 (defun org-imenu-get-tree ()
27541 "Produce the index for Imenu."
27542 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
27543 (setq org-imenu-markers nil)
27544 (let* ((n org-imenu-depth)
27545 (re (concat "^" outline-regexp))
27546 (subs (make-vector (1+ n) nil))
27547 (last-level 0)
27548 m tree level head)
27549 (save-excursion
27550 (save-restriction
27551 (widen)
27552 (goto-char (point-max))
27553 (while (re-search-backward re nil t)
27554 (setq level (org-reduced-level (funcall outline-level)))
27555 (when (<= level n)
27556 (looking-at org-complex-heading-regexp)
27557 (setq head (org-match-string-no-properties 4)
27558 m (org-imenu-new-marker))
27559 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
27560 (if (>= level last-level)
27561 (push (cons head m) (aref subs level))
27562 (push (cons head (aref subs (1+ level))) (aref subs level))
27563 (loop for i from (1+ level) to n do (aset subs i nil)))
27564 (setq last-level level)))))
27565 (aref subs 1)))
27567 (eval-after-load "imenu"
27568 '(progn
27569 (add-hook 'imenu-after-jump-hook
27570 (lambda () (org-show-context 'org-goto)))))
27572 ;; Speedbar support
27574 (defun org-speedbar-set-agenda-restriction ()
27575 "Restrict future agenda commands to the location at point in speedbar.
27576 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
27577 (interactive)
27578 (let (p m tp np dir txt w)
27579 (cond
27580 ((setq p (text-property-any (point-at-bol) (point-at-eol)
27581 'org-imenu t))
27582 (setq m (get-text-property p 'org-imenu-marker))
27583 (save-excursion
27584 (save-restriction
27585 (set-buffer (marker-buffer m))
27586 (goto-char m)
27587 (org-agenda-set-restriction-lock 'subtree))))
27588 ((setq p (text-property-any (point-at-bol) (point-at-eol)
27589 'speedbar-function 'speedbar-find-file))
27590 (setq tp (previous-single-property-change
27591 (1+ p) 'speedbar-function)
27592 np (next-single-property-change
27593 tp 'speedbar-function)
27594 dir (speedbar-line-directory)
27595 txt (buffer-substring-no-properties (or tp (point-min))
27596 (or np (point-max))))
27597 (save-excursion
27598 (save-restriction
27599 (set-buffer (find-file-noselect
27600 (let ((default-directory dir))
27601 (expand-file-name txt))))
27602 (unless (org-mode-p)
27603 (error "Cannot restrict to non-Org-mode file"))
27604 (org-agenda-set-restriction-lock 'file))))
27605 (t (error "Don't know how to restrict Org-mode's agenda")))
27606 (org-move-overlay org-speedbar-restriction-lock-overlay
27607 (point-at-bol) (point-at-eol))
27608 (setq current-prefix-arg nil)
27609 (org-agenda-maybe-redo)))
27611 (eval-after-load "speedbar"
27612 '(progn
27613 (speedbar-add-supported-extension ".org")
27614 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
27615 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
27616 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
27617 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
27618 (add-hook 'speedbar-visiting-tag-hook
27619 (lambda () (org-show-context 'org-goto)))))
27622 ;;; Fixes and Hacks
27624 ;; Make flyspell not check words in links, to not mess up our keymap
27625 (defun org-mode-flyspell-verify ()
27626 "Don't let flyspell put overlays at active buttons."
27627 (not (get-text-property (point) 'keymap)))
27629 ;; Make `bookmark-jump' show the jump location if it was hidden.
27630 (eval-after-load "bookmark"
27631 '(if (boundp 'bookmark-after-jump-hook)
27632 ;; We can use the hook
27633 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
27634 ;; Hook not available, use advice
27635 (defadvice bookmark-jump (after org-make-visible activate)
27636 "Make the position visible."
27637 (org-bookmark-jump-unhide))))
27639 (defun org-bookmark-jump-unhide ()
27640 "Unhide the current position, to show the bookmark location."
27641 (and (org-mode-p)
27642 (or (org-invisible-p)
27643 (save-excursion (goto-char (max (point-min) (1- (point))))
27644 (org-invisible-p)))
27645 (org-show-context 'bookmark-jump)))
27647 ;; Fix a bug in htmlize where there are text properties (face nil)
27648 (eval-after-load "htmlize"
27649 '(progn
27650 (defadvice htmlize-faces-in-buffer (after org-no-nil-faces activate)
27651 "Make sure there are no nil faces"
27652 (setq ad-return-value (delq nil ad-return-value)))))
27654 ;; Make session.el ignore our circular variable
27655 (eval-after-load "session"
27656 '(add-to-list 'session-globals-exclude 'org-mark-ring))
27658 ;;;; Experimental code
27660 (defun org-closed-in-range ()
27661 "Sparse tree of items closed in a certain time range.
27662 Still experimental, may disappear in the future."
27663 (interactive)
27664 ;; Get the time interval from the user.
27665 (let* ((time1 (time-to-seconds
27666 (org-read-date nil 'to-time nil "Starting date: ")))
27667 (time2 (time-to-seconds
27668 (org-read-date nil 'to-time nil "End date:")))
27669 ;; callback function
27670 (callback (lambda ()
27671 (let ((time
27672 (time-to-seconds
27673 (apply 'encode-time
27674 (org-parse-time-string
27675 (match-string 1))))))
27676 ;; check if time in interval
27677 (and (>= time time1) (<= time time2))))))
27678 ;; make tree, check each match with the callback
27679 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
27681 (defun org-first-list-item-p ()
27682 "Is this heading the item in a plain list?"
27683 (unless (org-at-item-p)
27684 (error "Not at a plain list item"))
27685 (org-beginning-of-item)
27686 (= (point) (save-excursion (org-beginning-of-item-list))))
27688 ;;;; Finish up
27690 (provide 'org)
27692 (run-hooks 'org-load-hook)
27694 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
27695 ;;; org.el ends here