Release 5.16b
[org-mode.git] / org.el
blobf01936d80de5f1ffe39df3c5213a905f7a82bc1c
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.16b
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.16a"
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 %t time stamp, date only
1441 %T time stamp with date and time
1442 %u, %U like the above, but inactive time stamps
1443 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1444 You may define a prompt like %^{Please specify birthday}t
1445 %n user name (taken from `user-full-name')
1446 %a annotation, normally the link created with org-store-link
1447 %i initial content, the region when remember is called with C-u.
1448 If %i is indented, the entire inserted text will be indented
1449 as well.
1451 %? After completing the template, position cursor here.
1453 Apart from these general escapes, you can access information specific to the
1454 link type that is created. For example, calling `remember' in emails or gnus
1455 will record the author and the subject of the message, which you can access
1456 with %:author and %:subject, respectively. Here is a complete list of what
1457 is recorded for each link type.
1459 Link type | Available information
1460 -------------------+------------------------------------------------------
1461 bbdb | %:type %:name %:company
1462 vm, wl, mh, rmail | %:type %:subject %:message-id
1463 | %:from %:fromname %:fromaddress
1464 | %:to %:toname %:toaddress
1465 | %:fromto (either \"to NAME\" or \"from NAME\")
1466 gnus | %:group, for messages also all email fields
1467 w3, w3m | %:type %:url
1468 info | %:type %:file %:node
1469 calendar | %:type %:date"
1470 :group 'org-remember
1471 :get (lambda (var) ; Make sure all entries have 5 elements
1472 (mapcar (lambda (x)
1473 (if (not (stringp (car x))) (setq x (cons "" x)))
1474 (cond ((= (length x) 4) (append x '("")))
1475 ((= (length x) 3) (append x '("" "")))
1476 (t x)))
1477 (default-value var)))
1478 :type '(repeat
1479 :tag "enabled"
1480 (list :value ("" ?a "\n" nil nil)
1481 (string :tag "Name")
1482 (character :tag "Selection Key")
1483 (string :tag "Template")
1484 (choice
1485 (file :tag "Destination file")
1486 (const :tag "Prompt for file" nil))
1487 (choice
1488 (string :tag "Destination headline")
1489 (const :tag "Selection interface for heading")))))
1491 (defcustom org-reverse-note-order nil
1492 "Non-nil means, store new notes at the beginning of a file or entry.
1493 When nil, new notes will be filed to the end of a file or entry.
1494 This can also be a list with cons cells of regular expressions that
1495 are matched against file names, and values."
1496 :group 'org-remember
1497 :type '(choice
1498 (const :tag "Reverse always" t)
1499 (const :tag "Reverse never" nil)
1500 (repeat :tag "By file name regexp"
1501 (cons regexp boolean))))
1503 (defcustom org-refile-targets '((nil . (:level . 1)))
1504 "Targets for refiling entries with \\[org-refile].
1505 This is list of cons cells. Each cell contains:
1506 - a specification of the files to be considered, either a list of files,
1507 or a symbol whose function or value fields will be used to retrieve
1508 a file name or a list of file names. Nil means, refile to a different
1509 heading in the current buffer.
1510 - A specification of how to find candidate refile targets. This may be
1511 any of
1512 - a cons cell (:tag . \"TAG\") to identify refile targes by a tag.
1513 This tag has to be present in all target headlines, inheritance will
1514 not be considered.
1515 - a cons cell (:todo . \"KEYWORD\" to identify refile targets by
1516 todo keyword.
1517 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1518 headlines that are refiling targets.
1519 - a cons cell (:level . N). Any headline of level N is considered a target."
1520 ;; FIXME: what if there are a var and func with same name???
1521 :group 'org
1522 :type '(repeat
1523 (cons
1524 (choice :value org-agenda-files
1525 (const :tag "All agenda files" org-agenda-files)
1526 (const :tag "Current buffer" nil)
1527 (function) (variable) (file))
1528 (choice :tag "Identify target headline by"
1529 (cons :tag "Specific tag" (const :tag) (string))
1530 (cons :tag "TODO keyword" (const :todo) (string))
1531 (cons :tag "Regular expression" (const :regexp) (regexp))
1532 (cons :tag "Level number" (const :level) (integer))))))
1534 (defgroup org-todo nil
1535 "Options concerning TODO items in Org-mode."
1536 :tag "Org TODO"
1537 :group 'org)
1539 (defgroup org-progress nil
1540 "Options concerning Progress logging in Org-mode."
1541 :tag "Org Progress"
1542 :group 'org-time)
1544 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1545 "List of TODO entry keyword sequences and their interpretation.
1546 \\<org-mode-map>This is a list of sequences.
1548 Each sequence starts with a symbol, either `sequence' or `type',
1549 indicating if the keywords should be interpreted as a sequence of
1550 action steps, or as different types of TODO items. The first
1551 keywords are states requiring action - these states will select a headline
1552 for inclusion into the global TODO list Org-mode produces. If one of
1553 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1554 signify that no further action is necessary. If \"|\" is not found,
1555 the last keyword is treated as the only DONE state of the sequence.
1557 The command \\[org-todo] cycles an entry through these states, and one
1558 additional state where no keyword is present. For details about this
1559 cycling, see the manual.
1561 TODO keywords and interpretation can also be set on a per-file basis with
1562 the special #+SEQ_TODO and #+TYP_TODO lines.
1564 For backward compatibility, this variable may also be just a list
1565 of keywords - in this case the interptetation (sequence or type) will be
1566 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1567 :group 'org-todo
1568 :group 'org-keywords
1569 :type '(choice
1570 (repeat :tag "Old syntax, just keywords"
1571 (string :tag "Keyword"))
1572 (repeat :tag "New syntax"
1573 (cons
1574 (choice
1575 :tag "Interpretation"
1576 (const :tag "Sequence (cycling hits every state)" sequence)
1577 (const :tag "Type (cycling directly to DONE)" type))
1578 (repeat
1579 (string :tag "Keyword"))))))
1581 (defvar org-todo-keywords-1 nil)
1582 (make-variable-buffer-local 'org-todo-keywords-1)
1583 (defvar org-todo-keywords-for-agenda nil)
1584 (defvar org-done-keywords-for-agenda nil)
1585 (defvar org-not-done-keywords nil)
1586 (make-variable-buffer-local 'org-not-done-keywords)
1587 (defvar org-done-keywords nil)
1588 (make-variable-buffer-local 'org-done-keywords)
1589 (defvar org-todo-heads nil)
1590 (make-variable-buffer-local 'org-todo-heads)
1591 (defvar org-todo-sets nil)
1592 (make-variable-buffer-local 'org-todo-sets)
1593 (defvar org-todo-log-states nil)
1594 (make-variable-buffer-local 'org-todo-log-states)
1595 (defvar org-todo-kwd-alist nil)
1596 (make-variable-buffer-local 'org-todo-kwd-alist)
1597 (defvar org-todo-key-alist nil)
1598 (make-variable-buffer-local 'org-todo-key-alist)
1599 (defvar org-todo-key-trigger nil)
1600 (make-variable-buffer-local 'org-todo-key-trigger)
1602 (defcustom org-todo-interpretation 'sequence
1603 "Controls how TODO keywords are interpreted.
1604 This variable is in principle obsolete and is only used for
1605 backward compatibility, if the interpretation of todo keywords is
1606 not given already in `org-todo-keywords'. See that variable for
1607 more information."
1608 :group 'org-todo
1609 :group 'org-keywords
1610 :type '(choice (const sequence)
1611 (const type)))
1613 (defcustom org-use-fast-todo-selection 'prefix
1614 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1615 This variable describes if and under what circumstances the cycling
1616 mechanism for TODO keywords will be replaced by a single-key, direct
1617 selection scheme.
1619 When nil, fast selection is never used.
1621 When the symbol `prefix', it will be used when `org-todo' is called with
1622 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1623 in an agenda buffer.
1625 When t, fast selection is used by default. In this case, the prefix
1626 argument forces cycling instead.
1628 In all cases, the special interface is only used if access keys have actually
1629 been assigned by the user, i.e. if keywords in the configuration are followed
1630 by a letter in parenthesis, like TODO(t)."
1631 :group 'org-todo
1632 :type '(choice
1633 (const :tag "Never" nil)
1634 (const :tag "By default" t)
1635 (const :tag "Only with C-u C-c C-t" prefix)))
1637 (defcustom org-after-todo-state-change-hook nil
1638 "Hook which is run after the state of a TODO item was changed.
1639 The new state (a string with a TODO keyword, or nil) is available in the
1640 Lisp variable `state'."
1641 :group 'org-todo
1642 :type 'hook)
1644 (defcustom org-log-done nil
1645 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1646 When the state of an entry is changed from nothing or a DONE state to
1647 a not-done TODO state, remove a previous closing date.
1649 This can also be a list of symbols indicating under which conditions
1650 the time stamp recording the action should be annotated with a short note.
1651 Valid members of this list are
1653 done Offer to record a note when marking entries done
1654 state Offer to record a note whenever changing the TODO state
1655 of an item. This is only relevant if TODO keywords are
1656 interpreted as sequence, see variable `org-todo-interpretation'.
1657 When `state' is set, this includes tracking `done'.
1658 clock-out Offer to record a note when clocking out of an item.
1660 A separate window will then pop up and allow you to type a note.
1661 After finishing with C-c C-c, the note will be added directly after the
1662 timestamp, as a plain list item. See also the variable
1663 `org-log-note-headings'.
1665 Logging can also be configured on a per-file basis by adding one of
1666 the following lines anywhere in the buffer:
1668 #+STARTUP: logdone
1669 #+STARTUP: nologging
1670 #+STARTUP: lognotedone
1671 #+STARTUP: lognotestate
1672 #+STARTUP: lognoteclock-out
1674 You can have local logging settings for a subtree by setting the LOGGING
1675 property to one or more of these keywords."
1676 :group 'org-todo
1677 :group 'org-progress
1678 :type '(choice
1679 (const :tag "off" nil)
1680 (const :tag "on" t)
1681 (set :tag "on, with notes, detailed control" :greedy t :value (done)
1682 (const :tag "when item is marked DONE" done)
1683 (const :tag "when TODO state changes" state)
1684 (const :tag "when clocking out" clock-out))))
1686 (defcustom org-log-done-with-time t
1687 "Non-nil means, the CLOSED time stamp will contain date and time.
1688 When nil, only the date will be recorded."
1689 :group 'org-progress
1690 :type 'boolean)
1692 (defcustom org-log-note-headings
1693 '((done . "CLOSING NOTE %t")
1694 (state . "State %-12s %t")
1695 (clock-out . ""))
1696 "Headings for notes added when clocking out or closing TODO items.
1697 The value is an alist, with the car being a symbol indicating the note
1698 context, and the cdr is the heading to be used. The heading may also be the
1699 empty string.
1700 %t in the heading will be replaced by a time stamp.
1701 %s will be replaced by the new TODO state, in double quotes.
1702 %u will be replaced by the user name.
1703 %U will be replaced by the full user name."
1704 :group 'org-todo
1705 :group 'org-progress
1706 :type '(list :greedy t
1707 (cons (const :tag "Heading when closing an item" done) string)
1708 (cons (const :tag
1709 "Heading when changing todo state (todo sequence only)"
1710 state) string)
1711 (cons (const :tag "Heading when clocking out" clock-out) string)))
1713 (defcustom org-log-states-order-reversed t
1714 "Non-nil means, the latest state change note will be directly after heading.
1715 When nil, the notes will be orderer according to time."
1716 :group 'org-todo
1717 :group 'org-progress
1718 :type 'boolean)
1720 (defcustom org-log-repeat t
1721 "Non-nil means, prompt for a note when REPEAT is resetting a TODO entry.
1722 When nil, no note will be taken.
1723 This option can also be set with on a per-file-basis with
1725 #+STARTUP: logrepeat
1726 #+STARTUP: nologrepeat
1728 You can have local logging settings for a subtree by setting the LOGGING
1729 property to one or more of these keywords."
1730 :group 'org-todo
1731 :group 'org-progress
1732 :type 'boolean)
1734 (defcustom org-clock-into-drawer 2
1735 "Should clocking info be wrapped into a drawer?
1736 When t, clocking info will always be inserted into a :CLOCK: drawer.
1737 If necessary, the drawer will be created.
1738 When nil, the drawer will not be created, but used when present.
1739 When an integer and the number of clocking entries in an item
1740 reaches or exceeds this number, a drawer will be created."
1741 :group 'org-todo
1742 :group 'org-progress
1743 :type '(choice
1744 (const :tag "Always" t)
1745 (const :tag "Only when drawer exists" nil)
1746 (integer :tag "When at least N clock entries")))
1748 (defcustom org-clock-out-when-done t
1749 "When t, the clock will be stopped when the relevant entry is marked DONE.
1750 Nil means, clock will keep running until stopped explicitly with
1751 `C-c C-x C-o', or until the clock is started in a different item."
1752 :group 'org-progress
1753 :type 'boolean)
1755 (defgroup org-priorities nil
1756 "Priorities in Org-mode."
1757 :tag "Org Priorities"
1758 :group 'org-todo)
1760 (defcustom org-highest-priority ?A
1761 "The highest priority of TODO items. A character like ?A, ?B etc.
1762 Must have a smaller ASCII number than `org-lowest-priority'."
1763 :group 'org-priorities
1764 :type 'character)
1766 (defcustom org-lowest-priority ?C
1767 "The lowest priority of TODO items. A character like ?A, ?B etc.
1768 Must have a larger ASCII number than `org-highest-priority'."
1769 :group 'org-priorities
1770 :type 'character)
1772 (defcustom org-default-priority ?B
1773 "The default priority of TODO items.
1774 This is the priority an item get if no explicit priority is given."
1775 :group 'org-priorities
1776 :type 'character)
1778 (defcustom org-priority-start-cycle-with-default t
1779 "Non-nil means, start with default priority when starting to cycle.
1780 When this is nil, the first step in the cycle will be (depending on the
1781 command used) one higher or lower that the default priority."
1782 :group 'org-priorities
1783 :type 'boolean)
1785 (defgroup org-time nil
1786 "Options concerning time stamps and deadlines in Org-mode."
1787 :tag "Org Time"
1788 :group 'org)
1790 (defcustom org-insert-labeled-timestamps-at-point nil
1791 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1792 When nil, these labeled time stamps are forces into the second line of an
1793 entry, just after the headline. When scheduling from the global TODO list,
1794 the time stamp will always be forced into the second line."
1795 :group 'org-time
1796 :type 'boolean)
1798 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1799 "Formats for `format-time-string' which are used for time stamps.
1800 It is not recommended to change this constant.")
1802 (defcustom org-time-stamp-rounding-minutes 0
1803 "Number of minutes to round time stamps to upon insertion.
1804 When zero, insert the time unmodified. Useful rounding numbers
1805 should be factors of 60, so for example 5, 10, 15.
1806 When this is not zero, you can still force an exact time-stamp by using
1807 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1808 :group 'org-time
1809 :type 'integer)
1811 (defcustom org-display-custom-times nil
1812 "Non-nil means, overlay custom formats over all time stamps.
1813 The formats are defined through the variable `org-time-stamp-custom-formats'.
1814 To turn this on on a per-file basis, insert anywhere in the file:
1815 #+STARTUP: customtime"
1816 :group 'org-time
1817 :set 'set-default
1818 :type 'sexp)
1819 (make-variable-buffer-local 'org-display-custom-times)
1821 (defcustom org-time-stamp-custom-formats
1822 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1823 "Custom formats for time stamps. See `format-time-string' for the syntax.
1824 These are overlayed over the default ISO format if the variable
1825 `org-display-custom-times' is set. Time like %H:%M should be at the
1826 end of the second format."
1827 :group 'org-time
1828 :type 'sexp)
1830 (defun org-time-stamp-format (&optional long inactive)
1831 "Get the right format for a time string."
1832 (let ((f (if long (cdr org-time-stamp-formats)
1833 (car org-time-stamp-formats))))
1834 (if inactive
1835 (concat "[" (substring f 1 -1) "]")
1836 f)))
1838 (defcustom org-read-date-prefer-future t
1839 "Non-nil means, assume future for incomplete date input from user.
1840 This affects the following situations:
1841 1. The user gives a day, but no month.
1842 For example, if today is the 15th, and you enter \"3\", Org-mode will
1843 read this as the third of *next* month. However, if you enter \"17\",
1844 it will be considered as *this* month.
1845 2. The user gives a month but not a year.
1846 For example, if it is april and you enter \"feb 2\", this will be read
1847 as feb 2, *next* year. \"May 5\", however, will be this year.
1849 When this option is nil, the current month and year will always be used
1850 as defaults."
1851 :group 'org-time
1852 :type 'boolean)
1854 (defcustom org-read-date-display-live t
1855 "Non-nil means, display current interpretation of date prompt live.
1856 This display will be in an overlay, in the minibuffer."
1857 :group 'org-time
1858 :type 'boolean)
1860 (defcustom org-read-date-popup-calendar t
1861 "Non-nil means, pop up a calendar when prompting for a date.
1862 In the calendar, the date can be selected with mouse-1. However, the
1863 minibuffer will also be active, and you can simply enter the date as well.
1864 When nil, only the minibuffer will be available."
1865 :group 'org-time
1866 :type 'boolean)
1867 (if (fboundp 'defvaralias)
1868 (defvaralias 'org-popup-calendar-for-date-prompt
1869 'org-read-date-popup-calendar))
1871 (defcustom org-extend-today-until 0
1872 "The hour when your day really ends.
1873 This has influence for the following applications:
1874 - When switching the agenda to \"today\". It it is still earlier than
1875 the time given here, the day recognized as TODAY is actually yesterday.
1876 - When a date is read from the user and it is still before the time given
1877 here, the current date and time will be assumed to be yesterday, 23:59.
1879 FIXME:
1880 IMPORTANT: This is still a very experimental feature, it may disappear
1881 again or it may be extended to mean more things."
1882 :group 'org-time
1883 :type 'number)
1885 (defcustom org-edit-timestamp-down-means-later nil
1886 "Non-nil means, S-down will increase the time in a time stamp.
1887 When nil, S-up will increase."
1888 :group 'org-time
1889 :type 'boolean)
1891 (defcustom org-calendar-follow-timestamp-change t
1892 "Non-nil means, make the calendar window follow timestamp changes.
1893 When a timestamp is modified and the calendar window is visible, it will be
1894 moved to the new date."
1895 :group 'org-time
1896 :type 'boolean)
1898 (defcustom org-clock-heading-function nil
1899 "When non-nil, should be a function to create `org-clock-heading'.
1900 This is the string shown in the mode line when a clock is running.
1901 The function is called with point at the beginning of the headline."
1902 :group 'org-time ; FIXME: Should we have a separate group????
1903 :type 'function)
1905 (defgroup org-tags nil
1906 "Options concerning tags in Org-mode."
1907 :tag "Org Tags"
1908 :group 'org)
1910 (defcustom org-tag-alist nil
1911 "List of tags allowed in Org-mode files.
1912 When this list is nil, Org-mode will base TAG input on what is already in the
1913 buffer.
1914 The value of this variable is an alist, the car of each entry must be a
1915 keyword as a string, the cdr may be a character that is used to select
1916 that tag through the fast-tag-selection interface.
1917 See the manual for details."
1918 :group 'org-tags
1919 :type '(repeat
1920 (choice
1921 (cons (string :tag "Tag name")
1922 (character :tag "Access char"))
1923 (const :tag "Start radio group" (:startgroup))
1924 (const :tag "End radio group" (:endgroup)))))
1926 (defcustom org-use-fast-tag-selection 'auto
1927 "Non-nil means, use fast tag selection scheme.
1928 This is a special interface to select and deselect tags with single keys.
1929 When nil, fast selection is never used.
1930 When the symbol `auto', fast selection is used if and only if selection
1931 characters for tags have been configured, either through the variable
1932 `org-tag-alist' or through a #+TAGS line in the buffer.
1933 When t, fast selection is always used and selection keys are assigned
1934 automatically if necessary."
1935 :group 'org-tags
1936 :type '(choice
1937 (const :tag "Always" t)
1938 (const :tag "Never" nil)
1939 (const :tag "When selection characters are configured" 'auto)))
1941 (defcustom org-fast-tag-selection-single-key nil
1942 "Non-nil means, fast tag selection exits after first change.
1943 When nil, you have to press RET to exit it.
1944 During fast tag selection, you can toggle this flag with `C-c'.
1945 This variable can also have the value `expert'. In this case, the window
1946 displaying the tags menu is not even shown, until you press C-c again."
1947 :group 'org-tags
1948 :type '(choice
1949 (const :tag "No" nil)
1950 (const :tag "Yes" t)
1951 (const :tag "Expert" expert)))
1953 (defvar org-fast-tag-selection-include-todo nil
1954 "Non-nil means, fast tags selection interface will also offer TODO states.
1955 This is an undocumented feature, you should not rely on it.")
1957 (defcustom org-tags-column -80
1958 "The column to which tags should be indented in a headline.
1959 If this number is positive, it specifies the column. If it is negative,
1960 it means that the tags should be flushright to that column. For example,
1961 -80 works well for a normal 80 character screen."
1962 :group 'org-tags
1963 :type 'integer)
1965 (defcustom org-auto-align-tags t
1966 "Non-nil means, realign tags after pro/demotion of TODO state change.
1967 These operations change the length of a headline and therefore shift
1968 the tags around. With this options turned on, after each such operation
1969 the tags are again aligned to `org-tags-column'."
1970 :group 'org-tags
1971 :type 'boolean)
1973 (defcustom org-use-tag-inheritance t
1974 "Non-nil means, tags in levels apply also for sublevels.
1975 When nil, only the tags directly given in a specific line apply there.
1976 If you turn off this option, you very likely want to turn on the
1977 companion option `org-tags-match-list-sublevels'."
1978 :group 'org-tags
1979 :type 'boolean)
1981 (defcustom org-tags-match-list-sublevels nil
1982 "Non-nil means list also sublevels of headlines matching tag search.
1983 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1984 the sublevels of a headline matching a tag search often also match
1985 the same search. Listing all of them can create very long lists.
1986 Setting this variable to nil causes subtrees of a match to be skipped.
1987 This option is off by default, because inheritance in on. If you turn
1988 inheritance off, you very likely want to turn this option on.
1990 As a special case, if the tag search is restricted to TODO items, the
1991 value of this variable is ignored and sublevels are always checked, to
1992 make sure all corresponding TODO items find their way into the list."
1993 :group 'org-tags
1994 :type 'boolean)
1996 (defvar org-tags-history nil
1997 "History of minibuffer reads for tags.")
1998 (defvar org-last-tags-completion-table nil
1999 "The last used completion table for tags.")
2000 (defvar org-after-tags-change-hook nil
2001 "Hook that is run after the tags in a line have changed.")
2003 (defgroup org-properties nil
2004 "Options concerning properties in Org-mode."
2005 :tag "Org Properties"
2006 :group 'org)
2008 (defcustom org-property-format "%-10s %s"
2009 "How property key/value pairs should be formatted by `indent-line'.
2010 When `indent-line' hits a property definition, it will format the line
2011 according to this format, mainly to make sure that the values are
2012 lined-up with respect to each other."
2013 :group 'org-properties
2014 :type 'string)
2016 (defcustom org-use-property-inheritance nil
2017 "Non-nil means, properties apply also for sublevels.
2018 This setting is only relevant during property searches, not when querying
2019 an entry with `org-entry-get'. To retrieve a property with inheritance,
2020 you need to call `org-entry-get' with the inheritance flag.
2021 Turning this on can cause significant overhead when doing a search, so
2022 this is turned off by default.
2023 When nil, only the properties directly given in the current entry count.
2024 The value may also be a list of properties that shouldhave inheritance.
2026 However, note that some special properties use inheritance under special
2027 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2028 and the properties ending in \"_ALL\" when they are used as descriptor
2029 for valid values of a property."
2030 :group 'org-properties
2031 :type '(choice
2032 (const :tag "Not" nil)
2033 (const :tag "Always" nil)
2034 (repeat :tag "Specific properties")))
2036 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2037 "The default column format, if no other format has been defined.
2038 This variable can be set on the per-file basis by inserting a line
2040 #+COLUMNS: %25ITEM ....."
2041 :group 'org-properties
2042 :type 'string)
2044 (defcustom org-global-properties nil
2045 "List of property/value pairs that can be inherited by any entry.
2046 You can set buffer-local values for this by adding lines like
2048 #+PROPERTY: NAME VALUE"
2049 :group 'org-properties
2050 :type '(repeat
2051 (cons (string :tag "Property")
2052 (string :tag "Value"))))
2054 (defvar org-local-properties nil
2055 "List of property/value pairs that can be inherited by any entry.
2056 Valid for the current buffer.
2057 This variable is populated from #+PROPERTY lines.")
2059 (defgroup org-agenda nil
2060 "Options concerning agenda views in Org-mode."
2061 :tag "Org Agenda"
2062 :group 'org)
2064 (defvar org-category nil
2065 "Variable used by org files to set a category for agenda display.
2066 Such files should use a file variable to set it, for example
2068 # -*- mode: org; org-category: \"ELisp\"
2070 or contain a special line
2072 #+CATEGORY: ELisp
2074 If the file does not specify a category, then file's base name
2075 is used instead.")
2076 (make-variable-buffer-local 'org-category)
2078 (defcustom org-agenda-files nil
2079 "The files to be used for agenda display.
2080 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2081 \\[org-remove-file]. You can also use customize to edit the list.
2083 If an entry is a directory, all files in that directory that are matched by
2084 `org-agenda-file-regexp' will be part of the file list.
2086 If the value of the variable is not a list but a single file name, then
2087 the list of agenda files is actually stored and maintained in that file, one
2088 agenda file per line."
2089 :group 'org-agenda
2090 :type '(choice
2091 (repeat :tag "List of files and directories" file)
2092 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2094 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2095 "Regular expression to match files for `org-agenda-files'.
2096 If any element in the list in that variable contains a directory instead
2097 of a normal file, all files in that directory that are matched by this
2098 regular expression will be included."
2099 :group 'org-agenda
2100 :type 'regexp)
2102 (defcustom org-agenda-skip-unavailable-files nil
2103 "t means to just skip non-reachable files in `org-agenda-files'.
2104 Nil means to remove them, after a query, from the list."
2105 :group 'org-agenda
2106 :type 'boolean)
2108 (defcustom org-agenda-multi-occur-extra-files nil
2109 "List of extra files to be searched by `org-occur-in-agenda-files'.
2110 The files in `org-agenda-files' are always searched."
2111 :group 'org-agenda
2112 :type '(repeat file))
2114 (defcustom org-agenda-confirm-kill 1
2115 "When set, remote killing from the agenda buffer needs confirmation.
2116 When t, a confirmation is always needed. When a number N, confirmation is
2117 only needed when the text to be killed contains more than N non-white lines."
2118 :group 'org-agenda
2119 :type '(choice
2120 (const :tag "Never" nil)
2121 (const :tag "Always" t)
2122 (number :tag "When more than N lines")))
2124 (defcustom org-calendar-to-agenda-key [?c]
2125 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2126 The command `org-calendar-goto-agenda' will be bound to this key. The
2127 default is the character `c' because then `c' can be used to switch back and
2128 forth between agenda and calendar."
2129 :group 'org-agenda
2130 :type 'sexp)
2132 (defcustom org-agenda-compact-blocks nil
2133 "Non-nil means, make the block agenda more compact.
2134 This is done by leaving out unnecessary lines."
2135 :group 'org-agenda
2136 :type nil)
2138 (defgroup org-agenda-export nil
2139 "Options concerning exporting agenda views in Org-mode."
2140 :tag "Org Agenda Export"
2141 :group 'org-agenda)
2143 (defcustom org-agenda-with-colors t
2144 "Non-nil means, use colors in agenda views."
2145 :group 'org-agenda-export
2146 :type 'boolean)
2148 (defcustom org-agenda-exporter-settings nil
2149 "Alist of variable/value pairs that should be active during agenda export.
2150 This is a good place to set uptions for ps-print and for htmlize."
2151 :group 'org-agenda-export
2152 :type '(repeat
2153 (list
2154 (variable)
2155 (sexp :tag "Value"))))
2157 (defcustom org-agenda-export-html-style ""
2158 "The style specification for exported HTML Agenda files.
2159 If this variable contains a string, it will replace the default <style>
2160 section as produced by `htmlize'.
2161 Since there are different ways of setting style information, this variable
2162 needs to contain the full HTML structure to provide a style, including the
2163 surrounding HTML tags. The style specifications should include definitions
2164 the fonts used by the agenda, here is an example:
2166 <style type=\"text/css\">
2167 p { font-weight: normal; color: gray; }
2168 .org-agenda-structure {
2169 font-size: 110%;
2170 color: #003399;
2171 font-weight: 600;
2173 .org-todo {
2174 color: #cc6666;Week-agenda:
2175 font-weight: bold;
2177 .org-done {
2178 color: #339933;
2180 .title { text-align: center; }
2181 .todo, .deadline { color: red; }
2182 .done { color: green; }
2183 </style>
2185 or, if you want to keep the style in a file,
2187 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2189 As the value of this option simply gets inserted into the HTML <head> header,
2190 you can \"misuse\" it to also add other text to the header. However,
2191 <style>...</style> is required, if not present the variable will be ignored."
2192 :group 'org-agenda-export
2193 :group 'org-export-html
2194 :type 'string)
2196 (defgroup org-agenda-custom-commands nil
2197 "Options concerning agenda views in Org-mode."
2198 :tag "Org Agenda Custom Commands"
2199 :group 'org-agenda)
2201 (defcustom org-agenda-custom-commands nil
2202 "Custom commands for the agenda.
2203 These commands will be offered on the splash screen displayed by the
2204 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2206 (key desc type match options files)
2208 key The key (one or more characters as a string) to be associated
2209 with the command.
2210 desc A description of the commend, when omitted or nil, a default
2211 description is built using MATCH.
2212 type The command type, any of the following symbols:
2213 todo Entries with a specific TODO keyword, in all agenda files.
2214 tags Tags match in all agenda files.
2215 tags-todo Tags match in all agenda files, TODO entries only.
2216 todo-tree Sparse tree of specific TODO keyword in *current* file.
2217 tags-tree Sparse tree with all tags matches in *current* file.
2218 occur-tree Occur sparse tree for *current* file.
2219 ... A user-defined function.
2220 match What to search for:
2221 - a single keyword for TODO keyword searches
2222 - a tags match expression for tags searches
2223 - a regular expression for occur searches
2224 options A list of option settings, similar to that in a let form, so like
2225 this: ((opt1 val1) (opt2 val2) ...)
2226 files A list of files file to write the produced agenda buffer to
2227 with the command `org-store-agenda-views'.
2228 If a file name ends in \".html\", an HTML version of the buffer
2229 is written out. If it ends in \".ps\", a postscript version is
2230 produced. Otherwide, only the plain text is written to the file.
2232 You can also define a set of commands, to create a composite agenda buffer.
2233 In this case, an entry looks like this:
2235 (key desc (cmd1 cmd2 ...) general-options file)
2237 where
2239 desc A description string to be displayed in the dispatcher menu.
2240 cmd An agenda command, similar to the above. However, tree commands
2241 are no allowed, but instead you can get agenda and global todo list.
2242 So valid commands for a set are:
2243 (agenda)
2244 (alltodo)
2245 (stuck)
2246 (todo \"match\" options files)
2247 (tags \"match\" options files)
2248 (tags-todo \"match\" options files)
2250 Each command can carry a list of options, and another set of options can be
2251 given for the whole set of commands. Individual command options take
2252 precedence over the general options.
2254 When using several characters as key to a command, the first characters
2255 are prefix commands. For the dispatcher to display useful information, you
2256 should provide a description for the prefix, like
2258 (setq org-agenda-custom-commands
2259 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2260 (\"hl\" tags \"+HOME+Lisa\")
2261 (\"hp\" tags \"+HOME+Peter\")
2262 (\"hk\" tags \"+HOME+Kim\")))"
2263 :group 'org-agenda-custom-commands
2264 :type '(repeat
2265 (choice :value ("a" "" tags "" nil)
2266 (list :tag "Single command"
2267 (string :tag "Access Key(s) ")
2268 (option (string :tag "Description"))
2269 (choice
2270 (const :tag "Agenda" agenda)
2271 (const :tag "TODO list" alltodo)
2272 (const :tag "Stuck projects" stuck)
2273 (const :tag "Tags search (all agenda files)" tags)
2274 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2275 (const :tag "TODO keyword search (all agenda files)" todo)
2276 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2277 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2278 (const :tag "Occur tree (current buffer)" occur-tree)
2279 (sexp :tag "Other, user-defined function"))
2280 (string :tag "Match")
2281 (repeat :tag "Local options"
2282 (list (variable :tag "Option") (sexp :tag "Value")))
2283 (option (repeat :tag "Export" (file :tag "Export to"))))
2284 (list :tag "Command series, all agenda files"
2285 (string :tag "Access Key(s)")
2286 (string :tag "Description ")
2287 (repeat
2288 (choice
2289 (const :tag "Agenda" (agenda))
2290 (const :tag "TODO list" (alltodo))
2291 (const :tag "Stuck projects" (stuck))
2292 (list :tag "Tags search"
2293 (const :format "" tags)
2294 (string :tag "Match")
2295 (repeat :tag "Local options"
2296 (list (variable :tag "Option")
2297 (sexp :tag "Value"))))
2299 (list :tag "Tags search, TODO entries only"
2300 (const :format "" tags-todo)
2301 (string :tag "Match")
2302 (repeat :tag "Local options"
2303 (list (variable :tag "Option")
2304 (sexp :tag "Value"))))
2306 (list :tag "TODO keyword search"
2307 (const :format "" todo)
2308 (string :tag "Match")
2309 (repeat :tag "Local options"
2310 (list (variable :tag "Option")
2311 (sexp :tag "Value"))))
2313 (list :tag "Other, user-defined function"
2314 (symbol :tag "function")
2315 (string :tag "Match")
2316 (repeat :tag "Local options"
2317 (list (variable :tag "Option")
2318 (sexp :tag "Value"))))))
2320 (repeat :tag "General options"
2321 (list (variable :tag "Option")
2322 (sexp :tag "Value")))
2323 (option (repeat :tag "Export" (file :tag "Export to"))))
2324 (cons :tag "Prefix key documentation"
2325 (string :tag "Access Key(s)")
2326 (string :tag "Description ")))))
2328 (defcustom org-stuck-projects
2329 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2330 "How to identify stuck projects.
2331 This is a list of four items:
2332 1. A tags/todo matcher string that is used to identify a project.
2333 The entire tree below a headline matched by this is considered one project.
2334 2. A list of TODO keywords identifying non-stuck projects.
2335 If the project subtree contains any headline with one of these todo
2336 keywords, the project is considered to be not stuck. If you specify
2337 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2338 3. A list of tags identifying non-stuck projects.
2339 If the project subtree contains any headline with one of these tags,
2340 the project is considered to be not stuck. If you specify \"*\" as
2341 a tag, any tag will mark the project unstuck.
2342 4. An arbitrary regular expression matching non-stuck projects.
2344 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2345 or `C-c a #' to produce the list."
2346 :group 'org-agenda-custom-commands
2347 :type '(list
2348 (string :tag "Tags/TODO match to identify a project")
2349 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2350 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2351 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2354 (defgroup org-agenda-skip nil
2355 "Options concerning skipping parts of agenda files."
2356 :tag "Org Agenda Skip"
2357 :group 'org-agenda)
2359 (defcustom org-agenda-todo-list-sublevels t
2360 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2361 When nil, the sublevels of a TODO entry are not checked, resulting in
2362 potentially much shorter TODO lists."
2363 :group 'org-agenda-skip
2364 :group 'org-todo
2365 :type 'boolean)
2367 (defcustom org-agenda-todo-ignore-with-date nil
2368 "Non-nil means, don't show entries with a date in the global todo list.
2369 You can use this if you prefer to mark mere appointments with a TODO keyword,
2370 but don't want them to show up in the TODO list.
2371 When this is set, it also covers deadlines and scheduled items, the settings
2372 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2373 will be ignored."
2374 :group 'org-agenda-skip
2375 :group 'org-todo
2376 :type 'boolean)
2378 (defcustom org-agenda-todo-ignore-scheduled nil
2379 "Non-nil means, don't show scheduled entries in the global todo list.
2380 The idea behind this is that by scheduling it, you have already taken care
2381 of this item.
2382 See also `org-agenda-todo-ignore-with-date'."
2383 :group 'org-agenda-skip
2384 :group 'org-todo
2385 :type 'boolean)
2387 (defcustom org-agenda-todo-ignore-deadlines nil
2388 "Non-nil means, don't show near deadline entries in the global todo list.
2389 Near means closer than `org-deadline-warning-days' days.
2390 The idea behind this is that such items will appear in the agenda anyway.
2391 See also `org-agenda-todo-ignore-with-date'."
2392 :group 'org-agenda-skip
2393 :group 'org-todo
2394 :type 'boolean)
2396 (defcustom org-agenda-skip-scheduled-if-done nil
2397 "Non-nil means don't show scheduled items in agenda when they are done.
2398 This is relevant for the daily/weekly agenda, not for the TODO list. And
2399 it applies only to the actual date of the scheduling. Warnings about
2400 an item with a past scheduling dates are always turned off when the item
2401 is DONE."
2402 :group 'org-agenda-skip
2403 :type 'boolean)
2405 (defcustom org-agenda-skip-deadline-if-done nil
2406 "Non-nil means don't show deadines when the corresponding item is done.
2407 When nil, the deadline is still shown and should give you a happy feeling.
2408 This is relevant for the daily/weekly agenda. And it applied only to the
2409 actualy date of the deadline. Warnings about approching and past-due
2410 deadlines are always turned off when the item is DONE."
2411 :group 'org-agenda-skip
2412 :type 'boolean)
2414 (defcustom org-agenda-skip-timestamp-if-done nil
2415 "Non-nil means don't don't select item by timestamp or -range if it is DONE."
2416 :group 'org-agenda-skip
2417 :type 'boolean)
2419 (defcustom org-timeline-show-empty-dates 3
2420 "Non-nil means, `org-timeline' also shows dates without an entry.
2421 When nil, only the days which actually have entries are shown.
2422 When t, all days between the first and the last date are shown.
2423 When an integer, show also empty dates, but if there is a gap of more than
2424 N days, just insert a special line indicating the size of the gap."
2425 :group 'org-agenda-skip
2426 :type '(choice
2427 (const :tag "None" nil)
2428 (const :tag "All" t)
2429 (number :tag "at most")))
2432 (defgroup org-agenda-startup nil
2433 "Options concerning initial settings in the Agenda in Org Mode."
2434 :tag "Org Agenda Startup"
2435 :group 'org-agenda)
2437 (defcustom org-finalize-agenda-hook nil
2438 "Hook run just before displaying an agenda buffer."
2439 :group 'org-agenda-startup
2440 :type 'hook)
2442 (defcustom org-agenda-mouse-1-follows-link nil
2443 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2444 A longer mouse click will still set point. Does not wortk on XEmacs.
2445 Needs to be set before org.el is loaded."
2446 :group 'org-agenda-startup
2447 :type 'boolean)
2449 (defcustom org-agenda-start-with-follow-mode nil
2450 "The initial value of follow-mode in a newly created agenda window."
2451 :group 'org-agenda-startup
2452 :type 'boolean)
2454 (defgroup org-agenda-windows nil
2455 "Options concerning the windows used by the Agenda in Org Mode."
2456 :tag "Org Agenda Windows"
2457 :group 'org-agenda)
2459 (defcustom org-agenda-window-setup 'reorganize-frame
2460 "How the agenda buffer should be displayed.
2461 Possible values for this option are:
2463 current-window Show agenda in the current window, keeping all other windows.
2464 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2465 other-window Use `switch-to-buffer-other-window' to display agenda.
2466 reorganize-frame Show only two windows on the current frame, the current
2467 window and the agenda.
2468 See also the variable `org-agenda-restore-windows-after-quit'."
2469 :group 'org-agenda-windows
2470 :type '(choice
2471 (const current-window)
2472 (const other-frame)
2473 (const other-window)
2474 (const reorganize-frame)))
2476 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2477 "The min and max height of the agenda window as a fraction of frame height.
2478 The value of the variable is a cons cell with two numbers between 0 and 1.
2479 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2480 :group 'org-agenda-windows
2481 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2483 (defcustom org-agenda-restore-windows-after-quit nil
2484 "Non-nil means, restore window configuration open exiting agenda.
2485 Before the window configuration is changed for displaying the agenda,
2486 the current status is recorded. When the agenda is exited with
2487 `q' or `x' and this option is set, the old state is restored. If
2488 `org-agenda-window-setup' is `other-frame', the value of this
2489 option will be ignored.."
2490 :group 'org-agenda-windows
2491 :type 'boolean)
2493 (defcustom org-indirect-buffer-display 'other-window
2494 "How should indirect tree buffers be displayed?
2495 This applies to indirect buffers created with the commands
2496 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2497 Valid values are:
2498 current-window Display in the current window
2499 other-window Just display in another window.
2500 dedicated-frame Create one new frame, and re-use it each time.
2501 new-frame Make a new frame each time. Note that in this case
2502 previously-made indirect buffers are kept, and you need to
2503 kill these buffers yourself."
2504 :group 'org-structure
2505 :group 'org-agenda-windows
2506 :type '(choice
2507 (const :tag "In current window" current-window)
2508 (const :tag "In current frame, other window" other-window)
2509 (const :tag "Each time a new frame" new-frame)
2510 (const :tag "One dedicated frame" dedicated-frame)))
2512 (defgroup org-agenda-daily/weekly nil
2513 "Options concerning the daily/weekly agenda."
2514 :tag "Org Agenda Daily/Weekly"
2515 :group 'org-agenda)
2517 (defcustom org-agenda-ndays 7
2518 "Number of days to include in overview display.
2519 Should be 1 or 7."
2520 :group 'org-agenda-daily/weekly
2521 :type 'number)
2523 (defcustom org-agenda-start-on-weekday 1
2524 "Non-nil means, start the overview always on the specified weekday.
2525 0 denotes Sunday, 1 denotes Monday etc.
2526 When nil, always start on the current day."
2527 :group 'org-agenda-daily/weekly
2528 :type '(choice (const :tag "Today" nil)
2529 (number :tag "Weekday No.")))
2531 (defcustom org-agenda-show-all-dates t
2532 "Non-nil means, `org-agenda' shows every day in the selected range.
2533 When nil, only the days which actually have entries are shown."
2534 :group 'org-agenda-daily/weekly
2535 :type 'boolean)
2537 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2538 "Format string for displaying dates in the agenda.
2539 Used by the daily/weekly agenda and by the timeline. This should be
2540 a format string understood by `format-time-string', or a function returning
2541 the formatted date as a string. The function must take a single argument,
2542 a calendar-style date list like (month day year)."
2543 :group 'org-agenda-daily/weekly
2544 :type '(choice
2545 (string :tag "Format string")
2546 (function :tag "Function")))
2548 (defun org-agenda-format-date-aligned (date)
2549 "Format a date string for display in the daily/weekly agenda, or timeline.
2550 This function makes sure that dates are aligned for easy reading."
2551 (format "%-9s %2d %s %4d"
2552 (calendar-day-name date)
2553 (extract-calendar-day date)
2554 (calendar-month-name (extract-calendar-month date))
2555 (extract-calendar-year date)))
2557 (defcustom org-agenda-include-diary nil
2558 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2559 :group 'org-agenda-daily/weekly
2560 :type 'boolean)
2562 (defcustom org-agenda-include-all-todo nil
2563 "Set means weekly/daily agenda will always contain all TODO entries.
2564 The TODO entries will be listed at the top of the agenda, before
2565 the entries for specific days."
2566 :group 'org-agenda-daily/weekly
2567 :type 'boolean)
2569 (defcustom org-agenda-repeating-timestamp-show-all t
2570 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2571 When nil, only one occurence is shown, either today or the
2572 nearest into the future."
2573 :group 'org-agenda-daily/weekly
2574 :type 'boolean)
2576 (defcustom org-deadline-warning-days 14
2577 "No. of days before expiration during which a deadline becomes active.
2578 This variable governs the display in sparse trees and in the agenda.
2579 When negative, it means use this number (the absolute value of it)
2580 even if a deadline has a different individual lead time specified."
2581 :group 'org-time
2582 :group 'org-agenda-daily/weekly
2583 :type 'number)
2585 (defcustom org-scheduled-past-days 10000
2586 "No. of days to continue listing scheduled items that are not marked DONE.
2587 When an item is scheduled on a date, it shows up in the agenda on this
2588 day and will be listed until it is marked done for the number of days
2589 given here."
2590 :group 'org-agenda-daily/weekly
2591 :type 'number)
2593 (defgroup org-agenda-time-grid nil
2594 "Options concerning the time grid in the Org-mode Agenda."
2595 :tag "Org Agenda Time Grid"
2596 :group 'org-agenda)
2598 (defcustom org-agenda-use-time-grid t
2599 "Non-nil means, show a time grid in the agenda schedule.
2600 A time grid is a set of lines for specific times (like every two hours between
2601 8:00 and 20:00). The items scheduled for a day at specific times are
2602 sorted in between these lines.
2603 For details about when the grid will be shown, and what it will look like, see
2604 the variable `org-agenda-time-grid'."
2605 :group 'org-agenda-time-grid
2606 :type 'boolean)
2608 (defcustom org-agenda-time-grid
2609 '((daily today require-timed)
2610 "----------------"
2611 (800 1000 1200 1400 1600 1800 2000))
2613 "The settings for time grid for agenda display.
2614 This is a list of three items. The first item is again a list. It contains
2615 symbols specifying conditions when the grid should be displayed:
2617 daily if the agenda shows a single day
2618 weekly if the agenda shows an entire week
2619 today show grid on current date, independent of daily/weekly display
2620 require-timed show grid only if at least one item has a time specification
2622 The second item is a string which will be places behing the grid time.
2624 The third item is a list of integers, indicating the times that should have
2625 a grid line."
2626 :group 'org-agenda-time-grid
2627 :type
2628 '(list
2629 (set :greedy t :tag "Grid Display Options"
2630 (const :tag "Show grid in single day agenda display" daily)
2631 (const :tag "Show grid in weekly agenda display" weekly)
2632 (const :tag "Always show grid for today" today)
2633 (const :tag "Show grid only if any timed entries are present"
2634 require-timed)
2635 (const :tag "Skip grid times already present in an entry"
2636 remove-match))
2637 (string :tag "Grid String")
2638 (repeat :tag "Grid Times" (integer :tag "Time"))))
2640 (defgroup org-agenda-sorting nil
2641 "Options concerning sorting in the Org-mode Agenda."
2642 :tag "Org Agenda Sorting"
2643 :group 'org-agenda)
2645 (defconst org-sorting-choice
2646 '(choice
2647 (const time-up) (const time-down)
2648 (const category-keep) (const category-up) (const category-down)
2649 (const tag-down) (const tag-up)
2650 (const priority-up) (const priority-down))
2651 "Sorting choices.")
2653 (defcustom org-agenda-sorting-strategy
2654 '((agenda time-up category-keep priority-down)
2655 (todo category-keep priority-down)
2656 (tags category-keep priority-down))
2657 "Sorting structure for the agenda items of a single day.
2658 This is a list of symbols which will be used in sequence to determine
2659 if an entry should be listed before another entry. The following
2660 symbols are recognized:
2662 time-up Put entries with time-of-day indications first, early first
2663 time-down Put entries with time-of-day indications first, late first
2664 category-keep Keep the default order of categories, corresponding to the
2665 sequence in `org-agenda-files'.
2666 category-up Sort alphabetically by category, A-Z.
2667 category-down Sort alphabetically by category, Z-A.
2668 tag-up Sort alphabetically by last tag, A-Z.
2669 tag-down Sort alphabetically by last tag, Z-A.
2670 priority-up Sort numerically by priority, high priority last.
2671 priority-down Sort numerically by priority, high priority first.
2673 The different possibilities will be tried in sequence, and testing stops
2674 if one comparison returns a \"not-equal\". For example, the default
2675 '(time-up category-keep priority-down)
2676 means: Pull out all entries having a specified time of day and sort them,
2677 in order to make a time schedule for the current day the first thing in the
2678 agenda listing for the day. Of the entries without a time indication, keep
2679 the grouped in categories, don't sort the categories, but keep them in
2680 the sequence given in `org-agenda-files'. Within each category sort by
2681 priority.
2683 Leaving out `category-keep' would mean that items will be sorted across
2684 categories by priority.
2686 Instead of a single list, this can also be a set of list for specific
2687 contents, with a context symbol in the car of the list, any of
2688 `agenda', `todo', `tags' for the corresponding agenda views."
2689 :group 'org-agenda-sorting
2690 :type `(choice
2691 (repeat :tag "General" org-sorting-choice)
2692 (list :tag "Individually"
2693 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2694 (repeat ,org-sorting-choice))
2695 (cons (const :tag "Strategy for TODO lists" todo)
2696 (repeat ,org-sorting-choice))
2697 (cons (const :tag "Strategy for Tags matches" tags)
2698 (repeat ,org-sorting-choice)))))
2700 (defcustom org-sort-agenda-notime-is-late t
2701 "Non-nil means, items without time are considered late.
2702 This is only relevant for sorting. When t, items which have no explicit
2703 time like 15:30 will be considered as 99:01, i.e. later than any items which
2704 do have a time. When nil, the default time is before 0:00. You can use this
2705 option to decide if the schedule for today should come before or after timeless
2706 agenda entries."
2707 :group 'org-agenda-sorting
2708 :type 'boolean)
2710 (defgroup org-agenda-line-format nil
2711 "Options concerning the entry prefix in the Org-mode agenda display."
2712 :tag "Org Agenda Line Format"
2713 :group 'org-agenda)
2715 (defcustom org-agenda-prefix-format
2716 '((agenda . " %-12:c%?-12t% s")
2717 (timeline . " % s")
2718 (todo . " %-12:c")
2719 (tags . " %-12:c"))
2720 "Format specifications for the prefix of items in the agenda views.
2721 An alist with four entries, for the different agenda types. The keys to the
2722 sublists are `agenda', `timeline', `todo', and `tags'. The values
2723 are format strings.
2724 This format works similar to a printf format, with the following meaning:
2726 %c the category of the item, \"Diary\" for entries from the diary, or
2727 as given by the CATEGORY keyword or derived from the file name.
2728 %T the *last* tag of the item. Last because inherited tags come
2729 first in the list.
2730 %t the time-of-day specification if one applies to the entry, in the
2731 format HH:MM
2732 %s Scheduling/Deadline information, a short string
2734 All specifiers work basically like the standard `%s' of printf, but may
2735 contain two additional characters: A question mark just after the `%' and
2736 a whitespace/punctuation character just before the final letter.
2738 If the first character after `%' is a question mark, the entire field
2739 will only be included if the corresponding value applies to the
2740 current entry. This is useful for fields which should have fixed
2741 width when present, but zero width when absent. For example,
2742 \"%?-12t\" will result in a 12 character time field if a time of the
2743 day is specified, but will completely disappear in entries which do
2744 not contain a time.
2746 If there is punctuation or whitespace character just before the final
2747 format letter, this character will be appended to the field value if
2748 the value is not empty. For example, the format \"%-12:c\" leads to
2749 \"Diary: \" if the category is \"Diary\". If the category were be
2750 empty, no additional colon would be interted.
2752 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2753 - Indent the line with two space characters
2754 - Give the category in a 12 chars wide field, padded with whitespace on
2755 the right (because of `-'). Append a colon if there is a category
2756 (because of `:').
2757 - If there is a time-of-day, put it into a 12 chars wide field. If no
2758 time, don't put in an empty field, just skip it (because of '?').
2759 - Finally, put the scheduling information and append a whitespace.
2761 As another example, if you don't want the time-of-day of entries in
2762 the prefix, you could use:
2764 (setq org-agenda-prefix-format \" %-11:c% s\")
2766 See also the variables `org-agenda-remove-times-when-in-prefix' and
2767 `org-agenda-remove-tags'."
2768 :type '(choice
2769 (string :tag "General format")
2770 (list :greedy t :tag "View dependent"
2771 (cons (const agenda) (string :tag "Format"))
2772 (cons (const timeline) (string :tag "Format"))
2773 (cons (const todo) (string :tag "Format"))
2774 (cons (const tags) (string :tag "Format"))))
2775 :group 'org-agenda-line-format)
2777 (defvar org-prefix-format-compiled nil
2778 "The compiled version of the most recently used prefix format.
2779 See the variable `org-agenda-prefix-format'.")
2781 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
2782 "Text preceeding scheduled items in the agenda view.
2783 THis is a list with two strings. The first applies when the item is
2784 scheduled on the current day. The second applies when it has been scheduled
2785 previously, it may contain a %d to capture how many days ago the item was
2786 scheduled."
2787 :group 'org-agenda-line-format
2788 :type '(list
2789 (string :tag "Scheduled today ")
2790 (string :tag "Scheduled previously")))
2792 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
2793 "Text preceeding deadline items in the agenda view.
2794 This is a list with two strings. The first applies when the item has its
2795 deadline on the current day. The second applies when it is in the past or
2796 in the future, it may contain %d to capture how many days away the deadline
2797 is (was)."
2798 :group 'org-agenda-line-format
2799 :type '(list
2800 (string :tag "Deadline today ")
2801 (string :tag "Deadline relative")))
2803 (defcustom org-agenda-remove-times-when-in-prefix t
2804 "Non-nil means, remove duplicate time specifications in agenda items.
2805 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2806 time-of-day specification in a headline or diary entry is extracted and
2807 placed into the prefix. If this option is non-nil, the original specification
2808 \(a timestamp or -range, or just a plain time(range) specification like
2809 11:30-4pm) will be removed for agenda display. This makes the agenda less
2810 cluttered.
2811 The option can be t or nil. It may also be the symbol `beg', indicating
2812 that the time should only be removed what it is located at the beginning of
2813 the headline/diary entry."
2814 :group 'org-agenda-line-format
2815 :type '(choice
2816 (const :tag "Always" t)
2817 (const :tag "Never" nil)
2818 (const :tag "When at beginning of entry" beg)))
2821 (defcustom org-agenda-default-appointment-duration nil
2822 "Default duration for appointments that only have a starting time.
2823 When nil, no duration is specified in such cases.
2824 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
2825 :group 'org-agenda-line-format
2826 :type '(choice
2827 (integer :tag "Minutes")
2828 (const :tag "No default duration")))
2831 (defcustom org-agenda-remove-tags nil
2832 "Non-nil means, remove the tags from the headline copy in the agenda.
2833 When this is the symbol `prefix', only remove tags when
2834 `org-agenda-prefix-format' contains a `%T' specifier."
2835 :group 'org-agenda-line-format
2836 :type '(choice
2837 (const :tag "Always" t)
2838 (const :tag "Never" nil)
2839 (const :tag "When prefix format contains %T" prefix)))
2841 (if (fboundp 'defvaralias)
2842 (defvaralias 'org-agenda-remove-tags-when-in-prefix
2843 'org-agenda-remove-tags))
2845 (defcustom org-agenda-tags-column -80
2846 "Shift tags in agenda items to this column.
2847 If this number is positive, it specifies the column. If it is negative,
2848 it means that the tags should be flushright to that column. For example,
2849 -80 works well for a normal 80 character screen."
2850 :group 'org-agenda-line-format
2851 :type 'integer)
2853 (if (fboundp 'defvaralias)
2854 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
2856 (defcustom org-agenda-fontify-priorities t
2857 "Non-nil means, highlight low and high priorities in agenda.
2858 When t, the highest priority entries are bold, lowest priority italic.
2859 This may also be an association list of priority faces. The face may be
2860 a names face, or a list like `(:background \"Red\")'."
2861 :group 'org-agenda-line-format
2862 :type '(choice
2863 (const :tag "Never" nil)
2864 (const :tag "Defaults" t)
2865 (repeat :tag "Specify"
2866 (list (character :tag "Priority" :value ?A)
2867 (sexp :tag "face")))))
2869 (defgroup org-latex nil
2870 "Options for embedding LaTeX code into Org-mode"
2871 :tag "Org LaTeX"
2872 :group 'org)
2874 (defcustom org-format-latex-options
2875 '(:foreground default :background default :scale 1.0
2876 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2877 :matchers ("begin" "$" "$$" "\\(" "\\["))
2878 "Options for creating images from LaTeX fragments.
2879 This is a property list with the following properties:
2880 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
2881 `default' means use the forground of the default face.
2882 :background the background color, or \"Transparent\".
2883 `default' means use the background of the default face.
2884 :scale a scaling factor for the size of the images
2885 :html-foreground, :html-background, :html-scale
2886 The same numbers for HTML export.
2887 :matchers a list indicating which matchers should be used to
2888 find LaTeX fragments. Valid members of this list are:
2889 \"begin\" find environments
2890 \"$\" find math expressions surrounded by $...$
2891 \"$$\" find math expressions surrounded by $$....$$
2892 \"\\(\" find math expressions surrounded by \\(...\\)
2893 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2894 :group 'org-latex
2895 :type 'plist)
2897 (defcustom org-format-latex-header "\\documentclass{article}
2898 \\usepackage{fullpage} % do not remove
2899 \\usepackage{amssymb}
2900 \\usepackage[usenames]{color}
2901 \\usepackage{amsmath}
2902 \\usepackage{latexsym}
2903 \\usepackage[mathscr]{eucal}
2904 \\pagestyle{empty} % do not remove"
2905 "The document header used for processing LaTeX fragments."
2906 :group 'org-latex
2907 :type 'string)
2909 (defgroup org-export nil
2910 "Options for exporting org-listings."
2911 :tag "Org Export"
2912 :group 'org)
2914 (defgroup org-export-general nil
2915 "General options for exporting Org-mode files."
2916 :tag "Org Export General"
2917 :group 'org-export)
2919 ;; FIXME
2920 (defvar org-export-publishing-directory nil)
2922 (defcustom org-export-with-special-strings t
2923 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
2924 When this option is turned on, these strings will be exported as:
2926 Org HTML LaTeX
2927 -----+----------+--------
2928 \\- &shy; \\-
2929 -- &ndash; --
2930 --- &mdash; ---
2931 ... &hellip; \ldots
2933 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
2934 :group 'org-export-translation
2935 :type 'boolean)
2937 (defcustom org-export-language-setup
2938 '(("en" "Author" "Date" "Table of Contents")
2939 ("cs" "Autor" "Datum" "Obsah")
2940 ("da" "Ophavsmand" "Dato" "Indhold")
2941 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
2942 ("es" "Autor" "Fecha" "\xcdndice")
2943 ("fr" "Auteur" "Date" "Table des mati\xe8res")
2944 ("it" "Autore" "Data" "Indice")
2945 ("nl" "Auteur" "Datum" "Inhoudsopgave")
2946 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
2947 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
2948 "Terms used in export text, translated to different languages.
2949 Use the variable `org-export-default-language' to set the language,
2950 or use the +OPTION lines for a per-file setting."
2951 :group 'org-export-general
2952 :type '(repeat
2953 (list
2954 (string :tag "HTML language tag")
2955 (string :tag "Author")
2956 (string :tag "Date")
2957 (string :tag "Table of Contents"))))
2959 (defcustom org-export-default-language "en"
2960 "The default language of HTML export, as a string.
2961 This should have an association in `org-export-language-setup'."
2962 :group 'org-export-general
2963 :type 'string)
2965 (defcustom org-export-skip-text-before-1st-heading t
2966 "Non-nil means, skip all text before the first headline when exporting.
2967 When nil, that text is exported as well."
2968 :group 'org-export-general
2969 :type 'boolean)
2971 (defcustom org-export-headline-levels 3
2972 "The last level which is still exported as a headline.
2973 Inferior levels will produce itemize lists when exported.
2974 Note that a numeric prefix argument to an exporter function overrides
2975 this setting.
2977 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
2978 :group 'org-export-general
2979 :type 'number)
2981 (defcustom org-export-with-section-numbers t
2982 "Non-nil means, add section numbers to headlines when exporting.
2984 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
2985 :group 'org-export-general
2986 :type 'boolean)
2988 (defcustom org-export-with-toc t
2989 "Non-nil means, create a table of contents in exported files.
2990 The TOC contains headlines with levels up to`org-export-headline-levels'.
2991 When an integer, include levels up to N in the toc, this may then be
2992 different from `org-export-headline-levels', but it will not be allowed
2993 to be larger than the number of headline levels.
2994 When nil, no table of contents is made.
2996 Headlines which contain any TODO items will be marked with \"(*)\" in
2997 ASCII export, and with red color in HTML output, if the option
2998 `org-export-mark-todo-in-toc' is set.
3000 In HTML output, the TOC will be clickable.
3002 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
3003 or \"toc:3\"."
3004 :group 'org-export-general
3005 :type '(choice
3006 (const :tag "No Table of Contents" nil)
3007 (const :tag "Full Table of Contents" t)
3008 (integer :tag "TOC to level")))
3010 (defcustom org-export-mark-todo-in-toc nil
3011 "Non-nil means, mark TOC lines that contain any open TODO items."
3012 :group 'org-export-general
3013 :type 'boolean)
3015 (defcustom org-export-preserve-breaks nil
3016 "Non-nil means, preserve all line breaks when exporting.
3017 Normally, in HTML output paragraphs will be reformatted. In ASCII
3018 export, line breaks will always be preserved, regardless of this variable.
3020 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3021 :group 'org-export-general
3022 :type 'boolean)
3024 (defcustom org-export-with-archived-trees 'headline
3025 "Whether subtrees with the ARCHIVE tag should be exported.
3026 This can have three different values
3027 nil Do not export, pretend this tree is not present
3028 t Do export the entire tree
3029 headline Only export the headline, but skip the tree below it."
3030 :group 'org-export-general
3031 :group 'org-archive
3032 :type '(choice
3033 (const :tag "not at all" nil)
3034 (const :tag "headline only" 'headline)
3035 (const :tag "entirely" t)))
3037 (defcustom org-export-author-info t
3038 "Non-nil means, insert author name and email into the exported file.
3040 This option can also be set with the +OPTIONS line,
3041 e.g. \"author-info:nil\"."
3042 :group 'org-export-general
3043 :type 'boolean)
3045 (defcustom org-export-time-stamp-file t
3046 "Non-nil means, insert a time stamp into the exported file.
3047 The time stamp shows when the file was created.
3049 This option can also be set with the +OPTIONS line,
3050 e.g. \"timestamp:nil\"."
3051 :group 'org-export-general
3052 :type 'boolean)
3054 (defcustom org-export-with-timestamps t
3055 "If nil, do not export time stamps and associated keywords."
3056 :group 'org-export-general
3057 :type 'boolean)
3059 (defcustom org-export-remove-timestamps-from-toc t
3060 "If nil, remove timestamps from the table of contents entries."
3061 :group 'org-export-general
3062 :type 'boolean)
3064 (defcustom org-export-with-tags 'not-in-toc
3065 "If nil, do not export tags, just remove them from headlines.
3066 If this is the symbol `not-in-toc', tags will be removed from table of
3067 contents entries, but still be shown in the headlines of the document.
3069 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3070 :group 'org-export-general
3071 :type '(choice
3072 (const :tag "Off" nil)
3073 (const :tag "Not in TOC" not-in-toc)
3074 (const :tag "On" t)))
3076 (defcustom org-export-with-drawers nil
3077 "Non-nil means, export with drawers like the property drawer.
3078 When t, all drawers are exported. This may also be a list of
3079 drawer names to export."
3080 :group 'org-export-general
3081 :type '(choice
3082 (const :tag "All drawers" t)
3083 (const :tag "None" nil)
3084 (repeat :tag "Selected drawers"
3085 (string :tag "Drawer name"))))
3087 (defgroup org-export-translation nil
3088 "Options for translating special ascii sequences for the export backends."
3089 :tag "Org Export Translation"
3090 :group 'org-export)
3092 (defcustom org-export-with-emphasize t
3093 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3094 If the export target supports emphasizing text, the word will be
3095 typeset in bold, italic, or underlined, respectively. Works only for
3096 single words, but you can say: I *really* *mean* *this*.
3097 Not all export backends support this.
3099 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3100 :group 'org-export-translation
3101 :type 'boolean)
3103 (defcustom org-export-with-footnotes t
3104 "If nil, export [1] as a footnote marker.
3105 Lines starting with [1] will be formatted as footnotes.
3107 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3108 :group 'org-export-translation
3109 :type 'boolean)
3111 (defcustom org-export-with-sub-superscripts t
3112 "Non-nil means, interpret \"_\" and \"^\" for export.
3113 When this option is turned on, you can use TeX-like syntax for sub- and
3114 superscripts. Several characters after \"_\" or \"^\" will be
3115 considered as a single item - so grouping with {} is normally not
3116 needed. For example, the following things will be parsed as single
3117 sub- or superscripts.
3119 10^24 or 10^tau several digits will be considered 1 item.
3120 10^-12 or 10^-tau a leading sign with digits or a word
3121 x^2-y^3 will be read as x^2 - y^3, because items are
3122 terminated by almost any nonword/nondigit char.
3123 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3125 Still, ambiguity is possible - so when in doubt use {} to enclose the
3126 sub/superscript. If you set this variable to the symbol `{}',
3127 the braces are *required* in order to trigger interpretations as
3128 sub/superscript. This can be helpful in documents that need \"_\"
3129 frequently in plain text.
3131 Not all export backends support this, but HTML does.
3133 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3134 :group 'org-export-translation
3135 :type '(choice
3136 (const :tag "Always interpret" t)
3137 (const :tag "Only with braces" {})
3138 (const :tag "Never interpret" nil)))
3140 (defcustom org-export-with-special-strings t
3141 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3142 When this option is turned on, these strings will be exported as:
3144 \\- : &shy;
3145 -- : &ndash;
3146 --- : &mdash;
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 'boolean)
3154 (defcustom org-export-with-TeX-macros t
3155 "Non-nil means, interpret simple TeX-like macros when exporting.
3156 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3157 No only real TeX macros will work here, but the standard HTML entities
3158 for math can be used as macro names as well. For a list of supported
3159 names in HTML export, see the constant `org-html-entities'.
3160 Not all export backends support this.
3162 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3163 :group 'org-export-translation
3164 :group 'org-export-latex
3165 :type 'boolean)
3167 (defcustom org-export-with-LaTeX-fragments nil
3168 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3169 When set, the exporter will find LaTeX environments if the \\begin line is
3170 the first non-white thing on a line. It will also find the math delimiters
3171 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3172 display math.
3174 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3175 :group 'org-export-translation
3176 :group 'org-export-latex
3177 :type 'boolean)
3179 (defcustom org-export-with-fixed-width t
3180 "Non-nil means, lines starting with \":\" will be in fixed width font.
3181 This can be used to have pre-formatted text, fragments of code etc. For
3182 example:
3183 : ;; Some Lisp examples
3184 : (while (defc cnt)
3185 : (ding))
3186 will be looking just like this in also HTML. See also the QUOTE keyword.
3187 Not all export backends support this.
3189 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3190 :group 'org-export-translation
3191 :type 'boolean)
3193 (defcustom org-match-sexp-depth 3
3194 "Number of stacked braces for sub/superscript matching.
3195 This has to be set before loading org.el to be effective."
3196 :group 'org-export-translation
3197 :type 'integer)
3199 (defgroup org-export-tables nil
3200 "Options for exporting tables in Org-mode."
3201 :tag "Org Export Tables"
3202 :group 'org-export)
3204 (defcustom org-export-with-tables t
3205 "If non-nil, lines starting with \"|\" define a table.
3206 For example:
3208 | Name | Address | Birthday |
3209 |-------------+----------+-----------|
3210 | Arthur Dent | England | 29.2.2100 |
3212 Not all export backends support this.
3214 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3215 :group 'org-export-tables
3216 :type 'boolean)
3218 (defcustom org-export-highlight-first-table-line t
3219 "Non-nil means, highlight the first table line.
3220 In HTML export, this means use <th> instead of <td>.
3221 In tables created with table.el, this applies to the first table line.
3222 In Org-mode tables, all lines before the first horizontal separator
3223 line will be formatted with <th> tags."
3224 :group 'org-export-tables
3225 :type 'boolean)
3227 (defcustom org-export-table-remove-special-lines t
3228 "Remove special lines and marking characters in calculating tables.
3229 This removes the special marking character column from tables that are set
3230 up for spreadsheet calculations. It also removes the entire lines
3231 marked with `!', `_', or `^'. The lines with `$' are kept, because
3232 the values of constants may be useful to have."
3233 :group 'org-export-tables
3234 :type 'boolean)
3236 (defcustom org-export-prefer-native-exporter-for-tables nil
3237 "Non-nil means, always export tables created with table.el natively.
3238 Natively means, use the HTML code generator in table.el.
3239 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3240 the table does not use row- or column-spanning). This has the
3241 advantage, that the automatic HTML conversions for math symbols and
3242 sub/superscripts can be applied. Org-mode's HTML generator is also
3243 much faster."
3244 :group 'org-export-tables
3245 :type 'boolean)
3247 (defgroup org-export-ascii nil
3248 "Options specific for ASCII export of Org-mode files."
3249 :tag "Org Export ASCII"
3250 :group 'org-export)
3252 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3253 "Characters for underlining headings in ASCII export.
3254 In the given sequence, these characters will be used for level 1, 2, ..."
3255 :group 'org-export-ascii
3256 :type '(repeat character))
3258 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3259 "Bullet characters for headlines converted to lists in ASCII export.
3260 The first character is is used for the first lest level generated in this
3261 way, and so on. If there are more levels than characters given here,
3262 the list will be repeated.
3263 Note that plain lists will keep the same bullets as the have in the
3264 Org-mode file."
3265 :group 'org-export-ascii
3266 :type '(repeat character))
3268 (defgroup org-export-xml nil
3269 "Options specific for XML export of Org-mode files."
3270 :tag "Org Export XML"
3271 :group 'org-export)
3273 (defgroup org-export-html nil
3274 "Options specific for HTML export of Org-mode files."
3275 :tag "Org Export HTML"
3276 :group 'org-export)
3278 (defcustom org-export-html-coding-system nil
3280 :group 'org-export-html
3281 :type 'coding-system)
3283 (defcustom org-export-html-extension "html"
3284 "The extension for exported HTML files."
3285 :group 'org-export-html
3286 :type 'string)
3288 (defcustom org-export-html-style
3289 "<style type=\"text/css\">
3290 html {
3291 font-family: Times, serif;
3292 font-size: 12pt;
3294 .title { text-align: center; }
3295 .todo { color: red; }
3296 .done { color: green; }
3297 .timestamp { color: grey }
3298 .timestamp-kwd { color: CadetBlue }
3299 .tag { background-color:lightblue; font-weight:normal }
3300 .target { background-color: lavender; }
3301 pre {
3302 border: 1pt solid #AEBDCC;
3303 background-color: #F3F5F7;
3304 padding: 5pt;
3305 font-family: courier, monospace;
3307 table { border-collapse: collapse; }
3308 td, th {
3309 vertical-align: top;
3310 <!--border: 1pt solid #ADB9CC;-->
3312 </style>"
3313 "The default style specification for exported HTML files.
3314 Since there are different ways of setting style information, this variable
3315 needs to contain the full HTML structure to provide a style, including the
3316 surrounding HTML tags. The style specifications should include definitions
3317 for new classes todo, done, title, and deadline. For example, legal values
3318 would be:
3320 <style type=\"text/css\">
3321 p { font-weight: normal; color: gray; }
3322 h1 { color: black; }
3323 .title { text-align: center; }
3324 .todo, .deadline { color: red; }
3325 .done { color: green; }
3326 </style>
3328 or, if you want to keep the style in a file,
3330 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3332 As the value of this option simply gets inserted into the HTML <head> header,
3333 you can \"misuse\" it to add arbitrary text to the header."
3334 :group 'org-export-html
3335 :type 'string)
3338 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3339 "Format for typesetting the document title in HTML export."
3340 :group 'org-export-html
3341 :type 'string)
3343 (defcustom org-export-html-toplevel-hlevel 2
3344 "The <H> level for level 1 headings in HTML export."
3345 :group 'org-export-html
3346 :type 'string)
3348 (defcustom org-export-html-link-org-files-as-html t
3349 "Non-nil means, make file links to `file.org' point to `file.html'.
3350 When org-mode is exporting an org-mode file to HTML, links to
3351 non-html files are directly put into a href tag in HTML.
3352 However, links to other Org-mode files (recognized by the
3353 extension `.org.) should become links to the corresponding html
3354 file, assuming that the linked org-mode file will also be
3355 converted to HTML.
3356 When nil, the links still point to the plain `.org' file."
3357 :group 'org-export-html
3358 :type 'boolean)
3360 (defcustom org-export-html-inline-images 'maybe
3361 "Non-nil means, inline images into exported HTML pages.
3362 This is done using an <img> tag. When nil, an anchor with href is used to
3363 link to the image. If this option is `maybe', then images in links with
3364 an empty description will be inlined, while images with a description will
3365 be linked only."
3366 :group 'org-export-html
3367 :type '(choice (const :tag "Never" nil)
3368 (const :tag "Always" t)
3369 (const :tag "When there is no description" maybe)))
3371 ;; FIXME: rename
3372 (defcustom org-export-html-expand t
3373 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3374 When nil, these tags will be exported as plain text and therefore
3375 not be interpreted by a browser.
3377 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3378 :group 'org-export-html
3379 :type 'boolean)
3381 (defcustom org-export-html-table-tag
3382 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3383 "The HTML tag that is used to start a table.
3384 This must be a <table> tag, but you may change the options like
3385 borders and spacing."
3386 :group 'org-export-html
3387 :type 'string)
3389 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3390 "The opening tag for table header fields.
3391 This is customizable so that alignment options can be specified."
3392 :group 'org-export-tables
3393 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3395 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3396 "The opening tag for table data fields.
3397 This is customizable so that alignment options can be specified."
3398 :group 'org-export-tables
3399 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3401 (defcustom org-export-html-with-timestamp nil
3402 "If non-nil, write `org-export-html-html-helper-timestamp'
3403 into the exported HTML text. Otherwise, the buffer will just be saved
3404 to a file."
3405 :group 'org-export-html
3406 :type 'boolean)
3408 (defcustom org-export-html-html-helper-timestamp
3409 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3410 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3411 :group 'org-export-html
3412 :type 'string)
3414 (defgroup org-export-icalendar nil
3415 "Options specific for iCalendar export of Org-mode files."
3416 :tag "Org Export iCalendar"
3417 :group 'org-export)
3419 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3420 "The file name for the iCalendar file covering all agenda files.
3421 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3422 The file name should be absolute, the file will be overwritten without warning."
3423 :group 'org-export-icalendar
3424 :type 'file)
3426 (defcustom org-icalendar-include-todo nil
3427 "Non-nil means, export to iCalendar files should also cover TODO items."
3428 :group 'org-export-icalendar
3429 :type '(choice
3430 (const :tag "None" nil)
3431 (const :tag "Unfinished" t)
3432 (const :tag "All" all)))
3434 (defcustom org-icalendar-include-sexps t
3435 "Non-nil means, export to iCalendar files should also cover sexp entries.
3436 These are entries like in the diary, but directly in an Org-mode file."
3437 :group 'org-export-icalendar
3438 :type 'boolean)
3440 (defcustom org-icalendar-include-body 100
3441 "Amount of text below headline to be included in iCalendar export.
3442 This is a number of characters that should maximally be included.
3443 Properties, scheduling and clocking lines will always be removed.
3444 The text will be inserted into the DESCRIPTION field."
3445 :group 'org-export-icalendar
3446 :type '(choice
3447 (const :tag "Nothing" nil)
3448 (const :tag "Everything" t)
3449 (integer :tag "Max characters")))
3451 (defcustom org-icalendar-combined-name "OrgMode"
3452 "Calendar name for the combined iCalendar representing all agenda files."
3453 :group 'org-export-icalendar
3454 :type 'string)
3456 (defgroup org-font-lock nil
3457 "Font-lock settings for highlighting in Org-mode."
3458 :tag "Org Font Lock"
3459 :group 'org)
3461 (defcustom org-level-color-stars-only nil
3462 "Non-nil means fontify only the stars in each headline.
3463 When nil, the entire headline is fontified.
3464 Changing it requires restart of `font-lock-mode' to become effective
3465 also in regions already fontified."
3466 :group 'org-font-lock
3467 :type 'boolean)
3469 (defcustom org-hide-leading-stars nil
3470 "Non-nil means, hide the first N-1 stars in a headline.
3471 This works by using the face `org-hide' for these stars. This
3472 face is white for a light background, and black for a dark
3473 background. You may have to customize the face `org-hide' to
3474 make this work.
3475 Changing it requires restart of `font-lock-mode' to become effective
3476 also in regions already fontified.
3477 You may also set this on a per-file basis by adding one of the following
3478 lines to the buffer:
3480 #+STARTUP: hidestars
3481 #+STARTUP: showstars"
3482 :group 'org-font-lock
3483 :type 'boolean)
3485 (defcustom org-fontify-done-headline nil
3486 "Non-nil means, change the face of a headline if it is marked DONE.
3487 Normally, only the TODO/DONE keyword indicates the state of a headline.
3488 When this is non-nil, the headline after the keyword is set to the
3489 `org-headline-done' as an additional indication."
3490 :group 'org-font-lock
3491 :type 'boolean)
3493 (defcustom org-fontify-emphasized-text t
3494 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3495 Changing this variable requires a restart of Emacs to take effect."
3496 :group 'org-font-lock
3497 :type 'boolean)
3499 (defcustom org-highlight-latex-fragments-and-specials nil
3500 "Non-nil means, fontify what is treated specially by the exporters."
3501 :group 'org-font-lock
3502 :type 'boolean)
3504 (defcustom org-hide-emphasis-markers nil
3505 "Non-nil mean font-lock should hide the emphasis marker characters."
3506 :group 'org-font-lock
3507 :type 'boolean)
3509 (defvar org-emph-re nil
3510 "Regular expression for matching emphasis.")
3511 (defvar org-verbatim-re nil
3512 "Regular expression for matching verbatim text.")
3513 (defvar org-emphasis-regexp-components) ; defined just below
3514 (defvar org-emphasis-alist) ; defined just below
3515 (defun org-set-emph-re (var val)
3516 "Set variable and compute the emphasis regular expression."
3517 (set var val)
3518 (when (and (boundp 'org-emphasis-alist)
3519 (boundp 'org-emphasis-regexp-components)
3520 org-emphasis-alist org-emphasis-regexp-components)
3521 (let* ((e org-emphasis-regexp-components)
3522 (pre (car e))
3523 (post (nth 1 e))
3524 (border (nth 2 e))
3525 (body (nth 3 e))
3526 (nl (nth 4 e))
3527 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3528 (body1 (concat body "*?"))
3529 (markers (mapconcat 'car org-emphasis-alist ""))
3530 (vmarkers (mapconcat
3531 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3532 org-emphasis-alist "")))
3533 ;; make sure special characters appear at the right position in the class
3534 (if (string-match "\\^" markers)
3535 (setq markers (concat (replace-match "" t t markers) "^")))
3536 (if (string-match "-" markers)
3537 (setq markers (concat (replace-match "" t t markers) "-")))
3538 (if (string-match "\\^" vmarkers)
3539 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3540 (if (string-match "-" vmarkers)
3541 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3542 (if (> nl 0)
3543 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3544 (int-to-string nl) "\\}")))
3545 ;; Make the regexp
3546 (setq org-emph-re
3547 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3548 "\\("
3549 "\\([" markers "]\\)"
3550 "\\("
3551 "[^" border "]\\|"
3552 "[^" border (if (and nil stacked) markers) "]"
3553 body1
3554 "[^" border (if (and nil stacked) markers) "]"
3555 "\\)"
3556 "\\3\\)"
3557 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3558 (setq org-verbatim-re
3559 (concat "\\([" pre "]\\|^\\)"
3560 "\\("
3561 "\\([" vmarkers "]\\)"
3562 "\\("
3563 "[^" border "]\\|"
3564 "[^" border "]"
3565 body1
3566 "[^" border "]"
3567 "\\)"
3568 "\\3\\)"
3569 "\\([" post "]\\|$\\)")))))
3571 (defcustom org-emphasis-regexp-components
3572 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3573 "Components used to build the regular expression for emphasis.
3574 This is a list with 6 entries. Terminology: In an emphasis string
3575 like \" *strong word* \", we call the initial space PREMATCH, the final
3576 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3577 and \"trong wor\" is the body. The different components in this variable
3578 specify what is allowed/forbidden in each part:
3580 pre Chars allowed as prematch. Beginning of line will be allowed too.
3581 post Chars allowed as postmatch. End of line will be allowed too.
3582 border The chars *forbidden* as border characters.
3583 body-regexp A regexp like \".\" to match a body character. Don't use
3584 non-shy groups here, and don't allow newline here.
3585 newline The maximum number of newlines allowed in an emphasis exp.
3587 Use customize to modify this, or restart Emacs after changing it."
3588 :group 'org-font-lock
3589 :set 'org-set-emph-re
3590 :type '(list
3591 (sexp :tag "Allowed chars in pre ")
3592 (sexp :tag "Allowed chars in post ")
3593 (sexp :tag "Forbidden chars in border ")
3594 (sexp :tag "Regexp for body ")
3595 (integer :tag "number of newlines allowed")
3596 (option (boolean :tag "Stacking (DISABLED) "))))
3598 (defcustom org-emphasis-alist
3599 '(("*" bold "<b>" "</b>")
3600 ("/" italic "<i>" "</i>")
3601 ("_" underline "<u>" "</u>")
3602 ("=" org-code "<code>" "</code>" verbatim)
3603 ("~" org-verbatim "" "" verbatim)
3604 ("+" (:strike-through t) "<del>" "</del>")
3606 "Special syntax for emphasized text.
3607 Text starting and ending with a special character will be emphasized, for
3608 example *bold*, _underlined_ and /italic/. This variable sets the marker
3609 characters, the face to be used by font-lock for highlighting in Org-mode
3610 Emacs buffers, and the HTML tags to be used for this.
3611 Use customize to modify this, or restart Emacs after changing it."
3612 :group 'org-font-lock
3613 :set 'org-set-emph-re
3614 :type '(repeat
3615 (list
3616 (string :tag "Marker character")
3617 (choice
3618 (face :tag "Font-lock-face")
3619 (plist :tag "Face property list"))
3620 (string :tag "HTML start tag")
3621 (string :tag "HTML end tag")
3622 (option (const verbatim)))))
3624 ;;; The faces
3626 (defgroup org-faces nil
3627 "Faces in Org-mode."
3628 :tag "Org Faces"
3629 :group 'org-font-lock)
3631 (defun org-compatible-face (inherits specs)
3632 "Make a compatible face specification.
3633 If INHERITS is an existing face and if the Emacs version supports it,
3634 just inherit the face. If not, use SPECS to define the face.
3635 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3636 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3637 to the top of the list. The `min-colors' attribute will be removed from
3638 any other entries, and any resulting duplicates will be removed entirely."
3639 (cond
3640 ((and inherits (facep inherits)
3641 (not (featurep 'xemacs)) (> emacs-major-version 22))
3642 ;; In Emacs 23, we use inheritance where possible.
3643 ;; We only do this in Emacs 23, because only there the outline
3644 ;; faces have been changed to the original org-mode-level-faces.
3645 (list (list t :inherit inherits)))
3646 ((or (featurep 'xemacs) (< emacs-major-version 22))
3647 ;; These do not understand the `min-colors' attribute.
3648 (let (r e a)
3649 (while (setq e (pop specs))
3650 (cond
3651 ((memq (car e) '(t default)) (push e r))
3652 ((setq a (member '(min-colors 8) (car e)))
3653 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3654 (cdr e)))))
3655 ((setq a (assq 'min-colors (car e)))
3656 (setq e (cons (delq a (car e)) (cdr e)))
3657 (or (assoc (car e) r) (push e r)))
3658 (t (or (assoc (car e) r) (push e r)))))
3659 (nreverse r)))
3660 (t specs)))
3661 (put 'org-compatible-face 'lisp-indent-function 1)
3663 (defface org-hide
3664 '((((background light)) (:foreground "white"))
3665 (((background dark)) (:foreground "black")))
3666 "Face used to hide leading stars in headlines.
3667 The forground color of this face should be equal to the background
3668 color of the frame."
3669 :group 'org-faces)
3671 (defface org-level-1 ;; font-lock-function-name-face
3672 (org-compatible-face 'outline-1
3673 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3674 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3675 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3676 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3677 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3678 (t (:bold t))))
3679 "Face used for level 1 headlines."
3680 :group 'org-faces)
3682 (defface org-level-2 ;; font-lock-variable-name-face
3683 (org-compatible-face 'outline-2
3684 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3685 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3686 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3687 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3688 (t (:bold t))))
3689 "Face used for level 2 headlines."
3690 :group 'org-faces)
3692 (defface org-level-3 ;; font-lock-keyword-face
3693 (org-compatible-face 'outline-3
3694 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3695 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3696 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3697 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3698 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3699 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3700 (t (:bold t))))
3701 "Face used for level 3 headlines."
3702 :group 'org-faces)
3704 (defface org-level-4 ;; font-lock-comment-face
3705 (org-compatible-face 'outline-4
3706 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3707 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3708 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3709 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3710 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3711 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3712 (t (:bold t))))
3713 "Face used for level 4 headlines."
3714 :group 'org-faces)
3716 (defface org-level-5 ;; font-lock-type-face
3717 (org-compatible-face 'outline-5
3718 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3719 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3720 (((class color) (min-colors 8)) (:foreground "green"))))
3721 "Face used for level 5 headlines."
3722 :group 'org-faces)
3724 (defface org-level-6 ;; font-lock-constant-face
3725 (org-compatible-face 'outline-6
3726 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3727 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3728 (((class color) (min-colors 8)) (:foreground "magenta"))))
3729 "Face used for level 6 headlines."
3730 :group 'org-faces)
3732 (defface org-level-7 ;; font-lock-builtin-face
3733 (org-compatible-face 'outline-7
3734 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3735 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3736 (((class color) (min-colors 8)) (:foreground "blue"))))
3737 "Face used for level 7 headlines."
3738 :group 'org-faces)
3740 (defface org-level-8 ;; font-lock-string-face
3741 (org-compatible-face 'outline-8
3742 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3743 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3744 (((class color) (min-colors 8)) (:foreground "green"))))
3745 "Face used for level 8 headlines."
3746 :group 'org-faces)
3748 (defface org-special-keyword ;; font-lock-string-face
3749 (org-compatible-face nil
3750 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3751 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3752 (t (:italic t))))
3753 "Face used for special keywords."
3754 :group 'org-faces)
3756 (defface org-drawer ;; font-lock-function-name-face
3757 (org-compatible-face nil
3758 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3759 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3760 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3761 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3762 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3763 (t (:bold t))))
3764 "Face used for drawers."
3765 :group 'org-faces)
3767 (defface org-property-value nil
3768 "Face used for the value of a property."
3769 :group 'org-faces)
3771 (defface org-column
3772 (org-compatible-face nil
3773 '((((class color) (min-colors 16) (background light))
3774 (:background "grey90"))
3775 (((class color) (min-colors 16) (background dark))
3776 (:background "grey30"))
3777 (((class color) (min-colors 8))
3778 (:background "cyan" :foreground "black"))
3779 (t (:inverse-video t))))
3780 "Face for column display of entry properties."
3781 :group 'org-faces)
3783 (when (fboundp 'set-face-attribute)
3784 ;; Make sure that a fixed-width face is used when we have a column table.
3785 (set-face-attribute 'org-column nil
3786 :height (face-attribute 'default :height)
3787 :family (face-attribute 'default :family)))
3789 (defface org-warning
3790 (org-compatible-face 'font-lock-warning-face
3791 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3792 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3793 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3794 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3795 (t (:bold t))))
3796 "Face for deadlines and TODO keywords."
3797 :group 'org-faces)
3799 (defface org-archived ; similar to shadow
3800 (org-compatible-face 'shadow
3801 '((((class color grayscale) (min-colors 88) (background light))
3802 (:foreground "grey50"))
3803 (((class color grayscale) (min-colors 88) (background dark))
3804 (:foreground "grey70"))
3805 (((class color) (min-colors 8) (background light))
3806 (:foreground "green"))
3807 (((class color) (min-colors 8) (background dark))
3808 (:foreground "yellow"))))
3809 "Face for headline with the ARCHIVE tag."
3810 :group 'org-faces)
3812 (defface org-link
3813 '((((class color) (background light)) (:foreground "Purple" :underline t))
3814 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3815 (t (:underline t)))
3816 "Face for links."
3817 :group 'org-faces)
3819 (defface org-ellipsis
3820 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
3821 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
3822 (t (:strike-through t)))
3823 "Face for the ellipsis in folded text."
3824 :group 'org-faces)
3826 (defface org-target
3827 '((((class color) (background light)) (:underline t))
3828 (((class color) (background dark)) (:underline t))
3829 (t (:underline t)))
3830 "Face for links."
3831 :group 'org-faces)
3833 (defface org-date
3834 '((((class color) (background light)) (:foreground "Purple" :underline t))
3835 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3836 (t (:underline t)))
3837 "Face for links."
3838 :group 'org-faces)
3840 (defface org-sexp-date
3841 '((((class color) (background light)) (:foreground "Purple"))
3842 (((class color) (background dark)) (:foreground "Cyan"))
3843 (t (:underline t)))
3844 "Face for links."
3845 :group 'org-faces)
3847 (defface org-tag
3848 '((t (:bold t)))
3849 "Face for tags."
3850 :group 'org-faces)
3852 (defface org-todo ; font-lock-warning-face
3853 (org-compatible-face nil
3854 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3855 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3856 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3857 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3858 (t (:inverse-video t :bold t))))
3859 "Face for TODO keywords."
3860 :group 'org-faces)
3862 (defface org-done ;; font-lock-type-face
3863 (org-compatible-face nil
3864 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
3865 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
3866 (((class color) (min-colors 8)) (:foreground "green"))
3867 (t (:bold t))))
3868 "Face used for todo keywords that indicate DONE items."
3869 :group 'org-faces)
3871 (defface org-headline-done ;; font-lock-string-face
3872 (org-compatible-face nil
3873 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3874 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3875 (((class color) (min-colors 8) (background light)) (:bold nil))))
3876 "Face used to indicate that a headline is DONE.
3877 This face is only used if `org-fontify-done-headline' is set. If applies
3878 to the part of the headline after the DONE keyword."
3879 :group 'org-faces)
3881 (defcustom org-todo-keyword-faces nil
3882 "Faces for specific TODO keywords.
3883 This is a list of cons cells, with TODO keywords in the car
3884 and faces in the cdr. The face can be a symbol, or a property
3885 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
3886 :group 'org-faces
3887 :group 'org-todo
3888 :type '(repeat
3889 (cons
3890 (string :tag "keyword")
3891 (sexp :tag "face"))))
3893 (defface org-table ;; font-lock-function-name-face
3894 (org-compatible-face nil
3895 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3896 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3897 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3898 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3899 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
3900 (((class color) (min-colors 8) (background dark)))))
3901 "Face used for tables."
3902 :group 'org-faces)
3904 (defface org-formula
3905 (org-compatible-face nil
3906 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3907 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3908 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3909 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
3910 (t (:bold t :italic t))))
3911 "Face for formulas."
3912 :group 'org-faces)
3914 (defface org-code
3915 (org-compatible-face nil
3916 '((((class color grayscale) (min-colors 88) (background light))
3917 (:foreground "grey50"))
3918 (((class color grayscale) (min-colors 88) (background dark))
3919 (:foreground "grey70"))
3920 (((class color) (min-colors 8) (background light))
3921 (:foreground "green"))
3922 (((class color) (min-colors 8) (background dark))
3923 (:foreground "yellow"))))
3924 "Face for fixed-with text like code snippets."
3925 :group 'org-faces
3926 :version "22.1")
3928 (defface org-verbatim
3929 (org-compatible-face nil
3930 '((((class color grayscale) (min-colors 88) (background light))
3931 (:foreground "grey50" :underline t))
3932 (((class color grayscale) (min-colors 88) (background dark))
3933 (:foreground "grey70" :underline t))
3934 (((class color) (min-colors 8) (background light))
3935 (:foreground "green" :underline t))
3936 (((class color) (min-colors 8) (background dark))
3937 (:foreground "yellow" :underline t))))
3938 "Face for fixed-with text like code snippets."
3939 :group 'org-faces
3940 :version "22.1")
3942 (defface org-agenda-structure ;; font-lock-function-name-face
3943 (org-compatible-face nil
3944 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3945 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3946 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3947 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3948 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3949 (t (:bold t))))
3950 "Face used in agenda for captions and dates."
3951 :group 'org-faces)
3953 (defface org-scheduled-today
3954 (org-compatible-face nil
3955 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
3956 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
3957 (((class color) (min-colors 8)) (:foreground "green"))
3958 (t (:bold t :italic t))))
3959 "Face for items scheduled for a certain day."
3960 :group 'org-faces)
3962 (defface org-scheduled-previously
3963 (org-compatible-face nil
3964 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3965 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3966 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3967 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3968 (t (:bold t))))
3969 "Face for items scheduled previously, and not yet done."
3970 :group 'org-faces)
3972 (defface org-upcoming-deadline
3973 (org-compatible-face nil
3974 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3975 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3976 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3977 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3978 (t (:bold t))))
3979 "Face for items scheduled previously, and not yet done."
3980 :group 'org-faces)
3982 (defcustom org-agenda-deadline-faces
3983 '((1.0 . org-warning)
3984 (0.5 . org-upcoming-deadline)
3985 (0.0 . default))
3986 "Faces for showing deadlines in the agenda.
3987 This is a list of cons cells. The cdr of each cess is a face to be used,
3988 and it can also just be a like like '(:foreground \"yellow\").
3989 Each car is a fraction of the head-warning time that must have passed for
3990 this the face in the cdr to be used for display. The numbers must be
3991 given in descending order. The head-warning time is normally taken
3992 from `org-deadline-warning-days', but can also be specified in the deadline
3993 timestamp itself, like this:
3995 DEADLINE: <2007-08-13 Mon -8d>
3997 You may use d for days, w for weeks, m for months and y for years. Months
3998 and years will only be treated in an approximate fashion (30.4 days for a
3999 month and 365.24 days for a year)."
4000 :group 'org-faces
4001 :group 'org-agenda-daily/weekly
4002 :type '(repeat
4003 (cons
4004 (number :tag "Fraction of head-warning time passed")
4005 (sexp :tag "Face"))))
4007 ;; FIXME: this is not a good face yet.
4008 (defface org-agenda-restriction-lock
4009 (org-compatible-face nil
4010 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
4011 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
4012 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
4013 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
4014 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
4015 (t (:inverse-video t))))
4016 "Face for showing the agenda restriction lock."
4017 :group 'org-faces)
4019 (defface org-time-grid ;; font-lock-variable-name-face
4020 (org-compatible-face nil
4021 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4022 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4023 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4024 "Face used for time grids."
4025 :group 'org-faces)
4027 (defconst org-level-faces
4028 '(org-level-1 org-level-2 org-level-3 org-level-4
4029 org-level-5 org-level-6 org-level-7 org-level-8
4032 (defcustom org-n-level-faces (length org-level-faces)
4033 "The number different faces to be used for headlines.
4034 Org-mode defines 8 different headline faces, so this can be at most 8.
4035 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4036 :type 'number
4037 :group 'org-faces)
4039 ;;; Variables for pre-computed regular expressions, all buffer local
4041 (defvar org-drawer-regexp nil
4042 "Matches first line of a hidden block.")
4043 (make-variable-buffer-local 'org-drawer-regexp)
4044 (defvar org-todo-regexp nil
4045 "Matches any of the TODO state keywords.")
4046 (make-variable-buffer-local 'org-todo-regexp)
4047 (defvar org-not-done-regexp nil
4048 "Matches any of the TODO state keywords except the last one.")
4049 (make-variable-buffer-local 'org-not-done-regexp)
4050 (defvar org-todo-line-regexp nil
4051 "Matches a headline and puts TODO state into group 2 if present.")
4052 (make-variable-buffer-local 'org-todo-line-regexp)
4053 (defvar org-complex-heading-regexp nil
4054 "Matches a headline and puts everything into groups:
4055 group 1: the stars
4056 group 2: The todo keyword, maybe
4057 group 3: Priority cookie
4058 group 4: True headline
4059 group 5: Tags")
4060 (make-variable-buffer-local 'org-complex-heading-regexp)
4061 (defvar org-todo-line-tags-regexp nil
4062 "Matches a headline and puts TODO state into group 2 if present.
4063 Also put tags into group 4 if tags are present.")
4064 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4065 (defvar org-nl-done-regexp nil
4066 "Matches newline followed by a headline with the DONE keyword.")
4067 (make-variable-buffer-local 'org-nl-done-regexp)
4068 (defvar org-looking-at-done-regexp nil
4069 "Matches the DONE keyword a point.")
4070 (make-variable-buffer-local 'org-looking-at-done-regexp)
4071 (defvar org-ds-keyword-length 12
4072 "Maximum length of the Deadline and SCHEDULED keywords.")
4073 (make-variable-buffer-local 'org-ds-keyword-length)
4074 (defvar org-deadline-regexp nil
4075 "Matches the DEADLINE keyword.")
4076 (make-variable-buffer-local 'org-deadline-regexp)
4077 (defvar org-deadline-time-regexp nil
4078 "Matches the DEADLINE keyword together with a time stamp.")
4079 (make-variable-buffer-local 'org-deadline-time-regexp)
4080 (defvar org-deadline-line-regexp nil
4081 "Matches the DEADLINE keyword and the rest of the line.")
4082 (make-variable-buffer-local 'org-deadline-line-regexp)
4083 (defvar org-scheduled-regexp nil
4084 "Matches the SCHEDULED keyword.")
4085 (make-variable-buffer-local 'org-scheduled-regexp)
4086 (defvar org-scheduled-time-regexp nil
4087 "Matches the SCHEDULED keyword together with a time stamp.")
4088 (make-variable-buffer-local 'org-scheduled-time-regexp)
4089 (defvar org-closed-time-regexp nil
4090 "Matches the CLOSED keyword together with a time stamp.")
4091 (make-variable-buffer-local 'org-closed-time-regexp)
4093 (defvar org-keyword-time-regexp nil
4094 "Matches any of the 4 keywords, together with the time stamp.")
4095 (make-variable-buffer-local 'org-keyword-time-regexp)
4096 (defvar org-keyword-time-not-clock-regexp nil
4097 "Matches any of the 3 keywords, together with the time stamp.")
4098 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4099 (defvar org-maybe-keyword-time-regexp nil
4100 "Matches a timestamp, possibly preceeded by a keyword.")
4101 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4102 (defvar org-planning-or-clock-line-re nil
4103 "Matches a line with planning or clock info.")
4104 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4106 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4107 rear-nonsticky t mouse-map t fontified t)
4108 "Properties to remove when a string without properties is wanted.")
4110 (defsubst org-match-string-no-properties (num &optional string)
4111 (if (featurep 'xemacs)
4112 (let ((s (match-string num string)))
4113 (remove-text-properties 0 (length s) org-rm-props s)
4115 (match-string-no-properties num string)))
4117 (defsubst org-no-properties (s)
4118 (if (fboundp 'set-text-properties)
4119 (set-text-properties 0 (length s) nil s)
4120 (remove-text-properties 0 (length s) org-rm-props s))
4123 (defsubst org-get-alist-option (option key)
4124 (cond ((eq key t) t)
4125 ((eq option t) t)
4126 ((assoc key option) (cdr (assoc key option)))
4127 (t (cdr (assq 'default option)))))
4129 (defsubst org-inhibit-invisibility ()
4130 "Modified `buffer-invisibility-spec' for Emacs 21.
4131 Some ops with invisible text do not work correctly on Emacs 21. For these
4132 we turn off invisibility temporarily. Use this in a `let' form."
4133 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4135 (defsubst org-set-local (var value)
4136 "Make VAR local in current buffer and set it to VALUE."
4137 (set (make-variable-buffer-local var) value))
4139 (defsubst org-mode-p ()
4140 "Check if the current buffer is in Org-mode."
4141 (eq major-mode 'org-mode))
4143 (defsubst org-last (list)
4144 "Return the last element of LIST."
4145 (car (last list)))
4147 (defun org-let (list &rest body)
4148 (eval (cons 'let (cons list body))))
4149 (put 'org-let 'lisp-indent-function 1)
4151 (defun org-let2 (list1 list2 &rest body)
4152 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4153 (put 'org-let2 'lisp-indent-function 2)
4154 (defconst org-startup-options
4155 '(("fold" org-startup-folded t)
4156 ("overview" org-startup-folded t)
4157 ("nofold" org-startup-folded nil)
4158 ("showall" org-startup-folded nil)
4159 ("content" org-startup-folded content)
4160 ("hidestars" org-hide-leading-stars t)
4161 ("showstars" org-hide-leading-stars nil)
4162 ("odd" org-odd-levels-only t)
4163 ("oddeven" org-odd-levels-only nil)
4164 ("align" org-startup-align-all-tables t)
4165 ("noalign" org-startup-align-all-tables nil)
4166 ("customtime" org-display-custom-times t)
4167 ("logging" org-log-done t)
4168 ("logdone" org-log-done t)
4169 ("nologging" org-log-done nil)
4170 ("lognotedone" org-log-done done push)
4171 ("lognotestate" org-log-done state push)
4172 ("lognoteclock-out" org-log-done clock-out push)
4173 ("logrepeat" org-log-repeat t)
4174 ("nologrepeat" org-log-repeat nil)
4175 ("constcgs" constants-unit-system cgs)
4176 ("constSI" constants-unit-system SI))
4177 "Variable associated with STARTUP options for org-mode.
4178 Each element is a list of three items: The startup options as written
4179 in the #+STARTUP line, the corresponding variable, and the value to
4180 set this variable to if the option is found. An optional forth element PUSH
4181 means to push this value onto the list in the variable.")
4183 (defun org-set-regexps-and-options ()
4184 "Precompute regular expressions for current buffer."
4185 (when (org-mode-p)
4186 (org-set-local 'org-todo-kwd-alist nil)
4187 (org-set-local 'org-todo-key-alist nil)
4188 (org-set-local 'org-todo-key-trigger nil)
4189 (org-set-local 'org-todo-keywords-1 nil)
4190 (org-set-local 'org-done-keywords nil)
4191 (org-set-local 'org-todo-heads nil)
4192 (org-set-local 'org-todo-sets nil)
4193 (org-set-local 'org-todo-log-states nil)
4194 (let ((re (org-make-options-regexp
4195 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4196 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4197 "CONSTANTS" "PROPERTY" "DRAWERS")))
4198 (splitre "[ \t]+")
4199 kwds kws0 kwsa key value cat arch tags const links hw dws
4200 tail sep kws1 prio props drawers
4201 ex log)
4202 (save-excursion
4203 (save-restriction
4204 (widen)
4205 (goto-char (point-min))
4206 (while (re-search-forward re nil t)
4207 (setq key (match-string 1) value (org-match-string-no-properties 2))
4208 (cond
4209 ((equal key "CATEGORY")
4210 (if (string-match "[ \t]+$" value)
4211 (setq value (replace-match "" t t value)))
4212 (setq cat value))
4213 ((member key '("SEQ_TODO" "TODO"))
4214 (push (cons 'sequence (org-split-string value splitre)) kwds))
4215 ((equal key "TYP_TODO")
4216 (push (cons 'type (org-split-string value splitre)) kwds))
4217 ((equal key "TAGS")
4218 (setq tags (append tags (org-split-string value splitre))))
4219 ((equal key "COLUMNS")
4220 (org-set-local 'org-columns-default-format value))
4221 ((equal key "LINK")
4222 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4223 (push (cons (match-string 1 value)
4224 (org-trim (match-string 2 value)))
4225 links)))
4226 ((equal key "PRIORITIES")
4227 (setq prio (org-split-string value " +")))
4228 ((equal key "PROPERTY")
4229 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4230 (push (cons (match-string 1 value) (match-string 2 value))
4231 props)))
4232 ((equal key "DRAWERS")
4233 (setq drawers (org-split-string value splitre)))
4234 ((equal key "CONSTANTS")
4235 (setq const (append const (org-split-string value splitre))))
4236 ((equal key "STARTUP")
4237 (let ((opts (org-split-string value splitre))
4238 l var val)
4239 (while (setq l (pop opts))
4240 (when (setq l (assoc l org-startup-options))
4241 (setq var (nth 1 l) val (nth 2 l))
4242 (if (not (nth 3 l))
4243 (set (make-local-variable var) val)
4244 (if (not (listp (symbol-value var)))
4245 (set (make-local-variable var) nil))
4246 (set (make-local-variable var) (symbol-value var))
4247 (add-to-list var val))))))
4248 ((equal key "ARCHIVE")
4249 (string-match " *$" value)
4250 (setq arch (replace-match "" t t value))
4251 (remove-text-properties 0 (length arch)
4252 '(face t fontified t) arch)))
4254 (when cat
4255 (org-set-local 'org-category (intern cat))
4256 (push (cons "CATEGORY" cat) props))
4257 (when prio
4258 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4259 (setq prio (mapcar 'string-to-char prio))
4260 (org-set-local 'org-highest-priority (nth 0 prio))
4261 (org-set-local 'org-lowest-priority (nth 1 prio))
4262 (org-set-local 'org-default-priority (nth 2 prio)))
4263 (and props (org-set-local 'org-local-properties (nreverse props)))
4264 (and drawers (org-set-local 'org-drawers drawers))
4265 (and arch (org-set-local 'org-archive-location arch))
4266 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4267 ;; Process the TODO keywords
4268 (unless kwds
4269 ;; Use the global values as if they had been given locally.
4270 (setq kwds (default-value 'org-todo-keywords))
4271 (if (stringp (car kwds))
4272 (setq kwds (list (cons org-todo-interpretation
4273 (default-value 'org-todo-keywords)))))
4274 (setq kwds (reverse kwds)))
4275 (setq kwds (nreverse kwds))
4276 (let (inter kws kw)
4277 (while (setq kws (pop kwds))
4278 (setq inter (pop kws) sep (member "|" kws)
4279 kws0 (delete "|" (copy-sequence kws))
4280 kwsa nil
4281 kws1 (mapcar
4282 (lambda (x)
4283 (if (string-match "^\\(.*?\\)\\(?:(\\(..?\\))\\)?$" x)
4284 (progn
4285 (setq kw (match-string 1 x)
4286 ex (and (match-end 2) (match-string 2 x))
4287 log (and ex (string-match "@" ex))
4288 key (and ex (substring ex 0 1)))
4289 (if (equal key "@") (setq key nil))
4290 (push (cons kw (and key (string-to-char key))) kwsa)
4291 (and log (push kw org-todo-log-states))
4293 (error "Invalid TODO keyword %s" x)))
4294 kws0)
4295 kwsa (if kwsa (append '((:startgroup))
4296 (nreverse kwsa)
4297 '((:endgroup))))
4298 hw (car kws1)
4299 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4300 tail (list inter hw (car dws) (org-last dws)))
4301 (add-to-list 'org-todo-heads hw 'append)
4302 (push kws1 org-todo-sets)
4303 (setq org-done-keywords (append org-done-keywords dws nil))
4304 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4305 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4306 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4307 (setq org-todo-sets (nreverse org-todo-sets)
4308 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4309 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4310 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4311 ;; Process the constants
4312 (when const
4313 (let (e cst)
4314 (while (setq e (pop const))
4315 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4316 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4317 (setq org-table-formula-constants-local cst)))
4319 ;; Process the tags.
4320 (when tags
4321 (let (e tgs)
4322 (while (setq e (pop tags))
4323 (cond
4324 ((equal e "{") (push '(:startgroup) tgs))
4325 ((equal e "}") (push '(:endgroup) tgs))
4326 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4327 (push (cons (match-string 1 e)
4328 (string-to-char (match-string 2 e)))
4329 tgs))
4330 (t (push (list e) tgs))))
4331 (org-set-local 'org-tag-alist nil)
4332 (while (setq e (pop tgs))
4333 (or (and (stringp (car e))
4334 (assoc (car e) org-tag-alist))
4335 (push e org-tag-alist))))))
4337 ;; Compute the regular expressions and other local variables
4338 (if (not org-done-keywords)
4339 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4340 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4341 (length org-scheduled-string)))
4342 org-drawer-regexp
4343 (concat "^[ \t]*:\\("
4344 (mapconcat 'regexp-quote org-drawers "\\|")
4345 "\\):[ \t]*$")
4346 org-not-done-keywords
4347 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4348 org-todo-regexp
4349 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4350 "\\|") "\\)\\>")
4351 org-not-done-regexp
4352 (concat "\\<\\("
4353 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4354 "\\)\\>")
4355 org-todo-line-regexp
4356 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4357 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4358 "\\)\\>\\)?[ \t]*\\(.*\\)")
4359 org-complex-heading-regexp
4360 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4361 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4362 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4363 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4364 org-nl-done-regexp
4365 (concat "\n\\*+[ \t]+"
4366 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4367 "\\)" "\\>")
4368 org-todo-line-tags-regexp
4369 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4370 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4371 (org-re
4372 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4373 org-looking-at-done-regexp
4374 (concat "^" "\\(?:"
4375 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4376 "\\>")
4377 org-deadline-regexp (concat "\\<" org-deadline-string)
4378 org-deadline-time-regexp
4379 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4380 org-deadline-line-regexp
4381 (concat "\\<\\(" org-deadline-string "\\).*")
4382 org-scheduled-regexp
4383 (concat "\\<" org-scheduled-string)
4384 org-scheduled-time-regexp
4385 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4386 org-closed-time-regexp
4387 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4388 org-keyword-time-regexp
4389 (concat "\\<\\(" org-scheduled-string
4390 "\\|" org-deadline-string
4391 "\\|" org-closed-string
4392 "\\|" org-clock-string "\\)"
4393 " *[[<]\\([^]>]+\\)[]>]")
4394 org-keyword-time-not-clock-regexp
4395 (concat "\\<\\(" org-scheduled-string
4396 "\\|" org-deadline-string
4397 "\\|" org-closed-string
4398 "\\)"
4399 " *[[<]\\([^]>]+\\)[]>]")
4400 org-maybe-keyword-time-regexp
4401 (concat "\\(\\<\\(" org-scheduled-string
4402 "\\|" org-deadline-string
4403 "\\|" org-closed-string
4404 "\\|" org-clock-string "\\)\\)?"
4405 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4406 org-planning-or-clock-line-re
4407 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4408 "\\|" org-deadline-string
4409 "\\|" org-closed-string "\\|" org-clock-string
4410 "\\)\\>\\)")
4412 (org-compute-latex-and-specials-regexp)
4413 (org-set-font-lock-defaults)))
4415 (defun org-remove-keyword-keys (list)
4416 (mapcar (lambda (x)
4417 (if (string-match "(..?)$" x)
4418 (substring x 0 (match-beginning 0))
4420 list))
4422 ;; FIXME: this could be done much better, using second characters etc.
4423 (defun org-assign-fast-keys (alist)
4424 "Assign fast keys to a keyword-key alist.
4425 Respect keys that are already there."
4426 (let (new e k c c1 c2 (char ?a))
4427 (while (setq e (pop alist))
4428 (cond
4429 ((equal e '(:startgroup)) (push e new))
4430 ((equal e '(:endgroup)) (push e new))
4432 (setq k (car e) c2 nil)
4433 (if (cdr e)
4434 (setq c (cdr e))
4435 ;; automatically assign a character.
4436 (setq c1 (string-to-char
4437 (downcase (substring
4438 k (if (= (string-to-char k) ?@) 1 0)))))
4439 (if (or (rassoc c1 new) (rassoc c1 alist))
4440 (while (or (rassoc char new) (rassoc char alist))
4441 (setq char (1+ char)))
4442 (setq c2 c1))
4443 (setq c (or c2 char)))
4444 (push (cons k c) new))))
4445 (nreverse new)))
4447 ;;; Some variables ujsed in various places
4449 (defvar org-window-configuration nil
4450 "Used in various places to store a window configuration.")
4451 (defvar org-finish-function nil
4452 "Function to be called when `C-c C-c' is used.
4453 This is for getting out of special buffers like remember.")
4455 ;;; Foreign variables, to inform the compiler
4457 ;; XEmacs only
4458 (defvar outline-mode-menu-heading)
4459 (defvar outline-mode-menu-show)
4460 (defvar outline-mode-menu-hide)
4461 (defvar zmacs-regions) ; XEmacs regions
4462 ;; Emacs only
4463 (defvar mark-active)
4465 ;; Packages that org-mode interacts with
4466 (defvar calc-embedded-close-formula)
4467 (defvar calc-embedded-open-formula)
4468 (defvar font-lock-unfontify-region-function)
4469 (defvar org-goto-start-pos)
4470 (defvar vm-message-pointer)
4471 (defvar vm-folder-directory)
4472 (defvar wl-summary-buffer-elmo-folder)
4473 (defvar wl-summary-buffer-folder-name)
4474 (defvar gnus-other-frame-object)
4475 (defvar gnus-group-name)
4476 (defvar gnus-article-current)
4477 (defvar w3m-current-url)
4478 (defvar w3m-current-title)
4479 (defvar mh-progs)
4480 (defvar mh-current-folder)
4481 (defvar mh-show-folder-buffer)
4482 (defvar mh-index-folder)
4483 (defvar mh-searcher)
4484 (defvar calendar-mode-map)
4485 (defvar Info-current-file)
4486 (defvar Info-current-node)
4487 (defvar texmathp-why)
4488 (defvar remember-save-after-remembering)
4489 (defvar remember-data-file)
4490 (defvar remember-register)
4491 (defvar remember-buffer)
4492 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
4493 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
4494 (defvar org-latex-regexps)
4495 (defvar constants-unit-system)
4497 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4499 ;; FIXME: Occasionally check by commenting these, to make sure
4500 ;; no other functions uses these, forgetting to let-bind them.
4501 (defvar entry)
4502 (defvar state)
4503 (defvar last-state)
4504 (defvar date)
4505 (defvar description)
4507 ;; Defined somewhere in this file, but used before definition.
4508 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4509 (defvar org-agenda-buffer-name)
4510 (defvar org-agenda-undo-list)
4511 (defvar org-agenda-pending-undo-list)
4512 (defvar org-agenda-overriding-header)
4513 (defvar orgtbl-mode)
4514 (defvar org-html-entities)
4515 (defvar org-struct-menu)
4516 (defvar org-org-menu)
4517 (defvar org-tbl-menu)
4518 (defvar org-agenda-keymap)
4520 ;;;; Emacs/XEmacs compatibility
4522 ;; Overlay compatibility functions
4523 (defun org-make-overlay (beg end &optional buffer)
4524 (if (featurep 'xemacs)
4525 (make-extent beg end buffer)
4526 (make-overlay beg end buffer)))
4527 (defun org-delete-overlay (ovl)
4528 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4529 (defun org-detach-overlay (ovl)
4530 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4531 (defun org-move-overlay (ovl beg end &optional buffer)
4532 (if (featurep 'xemacs)
4533 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4534 (move-overlay ovl beg end buffer)))
4535 (defun org-overlay-put (ovl prop value)
4536 (if (featurep 'xemacs)
4537 (set-extent-property ovl prop value)
4538 (overlay-put ovl prop value)))
4539 (defun org-overlay-display (ovl text &optional face evap)
4540 "Make overlay OVL display TEXT with face FACE."
4541 (if (featurep 'xemacs)
4542 (let ((gl (make-glyph text)))
4543 (and face (set-glyph-face gl face))
4544 (set-extent-property ovl 'invisible t)
4545 (set-extent-property ovl 'end-glyph gl))
4546 (overlay-put ovl 'display text)
4547 (if face (overlay-put ovl 'face face))
4548 (if evap (overlay-put ovl 'evaporate t))))
4549 (defun org-overlay-before-string (ovl text &optional face evap)
4550 "Make overlay OVL display TEXT with face FACE."
4551 (if (featurep 'xemacs)
4552 (let ((gl (make-glyph text)))
4553 (and face (set-glyph-face gl face))
4554 (set-extent-property ovl 'begin-glyph gl))
4555 (if face (org-add-props text nil 'face face))
4556 (overlay-put ovl 'before-string text)
4557 (if evap (overlay-put ovl 'evaporate t))))
4558 (defun org-overlay-get (ovl prop)
4559 (if (featurep 'xemacs)
4560 (extent-property ovl prop)
4561 (overlay-get ovl prop)))
4562 (defun org-overlays-at (pos)
4563 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4564 (defun org-overlays-in (&optional start end)
4565 (if (featurep 'xemacs)
4566 (extent-list nil start end)
4567 (overlays-in start end)))
4568 (defun org-overlay-start (o)
4569 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4570 (defun org-overlay-end (o)
4571 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4572 (defun org-find-overlays (prop &optional pos delete)
4573 "Find all overlays specifying PROP at POS or point.
4574 If DELETE is non-nil, delete all those overlays."
4575 (let ((overlays (org-overlays-at (or pos (point))))
4576 ov found)
4577 (while (setq ov (pop overlays))
4578 (if (org-overlay-get ov prop)
4579 (if delete (org-delete-overlay ov) (push ov found))))
4580 found))
4582 ;; Region compatibility
4584 (defun org-add-hook (hook function &optional append local)
4585 "Add-hook, compatible with both Emacsen."
4586 (if (and local (featurep 'xemacs))
4587 (add-local-hook hook function append)
4588 (add-hook hook function append local)))
4590 (defvar org-ignore-region nil
4591 "To temporarily disable the active region.")
4593 (defun org-region-active-p ()
4594 "Is `transient-mark-mode' on and the region active?
4595 Works on both Emacs and XEmacs."
4596 (if org-ignore-region
4598 (if (featurep 'xemacs)
4599 (and zmacs-regions (region-active-p))
4600 (and transient-mark-mode mark-active))))
4602 ;; Invisibility compatibility
4604 (defun org-add-to-invisibility-spec (arg)
4605 "Add elements to `buffer-invisibility-spec'.
4606 See documentation for `buffer-invisibility-spec' for the kind of elements
4607 that can be added."
4608 (cond
4609 ((fboundp 'add-to-invisibility-spec)
4610 (add-to-invisibility-spec arg))
4611 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4612 (setq buffer-invisibility-spec (list arg)))
4614 (setq buffer-invisibility-spec
4615 (cons arg buffer-invisibility-spec)))))
4617 (defun org-remove-from-invisibility-spec (arg)
4618 "Remove elements from `buffer-invisibility-spec'."
4619 (if (fboundp 'remove-from-invisibility-spec)
4620 (remove-from-invisibility-spec arg)
4621 (if (consp buffer-invisibility-spec)
4622 (setq buffer-invisibility-spec
4623 (delete arg buffer-invisibility-spec)))))
4625 (defun org-in-invisibility-spec-p (arg)
4626 "Is ARG a member of `buffer-invisibility-spec'?"
4627 (if (consp buffer-invisibility-spec)
4628 (member arg buffer-invisibility-spec)
4629 nil))
4631 ;;;; Define the Org-mode
4633 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4634 (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."))
4637 ;; We use a before-change function to check if a table might need
4638 ;; an update.
4639 (defvar org-table-may-need-update t
4640 "Indicates that a table might need an update.
4641 This variable is set by `org-before-change-function'.
4642 `org-table-align' sets it back to nil.")
4643 (defvar org-mode-map)
4644 (defvar org-mode-hook nil)
4645 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4646 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4647 (defvar org-table-buffer-is-an nil)
4648 (defconst org-outline-regexp "\\*+ ")
4650 ;;;###autoload
4651 (define-derived-mode org-mode outline-mode "Org"
4652 "Outline-based notes management and organizer, alias
4653 \"Carsten's outline-mode for keeping track of everything.\"
4655 Org-mode develops organizational tasks around a NOTES file which
4656 contains information about projects as plain text. Org-mode is
4657 implemented on top of outline-mode, which is ideal to keep the content
4658 of large files well structured. It supports ToDo items, deadlines and
4659 time stamps, which magically appear in the diary listing of the Emacs
4660 calendar. Tables are easily created with a built-in table editor.
4661 Plain text URL-like links connect to websites, emails (VM), Usenet
4662 messages (Gnus), BBDB entries, and any files related to the project.
4663 For printing and sharing of notes, an Org-mode file (or a part of it)
4664 can be exported as a structured ASCII or HTML file.
4666 The following commands are available:
4668 \\{org-mode-map}"
4670 ;; Get rid of Outline menus, they are not needed
4671 ;; Need to do this here because define-derived-mode sets up
4672 ;; the keymap so late. Still, it is a waste to call this each time
4673 ;; we switch another buffer into org-mode.
4674 (if (featurep 'xemacs)
4675 (when (boundp 'outline-mode-menu-heading)
4676 ;; Assume this is Greg's port, it used easymenu
4677 (easy-menu-remove outline-mode-menu-heading)
4678 (easy-menu-remove outline-mode-menu-show)
4679 (easy-menu-remove outline-mode-menu-hide))
4680 (define-key org-mode-map [menu-bar headings] 'undefined)
4681 (define-key org-mode-map [menu-bar hide] 'undefined)
4682 (define-key org-mode-map [menu-bar show] 'undefined))
4684 (easy-menu-add org-org-menu)
4685 (easy-menu-add org-tbl-menu)
4686 (org-install-agenda-files-menu)
4687 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4688 (org-add-to-invisibility-spec '(org-cwidth))
4689 (when (featurep 'xemacs)
4690 (org-set-local 'line-move-ignore-invisible t))
4691 (org-set-local 'outline-regexp org-outline-regexp)
4692 (org-set-local 'outline-level 'org-outline-level)
4693 (when (and org-ellipsis
4694 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4695 (fboundp 'make-glyph-code))
4696 (unless org-display-table
4697 (setq org-display-table (make-display-table)))
4698 (set-display-table-slot
4699 org-display-table 4
4700 (vconcat (mapcar
4701 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4702 org-ellipsis)))
4703 (if (stringp org-ellipsis) org-ellipsis "..."))))
4704 (setq buffer-display-table org-display-table))
4705 (org-set-regexps-and-options)
4706 ;; Calc embedded
4707 (org-set-local 'calc-embedded-open-mode "# ")
4708 (modify-syntax-entry ?# "<")
4709 (modify-syntax-entry ?@ "w")
4710 (if org-startup-truncated (setq truncate-lines t))
4711 (org-set-local 'font-lock-unfontify-region-function
4712 'org-unfontify-region)
4713 ;; Activate before-change-function
4714 (org-set-local 'org-table-may-need-update t)
4715 (org-add-hook 'before-change-functions 'org-before-change-function nil
4716 'local)
4717 ;; Check for running clock before killing a buffer
4718 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4719 ;; Paragraphs and auto-filling
4720 (org-set-autofill-regexps)
4721 (setq indent-line-function 'org-indent-line-function)
4722 (org-update-radio-target-regexp)
4724 ;; Comment characters
4725 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4726 (org-set-local 'comment-padding " ")
4728 ;; Imenu
4729 (org-set-local 'imenu-create-index-function
4730 'org-imenu-get-tree)
4732 ;; Make isearch reveal context
4733 (if (or (featurep 'xemacs)
4734 (not (boundp 'outline-isearch-open-invisible-function)))
4735 ;; Emacs 21 and XEmacs make use of the hook
4736 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4737 ;; Emacs 22 deals with this through a special variable
4738 (org-set-local 'outline-isearch-open-invisible-function
4739 (lambda (&rest ignore) (org-show-context 'isearch))))
4741 ;; If empty file that did not turn on org-mode automatically, make it to.
4742 (if (and org-insert-mode-line-in-empty-file
4743 (interactive-p)
4744 (= (point-min) (point-max)))
4745 (insert "# -*- mode: org -*-\n\n"))
4747 (unless org-inhibit-startup
4748 (when org-startup-align-all-tables
4749 (let ((bmp (buffer-modified-p)))
4750 (org-table-map-tables 'org-table-align)
4751 (set-buffer-modified-p bmp)))
4752 (org-cycle-hide-drawers 'all)
4753 (cond
4754 ((eq org-startup-folded t)
4755 (org-cycle '(4)))
4756 ((eq org-startup-folded 'content)
4757 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4758 (org-cycle '(4)) (org-cycle '(4)))))))
4760 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4762 (defsubst org-call-with-arg (command arg)
4763 "Call COMMAND interactively, but pretend prefix are was ARG."
4764 (let ((current-prefix-arg arg)) (call-interactively command)))
4766 (defsubst org-current-line (&optional pos)
4767 (save-excursion
4768 (and pos (goto-char pos))
4769 ;; works also in narrowed buffer, because we start at 1, not point-min
4770 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
4772 (defun org-current-time ()
4773 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4774 (if (> org-time-stamp-rounding-minutes 0)
4775 (let ((r org-time-stamp-rounding-minutes)
4776 (time (decode-time)))
4777 (apply 'encode-time
4778 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4779 (nthcdr 2 time))))
4780 (current-time)))
4782 (defun org-add-props (string plist &rest props)
4783 "Add text properties to entire string, from beginning to end.
4784 PLIST may be a list of properties, PROPS are individual properties and values
4785 that will be added to PLIST. Returns the string that was modified."
4786 (add-text-properties
4787 0 (length string) (if props (append plist props) plist) string)
4788 string)
4789 (put 'org-add-props 'lisp-indent-function 2)
4792 ;;;; Font-Lock stuff, including the activators
4794 (defvar org-mouse-map (make-sparse-keymap))
4795 (org-defkey org-mouse-map
4796 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4797 (org-defkey org-mouse-map
4798 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4799 (when org-mouse-1-follows-link
4800 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4801 (when org-tab-follows-link
4802 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4803 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4804 (when org-return-follows-link
4805 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
4806 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
4808 (require 'font-lock)
4810 (defconst org-non-link-chars "]\t\n\r<>")
4811 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
4812 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
4813 (defvar org-link-re-with-space nil
4814 "Matches a link with spaces, optional angular brackets around it.")
4815 (defvar org-link-re-with-space2 nil
4816 "Matches a link with spaces, optional angular brackets around it.")
4817 (defvar org-angle-link-re nil
4818 "Matches link with angular brackets, spaces are allowed.")
4819 (defvar org-plain-link-re nil
4820 "Matches plain link, without spaces.")
4821 (defvar org-bracket-link-regexp nil
4822 "Matches a link in double brackets.")
4823 (defvar org-bracket-link-analytic-regexp nil
4824 "Regular expression used to analyze links.
4825 Here is what the match groups contain after a match:
4826 1: http:
4827 2: http
4828 3: path
4829 4: [desc]
4830 5: desc")
4831 (defvar org-any-link-re nil
4832 "Regular expression matching any link.")
4834 (defun org-make-link-regexps ()
4835 "Update the link regular expressions.
4836 This should be called after the variable `org-link-types' has changed."
4837 (setq org-link-re-with-space
4838 (concat
4839 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4840 "\\([^" org-non-link-chars " ]"
4841 "[^" org-non-link-chars "]*"
4842 "[^" org-non-link-chars " ]\\)>?")
4843 org-link-re-with-space2
4844 (concat
4845 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4846 "\\([^" org-non-link-chars " ]"
4847 "[^]\t\n\r]*"
4848 "[^" org-non-link-chars " ]\\)>?")
4849 org-angle-link-re
4850 (concat
4851 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4852 "\\([^" org-non-link-chars " ]"
4853 "[^" org-non-link-chars "]*"
4854 "\\)>")
4855 org-plain-link-re
4856 (concat
4857 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4858 "\\([^]\t\n\r<>,;() ]+\\)")
4859 org-bracket-link-regexp
4860 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4861 org-bracket-link-analytic-regexp
4862 (concat
4863 "\\[\\["
4864 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4865 "\\([^]]+\\)"
4866 "\\]"
4867 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4868 "\\]")
4869 org-any-link-re
4870 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4871 org-angle-link-re "\\)\\|\\("
4872 org-plain-link-re "\\)")))
4874 (org-make-link-regexps)
4876 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4877 "Regular expression for fast time stamp matching.")
4878 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4879 "Regular expression for fast time stamp matching.")
4880 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4881 "Regular expression matching time strings for analysis.
4882 This one does not require the space after the date.")
4883 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4884 "Regular expression matching time strings for analysis.")
4885 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4886 "Regular expression matching time stamps, with groups.")
4887 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4888 "Regular expression matching time stamps (also [..]), with groups.")
4889 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4890 "Regular expression matching a time stamp range.")
4891 (defconst org-tr-regexp-both
4892 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4893 "Regular expression matching a time stamp range.")
4894 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4895 org-ts-regexp "\\)?")
4896 "Regular expression matching a time stamp or time stamp range.")
4897 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4898 org-ts-regexp-both "\\)?")
4899 "Regular expression matching a time stamp or time stamp range.
4900 The time stamps may be either active or inactive.")
4902 (defvar org-emph-face nil)
4904 (defun org-do-emphasis-faces (limit)
4905 "Run through the buffer and add overlays to links."
4906 (let (rtn)
4907 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4908 (if (not (= (char-after (match-beginning 3))
4909 (char-after (match-beginning 4))))
4910 (progn
4911 (setq rtn t)
4912 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4913 'face
4914 (nth 1 (assoc (match-string 3)
4915 org-emphasis-alist)))
4916 (add-text-properties (match-beginning 2) (match-end 2)
4917 '(font-lock-multiline t))
4918 (when org-hide-emphasis-markers
4919 (add-text-properties (match-end 4) (match-beginning 5)
4920 '(invisible org-link))
4921 (add-text-properties (match-beginning 3) (match-end 3)
4922 '(invisible org-link)))))
4923 (backward-char 1))
4924 rtn))
4926 (defun org-emphasize (&optional char)
4927 "Insert or change an emphasis, i.e. a font like bold or italic.
4928 If there is an active region, change that region to a new emphasis.
4929 If there is no region, just insert the marker characters and position
4930 the cursor between them.
4931 CHAR should be either the marker character, or the first character of the
4932 HTML tag associated with that emphasis. If CHAR is a space, the means
4933 to remove the emphasis of the selected region.
4934 If char is not given (for example in an interactive call) it
4935 will be prompted for."
4936 (interactive)
4937 (let ((eal org-emphasis-alist) e det
4938 (erc org-emphasis-regexp-components)
4939 (prompt "")
4940 (string "") beg end move tag c s)
4941 (if (org-region-active-p)
4942 (setq beg (region-beginning) end (region-end)
4943 string (buffer-substring beg end))
4944 (setq move t))
4946 (while (setq e (pop eal))
4947 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4948 c (aref tag 0))
4949 (push (cons c (string-to-char (car e))) det)
4950 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4951 (substring tag 1)))))
4952 (unless char
4953 (message "%s" (concat "Emphasis marker or tag:" prompt))
4954 (setq char (read-char-exclusive)))
4955 (setq char (or (cdr (assoc char det)) char))
4956 (if (equal char ?\ )
4957 (setq s "" move nil)
4958 (unless (assoc (char-to-string char) org-emphasis-alist)
4959 (error "No such emphasis marker: \"%c\"" char))
4960 (setq s (char-to-string char)))
4961 (while (and (> (length string) 1)
4962 (equal (substring string 0 1) (substring string -1))
4963 (assoc (substring string 0 1) org-emphasis-alist))
4964 (setq string (substring string 1 -1)))
4965 (setq string (concat s string s))
4966 (if beg (delete-region beg end))
4967 (unless (or (bolp)
4968 (string-match (concat "[" (nth 0 erc) "\n]")
4969 (char-to-string (char-before (point)))))
4970 (insert " "))
4971 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4972 (char-to-string (char-after (point))))
4973 (insert " ") (backward-char 1))
4974 (insert string)
4975 (and move (backward-char 1))))
4977 (defconst org-nonsticky-props
4978 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4981 (defun org-activate-plain-links (limit)
4982 "Run through the buffer and add overlays to links."
4983 (catch 'exit
4984 (let (f)
4985 (while (re-search-forward org-plain-link-re limit t)
4986 (setq f (get-text-property (match-beginning 0) 'face))
4987 (if (or (eq f 'org-tag)
4988 (and (listp f) (memq 'org-tag f)))
4990 (add-text-properties (match-beginning 0) (match-end 0)
4991 (list 'mouse-face 'highlight
4992 'rear-nonsticky org-nonsticky-props
4993 'keymap org-mouse-map
4995 (throw 'exit t))))))
4997 (defun org-activate-code (limit)
4998 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
4999 (unless (get-text-property (match-beginning 1) 'face)
5000 (remove-text-properties (match-beginning 0) (match-end 0)
5001 '(display t invisible t intangible t))
5002 t)))
5004 (defun org-activate-angle-links (limit)
5005 "Run through the buffer and add overlays to links."
5006 (if (re-search-forward org-angle-link-re limit t)
5007 (progn
5008 (add-text-properties (match-beginning 0) (match-end 0)
5009 (list 'mouse-face 'highlight
5010 'rear-nonsticky org-nonsticky-props
5011 'keymap org-mouse-map
5013 t)))
5015 (defmacro org-maybe-intangible (props)
5016 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
5017 In emacs 21, invisible text is not avoided by the command loop, so the
5018 intangible property is needed to make sure point skips this text.
5019 In Emacs 22, this is not necessary. The intangible text property has
5020 led to problems with flyspell. These problems are fixed in flyspell.el,
5021 but we still avoid setting the property in Emacs 22 and later.
5022 We use a macro so that the test can happen at compilation time."
5023 (if (< emacs-major-version 22)
5024 `(append '(intangible t) ,props)
5025 props))
5027 (defun org-activate-bracket-links (limit)
5028 "Run through the buffer and add overlays to bracketed links."
5029 (if (re-search-forward org-bracket-link-regexp limit t)
5030 (let* ((help (concat "LINK: "
5031 (org-match-string-no-properties 1)))
5032 ;; FIXME: above we should remove the escapes.
5033 ;; but that requires another match, protecting match data,
5034 ;; a lot of overhead for font-lock.
5035 (ip (org-maybe-intangible
5036 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5037 'keymap org-mouse-map 'mouse-face 'highlight
5038 'font-lock-multiline t 'help-echo help)))
5039 (vp (list 'rear-nonsticky org-nonsticky-props
5040 'keymap org-mouse-map 'mouse-face 'highlight
5041 ' font-lock-multiline t 'help-echo help)))
5042 ;; We need to remove the invisible property here. Table narrowing
5043 ;; may have made some of this invisible.
5044 (remove-text-properties (match-beginning 0) (match-end 0)
5045 '(invisible nil))
5046 (if (match-end 3)
5047 (progn
5048 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5049 (add-text-properties (match-beginning 3) (match-end 3) vp)
5050 (add-text-properties (match-end 3) (match-end 0) ip))
5051 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5052 (add-text-properties (match-beginning 1) (match-end 1) vp)
5053 (add-text-properties (match-end 1) (match-end 0) ip))
5054 t)))
5056 (defun org-activate-dates (limit)
5057 "Run through the buffer and add overlays to dates."
5058 (if (re-search-forward org-tsr-regexp-both limit t)
5059 (progn
5060 (add-text-properties (match-beginning 0) (match-end 0)
5061 (list 'mouse-face 'highlight
5062 'rear-nonsticky org-nonsticky-props
5063 'keymap org-mouse-map))
5064 (when org-display-custom-times
5065 (if (match-end 3)
5066 (org-display-custom-time (match-beginning 3) (match-end 3)))
5067 (org-display-custom-time (match-beginning 1) (match-end 1)))
5068 t)))
5070 (defvar org-target-link-regexp nil
5071 "Regular expression matching radio targets in plain text.")
5072 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5073 "Regular expression matching a link target.")
5074 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5075 "Regular expression matching a radio target.")
5076 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5077 "Regular expression matching any target.")
5079 (defun org-activate-target-links (limit)
5080 "Run through the buffer and add overlays to target matches."
5081 (when org-target-link-regexp
5082 (let ((case-fold-search t))
5083 (if (re-search-forward org-target-link-regexp limit t)
5084 (progn
5085 (add-text-properties (match-beginning 0) (match-end 0)
5086 (list 'mouse-face 'highlight
5087 'rear-nonsticky org-nonsticky-props
5088 'keymap org-mouse-map
5089 'help-echo "Radio target link"
5090 'org-linked-text t))
5091 t)))))
5093 (defun org-update-radio-target-regexp ()
5094 "Find all radio targets in this file and update the regular expression."
5095 (interactive)
5096 (when (memq 'radio org-activate-links)
5097 (setq org-target-link-regexp
5098 (org-make-target-link-regexp (org-all-targets 'radio)))
5099 (org-restart-font-lock)))
5101 (defun org-hide-wide-columns (limit)
5102 (let (s e)
5103 (setq s (text-property-any (point) (or limit (point-max))
5104 'org-cwidth t))
5105 (when s
5106 (setq e (next-single-property-change s 'org-cwidth))
5107 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5108 (goto-char e)
5109 t)))
5111 (defvar org-latex-and-specials-regexp nil
5112 "Regular expression for highlighting export special stuff.")
5113 (defvar org-match-substring-regexp)
5114 (defvar org-match-substring-with-braces-regexp)
5115 (defvar org-export-html-special-string-regexps)
5117 (defun org-compute-latex-and-specials-regexp ()
5118 "Compute regular expression for stuff treated specially by exporters."
5119 (if (not org-highlight-latex-fragments-and-specials)
5120 (org-set-local 'org-latex-and-specials-regexp nil)
5121 (let*
5122 ((matchers (plist-get org-format-latex-options :matchers))
5123 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5124 org-latex-regexps)))
5125 (options (org-combine-plists (org-default-export-plist)
5126 (org-infile-export-plist)))
5127 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5128 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5129 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5130 (org-export-html-expand (plist-get options :expand-quoted-html))
5131 (org-export-with-special-strings (plist-get options :special-strings))
5132 (re-sub
5133 (cond
5134 ((equal org-export-with-sub-superscripts '{})
5135 (list org-match-substring-with-braces-regexp))
5136 (org-export-with-sub-superscripts
5137 (list org-match-substring-regexp))
5138 (t nil)))
5139 (re-latex
5140 (if org-export-with-LaTeX-fragments
5141 (mapcar (lambda (x) (nth 1 x)) latexs)))
5142 (re-macros
5143 (if org-export-with-TeX-macros
5144 (list (concat "\\\\"
5145 (regexp-opt
5146 (append (mapcar 'car org-html-entities)
5147 (if (boundp 'org-latex-entities)
5148 org-latex-entities nil))
5149 'words))) ; FIXME
5151 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5152 (re-special (if org-export-with-special-strings
5153 (mapcar (lambda (x) (car x))
5154 org-export-html-special-string-regexps)))
5155 (re-rest
5156 (delq nil
5157 (list
5158 (if org-export-html-expand "@<[^>\n]+>")
5159 ))))
5160 (org-set-local
5161 'org-latex-and-specials-regexp
5162 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5163 re-rest) "\\|")))))
5165 (defface org-latex-and-export-specials
5166 (let ((font (cond ((assq :inherit custom-face-attributes)
5167 '(:inherit underline))
5168 (t '(:underline t)))))
5169 `((((class grayscale) (background light))
5170 (:foreground "DimGray" ,@font))
5171 (((class grayscale) (background dark))
5172 (:foreground "LightGray" ,@font))
5173 (((class color) (background light))
5174 (:foreground "SaddleBrown"))
5175 (((class color) (background dark))
5176 (:foreground "burlywood"))
5177 (t (,@font))))
5178 "Face used to highlight math latex and other special exporter stuff."
5179 :group 'org-faces)
5181 (defun org-do-latex-and-special-faces (limit)
5182 "Run through the buffer and add overlays to links."
5183 (when org-latex-and-specials-regexp
5184 (let (rtn d)
5185 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5186 limit t))
5187 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5188 'face))
5189 '(org-code org-verbatim underline)))
5190 (progn
5191 (setq rtn t
5192 d (cond ((member (char-after (1+ (match-beginning 0)))
5193 '(?_ ?^)) 1)
5194 (t 0)))
5195 (font-lock-prepend-text-property
5196 (+ d (match-beginning 0)) (match-end 0)
5197 'face 'org-latex-and-export-specials)
5198 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5199 '(font-lock-multiline t)))))
5200 rtn)))
5202 (defun org-restart-font-lock ()
5203 "Restart font-lock-mode, to force refontification."
5204 (when (and (boundp 'font-lock-mode) font-lock-mode)
5205 (font-lock-mode -1)
5206 (font-lock-mode 1)))
5208 (defun org-all-targets (&optional radio)
5209 "Return a list of all targets in this file.
5210 With optional argument RADIO, only find radio targets."
5211 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5212 rtn)
5213 (save-excursion
5214 (goto-char (point-min))
5215 (while (re-search-forward re nil t)
5216 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5217 rtn)))
5219 (defun org-make-target-link-regexp (targets)
5220 "Make regular expression matching all strings in TARGETS.
5221 The regular expression finds the targets also if there is a line break
5222 between words."
5223 (and targets
5224 (concat
5225 "\\<\\("
5226 (mapconcat
5227 (lambda (x)
5228 (while (string-match " +" x)
5229 (setq x (replace-match "\\s-+" t t x)))
5231 targets
5232 "\\|")
5233 "\\)\\>")))
5235 (defun org-activate-tags (limit)
5236 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5237 (progn
5238 (add-text-properties (match-beginning 1) (match-end 1)
5239 (list 'mouse-face 'highlight
5240 'rear-nonsticky org-nonsticky-props
5241 'keymap org-mouse-map))
5242 t)))
5244 (defun org-outline-level ()
5245 (save-excursion
5246 (looking-at outline-regexp)
5247 (if (match-beginning 1)
5248 (+ (org-get-string-indentation (match-string 1)) 1000)
5249 (1- (- (match-end 0) (match-beginning 0))))))
5251 (defvar org-font-lock-keywords nil)
5253 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5254 "Regular expression matching a property line.")
5256 (defun org-set-font-lock-defaults ()
5257 (let* ((em org-fontify-emphasized-text)
5258 (lk org-activate-links)
5259 (org-font-lock-extra-keywords
5260 (list
5261 ;; Headlines
5262 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5263 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5264 ;; Table lines
5265 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5266 (1 'org-table t))
5267 ;; Table internals
5268 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5269 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5270 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5271 ;; Drawers
5272 (list org-drawer-regexp '(0 'org-special-keyword t))
5273 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5274 ;; Properties
5275 (list org-property-re
5276 '(1 'org-special-keyword t)
5277 '(3 'org-property-value t))
5278 (if org-format-transports-properties-p
5279 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5280 ;; Links
5281 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5282 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5283 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5284 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5285 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5286 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5287 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5288 '(org-hide-wide-columns (0 nil append))
5289 ;; TODO lines
5290 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5291 '(1 (org-get-todo-face 1) t))
5292 ;; DONE
5293 (if org-fontify-done-headline
5294 (list (concat "^[*]+ +\\<\\("
5295 (mapconcat 'regexp-quote org-done-keywords "\\|")
5296 "\\)\\(.*\\)")
5297 '(2 'org-headline-done t))
5298 nil)
5299 ;; Priorities
5300 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5301 ;; Special keywords
5302 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5303 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5304 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5305 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5306 ;; Emphasis
5307 (if em
5308 (if (featurep 'xemacs)
5309 '(org-do-emphasis-faces (0 nil append))
5310 '(org-do-emphasis-faces)))
5311 ;; Checkboxes
5312 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5313 2 'bold prepend)
5314 (if org-provide-checkbox-statistics
5315 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5316 (0 (org-get-checkbox-statistics-face) t)))
5317 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5318 '(1 'org-archived prepend))
5319 ;; Specials
5320 '(org-do-latex-and-special-faces)
5321 ;; Code
5322 '(org-activate-code (1 'org-code t))
5323 ;; COMMENT
5324 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5325 "\\|" org-quote-string "\\)\\>")
5326 '(1 'org-special-keyword t))
5327 '("^#.*" (0 'font-lock-comment-face t))
5329 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5330 ;; Now set the full font-lock-keywords
5331 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5332 (org-set-local 'font-lock-defaults
5333 '(org-font-lock-keywords t nil nil backward-paragraph))
5334 (kill-local-variable 'font-lock-keywords) nil))
5336 (defvar org-m nil)
5337 (defvar org-l nil)
5338 (defvar org-f nil)
5339 (defun org-get-level-face (n)
5340 "Get the right face for match N in font-lock matching of healdines."
5341 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5342 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5343 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5344 (cond
5345 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5346 ((eq n 2) org-f)
5347 (t (if org-level-color-stars-only nil org-f))))
5349 (defun org-get-todo-face (kwd)
5350 "Get the right face for a TODO keyword KWD.
5351 If KWD is a number, get the corresponding match group."
5352 (if (numberp kwd) (setq kwd (match-string kwd)))
5353 (or (cdr (assoc kwd org-todo-keyword-faces))
5354 (and (member kwd org-done-keywords) 'org-done)
5355 'org-todo))
5357 (defun org-unfontify-region (beg end &optional maybe_loudly)
5358 "Remove fontification and activation overlays from links."
5359 (font-lock-default-unfontify-region beg end)
5360 (let* ((buffer-undo-list t)
5361 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5362 (inhibit-modification-hooks t)
5363 deactivate-mark buffer-file-name buffer-file-truename)
5364 (remove-text-properties beg end
5365 '(mouse-face t keymap t org-linked-text t
5366 invisible t intangible t))))
5368 ;;;; Visibility cycling, including org-goto and indirect buffer
5370 ;;; Cycling
5372 (defvar org-cycle-global-status nil)
5373 (make-variable-buffer-local 'org-cycle-global-status)
5374 (defvar org-cycle-subtree-status nil)
5375 (make-variable-buffer-local 'org-cycle-subtree-status)
5377 ;;;###autoload
5378 (defun org-cycle (&optional arg)
5379 "Visibility cycling for Org-mode.
5381 - When this function is called with a prefix argument, rotate the entire
5382 buffer through 3 states (global cycling)
5383 1. OVERVIEW: Show only top-level headlines.
5384 2. CONTENTS: Show all headlines of all levels, but no body text.
5385 3. SHOW ALL: Show everything.
5387 - When point is at the beginning of a headline, rotate the subtree started
5388 by this line through 3 different states (local cycling)
5389 1. FOLDED: Only the main headline is shown.
5390 2. CHILDREN: The main headline and the direct children are shown.
5391 From this state, you can move to one of the children
5392 and zoom in further.
5393 3. SUBTREE: Show the entire subtree, including body text.
5395 - When there is a numeric prefix, go up to a heading with level ARG, do
5396 a `show-subtree' and return to the previous cursor position. If ARG
5397 is negative, go up that many levels.
5399 - When point is not at the beginning of a headline, execute
5400 `indent-relative', like TAB normally does. See the option
5401 `org-cycle-emulate-tab' for details.
5403 - Special case: if point is at the beginning of the buffer and there is
5404 no headline in line 1, this function will act as if called with prefix arg.
5405 But only if also the variable `org-cycle-global-at-bob' is t."
5406 (interactive "P")
5407 (let* ((outline-regexp
5408 (if (and (org-mode-p) org-cycle-include-plain-lists)
5409 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5410 outline-regexp))
5411 (bob-special (and org-cycle-global-at-bob (bobp)
5412 (not (looking-at outline-regexp))))
5413 (org-cycle-hook
5414 (if bob-special
5415 (delq 'org-optimize-window-after-visibility-change
5416 (copy-sequence org-cycle-hook))
5417 org-cycle-hook))
5418 (pos (point)))
5420 (if (or bob-special (equal arg '(4)))
5421 ;; special case: use global cycling
5422 (setq arg t))
5424 (cond
5426 ((org-at-table-p 'any)
5427 ;; Enter the table or move to the next field in the table
5428 (or (org-table-recognize-table.el)
5429 (progn
5430 (if arg (org-table-edit-field t)
5431 (org-table-justify-field-maybe)
5432 (call-interactively 'org-table-next-field)))))
5434 ((eq arg t) ;; Global cycling
5436 (cond
5437 ((and (eq last-command this-command)
5438 (eq org-cycle-global-status 'overview))
5439 ;; We just created the overview - now do table of contents
5440 ;; This can be slow in very large buffers, so indicate action
5441 (message "CONTENTS...")
5442 (org-content)
5443 (message "CONTENTS...done")
5444 (setq org-cycle-global-status 'contents)
5445 (run-hook-with-args 'org-cycle-hook 'contents))
5447 ((and (eq last-command this-command)
5448 (eq org-cycle-global-status 'contents))
5449 ;; We just showed the table of contents - now show everything
5450 (show-all)
5451 (message "SHOW ALL")
5452 (setq org-cycle-global-status 'all)
5453 (run-hook-with-args 'org-cycle-hook 'all))
5456 ;; Default action: go to overview
5457 (org-overview)
5458 (message "OVERVIEW")
5459 (setq org-cycle-global-status 'overview)
5460 (run-hook-with-args 'org-cycle-hook 'overview))))
5462 ((and org-drawers org-drawer-regexp
5463 (save-excursion
5464 (beginning-of-line 1)
5465 (looking-at org-drawer-regexp)))
5466 ;; Toggle block visibility
5467 (org-flag-drawer
5468 (not (get-char-property (match-end 0) 'invisible))))
5470 ((integerp arg)
5471 ;; Show-subtree, ARG levels up from here.
5472 (save-excursion
5473 (org-back-to-heading)
5474 (outline-up-heading (if (< arg 0) (- arg)
5475 (- (funcall outline-level) arg)))
5476 (org-show-subtree)))
5478 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5479 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5480 ;; At a heading: rotate between three different views
5481 (org-back-to-heading)
5482 (let ((goal-column 0) eoh eol eos)
5483 ;; First, some boundaries
5484 (save-excursion
5485 (org-back-to-heading)
5486 (save-excursion
5487 (beginning-of-line 2)
5488 (while (and (not (eobp)) ;; this is like `next-line'
5489 (get-char-property (1- (point)) 'invisible))
5490 (beginning-of-line 2)) (setq eol (point)))
5491 (outline-end-of-heading) (setq eoh (point))
5492 (org-end-of-subtree t)
5493 (unless (eobp)
5494 (skip-chars-forward " \t\n")
5495 (beginning-of-line 1) ; in case this is an item
5497 (setq eos (1- (point))))
5498 ;; Find out what to do next and set `this-command'
5499 (cond
5500 ((= eos eoh)
5501 ;; Nothing is hidden behind this heading
5502 (message "EMPTY ENTRY")
5503 (setq org-cycle-subtree-status nil)
5504 (save-excursion
5505 (goto-char eos)
5506 (outline-next-heading)
5507 (if (org-invisible-p) (org-flag-heading nil))))
5508 ((or (>= eol eos)
5509 (not (string-match "\\S-" (buffer-substring eol eos))))
5510 ;; Entire subtree is hidden in one line: open it
5511 (org-show-entry)
5512 (show-children)
5513 (message "CHILDREN")
5514 (save-excursion
5515 (goto-char eos)
5516 (outline-next-heading)
5517 (if (org-invisible-p) (org-flag-heading nil)))
5518 (setq org-cycle-subtree-status 'children)
5519 (run-hook-with-args 'org-cycle-hook 'children))
5520 ((and (eq last-command this-command)
5521 (eq org-cycle-subtree-status 'children))
5522 ;; We just showed the children, now show everything.
5523 (org-show-subtree)
5524 (message "SUBTREE")
5525 (setq org-cycle-subtree-status 'subtree)
5526 (run-hook-with-args 'org-cycle-hook 'subtree))
5528 ;; Default action: hide the subtree.
5529 (hide-subtree)
5530 (message "FOLDED")
5531 (setq org-cycle-subtree-status 'folded)
5532 (run-hook-with-args 'org-cycle-hook 'folded)))))
5534 ;; TAB emulation
5535 (buffer-read-only (org-back-to-heading))
5537 ((org-try-cdlatex-tab))
5539 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5540 (or (not (bolp))
5541 (not (looking-at outline-regexp))))
5542 (call-interactively (global-key-binding "\t")))
5544 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5545 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5546 (or (and (eq org-cycle-emulate-tab 'white)
5547 (= (match-end 0) (point-at-eol)))
5548 (and (eq org-cycle-emulate-tab 'whitestart)
5549 (>= (match-end 0) pos))))
5551 (eq org-cycle-emulate-tab t))
5552 ; (if (and (looking-at "[ \n\r\t]")
5553 ; (string-match "^[ \t]*$" (buffer-substring
5554 ; (point-at-bol) (point))))
5555 ; (progn
5556 ; (beginning-of-line 1)
5557 ; (and (looking-at "[ \t]+") (replace-match ""))))
5558 (call-interactively (global-key-binding "\t")))
5560 (t (save-excursion
5561 (org-back-to-heading)
5562 (org-cycle))))))
5564 ;;;###autoload
5565 (defun org-global-cycle (&optional arg)
5566 "Cycle the global visibility. For details see `org-cycle'."
5567 (interactive "P")
5568 (let ((org-cycle-include-plain-lists
5569 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5570 (if (integerp arg)
5571 (progn
5572 (show-all)
5573 (hide-sublevels arg)
5574 (setq org-cycle-global-status 'contents))
5575 (org-cycle '(4)))))
5577 (defun org-overview ()
5578 "Switch to overview mode, shoing only top-level headlines.
5579 Really, this shows all headlines with level equal or greater than the level
5580 of the first headline in the buffer. This is important, because if the
5581 first headline is not level one, then (hide-sublevels 1) gives confusing
5582 results."
5583 (interactive)
5584 (let ((level (save-excursion
5585 (goto-char (point-min))
5586 (if (re-search-forward (concat "^" outline-regexp) nil t)
5587 (progn
5588 (goto-char (match-beginning 0))
5589 (funcall outline-level))))))
5590 (and level (hide-sublevels level))))
5592 (defun org-content (&optional arg)
5593 "Show all headlines in the buffer, like a table of contents.
5594 With numerical argument N, show content up to level N."
5595 (interactive "P")
5596 (save-excursion
5597 ;; Visit all headings and show their offspring
5598 (and (integerp arg) (org-overview))
5599 (goto-char (point-max))
5600 (catch 'exit
5601 (while (and (progn (condition-case nil
5602 (outline-previous-visible-heading 1)
5603 (error (goto-char (point-min))))
5605 (looking-at outline-regexp))
5606 (if (integerp arg)
5607 (show-children (1- arg))
5608 (show-branches))
5609 (if (bobp) (throw 'exit nil))))))
5612 (defun org-optimize-window-after-visibility-change (state)
5613 "Adjust the window after a change in outline visibility.
5614 This function is the default value of the hook `org-cycle-hook'."
5615 (when (get-buffer-window (current-buffer))
5616 (cond
5617 ; ((eq state 'overview) (org-first-headline-recenter 1))
5618 ; ((eq state 'overview) (org-beginning-of-line))
5619 ((eq state 'content) nil)
5620 ((eq state 'all) nil)
5621 ((eq state 'folded) nil)
5622 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5623 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5626 (defun org-cycle-show-empty-lines (state)
5627 "Show empty lines above all visible headlines.
5628 The region to be covered depends on STATE when called through
5629 `org-cycle-hook'. Lisp program can use t for STATE to get the
5630 entire buffer covered. Note that an empty line is only shown if there
5631 are at least `org-cycle-separator-lines' empty lines before the headeline."
5632 (when (> org-cycle-separator-lines 0)
5633 (save-excursion
5634 (let* ((n org-cycle-separator-lines)
5635 (re (cond
5636 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5637 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5638 (t (let ((ns (number-to-string (- n 2))))
5639 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5640 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5641 beg end)
5642 (cond
5643 ((memq state '(overview contents t))
5644 (setq beg (point-min) end (point-max)))
5645 ((memq state '(children folded))
5646 (setq beg (point) end (progn (org-end-of-subtree t t)
5647 (beginning-of-line 2)
5648 (point)))))
5649 (when beg
5650 (goto-char beg)
5651 (while (re-search-forward re end t)
5652 (if (not (get-char-property (match-end 1) 'invisible))
5653 (outline-flag-region
5654 (match-beginning 1) (match-end 1) nil)))))))
5655 ;; Never hide empty lines at the end of the file.
5656 (save-excursion
5657 (goto-char (point-max))
5658 (outline-previous-heading)
5659 (outline-end-of-heading)
5660 (if (and (looking-at "[ \t\n]+")
5661 (= (match-end 0) (point-max)))
5662 (outline-flag-region (point) (match-end 0) nil))))
5664 (defun org-subtree-end-visible-p ()
5665 "Is the end of the current subtree visible?"
5666 (pos-visible-in-window-p
5667 (save-excursion (org-end-of-subtree t) (point))))
5669 (defun org-first-headline-recenter (&optional N)
5670 "Move cursor to the first headline and recenter the headline.
5671 Optional argument N means, put the headline into the Nth line of the window."
5672 (goto-char (point-min))
5673 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5674 (beginning-of-line)
5675 (recenter (prefix-numeric-value N))))
5677 ;;; Org-goto
5679 (defvar org-goto-window-configuration nil)
5680 (defvar org-goto-marker nil)
5681 (defvar org-goto-map
5682 (let ((map (make-sparse-keymap)))
5683 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5684 (while (setq cmd (pop cmds))
5685 (substitute-key-definition cmd cmd map global-map)))
5686 (suppress-keymap map)
5687 (org-defkey map "\C-m" 'org-goto-ret)
5688 (org-defkey map [(left)] 'org-goto-left)
5689 (org-defkey map [(right)] 'org-goto-right)
5690 (org-defkey map [(?q)] 'org-goto-quit)
5691 (org-defkey map [(control ?g)] 'org-goto-quit)
5692 (org-defkey map "\C-i" 'org-cycle)
5693 (org-defkey map [(tab)] 'org-cycle)
5694 (org-defkey map [(down)] 'outline-next-visible-heading)
5695 (org-defkey map [(up)] 'outline-previous-visible-heading)
5696 (org-defkey map "n" 'outline-next-visible-heading)
5697 (org-defkey map "p" 'outline-previous-visible-heading)
5698 (org-defkey map "f" 'outline-forward-same-level)
5699 (org-defkey map "b" 'outline-backward-same-level)
5700 (org-defkey map "u" 'outline-up-heading)
5701 (org-defkey map "/" 'org-occur)
5702 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5703 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5704 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5705 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5706 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5707 map))
5709 (defconst org-goto-help
5710 "Browse copy of buffer to find location or copy text.
5711 RET=jump to location [Q]uit and return to previous location
5712 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur"
5715 (defun org-goto ()
5716 "Look up a different location in the current file, keeping current visibility.
5718 When you want look-up or go to a different location in a document, the
5719 fastest way is often to fold the entire buffer and then dive into the tree.
5720 This method has the disadvantage, that the previous location will be folded,
5721 which may not be what you want.
5723 This command works around this by showing a copy of the current buffer
5724 in an indirect buffer, in overview mode. You can dive into the tree in
5725 that copy, use org-occur and incremental search to find a location.
5726 When pressing RET or `Q', the command returns to the original buffer in
5727 which the visibility is still unchanged. After RET is will also jump to
5728 the location selected in the indirect buffer and expose the
5729 the headline hierarchy above."
5730 (interactive)
5731 (let* ((org-goto-start-pos (point))
5732 (selected-point
5733 (car (org-get-location (current-buffer) org-goto-help))))
5734 (if selected-point
5735 (progn
5736 (org-mark-ring-push org-goto-start-pos)
5737 (goto-char selected-point)
5738 (if (or (org-invisible-p) (org-invisible-p2))
5739 (org-show-context 'org-goto)))
5740 (message "Quit"))))
5742 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5743 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5745 (defun org-get-location (buf help)
5746 "Let the user select a location in the Org-mode buffer BUF.
5747 This function uses a recursive edit. It returns the selected position
5748 or nil."
5749 (let (org-goto-selected-point org-goto-exit-command)
5750 (save-excursion
5751 (save-window-excursion
5752 (delete-other-windows)
5753 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5754 (switch-to-buffer
5755 (condition-case nil
5756 (make-indirect-buffer (current-buffer) "*org-goto*")
5757 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5758 (with-output-to-temp-buffer "*Help*"
5759 (princ help))
5760 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
5761 (setq buffer-read-only nil)
5762 (let ((org-startup-truncated t)
5763 (org-startup-folded nil)
5764 (org-startup-align-all-tables nil))
5765 (org-mode)
5766 (org-overview))
5767 (setq buffer-read-only t)
5768 (if (and (boundp 'org-goto-start-pos)
5769 (integer-or-marker-p org-goto-start-pos))
5770 (let ((org-show-hierarchy-above t)
5771 (org-show-siblings t)
5772 (org-show-following-heading t))
5773 (goto-char org-goto-start-pos)
5774 (and (org-invisible-p) (org-show-context)))
5775 (goto-char (point-min)))
5776 (org-beginning-of-line)
5777 (message "Select location and press RET")
5778 ;; now we make sure that during selection, ony very few keys work
5779 ;; and that it is impossible to switch to another window.
5780 ; (let ((gm (current-global-map))
5781 ; (overriding-local-map org-goto-map))
5782 ; (unwind-protect
5783 ; (progn
5784 ; (use-global-map org-goto-map)
5785 ; (recursive-edit))
5786 ; (use-global-map gm)))
5787 (use-local-map org-goto-map)
5788 (recursive-edit)
5790 (kill-buffer "*org-goto*")
5791 (cons org-goto-selected-point org-goto-exit-command)))
5793 (defun org-goto-ret (&optional arg)
5794 "Finish `org-goto' by going to the new location."
5795 (interactive "P")
5796 (setq org-goto-selected-point (point)
5797 org-goto-exit-command 'return)
5798 (throw 'exit nil))
5800 (defun org-goto-left ()
5801 "Finish `org-goto' by going to the new location."
5802 (interactive)
5803 (if (org-on-heading-p)
5804 (progn
5805 (beginning-of-line 1)
5806 (setq org-goto-selected-point (point)
5807 org-goto-exit-command 'left)
5808 (throw 'exit nil))
5809 (error "Not on a heading")))
5811 (defun org-goto-right ()
5812 "Finish `org-goto' by going to the new location."
5813 (interactive)
5814 (if (org-on-heading-p)
5815 (progn
5816 (setq org-goto-selected-point (point)
5817 org-goto-exit-command 'right)
5818 (throw 'exit nil))
5819 (error "Not on a heading")))
5821 (defun org-goto-quit ()
5822 "Finish `org-goto' without cursor motion."
5823 (interactive)
5824 (setq org-goto-selected-point nil)
5825 (setq org-goto-exit-command 'quit)
5826 (throw 'exit nil))
5828 ;;; Indirect buffer display of subtrees
5830 (defvar org-indirect-dedicated-frame nil
5831 "This is the frame being used for indirect tree display.")
5832 (defvar org-last-indirect-buffer nil)
5834 (defun org-tree-to-indirect-buffer (&optional arg)
5835 "Create indirect buffer and narrow it to current subtree.
5836 With numerical prefix ARG, go up to this level and then take that tree.
5837 If ARG is negative, go up that many levels.
5838 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5839 indirect buffer previously made with this command, to avoid proliferation of
5840 indirect buffers. However, when you call the command with a `C-u' prefix, or
5841 when `org-indirect-buffer-display' is `new-frame', the last buffer
5842 is kept so that you can work with several indirect buffers at the same time.
5843 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5844 requests that a new frame be made for the new buffer, so that the dedicated
5845 frame is not changed."
5846 (interactive "P")
5847 (let ((cbuf (current-buffer))
5848 (cwin (selected-window))
5849 (pos (point))
5850 beg end level heading ibuf)
5851 (save-excursion
5852 (org-back-to-heading t)
5853 (when (numberp arg)
5854 (setq level (org-outline-level))
5855 (if (< arg 0) (setq arg (+ level arg)))
5856 (while (> (setq level (org-outline-level)) arg)
5857 (outline-up-heading 1 t)))
5858 (setq beg (point)
5859 heading (org-get-heading))
5860 (org-end-of-subtree t) (setq end (point)))
5861 (if (and (buffer-live-p org-last-indirect-buffer)
5862 (not (eq org-indirect-buffer-display 'new-frame))
5863 (not arg))
5864 (kill-buffer org-last-indirect-buffer))
5865 (setq ibuf (org-get-indirect-buffer cbuf)
5866 org-last-indirect-buffer ibuf)
5867 (cond
5868 ((or (eq org-indirect-buffer-display 'new-frame)
5869 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5870 (select-frame (make-frame))
5871 (delete-other-windows)
5872 (switch-to-buffer ibuf)
5873 (org-set-frame-title heading))
5874 ((eq org-indirect-buffer-display 'dedicated-frame)
5875 (raise-frame
5876 (select-frame (or (and org-indirect-dedicated-frame
5877 (frame-live-p org-indirect-dedicated-frame)
5878 org-indirect-dedicated-frame)
5879 (setq org-indirect-dedicated-frame (make-frame)))))
5880 (delete-other-windows)
5881 (switch-to-buffer ibuf)
5882 (org-set-frame-title (concat "Indirect: " heading)))
5883 ((eq org-indirect-buffer-display 'current-window)
5884 (switch-to-buffer ibuf))
5885 ((eq org-indirect-buffer-display 'other-window)
5886 (pop-to-buffer ibuf))
5887 (t (error "Invalid value.")))
5888 (if (featurep 'xemacs)
5889 (save-excursion (org-mode) (turn-on-font-lock)))
5890 (narrow-to-region beg end)
5891 (show-all)
5892 (goto-char pos)
5893 (and (window-live-p cwin) (select-window cwin))))
5895 (defun org-get-indirect-buffer (&optional buffer)
5896 (setq buffer (or buffer (current-buffer)))
5897 (let ((n 1) (base (buffer-name buffer)) bname)
5898 (while (buffer-live-p
5899 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5900 (setq n (1+ n)))
5901 (condition-case nil
5902 (make-indirect-buffer buffer bname 'clone)
5903 (error (make-indirect-buffer buffer bname)))))
5905 (defun org-set-frame-title (title)
5906 "Set the title of the current frame to the string TITLE."
5907 ;; FIXME: how to name a single frame in XEmacs???
5908 (unless (featurep 'xemacs)
5909 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5911 ;;;; Structure editing
5913 ;;; Inserting headlines
5915 (defun org-insert-heading (&optional force-heading)
5916 "Insert a new heading or item with same depth at point.
5917 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5918 If point is at the beginning of a headline, insert a sibling before the
5919 current headline. If point is in the middle of a headline, split the headline
5920 at that position and make the rest of the headline part of the sibling below
5921 the current headline."
5922 (interactive "P")
5923 (if (= (buffer-size) 0)
5924 (insert "\n* ")
5925 (when (or force-heading (not (org-insert-item)))
5926 (let* ((head (save-excursion
5927 (condition-case nil
5928 (progn
5929 (org-back-to-heading)
5930 (match-string 0))
5931 (error "*"))))
5932 (blank (cdr (assq 'heading org-blank-before-new-entry)))
5933 pos)
5934 (cond
5935 ((and (org-on-heading-p) (bolp)
5936 (or (bobp)
5937 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5938 (open-line (if blank 2 1)))
5939 ((and (bolp)
5940 (or (bobp)
5941 (save-excursion
5942 (backward-char 1) (not (org-invisible-p)))))
5943 nil)
5944 (t (newline (if blank 2 1))))
5945 (insert head) (just-one-space)
5946 (setq pos (point))
5947 (end-of-line 1)
5948 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5949 (run-hooks 'org-insert-heading-hook)))))
5951 (defun org-insert-heading-after-current ()
5952 "Insert a new heading with same level as current, after current subtree."
5953 (interactive)
5954 (org-back-to-heading)
5955 (org-insert-heading)
5956 (org-move-subtree-down)
5957 (end-of-line 1))
5959 (defun org-insert-todo-heading (arg)
5960 "Insert a new heading with the same level and TODO state as current heading.
5961 If the heading has no TODO state, or if the state is DONE, use the first
5962 state (TODO by default). Also with prefix arg, force first state."
5963 (interactive "P")
5964 (when (not (org-insert-item 'checkbox))
5965 (org-insert-heading)
5966 (save-excursion
5967 (org-back-to-heading)
5968 (outline-previous-heading)
5969 (looking-at org-todo-line-regexp))
5970 (if (or arg
5971 (not (match-beginning 2))
5972 (member (match-string 2) org-done-keywords))
5973 (insert (car org-todo-keywords-1) " ")
5974 (insert (match-string 2) " "))))
5976 (defun org-insert-subheading (arg)
5977 "Insert a new subheading and demote it.
5978 Works for outline headings and for plain lists alike."
5979 (interactive "P")
5980 (org-insert-heading arg)
5981 (cond
5982 ((org-on-heading-p) (org-do-demote))
5983 ((org-at-item-p) (org-indent-item 1))))
5985 (defun org-insert-todo-subheading (arg)
5986 "Insert a new subheading with TODO keyword or checkbox and demote it.
5987 Works for outline headings and for plain lists alike."
5988 (interactive "P")
5989 (org-insert-todo-heading arg)
5990 (cond
5991 ((org-on-heading-p) (org-do-demote))
5992 ((org-at-item-p) (org-indent-item 1))))
5994 ;;; Promotion and Demotion
5996 (defun org-promote-subtree ()
5997 "Promote the entire subtree.
5998 See also `org-promote'."
5999 (interactive)
6000 (save-excursion
6001 (org-map-tree 'org-promote))
6002 (org-fix-position-after-promote))
6004 (defun org-demote-subtree ()
6005 "Demote the entire subtree. See `org-demote'.
6006 See also `org-promote'."
6007 (interactive)
6008 (save-excursion
6009 (org-map-tree 'org-demote))
6010 (org-fix-position-after-promote))
6013 (defun org-do-promote ()
6014 "Promote the current heading higher up the tree.
6015 If the region is active in `transient-mark-mode', promote all headings
6016 in the region."
6017 (interactive)
6018 (save-excursion
6019 (if (org-region-active-p)
6020 (org-map-region 'org-promote (region-beginning) (region-end))
6021 (org-promote)))
6022 (org-fix-position-after-promote))
6024 (defun org-do-demote ()
6025 "Demote the current heading lower down the tree.
6026 If the region is active in `transient-mark-mode', demote all headings
6027 in the region."
6028 (interactive)
6029 (save-excursion
6030 (if (org-region-active-p)
6031 (org-map-region 'org-demote (region-beginning) (region-end))
6032 (org-demote)))
6033 (org-fix-position-after-promote))
6035 (defun org-fix-position-after-promote ()
6036 "Make sure that after pro/demotion cursor position is right."
6037 (let ((pos (point)))
6038 (when (save-excursion
6039 (beginning-of-line 1)
6040 (looking-at org-todo-line-regexp)
6041 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6042 (cond ((eobp) (insert " "))
6043 ((eolp) (insert " "))
6044 ((equal (char-after) ?\ ) (forward-char 1))))))
6046 (defun org-reduced-level (l)
6047 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6049 (defun org-get-legal-level (level &optional change)
6050 "Rectify a level change under the influence of `org-odd-levels-only'
6051 LEVEL is a current level, CHANGE is by how much the level should be
6052 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6053 even level numbers will become the next higher odd number."
6054 (if org-odd-levels-only
6055 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6056 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6057 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6058 (max 1 (+ level change))))
6060 (defun org-promote ()
6061 "Promote the current heading higher up the tree.
6062 If the region is active in `transient-mark-mode', promote all headings
6063 in the region."
6064 (org-back-to-heading t)
6065 (let* ((level (save-match-data (funcall outline-level)))
6066 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
6067 (diff (abs (- level (length up-head) -1))))
6068 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6069 (replace-match up-head nil t)
6070 ;; Fixup tag positioning
6071 (and org-auto-align-tags (org-set-tags nil t))
6072 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
6074 (defun org-demote ()
6075 "Demote the current heading lower down the tree.
6076 If the region is active in `transient-mark-mode', demote all headings
6077 in the region."
6078 (org-back-to-heading t)
6079 (let* ((level (save-match-data (funcall outline-level)))
6080 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
6081 (diff (abs (- level (length down-head) -1))))
6082 (replace-match down-head nil t)
6083 ;; Fixup tag positioning
6084 (and org-auto-align-tags (org-set-tags nil t))
6085 (if org-adapt-indentation (org-fixup-indentation diff))))
6087 (defun org-map-tree (fun)
6088 "Call FUN for every heading underneath the current one."
6089 (org-back-to-heading)
6090 (let ((level (funcall outline-level)))
6091 (save-excursion
6092 (funcall fun)
6093 (while (and (progn
6094 (outline-next-heading)
6095 (> (funcall outline-level) level))
6096 (not (eobp)))
6097 (funcall fun)))))
6099 (defun org-map-region (fun beg end)
6100 "Call FUN for every heading between BEG and END."
6101 (let ((org-ignore-region t))
6102 (save-excursion
6103 (setq end (copy-marker end))
6104 (goto-char beg)
6105 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6106 (< (point) end))
6107 (funcall fun))
6108 (while (and (progn
6109 (outline-next-heading)
6110 (< (point) end))
6111 (not (eobp)))
6112 (funcall fun)))))
6114 (defun org-fixup-indentation (diff)
6115 "Change the indentation in the current entry by DIFF
6116 However, if any line in the current entry has no indentation, or if it
6117 would end up with no indentation after the change, nothing at all is done."
6118 (save-excursion
6119 (let ((end (save-excursion (outline-next-heading)
6120 (point-marker)))
6121 (prohibit (if (> diff 0)
6122 "^\\S-"
6123 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6124 col)
6125 (unless (save-excursion (end-of-line 1)
6126 (re-search-forward prohibit end t))
6127 (while (and (< (point) end)
6128 (re-search-forward "^[ \t]+" end t))
6129 (goto-char (match-end 0))
6130 (setq col (current-column))
6131 (if (< diff 0) (replace-match ""))
6132 (indent-to (+ diff col))))
6133 (move-marker end nil))))
6135 (defun org-convert-to-odd-levels ()
6136 "Convert an org-mode file with all levels allowed to one with odd levels.
6137 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6138 level 5 etc."
6139 (interactive)
6140 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6141 (let ((org-odd-levels-only nil) n)
6142 (save-excursion
6143 (goto-char (point-min))
6144 (while (re-search-forward "^\\*\\*+ " nil t)
6145 (setq n (- (length (match-string 0)) 2))
6146 (while (>= (setq n (1- n)) 0)
6147 (org-demote))
6148 (end-of-line 1))))))
6151 (defun org-convert-to-oddeven-levels ()
6152 "Convert an org-mode file with only odd levels to one with odd and even levels.
6153 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6154 section with an even level, conversion would destroy the structure of the file. An error
6155 is signaled in this case."
6156 (interactive)
6157 (goto-char (point-min))
6158 ;; First check if there are no even levels
6159 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6160 (org-show-context t)
6161 (error "Not all levels are odd in this file. Conversion not possible."))
6162 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6163 (let ((org-odd-levels-only nil) n)
6164 (save-excursion
6165 (goto-char (point-min))
6166 (while (re-search-forward "^\\*\\*+ " nil t)
6167 (setq n (/ (1- (length (match-string 0))) 2))
6168 (while (>= (setq n (1- n)) 0)
6169 (org-promote))
6170 (end-of-line 1))))))
6172 (defun org-tr-level (n)
6173 "Make N odd if required."
6174 (if org-odd-levels-only (1+ (/ n 2)) n))
6176 ;;; Vertical tree motion, cutting and pasting of subtrees
6178 (defun org-move-subtree-up (&optional arg)
6179 "Move the current subtree up past ARG headlines of the same level."
6180 (interactive "p")
6181 (org-move-subtree-down (- (prefix-numeric-value arg))))
6183 (defun org-move-subtree-down (&optional arg)
6184 "Move the current subtree down past ARG headlines of the same level."
6185 (interactive "p")
6186 (setq arg (prefix-numeric-value arg))
6187 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6188 'outline-get-last-sibling))
6189 (ins-point (make-marker))
6190 (cnt (abs arg))
6191 beg end txt folded)
6192 ;; Select the tree
6193 (org-back-to-heading)
6194 (setq beg (point))
6195 (save-match-data
6196 (save-excursion (outline-end-of-heading)
6197 (setq folded (org-invisible-p)))
6198 (outline-end-of-subtree))
6199 (outline-next-heading)
6200 (setq end (point))
6201 ;; Find insertion point, with error handling
6202 (goto-char beg)
6203 (while (> cnt 0)
6204 (or (and (funcall movfunc) (looking-at outline-regexp))
6205 (progn (goto-char beg)
6206 (error "Cannot move past superior level or buffer limit")))
6207 (setq cnt (1- cnt)))
6208 (if (> arg 0)
6209 ;; Moving forward - still need to move over subtree
6210 (progn (outline-end-of-subtree)
6211 (outline-next-heading)
6212 (if (not (or (looking-at (concat "^" outline-regexp))
6213 (bolp)))
6214 (newline))))
6215 (move-marker ins-point (point))
6216 (setq txt (buffer-substring beg end))
6217 (delete-region beg end)
6218 (insert txt)
6219 (or (bolp) (insert "\n"))
6220 (goto-char ins-point)
6221 (if folded (hide-subtree))
6222 (move-marker ins-point nil)))
6224 (defvar org-subtree-clip ""
6225 "Clipboard for cut and paste of subtrees.
6226 This is actually only a copy of the kill, because we use the normal kill
6227 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6229 (defvar org-subtree-clip-folded nil
6230 "Was the last copied subtree folded?
6231 This is used to fold the tree back after pasting.")
6233 (defun org-cut-subtree (&optional n)
6234 "Cut the current subtree into the clipboard.
6235 With prefix arg N, cut this many sequential subtrees.
6236 This is a short-hand for marking the subtree and then cutting it."
6237 (interactive "p")
6238 (org-copy-subtree n 'cut))
6240 (defun org-copy-subtree (&optional n cut)
6241 "Cut the current subtree into the clipboard.
6242 With prefix arg N, cut this many sequential subtrees.
6243 This is a short-hand for marking the subtree and then copying it.
6244 If CUT is non-nil, actually cut the subtree."
6245 (interactive "p")
6246 (let (beg end folded)
6247 (if (interactive-p)
6248 (org-back-to-heading nil) ; take what looks like a subtree
6249 (org-back-to-heading t)) ; take what is really there
6250 (setq beg (point))
6251 (save-match-data
6252 (save-excursion (outline-end-of-heading)
6253 (setq folded (org-invisible-p)))
6254 (condition-case nil
6255 (outline-forward-same-level (1- n))
6256 (error nil))
6257 (org-end-of-subtree t t))
6258 (setq end (point))
6259 (goto-char beg)
6260 (when (> end beg)
6261 (setq org-subtree-clip-folded folded)
6262 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6263 (setq org-subtree-clip (current-kill 0))
6264 (message "%s: Subtree(s) with %d characters"
6265 (if cut "Cut" "Copied")
6266 (length org-subtree-clip)))))
6268 (defun org-paste-subtree (&optional level tree)
6269 "Paste the clipboard as a subtree, with modification of headline level.
6270 The entire subtree is promoted or demoted in order to match a new headline
6271 level. By default, the new level is derived from the visible headings
6272 before and after the insertion point, and taken to be the inferior headline
6273 level of the two. So if the previous visible heading is level 3 and the
6274 next is level 4 (or vice versa), level 4 will be used for insertion.
6275 This makes sure that the subtree remains an independent subtree and does
6276 not swallow low level entries.
6278 You can also force a different level, either by using a numeric prefix
6279 argument, or by inserting the heading marker by hand. For example, if the
6280 cursor is after \"*****\", then the tree will be shifted to level 5.
6282 If you want to insert the tree as is, just use \\[yank].
6284 If optional TREE is given, use this text instead of the kill ring."
6285 (interactive "P")
6286 (unless (org-kill-is-subtree-p tree)
6287 (error
6288 (substitute-command-keys
6289 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6290 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6291 (^re (concat "^\\(" outline-regexp "\\)"))
6292 (re (concat "\\(" outline-regexp "\\)"))
6293 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6295 (old-level (if (string-match ^re txt)
6296 (- (match-end 0) (match-beginning 0) 1)
6297 -1))
6298 (force-level (cond (level (prefix-numeric-value level))
6299 ((string-match
6300 ^re_ (buffer-substring (point-at-bol) (point)))
6301 (- (match-end 1) (match-beginning 1)))
6302 (t nil)))
6303 (previous-level (save-excursion
6304 (condition-case nil
6305 (progn
6306 (outline-previous-visible-heading 1)
6307 (if (looking-at re)
6308 (- (match-end 0) (match-beginning 0) 1)
6310 (error 1))))
6311 (next-level (save-excursion
6312 (condition-case nil
6313 (progn
6314 (or (looking-at outline-regexp)
6315 (outline-next-visible-heading 1))
6316 (if (looking-at re)
6317 (- (match-end 0) (match-beginning 0) 1)
6319 (error 1))))
6320 (new-level (or force-level (max previous-level next-level)))
6321 (shift (if (or (= old-level -1)
6322 (= new-level -1)
6323 (= old-level new-level))
6325 (- new-level old-level)))
6326 (delta (if (> shift 0) -1 1))
6327 (func (if (> shift 0) 'org-demote 'org-promote))
6328 (org-odd-levels-only nil)
6329 beg end)
6330 ;; Remove the forced level indicator
6331 (if force-level
6332 (delete-region (point-at-bol) (point)))
6333 ;; Paste
6334 (beginning-of-line 1)
6335 (setq beg (point))
6336 (insert txt)
6337 (unless (string-match "\n\\'" txt) (insert "\n"))
6338 (setq end (point))
6339 (goto-char beg)
6340 ;; Shift if necessary
6341 (unless (= shift 0)
6342 (save-restriction
6343 (narrow-to-region beg end)
6344 (while (not (= shift 0))
6345 (org-map-region func (point-min) (point-max))
6346 (setq shift (+ delta shift)))
6347 (goto-char (point-min))))
6348 (when (interactive-p)
6349 (message "Clipboard pasted as level %d subtree" new-level))
6350 (if (and kill-ring
6351 (eq org-subtree-clip (current-kill 0))
6352 org-subtree-clip-folded)
6353 ;; The tree was folded before it was killed/copied
6354 (hide-subtree))))
6356 (defun org-kill-is-subtree-p (&optional txt)
6357 "Check if the current kill is an outline subtree, or a set of trees.
6358 Returns nil if kill does not start with a headline, or if the first
6359 headline level is not the largest headline level in the tree.
6360 So this will actually accept several entries of equal levels as well,
6361 which is OK for `org-paste-subtree'.
6362 If optional TXT is given, check this string instead of the current kill."
6363 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6364 (start-level (and kill
6365 (string-match (concat "\\`" org-outline-regexp) kill)
6366 (- (match-end 0) (match-beginning 0) 1)))
6367 (re (concat "^" org-outline-regexp))
6368 (start 1))
6369 (if (not start-level)
6370 (progn
6371 nil) ;; does not even start with a heading
6372 (catch 'exit
6373 (while (setq start (string-match re kill (1+ start)))
6374 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6375 (throw 'exit nil)))
6376 t))))
6378 (defun org-narrow-to-subtree ()
6379 "Narrow buffer to the current subtree."
6380 (interactive)
6381 (save-excursion
6382 (narrow-to-region
6383 (progn (org-back-to-heading) (point))
6384 (progn (org-end-of-subtree t t) (point)))))
6387 ;;; Outline Sorting
6389 (defun org-sort (with-case)
6390 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6391 Optional argument WITH-CASE means sort case-sensitively."
6392 (interactive "P")
6393 (if (org-at-table-p)
6394 (org-call-with-arg 'org-table-sort-lines with-case)
6395 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6397 (defvar org-priority-regexp) ; defined later in the file
6399 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6400 "Sort entries on a certain level of an outline tree.
6401 If there is an active region, the entries in the region are sorted.
6402 Else, if the cursor is before the first entry, sort the top-level items.
6403 Else, the children of the entry at point are sorted.
6405 Sorting can be alphabetically, numerically, and by date/time as given by
6406 the first time stamp in the entry. The command prompts for the sorting
6407 type unless it has been given to the function through the SORTING-TYPE
6408 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6409 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6410 called with point at the beginning of the record. It must return either
6411 a string or a number that should serve as the sorting key for that record.
6413 Comparing entries ignores case by default. However, with an optional argument
6414 WITH-CASE, the sorting considers case as well."
6415 (interactive "P")
6416 (let ((case-func (if with-case 'identity 'downcase))
6417 start beg end stars re re2
6418 txt what tmp plain-list-p)
6419 ;; Find beginning and end of region to sort
6420 (cond
6421 ((org-region-active-p)
6422 ;; we will sort the region
6423 (setq end (region-end)
6424 what "region")
6425 (goto-char (region-beginning))
6426 (if (not (org-on-heading-p)) (outline-next-heading))
6427 (setq start (point)))
6428 ((org-at-item-p)
6429 ;; we will sort this plain list
6430 (org-beginning-of-item-list) (setq start (point))
6431 (org-end-of-item-list) (setq end (point))
6432 (goto-char start)
6433 (setq plain-list-p t
6434 what "plain list"))
6435 ((or (org-on-heading-p)
6436 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6437 ;; we will sort the children of the current headline
6438 (org-back-to-heading)
6439 (setq start (point) end (org-end-of-subtree) what "children")
6440 (goto-char start)
6441 (show-subtree)
6442 (outline-next-heading))
6444 ;; we will sort the top-level entries in this file
6445 (goto-char (point-min))
6446 (or (org-on-heading-p) (outline-next-heading))
6447 (setq start (point) end (point-max) what "top-level")
6448 (goto-char start)
6449 (show-all)))
6451 (setq beg (point))
6452 (if (>= beg end) (error "Nothing to sort"))
6454 (unless plain-list-p
6455 (looking-at "\\(\\*+\\)")
6456 (setq stars (match-string 1)
6457 re (concat "^" (regexp-quote stars) " +")
6458 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6459 txt (buffer-substring beg end))
6460 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6461 (if (and (not (equal stars "*")) (string-match re2 txt))
6462 (error "Region to sort contains a level above the first entry")))
6464 (unless sorting-type
6465 (message
6466 (if plain-list-p
6467 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6468 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
6469 what)
6470 (setq sorting-type (read-char-exclusive))
6472 (and (= (downcase sorting-type) ?f)
6473 (setq getkey-func
6474 (completing-read "Sort using function: "
6475 obarray 'fboundp t nil nil))
6476 (setq getkey-func (intern getkey-func)))
6478 (and (= (downcase sorting-type) ?r)
6479 (setq property
6480 (completing-read "Property: "
6481 (mapcar 'list (org-buffer-property-keys t))
6482 nil t))))
6484 (message "Sorting entries...")
6486 (save-restriction
6487 (narrow-to-region start end)
6489 (let ((dcst (downcase sorting-type))
6490 (now (current-time)))
6491 (sort-subr
6492 (/= dcst sorting-type)
6493 ;; This function moves to the beginning character of the "record" to
6494 ;; be sorted.
6495 (if plain-list-p
6496 (lambda nil
6497 (if (org-at-item-p) t (goto-char (point-max))))
6498 (lambda nil
6499 (if (re-search-forward re nil t)
6500 (goto-char (match-beginning 0))
6501 (goto-char (point-max)))))
6502 ;; This function moves to the last character of the "record" being
6503 ;; sorted.
6504 (if plain-list-p
6505 'org-end-of-item
6506 (lambda nil
6507 (save-match-data
6508 (condition-case nil
6509 (outline-forward-same-level 1)
6510 (error
6511 (goto-char (point-max)))))))
6513 ;; This function returns the value that gets sorted against.
6514 (if plain-list-p
6515 (lambda nil
6516 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6517 (cond
6518 ((= dcst ?n)
6519 (string-to-number (buffer-substring (match-end 0)
6520 (point-at-eol))))
6521 ((= dcst ?a)
6522 (buffer-substring (match-end 0) (point-at-eol)))
6523 ((= dcst ?t)
6524 (if (re-search-forward org-ts-regexp
6525 (point-at-eol) t)
6526 (org-time-string-to-time (match-string 0))
6527 now))
6528 ((= dcst ?f)
6529 (if getkey-func
6530 (progn
6531 (setq tmp (funcall getkey-func))
6532 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6533 tmp)
6534 (error "Invalid key function `%s'" getkey-func)))
6535 (t (error "Invalid sorting type `%c'" sorting-type)))))
6536 (lambda nil
6537 (cond
6538 ((= dcst ?n)
6539 (if (looking-at outline-regexp)
6540 (string-to-number (buffer-substring (match-end 0)
6541 (point-at-eol)))
6542 nil))
6543 ((= dcst ?a)
6544 (funcall case-func (buffer-substring (point-at-bol)
6545 (point-at-eol))))
6546 ((= dcst ?t)
6547 (if (re-search-forward org-ts-regexp
6548 (save-excursion
6549 (forward-line 2)
6550 (point)) t)
6551 (org-time-string-to-time (match-string 0))
6552 now))
6553 ((= dcst ?p)
6554 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6555 (string-to-char (match-string 2))
6556 org-default-priority))
6557 ((= dcst ?r)
6558 (or (org-entry-get nil property) ""))
6559 ((= dcst ?f)
6560 (if getkey-func
6561 (progn
6562 (setq tmp (funcall getkey-func))
6563 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6564 tmp)
6565 (error "Invalid key function `%s'" getkey-func)))
6566 (t (error "Invalid sorting type `%c'" sorting-type)))))
6568 (cond
6569 ((= dcst ?a) 'string<)
6570 ((= dcst ?t) 'time-less-p)
6571 (t nil)))))
6572 (message "Sorting entries...done")))
6574 (defun org-do-sort (table what &optional with-case sorting-type)
6575 "Sort TABLE of WHAT according to SORTING-TYPE.
6576 The user will be prompted for the SORTING-TYPE if the call to this
6577 function does not specify it. WHAT is only for the prompt, to indicate
6578 what is being sorted. The sorting key will be extracted from
6579 the car of the elements of the table.
6580 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6581 (unless sorting-type
6582 (message
6583 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6584 what)
6585 (setq sorting-type (read-char-exclusive)))
6586 (let ((dcst (downcase sorting-type))
6587 extractfun comparefun)
6588 ;; Define the appropriate functions
6589 (cond
6590 ((= dcst ?n)
6591 (setq extractfun 'string-to-number
6592 comparefun (if (= dcst sorting-type) '< '>)))
6593 ((= dcst ?a)
6594 (setq extractfun (if with-case 'identity 'downcase)
6595 comparefun (if (= dcst sorting-type)
6596 'string<
6597 (lambda (a b) (and (not (string< a b))
6598 (not (string= a b)))))))
6599 ((= dcst ?t)
6600 (setq extractfun
6601 (lambda (x)
6602 (if (string-match org-ts-regexp x)
6603 (time-to-seconds
6604 (org-time-string-to-time (match-string 0 x)))
6606 comparefun (if (= dcst sorting-type) '< '>)))
6607 (t (error "Invalid sorting type `%c'" sorting-type)))
6609 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6610 table)
6611 (lambda (a b) (funcall comparefun (car a) (car b))))))
6613 ;;;; Plain list items, including checkboxes
6615 ;;; Plain list items
6617 (defun org-at-item-p ()
6618 "Is point in a line starting a hand-formatted item?"
6619 (let ((llt org-plain-list-ordered-item-terminator))
6620 (save-excursion
6621 (goto-char (point-at-bol))
6622 (looking-at
6623 (cond
6624 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6625 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6626 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6627 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
6629 (defun org-in-item-p ()
6630 "It the cursor inside a plain list item.
6631 Does not have to be the first line."
6632 (save-excursion
6633 (condition-case nil
6634 (progn
6635 (org-beginning-of-item)
6636 (org-at-item-p)
6638 (error nil))))
6640 (defun org-insert-item (&optional checkbox)
6641 "Insert a new item at the current level.
6642 Return t when things worked, nil when we are not in an item."
6643 (when (save-excursion
6644 (condition-case nil
6645 (progn
6646 (org-beginning-of-item)
6647 (org-at-item-p)
6648 (if (org-invisible-p) (error "Invisible item"))
6650 (error nil)))
6651 (let* ((bul (match-string 0))
6652 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
6653 (match-end 0)))
6654 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
6655 pos)
6656 (cond
6657 ((and (org-at-item-p) (<= (point) eow))
6658 ;; before the bullet
6659 (beginning-of-line 1)
6660 (open-line (if blank 2 1)))
6661 ((<= (point) eow)
6662 (beginning-of-line 1))
6663 (t (newline (if blank 2 1))))
6664 (insert bul (if checkbox "[ ]" ""))
6665 (just-one-space)
6666 (setq pos (point))
6667 (end-of-line 1)
6668 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
6669 (org-maybe-renumber-ordered-list)
6670 (and checkbox (org-update-checkbox-count-maybe))
6673 ;;; Checkboxes
6675 (defun org-at-item-checkbox-p ()
6676 "Is point at a line starting a plain-list item with a checklet?"
6677 (and (org-at-item-p)
6678 (save-excursion
6679 (goto-char (match-end 0))
6680 (skip-chars-forward " \t")
6681 (looking-at "\\[[- X]\\]"))))
6683 (defun org-toggle-checkbox (&optional arg)
6684 "Toggle the checkbox in the current line."
6685 (interactive "P")
6686 (catch 'exit
6687 (let (beg end status (firstnew 'unknown))
6688 (cond
6689 ((org-region-active-p)
6690 (setq beg (region-beginning) end (region-end)))
6691 ((org-on-heading-p)
6692 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
6693 ((org-at-item-checkbox-p)
6694 (let ((pos (point)))
6695 (replace-match
6696 (cond (arg "[-]")
6697 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
6698 (t "[ ]"))
6699 t t)
6700 (goto-char pos))
6701 (throw 'exit t))
6702 (t (error "Not at a checkbox or heading, and no active region")))
6703 (save-excursion
6704 (goto-char beg)
6705 (while (< (point) end)
6706 (when (org-at-item-checkbox-p)
6707 (setq status (equal (match-string 0) "[X]"))
6708 (when (eq firstnew 'unknown)
6709 (setq firstnew (not status)))
6710 (replace-match
6711 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
6712 (beginning-of-line 2)))))
6713 (org-update-checkbox-count-maybe))
6715 (defun org-update-checkbox-count-maybe ()
6716 "Update checkbox statistics unless turned off by user."
6717 (when org-provide-checkbox-statistics
6718 (org-update-checkbox-count)))
6720 (defun org-update-checkbox-count (&optional all)
6721 "Update the checkbox statistics in the current section.
6722 This will find all statistic cookies like [57%] and [6/12] and update them
6723 with the current numbers. With optional prefix argument ALL, do this for
6724 the whole buffer."
6725 (interactive "P")
6726 (save-excursion
6727 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
6728 (beg (condition-case nil
6729 (progn (outline-back-to-heading) (point))
6730 (error (point-min))))
6731 (end (move-marker (make-marker)
6732 (progn (outline-next-heading) (point))))
6733 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
6734 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
6735 b1 e1 f1 c-on c-off lim (cstat 0))
6736 (when all
6737 (goto-char (point-min))
6738 (outline-next-heading)
6739 (setq beg (point) end (point-max)))
6740 (goto-char beg)
6741 (while (re-search-forward re end t)
6742 (setq cstat (1+ cstat)
6743 b1 (match-beginning 0)
6744 e1 (match-end 0)
6745 f1 (match-beginning 1)
6746 lim (cond
6747 ((org-on-heading-p) (outline-next-heading) (point))
6748 ((org-at-item-p) (org-end-of-item) (point))
6749 (t nil))
6750 c-on 0 c-off 0)
6751 (goto-char e1)
6752 (when lim
6753 (while (re-search-forward re-box lim t)
6754 (if (member (match-string 2) '("[ ]" "[-]"))
6755 (setq c-off (1+ c-off))
6756 (setq c-on (1+ c-on))))
6757 ; (delete-region b1 e1)
6758 (goto-char b1)
6759 (insert (if f1
6760 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
6761 (format "[%d/%d]" c-on (+ c-on c-off))))
6762 (and (looking-at "\\[.*?\\]")
6763 (replace-match ""))))
6764 (when (interactive-p)
6765 (message "Checkbox satistics updated %s (%d places)"
6766 (if all "in entire file" "in current outline entry") cstat)))))
6768 (defun org-get-checkbox-statistics-face ()
6769 "Select the face for checkbox statistics.
6770 The face will be `org-done' when all relevant boxes are checked. Otherwise
6771 it will be `org-todo'."
6772 (if (match-end 1)
6773 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
6774 (if (and (> (match-end 2) (match-beginning 2))
6775 (equal (match-string 2) (match-string 3)))
6776 'org-done
6777 'org-todo)))
6779 (defun org-get-indentation (&optional line)
6780 "Get the indentation of the current line, interpreting tabs.
6781 When LINE is given, assume it represents a line and compute its indentation."
6782 (if line
6783 (if (string-match "^ *" (org-remove-tabs line))
6784 (match-end 0))
6785 (save-excursion
6786 (beginning-of-line 1)
6787 (skip-chars-forward " \t")
6788 (current-column))))
6790 (defun org-remove-tabs (s &optional width)
6791 "Replace tabulators in S with spaces.
6792 Assumes that s is a single line, starting in column 0."
6793 (setq width (or width tab-width))
6794 (while (string-match "\t" s)
6795 (setq s (replace-match
6796 (make-string
6797 (- (* width (/ (+ (match-beginning 0) width) width))
6798 (match-beginning 0)) ?\ )
6799 t t s)))
6802 (defun org-fix-indentation (line ind)
6803 "Fix indentation in LINE.
6804 IND is a cons cell with target and minimum indentation.
6805 If the current indenation in LINE is smaller than the minimum,
6806 leave it alone. If it is larger than ind, set it to the target."
6807 (let* ((l (org-remove-tabs line))
6808 (i (org-get-indentation l))
6809 (i1 (car ind)) (i2 (cdr ind)))
6810 (if (>= i i2) (setq l (substring line i2)))
6811 (if (> i1 0)
6812 (concat (make-string i1 ?\ ) l)
6813 l)))
6815 (defcustom org-empty-line-terminates-plain-lists nil
6816 "Non-nil means, an empty line ends all plain list levels.
6817 When nil, empty lines are part of the preceeding item."
6818 :group 'org-plain-lists
6819 :type 'boolean)
6821 (defun org-beginning-of-item ()
6822 "Go to the beginning of the current hand-formatted item.
6823 If the cursor is not in an item, throw an error."
6824 (interactive)
6825 (let ((pos (point))
6826 (limit (save-excursion
6827 (condition-case nil
6828 (progn
6829 (org-back-to-heading)
6830 (beginning-of-line 2) (point))
6831 (error (point-min)))))
6832 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
6833 ind ind1)
6834 (if (org-at-item-p)
6835 (beginning-of-line 1)
6836 (beginning-of-line 1)
6837 (skip-chars-forward " \t")
6838 (setq ind (current-column))
6839 (if (catch 'exit
6840 (while t
6841 (beginning-of-line 0)
6842 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
6844 (if (looking-at "[ \t]*$")
6845 (setq ind1 ind-empty)
6846 (skip-chars-forward " \t")
6847 (setq ind1 (current-column)))
6848 (if (< ind1 ind)
6849 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
6851 (goto-char pos)
6852 (error "Not in an item")))))
6854 (defun org-end-of-item ()
6855 "Go to the end of the current hand-formatted item.
6856 If the cursor is not in an item, throw an error."
6857 (interactive)
6858 (let* ((pos (point))
6859 ind1
6860 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
6861 (limit (save-excursion (outline-next-heading) (point)))
6862 (ind (save-excursion
6863 (org-beginning-of-item)
6864 (skip-chars-forward " \t")
6865 (current-column)))
6866 (end (catch 'exit
6867 (while t
6868 (beginning-of-line 2)
6869 (if (eobp) (throw 'exit (point)))
6870 (if (>= (point) limit) (throw 'exit (point-at-bol)))
6871 (if (looking-at "[ \t]*$")
6872 (setq ind1 ind-empty)
6873 (skip-chars-forward " \t")
6874 (setq ind1 (current-column)))
6875 (if (<= ind1 ind)
6876 (throw 'exit (point-at-bol)))))))
6877 (if end
6878 (goto-char end)
6879 (goto-char pos)
6880 (error "Not in an item"))))
6882 (defun org-next-item ()
6883 "Move to the beginning of the next item in the current plain list.
6884 Error if not at a plain list, or if this is the last item in the list."
6885 (interactive)
6886 (let (ind ind1 (pos (point)))
6887 (org-beginning-of-item)
6888 (setq ind (org-get-indentation))
6889 (org-end-of-item)
6890 (setq ind1 (org-get-indentation))
6891 (unless (and (org-at-item-p) (= ind ind1))
6892 (goto-char pos)
6893 (error "On last item"))))
6895 (defun org-previous-item ()
6896 "Move to the beginning of the previous item in the current plain list.
6897 Error if not at a plain list, or if this is the first item in the list."
6898 (interactive)
6899 (let (beg ind ind1 (pos (point)))
6900 (org-beginning-of-item)
6901 (setq beg (point))
6902 (setq ind (org-get-indentation))
6903 (goto-char beg)
6904 (catch 'exit
6905 (while t
6906 (beginning-of-line 0)
6907 (if (looking-at "[ \t]*$")
6909 (if (<= (setq ind1 (org-get-indentation)) ind)
6910 (throw 'exit t)))))
6911 (condition-case nil
6912 (if (or (not (org-at-item-p))
6913 (< ind1 (1- ind)))
6914 (error "")
6915 (org-beginning-of-item))
6916 (error (goto-char pos)
6917 (error "On first item")))))
6919 (defun org-move-item-down ()
6920 "Move the plain list item at point down, i.e. swap with following item.
6921 Subitems (items with larger indentation) are considered part of the item,
6922 so this really moves item trees."
6923 (interactive)
6924 (let (beg end ind ind1 (pos (point)) txt)
6925 (org-beginning-of-item)
6926 (setq beg (point))
6927 (setq ind (org-get-indentation))
6928 (org-end-of-item)
6929 (setq end (point))
6930 (setq ind1 (org-get-indentation))
6931 (if (and (org-at-item-p) (= ind ind1))
6932 (progn
6933 (org-end-of-item)
6934 (setq txt (buffer-substring beg end))
6935 (save-excursion
6936 (delete-region beg end))
6937 (setq pos (point))
6938 (insert txt)
6939 (goto-char pos)
6940 (org-maybe-renumber-ordered-list))
6941 (goto-char pos)
6942 (error "Cannot move this item further down"))))
6944 (defun org-move-item-up (arg)
6945 "Move the plain list item at point up, i.e. swap with previous item.
6946 Subitems (items with larger indentation) are considered part of the item,
6947 so this really moves item trees."
6948 (interactive "p")
6949 (let (beg end ind ind1 (pos (point)) txt)
6950 (org-beginning-of-item)
6951 (setq beg (point))
6952 (setq ind (org-get-indentation))
6953 (org-end-of-item)
6954 (setq end (point))
6955 (goto-char beg)
6956 (catch 'exit
6957 (while t
6958 (beginning-of-line 0)
6959 (if (looking-at "[ \t]*$")
6960 (if org-empty-line-terminates-plain-lists
6961 (progn
6962 (goto-char pos)
6963 (error "Cannot move this item further up"))
6964 nil)
6965 (if (<= (setq ind1 (org-get-indentation)) ind)
6966 (throw 'exit t)))))
6967 (condition-case nil
6968 (org-beginning-of-item)
6969 (error (goto-char beg)
6970 (error "Cannot move this item further up")))
6971 (setq ind1 (org-get-indentation))
6972 (if (and (org-at-item-p) (= ind ind1))
6973 (progn
6974 (setq txt (buffer-substring beg end))
6975 (save-excursion
6976 (delete-region beg end))
6977 (setq pos (point))
6978 (insert txt)
6979 (goto-char pos)
6980 (org-maybe-renumber-ordered-list))
6981 (goto-char pos)
6982 (error "Cannot move this item further up"))))
6984 (defun org-maybe-renumber-ordered-list ()
6985 "Renumber the ordered list at point if setup allows it.
6986 This tests the user option `org-auto-renumber-ordered-lists' before
6987 doing the renumbering."
6988 (interactive)
6989 (when (and org-auto-renumber-ordered-lists
6990 (org-at-item-p))
6991 (if (match-beginning 3)
6992 (org-renumber-ordered-list 1)
6993 (org-fix-bullet-type))))
6995 (defun org-maybe-renumber-ordered-list-safe ()
6996 (condition-case nil
6997 (save-excursion
6998 (org-maybe-renumber-ordered-list))
6999 (error nil)))
7001 (defun org-cycle-list-bullet (&optional which)
7002 "Cycle through the different itemize/enumerate bullets.
7003 This cycle the entire list level through the sequence:
7005 `-' -> `+' -> `*' -> `1.' -> `1)'
7007 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7008 0 meand `-', 1 means `+' etc."
7009 (interactive "P")
7010 (org-preserve-lc
7011 (org-beginning-of-item-list)
7012 (org-at-item-p)
7013 (beginning-of-line 1)
7014 (let ((current (match-string 0))
7015 (prevp (eq which 'previous))
7016 new)
7017 (setq new (cond
7018 ((and (numberp which)
7019 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7020 ((string-match "-" current) (if prevp "1)" "+"))
7021 ((string-match "\\+" current)
7022 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7023 ((string-match "\\*" current) (if prevp "+" "1."))
7024 ((string-match "\\." current) (if prevp "*" "1)"))
7025 ((string-match ")" current) (if prevp "1." "-"))
7026 (t (error "This should not happen"))))
7027 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7028 (org-fix-bullet-type)
7029 (org-maybe-renumber-ordered-list))))
7031 (defun org-get-string-indentation (s)
7032 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7033 (let ((n -1) (i 0) (w tab-width) c)
7034 (catch 'exit
7035 (while (< (setq n (1+ n)) (length s))
7036 (setq c (aref s n))
7037 (cond ((= c ?\ ) (setq i (1+ i)))
7038 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7039 (t (throw 'exit t)))))
7042 (defun org-renumber-ordered-list (arg)
7043 "Renumber an ordered plain list.
7044 Cursor needs to be in the first line of an item, the line that starts
7045 with something like \"1.\" or \"2)\"."
7046 (interactive "p")
7047 (unless (and (org-at-item-p)
7048 (match-beginning 3))
7049 (error "This is not an ordered list"))
7050 (let ((line (org-current-line))
7051 (col (current-column))
7052 (ind (org-get-string-indentation
7053 (buffer-substring (point-at-bol) (match-beginning 3))))
7054 ;; (term (substring (match-string 3) -1))
7055 ind1 (n (1- arg))
7056 fmt)
7057 ;; find where this list begins
7058 (org-beginning-of-item-list)
7059 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7060 (setq fmt (concat "%d" (match-string 1)))
7061 (beginning-of-line 0)
7062 ;; walk forward and replace these numbers
7063 (catch 'exit
7064 (while t
7065 (catch 'next
7066 (beginning-of-line 2)
7067 (if (eobp) (throw 'exit nil))
7068 (if (looking-at "[ \t]*$") (throw 'next nil))
7069 (skip-chars-forward " \t") (setq ind1 (current-column))
7070 (if (> ind1 ind) (throw 'next t))
7071 (if (< ind1 ind) (throw 'exit t))
7072 (if (not (org-at-item-p)) (throw 'exit nil))
7073 (delete-region (match-beginning 2) (match-end 2))
7074 (goto-char (match-beginning 2))
7075 (insert (format fmt (setq n (1+ n)))))))
7076 (goto-line line)
7077 (move-to-column col)))
7079 (defun org-fix-bullet-type ()
7080 "Make sure all items in this list have the same bullet as the firsst item."
7081 (interactive)
7082 (unless (org-at-item-p) (error "This is not a list"))
7083 (let ((line (org-current-line))
7084 (col (current-column))
7085 (ind (current-indentation))
7086 ind1 bullet)
7087 ;; find where this list begins
7088 (org-beginning-of-item-list)
7089 (beginning-of-line 1)
7090 ;; find out what the bullet type is
7091 (looking-at "[ \t]*\\(\\S-+\\)")
7092 (setq bullet (match-string 1))
7093 ;; walk forward and replace these numbers
7094 (beginning-of-line 0)
7095 (catch 'exit
7096 (while t
7097 (catch 'next
7098 (beginning-of-line 2)
7099 (if (eobp) (throw 'exit nil))
7100 (if (looking-at "[ \t]*$") (throw 'next nil))
7101 (skip-chars-forward " \t") (setq ind1 (current-column))
7102 (if (> ind1 ind) (throw 'next t))
7103 (if (< ind1 ind) (throw 'exit t))
7104 (if (not (org-at-item-p)) (throw 'exit nil))
7105 (skip-chars-forward " \t")
7106 (looking-at "\\S-+")
7107 (replace-match bullet))))
7108 (goto-line line)
7109 (move-to-column col)
7110 (if (string-match "[0-9]" bullet)
7111 (org-renumber-ordered-list 1))))
7113 (defun org-beginning-of-item-list ()
7114 "Go to the beginning of the current item list.
7115 I.e. to the first item in this list."
7116 (interactive)
7117 (org-beginning-of-item)
7118 (let ((pos (point-at-bol))
7119 (ind (org-get-indentation))
7120 ind1)
7121 ;; find where this list begins
7122 (catch 'exit
7123 (while t
7124 (catch 'next
7125 (beginning-of-line 0)
7126 (if (looking-at "[ \t]*$")
7127 (throw (if (bobp) 'exit 'next) t))
7128 (skip-chars-forward " \t") (setq ind1 (current-column))
7129 (if (or (< ind1 ind)
7130 (and (= ind1 ind)
7131 (not (org-at-item-p)))
7132 (bobp))
7133 (throw 'exit t)
7134 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7135 (goto-char pos)))
7138 (defun org-end-of-item-list ()
7139 "Go to the end of the current item list.
7140 I.e. to the text after the last item."
7141 (interactive)
7142 (org-beginning-of-item)
7143 (let ((pos (point-at-bol))
7144 (ind (org-get-indentation))
7145 ind1)
7146 ;; find where this list begins
7147 (catch 'exit
7148 (while t
7149 (catch 'next
7150 (beginning-of-line 2)
7151 (if (looking-at "[ \t]*$")
7152 (throw (if (eobp) 'exit 'next) t))
7153 (skip-chars-forward " \t") (setq ind1 (current-column))
7154 (if (or (< ind1 ind)
7155 (and (= ind1 ind)
7156 (not (org-at-item-p)))
7157 (eobp))
7158 (progn
7159 (setq pos (point-at-bol))
7160 (throw 'exit t))))))
7161 (goto-char pos)))
7164 (defvar org-last-indent-begin-marker (make-marker))
7165 (defvar org-last-indent-end-marker (make-marker))
7167 (defun org-outdent-item (arg)
7168 "Outdent a local list item."
7169 (interactive "p")
7170 (org-indent-item (- arg)))
7172 (defun org-indent-item (arg)
7173 "Indent a local list item."
7174 (interactive "p")
7175 (unless (org-at-item-p)
7176 (error "Not on an item"))
7177 (save-excursion
7178 (let (beg end ind ind1 tmp delta ind-down ind-up)
7179 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7180 (setq beg org-last-indent-begin-marker
7181 end org-last-indent-end-marker)
7182 (org-beginning-of-item)
7183 (setq beg (move-marker org-last-indent-begin-marker (point)))
7184 (org-end-of-item)
7185 (setq end (move-marker org-last-indent-end-marker (point))))
7186 (goto-char beg)
7187 (setq tmp (org-item-indent-positions)
7188 ind (car tmp)
7189 ind-down (nth 2 tmp)
7190 ind-up (nth 1 tmp)
7191 delta (if (> arg 0)
7192 (if ind-down (- ind-down ind) 2)
7193 (if ind-up (- ind-up ind) -2)))
7194 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7195 (while (< (point) end)
7196 (beginning-of-line 1)
7197 (skip-chars-forward " \t") (setq ind1 (current-column))
7198 (delete-region (point-at-bol) (point))
7199 (or (eolp) (indent-to-column (+ ind1 delta)))
7200 (beginning-of-line 2))))
7201 (org-fix-bullet-type)
7202 (org-maybe-renumber-ordered-list-safe)
7203 (save-excursion
7204 (beginning-of-line 0)
7205 (condition-case nil (org-beginning-of-item) (error nil))
7206 (org-maybe-renumber-ordered-list-safe)))
7208 (defun org-item-indent-positions ()
7209 "Return indentation for plain list items.
7210 This returns a list with three values: The current indentation, the
7211 parent indentation and the indentation a child should habe.
7212 Assumes cursor in item line."
7213 (let* ((bolpos (point-at-bol))
7214 (ind (org-get-indentation))
7215 ind-down ind-up pos)
7216 (save-excursion
7217 (org-beginning-of-item-list)
7218 (skip-chars-backward "\n\r \t")
7219 (when (org-in-item-p)
7220 (org-beginning-of-item)
7221 (setq ind-up (org-get-indentation))))
7222 (setq pos (point))
7223 (save-excursion
7224 (cond
7225 ((and (condition-case nil (progn (org-previous-item) t)
7226 (error nil))
7227 (or (forward-char 1) t)
7228 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7229 (setq ind-down (org-get-indentation)))
7230 ((and (goto-char pos)
7231 (org-at-item-p))
7232 (goto-char (match-end 0))
7233 (skip-chars-forward " \t")
7234 (setq ind-down (current-column)))))
7235 (list ind ind-up ind-down)))
7237 ;;; The orgstruct minor mode
7239 ;; Define a minor mode which can be used in other modes in order to
7240 ;; integrate the org-mode structure editing commands.
7242 ;; This is really a hack, because the org-mode structure commands use
7243 ;; keys which normally belong to the major mode. Here is how it
7244 ;; works: The minor mode defines all the keys necessary to operate the
7245 ;; structure commands, but wraps the commands into a function which
7246 ;; tests if the cursor is currently at a headline or a plain list
7247 ;; item. If that is the case, the structure command is used,
7248 ;; temporarily setting many Org-mode variables like regular
7249 ;; expressions for filling etc. However, when any of those keys is
7250 ;; used at a different location, function uses `key-binding' to look
7251 ;; up if the key has an associated command in another currently active
7252 ;; keymap (minor modes, major mode, global), and executes that
7253 ;; command. There might be problems if any of the keys is otherwise
7254 ;; used as a prefix key.
7256 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7257 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7258 ;; addresses this by checking explicitly for both bindings.
7260 (defvar orgstruct-mode-map (make-sparse-keymap)
7261 "Keymap for the minor `orgstruct-mode'.")
7263 (defvar org-local-vars nil
7264 "List of local variables, for use by `orgstruct-mode'")
7266 ;;;###autoload
7267 (define-minor-mode orgstruct-mode
7268 "Toggle the minor more `orgstruct-mode'.
7269 This mode is for using Org-mode structure commands in other modes.
7270 The following key behave as if Org-mode was active, if the cursor
7271 is on a headline, or on a plain list item (both in the definition
7272 of Org-mode).
7274 M-up Move entry/item up
7275 M-down Move entry/item down
7276 M-left Promote
7277 M-right Demote
7278 M-S-up Move entry/item up
7279 M-S-down Move entry/item down
7280 M-S-left Promote subtree
7281 M-S-right Demote subtree
7282 M-q Fill paragraph and items like in Org-mode
7283 C-c ^ Sort entries
7284 C-c - Cycle list bullet
7285 TAB Cycle item visibility
7286 M-RET Insert new heading/item
7287 S-M-RET Insert new TODO heading / Chekbox item
7288 C-c C-c Set tags / toggle checkbox"
7289 nil " OrgStruct" nil
7290 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7292 ;;;###autoload
7293 (defun turn-on-orgstruct ()
7294 "Unconditionally turn on `orgstruct-mode'."
7295 (orgstruct-mode 1))
7297 ;;;###autoload
7298 (defun turn-on-orgstruct++ ()
7299 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7300 In addition to setting orgstruct-mode, this also exports all indentation and
7301 autofilling variables from org-mode into the buffer. Note that turning
7302 off orgstruct-mode will *not* remove these additonal settings."
7303 (orgstruct-mode 1)
7304 (let (var val)
7305 (mapc
7306 (lambda (x)
7307 (when (string-match
7308 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7309 (symbol-name (car x)))
7310 (setq var (car x) val (nth 1 x))
7311 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7312 org-local-vars)))
7314 (defun orgstruct-error ()
7315 "Error when there is no default binding for a structure key."
7316 (interactive)
7317 (error "This key is has no function outside structure elements"))
7319 (defun orgstruct-setup ()
7320 "Setup orgstruct keymaps."
7321 (let ((nfunc 0)
7322 (bindings
7323 (list
7324 '([(meta up)] org-metaup)
7325 '([(meta down)] org-metadown)
7326 '([(meta left)] org-metaleft)
7327 '([(meta right)] org-metaright)
7328 '([(meta shift up)] org-shiftmetaup)
7329 '([(meta shift down)] org-shiftmetadown)
7330 '([(meta shift left)] org-shiftmetaleft)
7331 '([(meta shift right)] org-shiftmetaright)
7332 '([(shift up)] org-shiftup)
7333 '([(shift down)] org-shiftdown)
7334 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7335 '("\M-q" fill-paragraph)
7336 '("\C-c^" org-sort)
7337 '("\C-c-" org-cycle-list-bullet)))
7338 elt key fun cmd)
7339 (while (setq elt (pop bindings))
7340 (setq nfunc (1+ nfunc))
7341 (setq key (org-key (car elt))
7342 fun (nth 1 elt)
7343 cmd (orgstruct-make-binding fun nfunc key))
7344 (org-defkey orgstruct-mode-map key cmd))
7346 ;; Special treatment needed for TAB and RET
7347 (org-defkey orgstruct-mode-map [(tab)]
7348 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7349 (org-defkey orgstruct-mode-map "\C-i"
7350 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7352 (org-defkey orgstruct-mode-map "\M-\C-m"
7353 (orgstruct-make-binding 'org-insert-heading 105
7354 "\M-\C-m" [(meta return)]))
7355 (org-defkey orgstruct-mode-map [(meta return)]
7356 (orgstruct-make-binding 'org-insert-heading 106
7357 [(meta return)] "\M-\C-m"))
7359 (org-defkey orgstruct-mode-map [(shift meta return)]
7360 (orgstruct-make-binding 'org-insert-todo-heading 107
7361 [(meta return)] "\M-\C-m"))
7363 (unless org-local-vars
7364 (setq org-local-vars (org-get-local-variables)))
7368 (defun orgstruct-make-binding (fun n &rest keys)
7369 "Create a function for binding in the structure minor mode.
7370 FUN is the command to call inside a table. N is used to create a unique
7371 command name. KEYS are keys that should be checked in for a command
7372 to execute outside of tables."
7373 (eval
7374 (list 'defun
7375 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7376 '(arg)
7377 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7378 "Outside of structure, run the binding of `"
7379 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7380 "'.")
7381 '(interactive "p")
7382 (list 'if
7383 '(org-context-p 'headline 'item)
7384 (list 'org-run-like-in-org-mode (list 'quote fun))
7385 (list 'let '(orgstruct-mode)
7386 (list 'call-interactively
7387 (append '(or)
7388 (mapcar (lambda (k)
7389 (list 'key-binding k))
7390 keys)
7391 '('orgstruct-error))))))))
7393 (defun org-context-p (&rest contexts)
7394 "Check if local context is and of CONTEXTS.
7395 Possible values in the list of contexts are `table', `headline', and `item'."
7396 (let ((pos (point)))
7397 (goto-char (point-at-bol))
7398 (prog1 (or (and (memq 'table contexts)
7399 (looking-at "[ \t]*|"))
7400 (and (memq 'headline contexts)
7401 (looking-at "\\*+"))
7402 (and (memq 'item contexts)
7403 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
7404 (goto-char pos))))
7406 (defun org-get-local-variables ()
7407 "Return a list of all local variables in an org-mode buffer."
7408 (let (varlist)
7409 (with-current-buffer (get-buffer-create "*Org tmp*")
7410 (erase-buffer)
7411 (org-mode)
7412 (setq varlist (buffer-local-variables)))
7413 (kill-buffer "*Org tmp*")
7414 (delq nil
7415 (mapcar
7416 (lambda (x)
7417 (setq x
7418 (if (symbolp x)
7419 (list x)
7420 (list (car x) (list 'quote (cdr x)))))
7421 (if (string-match
7422 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7423 (symbol-name (car x)))
7424 x nil))
7425 varlist))))
7427 ;;;###autoload
7428 (defun org-run-like-in-org-mode (cmd)
7429 (unless org-local-vars
7430 (setq org-local-vars (org-get-local-variables)))
7431 (eval (list 'let org-local-vars
7432 (list 'call-interactively (list 'quote cmd)))))
7434 ;;;; Archiving
7436 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
7438 (defun org-archive-subtree (&optional find-done)
7439 "Move the current subtree to the archive.
7440 The archive can be a certain top-level heading in the current file, or in
7441 a different file. The tree will be moved to that location, the subtree
7442 heading be marked DONE, and the current time will be added.
7444 When called with prefix argument FIND-DONE, find whole trees without any
7445 open TODO items and archive them (after getting confirmation from the user).
7446 If the cursor is not at a headline when this comand is called, try all level
7447 1 trees. If the cursor is on a headline, only try the direct children of
7448 this heading."
7449 (interactive "P")
7450 (if find-done
7451 (org-archive-all-done)
7452 ;; Save all relevant TODO keyword-relatex variables
7454 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
7455 (tr-org-todo-keywords-1 org-todo-keywords-1)
7456 (tr-org-todo-kwd-alist org-todo-kwd-alist)
7457 (tr-org-done-keywords org-done-keywords)
7458 (tr-org-todo-regexp org-todo-regexp)
7459 (tr-org-todo-line-regexp org-todo-line-regexp)
7460 (tr-org-odd-levels-only org-odd-levels-only)
7461 (this-buffer (current-buffer))
7462 (org-archive-location org-archive-location)
7463 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
7464 ;; start of variables that will be used for saving context
7465 ;; The compiler complains about them - keep them anyway!
7466 (file (abbreviate-file-name (buffer-file-name)))
7467 (time (format-time-string
7468 (substring (cdr org-time-stamp-formats) 1 -1)
7469 (current-time)))
7470 afile heading buffer level newfile-p
7471 category todo priority
7472 ;; start of variables that will be used for savind context
7473 ltags itags prop)
7475 ;; Try to find a local archive location
7476 (save-excursion
7477 (save-restriction
7478 (widen)
7479 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
7480 (if (and prop (string-match "\\S-" prop))
7481 (setq org-archive-location prop)
7482 (if (or (re-search-backward re nil t)
7483 (re-search-forward re nil t))
7484 (setq org-archive-location (match-string 1))))))
7486 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
7487 (progn
7488 (setq afile (format (match-string 1 org-archive-location)
7489 (file-name-nondirectory buffer-file-name))
7490 heading (match-string 2 org-archive-location)))
7491 (error "Invalid `org-archive-location'"))
7492 (if (> (length afile) 0)
7493 (setq newfile-p (not (file-exists-p afile))
7494 buffer (find-file-noselect afile))
7495 (setq buffer (current-buffer)))
7496 (unless buffer
7497 (error "Cannot access file \"%s\"" afile))
7498 (if (and (> (length heading) 0)
7499 (string-match "^\\*+" heading))
7500 (setq level (match-end 0))
7501 (setq heading nil level 0))
7502 (save-excursion
7503 (org-back-to-heading t)
7504 ;; Get context information that will be lost by moving the tree
7505 (org-refresh-category-properties)
7506 (setq category (org-get-category)
7507 todo (and (looking-at org-todo-line-regexp)
7508 (match-string 2))
7509 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
7510 ltags (org-get-tags)
7511 itags (org-delete-all ltags (org-get-tags-at)))
7512 (setq ltags (mapconcat 'identity ltags " ")
7513 itags (mapconcat 'identity itags " "))
7514 ;; We first only copy, in case something goes wrong
7515 ;; we need to protect this-command, to avoid kill-region sets it,
7516 ;; which would lead to duplication of subtrees
7517 (let (this-command) (org-copy-subtree))
7518 (set-buffer buffer)
7519 ;; Enforce org-mode for the archive buffer
7520 (if (not (org-mode-p))
7521 ;; Force the mode for future visits.
7522 (let ((org-insert-mode-line-in-empty-file t)
7523 (org-inhibit-startup t))
7524 (call-interactively 'org-mode)))
7525 (when newfile-p
7526 (goto-char (point-max))
7527 (insert (format "\nArchived entries from file %s\n\n"
7528 (buffer-file-name this-buffer))))
7529 ;; Force the TODO keywords of the original buffer
7530 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
7531 (org-todo-keywords-1 tr-org-todo-keywords-1)
7532 (org-todo-kwd-alist tr-org-todo-kwd-alist)
7533 (org-done-keywords tr-org-done-keywords)
7534 (org-todo-regexp tr-org-todo-regexp)
7535 (org-todo-line-regexp tr-org-todo-line-regexp)
7536 (org-odd-levels-only
7537 (if (local-variable-p 'org-odd-levels-only (current-buffer))
7538 org-odd-levels-only
7539 tr-org-odd-levels-only)))
7540 (goto-char (point-min))
7541 (if heading
7542 (progn
7543 (if (re-search-forward
7544 (concat "^" (regexp-quote heading)
7545 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
7546 nil t)
7547 (goto-char (match-end 0))
7548 ;; Heading not found, just insert it at the end
7549 (goto-char (point-max))
7550 (or (bolp) (insert "\n"))
7551 (insert "\n" heading "\n")
7552 (end-of-line 0))
7553 ;; Make the subtree visible
7554 (show-subtree)
7555 (org-end-of-subtree t)
7556 (skip-chars-backward " \t\r\n")
7557 (and (looking-at "[ \t\r\n]*")
7558 (replace-match "\n\n")))
7559 ;; No specific heading, just go to end of file.
7560 (goto-char (point-max)) (insert "\n"))
7561 ;; Paste
7562 (org-paste-subtree (org-get-legal-level level 1))
7564 ;; Mark the entry as done
7565 (when (and org-archive-mark-done
7566 (looking-at org-todo-line-regexp)
7567 (or (not (match-end 2))
7568 (not (member (match-string 2) org-done-keywords))))
7569 (let (org-log-done)
7570 (org-todo
7571 (car (or (member org-archive-mark-done org-done-keywords)
7572 org-done-keywords)))))
7574 ;; Add the context info
7575 (when org-archive-save-context-info
7576 (let ((l org-archive-save-context-info) e n v)
7577 (while (setq e (pop l))
7578 (when (and (setq v (symbol-value e))
7579 (stringp v) (string-match "\\S-" v))
7580 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
7581 (org-entry-put (point) n v)))))
7583 ;; Save the buffer, if it is not the same buffer.
7584 (if (not (eq this-buffer buffer)) (save-buffer))))
7585 ;; Here we are back in the original buffer. Everything seems to have
7586 ;; worked. So now cut the tree and finish up.
7587 (let (this-command) (org-cut-subtree))
7588 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
7589 (message "Subtree archived %s"
7590 (if (eq this-buffer buffer)
7591 (concat "under heading: " heading)
7592 (concat "in file: " (abbreviate-file-name afile)))))))
7594 (defun org-refresh-category-properties ()
7595 "Refresh category text properties in teh buffer."
7596 (let ((def-cat (cond
7597 ((null org-category)
7598 (if buffer-file-name
7599 (file-name-sans-extension
7600 (file-name-nondirectory buffer-file-name))
7601 "???"))
7602 ((symbolp org-category) (symbol-name org-category))
7603 (t org-category)))
7604 beg end cat pos optionp)
7605 (org-unmodified
7606 (save-excursion
7607 (save-restriction
7608 (widen)
7609 (goto-char (point-min))
7610 (put-text-property (point) (point-max) 'org-category def-cat)
7611 (while (re-search-forward
7612 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7613 (setq pos (match-end 0)
7614 optionp (equal (char-after (match-beginning 0)) ?#)
7615 cat (org-trim (match-string 2)))
7616 (if optionp
7617 (setq beg (point-at-bol) end (point-max))
7618 (org-back-to-heading t)
7619 (setq beg (point) end (org-end-of-subtree t t)))
7620 (put-text-property beg end 'org-category cat)
7621 (goto-char pos)))))))
7623 (defun org-archive-all-done (&optional tag)
7624 "Archive sublevels of the current tree without open TODO items.
7625 If the cursor is not on a headline, try all level 1 trees. If
7626 it is on a headline, try all direct children.
7627 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
7628 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
7629 (rea (concat ".*:" org-archive-tag ":"))
7630 (begm (make-marker))
7631 (endm (make-marker))
7632 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
7633 "Move subtree to archive (no open TODO items)? "))
7634 beg end (cntarch 0))
7635 (if (org-on-heading-p)
7636 (progn
7637 (setq re1 (concat "^" (regexp-quote
7638 (make-string
7639 (1+ (- (match-end 0) (match-beginning 0)))
7640 ?*))
7641 " "))
7642 (move-marker begm (point))
7643 (move-marker endm (org-end-of-subtree t)))
7644 (setq re1 "^* ")
7645 (move-marker begm (point-min))
7646 (move-marker endm (point-max)))
7647 (save-excursion
7648 (goto-char begm)
7649 (while (re-search-forward re1 endm t)
7650 (setq beg (match-beginning 0)
7651 end (save-excursion (org-end-of-subtree t) (point)))
7652 (goto-char beg)
7653 (if (re-search-forward re end t)
7654 (goto-char end)
7655 (goto-char beg)
7656 (if (and (or (not tag) (not (looking-at rea)))
7657 (y-or-n-p question))
7658 (progn
7659 (if tag
7660 (org-toggle-tag org-archive-tag 'on)
7661 (org-archive-subtree))
7662 (setq cntarch (1+ cntarch)))
7663 (goto-char end)))))
7664 (message "%d trees archived" cntarch)))
7666 (defun org-cycle-hide-drawers (state)
7667 "Re-hide all drawers after a visibility state change."
7668 (when (and (org-mode-p)
7669 (not (memq state '(overview folded))))
7670 (save-excursion
7671 (let* ((globalp (memq state '(contents all)))
7672 (beg (if globalp (point-min) (point)))
7673 (end (if globalp (point-max) (org-end-of-subtree t))))
7674 (goto-char beg)
7675 (while (re-search-forward org-drawer-regexp end t)
7676 (org-flag-drawer t))))))
7678 (defun org-flag-drawer (flag)
7679 (save-excursion
7680 (beginning-of-line 1)
7681 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7682 (let ((b (match-end 0)))
7683 (if (re-search-forward
7684 "^[ \t]*:END:"
7685 (save-excursion (outline-next-heading) (point)) t)
7686 (outline-flag-region b (point-at-eol) flag)
7687 (error ":END: line missing"))))))
7689 (defun org-cycle-hide-archived-subtrees (state)
7690 "Re-hide all archived subtrees after a visibility state change."
7691 (when (and (not org-cycle-open-archived-trees)
7692 (not (memq state '(overview folded))))
7693 (save-excursion
7694 (let* ((globalp (memq state '(contents all)))
7695 (beg (if globalp (point-min) (point)))
7696 (end (if globalp (point-max) (org-end-of-subtree t))))
7697 (org-hide-archived-subtrees beg end)
7698 (goto-char beg)
7699 (if (looking-at (concat ".*:" org-archive-tag ":"))
7700 (message (substitute-command-keys
7701 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
7703 (defun org-force-cycle-archived ()
7704 "Cycle subtree even if it is archived."
7705 (interactive)
7706 (setq this-command 'org-cycle)
7707 (let ((org-cycle-open-archived-trees t))
7708 (call-interactively 'org-cycle)))
7710 (defun org-hide-archived-subtrees (beg end)
7711 "Re-hide all archived subtrees after a visibility state change."
7712 (save-excursion
7713 (let* ((re (concat ":" org-archive-tag ":")))
7714 (goto-char beg)
7715 (while (re-search-forward re end t)
7716 (and (org-on-heading-p) (hide-subtree))
7717 (org-end-of-subtree t)))))
7719 (defun org-toggle-tag (tag &optional onoff)
7720 "Toggle the tag TAG for the current line.
7721 If ONOFF is `on' or `off', don't toggle but set to this state."
7722 (unless (org-on-heading-p t) (error "Not on headling"))
7723 (let (res current)
7724 (save-excursion
7725 (beginning-of-line)
7726 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
7727 (point-at-eol) t)
7728 (progn
7729 (setq current (match-string 1))
7730 (replace-match ""))
7731 (setq current ""))
7732 (setq current (nreverse (org-split-string current ":")))
7733 (cond
7734 ((eq onoff 'on)
7735 (setq res t)
7736 (or (member tag current) (push tag current)))
7737 ((eq onoff 'off)
7738 (or (not (member tag current)) (setq current (delete tag current))))
7739 (t (if (member tag current)
7740 (setq current (delete tag current))
7741 (setq res t)
7742 (push tag current))))
7743 (end-of-line 1)
7744 (if current
7745 (progn
7746 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
7747 (org-set-tags nil t))
7748 (delete-horizontal-space))
7749 (run-hooks 'org-after-tags-change-hook))
7750 res))
7752 (defun org-toggle-archive-tag (&optional arg)
7753 "Toggle the archive tag for the current headline.
7754 With prefix ARG, check all children of current headline and offer tagging
7755 the children that do not contain any open TODO items."
7756 (interactive "P")
7757 (if arg
7758 (org-archive-all-done 'tag)
7759 (let (set)
7760 (save-excursion
7761 (org-back-to-heading t)
7762 (setq set (org-toggle-tag org-archive-tag))
7763 (when set (hide-subtree)))
7764 (and set (beginning-of-line 1))
7765 (message "Subtree %s" (if set "archived" "unarchived")))))
7768 ;;;; Tables
7770 ;;; The table editor
7772 ;; Watch out: Here we are talking about two different kind of tables.
7773 ;; Most of the code is for the tables created with the Org-mode table editor.
7774 ;; Sometimes, we talk about tables created and edited with the table.el
7775 ;; Emacs package. We call the former org-type tables, and the latter
7776 ;; table.el-type tables.
7778 (defun org-before-change-function (beg end)
7779 "Every change indicates that a table might need an update."
7780 (setq org-table-may-need-update t))
7782 (defconst org-table-line-regexp "^[ \t]*|"
7783 "Detects an org-type table line.")
7784 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
7785 "Detects an org-type table line.")
7786 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
7787 "Detects a table line marked for automatic recalculation.")
7788 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
7789 "Detects a table line marked for automatic recalculation.")
7790 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
7791 "Detects a table line marked for automatic recalculation.")
7792 (defconst org-table-hline-regexp "^[ \t]*|-"
7793 "Detects an org-type table hline.")
7794 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
7795 "Detects a table-type table hline.")
7796 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
7797 "Detects an org-type or table-type table.")
7798 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
7799 "Searching from within a table (any type) this finds the first line
7800 outside the table.")
7801 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
7802 "Searching from within a table (any type) this finds the first line
7803 outside the table.")
7805 (defvar org-table-last-highlighted-reference nil)
7806 (defvar org-table-formula-history nil)
7808 (defvar org-table-column-names nil
7809 "Alist with column names, derived from the `!' line.")
7810 (defvar org-table-column-name-regexp nil
7811 "Regular expression matching the current column names.")
7812 (defvar org-table-local-parameters nil
7813 "Alist with parameter names, derived from the `$' line.")
7814 (defvar org-table-named-field-locations nil
7815 "Alist with locations of named fields.")
7817 (defvar org-table-current-line-types nil
7818 "Table row types, non-nil only for the duration of a comand.")
7819 (defvar org-table-current-begin-line nil
7820 "Table begin line, non-nil only for the duration of a comand.")
7821 (defvar org-table-current-begin-pos nil
7822 "Table begin position, non-nil only for the duration of a comand.")
7823 (defvar org-table-dlines nil
7824 "Vector of data line line numbers in the current table.")
7825 (defvar org-table-hlines nil
7826 "Vector of hline line numbers in the current table.")
7828 (defconst org-table-range-regexp
7829 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
7830 ;; 1 2 3 4 5
7831 "Regular expression for matching ranges in formulas.")
7833 (defconst org-table-range-regexp2
7834 (concat
7835 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
7836 "\\.\\."
7837 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
7838 "Match a range for reference display.")
7840 (defconst org-table-translate-regexp
7841 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
7842 "Match a reference that needs translation, for reference display.")
7844 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
7846 (defun org-table-create-with-table.el ()
7847 "Use the table.el package to insert a new table.
7848 If there is already a table at point, convert between Org-mode tables
7849 and table.el tables."
7850 (interactive)
7851 (require 'table)
7852 (cond
7853 ((org-at-table.el-p)
7854 (if (y-or-n-p "Convert table to Org-mode table? ")
7855 (org-table-convert)))
7856 ((org-at-table-p)
7857 (if (y-or-n-p "Convert table to table.el table? ")
7858 (org-table-convert)))
7859 (t (call-interactively 'table-insert))))
7861 (defun org-table-create-or-convert-from-region (arg)
7862 "Convert region to table, or create an empty table.
7863 If there is an active region, convert it to a table, using the function
7864 `org-table-convert-region'. See the documentation of that function
7865 to learn how the prefix argument is interpreted to determine the field
7866 separator.
7867 If there is no such region, create an empty table with `org-table-create'."
7868 (interactive "P")
7869 (if (org-region-active-p)
7870 (org-table-convert-region (region-beginning) (region-end) arg)
7871 (org-table-create arg)))
7873 (defun org-table-create (&optional size)
7874 "Query for a size and insert a table skeleton.
7875 SIZE is a string Columns x Rows like for example \"3x2\"."
7876 (interactive "P")
7877 (unless size
7878 (setq size (read-string
7879 (concat "Table size Columns x Rows [e.g. "
7880 org-table-default-size "]: ")
7881 "" nil org-table-default-size)))
7883 (let* ((pos (point))
7884 (indent (make-string (current-column) ?\ ))
7885 (split (org-split-string size " *x *"))
7886 (rows (string-to-number (nth 1 split)))
7887 (columns (string-to-number (car split)))
7888 (line (concat (apply 'concat indent "|" (make-list columns " |"))
7889 "\n")))
7890 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
7891 (point-at-bol) (point)))
7892 (beginning-of-line 1)
7893 (newline))
7894 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
7895 (dotimes (i rows) (insert line))
7896 (goto-char pos)
7897 (if (> rows 1)
7898 ;; Insert a hline after the first row.
7899 (progn
7900 (end-of-line 1)
7901 (insert "\n|-")
7902 (goto-char pos)))
7903 (org-table-align)))
7905 (defun org-table-convert-region (beg0 end0 &optional separator)
7906 "Convert region to a table.
7907 The region goes from BEG0 to END0, but these borders will be moved
7908 slightly, to make sure a beginning of line in the first line is included.
7910 SEPARATOR specifies the field separator in the lines. It can have the
7911 following values:
7913 '(4) Use the comma as a field separator
7914 '(16) Use a TAB as field separator
7915 integer When a number, use that many spaces as field separator
7916 nil When nil, the command tries to be smart and figure out the
7917 separator in the following way:
7918 - when each line contains a TAB, assume TAB-separated material
7919 - when each line contains a comme, assume CSV material
7920 - else, assume one or more SPACE charcters as separator."
7921 (interactive "rP")
7922 (let* ((beg (min beg0 end0))
7923 (end (max beg0 end0))
7925 (goto-char beg)
7926 (beginning-of-line 1)
7927 (setq beg (move-marker (make-marker) (point)))
7928 (goto-char end)
7929 (if (bolp) (backward-char 1) (end-of-line 1))
7930 (setq end (move-marker (make-marker) (point)))
7931 ;; Get the right field separator
7932 (unless separator
7933 (goto-char beg)
7934 (setq separator
7935 (cond
7936 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
7937 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
7938 (t 1))))
7939 (setq re (cond
7940 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
7941 ((equal separator '(16)) "^\\|\t")
7942 ((integerp separator)
7943 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
7944 (t (error "This should not happen"))))
7945 (goto-char beg)
7946 (while (re-search-forward re end t)
7947 (replace-match "| " t t))
7948 (goto-char beg)
7949 (insert " ")
7950 (org-table-align)))
7952 (defun org-table-import (file arg)
7953 "Import FILE as a table.
7954 The file is assumed to be tab-separated. Such files can be produced by most
7955 spreadsheet and database applications. If no tabs (at least one per line)
7956 are found, lines will be split on whitespace into fields."
7957 (interactive "f\nP")
7958 (or (bolp) (newline))
7959 (let ((beg (point))
7960 (pm (point-max)))
7961 (insert-file-contents file)
7962 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
7964 (defun org-table-export ()
7965 "Export table as a tab-separated file.
7966 Such a file can be imported into a spreadsheet program like Excel."
7967 (interactive)
7968 (let* ((beg (org-table-begin))
7969 (end (org-table-end))
7970 (table (buffer-substring beg end))
7971 (file (read-file-name "Export table to: "))
7972 buf)
7973 (unless (or (not (file-exists-p file))
7974 (y-or-n-p (format "Overwrite file %s? " file)))
7975 (error "Abort"))
7976 (with-current-buffer (find-file-noselect file)
7977 (setq buf (current-buffer))
7978 (erase-buffer)
7979 (fundamental-mode)
7980 (insert table)
7981 (goto-char (point-min))
7982 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
7983 (replace-match "" t t)
7984 (end-of-line 1))
7985 (goto-char (point-min))
7986 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
7987 (replace-match "" t t)
7988 (goto-char (min (1+ (point)) (point-max))))
7989 (goto-char (point-min))
7990 (while (re-search-forward "^-[-+]*$" nil t)
7991 (replace-match "")
7992 (if (looking-at "\n")
7993 (delete-char 1)))
7994 (goto-char (point-min))
7995 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
7996 (replace-match "\t" t t))
7997 (save-buffer))
7998 (kill-buffer buf)))
8000 (defvar org-table-aligned-begin-marker (make-marker)
8001 "Marker at the beginning of the table last aligned.
8002 Used to check if cursor still is in that table, to minimize realignment.")
8003 (defvar org-table-aligned-end-marker (make-marker)
8004 "Marker at the end of the table last aligned.
8005 Used to check if cursor still is in that table, to minimize realignment.")
8006 (defvar org-table-last-alignment nil
8007 "List of flags for flushright alignment, from the last re-alignment.
8008 This is being used to correctly align a single field after TAB or RET.")
8009 (defvar org-table-last-column-widths nil
8010 "List of max width of fields in each column.
8011 This is being used to correctly align a single field after TAB or RET.")
8012 (defvar org-table-overlay-coordinates nil
8013 "Overlay coordinates after each align of a table.")
8014 (make-variable-buffer-local 'org-table-overlay-coordinates)
8016 (defvar org-last-recalc-line nil)
8017 (defconst org-narrow-column-arrow "=>"
8018 "Used as display property in narrowed table columns.")
8020 (defun org-table-align ()
8021 "Align the table at point by aligning all vertical bars."
8022 (interactive)
8023 (let* (
8024 ;; Limits of table
8025 (beg (org-table-begin))
8026 (end (org-table-end))
8027 ;; Current cursor position
8028 (linepos (org-current-line))
8029 (colpos (org-table-current-column))
8030 (winstart (window-start))
8031 (winstartline (org-current-line (min winstart (1- (point-max)))))
8032 lines (new "") lengths l typenums ty fields maxfields i
8033 column
8034 (indent "") cnt frac
8035 rfmt hfmt
8036 (spaces '(1 . 1))
8037 (sp1 (car spaces))
8038 (sp2 (cdr spaces))
8039 (rfmt1 (concat
8040 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8041 (hfmt1 (concat
8042 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8043 emptystrings links dates emph narrow fmax f1 len c e)
8044 (untabify beg end)
8045 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8046 ;; Check if we have links or dates
8047 (goto-char beg)
8048 (setq links (re-search-forward org-bracket-link-regexp end t))
8049 (goto-char beg)
8050 (setq emph (and org-hide-emphasis-markers
8051 (re-search-forward org-emph-re end t)))
8052 (goto-char beg)
8053 (setq dates (and org-display-custom-times
8054 (re-search-forward org-ts-regexp-both end t)))
8055 ;; Make sure the link properties are right
8056 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8057 ;; Make sure the date properties are right
8058 (when dates (goto-char beg) (while (org-activate-dates end)))
8059 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8061 ;; Check if we are narrowing any columns
8062 (goto-char beg)
8063 (setq narrow (and org-format-transports-properties-p
8064 (re-search-forward "<[0-9]+>" end t)))
8065 ;; Get the rows
8066 (setq lines (org-split-string
8067 (buffer-substring beg end) "\n"))
8068 ;; Store the indentation of the first line
8069 (if (string-match "^ *" (car lines))
8070 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8071 ;; Mark the hlines by setting the corresponding element to nil
8072 ;; At the same time, we remove trailing space.
8073 (setq lines (mapcar (lambda (l)
8074 (if (string-match "^ *|-" l)
8076 (if (string-match "[ \t]+$" l)
8077 (substring l 0 (match-beginning 0))
8078 l)))
8079 lines))
8080 ;; Get the data fields by splitting the lines.
8081 (setq fields (mapcar
8082 (lambda (l)
8083 (org-split-string l " *| *"))
8084 (delq nil (copy-sequence lines))))
8085 ;; How many fields in the longest line?
8086 (condition-case nil
8087 (setq maxfields (apply 'max (mapcar 'length fields)))
8088 (error
8089 (kill-region beg end)
8090 (org-table-create org-table-default-size)
8091 (error "Empty table - created default table")))
8092 ;; A list of empty strings to fill any short rows on output
8093 (setq emptystrings (make-list maxfields ""))
8094 ;; Check for special formatting.
8095 (setq i -1)
8096 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8097 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8098 ;; Check if there is an explicit width specified
8099 (when narrow
8100 (setq c column fmax nil)
8101 (while c
8102 (setq e (pop c))
8103 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8104 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8105 ;; Find fields that are wider than fmax, and shorten them
8106 (when fmax
8107 (loop for xx in column do
8108 (when (and (stringp xx)
8109 (> (org-string-width xx) fmax))
8110 (org-add-props xx nil
8111 'help-echo
8112 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8113 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8114 (unless (> f1 1)
8115 (error "Cannot narrow field starting with wide link \"%s\""
8116 (match-string 0 xx)))
8117 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8118 (add-text-properties (- f1 2) f1
8119 (list 'display org-narrow-column-arrow)
8120 xx)))))
8121 ;; Get the maximum width for each column
8122 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8123 ;; Get the fraction of numbers, to decide about alignment of the column
8124 (setq cnt 0 frac 0.0)
8125 (loop for x in column do
8126 (if (equal x "")
8128 (setq frac ( / (+ (* frac cnt)
8129 (if (string-match org-table-number-regexp x) 1 0))
8130 (setq cnt (1+ cnt))))))
8131 (push (>= frac org-table-number-fraction) typenums))
8132 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8134 ;; Store the alignment of this table, for later editing of single fields
8135 (setq org-table-last-alignment typenums
8136 org-table-last-column-widths lengths)
8138 ;; With invisible characters, `format' does not get the field width right
8139 ;; So we need to make these fields wide by hand.
8140 (when (or links emph)
8141 (loop for i from 0 upto (1- maxfields) do
8142 (setq len (nth i lengths))
8143 (loop for j from 0 upto (1- (length fields)) do
8144 (setq c (nthcdr i (car (nthcdr j fields))))
8145 (if (and (stringp (car c))
8146 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8147 ; (string-match org-bracket-link-regexp (car c))
8148 (< (org-string-width (car c)) len))
8149 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8151 ;; Compute the formats needed for output of the table
8152 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8153 (while (setq l (pop lengths))
8154 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8155 (setq rfmt (concat rfmt (format rfmt1 ty l))
8156 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8157 (setq rfmt (concat rfmt "\n")
8158 hfmt (concat (substring hfmt 0 -1) "|\n"))
8160 (setq new (mapconcat
8161 (lambda (l)
8162 (if l (apply 'format rfmt
8163 (append (pop fields) emptystrings))
8164 hfmt))
8165 lines ""))
8166 ;; Replace the old one
8167 (delete-region beg end)
8168 (move-marker end nil)
8169 (move-marker org-table-aligned-begin-marker (point))
8170 (insert new)
8171 (move-marker org-table-aligned-end-marker (point))
8172 (when (and orgtbl-mode (not (org-mode-p)))
8173 (goto-char org-table-aligned-begin-marker)
8174 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8175 ;; Try to move to the old location
8176 (goto-line winstartline)
8177 (setq winstart (point-at-bol))
8178 (goto-line linepos)
8179 (set-window-start (selected-window) winstart 'noforce)
8180 (org-table-goto-column colpos)
8181 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8182 (setq org-table-may-need-update nil)
8185 (defun org-string-width (s)
8186 "Compute width of string, ignoring invisible characters.
8187 This ignores character with invisibility property `org-link', and also
8188 characters with property `org-cwidth', because these will become invisible
8189 upon the next fontification round."
8190 (let (b l)
8191 (when (or (eq t buffer-invisibility-spec)
8192 (assq 'org-link buffer-invisibility-spec))
8193 (while (setq b (text-property-any 0 (length s)
8194 'invisible 'org-link s))
8195 (setq s (concat (substring s 0 b)
8196 (substring s (or (next-single-property-change
8197 b 'invisible s) (length s)))))))
8198 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8199 (setq s (concat (substring s 0 b)
8200 (substring s (or (next-single-property-change
8201 b 'org-cwidth s) (length s))))))
8202 (setq l (string-width s) b -1)
8203 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8204 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8207 (defun org-table-begin (&optional table-type)
8208 "Find the beginning of the table and return its position.
8209 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8210 (save-excursion
8211 (if (not (re-search-backward
8212 (if table-type org-table-any-border-regexp
8213 org-table-border-regexp)
8214 nil t))
8215 (progn (goto-char (point-min)) (point))
8216 (goto-char (match-beginning 0))
8217 (beginning-of-line 2)
8218 (point))))
8220 (defun org-table-end (&optional table-type)
8221 "Find the end of the table and return its position.
8222 With argument TABLE-TYPE, go to the end of a table.el-type table."
8223 (save-excursion
8224 (if (not (re-search-forward
8225 (if table-type org-table-any-border-regexp
8226 org-table-border-regexp)
8227 nil t))
8228 (goto-char (point-max))
8229 (goto-char (match-beginning 0)))
8230 (point-marker)))
8232 (defun org-table-justify-field-maybe (&optional new)
8233 "Justify the current field, text to left, number to right.
8234 Optional argument NEW may specify text to replace the current field content."
8235 (cond
8236 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8237 ((org-at-table-hline-p))
8238 ((and (not new)
8239 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8240 (current-buffer)))
8241 (< (point) org-table-aligned-begin-marker)
8242 (>= (point) org-table-aligned-end-marker)))
8243 ;; This is not the same table, force a full re-align
8244 (setq org-table-may-need-update t))
8245 (t ;; realign the current field, based on previous full realign
8246 (let* ((pos (point)) s
8247 (col (org-table-current-column))
8248 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8249 l f n o e)
8250 (when (> col 0)
8251 (skip-chars-backward "^|\n")
8252 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8253 (progn
8254 (setq s (match-string 1)
8255 o (match-string 0)
8256 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8257 e (not (= (match-beginning 2) (match-end 2))))
8258 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8259 l (if e "|" (setq org-table-may-need-update t) ""))
8260 n (format f s))
8261 (if new
8262 (if (<= (length new) l) ;; FIXME: length -> str-width?
8263 (setq n (format f new))
8264 (setq n (concat new "|") org-table-may-need-update t)))
8265 (or (equal n o)
8266 (let (org-table-may-need-update)
8267 (replace-match n t t))))
8268 (setq org-table-may-need-update t))
8269 (goto-char pos))))))
8271 (defun org-table-next-field ()
8272 "Go to the next field in the current table, creating new lines as needed.
8273 Before doing so, re-align the table if necessary."
8274 (interactive)
8275 (org-table-maybe-eval-formula)
8276 (org-table-maybe-recalculate-line)
8277 (if (and org-table-automatic-realign
8278 org-table-may-need-update)
8279 (org-table-align))
8280 (let ((end (org-table-end)))
8281 (if (org-at-table-hline-p)
8282 (end-of-line 1))
8283 (condition-case nil
8284 (progn
8285 (re-search-forward "|" end)
8286 (if (looking-at "[ \t]*$")
8287 (re-search-forward "|" end))
8288 (if (and (looking-at "-")
8289 org-table-tab-jumps-over-hlines
8290 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8291 (goto-char (match-beginning 1)))
8292 (if (looking-at "-")
8293 (progn
8294 (beginning-of-line 0)
8295 (org-table-insert-row 'below))
8296 (if (looking-at " ") (forward-char 1))))
8297 (error
8298 (org-table-insert-row 'below)))))
8300 (defun org-table-previous-field ()
8301 "Go to the previous field in the table.
8302 Before doing so, re-align the table if necessary."
8303 (interactive)
8304 (org-table-justify-field-maybe)
8305 (org-table-maybe-recalculate-line)
8306 (if (and org-table-automatic-realign
8307 org-table-may-need-update)
8308 (org-table-align))
8309 (if (org-at-table-hline-p)
8310 (end-of-line 1))
8311 (re-search-backward "|" (org-table-begin))
8312 (re-search-backward "|" (org-table-begin))
8313 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8314 (re-search-backward "|" (org-table-begin)))
8315 (if (looking-at "| ?")
8316 (goto-char (match-end 0))))
8318 (defun org-table-next-row ()
8319 "Go to the next row (same column) in the current table.
8320 Before doing so, re-align the table if necessary."
8321 (interactive)
8322 (org-table-maybe-eval-formula)
8323 (org-table-maybe-recalculate-line)
8324 (if (or (looking-at "[ \t]*$")
8325 (save-excursion (skip-chars-backward " \t") (bolp)))
8326 (newline)
8327 (if (and org-table-automatic-realign
8328 org-table-may-need-update)
8329 (org-table-align))
8330 (let ((col (org-table-current-column)))
8331 (beginning-of-line 2)
8332 (if (or (not (org-at-table-p))
8333 (org-at-table-hline-p))
8334 (progn
8335 (beginning-of-line 0)
8336 (org-table-insert-row 'below)))
8337 (org-table-goto-column col)
8338 (skip-chars-backward "^|\n\r")
8339 (if (looking-at " ") (forward-char 1)))))
8341 (defun org-table-copy-down (n)
8342 "Copy a field down in the current column.
8343 If the field at the cursor is empty, copy into it the content of the nearest
8344 non-empty field above. With argument N, use the Nth non-empty field.
8345 If the current field is not empty, it is copied down to the next row, and
8346 the cursor is moved with it. Therefore, repeating this command causes the
8347 column to be filled row-by-row.
8348 If the variable `org-table-copy-increment' is non-nil and the field is an
8349 integer or a timestamp, it will be incremented while copying. In the case of
8350 a timestamp, if the cursor is on the year, change the year. If it is on the
8351 month or the day, change that. Point will stay on the current date field
8352 in order to easily repeat the interval."
8353 (interactive "p")
8354 (let* ((colpos (org-table-current-column))
8355 (col (current-column))
8356 (field (org-table-get-field))
8357 (non-empty (string-match "[^ \t]" field))
8358 (beg (org-table-begin))
8359 txt)
8360 (org-table-check-inside-data-field)
8361 (if non-empty
8362 (progn
8363 (setq txt (org-trim field))
8364 (org-table-next-row)
8365 (org-table-blank-field))
8366 (save-excursion
8367 (setq txt
8368 (catch 'exit
8369 (while (progn (beginning-of-line 1)
8370 (re-search-backward org-table-dataline-regexp
8371 beg t))
8372 (org-table-goto-column colpos t)
8373 (if (and (looking-at
8374 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8375 (= (setq n (1- n)) 0))
8376 (throw 'exit (match-string 1))))))))
8377 (if txt
8378 (progn
8379 (if (and org-table-copy-increment
8380 (string-match "^[0-9]+$" txt))
8381 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8382 (insert txt)
8383 (move-to-column col)
8384 (if (and org-table-copy-increment (org-at-timestamp-p t))
8385 (org-timestamp-up 1)
8386 (org-table-maybe-recalculate-line))
8387 (org-table-align)
8388 (move-to-column col))
8389 (error "No non-empty field found"))))
8391 (defun org-table-check-inside-data-field ()
8392 "Is point inside a table data field?
8393 I.e. not on a hline or before the first or after the last column?
8394 This actually throws an error, so it aborts the current command."
8395 (if (or (not (org-at-table-p))
8396 (= (org-table-current-column) 0)
8397 (org-at-table-hline-p)
8398 (looking-at "[ \t]*$"))
8399 (error "Not in table data field")))
8401 (defvar org-table-clip nil
8402 "Clipboard for table regions.")
8404 (defun org-table-blank-field ()
8405 "Blank the current table field or active region."
8406 (interactive)
8407 (org-table-check-inside-data-field)
8408 (if (and (interactive-p) (org-region-active-p))
8409 (let (org-table-clip)
8410 (org-table-cut-region (region-beginning) (region-end)))
8411 (skip-chars-backward "^|")
8412 (backward-char 1)
8413 (if (looking-at "|[^|\n]+")
8414 (let* ((pos (match-beginning 0))
8415 (match (match-string 0))
8416 (len (org-string-width match)))
8417 (replace-match (concat "|" (make-string (1- len) ?\ )))
8418 (goto-char (+ 2 pos))
8419 (substring match 1)))))
8421 (defun org-table-get-field (&optional n replace)
8422 "Return the value of the field in column N of current row.
8423 N defaults to current field.
8424 If REPLACE is a string, replace field with this value. The return value
8425 is always the old value."
8426 (and n (org-table-goto-column n))
8427 (skip-chars-backward "^|\n")
8428 (backward-char 1)
8429 (if (looking-at "|[^|\r\n]*")
8430 (let* ((pos (match-beginning 0))
8431 (val (buffer-substring (1+ pos) (match-end 0))))
8432 (if replace
8433 (replace-match (concat "|" replace) t t))
8434 (goto-char (min (point-at-eol) (+ 2 pos)))
8435 val)
8436 (forward-char 1) ""))
8438 (defun org-table-field-info (arg)
8439 "Show info about the current field, and highlight any reference at point."
8440 (interactive "P")
8441 (org-table-get-specials)
8442 (save-excursion
8443 (let* ((pos (point))
8444 (col (org-table-current-column))
8445 (cname (car (rassoc (int-to-string col) org-table-column-names)))
8446 (name (car (rassoc (list (org-current-line) col)
8447 org-table-named-field-locations)))
8448 (eql (org-table-get-stored-formulas))
8449 (dline (org-table-current-dline))
8450 (ref (format "@%d$%d" dline col))
8451 (ref1 (org-table-convert-refs-to-an ref))
8452 (fequation (or (assoc name eql) (assoc ref eql)))
8453 (cequation (assoc (int-to-string col) eql))
8454 (eqn (or fequation cequation)))
8455 (goto-char pos)
8456 (condition-case nil
8457 (org-table-show-reference 'local)
8458 (error nil))
8459 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
8460 dline col
8461 (if cname (concat " or $" cname) "")
8462 dline col ref1
8463 (if name (concat " or $" name) "")
8464 ;; FIXME: formula info not correct if special table line
8465 (if eqn
8466 (concat ", formula: "
8467 (org-table-formula-to-user
8468 (concat
8469 (if (string-match "^[$@]"(car eqn)) "" "$")
8470 (car eqn) "=" (cdr eqn))))
8471 "")))))
8473 (defun org-table-current-column ()
8474 "Find out which column we are in.
8475 When called interactively, column is also displayed in echo area."
8476 (interactive)
8477 (if (interactive-p) (org-table-check-inside-data-field))
8478 (save-excursion
8479 (let ((cnt 0) (pos (point)))
8480 (beginning-of-line 1)
8481 (while (search-forward "|" pos t)
8482 (setq cnt (1+ cnt)))
8483 (if (interactive-p) (message "This is table column %d" cnt))
8484 cnt)))
8486 (defun org-table-current-dline ()
8487 "Find out what table data line we are in.
8488 Only datalins count for this."
8489 (interactive)
8490 (if (interactive-p) (org-table-check-inside-data-field))
8491 (save-excursion
8492 (let ((cnt 0) (pos (point)))
8493 (goto-char (org-table-begin))
8494 (while (<= (point) pos)
8495 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
8496 (beginning-of-line 2))
8497 (if (interactive-p) (message "This is table line %d" cnt))
8498 cnt)))
8500 (defun org-table-goto-column (n &optional on-delim force)
8501 "Move the cursor to the Nth column in the current table line.
8502 With optional argument ON-DELIM, stop with point before the left delimiter
8503 of the field.
8504 If there are less than N fields, just go to after the last delimiter.
8505 However, when FORCE is non-nil, create new columns if necessary."
8506 (interactive "p")
8507 (let ((pos (point-at-eol)))
8508 (beginning-of-line 1)
8509 (when (> n 0)
8510 (while (and (> (setq n (1- n)) -1)
8511 (or (search-forward "|" pos t)
8512 (and force
8513 (progn (end-of-line 1)
8514 (skip-chars-backward "^|")
8515 (insert " | "))))))
8516 ; (backward-char 2) t)))))
8517 (when (and force (not (looking-at ".*|")))
8518 (save-excursion (end-of-line 1) (insert " | ")))
8519 (if on-delim
8520 (backward-char 1)
8521 (if (looking-at " ") (forward-char 1))))))
8523 (defun org-at-table-p (&optional table-type)
8524 "Return t if the cursor is inside an org-type table.
8525 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8526 (if org-enable-table-editor
8527 (save-excursion
8528 (beginning-of-line 1)
8529 (looking-at (if table-type org-table-any-line-regexp
8530 org-table-line-regexp)))
8531 nil))
8533 (defun org-at-table.el-p ()
8534 "Return t if and only if we are at a table.el table."
8535 (and (org-at-table-p 'any)
8536 (save-excursion
8537 (goto-char (org-table-begin 'any))
8538 (looking-at org-table1-hline-regexp))))
8540 (defun org-table-recognize-table.el ()
8541 "If there is a table.el table nearby, recognize it and move into it."
8542 (if org-table-tab-recognizes-table.el
8543 (if (org-at-table.el-p)
8544 (progn
8545 (beginning-of-line 1)
8546 (if (looking-at org-table-dataline-regexp)
8548 (if (looking-at org-table1-hline-regexp)
8549 (progn
8550 (beginning-of-line 2)
8551 (if (looking-at org-table-any-border-regexp)
8552 (beginning-of-line -1)))))
8553 (if (re-search-forward "|" (org-table-end t) t)
8554 (progn
8555 (require 'table)
8556 (if (table--at-cell-p (point))
8558 (message "recognizing table.el table...")
8559 (table-recognize-table)
8560 (message "recognizing table.el table...done")))
8561 (error "This should not happen..."))
8563 nil)
8564 nil))
8566 (defun org-at-table-hline-p ()
8567 "Return t if the cursor is inside a hline in a table."
8568 (if org-enable-table-editor
8569 (save-excursion
8570 (beginning-of-line 1)
8571 (looking-at org-table-hline-regexp))
8572 nil))
8574 (defun org-table-insert-column ()
8575 "Insert a new column into the table."
8576 (interactive)
8577 (if (not (org-at-table-p))
8578 (error "Not at a table"))
8579 (org-table-find-dataline)
8580 (let* ((col (max 1 (org-table-current-column)))
8581 (beg (org-table-begin))
8582 (end (org-table-end))
8583 ;; Current cursor position
8584 (linepos (org-current-line))
8585 (colpos col))
8586 (goto-char beg)
8587 (while (< (point) end)
8588 (if (org-at-table-hline-p)
8590 (org-table-goto-column col t)
8591 (insert "| "))
8592 (beginning-of-line 2))
8593 (move-marker end nil)
8594 (goto-line linepos)
8595 (org-table-goto-column colpos)
8596 (org-table-align)
8597 (org-table-fix-formulas "$" nil (1- col) 1)))
8599 (defun org-table-find-dataline ()
8600 "Find a dataline in the current table, which is needed for column commands."
8601 (if (and (org-at-table-p)
8602 (not (org-at-table-hline-p)))
8604 (let ((col (current-column))
8605 (end (org-table-end)))
8606 (move-to-column col)
8607 (while (and (< (point) end)
8608 (or (not (= (current-column) col))
8609 (org-at-table-hline-p)))
8610 (beginning-of-line 2)
8611 (move-to-column col))
8612 (if (and (org-at-table-p)
8613 (not (org-at-table-hline-p)))
8615 (error
8616 "Please position cursor in a data line for column operations")))))
8618 (defun org-table-delete-column ()
8619 "Delete a column from the table."
8620 (interactive)
8621 (if (not (org-at-table-p))
8622 (error "Not at a table"))
8623 (org-table-find-dataline)
8624 (org-table-check-inside-data-field)
8625 (let* ((col (org-table-current-column))
8626 (beg (org-table-begin))
8627 (end (org-table-end))
8628 ;; Current cursor position
8629 (linepos (org-current-line))
8630 (colpos col))
8631 (goto-char beg)
8632 (while (< (point) end)
8633 (if (org-at-table-hline-p)
8635 (org-table-goto-column col t)
8636 (and (looking-at "|[^|\n]+|")
8637 (replace-match "|")))
8638 (beginning-of-line 2))
8639 (move-marker end nil)
8640 (goto-line linepos)
8641 (org-table-goto-column colpos)
8642 (org-table-align)
8643 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
8644 col -1 col)))
8646 (defun org-table-move-column-right ()
8647 "Move column to the right."
8648 (interactive)
8649 (org-table-move-column nil))
8650 (defun org-table-move-column-left ()
8651 "Move column to the left."
8652 (interactive)
8653 (org-table-move-column 'left))
8655 (defun org-table-move-column (&optional left)
8656 "Move the current column to the right. With arg LEFT, move to the left."
8657 (interactive "P")
8658 (if (not (org-at-table-p))
8659 (error "Not at a table"))
8660 (org-table-find-dataline)
8661 (org-table-check-inside-data-field)
8662 (let* ((col (org-table-current-column))
8663 (col1 (if left (1- col) col))
8664 (beg (org-table-begin))
8665 (end (org-table-end))
8666 ;; Current cursor position
8667 (linepos (org-current-line))
8668 (colpos (if left (1- col) (1+ col))))
8669 (if (and left (= col 1))
8670 (error "Cannot move column further left"))
8671 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8672 (error "Cannot move column further right"))
8673 (goto-char beg)
8674 (while (< (point) end)
8675 (if (org-at-table-hline-p)
8677 (org-table-goto-column col1 t)
8678 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8679 (replace-match "|\\2|\\1|")))
8680 (beginning-of-line 2))
8681 (move-marker end nil)
8682 (goto-line linepos)
8683 (org-table-goto-column colpos)
8684 (org-table-align)
8685 (org-table-fix-formulas
8686 "$" (list (cons (number-to-string col) (number-to-string colpos))
8687 (cons (number-to-string colpos) (number-to-string col))))))
8689 (defun org-table-move-row-down ()
8690 "Move table row down."
8691 (interactive)
8692 (org-table-move-row nil))
8693 (defun org-table-move-row-up ()
8694 "Move table row up."
8695 (interactive)
8696 (org-table-move-row 'up))
8698 (defun org-table-move-row (&optional up)
8699 "Move the current table line down. With arg UP, move it up."
8700 (interactive "P")
8701 (let* ((col (current-column))
8702 (pos (point))
8703 (hline1p (save-excursion (beginning-of-line 1)
8704 (looking-at org-table-hline-regexp)))
8705 (dline1 (org-table-current-dline))
8706 (dline2 (+ dline1 (if up -1 1)))
8707 (tonew (if up 0 2))
8708 txt hline2p)
8709 (beginning-of-line tonew)
8710 (unless (org-at-table-p)
8711 (goto-char pos)
8712 (error "Cannot move row further"))
8713 (setq hline2p (looking-at org-table-hline-regexp))
8714 (goto-char pos)
8715 (beginning-of-line 1)
8716 (setq pos (point))
8717 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
8718 (delete-region (point) (1+ (point-at-eol)))
8719 (beginning-of-line tonew)
8720 (insert txt)
8721 (beginning-of-line 0)
8722 (move-to-column col)
8723 (unless (or hline1p hline2p)
8724 (org-table-fix-formulas
8725 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
8726 (cons (number-to-string dline2) (number-to-string dline1)))))))
8728 (defun org-table-insert-row (&optional arg)
8729 "Insert a new row above the current line into the table.
8730 With prefix ARG, insert below the current line."
8731 (interactive "P")
8732 (if (not (org-at-table-p))
8733 (error "Not at a table"))
8734 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
8735 (new (org-table-clean-line line)))
8736 ;; Fix the first field if necessary
8737 (if (string-match "^[ \t]*| *[#$] *|" line)
8738 (setq new (replace-match (match-string 0 line) t t new)))
8739 (beginning-of-line (if arg 2 1))
8740 (let (org-table-may-need-update) (insert-before-markers new "\n"))
8741 (beginning-of-line 0)
8742 (re-search-forward "| ?" (point-at-eol) t)
8743 (and (or org-table-may-need-update org-table-overlay-coordinates)
8744 (org-table-align))
8745 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
8747 (defun org-table-insert-hline (&optional above)
8748 "Insert a horizontal-line below the current line into the table.
8749 With prefix ABOVE, insert above the current line."
8750 (interactive "P")
8751 (if (not (org-at-table-p))
8752 (error "Not at a table"))
8753 (let ((line (org-table-clean-line
8754 (buffer-substring (point-at-bol) (point-at-eol))))
8755 (col (current-column)))
8756 (while (string-match "|\\( +\\)|" line)
8757 (setq line (replace-match
8758 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
8759 ?-) "|") t t line)))
8760 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
8761 (beginning-of-line (if above 1 2))
8762 (insert line "\n")
8763 (beginning-of-line (if above 1 -1))
8764 (move-to-column col)
8765 (and org-table-overlay-coordinates (org-table-align))))
8767 (defun org-table-hline-and-move (&optional same-column)
8768 "Insert a hline and move to the row below that line."
8769 (interactive "P")
8770 (let ((col (org-table-current-column)))
8771 (org-table-maybe-eval-formula)
8772 (org-table-maybe-recalculate-line)
8773 (org-table-insert-hline)
8774 (end-of-line 2)
8775 (if (looking-at "\n[ \t]*|-")
8776 (progn (insert "\n|") (org-table-align))
8777 (org-table-next-field))
8778 (if same-column (org-table-goto-column col))))
8780 (defun org-table-clean-line (s)
8781 "Convert a table line S into a string with only \"|\" and space.
8782 In particular, this does handle wide and invisible characters."
8783 (if (string-match "^[ \t]*|-" s)
8784 ;; It's a hline, just map the characters
8785 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
8786 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
8787 (setq s (replace-match
8788 (concat "|" (make-string (org-string-width (match-string 1 s))
8789 ?\ ) "|")
8790 t t s)))
8793 (defun org-table-kill-row ()
8794 "Delete the current row or horizontal line from the table."
8795 (interactive)
8796 (if (not (org-at-table-p))
8797 (error "Not at a table"))
8798 (let ((col (current-column))
8799 (dline (org-table-current-dline)))
8800 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
8801 (if (not (org-at-table-p)) (beginning-of-line 0))
8802 (move-to-column col)
8803 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
8804 dline -1 dline)))
8806 (defun org-table-sort-lines (with-case &optional sorting-type)
8807 "Sort table lines according to the column at point.
8809 The position of point indicates the column to be used for
8810 sorting, and the range of lines is the range between the nearest
8811 horizontal separator lines, or the entire table of no such lines
8812 exist. If point is before the first column, you will be prompted
8813 for the sorting column. If there is an active region, the mark
8814 specifies the first line and the sorting column, while point
8815 should be in the last line to be included into the sorting.
8817 The command then prompts for the sorting type which can be
8818 alphabetically, numerically, or by time (as given in a time stamp
8819 in the field). Sorting in reverse order is also possible.
8821 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
8823 If SORTING-TYPE is specified when this function is called from a Lisp
8824 program, no prompting will take place. SORTING-TYPE must be a character,
8825 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
8826 should be done in reverse order."
8827 (interactive "P")
8828 (let* ((thisline (org-current-line))
8829 (thiscol (org-table-current-column))
8830 beg end bcol ecol tend tbeg column lns pos)
8831 (when (equal thiscol 0)
8832 (if (interactive-p)
8833 (setq thiscol
8834 (string-to-number
8835 (read-string "Use column N for sorting: ")))
8836 (setq thiscol 1))
8837 (org-table-goto-column thiscol))
8838 (org-table-check-inside-data-field)
8839 (if (org-region-active-p)
8840 (progn
8841 (setq beg (region-beginning) end (region-end))
8842 (goto-char beg)
8843 (setq column (org-table-current-column)
8844 beg (point-at-bol))
8845 (goto-char end)
8846 (setq end (point-at-bol 2)))
8847 (setq column (org-table-current-column)
8848 pos (point)
8849 tbeg (org-table-begin)
8850 tend (org-table-end))
8851 (if (re-search-backward org-table-hline-regexp tbeg t)
8852 (setq beg (point-at-bol 2))
8853 (goto-char tbeg)
8854 (setq beg (point-at-bol 1)))
8855 (goto-char pos)
8856 (if (re-search-forward org-table-hline-regexp tend t)
8857 (setq end (point-at-bol 1))
8858 (goto-char tend)
8859 (setq end (point-at-bol))))
8860 (setq beg (move-marker (make-marker) beg)
8861 end (move-marker (make-marker) end))
8862 (untabify beg end)
8863 (goto-char beg)
8864 (org-table-goto-column column)
8865 (skip-chars-backward "^|")
8866 (setq bcol (current-column))
8867 (org-table-goto-column (1+ column))
8868 (skip-chars-backward "^|")
8869 (setq ecol (1- (current-column)))
8870 (org-table-goto-column column)
8871 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
8872 (org-split-string (buffer-substring beg end) "\n")))
8873 (setq lns (org-do-sort lns "Table" with-case sorting-type))
8874 (delete-region beg end)
8875 (move-marker beg nil)
8876 (move-marker end nil)
8877 (insert (mapconcat 'cdr lns "\n") "\n")
8878 (goto-line thisline)
8879 (org-table-goto-column thiscol)
8880 (message "%d lines sorted, based on column %d" (length lns) column)))
8882 (defun org-table-cut-region (beg end)
8883 "Copy region in table to the clipboard and blank all relevant fields."
8884 (interactive "r")
8885 (org-table-copy-region beg end 'cut))
8887 (defun org-table-copy-region (beg end &optional cut)
8888 "Copy rectangular region in table to clipboard.
8889 A special clipboard is used which can only be accessed
8890 with `org-table-paste-rectangle'."
8891 (interactive "rP")
8892 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
8893 region cols
8894 (rpl (if cut " " nil)))
8895 (goto-char beg)
8896 (org-table-check-inside-data-field)
8897 (setq l01 (org-current-line)
8898 c01 (org-table-current-column))
8899 (goto-char end)
8900 (org-table-check-inside-data-field)
8901 (setq l02 (org-current-line)
8902 c02 (org-table-current-column))
8903 (setq l1 (min l01 l02) l2 (max l01 l02)
8904 c1 (min c01 c02) c2 (max c01 c02))
8905 (catch 'exit
8906 (while t
8907 (catch 'nextline
8908 (if (> l1 l2) (throw 'exit t))
8909 (goto-line l1)
8910 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
8911 (setq cols nil ic1 c1 ic2 c2)
8912 (while (< ic1 (1+ ic2))
8913 (push (org-table-get-field ic1 rpl) cols)
8914 (setq ic1 (1+ ic1)))
8915 (push (nreverse cols) region)
8916 (setq l1 (1+ l1)))))
8917 (setq org-table-clip (nreverse region))
8918 (if cut (org-table-align))
8919 org-table-clip))
8921 (defun org-table-paste-rectangle ()
8922 "Paste a rectangular region into a table.
8923 The upper right corner ends up in the current field. All involved fields
8924 will be overwritten. If the rectangle does not fit into the present table,
8925 the table is enlarged as needed. The process ignores horizontal separator
8926 lines."
8927 (interactive)
8928 (unless (and org-table-clip (listp org-table-clip))
8929 (error "First cut/copy a region to paste!"))
8930 (org-table-check-inside-data-field)
8931 (let* ((clip org-table-clip)
8932 (line (org-current-line))
8933 (col (org-table-current-column))
8934 (org-enable-table-editor t)
8935 (org-table-automatic-realign nil)
8936 c cols field)
8937 (while (setq cols (pop clip))
8938 (while (org-at-table-hline-p) (beginning-of-line 2))
8939 (if (not (org-at-table-p))
8940 (progn (end-of-line 0) (org-table-next-field)))
8941 (setq c col)
8942 (while (setq field (pop cols))
8943 (org-table-goto-column c nil 'force)
8944 (org-table-get-field nil field)
8945 (setq c (1+ c)))
8946 (beginning-of-line 2))
8947 (goto-line line)
8948 (org-table-goto-column col)
8949 (org-table-align)))
8951 (defun org-table-convert ()
8952 "Convert from `org-mode' table to table.el and back.
8953 Obviously, this only works within limits. When an Org-mode table is
8954 converted to table.el, all horizontal separator lines get lost, because
8955 table.el uses these as cell boundaries and has no notion of horizontal lines.
8956 A table.el table can be converted to an Org-mode table only if it does not
8957 do row or column spanning. Multiline cells will become multiple cells.
8958 Beware, Org-mode does not test if the table can be successfully converted - it
8959 blindly applies a recipe that works for simple tables."
8960 (interactive)
8961 (require 'table)
8962 (if (org-at-table.el-p)
8963 ;; convert to Org-mode table
8964 (let ((beg (move-marker (make-marker) (org-table-begin t)))
8965 (end (move-marker (make-marker) (org-table-end t))))
8966 (table-unrecognize-region beg end)
8967 (goto-char beg)
8968 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
8969 (replace-match ""))
8970 (goto-char beg))
8971 (if (org-at-table-p)
8972 ;; convert to table.el table
8973 (let ((beg (move-marker (make-marker) (org-table-begin)))
8974 (end (move-marker (make-marker) (org-table-end))))
8975 ;; first, get rid of all horizontal lines
8976 (goto-char beg)
8977 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
8978 (replace-match ""))
8979 ;; insert a hline before first
8980 (goto-char beg)
8981 (org-table-insert-hline 'above)
8982 (beginning-of-line -1)
8983 ;; insert a hline after each line
8984 (while (progn (beginning-of-line 3) (< (point) end))
8985 (org-table-insert-hline))
8986 (goto-char beg)
8987 (setq end (move-marker end (org-table-end)))
8988 ;; replace "+" at beginning and ending of hlines
8989 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
8990 (replace-match "\\1+-"))
8991 (goto-char beg)
8992 (while (re-search-forward "-|[ \t]*$" end t)
8993 (replace-match "-+"))
8994 (goto-char beg)))))
8996 (defun org-table-wrap-region (arg)
8997 "Wrap several fields in a column like a paragraph.
8998 This is useful if you'd like to spread the contents of a field over several
8999 lines, in order to keep the table compact.
9001 If there is an active region, and both point and mark are in the same column,
9002 the text in the column is wrapped to minimum width for the given number of
9003 lines. Generally, this makes the table more compact. A prefix ARG may be
9004 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9005 formats the selected text to two lines. If the region was longer than two
9006 lines, the remaining lines remain empty. A negative prefix argument reduces
9007 the current number of lines by that amount. The wrapped text is pasted back
9008 into the table. If you formatted it to more lines than it was before, fields
9009 further down in the table get overwritten - so you might need to make space in
9010 the table first.
9012 If there is no region, the current field is split at the cursor position and
9013 the text fragment to the right of the cursor is prepended to the field one
9014 line down.
9016 If there is no region, but you specify a prefix ARG, the current field gets
9017 blank, and the content is appended to the field above."
9018 (interactive "P")
9019 (org-table-check-inside-data-field)
9020 (if (org-region-active-p)
9021 ;; There is a region: fill as a paragraph
9022 (let* ((beg (region-beginning))
9023 (cline (save-excursion (goto-char beg) (org-current-line)))
9024 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9025 nlines)
9026 (org-table-cut-region (region-beginning) (region-end))
9027 (if (> (length (car org-table-clip)) 1)
9028 (error "Region must be limited to single column"))
9029 (setq nlines (if arg
9030 (if (< arg 1)
9031 (+ (length org-table-clip) arg)
9032 arg)
9033 (length org-table-clip)))
9034 (setq org-table-clip
9035 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9036 nil nlines)))
9037 (goto-line cline)
9038 (org-table-goto-column ccol)
9039 (org-table-paste-rectangle))
9040 ;; No region, split the current field at point
9041 (if arg
9042 ;; combine with field above
9043 (let ((s (org-table-blank-field))
9044 (col (org-table-current-column)))
9045 (beginning-of-line 0)
9046 (while (org-at-table-hline-p) (beginning-of-line 0))
9047 (org-table-goto-column col)
9048 (skip-chars-forward "^|")
9049 (skip-chars-backward " ")
9050 (insert " " (org-trim s))
9051 (org-table-align))
9052 ;; split field
9053 (when (looking-at "\\([^|]+\\)+|")
9054 (let ((s (match-string 1)))
9055 (replace-match " |")
9056 (goto-char (match-beginning 0))
9057 (org-table-next-row)
9058 (insert (org-trim s) " ")
9059 (org-table-align))))))
9061 (defvar org-field-marker nil)
9063 (defun org-table-edit-field (arg)
9064 "Edit table field in a different window.
9065 This is mainly useful for fields that contain hidden parts.
9066 When called with a \\[universal-argument] prefix, just make the full field visible so that
9067 it can be edited in place."
9068 (interactive "P")
9069 (if arg
9070 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9071 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9072 (remove-text-properties b e '(org-cwidth t invisible t
9073 display t intangible t))
9074 (if (and (boundp 'font-lock-mode) font-lock-mode)
9075 (font-lock-fontify-block)))
9076 (let ((pos (move-marker (make-marker) (point)))
9077 (field (org-table-get-field))
9078 (cw (current-window-configuration))
9080 (org-switch-to-buffer-other-window "*Org tmp*")
9081 (erase-buffer)
9082 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9083 (let ((org-inhibit-startup t)) (org-mode))
9084 (goto-char (setq p (point-max)))
9085 (insert (org-trim field))
9086 (remove-text-properties p (point-max)
9087 '(invisible t org-cwidth t display t
9088 intangible t))
9089 (goto-char p)
9090 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9091 (org-set-local 'org-window-configuration cw)
9092 (org-set-local 'org-field-marker pos)
9093 (message "Edit and finish with C-c C-c"))))
9095 (defun org-table-finish-edit-field ()
9096 "Finish editing a table data field.
9097 Remove all newline characters, insert the result into the table, realign
9098 the table and kill the editing buffer."
9099 (let ((pos org-field-marker)
9100 (cw org-window-configuration)
9101 (cb (current-buffer))
9102 text)
9103 (goto-char (point-min))
9104 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9105 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9106 (replace-match " "))
9107 (setq text (org-trim (buffer-string)))
9108 (set-window-configuration cw)
9109 (kill-buffer cb)
9110 (select-window (get-buffer-window (marker-buffer pos)))
9111 (goto-char pos)
9112 (move-marker pos nil)
9113 (org-table-check-inside-data-field)
9114 (org-table-get-field nil text)
9115 (org-table-align)
9116 (message "New field value inserted")))
9118 (defun org-trim (s)
9119 "Remove whitespace at beginning and end of string."
9120 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9121 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9124 (defun org-wrap (string &optional width lines)
9125 "Wrap string to either a number of lines, or a width in characters.
9126 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9127 that costs. If there is a word longer than WIDTH, the text is actually
9128 wrapped to the length of that word.
9129 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9130 many lines, whatever width that takes.
9131 The return value is a list of lines, without newlines at the end."
9132 (let* ((words (org-split-string string "[ \t\n]+"))
9133 (maxword (apply 'max (mapcar 'org-string-width words)))
9134 w ll)
9135 (cond (width
9136 (org-do-wrap words (max maxword width)))
9137 (lines
9138 (setq w maxword)
9139 (setq ll (org-do-wrap words maxword))
9140 (if (<= (length ll) lines)
9142 (setq ll words)
9143 (while (> (length ll) lines)
9144 (setq w (1+ w))
9145 (setq ll (org-do-wrap words w)))
9146 ll))
9147 (t (error "Cannot wrap this")))))
9150 (defun org-do-wrap (words width)
9151 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9152 (let (lines line)
9153 (while words
9154 (setq line (pop words))
9155 (while (and words (< (+ (length line) (length (car words))) width))
9156 (setq line (concat line " " (pop words))))
9157 (setq lines (push line lines)))
9158 (nreverse lines)))
9160 (defun org-split-string (string &optional separators)
9161 "Splits STRING into substrings at SEPARATORS.
9162 No empty strings are returned if there are matches at the beginning
9163 and end of string."
9164 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9165 (start 0)
9166 notfirst
9167 (list nil))
9168 (while (and (string-match rexp string
9169 (if (and notfirst
9170 (= start (match-beginning 0))
9171 (< start (length string)))
9172 (1+ start) start))
9173 (< (match-beginning 0) (length string)))
9174 (setq notfirst t)
9175 (or (eq (match-beginning 0) 0)
9176 (and (eq (match-beginning 0) (match-end 0))
9177 (eq (match-beginning 0) start))
9178 (setq list
9179 (cons (substring string start (match-beginning 0))
9180 list)))
9181 (setq start (match-end 0)))
9182 (or (eq start (length string))
9183 (setq list
9184 (cons (substring string start)
9185 list)))
9186 (nreverse list)))
9188 (defun org-table-map-tables (function)
9189 "Apply FUNCTION to the start of all tables in the buffer."
9190 (save-excursion
9191 (save-restriction
9192 (widen)
9193 (goto-char (point-min))
9194 (while (re-search-forward org-table-any-line-regexp nil t)
9195 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9196 (beginning-of-line 1)
9197 (if (looking-at org-table-line-regexp)
9198 (save-excursion (funcall function)))
9199 (re-search-forward org-table-any-border-regexp nil 1))))
9200 (message "Mapping tables: done"))
9202 (defvar org-timecnt) ; dynamically scoped parameter
9204 (defun org-table-sum (&optional beg end nlast)
9205 "Sum numbers in region of current table column.
9206 The result will be displayed in the echo area, and will be available
9207 as kill to be inserted with \\[yank].
9209 If there is an active region, it is interpreted as a rectangle and all
9210 numbers in that rectangle will be summed. If there is no active
9211 region and point is located in a table column, sum all numbers in that
9212 column.
9214 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9215 numbers are assumed to be times as well (in decimal hours) and the
9216 numbers are added as such.
9218 If NLAST is a number, only the NLAST fields will actually be summed."
9219 (interactive)
9220 (save-excursion
9221 (let (col (org-timecnt 0) diff h m s org-table-clip)
9222 (cond
9223 ((and beg end)) ; beg and end given explicitly
9224 ((org-region-active-p)
9225 (setq beg (region-beginning) end (region-end)))
9227 (setq col (org-table-current-column))
9228 (goto-char (org-table-begin))
9229 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9230 (error "No table data"))
9231 (org-table-goto-column col)
9232 (setq beg (point))
9233 (goto-char (org-table-end))
9234 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9235 (error "No table data"))
9236 (org-table-goto-column col)
9237 (setq end (point))))
9238 (let* ((items (apply 'append (org-table-copy-region beg end)))
9239 (items1 (cond ((not nlast) items)
9240 ((>= nlast (length items)) items)
9241 (t (setq items (reverse items))
9242 (setcdr (nthcdr (1- nlast) items) nil)
9243 (nreverse items))))
9244 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9245 items1)))
9246 (res (apply '+ numbers))
9247 (sres (if (= org-timecnt 0)
9248 (format "%g" res)
9249 (setq diff (* 3600 res)
9250 h (floor (/ diff 3600)) diff (mod diff 3600)
9251 m (floor (/ diff 60)) diff (mod diff 60)
9252 s diff)
9253 (format "%d:%02d:%02d" h m s))))
9254 (kill-new sres)
9255 (if (interactive-p)
9256 (message "%s"
9257 (substitute-command-keys
9258 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9259 (length numbers) sres))))
9260 sres))))
9262 (defun org-table-get-number-for-summing (s)
9263 (let (n)
9264 (if (string-match "^ *|? *" s)
9265 (setq s (replace-match "" nil nil s)))
9266 (if (string-match " *|? *$" s)
9267 (setq s (replace-match "" nil nil s)))
9268 (setq n (string-to-number s))
9269 (cond
9270 ((and (string-match "0" s)
9271 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9272 ((string-match "\\`[ \t]+\\'" s) nil)
9273 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9274 (let ((h (string-to-number (or (match-string 1 s) "0")))
9275 (m (string-to-number (or (match-string 2 s) "0")))
9276 (s (string-to-number (or (match-string 4 s) "0"))))
9277 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9278 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9279 ((equal n 0) nil)
9280 (t n))))
9282 (defun org-table-current-field-formula (&optional key noerror)
9283 "Return the formula active for the current field.
9284 Assumes that specials are in place.
9285 If KEY is given, return the key to this formula.
9286 Otherwise return the formula preceeded with \"=\" or \":=\"."
9287 (let* ((name (car (rassoc (list (org-current-line)
9288 (org-table-current-column))
9289 org-table-named-field-locations)))
9290 (col (org-table-current-column))
9291 (scol (int-to-string col))
9292 (ref (format "@%d$%d" (org-table-current-dline) col))
9293 (stored-list (org-table-get-stored-formulas noerror))
9294 (ass (or (assoc name stored-list)
9295 (assoc ref stored-list)
9296 (assoc scol stored-list))))
9297 (if key
9298 (car ass)
9299 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9300 (cdr ass))))))
9302 (defun org-table-get-formula (&optional equation named)
9303 "Read a formula from the minibuffer, offer stored formula as default.
9304 When NAMED is non-nil, look for a named equation."
9305 (let* ((stored-list (org-table-get-stored-formulas))
9306 (name (car (rassoc (list (org-current-line)
9307 (org-table-current-column))
9308 org-table-named-field-locations)))
9309 (ref (format "@%d$%d" (org-table-current-dline)
9310 (org-table-current-column)))
9311 (refass (assoc ref stored-list))
9312 (scol (if named
9313 (if name name ref)
9314 (int-to-string (org-table-current-column))))
9315 (dummy (and (or name refass) (not named)
9316 (not (y-or-n-p "Replace field formula with column formula? " ))
9317 (error "Abort")))
9318 (name (or name ref))
9319 (org-table-may-need-update nil)
9320 (stored (cdr (assoc scol stored-list)))
9321 (eq (cond
9322 ((and stored equation (string-match "^ *=? *$" equation))
9323 stored)
9324 ((stringp equation)
9325 equation)
9326 (t (org-table-formula-from-user
9327 (read-string
9328 (org-table-formula-to-user
9329 (format "%s formula %s%s="
9330 (if named "Field" "Column")
9331 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9332 scol))
9333 (if stored (org-table-formula-to-user stored) "")
9334 'org-table-formula-history
9335 )))))
9336 mustsave)
9337 (when (not (string-match "\\S-" eq))
9338 ;; remove formula
9339 (setq stored-list (delq (assoc scol stored-list) stored-list))
9340 (org-table-store-formulas stored-list)
9341 (error "Formula removed"))
9342 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9343 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9344 (if (and name (not named))
9345 ;; We set the column equation, delete the named one.
9346 (setq stored-list (delq (assoc name stored-list) stored-list)
9347 mustsave t))
9348 (if stored
9349 (setcdr (assoc scol stored-list) eq)
9350 (setq stored-list (cons (cons scol eq) stored-list)))
9351 (if (or mustsave (not (equal stored eq)))
9352 (org-table-store-formulas stored-list))
9353 eq))
9355 (defun org-table-store-formulas (alist)
9356 "Store the list of formulas below the current table."
9357 (setq alist (sort alist 'org-table-formula-less-p))
9358 (save-excursion
9359 (goto-char (org-table-end))
9360 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9361 (progn
9362 ;; don't overwrite TBLFM, we might use text properties to store stuff
9363 (goto-char (match-beginning 2))
9364 (delete-region (match-beginning 2) (match-end 0)))
9365 (insert "#+TBLFM:"))
9366 (insert " "
9367 (mapconcat (lambda (x)
9368 (concat
9369 (if (equal (string-to-char (car x)) ?@) "" "$")
9370 (car x) "=" (cdr x)))
9371 alist "::")
9372 "\n")))
9374 (defsubst org-table-formula-make-cmp-string (a)
9375 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9376 (concat
9377 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9378 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9379 (if (match-end 5) (concat "@@" (match-string 5 a))))))
9381 (defun org-table-formula-less-p (a b)
9382 "Compare two formulas for sorting."
9383 (let ((as (org-table-formula-make-cmp-string (car a)))
9384 (bs (org-table-formula-make-cmp-string (car b))))
9385 (and as bs (string< as bs))))
9387 (defun org-table-get-stored-formulas (&optional noerror)
9388 "Return an alist with the stored formulas directly after current table."
9389 (interactive)
9390 (let (scol eq eq-alist strings string seen)
9391 (save-excursion
9392 (goto-char (org-table-end))
9393 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9394 (setq strings (org-split-string (match-string 2) " *:: *"))
9395 (while (setq string (pop strings))
9396 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
9397 (setq scol (if (match-end 2)
9398 (match-string 2 string)
9399 (match-string 1 string))
9400 eq (match-string 3 string)
9401 eq-alist (cons (cons scol eq) eq-alist))
9402 (if (member scol seen)
9403 (if noerror
9404 (progn
9405 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9406 (ding)
9407 (sit-for 2))
9408 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
9409 (push scol seen))))))
9410 (nreverse eq-alist)))
9412 (defun org-table-fix-formulas (key replace &optional limit delta remove)
9413 "Modify the equations after the table structure has been edited.
9414 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
9415 For all numbers larger than LIMIT, shift them by DELTA."
9416 (save-excursion
9417 (goto-char (org-table-end))
9418 (when (looking-at "#\\+TBLFM:")
9419 (let ((re (concat key "\\([0-9]+\\)"))
9420 (re2
9421 (when remove
9422 (if (equal key "$")
9423 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
9424 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
9425 s n a)
9426 (when remove
9427 (while (re-search-forward re2 (point-at-eol) t)
9428 (replace-match "")))
9429 (while (re-search-forward re (point-at-eol) t)
9430 (setq s (match-string 1) n (string-to-number s))
9431 (cond
9432 ((setq a (assoc s replace))
9433 (replace-match (concat key (cdr a)) t t))
9434 ((and limit (> n limit))
9435 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
9437 (defun org-table-get-specials ()
9438 "Get the column names and local parameters for this table."
9439 (save-excursion
9440 (let ((beg (org-table-begin)) (end (org-table-end))
9441 names name fields fields1 field cnt
9442 c v l line col types dlines hlines)
9443 (setq org-table-column-names nil
9444 org-table-local-parameters nil
9445 org-table-named-field-locations nil
9446 org-table-current-begin-line nil
9447 org-table-current-begin-pos nil
9448 org-table-current-line-types nil)
9449 (goto-char beg)
9450 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9451 (setq names (org-split-string (match-string 1) " *| *")
9452 cnt 1)
9453 (while (setq name (pop names))
9454 (setq cnt (1+ cnt))
9455 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9456 (push (cons name (int-to-string cnt)) org-table-column-names))))
9457 (setq org-table-column-names (nreverse org-table-column-names))
9458 (setq org-table-column-name-regexp
9459 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9460 (goto-char beg)
9461 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9462 (setq fields (org-split-string (match-string 1) " *| *"))
9463 (while (setq field (pop fields))
9464 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9465 (push (cons (match-string 1 field) (match-string 2 field))
9466 org-table-local-parameters))))
9467 (goto-char beg)
9468 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9469 (setq c (match-string 1)
9470 fields (org-split-string (match-string 2) " *| *"))
9471 (save-excursion
9472 (beginning-of-line (if (equal c "_") 2 0))
9473 (setq line (org-current-line) col 1)
9474 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9475 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9476 (while (and fields1 (setq field (pop fields)))
9477 (setq v (pop fields1) col (1+ col))
9478 (when (and (stringp field) (stringp v)
9479 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9480 (push (cons field v) org-table-local-parameters)
9481 (push (list field line col) org-table-named-field-locations))))
9482 ;; Analyse the line types
9483 (goto-char beg)
9484 (setq org-table-current-begin-line (org-current-line)
9485 org-table-current-begin-pos (point)
9486 l org-table-current-begin-line)
9487 (while (looking-at "[ \t]*|\\(-\\)?")
9488 (push (if (match-end 1) 'hline 'dline) types)
9489 (if (match-end 1) (push l hlines) (push l dlines))
9490 (beginning-of-line 2)
9491 (setq l (1+ l)))
9492 (setq org-table-current-line-types (apply 'vector (nreverse types))
9493 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
9494 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
9496 (defun org-table-maybe-eval-formula ()
9497 "Check if the current field starts with \"=\" or \":=\".
9498 If yes, store the formula and apply it."
9499 ;; We already know we are in a table. Get field will only return a formula
9500 ;; when appropriate. It might return a separator line, but no problem.
9501 (when org-table-formula-evaluate-inline
9502 (let* ((field (org-trim (or (org-table-get-field) "")))
9503 named eq)
9504 (when (string-match "^:?=\\(.*\\)" field)
9505 (setq named (equal (string-to-char field) ?:)
9506 eq (match-string 1 field))
9507 (if (or (fboundp 'calc-eval)
9508 (equal (substring eq 0 (min 2 (length eq))) "'("))
9509 (org-table-eval-formula (if named '(4) nil)
9510 (org-table-formula-from-user eq))
9511 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
9513 (defvar org-recalc-commands nil
9514 "List of commands triggering the recalculation of a line.
9515 Will be filled automatically during use.")
9517 (defvar org-recalc-marks
9518 '((" " . "Unmarked: no special line, no automatic recalculation")
9519 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9520 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9521 ("!" . "Column name definition line. Reference in formula as $name.")
9522 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9523 ("_" . "Names for values in row below this one.")
9524 ("^" . "Names for values in row above this one.")))
9526 (defun org-table-rotate-recalc-marks (&optional newchar)
9527 "Rotate the recalculation mark in the first column.
9528 If in any row, the first field is not consistent with a mark,
9529 insert a new column for the markers.
9530 When there is an active region, change all the lines in the region,
9531 after prompting for the marking character.
9532 After each change, a message will be displayed indicating the meaning
9533 of the new mark."
9534 (interactive)
9535 (unless (org-at-table-p) (error "Not at a table"))
9536 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9537 (beg (org-table-begin))
9538 (end (org-table-end))
9539 (l (org-current-line))
9540 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9541 (l2 (if (org-region-active-p) (org-current-line (region-end))))
9542 (have-col
9543 (save-excursion
9544 (goto-char beg)
9545 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
9546 (col (org-table-current-column))
9547 (forcenew (car (assoc newchar org-recalc-marks)))
9548 epos new)
9549 (when l1
9550 (message "Change region to what mark? Type # * ! $ or SPC: ")
9551 (setq newchar (char-to-string (read-char-exclusive))
9552 forcenew (car (assoc newchar org-recalc-marks))))
9553 (if (and newchar (not forcenew))
9554 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
9555 newchar))
9556 (if l1 (goto-line l1))
9557 (save-excursion
9558 (beginning-of-line 1)
9559 (unless (looking-at org-table-dataline-regexp)
9560 (error "Not at a table data line")))
9561 (unless have-col
9562 (org-table-goto-column 1)
9563 (org-table-insert-column)
9564 (org-table-goto-column (1+ col)))
9565 (setq epos (point-at-eol))
9566 (save-excursion
9567 (beginning-of-line 1)
9568 (org-table-get-field
9569 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
9570 (concat " "
9571 (setq new (or forcenew
9572 (cadr (member (match-string 1) marks))))
9573 " ")
9574 " # ")))
9575 (if (and l1 l2)
9576 (progn
9577 (goto-line l1)
9578 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
9579 (and (looking-at org-table-dataline-regexp)
9580 (org-table-get-field 1 (concat " " new " "))))
9581 (goto-line l1)))
9582 (if (not (= epos (point-at-eol))) (org-table-align))
9583 (goto-line l)
9584 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
9586 (defun org-table-maybe-recalculate-line ()
9587 "Recompute the current line if marked for it, and if we haven't just done it."
9588 (interactive)
9589 (and org-table-allow-automatic-line-recalculation
9590 (not (and (memq last-command org-recalc-commands)
9591 (equal org-last-recalc-line (org-current-line))))
9592 (save-excursion (beginning-of-line 1)
9593 (looking-at org-table-auto-recalculate-regexp))
9594 (org-table-recalculate) t))
9596 (defvar org-table-formula-debug nil
9597 "Non-nil means, debug table formulas.
9598 When nil, simply write \"#ERROR\" in corrupted fields.")
9599 (make-variable-buffer-local 'org-table-formula-debug)
9601 (defvar modes)
9602 (defsubst org-set-calc-mode (var &optional value)
9603 (if (stringp var)
9604 (setq var (assoc var '(("D" calc-angle-mode deg)
9605 ("R" calc-angle-mode rad)
9606 ("F" calc-prefer-frac t)
9607 ("S" calc-symbolic-mode t)))
9608 value (nth 2 var) var (nth 1 var)))
9609 (if (memq var modes)
9610 (setcar (cdr (memq var modes)) value)
9611 (cons var (cons value modes)))
9612 modes)
9614 (defun org-table-eval-formula (&optional arg equation
9615 suppress-align suppress-const
9616 suppress-store suppress-analysis)
9617 "Replace the table field value at the cursor by the result of a calculation.
9619 This function makes use of Dave Gillespie's Calc package, in my view the
9620 most exciting program ever written for GNU Emacs. So you need to have Calc
9621 installed in order to use this function.
9623 In a table, this command replaces the value in the current field with the
9624 result of a formula. It also installs the formula as the \"current\" column
9625 formula, by storing it in a special line below the table. When called
9626 with a `C-u' prefix, the current field must ba a named field, and the
9627 formula is installed as valid in only this specific field.
9629 When called with two `C-u' prefixes, insert the active equation
9630 for the field back into the current field, so that it can be
9631 edited there. This is useful in order to use \\[org-table-show-reference]
9632 to check the referenced fields.
9634 When called, the command first prompts for a formula, which is read in
9635 the minibuffer. Previously entered formulas are available through the
9636 history list, and the last used formula is offered as a default.
9637 These stored formulas are adapted correctly when moving, inserting, or
9638 deleting columns with the corresponding commands.
9640 The formula can be any algebraic expression understood by the Calc package.
9641 For details, see the Org-mode manual.
9643 This function can also be called from Lisp programs and offers
9644 additional arguments: EQUATION can be the formula to apply. If this
9645 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
9646 used to speed-up recursive calls by by-passing unnecessary aligns.
9647 SUPPRESS-CONST suppresses the interpretation of constants in the
9648 formula, assuming that this has been done already outside the function.
9649 SUPPRESS-STORE means the formula should not be stored, either because
9650 it is already stored, or because it is a modified equation that should
9651 not overwrite the stored one."
9652 (interactive "P")
9653 (org-table-check-inside-data-field)
9654 (or suppress-analysis (org-table-get-specials))
9655 (if (equal arg '(16))
9656 (let ((eq (org-table-current-field-formula)))
9657 (or eq (error "No equation active for current field"))
9658 (org-table-get-field nil eq)
9659 (org-table-align)
9660 (setq org-table-may-need-update t))
9661 (let* (fields
9662 (ndown (if (integerp arg) arg 1))
9663 (org-table-automatic-realign nil)
9664 (case-fold-search nil)
9665 (down (> ndown 1))
9666 (formula (if (and equation suppress-store)
9667 equation
9668 (org-table-get-formula equation (equal arg '(4)))))
9669 (n0 (org-table-current-column))
9670 (modes (copy-sequence org-calc-default-modes))
9671 (numbers nil) ; was a variable, now fixed default
9672 (keep-empty nil)
9673 n form form0 bw fmt x ev orig c lispp literal)
9674 ;; Parse the format string. Since we have a lot of modes, this is
9675 ;; a lot of work. However, I think calc still uses most of the time.
9676 (if (string-match ";" formula)
9677 (let ((tmp (org-split-string formula ";")))
9678 (setq formula (car tmp)
9679 fmt (concat (cdr (assoc "%" org-table-local-parameters))
9680 (nth 1 tmp)))
9681 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
9682 (setq c (string-to-char (match-string 1 fmt))
9683 n (string-to-number (match-string 2 fmt)))
9684 (if (= c ?p)
9685 (setq modes (org-set-calc-mode 'calc-internal-prec n))
9686 (setq modes (org-set-calc-mode
9687 'calc-float-format
9688 (list (cdr (assoc c '((?n . float) (?f . fix)
9689 (?s . sci) (?e . eng))))
9690 n))))
9691 (setq fmt (replace-match "" t t fmt)))
9692 (if (string-match "[NT]" fmt)
9693 (setq numbers (equal (match-string 0 fmt) "N")
9694 fmt (replace-match "" t t fmt)))
9695 (if (string-match "L" fmt)
9696 (setq literal t
9697 fmt (replace-match "" t t fmt)))
9698 (if (string-match "E" fmt)
9699 (setq keep-empty t
9700 fmt (replace-match "" t t fmt)))
9701 (while (string-match "[DRFS]" fmt)
9702 (setq modes (org-set-calc-mode (match-string 0 fmt)))
9703 (setq fmt (replace-match "" t t fmt)))
9704 (unless (string-match "\\S-" fmt)
9705 (setq fmt nil))))
9706 (if (and (not suppress-const) org-table-formula-use-constants)
9707 (setq formula (org-table-formula-substitute-names formula)))
9708 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
9709 (while (> ndown 0)
9710 (setq fields (org-split-string
9711 (org-no-properties
9712 (buffer-substring (point-at-bol) (point-at-eol)))
9713 " *| *"))
9714 (if (eq numbers t)
9715 (setq fields (mapcar
9716 (lambda (x) (number-to-string (string-to-number x)))
9717 fields)))
9718 (setq ndown (1- ndown))
9719 (setq form (copy-sequence formula)
9720 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
9721 (if (and lispp literal) (setq lispp 'literal))
9722 ;; Check for old vertical references
9723 (setq form (org-rewrite-old-row-references form))
9724 ;; Insert complex ranges
9725 (while (string-match org-table-range-regexp form)
9726 (setq form
9727 (replace-match
9728 (save-match-data
9729 (org-table-make-reference
9730 (org-table-get-range (match-string 0 form) nil n0)
9731 keep-empty numbers lispp))
9732 t t form)))
9733 ;; Insert simple ranges
9734 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
9735 (setq form
9736 (replace-match
9737 (save-match-data
9738 (org-table-make-reference
9739 (org-sublist
9740 fields (string-to-number (match-string 1 form))
9741 (string-to-number (match-string 2 form)))
9742 keep-empty numbers lispp))
9743 t t form)))
9744 (setq form0 form)
9745 ;; Insert the references to fields in same row
9746 (while (string-match "\\$\\([0-9]+\\)" form)
9747 (setq n (string-to-number (match-string 1 form))
9748 x (nth (1- (if (= n 0) n0 n)) fields))
9749 (unless x (error "Invalid field specifier \"%s\""
9750 (match-string 0 form)))
9751 (setq form (replace-match
9752 (save-match-data
9753 (org-table-make-reference x nil numbers lispp))
9754 t t form)))
9756 (if lispp
9757 (setq ev (condition-case nil
9758 (eval (eval (read form)))
9759 (error "#ERROR"))
9760 ev (if (numberp ev) (number-to-string ev) ev))
9761 (or (fboundp 'calc-eval)
9762 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
9763 (setq ev (calc-eval (cons form modes)
9764 (if numbers 'num))))
9766 (when org-table-formula-debug
9767 (with-output-to-temp-buffer "*Substitution History*"
9768 (princ (format "Substitution history of formula
9769 Orig: %s
9770 $xyz-> %s
9771 @r$c-> %s
9772 $1-> %s\n" orig formula form0 form))
9773 (if (listp ev)
9774 (princ (format " %s^\nError: %s"
9775 (make-string (car ev) ?\-) (nth 1 ev)))
9776 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
9777 ev (or fmt "NONE")
9778 (if fmt (format fmt (string-to-number ev)) ev)))))
9779 (setq bw (get-buffer-window "*Substitution History*"))
9780 (shrink-window-if-larger-than-buffer bw)
9781 (unless (and (interactive-p) (not ndown))
9782 (unless (let (inhibit-redisplay)
9783 (y-or-n-p "Debugging Formula. Continue to next? "))
9784 (org-table-align)
9785 (error "Abort"))
9786 (delete-window bw)
9787 (message "")))
9788 (if (listp ev) (setq fmt nil ev "#ERROR"))
9789 (org-table-justify-field-maybe
9790 (if fmt (format fmt (string-to-number ev)) ev))
9791 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
9792 (call-interactively 'org-return)
9793 (setq ndown 0)))
9794 (and down (org-table-maybe-recalculate-line))
9795 (or suppress-align (and org-table-may-need-update
9796 (org-table-align))))))
9798 (defun org-table-put-field-property (prop value)
9799 (save-excursion
9800 (put-text-property (progn (skip-chars-backward "^|") (point))
9801 (progn (skip-chars-forward "^|") (point))
9802 prop value)))
9804 (defun org-table-get-range (desc &optional tbeg col highlight)
9805 "Get a calc vector from a column, accorting to descriptor DESC.
9806 Optional arguments TBEG and COL can give the beginning of the table and
9807 the current column, to avoid unnecessary parsing.
9808 HIGHLIGHT means, just highlight the range."
9809 (if (not (equal (string-to-char desc) ?@))
9810 (setq desc (concat "@" desc)))
9811 (save-excursion
9812 (or tbeg (setq tbeg (org-table-begin)))
9813 (or col (setq col (org-table-current-column)))
9814 (let ((thisline (org-current-line))
9815 beg end c1 c2 r1 r2 rangep tmp)
9816 (unless (string-match org-table-range-regexp desc)
9817 (error "Invalid table range specifier `%s'" desc))
9818 (setq rangep (match-end 3)
9819 r1 (and (match-end 1) (match-string 1 desc))
9820 r2 (and (match-end 4) (match-string 4 desc))
9821 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
9822 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
9824 (and c1 (setq c1 (+ (string-to-number c1)
9825 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
9826 (and c2 (setq c2 (+ (string-to-number c2)
9827 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
9828 (if (equal r1 "") (setq r1 nil))
9829 (if (equal r2 "") (setq r2 nil))
9830 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
9831 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
9832 ; (setq r2 (or r2 r1) c2 (or c2 c1))
9833 (if (not r1) (setq r1 thisline))
9834 (if (not r2) (setq r2 thisline))
9835 (if (not c1) (setq c1 col))
9836 (if (not c2) (setq c2 col))
9837 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
9838 ;; just one field
9839 (progn
9840 (goto-line r1)
9841 (while (not (looking-at org-table-dataline-regexp))
9842 (beginning-of-line 2))
9843 (prog1 (org-trim (org-table-get-field c1))
9844 (if highlight (org-table-highlight-rectangle (point) (point)))))
9845 ;; A range, return a vector
9846 ;; First sort the numbers to get a regular ractangle
9847 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
9848 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
9849 (goto-line r1)
9850 (while (not (looking-at org-table-dataline-regexp))
9851 (beginning-of-line 2))
9852 (org-table-goto-column c1)
9853 (setq beg (point))
9854 (goto-line r2)
9855 (while (not (looking-at org-table-dataline-regexp))
9856 (beginning-of-line 0))
9857 (org-table-goto-column c2)
9858 (setq end (point))
9859 (if highlight
9860 (org-table-highlight-rectangle
9861 beg (progn (skip-chars-forward "^|\n") (point))))
9862 ;; return string representation of calc vector
9863 (mapcar 'org-trim
9864 (apply 'append (org-table-copy-region beg end)))))))
9866 (defun org-table-get-descriptor-line (desc &optional cline bline table)
9867 "Analyze descriptor DESC and retrieve the corresponding line number.
9868 The cursor is currently in line CLINE, the table begins in line BLINE,
9869 and TABLE is a vector with line types."
9870 (if (string-match "^[0-9]+$" desc)
9871 (aref org-table-dlines (string-to-number desc))
9872 (setq cline (or cline (org-current-line))
9873 bline (or bline org-table-current-begin-line)
9874 table (or table org-table-current-line-types))
9875 (if (or
9876 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
9877 ;; 1 2 3 4 5 6
9878 (and (not (match-end 3)) (not (match-end 6)))
9879 (and (match-end 3) (match-end 6) (not (match-end 5))))
9880 (error "invalid row descriptor `%s'" desc))
9881 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
9882 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
9883 (odir (and (match-end 5) (match-string 5 desc)))
9884 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
9885 (i (- cline bline))
9886 (rel (and (match-end 6)
9887 (or (and (match-end 1) (not (match-end 3)))
9888 (match-end 5)))))
9889 (if (and hn (not hdir))
9890 (progn
9891 (setq i 0 hdir "+")
9892 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
9893 (if (and (not hn) on (not odir))
9894 (error "should never happen");;(aref org-table-dlines on)
9895 (if (and hn (> hn 0))
9896 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
9897 (if on
9898 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
9899 (+ bline i)))))
9901 (defun org-find-row-type (table i type backwards relative n)
9902 (let ((l (length table)))
9903 (while (> n 0)
9904 (while (and (setq i (+ i (if backwards -1 1)))
9905 (>= i 0) (< i l)
9906 (not (eq (aref table i) type))
9907 (if (and relative (eq (aref table i) 'hline))
9908 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
9909 t)))
9910 (setq n (1- n)))
9911 (if (or (< i 0) (>= i l))
9912 (error "Row descriptior leads outside table")
9913 i)))
9915 (defun org-rewrite-old-row-references (s)
9916 (if (string-match "&[-+0-9I]" s)
9917 (error "Formula contains old &row reference, please rewrite using @-syntax")
9920 (defun org-table-make-reference (elements keep-empty numbers lispp)
9921 "Convert list ELEMENTS to something appropriate to insert into formula.
9922 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
9923 NUMBERS indicates that everything should be converted to numbers.
9924 LISPP means to return something appropriate for a Lisp list."
9925 (if (stringp elements) ; just a single val
9926 (if lispp
9927 (if (eq lispp 'literal)
9928 elements
9929 (prin1-to-string (if numbers (string-to-number elements) elements)))
9930 (if (equal elements "") (setq elements "0"))
9931 (if numbers (number-to-string (string-to-number elements)) elements))
9932 (unless keep-empty
9933 (setq elements
9934 (delq nil
9935 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
9936 elements))))
9937 (setq elements (or elements '("0")))
9938 (if lispp
9939 (mapconcat
9940 (lambda (x)
9941 (if (eq lispp 'literal)
9943 (prin1-to-string (if numbers (string-to-number x) x))))
9944 elements " ")
9945 (concat "[" (mapconcat
9946 (lambda (x)
9947 (if numbers (number-to-string (string-to-number x)) x))
9948 elements
9949 ",") "]"))))
9951 (defun org-table-recalculate (&optional all noalign)
9952 "Recalculate the current table line by applying all stored formulas.
9953 With prefix arg ALL, do this for all lines in the table."
9954 (interactive "P")
9955 (or (memq this-command org-recalc-commands)
9956 (setq org-recalc-commands (cons this-command org-recalc-commands)))
9957 (unless (org-at-table-p) (error "Not at a table"))
9958 (if (equal all '(16))
9959 (org-table-iterate)
9960 (org-table-get-specials)
9961 (let* ((eqlist (sort (org-table-get-stored-formulas)
9962 (lambda (a b) (string< (car a) (car b)))))
9963 (inhibit-redisplay (not debug-on-error))
9964 (line-re org-table-dataline-regexp)
9965 (thisline (org-current-line))
9966 (thiscol (org-table-current-column))
9967 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
9968 ;; Insert constants in all formulas
9969 (setq eqlist
9970 (mapcar (lambda (x)
9971 (setcdr x (org-table-formula-substitute-names (cdr x)))
9973 eqlist))
9974 ;; Split the equation list
9975 (while (setq eq (pop eqlist))
9976 (if (<= (string-to-char (car eq)) ?9)
9977 (push eq eqlnum)
9978 (push eq eqlname)))
9979 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
9980 (if all
9981 (progn
9982 (setq end (move-marker (make-marker) (1+ (org-table-end))))
9983 (goto-char (setq beg (org-table-begin)))
9984 (if (re-search-forward org-table-calculate-mark-regexp end t)
9985 ;; This is a table with marked lines, compute selected lines
9986 (setq line-re org-table-recalculate-regexp)
9987 ;; Move forward to the first non-header line
9988 (if (and (re-search-forward org-table-dataline-regexp end t)
9989 (re-search-forward org-table-hline-regexp end t)
9990 (re-search-forward org-table-dataline-regexp end t))
9991 (setq beg (match-beginning 0))
9992 nil))) ;; just leave beg where it is
9993 (setq beg (point-at-bol)
9994 end (move-marker (make-marker) (1+ (point-at-eol)))))
9995 (goto-char beg)
9996 (and all (message "Re-applying formulas to full table..."))
9998 ;; First find the named fields, and mark them untouchanble
9999 (remove-text-properties beg end '(org-untouchable t))
10000 (while (setq eq (pop eqlname))
10001 (setq name (car eq)
10002 a (assoc name org-table-named-field-locations))
10003 (and (not a)
10004 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10005 (setq a (list name
10006 (aref org-table-dlines
10007 (string-to-number (match-string 1 name)))
10008 (string-to-number (match-string 2 name)))))
10009 (when (and a (or all (equal (nth 1 a) thisline)))
10010 (message "Re-applying formula to field: %s" name)
10011 (goto-line (nth 1 a))
10012 (org-table-goto-column (nth 2 a))
10013 (push (append a (list (cdr eq))) eqlname1)
10014 (org-table-put-field-property :org-untouchable t)))
10016 ;; Now evauluate the column formulas, but skip fields covered by
10017 ;; field formulas
10018 (goto-char beg)
10019 (while (re-search-forward line-re end t)
10020 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10021 ;; Unprotected line, recalculate
10022 (and all (message "Re-applying formulas to full table...(line %d)"
10023 (setq cnt (1+ cnt))))
10024 (setq org-last-recalc-line (org-current-line))
10025 (setq eql eqlnum)
10026 (while (setq entry (pop eql))
10027 (goto-line org-last-recalc-line)
10028 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10029 (unless (get-text-property (point) :org-untouchable)
10030 (org-table-eval-formula nil (cdr entry)
10031 'noalign 'nocst 'nostore 'noanalysis)))))
10033 ;; Now evaluate the field formulas
10034 (while (setq eq (pop eqlname1))
10035 (message "Re-applying formula to field: %s" (car eq))
10036 (goto-line (nth 1 eq))
10037 (org-table-goto-column (nth 2 eq))
10038 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10039 'nostore 'noanalysis))
10041 (goto-line thisline)
10042 (org-table-goto-column thiscol)
10043 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10044 (or noalign (and org-table-may-need-update (org-table-align))
10045 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10047 ;; back to initial position
10048 (message "Re-applying formulas...done")
10049 (goto-line thisline)
10050 (org-table-goto-column thiscol)
10051 (or noalign (and org-table-may-need-update (org-table-align))
10052 (and all (message "Re-applying formulas...done"))))))
10054 (defun org-table-iterate (&optional arg)
10055 "Recalculate the table until it does not change anymore."
10056 (interactive "P")
10057 (let ((imax (if arg (prefix-numeric-value arg) 10))
10058 (i 0)
10059 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10060 thistbl)
10061 (catch 'exit
10062 (while (< i imax)
10063 (setq i (1+ i))
10064 (org-table-recalculate 'all)
10065 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10066 (if (not (string= lasttbl thistbl))
10067 (setq lasttbl thistbl)
10068 (if (> i 1)
10069 (message "Convergence after %d iterations" i)
10070 (message "Table was already stable"))
10071 (throw 'exit t)))
10072 (error "No convergence after %d iterations" i))))
10074 (defun org-table-formula-substitute-names (f)
10075 "Replace $const with values in string F."
10076 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10077 ;; First, check for column names
10078 (while (setq start (string-match org-table-column-name-regexp f start))
10079 (setq start (1+ start))
10080 (setq a (assoc (match-string 1 f) org-table-column-names))
10081 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10082 ;; Parameters and constants
10083 (setq start 0)
10084 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10085 (setq start (1+ start))
10086 (if (setq a (save-match-data
10087 (org-table-get-constant (match-string 1 f))))
10088 (setq f (replace-match
10089 (concat (if pp "(") a (if pp ")")) t t f))))
10090 (if org-table-formula-debug
10091 (put-text-property 0 (length f) :orig-formula f1 f))
10094 (defun org-table-get-constant (const)
10095 "Find the value for a parameter or constant in a formula.
10096 Parameters get priority."
10097 (or (cdr (assoc const org-table-local-parameters))
10098 (cdr (assoc const org-table-formula-constants-local))
10099 (cdr (assoc const org-table-formula-constants))
10100 (and (fboundp 'constants-get) (constants-get const))
10101 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10102 (org-entry-get nil (substring const 5) 'inherit))
10103 "#UNDEFINED_NAME"))
10105 (defvar org-table-fedit-map
10106 (let ((map (make-sparse-keymap)))
10107 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10108 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10109 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10110 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10111 (org-defkey map "\C-c?" 'org-table-show-reference)
10112 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10113 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10114 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10115 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10116 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10117 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10118 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10119 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10120 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10121 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10122 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10123 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10124 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10125 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10126 map))
10128 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10129 '("Edit-Formulas"
10130 ["Finish and Install" org-table-fedit-finish t]
10131 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10132 ["Abort" org-table-fedit-abort t]
10133 "--"
10134 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10135 ["Complete Lisp Symbol" lisp-complete-symbol t]
10136 "--"
10137 "Shift Reference at Point"
10138 ["Up" org-table-fedit-ref-up t]
10139 ["Down" org-table-fedit-ref-down t]
10140 ["Left" org-table-fedit-ref-left t]
10141 ["Right" org-table-fedit-ref-right t]
10143 "Change Test Row for Column Formulas"
10144 ["Up" org-table-fedit-line-up t]
10145 ["Down" org-table-fedit-line-down t]
10146 "--"
10147 ["Scroll Table Window" org-table-fedit-scroll t]
10148 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10149 ["Show Table Grid" org-table-fedit-toggle-coordinates
10150 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10151 org-table-overlay-coordinates)]
10152 "--"
10153 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10154 :style toggle :selected org-table-buffer-is-an]))
10156 (defvar org-pos)
10158 (defun org-table-edit-formulas ()
10159 "Edit the formulas of the current table in a separate buffer."
10160 (interactive)
10161 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10162 (beginning-of-line 0))
10163 (unless (org-at-table-p) (error "Not at a table"))
10164 (org-table-get-specials)
10165 (let ((key (org-table-current-field-formula 'key 'noerror))
10166 (eql (sort (org-table-get-stored-formulas 'noerror)
10167 'org-table-formula-less-p))
10168 (pos (move-marker (make-marker) (point)))
10169 (startline 1)
10170 (wc (current-window-configuration))
10171 (titles '((column . "# Column Formulas\n")
10172 (field . "# Field Formulas\n")
10173 (named . "# Named Field Formulas\n")))
10174 entry s type title)
10175 (org-switch-to-buffer-other-window "*Edit Formulas*")
10176 (erase-buffer)
10177 ;; Keep global-font-lock-mode from turning on font-lock-mode
10178 (let ((font-lock-global-modes '(not fundamental-mode)))
10179 (fundamental-mode))
10180 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10181 (org-set-local 'org-pos pos)
10182 (org-set-local 'org-window-configuration wc)
10183 (use-local-map org-table-fedit-map)
10184 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10185 (easy-menu-add org-table-fedit-menu)
10186 (setq startline (org-current-line))
10187 (while (setq entry (pop eql))
10188 (setq type (cond
10189 ((equal (string-to-char (car entry)) ?@) 'field)
10190 ((string-match "^[0-9]" (car entry)) 'column)
10191 (t 'named)))
10192 (when (setq title (assq type titles))
10193 (or (bobp) (insert "\n"))
10194 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10195 (setq titles (delq title titles)))
10196 (if (equal key (car entry)) (setq startline (org-current-line)))
10197 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10198 (car entry) " = " (cdr entry) "\n"))
10199 (remove-text-properties 0 (length s) '(face nil) s)
10200 (insert s))
10201 (if (eq org-table-use-standard-references t)
10202 (org-table-fedit-toggle-ref-type))
10203 (goto-line startline)
10204 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10206 (defun org-table-fedit-post-command ()
10207 (when (not (memq this-command '(lisp-complete-symbol)))
10208 (let ((win (selected-window)))
10209 (save-excursion
10210 (condition-case nil
10211 (org-table-show-reference)
10212 (error nil))
10213 (select-window win)))))
10215 (defun org-table-formula-to-user (s)
10216 "Convert a formula from internal to user representation."
10217 (if (eq org-table-use-standard-references t)
10218 (org-table-convert-refs-to-an s)
10221 (defun org-table-formula-from-user (s)
10222 "Convert a formula from user to internal representation."
10223 (if org-table-use-standard-references
10224 (org-table-convert-refs-to-rc s)
10227 (defun org-table-convert-refs-to-rc (s)
10228 "Convert spreadsheet references from AB7 to @7$28.
10229 Works for single references, but also for entire formulas and even the
10230 full TBLFM line."
10231 (let ((start 0))
10232 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10233 (cond
10234 ((match-end 3)
10235 ;; format match, just advance
10236 (setq start (match-end 0)))
10237 ((and (> (match-beginning 0) 0)
10238 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10239 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10240 ;; 3.e5 or something like this.
10241 (setq start (match-end 0)))
10243 (setq start (match-beginning 0)
10244 s (replace-match
10245 (if (equal (match-string 2 s) "&")
10246 (format "$%d" (org-letters-to-number (match-string 1 s)))
10247 (format "@%d$%d"
10248 (string-to-number (match-string 2 s))
10249 (org-letters-to-number (match-string 1 s))))
10250 t t s)))))
10253 (defun org-table-convert-refs-to-an (s)
10254 "Convert spreadsheet references from to @7$28 to AB7.
10255 Works for single references, but also for entire formulas and even the
10256 full TBLFM line."
10257 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10258 (setq s (replace-match
10259 (format "%s%d"
10260 (org-number-to-letters
10261 (string-to-number (match-string 2 s)))
10262 (string-to-number (match-string 1 s)))
10263 t t s)))
10264 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10265 (setq s (replace-match (concat "\\1"
10266 (org-number-to-letters
10267 (string-to-number (match-string 2 s))) "&")
10268 t nil s)))
10271 (defun org-letters-to-number (s)
10272 "Convert a base 26 number represented by letters into an integer.
10273 For example: AB -> 28."
10274 (let ((n 0))
10275 (setq s (upcase s))
10276 (while (> (length s) 0)
10277 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10278 s (substring s 1)))
10281 (defun org-number-to-letters (n)
10282 "Convert an integer into a base 26 number represented by letters.
10283 For example: 28 -> AB."
10284 (let ((s ""))
10285 (while (> n 0)
10286 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10287 n (/ (1- n) 26)))
10290 (defun org-table-fedit-convert-buffer (function)
10291 "Convert all references in this buffer, using FUNTION."
10292 (let ((line (org-current-line)))
10293 (goto-char (point-min))
10294 (while (not (eobp))
10295 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10296 (delete-region (point) (point-at-eol))
10297 (or (eobp) (forward-char 1)))
10298 (goto-line line)))
10300 (defun org-table-fedit-toggle-ref-type ()
10301 "Convert all references in the buffer from B3 to @3$2 and back."
10302 (interactive)
10303 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10304 (org-table-fedit-convert-buffer
10305 (if org-table-buffer-is-an
10306 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10307 (message "Reference type switched to %s"
10308 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10310 (defun org-table-fedit-ref-up ()
10311 "Shift the reference at point one row/hline up."
10312 (interactive)
10313 (org-table-fedit-shift-reference 'up))
10314 (defun org-table-fedit-ref-down ()
10315 "Shift the reference at point one row/hline down."
10316 (interactive)
10317 (org-table-fedit-shift-reference 'down))
10318 (defun org-table-fedit-ref-left ()
10319 "Shift the reference at point one field to the left."
10320 (interactive)
10321 (org-table-fedit-shift-reference 'left))
10322 (defun org-table-fedit-ref-right ()
10323 "Shift the reference at point one field to the right."
10324 (interactive)
10325 (org-table-fedit-shift-reference 'right))
10327 (defun org-table-fedit-shift-reference (dir)
10328 (cond
10329 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10330 (if (memq dir '(left right))
10331 (org-rematch-and-replace 1 (eq dir 'left))
10332 (error "Cannot shift reference in this direction")))
10333 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10334 ;; A B3-like reference
10335 (if (memq dir '(up down))
10336 (org-rematch-and-replace 2 (eq dir 'up))
10337 (org-rematch-and-replace 1 (eq dir 'left))))
10338 ((org-at-regexp-p
10339 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10340 ;; An internal reference
10341 (if (memq dir '(up down))
10342 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10343 (org-rematch-and-replace 5 (eq dir 'left))))))
10345 (defun org-rematch-and-replace (n &optional decr hline)
10346 "Re-match the group N, and replace it with the shifted refrence."
10347 (or (match-end n) (error "Cannot shift reference in this direction"))
10348 (goto-char (match-beginning n))
10349 (and (looking-at (regexp-quote (match-string n)))
10350 (replace-match (org-shift-refpart (match-string 0) decr hline)
10351 t t)))
10353 (defun org-shift-refpart (ref &optional decr hline)
10354 "Shift a refrence part REF.
10355 If DECR is set, decrease the references row/column, else increase.
10356 If HLINE is set, this may be a hline reference, it certainly is not
10357 a translation reference."
10358 (save-match-data
10359 (let* ((sign (string-match "^[-+]" ref)) n)
10361 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10362 (cond
10363 ((and hline (string-match "^I+" ref))
10364 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10365 (setq n (+ n (if decr -1 1)))
10366 (if (= n 0) (setq n (+ n (if decr -1 1))))
10367 (if sign
10368 (setq sign (if (< n 0) "-" "+") n (abs n))
10369 (setq n (max 1 n)))
10370 (concat sign (make-string n ?I)))
10372 ((string-match "^[0-9]+" ref)
10373 (setq n (string-to-number (concat sign ref)))
10374 (setq n (+ n (if decr -1 1)))
10375 (if sign
10376 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10377 (number-to-string (max 1 n))))
10379 ((string-match "^[a-zA-Z]+" ref)
10380 (org-number-to-letters
10381 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10383 (t (error "Cannot shift reference"))))))
10385 (defun org-table-fedit-toggle-coordinates ()
10386 "Toggle the display of coordinates in the refrenced table."
10387 (interactive)
10388 (let ((pos (marker-position org-pos)))
10389 (with-current-buffer (marker-buffer org-pos)
10390 (save-excursion
10391 (goto-char pos)
10392 (org-table-toggle-coordinate-overlays)))))
10394 (defun org-table-fedit-finish (&optional arg)
10395 "Parse the buffer for formula definitions and install them.
10396 With prefix ARG, apply the new formulas to the table."
10397 (interactive "P")
10398 (org-table-remove-rectangle-highlight)
10399 (if org-table-use-standard-references
10400 (progn
10401 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
10402 (setq org-table-buffer-is-an nil)))
10403 (let ((pos org-pos) eql var form)
10404 (goto-char (point-min))
10405 (while (re-search-forward
10406 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
10407 nil t)
10408 (setq var (if (match-end 2) (match-string 2) (match-string 1))
10409 form (match-string 3))
10410 (setq form (org-trim form))
10411 (when (not (equal form ""))
10412 (while (string-match "[ \t]*\n[ \t]*" form)
10413 (setq form (replace-match " " t t form)))
10414 (when (assoc var eql)
10415 (error "Double formulas for %s" var))
10416 (push (cons var form) eql)))
10417 (setq org-pos nil)
10418 (set-window-configuration org-window-configuration)
10419 (select-window (get-buffer-window (marker-buffer pos)))
10420 (goto-char pos)
10421 (unless (org-at-table-p)
10422 (error "Lost table position - cannot install formulae"))
10423 (org-table-store-formulas eql)
10424 (move-marker pos nil)
10425 (kill-buffer "*Edit Formulas*")
10426 (if arg
10427 (org-table-recalculate 'all)
10428 (message "New formulas installed - press C-u C-c C-c to apply."))))
10430 (defun org-table-fedit-abort ()
10431 "Abort editing formulas, without installing the changes."
10432 (interactive)
10433 (org-table-remove-rectangle-highlight)
10434 (let ((pos org-pos))
10435 (set-window-configuration org-window-configuration)
10436 (select-window (get-buffer-window (marker-buffer pos)))
10437 (goto-char pos)
10438 (move-marker pos nil)
10439 (message "Formula editing aborted without installing changes")))
10441 (defun org-table-fedit-lisp-indent ()
10442 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
10443 (interactive)
10444 (let ((pos (point)) beg end ind)
10445 (beginning-of-line 1)
10446 (cond
10447 ((looking-at "[ \t]")
10448 (goto-char pos)
10449 (call-interactively 'lisp-indent-line))
10450 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
10451 ((not (fboundp 'pp-buffer))
10452 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
10453 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
10454 (goto-char (- (match-end 0) 2))
10455 (setq beg (point))
10456 (setq ind (make-string (current-column) ?\ ))
10457 (condition-case nil (forward-sexp 1)
10458 (error
10459 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
10460 (setq end (point))
10461 (save-restriction
10462 (narrow-to-region beg end)
10463 (if (eq last-command this-command)
10464 (progn
10465 (goto-char (point-min))
10466 (setq this-command nil)
10467 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
10468 (replace-match " ")))
10469 (pp-buffer)
10470 (untabify (point-min) (point-max))
10471 (goto-char (1+ (point-min)))
10472 (while (re-search-forward "^." nil t)
10473 (beginning-of-line 1)
10474 (insert ind))
10475 (goto-char (point-max))
10476 (backward-delete-char 1)))
10477 (goto-char beg))
10478 (t nil))))
10480 (defvar org-show-positions nil)
10482 (defun org-table-show-reference (&optional local)
10483 "Show the location/value of the $ expression at point."
10484 (interactive)
10485 (org-table-remove-rectangle-highlight)
10486 (catch 'exit
10487 (let ((pos (if local (point) org-pos))
10488 (face2 'highlight)
10489 (org-inhibit-highlight-removal t)
10490 (win (selected-window))
10491 (org-show-positions nil)
10492 var name e what match dest)
10493 (if local (org-table-get-specials))
10494 (setq what (cond
10495 ((or (org-at-regexp-p org-table-range-regexp2)
10496 (org-at-regexp-p org-table-translate-regexp)
10497 (org-at-regexp-p org-table-range-regexp))
10498 (setq match
10499 (save-match-data
10500 (org-table-convert-refs-to-rc (match-string 0))))
10501 'range)
10502 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
10503 ((org-at-regexp-p "\\$[0-9]+") 'column)
10504 ((not local) nil)
10505 (t (error "No reference at point")))
10506 match (and what (or match (match-string 0))))
10507 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
10508 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
10509 'secondary-selection))
10510 (org-add-hook 'before-change-functions
10511 'org-table-remove-rectangle-highlight)
10512 (if (eq what 'name) (setq var (substring match 1)))
10513 (when (eq what 'range)
10514 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
10515 (setq match (org-table-formula-substitute-names match)))
10516 (unless local
10517 (save-excursion
10518 (end-of-line 1)
10519 (re-search-backward "^\\S-" nil t)
10520 (beginning-of-line 1)
10521 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
10522 (setq dest
10523 (save-match-data
10524 (org-table-convert-refs-to-rc (match-string 1))))
10525 (org-table-add-rectangle-overlay
10526 (match-beginning 1) (match-end 1) face2))))
10527 (if (and (markerp pos) (marker-buffer pos))
10528 (if (get-buffer-window (marker-buffer pos))
10529 (select-window (get-buffer-window (marker-buffer pos)))
10530 (org-switch-to-buffer-other-window (get-buffer-window
10531 (marker-buffer pos)))))
10532 (goto-char pos)
10533 (org-table-force-dataline)
10534 (when dest
10535 (setq name (substring dest 1))
10536 (cond
10537 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
10538 (setq e (assoc name org-table-named-field-locations))
10539 (goto-line (nth 1 e))
10540 (org-table-goto-column (nth 2 e)))
10541 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
10542 (let ((l (string-to-number (match-string 1 dest)))
10543 (c (string-to-number (match-string 2 dest))))
10544 (goto-line (aref org-table-dlines l))
10545 (org-table-goto-column c)))
10546 (t (org-table-goto-column (string-to-number name))))
10547 (move-marker pos (point))
10548 (org-table-highlight-rectangle nil nil face2))
10549 (cond
10550 ((equal dest match))
10551 ((not match))
10552 ((eq what 'range)
10553 (condition-case nil
10554 (save-excursion
10555 (org-table-get-range match nil nil 'highlight))
10556 (error nil)))
10557 ((setq e (assoc var org-table-named-field-locations))
10558 (goto-line (nth 1 e))
10559 (org-table-goto-column (nth 2 e))
10560 (org-table-highlight-rectangle (point) (point))
10561 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
10562 ((setq e (assoc var org-table-column-names))
10563 (org-table-goto-column (string-to-number (cdr e)))
10564 (org-table-highlight-rectangle (point) (point))
10565 (goto-char (org-table-begin))
10566 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
10567 (org-table-end) t)
10568 (progn
10569 (goto-char (match-beginning 1))
10570 (org-table-highlight-rectangle)
10571 (message "Named column (column %s)" (cdr e)))
10572 (error "Column name not found")))
10573 ((eq what 'column)
10574 ;; column number
10575 (org-table-goto-column (string-to-number (substring match 1)))
10576 (org-table-highlight-rectangle (point) (point))
10577 (message "Column %s" (substring match 1)))
10578 ((setq e (assoc var org-table-local-parameters))
10579 (goto-char (org-table-begin))
10580 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
10581 (progn
10582 (goto-char (match-beginning 1))
10583 (org-table-highlight-rectangle)
10584 (message "Local parameter."))
10585 (error "Parameter not found")))
10587 (cond
10588 ((not var) (error "No reference at point"))
10589 ((setq e (assoc var org-table-formula-constants-local))
10590 (message "Local Constant: $%s=%s in #+CONSTANTS line."
10591 var (cdr e)))
10592 ((setq e (assoc var org-table-formula-constants))
10593 (message "Constant: $%s=%s in `org-table-formula-constants'."
10594 var (cdr e)))
10595 ((setq e (and (fboundp 'constants-get) (constants-get var)))
10596 (message "Constant: $%s=%s, from `constants.el'%s."
10597 var e (format " (%s units)" constants-unit-system)))
10598 (t (error "Undefined name $%s" var)))))
10599 (goto-char pos)
10600 (when (and org-show-positions
10601 (not (memq this-command '(org-table-fedit-scroll
10602 org-table-fedit-scroll-down))))
10603 (push pos org-show-positions)
10604 (push org-table-current-begin-pos org-show-positions)
10605 (let ((min (apply 'min org-show-positions))
10606 (max (apply 'max org-show-positions)))
10607 (goto-char min) (recenter 0)
10608 (goto-char max)
10609 (or (pos-visible-in-window-p max) (recenter -1))))
10610 (select-window win))))
10612 (defun org-table-force-dataline ()
10613 "Make sure the cursor is in a dataline in a table."
10614 (unless (save-excursion
10615 (beginning-of-line 1)
10616 (looking-at org-table-dataline-regexp))
10617 (let* ((re org-table-dataline-regexp)
10618 (p1 (save-excursion (re-search-forward re nil 'move)))
10619 (p2 (save-excursion (re-search-backward re nil 'move))))
10620 (cond ((and p1 p2)
10621 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
10622 p1 p2)))
10623 ((or p1 p2) (goto-char (or p1 p2)))
10624 (t (error "No table dataline around here"))))))
10626 (defun org-table-fedit-line-up ()
10627 "Move cursor one line up in the window showing the table."
10628 (interactive)
10629 (org-table-fedit-move 'previous-line))
10631 (defun org-table-fedit-line-down ()
10632 "Move cursor one line down in the window showing the table."
10633 (interactive)
10634 (org-table-fedit-move 'next-line))
10636 (defun org-table-fedit-move (command)
10637 "Move the cursor in the window shoinw the table.
10638 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
10639 (let ((org-table-allow-automatic-line-recalculation nil)
10640 (pos org-pos) (win (selected-window)) p)
10641 (select-window (get-buffer-window (marker-buffer org-pos)))
10642 (setq p (point))
10643 (call-interactively command)
10644 (while (and (org-at-table-p)
10645 (org-at-table-hline-p))
10646 (call-interactively command))
10647 (or (org-at-table-p) (goto-char p))
10648 (move-marker pos (point))
10649 (select-window win)))
10651 (defun org-table-fedit-scroll (N)
10652 (interactive "p")
10653 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
10654 (scroll-other-window N)))
10656 (defun org-table-fedit-scroll-down (N)
10657 (interactive "p")
10658 (org-table-fedit-scroll (- N)))
10660 (defvar org-table-rectangle-overlays nil)
10662 (defun org-table-add-rectangle-overlay (beg end &optional face)
10663 "Add a new overlay."
10664 (let ((ov (org-make-overlay beg end)))
10665 (org-overlay-put ov 'face (or face 'secondary-selection))
10666 (push ov org-table-rectangle-overlays)))
10668 (defun org-table-highlight-rectangle (&optional beg end face)
10669 "Highlight rectangular region in a table."
10670 (setq beg (or beg (point)) end (or end (point)))
10671 (let ((b (min beg end))
10672 (e (max beg end))
10673 l1 c1 l2 c2 tmp)
10674 (and (boundp 'org-show-positions)
10675 (setq org-show-positions (cons b (cons e org-show-positions))))
10676 (goto-char (min beg end))
10677 (setq l1 (org-current-line)
10678 c1 (org-table-current-column))
10679 (goto-char (max beg end))
10680 (setq l2 (org-current-line)
10681 c2 (org-table-current-column))
10682 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
10683 (goto-line l1)
10684 (beginning-of-line 1)
10685 (loop for line from l1 to l2 do
10686 (when (looking-at org-table-dataline-regexp)
10687 (org-table-goto-column c1)
10688 (skip-chars-backward "^|\n") (setq beg (point))
10689 (org-table-goto-column c2)
10690 (skip-chars-forward "^|\n") (setq end (point))
10691 (org-table-add-rectangle-overlay beg end face))
10692 (beginning-of-line 2))
10693 (goto-char b))
10694 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
10696 (defun org-table-remove-rectangle-highlight (&rest ignore)
10697 "Remove the rectangle overlays."
10698 (unless org-inhibit-highlight-removal
10699 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
10700 (mapc 'org-delete-overlay org-table-rectangle-overlays)
10701 (setq org-table-rectangle-overlays nil)))
10703 (defvar org-table-coordinate-overlays nil
10704 "Collects the cooordinate grid overlays, so that they can be removed.")
10705 (make-variable-buffer-local 'org-table-coordinate-overlays)
10707 (defun org-table-overlay-coordinates ()
10708 "Add overlays to the table at point, to show row/column coordinates."
10709 (interactive)
10710 (mapc 'org-delete-overlay org-table-coordinate-overlays)
10711 (setq org-table-coordinate-overlays nil)
10712 (save-excursion
10713 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
10714 (goto-char (org-table-begin))
10715 (while (org-at-table-p)
10716 (setq eol (point-at-eol))
10717 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
10718 (push ov org-table-coordinate-overlays)
10719 (setq hline (looking-at org-table-hline-regexp))
10720 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
10721 (format "%4d" (setq id (1+ id)))))
10722 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
10723 (when hline
10724 (setq ic 0)
10725 (while (re-search-forward "[+|]\\(-+\\)" eol t)
10726 (setq beg (1+ (match-beginning 0))
10727 ic (1+ ic)
10728 s1 (concat "$" (int-to-string ic))
10729 s2 (org-number-to-letters ic)
10730 str (if (eq org-table-use-standard-references t) s2 s1))
10731 (setq ov (org-make-overlay beg (+ beg (length str))))
10732 (push ov org-table-coordinate-overlays)
10733 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
10734 (beginning-of-line 2)))))
10736 (defun org-table-toggle-coordinate-overlays ()
10737 "Toggle the display of Row/Column numbers in tables."
10738 (interactive)
10739 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
10740 (message "Row/Column number display turned %s"
10741 (if org-table-overlay-coordinates "on" "off"))
10742 (if (and (org-at-table-p) org-table-overlay-coordinates)
10743 (org-table-align))
10744 (unless org-table-overlay-coordinates
10745 (mapc 'org-delete-overlay org-table-coordinate-overlays)
10746 (setq org-table-coordinate-overlays nil)))
10748 (defun org-table-toggle-formula-debugger ()
10749 "Toggle the formula debugger in tables."
10750 (interactive)
10751 (setq org-table-formula-debug (not org-table-formula-debug))
10752 (message "Formula debugging has been turned %s"
10753 (if org-table-formula-debug "on" "off")))
10755 ;;; The orgtbl minor mode
10757 ;; Define a minor mode which can be used in other modes in order to
10758 ;; integrate the org-mode table editor.
10760 ;; This is really a hack, because the org-mode table editor uses several
10761 ;; keys which normally belong to the major mode, for example the TAB and
10762 ;; RET keys. Here is how it works: The minor mode defines all the keys
10763 ;; necessary to operate the table editor, but wraps the commands into a
10764 ;; function which tests if the cursor is currently inside a table. If that
10765 ;; is the case, the table editor command is executed. However, when any of
10766 ;; those keys is used outside a table, the function uses `key-binding' to
10767 ;; look up if the key has an associated command in another currently active
10768 ;; keymap (minor modes, major mode, global), and executes that command.
10769 ;; There might be problems if any of the keys used by the table editor is
10770 ;; otherwise used as a prefix key.
10772 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
10773 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
10774 ;; addresses this by checking explicitly for both bindings.
10776 ;; The optimized version (see variable `orgtbl-optimized') takes over
10777 ;; all keys which are bound to `self-insert-command' in the *global map*.
10778 ;; Some modes bind other commands to simple characters, for example
10779 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
10780 ;; active, this binding is ignored inside tables and replaced with a
10781 ;; modified self-insert.
10783 (defvar orgtbl-mode nil
10784 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
10785 table editor in arbitrary modes.")
10786 (make-variable-buffer-local 'orgtbl-mode)
10788 (defvar orgtbl-mode-map (make-keymap)
10789 "Keymap for `orgtbl-mode'.")
10791 ;;;###autoload
10792 (defun turn-on-orgtbl ()
10793 "Unconditionally turn on `orgtbl-mode'."
10794 (orgtbl-mode 1))
10796 (defvar org-old-auto-fill-inhibit-regexp nil
10797 "Local variable used by `orgtbl-mode'")
10799 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
10800 "Matches a line belonging to an orgtbl.")
10802 (defconst orgtbl-extra-font-lock-keywords
10803 (list (list (concat "^" orgtbl-line-start-regexp ".*")
10804 0 (quote 'org-table) 'prepend))
10805 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
10807 ;;;###autoload
10808 (defun orgtbl-mode (&optional arg)
10809 "The `org-mode' table editor as a minor mode for use in other modes."
10810 (interactive)
10811 (if (org-mode-p)
10812 ;; Exit without error, in case some hook functions calls this
10813 ;; by accident in org-mode.
10814 (message "Orgtbl-mode is not useful in org-mode, command ignored")
10815 (setq orgtbl-mode
10816 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
10817 (if orgtbl-mode
10818 (progn
10819 (and (orgtbl-setup) (defun orgtbl-setup () nil))
10820 ;; Make sure we are first in minor-mode-map-alist
10821 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
10822 (and c (setq minor-mode-map-alist
10823 (cons c (delq c minor-mode-map-alist)))))
10824 (org-set-local (quote org-table-may-need-update) t)
10825 (org-add-hook 'before-change-functions 'org-before-change-function
10826 nil 'local)
10827 (org-set-local 'org-old-auto-fill-inhibit-regexp
10828 auto-fill-inhibit-regexp)
10829 (org-set-local 'auto-fill-inhibit-regexp
10830 (if auto-fill-inhibit-regexp
10831 (concat orgtbl-line-start-regexp "\\|"
10832 auto-fill-inhibit-regexp)
10833 orgtbl-line-start-regexp))
10834 (org-add-to-invisibility-spec '(org-cwidth))
10835 (when (fboundp 'font-lock-add-keywords)
10836 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
10837 (org-restart-font-lock))
10838 (easy-menu-add orgtbl-mode-menu)
10839 (run-hooks 'orgtbl-mode-hook))
10840 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
10841 (org-cleanup-narrow-column-properties)
10842 (org-remove-from-invisibility-spec '(org-cwidth))
10843 (remove-hook 'before-change-functions 'org-before-change-function t)
10844 (when (fboundp 'font-lock-remove-keywords)
10845 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
10846 (org-restart-font-lock))
10847 (easy-menu-remove orgtbl-mode-menu)
10848 (force-mode-line-update 'all))))
10850 (defun org-cleanup-narrow-column-properties ()
10851 "Remove all properties related to narrow-column invisibility."
10852 (let ((s 1))
10853 (while (setq s (text-property-any s (point-max)
10854 'display org-narrow-column-arrow))
10855 (remove-text-properties s (1+ s) '(display t)))
10856 (setq s 1)
10857 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
10858 (remove-text-properties s (1+ s) '(org-cwidth t)))
10859 (setq s 1)
10860 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
10861 (remove-text-properties s (1+ s) '(invisible t)))))
10863 ;; Install it as a minor mode.
10864 (put 'orgtbl-mode :included t)
10865 (put 'orgtbl-mode :menu-tag "Org Table Mode")
10866 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
10868 (defun orgtbl-make-binding (fun n &rest keys)
10869 "Create a function for binding in the table minor mode.
10870 FUN is the command to call inside a table. N is used to create a unique
10871 command name. KEYS are keys that should be checked in for a command
10872 to execute outside of tables."
10873 (eval
10874 (list 'defun
10875 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
10876 '(arg)
10877 (concat "In tables, run `" (symbol-name fun) "'.\n"
10878 "Outside of tables, run the binding of `"
10879 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
10880 "'.")
10881 '(interactive "p")
10882 (list 'if
10883 '(org-at-table-p)
10884 (list 'call-interactively (list 'quote fun))
10885 (list 'let '(orgtbl-mode)
10886 (list 'call-interactively
10887 (append '(or)
10888 (mapcar (lambda (k)
10889 (list 'key-binding k))
10890 keys)
10891 '('orgtbl-error))))))))
10893 (defun orgtbl-error ()
10894 "Error when there is no default binding for a table key."
10895 (interactive)
10896 (error "This key is has no function outside tables"))
10898 (defun orgtbl-setup ()
10899 "Setup orgtbl keymaps."
10900 (let ((nfunc 0)
10901 (bindings
10902 (list
10903 '([(meta shift left)] org-table-delete-column)
10904 '([(meta left)] org-table-move-column-left)
10905 '([(meta right)] org-table-move-column-right)
10906 '([(meta shift right)] org-table-insert-column)
10907 '([(meta shift up)] org-table-kill-row)
10908 '([(meta shift down)] org-table-insert-row)
10909 '([(meta up)] org-table-move-row-up)
10910 '([(meta down)] org-table-move-row-down)
10911 '("\C-c\C-w" org-table-cut-region)
10912 '("\C-c\M-w" org-table-copy-region)
10913 '("\C-c\C-y" org-table-paste-rectangle)
10914 '("\C-c-" org-table-insert-hline)
10915 '("\C-c}" org-table-toggle-coordinate-overlays)
10916 '("\C-c{" org-table-toggle-formula-debugger)
10917 '("\C-m" org-table-next-row)
10918 '([(shift return)] org-table-copy-down)
10919 '("\C-c\C-q" org-table-wrap-region)
10920 '("\C-c?" org-table-field-info)
10921 '("\C-c " org-table-blank-field)
10922 '("\C-c+" org-table-sum)
10923 '("\C-c=" org-table-eval-formula)
10924 '("\C-c'" org-table-edit-formulas)
10925 '("\C-c`" org-table-edit-field)
10926 '("\C-c*" org-table-recalculate)
10927 '("\C-c|" org-table-create-or-convert-from-region)
10928 '("\C-c^" org-table-sort-lines)
10929 '([(control ?#)] org-table-rotate-recalc-marks)))
10930 elt key fun cmd)
10931 (while (setq elt (pop bindings))
10932 (setq nfunc (1+ nfunc))
10933 (setq key (org-key (car elt))
10934 fun (nth 1 elt)
10935 cmd (orgtbl-make-binding fun nfunc key))
10936 (org-defkey orgtbl-mode-map key cmd))
10938 ;; Special treatment needed for TAB and RET
10939 (org-defkey orgtbl-mode-map [(return)]
10940 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
10941 (org-defkey orgtbl-mode-map "\C-m"
10942 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
10944 (org-defkey orgtbl-mode-map [(tab)]
10945 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
10946 (org-defkey orgtbl-mode-map "\C-i"
10947 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
10949 (org-defkey orgtbl-mode-map [(shift tab)]
10950 (orgtbl-make-binding 'org-table-previous-field 104
10951 [(shift tab)] [(tab)] "\C-i"))
10953 (org-defkey orgtbl-mode-map "\M-\C-m"
10954 (orgtbl-make-binding 'org-table-wrap-region 105
10955 "\M-\C-m" [(meta return)]))
10956 (org-defkey orgtbl-mode-map [(meta return)]
10957 (orgtbl-make-binding 'org-table-wrap-region 106
10958 [(meta return)] "\M-\C-m"))
10960 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
10961 (when orgtbl-optimized
10962 ;; If the user wants maximum table support, we need to hijack
10963 ;; some standard editing functions
10964 (org-remap orgtbl-mode-map
10965 'self-insert-command 'orgtbl-self-insert-command
10966 'delete-char 'org-delete-char
10967 'delete-backward-char 'org-delete-backward-char)
10968 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
10969 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
10970 '("OrgTbl"
10971 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
10972 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
10973 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
10974 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
10975 "--"
10976 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
10977 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
10978 ["Copy Field from Above"
10979 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
10980 "--"
10981 ("Column"
10982 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
10983 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
10984 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
10985 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
10986 ("Row"
10987 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
10988 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
10989 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
10990 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
10991 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
10992 "--"
10993 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
10994 ("Rectangle"
10995 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
10996 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
10997 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
10998 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
10999 "--"
11000 ("Radio tables"
11001 ["Insert table template" orgtbl-insert-radio-table
11002 (assq major-mode orgtbl-radio-table-templates)]
11003 ["Comment/uncomment table" orgtbl-toggle-comment t])
11004 "--"
11005 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11006 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11007 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11008 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11009 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11010 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11011 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11012 ["Sum Column/Rectangle" org-table-sum
11013 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11014 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11015 ["Debug Formulas"
11016 org-table-toggle-formula-debugger :active (org-at-table-p)
11017 :keys "C-c {"
11018 :style toggle :selected org-table-formula-debug]
11019 ["Show Col/Row Numbers"
11020 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11021 :keys "C-c }"
11022 :style toggle :selected org-table-overlay-coordinates]
11026 (defun orgtbl-ctrl-c-ctrl-c (arg)
11027 "If the cursor is inside a table, realign the table.
11028 It it is a table to be sent away to a receiver, do it.
11029 With prefix arg, also recompute table."
11030 (interactive "P")
11031 (let ((pos (point)) action)
11032 (save-excursion
11033 (beginning-of-line 1)
11034 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11035 ((looking-at "[ \t]*|") pos)
11036 ((looking-at "#\\+TBLFM:") 'recalc))))
11037 (cond
11038 ((integerp action)
11039 (goto-char action)
11040 (org-table-maybe-eval-formula)
11041 (if arg
11042 (call-interactively 'org-table-recalculate)
11043 (org-table-maybe-recalculate-line))
11044 (call-interactively 'org-table-align)
11045 (orgtbl-send-table 'maybe))
11046 ((eq action 'recalc)
11047 (save-excursion
11048 (beginning-of-line 1)
11049 (skip-chars-backward " \r\n\t")
11050 (if (org-at-table-p)
11051 (org-call-with-arg 'org-table-recalculate t))))
11052 (t (let (orgtbl-mode)
11053 (call-interactively (key-binding "\C-c\C-c")))))))
11055 (defun orgtbl-tab (arg)
11056 "Justification and field motion for `orgtbl-mode'."
11057 (interactive "P")
11058 (if arg (org-table-edit-field t)
11059 (org-table-justify-field-maybe)
11060 (org-table-next-field)))
11062 (defun orgtbl-ret ()
11063 "Justification and field motion for `orgtbl-mode'."
11064 (interactive)
11065 (org-table-justify-field-maybe)
11066 (org-table-next-row))
11068 (defun orgtbl-self-insert-command (N)
11069 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11070 If the cursor is in a table looking at whitespace, the whitespace is
11071 overwritten, and the table is not marked as requiring realignment."
11072 (interactive "p")
11073 (if (and (org-at-table-p)
11075 (and org-table-auto-blank-field
11076 (member last-command
11077 '(orgtbl-hijacker-command-100
11078 orgtbl-hijacker-command-101
11079 orgtbl-hijacker-command-102
11080 orgtbl-hijacker-command-103
11081 orgtbl-hijacker-command-104
11082 orgtbl-hijacker-command-105))
11083 (org-table-blank-field))
11085 (eq N 1)
11086 (looking-at "[^|\n]* +|"))
11087 (let (org-table-may-need-update)
11088 (goto-char (1- (match-end 0)))
11089 (delete-backward-char 1)
11090 (goto-char (match-beginning 0))
11091 (self-insert-command N))
11092 (setq org-table-may-need-update t)
11093 (let (orgtbl-mode)
11094 (call-interactively (key-binding (vector last-input-event))))))
11096 (defun org-force-self-insert (N)
11097 "Needed to enforce self-insert under remapping."
11098 (interactive "p")
11099 (self-insert-command N))
11101 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11102 "Regula expression matching exponentials as produced by calc.")
11104 (defvar org-table-clean-did-remove-column nil)
11106 (defun orgtbl-export (table target)
11107 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11108 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11109 org-table-last-alignment org-table-last-column-widths
11110 maxcol column)
11111 (if (not (fboundp func))
11112 (error "Cannot export orgtbl table to %s" target))
11113 (setq lines (org-table-clean-before-export lines))
11114 (setq table
11115 (mapcar
11116 (lambda (x)
11117 (if (string-match org-table-hline-regexp x)
11118 'hline
11119 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11120 lines))
11121 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11122 table)))
11123 (loop for i from (1- maxcol) downto 0 do
11124 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11125 (setq column (delq nil column))
11126 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11127 (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))
11128 (funcall func table nil)))
11130 (defun orgtbl-send-table (&optional maybe)
11131 "Send a tranformed version of this table to the receiver position.
11132 With argument MAYBE, fail quietly if no transformation is defined for
11133 this table."
11134 (interactive)
11135 (catch 'exit
11136 (unless (org-at-table-p) (error "Not at a table"))
11137 ;; when non-interactive, we assume align has just happened.
11138 (when (interactive-p) (org-table-align))
11139 (save-excursion
11140 (goto-char (org-table-begin))
11141 (beginning-of-line 0)
11142 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11143 (if maybe
11144 (throw 'exit nil)
11145 (error "Don't know how to transform this table."))))
11146 (let* ((name (match-string 1))
11148 (transform (intern (match-string 2)))
11149 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11150 (skip (plist-get params :skip))
11151 (skipcols (plist-get params :skipcols))
11152 (txt (buffer-substring-no-properties
11153 (org-table-begin) (org-table-end)))
11154 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11155 (lines (org-table-clean-before-export lines))
11156 (i0 (if org-table-clean-did-remove-column 2 1))
11157 (table (mapcar
11158 (lambda (x)
11159 (if (string-match org-table-hline-regexp x)
11160 'hline
11161 (org-remove-by-index
11162 (org-split-string (org-trim x) "\\s-*|\\s-*")
11163 skipcols i0)))
11164 lines))
11165 (fun (if (= i0 2) 'cdr 'identity))
11166 (org-table-last-alignment
11167 (org-remove-by-index (funcall fun org-table-last-alignment)
11168 skipcols i0))
11169 (org-table-last-column-widths
11170 (org-remove-by-index (funcall fun org-table-last-column-widths)
11171 skipcols i0)))
11173 (unless (fboundp transform)
11174 (error "No such transformation function %s" transform))
11175 (setq txt (funcall transform table params))
11176 ;; Find the insertion place
11177 (save-excursion
11178 (goto-char (point-min))
11179 (unless (re-search-forward
11180 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11181 (error "Don't know where to insert translated table"))
11182 (goto-char (match-beginning 0))
11183 (beginning-of-line 2)
11184 (setq beg (point))
11185 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11186 (error "Cannot find end of insertion region"))
11187 (beginning-of-line 1)
11188 (delete-region beg (point))
11189 (goto-char beg)
11190 (insert txt "\n"))
11191 (message "Table converted and installed at receiver location"))))
11193 (defun org-remove-by-index (list indices &optional i0)
11194 "Remove the elements in LIST with indices in INDICES.
11195 First element has index 0, or I0 if given."
11196 (if (not indices)
11197 list
11198 (if (integerp indices) (setq indices (list indices)))
11199 (setq i0 (1- (or i0 0)))
11200 (delq :rm (mapcar (lambda (x)
11201 (setq i0 (1+ i0))
11202 (if (memq i0 indices) :rm x))
11203 list))))
11205 (defun orgtbl-toggle-comment ()
11206 "Comment or uncomment the orgtbl at point."
11207 (interactive)
11208 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11209 (re2 (concat "^" orgtbl-line-start-regexp))
11210 (commented (save-excursion (beginning-of-line 1)
11211 (cond ((looking-at re1) t)
11212 ((looking-at re2) nil)
11213 (t (error "Not at an org table")))))
11214 (re (if commented re1 re2))
11215 beg end)
11216 (save-excursion
11217 (beginning-of-line 1)
11218 (while (looking-at re) (beginning-of-line 0))
11219 (beginning-of-line 2)
11220 (setq beg (point))
11221 (while (looking-at re) (beginning-of-line 2))
11222 (setq end (point)))
11223 (comment-region beg end (if commented '(4) nil))))
11225 (defun orgtbl-insert-radio-table ()
11226 "Insert a radio table template appropriate for this major mode."
11227 (interactive)
11228 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11229 (txt (nth 1 e))
11230 name pos)
11231 (unless e (error "No radio table setup defined for %s" major-mode))
11232 (setq name (read-string "Table name: "))
11233 (while (string-match "%n" txt)
11234 (setq txt (replace-match name t t txt)))
11235 (or (bolp) (insert "\n"))
11236 (setq pos (point))
11237 (insert txt)
11238 (goto-char pos)))
11240 (defun org-get-param (params header i sym &optional hsym)
11241 "Get parameter value for symbol SYM.
11242 If this is a header line, actually get the value for the symbol with an
11243 additional \"h\" inserted after the colon.
11244 If the value is a protperty list, get the element for the current column.
11245 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11246 (let ((val (plist-get params sym)))
11247 (and hsym header (setq val (or (plist-get params hsym) val)))
11248 (if (consp val) (plist-get val i) val)))
11250 (defun orgtbl-to-generic (table params)
11251 "Convert the orgtbl-mode TABLE to some other format.
11252 This generic routine can be used for many standard cases.
11253 TABLE is a list, each entry either the symbol `hline' for a horizontal
11254 separator line, or a list of fields for that line.
11255 PARAMS is a property list of parameters that can influence the conversion.
11256 For the generic converter, some parameters are obligatory: You need to
11257 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11258 :splice, you must have :tstart and :tend.
11260 Valid parameters are
11262 :tstart String to start the table. Ignored when :splice is t.
11263 :tend String to end the table. Ignored when :splice is t.
11265 :splice When set to t, return only table body lines, don't wrap
11266 them into :tstart and :tend. Default is nil.
11268 :hline String to be inserted on horizontal separation lines.
11269 May be nil to ignore hlines.
11271 :lstart String to start a new table line.
11272 :lend String to end a table line
11273 :sep Separator between two fields
11274 :lfmt Format for entire line, with enough %s to capture all fields.
11275 If this is present, :lstart, :lend, and :sep are ignored.
11276 :fmt A format to be used to wrap the field, should contain
11277 %s for the original field value. For example, to wrap
11278 everything in dollars, you could use :fmt \"$%s$\".
11279 This may also be a property list with column numbers and
11280 formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11282 :hlstart :hlend :hlsep :hlfmt :hfmt
11283 Same as above, specific for the header lines in the table.
11284 All lines before the first hline are treated as header.
11285 If any of these is not present, the data line value is used.
11287 :efmt Use this format to print numbers with exponentials.
11288 The format should have %s twice for inserting mantissa
11289 and exponent, for example \"%s\\\\times10^{%s}\". This
11290 may also be a property list with column numbers and
11291 formats. :fmt will still be applied after :efmt.
11293 In addition to this, the parameters :skip and :skipcols are always handled
11294 directly by `orgtbl-send-table'. See manual."
11295 (interactive)
11296 (let* ((p params)
11297 (splicep (plist-get p :splice))
11298 (hline (plist-get p :hline))
11299 rtn line i fm efm lfmt h)
11301 ;; Do we have a header?
11302 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11303 (setq h t))
11305 ;; Put header
11306 (unless splicep
11307 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11309 ;; Now loop over all lines
11310 (while (setq line (pop table))
11311 (if (eq line 'hline)
11312 ;; A horizontal separator line
11313 (progn (if hline (push hline rtn))
11314 (setq h nil)) ; no longer in header
11315 ;; A normal line. Convert the fields, push line onto the result list
11316 (setq i 0)
11317 (setq line
11318 (mapcar
11319 (lambda (f)
11320 (setq i (1+ i)
11321 fm (org-get-param p h i :fmt :hfmt)
11322 efm (org-get-param p h i :efmt))
11323 (if (and efm (string-match orgtbl-exp-regexp f))
11324 (setq f (format
11325 efm (match-string 1 f) (match-string 2 f))))
11326 (if fm (setq f (format fm f)))
11328 line))
11329 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11330 (push (apply 'format lfmt line) rtn)
11331 (push (concat
11332 (org-get-param p h i :lstart :hlstart)
11333 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11334 (org-get-param p h i :lend :hlend))
11335 rtn))))
11337 (unless splicep
11338 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11340 (mapconcat 'identity (nreverse rtn) "\n")))
11342 (defun orgtbl-to-latex (table params)
11343 "Convert the orgtbl-mode TABLE to LaTeX.
11344 TABLE is a list, each entry either the symbol `hline' for a horizontal
11345 separator line, or a list of fields for that line.
11346 PARAMS is a property list of parameters that can influence the conversion.
11347 Supports all parameters from `orgtbl-to-generic'. Most important for
11348 LaTeX are:
11350 :splice When set to t, return only table body lines, don't wrap
11351 them into a tabular environment. Default is nil.
11353 :fmt A format to be used to wrap the field, should contain %s for the
11354 original field value. For example, to wrap everything in dollars,
11355 use :fmt \"$%s$\". This may also be a property list with column
11356 numbers and formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11358 :efmt Format for transforming numbers with exponentials. The format
11359 should have %s twice for inserting mantissa and exponent, for
11360 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11361 This may also be a property list with column numbers and formats.
11363 The general parameters :skip and :skipcols have already been applied when
11364 this function is called."
11365 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11366 org-table-last-alignment ""))
11367 (params2
11368 (list
11369 :tstart (concat "\\begin{tabular}{" alignment "}")
11370 :tend "\\end{tabular}"
11371 :lstart "" :lend " \\\\" :sep " & "
11372 :efmt "%s\\,(%s)" :hline "\\hline")))
11373 (orgtbl-to-generic table (org-combine-plists params2 params))))
11375 (defun orgtbl-to-html (table params)
11376 "Convert the orgtbl-mode TABLE to LaTeX.
11377 TABLE is a list, each entry either the symbol `hline' for a horizontal
11378 separator line, or a list of fields for that line.
11379 PARAMS is a property list of parameters that can influence the conversion.
11380 Currently this function recognizes the following parameters:
11382 :splice When set to t, return only table body lines, don't wrap
11383 them into a <table> environment. Default is nil.
11385 The general parameters :skip and :skipcols have already been applied when
11386 this function is called. The function does *not* use `orgtbl-to-generic',
11387 so you cannot specify parameters for it."
11388 (let* ((splicep (plist-get params :splice))
11389 html)
11390 ;; Just call the formatter we already have
11391 ;; We need to make text lines for it, so put the fields back together.
11392 (setq html (org-format-org-table-html
11393 (mapcar
11394 (lambda (x)
11395 (if (eq x 'hline)
11396 "|----+----|"
11397 (concat "| " (mapconcat 'identity x " | ") " |")))
11398 table)
11399 splicep))
11400 (if (string-match "\n+\\'" html)
11401 (setq html (replace-match "" t t html)))
11402 html))
11404 (defun orgtbl-to-texinfo (table params)
11405 "Convert the orgtbl-mode TABLE to TeXInfo.
11406 TABLE is a list, each entry either the symbol `hline' for a horizontal
11407 separator line, or a list of fields for that line.
11408 PARAMS is a property list of parameters that can influence the conversion.
11409 Supports all parameters from `orgtbl-to-generic'. Most important for
11410 TeXInfo are:
11412 :splice nil/t When set to t, return only table body lines, don't wrap
11413 them into a multitable environment. Default is nil.
11415 :fmt fmt A format to be used to wrap the field, should contain
11416 %s for the original field value. For example, to wrap
11417 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
11418 This may also be a property list with column numbers and
11419 formats. for example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
11421 :cf \"f1 f2..\" The column fractions for the table. Bye default these
11422 are computed automatically from the width of the columns
11423 under org-mode.
11425 The general parameters :skip and :skipcols have already been applied when
11426 this function is called."
11427 (let* ((total (float (apply '+ org-table-last-column-widths)))
11428 (colfrac (or (plist-get params :cf)
11429 (mapconcat
11430 (lambda (x) (format "%.3f" (/ (float x) total)))
11431 org-table-last-column-widths " ")))
11432 (params2
11433 (list
11434 :tstart (concat "@multitable @columnfractions " colfrac)
11435 :tend "@end multitable"
11436 :lstart "@item " :lend "" :sep " @tab "
11437 :hlstart "@headitem ")))
11438 (orgtbl-to-generic table (org-combine-plists params2 params))))
11440 ;;;; Link Stuff
11442 ;;; Link abbreviations
11444 (defun org-link-expand-abbrev (link)
11445 "Apply replacements as defined in `org-link-abbrev-alist."
11446 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
11447 (let* ((key (match-string 1 link))
11448 (as (or (assoc key org-link-abbrev-alist-local)
11449 (assoc key org-link-abbrev-alist)))
11450 (tag (and (match-end 2) (match-string 3 link)))
11451 rpl)
11452 (if (not as)
11453 link
11454 (setq rpl (cdr as))
11455 (cond
11456 ((symbolp rpl) (funcall rpl tag))
11457 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
11458 (t (concat rpl tag)))))
11459 link))
11461 ;;; Storing and inserting links
11463 (defvar org-insert-link-history nil
11464 "Minibuffer history for links inserted with `org-insert-link'.")
11466 (defvar org-stored-links nil
11467 "Contains the links stored with `org-store-link'.")
11469 (defvar org-store-link-plist nil
11470 "Plist with info about the most recently link created with `org-store-link'.")
11472 (defvar org-link-protocols nil
11473 "Link protocols added to Org-mode using `org-add-link-type'.")
11475 (defvar org-store-link-functions nil
11476 "List of functions that are called to create and store a link.
11477 Each function will be called in turn until one returns a non-nil
11478 value. Each function should check if it is responsible for creating
11479 this link (for example by looking at the major mode).
11480 If not, it must exit and return nil.
11481 If yes, it should return a non-nil value after a calling
11482 `org-store-link-props' with a list of properties and values.
11483 Special properties are:
11485 :type The link prefix. like \"http\". This must be given.
11486 :link The link, like \"http://www.astro.uva.nl/~dominik\".
11487 This is obligatory as well.
11488 :description Optional default description for the second pair
11489 of brackets in an Org-mode link. The user can still change
11490 this when inserting this link into an Org-mode buffer.
11492 In addition to these, any additional properties can be specified
11493 and then used in remember templates.")
11495 (defun org-add-link-type (type &optional follow publish)
11496 "Add TYPE to the list of `org-link-types'.
11497 Re-compute all regular expressions depending on `org-link-types'
11498 FOLLOW and PUBLISH are two functions. Both take the link path as
11499 an argument.
11500 FOLLOW should do whatever is necessary to follow the link, for example
11501 to find a file or display a mail message.
11503 PUBLISH takes the path and retuns the string that should be used when
11504 this document is published. FIMXE: This is actually not yet implemented."
11505 (add-to-list 'org-link-types type t)
11506 (org-make-link-regexps)
11507 (add-to-list 'org-link-protocols
11508 (list type follow publish)))
11510 (defun org-add-agenda-custom-command (entry)
11511 "Replace or add a command in `org-agenda-custom-commands'.
11512 This is mostly for hacking and trying a new command - once the command
11513 works you probably want to add it to `org-agenda-custom-commands' for good."
11514 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
11515 (if ass
11516 (setcdr ass (cdr entry))
11517 (push entry org-agenda-custom-commands))))
11519 ;;;###autoload
11520 (defun org-store-link (arg)
11521 "\\<org-mode-map>Store an org-link to the current location.
11522 This link can later be inserted into an org-buffer with
11523 \\[org-insert-link].
11524 For some link types, a prefix arg is interpreted:
11525 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
11526 For file links, arg negates `org-context-in-file-links'."
11527 (interactive "P")
11528 (setq org-store-link-plist nil) ; reset
11529 (let (link cpltxt desc description search txt)
11530 (cond
11532 ((run-hook-with-args-until-success 'org-store-link-functions)
11533 (setq link (plist-get org-store-link-plist :link)
11534 desc (or (plist-get org-store-link-plist :description) link)))
11536 ((eq major-mode 'bbdb-mode)
11537 (let ((name (bbdb-record-name (bbdb-current-record)))
11538 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
11539 (setq cpltxt (concat "bbdb:" (or name company))
11540 link (org-make-link cpltxt))
11541 (org-store-link-props :type "bbdb" :name name :company company)))
11543 ((eq major-mode 'Info-mode)
11544 (setq link (org-make-link "info:"
11545 (file-name-nondirectory Info-current-file)
11546 ":" Info-current-node))
11547 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
11548 ":" Info-current-node))
11549 (org-store-link-props :type "info" :file Info-current-file
11550 :node Info-current-node))
11552 ((eq major-mode 'calendar-mode)
11553 (let ((cd (calendar-cursor-to-date)))
11554 (setq link
11555 (format-time-string
11556 (car org-time-stamp-formats)
11557 (apply 'encode-time
11558 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
11559 nil nil nil))))
11560 (org-store-link-props :type "calendar" :date cd)))
11562 ((or (eq major-mode 'vm-summary-mode)
11563 (eq major-mode 'vm-presentation-mode))
11564 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
11565 (vm-follow-summary-cursor)
11566 (save-excursion
11567 (vm-select-folder-buffer)
11568 (let* ((message (car vm-message-pointer))
11569 (folder buffer-file-name)
11570 (subject (vm-su-subject message))
11571 (to (vm-get-header-contents message "To"))
11572 (from (vm-get-header-contents message "From"))
11573 (message-id (vm-su-message-id message)))
11574 (org-store-link-props :type "vm" :from from :to to :subject subject
11575 :message-id message-id)
11576 (setq message-id (org-remove-angle-brackets message-id))
11577 (setq folder (abbreviate-file-name folder))
11578 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
11579 folder)
11580 (setq folder (replace-match "" t t folder)))
11581 (setq cpltxt (org-email-link-description))
11582 (setq link (org-make-link "vm:" folder "#" message-id)))))
11584 ((eq major-mode 'wl-summary-mode)
11585 (let* ((msgnum (wl-summary-message-number))
11586 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
11587 msgnum 'message-id))
11588 (wl-message-entity
11589 (if (fboundp 'elmo-message-entity)
11590 (elmo-message-entity
11591 wl-summary-buffer-elmo-folder msgnum)
11592 (elmo-msgdb-overview-get-entity
11593 msgnum (wl-summary-buffer-msgdb))))
11594 (from (wl-summary-line-from))
11595 (to (elmo-message-entity-field wl-message-entity 'to))
11596 (subject (let (wl-thr-indent-string wl-parent-message-entity)
11597 (wl-summary-line-subject))))
11598 (org-store-link-props :type "wl" :from from :to to
11599 :subject subject :message-id message-id)
11600 (setq message-id (org-remove-angle-brackets message-id))
11601 (setq cpltxt (org-email-link-description))
11602 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
11603 "#" message-id))))
11605 ((or (equal major-mode 'mh-folder-mode)
11606 (equal major-mode 'mh-show-mode))
11607 (let ((from (org-mhe-get-header "From:"))
11608 (to (org-mhe-get-header "To:"))
11609 (message-id (org-mhe-get-header "Message-Id:"))
11610 (subject (org-mhe-get-header "Subject:")))
11611 (org-store-link-props :type "mh" :from from :to to
11612 :subject subject :message-id message-id)
11613 (setq cpltxt (org-email-link-description))
11614 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
11615 (org-remove-angle-brackets message-id)))))
11617 ((eq major-mode 'rmail-mode)
11618 (save-excursion
11619 (save-restriction
11620 (rmail-narrow-to-non-pruned-header)
11621 (let ((folder buffer-file-name)
11622 (message-id (mail-fetch-field "message-id"))
11623 (from (mail-fetch-field "from"))
11624 (to (mail-fetch-field "to"))
11625 (subject (mail-fetch-field "subject")))
11626 (org-store-link-props
11627 :type "rmail" :from from :to to
11628 :subject subject :message-id message-id)
11629 (setq message-id (org-remove-angle-brackets message-id))
11630 (setq cpltxt (org-email-link-description))
11631 (setq link (org-make-link "rmail:" folder "#" message-id))))))
11633 ((eq major-mode 'gnus-group-mode)
11634 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
11635 (gnus-group-group-name)) ; version
11636 ((fboundp 'gnus-group-name)
11637 (gnus-group-name))
11638 (t "???"))))
11639 (unless group (error "Not on a group"))
11640 (org-store-link-props :type "gnus" :group group)
11641 (setq cpltxt (concat
11642 (if (org-xor arg org-usenet-links-prefer-google)
11643 "http://groups.google.com/groups?group="
11644 "gnus:")
11645 group)
11646 link (org-make-link cpltxt))))
11648 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
11649 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
11650 (let* ((group gnus-newsgroup-name)
11651 (article (gnus-summary-article-number))
11652 (header (gnus-summary-article-header article))
11653 (from (mail-header-from header))
11654 (message-id (mail-header-id header))
11655 (date (mail-header-date header))
11656 (subject (gnus-summary-subject-string)))
11657 (org-store-link-props :type "gnus" :from from :subject subject
11658 :message-id message-id :group group)
11659 (setq cpltxt (org-email-link-description))
11660 (if (org-xor arg org-usenet-links-prefer-google)
11661 (setq link
11662 (concat
11663 cpltxt "\n "
11664 (format "http://groups.google.com/groups?as_umsgid=%s"
11665 (org-fixup-message-id-for-http message-id))))
11666 (setq link (org-make-link "gnus:" group
11667 "#" (number-to-string article))))))
11669 ((eq major-mode 'w3-mode)
11670 (setq cpltxt (url-view-url t)
11671 link (org-make-link cpltxt))
11672 (org-store-link-props :type "w3" :url (url-view-url t)))
11674 ((eq major-mode 'w3m-mode)
11675 (setq cpltxt (or w3m-current-title w3m-current-url)
11676 link (org-make-link w3m-current-url))
11677 (org-store-link-props :type "w3m" :url (url-view-url t)))
11679 ((setq search (run-hook-with-args-until-success
11680 'org-create-file-search-functions))
11681 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
11682 "::" search))
11683 (setq cpltxt (or description link)))
11685 ((eq major-mode 'image-mode)
11686 (setq cpltxt (concat "file:"
11687 (abbreviate-file-name buffer-file-name))
11688 link (org-make-link cpltxt))
11689 (org-store-link-props :type "image" :file buffer-file-name))
11691 ((eq major-mode 'dired-mode)
11692 ;; link to the file in the current line
11693 (setq cpltxt (concat "file:"
11694 (abbreviate-file-name
11695 (expand-file-name
11696 (dired-get-filename nil t))))
11697 link (org-make-link cpltxt)))
11699 ((and buffer-file-name (org-mode-p))
11700 ;; Just link to current headline
11701 (setq cpltxt (concat "file:"
11702 (abbreviate-file-name buffer-file-name)))
11703 ;; Add a context search string
11704 (when (org-xor org-context-in-file-links arg)
11705 ;; Check if we are on a target
11706 (if (org-in-regexp "<<\\(.*?\\)>>")
11707 (setq cpltxt (concat cpltxt "::" (match-string 1)))
11708 (setq txt (cond
11709 ((org-on-heading-p) nil)
11710 ((org-region-active-p)
11711 (buffer-substring (region-beginning) (region-end)))
11712 (t (buffer-substring (point-at-bol) (point-at-eol)))))
11713 (when (or (null txt) (string-match "\\S-" txt))
11714 (setq cpltxt
11715 (concat cpltxt "::" (org-make-org-heading-search-string txt))
11716 desc "NONE"))))
11717 (if (string-match "::\\'" cpltxt)
11718 (setq cpltxt (substring cpltxt 0 -2)))
11719 (setq link (org-make-link cpltxt)))
11721 ((buffer-file-name (buffer-base-buffer))
11722 ;; Just link to this file here.
11723 (setq cpltxt (concat "file:"
11724 (abbreviate-file-name
11725 (buffer-file-name (buffer-base-buffer)))))
11726 ;; Add a context string
11727 (when (org-xor org-context-in-file-links arg)
11728 (setq txt (if (org-region-active-p)
11729 (buffer-substring (region-beginning) (region-end))
11730 (buffer-substring (point-at-bol) (point-at-eol))))
11731 ;; Only use search option if there is some text.
11732 (when (string-match "\\S-" txt)
11733 (setq cpltxt
11734 (concat cpltxt "::" (org-make-org-heading-search-string txt))
11735 desc "NONE")))
11736 (setq link (org-make-link cpltxt)))
11738 ((interactive-p)
11739 (error "Cannot link to a buffer which is not visiting a file"))
11741 (t (setq link nil)))
11743 (if (consp link) (setq cpltxt (car link) link (cdr link)))
11744 (setq link (or link cpltxt)
11745 desc (or desc cpltxt))
11746 (if (equal desc "NONE") (setq desc nil))
11748 (if (and (interactive-p) link)
11749 (progn
11750 (setq org-stored-links
11751 (cons (list link desc) org-stored-links))
11752 (message "Stored: %s" (or desc link)))
11753 (and link (org-make-link-string link desc)))))
11755 (defun org-store-link-props (&rest plist)
11756 "Store link properties, extract names and addresses."
11757 (let (x adr)
11758 (when (setq x (plist-get plist :from))
11759 (setq adr (mail-extract-address-components x))
11760 (plist-put plist :fromname (car adr))
11761 (plist-put plist :fromaddress (nth 1 adr)))
11762 (when (setq x (plist-get plist :to))
11763 (setq adr (mail-extract-address-components x))
11764 (plist-put plist :toname (car adr))
11765 (plist-put plist :toaddress (nth 1 adr))))
11766 (let ((from (plist-get plist :from))
11767 (to (plist-get plist :to)))
11768 (when (and from to org-from-is-user-regexp)
11769 (plist-put plist :fromto
11770 (if (string-match org-from-is-user-regexp from)
11771 (concat "to %t")
11772 (concat "from %f")))))
11773 (setq org-store-link-plist plist))
11775 (defun org-email-link-description (&optional fmt)
11776 "Return the description part of an email link.
11777 This takes information from `org-store-link-plist' and formats it
11778 according to FMT (default from `org-email-link-description-format')."
11779 (setq fmt (or fmt org-email-link-description-format))
11780 (let* ((p org-store-link-plist)
11781 (to (plist-get p :toaddress))
11782 (from (plist-get p :fromaddress))
11783 (table
11784 (list
11785 (cons "%c" (plist-get p :fromto))
11786 (cons "%F" (plist-get p :from))
11787 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
11788 (cons "%T" (plist-get p :to))
11789 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
11790 (cons "%s" (plist-get p :subject))
11791 (cons "%m" (plist-get p :message-id)))))
11792 (when (string-match "%c" fmt)
11793 ;; Check if the user wrote this message
11794 (if (and org-from-is-user-regexp from to
11795 (save-match-data (string-match org-from-is-user-regexp from)))
11796 (setq fmt (replace-match "to %t" t t fmt))
11797 (setq fmt (replace-match "from %f" t t fmt))))
11798 (org-replace-escapes fmt table)))
11800 (defun org-make-org-heading-search-string (&optional string heading)
11801 "Make search string for STRING or current headline."
11802 (interactive)
11803 (let ((s (or string (org-get-heading))))
11804 (unless (and string (not heading))
11805 ;; We are using a headline, clean up garbage in there.
11806 (if (string-match org-todo-regexp s)
11807 (setq s (replace-match "" t t s)))
11808 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
11809 (setq s (replace-match "" t t s)))
11810 (setq s (org-trim s))
11811 (if (string-match (concat "^\\(" org-quote-string "\\|"
11812 org-comment-string "\\)") s)
11813 (setq s (replace-match "" t t s)))
11814 (while (string-match org-ts-regexp s)
11815 (setq s (replace-match "" t t s))))
11816 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
11817 (setq s (replace-match " " t t s)))
11818 (or string (setq s (concat "*" s))) ; Add * for headlines
11819 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
11821 (defun org-make-link (&rest strings)
11822 "Concatenate STRINGS."
11823 (apply 'concat strings))
11825 (defun org-make-link-string (link &optional description)
11826 "Make a link with brackets, consisting of LINK and DESCRIPTION."
11827 (unless (string-match "\\S-" link)
11828 (error "Empty link"))
11829 (when (stringp description)
11830 ;; Remove brackets from the description, they are fatal.
11831 (while (string-match "\\[\\|\\]" description)
11832 (setq description (replace-match "" t t description))))
11833 (when (equal (org-link-escape link) description)
11834 ;; No description needed, it is identical
11835 (setq description nil))
11836 (when (and (not description)
11837 (not (equal link (org-link-escape link))))
11838 (setq description link))
11839 (concat "[[" (org-link-escape link) "]"
11840 (if description (concat "[" description "]") "")
11841 "]"))
11843 (defconst org-link-escape-chars
11844 '((?\ . "%20")
11845 (?\[ . "%5B")
11846 (?\] . "%5d")
11847 (?\340 . "%E0") ; `a
11848 (?\342 . "%E2") ; ^a
11849 (?\347 . "%E7") ; ,c
11850 (?\350 . "%E8") ; `e
11851 (?\351 . "%E9") ; 'e
11852 (?\352 . "%EA") ; ^e
11853 (?\356 . "%EE") ; ^i
11854 (?\364 . "%F4") ; ^o
11855 (?\371 . "%F9") ; `u
11856 (?\373 . "%FB") ; ^u
11857 (?\; . "%3B")
11858 (?? . "%3F")
11859 (?= . "%3D")
11860 (?+ . "%2B")
11862 "Association list of escapes for some characters problematic in links.
11863 This is the list that is used for internal purposes.")
11865 (defconst org-link-escape-chars-browser
11866 '((?\ . "%20")) ; 32 for the SPC char
11868 "Association list of escapes for some characters problematic in links.
11869 This is the list that is used before handing over to the browser.")
11871 (defun org-link-escape (text &optional table)
11872 "Escape charaters in TEXT that are problematic for links."
11873 (setq table (or table org-link-escape-chars))
11874 (when text
11875 (let ((re (mapconcat (lambda (x) (regexp-quote
11876 (char-to-string (car x))))
11877 table "\\|")))
11878 (while (string-match re text)
11879 (setq text
11880 (replace-match
11881 (cdr (assoc (string-to-char (match-string 0 text))
11882 table))
11883 t t text)))
11884 text)))
11886 (defun org-link-unescape (text &optional table)
11887 "Reverse the action of `org-link-escape'."
11888 (setq table (or table org-link-escape-chars))
11889 (when text
11890 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
11891 table "\\|")))
11892 (while (string-match re text)
11893 (setq text
11894 (replace-match
11895 (char-to-string (car (rassoc (match-string 0 text) table)))
11896 t t text)))
11897 text)))
11899 (defun org-xor (a b)
11900 "Exclusive or."
11901 (if a (not b) b))
11903 (defun org-get-header (header)
11904 "Find a header field in the current buffer."
11905 (save-excursion
11906 (goto-char (point-min))
11907 (let ((case-fold-search t) s)
11908 (cond
11909 ((eq header 'from)
11910 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
11911 (setq s (match-string 1)))
11912 (while (string-match "\"" s)
11913 (setq s (replace-match "" t t s)))
11914 (if (string-match "[<(].*" s)
11915 (setq s (replace-match "" t t s))))
11916 ((eq header 'message-id)
11917 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
11918 (setq s (match-string 1))))
11919 ((eq header 'subject)
11920 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
11921 (setq s (match-string 1)))))
11922 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
11923 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
11924 s)))
11927 (defun org-fixup-message-id-for-http (s)
11928 "Replace special characters in a message id, so it can be used in an http query."
11929 (while (string-match "<" s)
11930 (setq s (replace-match "%3C" t t s)))
11931 (while (string-match ">" s)
11932 (setq s (replace-match "%3E" t t s)))
11933 (while (string-match "@" s)
11934 (setq s (replace-match "%40" t t s)))
11937 ;;;###autoload
11938 (defun org-insert-link-global ()
11939 "Insert a link like Org-mode does.
11940 This command can be called in any mode to insert a link in Org-mode syntax."
11941 (interactive)
11942 (org-run-like-in-org-mode 'org-insert-link))
11944 (defun org-insert-link (&optional complete-file)
11945 "Insert a link. At the prompt, enter the link.
11947 Completion can be used to select a link previously stored with
11948 `org-store-link'. When the empty string is entered (i.e. if you just
11949 press RET at the prompt), the link defaults to the most recently
11950 stored link. As SPC triggers completion in the minibuffer, you need to
11951 use M-SPC or C-q SPC to force the insertion of a space character.
11953 You will also be prompted for a description, and if one is given, it will
11954 be displayed in the buffer instead of the link.
11956 If there is already a link at point, this command will allow you to edit link
11957 and description parts.
11959 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
11960 selected using completion. The path to the file will be relative to
11961 the current directory if the file is in the current directory or a
11962 subdirectory. Otherwise, the link will be the absolute path as
11963 completed in the minibuffer (i.e. normally ~/path/to/file).
11965 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
11966 is in the current directory or below.
11967 With three \\[universal-argument] prefixes, negate the meaning of
11968 `org-keep-stored-link-after-insertion'."
11969 (interactive "P")
11970 (let* ((wcf (current-window-configuration))
11971 (region (if (org-region-active-p)
11972 (buffer-substring (region-beginning) (region-end))))
11973 (remove (and region (list (region-beginning) (region-end))))
11974 (desc region)
11975 tmphist ; byte-compile incorrectly complains about this
11976 link entry file)
11977 (cond
11978 ((org-in-regexp org-bracket-link-regexp 1)
11979 ;; We do have a link at point, and we are going to edit it.
11980 (setq remove (list (match-beginning 0) (match-end 0)))
11981 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
11982 (setq link (read-string "Link: "
11983 (org-link-unescape
11984 (org-match-string-no-properties 1)))))
11985 ((or (org-in-regexp org-angle-link-re)
11986 (org-in-regexp org-plain-link-re))
11987 ;; Convert to bracket link
11988 (setq remove (list (match-beginning 0) (match-end 0))
11989 link (read-string "Link: "
11990 (org-remove-angle-brackets (match-string 0)))))
11991 ((equal complete-file '(4))
11992 ;; Completing read for file names.
11993 (setq file (read-file-name "File: "))
11994 (let ((pwd (file-name-as-directory (expand-file-name ".")))
11995 (pwd1 (file-name-as-directory (abbreviate-file-name
11996 (expand-file-name ".")))))
11997 (cond
11998 ((equal complete-file '(16))
11999 (setq link (org-make-link
12000 "file:"
12001 (abbreviate-file-name (expand-file-name file)))))
12002 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12003 (setq link (org-make-link "file:" (match-string 1 file))))
12004 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12005 (expand-file-name file))
12006 (setq link (org-make-link
12007 "file:" (match-string 1 (expand-file-name file)))))
12008 (t (setq link (org-make-link "file:" file))))))
12010 ;; Read link, with completion for stored links.
12011 (with-output-to-temp-buffer "*Org Links*"
12012 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12013 (when org-stored-links
12014 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12015 (princ (mapconcat
12016 (lambda (x)
12017 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12018 (reverse org-stored-links) "\n"))))
12019 (let ((cw (selected-window)))
12020 (select-window (get-buffer-window "*Org Links*"))
12021 (shrink-window-if-larger-than-buffer)
12022 (setq truncate-lines t)
12023 (select-window cw))
12024 ;; Fake a link history, containing the stored links.
12025 (setq tmphist (append (mapcar 'car org-stored-links)
12026 org-insert-link-history))
12027 (unwind-protect
12028 (setq link (org-completing-read
12029 "Link: "
12030 (append
12031 (mapcar (lambda (x) (list (concat (car x) ":")))
12032 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12033 (mapcar (lambda (x) (list (concat x ":")))
12034 org-link-types))
12035 nil nil nil
12036 'tmphist
12037 (or (car (car org-stored-links)))))
12038 (set-window-configuration wcf)
12039 (kill-buffer "*Org Links*"))
12040 (setq entry (assoc link org-stored-links))
12041 (or entry (push link org-insert-link-history))
12042 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12043 (not org-keep-stored-link-after-insertion))
12044 (setq org-stored-links (delq (assoc link org-stored-links)
12045 org-stored-links)))
12046 (setq desc (or desc (nth 1 entry)))))
12048 (if (string-match org-plain-link-re link)
12049 ;; URL-like link, normalize the use of angular brackets.
12050 (setq link (org-make-link (org-remove-angle-brackets link))))
12052 ;; Check if we are linking to the current file with a search option
12053 ;; If yes, simplify the link by using only the search option.
12054 (when (and buffer-file-name
12055 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12056 (let* ((path (match-string 1 link))
12057 (case-fold-search nil)
12058 (search (match-string 2 link)))
12059 (save-match-data
12060 (if (equal (file-truename buffer-file-name) (file-truename path))
12061 ;; We are linking to this same file, with a search option
12062 (setq link search)))))
12064 ;; Check if we can/should use a relative path. If yes, simplify the link
12065 (when (string-match "\\<file:\\(.*\\)" link)
12066 (let* ((path (match-string 1 link))
12067 (origpath path)
12068 (desc-is-link (equal link desc))
12069 (case-fold-search nil))
12070 (cond
12071 ((eq org-link-file-path-type 'absolute)
12072 (setq path (abbreviate-file-name (expand-file-name path))))
12073 ((eq org-link-file-path-type 'noabbrev)
12074 (setq path (expand-file-name path)))
12075 ((eq org-link-file-path-type 'relative)
12076 (setq path (file-relative-name path)))
12078 (save-match-data
12079 (if (string-match (concat "^" (regexp-quote
12080 (file-name-as-directory
12081 (expand-file-name "."))))
12082 (expand-file-name path))
12083 ;; We are linking a file with relative path name.
12084 (setq path (substring (expand-file-name path)
12085 (match-end 0)))))))
12086 (setq link (concat "file:" path))
12087 (if (equal desc origpath)
12088 (setq desc path))))
12090 (setq desc (read-string "Description: " desc))
12091 (unless (string-match "\\S-" desc) (setq desc nil))
12092 (if remove (apply 'delete-region remove))
12093 (insert (org-make-link-string link desc))))
12095 (defun org-completing-read (&rest args)
12096 (let ((minibuffer-local-completion-map
12097 (copy-keymap minibuffer-local-completion-map)))
12098 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12099 (apply 'completing-read args)))
12101 ;;; Opening/following a link
12102 (defvar org-link-search-failed nil)
12104 (defun org-next-link ()
12105 "Move forward to the next link.
12106 If the link is in hidden text, expose it."
12107 (interactive)
12108 (when (and org-link-search-failed (eq this-command last-command))
12109 (goto-char (point-min))
12110 (message "Link search wrapped back to beginning of buffer"))
12111 (setq org-link-search-failed nil)
12112 (let* ((pos (point))
12113 (ct (org-context))
12114 (a (assoc :link ct)))
12115 (if a (goto-char (nth 2 a)))
12116 (if (re-search-forward org-any-link-re nil t)
12117 (progn
12118 (goto-char (match-beginning 0))
12119 (if (org-invisible-p) (org-show-context)))
12120 (goto-char pos)
12121 (setq org-link-search-failed t)
12122 (error "No further link found"))))
12124 (defun org-previous-link ()
12125 "Move backward to the previous link.
12126 If the link is in hidden text, expose it."
12127 (interactive)
12128 (when (and org-link-search-failed (eq this-command last-command))
12129 (goto-char (point-max))
12130 (message "Link search wrapped back to end of buffer"))
12131 (setq org-link-search-failed nil)
12132 (let* ((pos (point))
12133 (ct (org-context))
12134 (a (assoc :link ct)))
12135 (if a (goto-char (nth 1 a)))
12136 (if (re-search-backward org-any-link-re nil t)
12137 (progn
12138 (goto-char (match-beginning 0))
12139 (if (org-invisible-p) (org-show-context)))
12140 (goto-char pos)
12141 (setq org-link-search-failed t)
12142 (error "No further link found"))))
12144 (defun org-find-file-at-mouse (ev)
12145 "Open file link or URL at mouse."
12146 (interactive "e")
12147 (mouse-set-point ev)
12148 (org-open-at-point 'in-emacs))
12150 (defun org-open-at-mouse (ev)
12151 "Open file link or URL at mouse."
12152 (interactive "e")
12153 (mouse-set-point ev)
12154 (org-open-at-point))
12156 (defvar org-window-config-before-follow-link nil
12157 "The window configuration before following a link.
12158 This is saved in case the need arises to restore it.")
12160 (defvar org-open-link-marker (make-marker)
12161 "Marker pointing to the location where `org-open-at-point; was called.")
12163 ;;;###autoload
12164 (defun org-open-at-point-global ()
12165 "Follow a link like Org-mode does.
12166 This command can be called in any mode to follow a link that has
12167 Org-mode syntax."
12168 (interactive)
12169 (org-run-like-in-org-mode 'org-open-at-point))
12171 (defun org-open-at-point (&optional in-emacs)
12172 "Open link at or after point.
12173 If there is no link at point, this function will search forward up to
12174 the end of the current subtree.
12175 Normally, files will be opened by an appropriate application. If the
12176 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12177 (interactive "P")
12178 (catch 'abort
12179 (move-marker org-open-link-marker (point))
12180 (setq org-window-config-before-follow-link (current-window-configuration))
12181 (org-remove-occur-highlights nil nil t)
12182 (if (org-at-timestamp-p t)
12183 (org-follow-timestamp-link)
12184 (let (type path link line search (pos (point)))
12185 (catch 'match
12186 (save-excursion
12187 (skip-chars-forward "^]\n\r")
12188 (when (org-in-regexp org-bracket-link-regexp)
12189 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12190 (while (string-match " *\n *" link)
12191 (setq link (replace-match " " t t link)))
12192 (setq link (org-link-expand-abbrev link))
12193 (if (string-match org-link-re-with-space2 link)
12194 (setq type (match-string 1 link) path (match-string 2 link))
12195 (setq type "thisfile" path link))
12196 (throw 'match t)))
12198 (when (get-text-property (point) 'org-linked-text)
12199 (setq type "thisfile"
12200 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12201 (1+ (point)) (point))
12202 path (buffer-substring
12203 (previous-single-property-change pos 'org-linked-text)
12204 (next-single-property-change pos 'org-linked-text)))
12205 (throw 'match t))
12207 (save-excursion
12208 (when (or (org-in-regexp org-angle-link-re)
12209 (org-in-regexp org-plain-link-re))
12210 (setq type (match-string 1) path (match-string 2))
12211 (throw 'match t)))
12212 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12213 (setq type "tree-match"
12214 path (match-string 1))
12215 (throw 'match t))
12216 (save-excursion
12217 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12218 (setq type "tags"
12219 path (match-string 1))
12220 (while (string-match ":" path)
12221 (setq path (replace-match "+" t t path)))
12222 (throw 'match t))))
12223 (unless path
12224 (error "No link found"))
12225 ;; Remove any trailing spaces in path
12226 (if (string-match " +\\'" path)
12227 (setq path (replace-match "" t t path)))
12229 (cond
12231 ((assoc type org-link-protocols)
12232 (funcall (nth 1 (assoc type org-link-protocols)) path))
12234 ((equal type "mailto")
12235 (let ((cmd (car org-link-mailto-program))
12236 (args (cdr org-link-mailto-program)) args1
12237 (address path) (subject "") a)
12238 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12239 (setq address (match-string 1 path)
12240 subject (org-link-escape (match-string 2 path))))
12241 (while args
12242 (cond
12243 ((not (stringp (car args))) (push (pop args) args1))
12244 (t (setq a (pop args))
12245 (if (string-match "%a" a)
12246 (setq a (replace-match address t t a)))
12247 (if (string-match "%s" a)
12248 (setq a (replace-match subject t t a)))
12249 (push a args1))))
12250 (apply cmd (nreverse args1))))
12252 ((member type '("http" "https" "ftp" "news"))
12253 (browse-url (concat type ":" (org-link-escape
12254 path org-link-escape-chars-browser))))
12256 ((string= type "tags")
12257 (org-tags-view in-emacs path))
12258 ((string= type "thisfile")
12259 (if in-emacs
12260 (switch-to-buffer-other-window
12261 (org-get-buffer-for-internal-link (current-buffer)))
12262 (org-mark-ring-push))
12263 (let ((cmd `(org-link-search
12264 ,path
12265 ,(cond ((equal in-emacs '(4)) 'occur)
12266 ((equal in-emacs '(16)) 'org-occur)
12267 (t nil))
12268 ,pos)))
12269 (condition-case nil (eval cmd)
12270 (error (progn (widen) (eval cmd))))))
12272 ((string= type "tree-match")
12273 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12275 ((string= type "file")
12276 (if (string-match "::\\([0-9]+\\)\\'" path)
12277 (setq line (string-to-number (match-string 1 path))
12278 path (substring path 0 (match-beginning 0)))
12279 (if (string-match "::\\(.+\\)\\'" path)
12280 (setq search (match-string 1 path)
12281 path (substring path 0 (match-beginning 0)))))
12282 (if (string-match "[*?{]" (file-name-nondirectory path))
12283 (dired path)
12284 (org-open-file path in-emacs line search)))
12286 ((string= type "news")
12287 (org-follow-gnus-link path))
12289 ((string= type "bbdb")
12290 (org-follow-bbdb-link path))
12292 ((string= type "info")
12293 (org-follow-info-link path))
12295 ((string= type "gnus")
12296 (let (group article)
12297 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12298 (error "Error in Gnus link"))
12299 (setq group (match-string 1 path)
12300 article (match-string 3 path))
12301 (org-follow-gnus-link group article)))
12303 ((string= type "vm")
12304 (let (folder article)
12305 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12306 (error "Error in VM link"))
12307 (setq folder (match-string 1 path)
12308 article (match-string 3 path))
12309 ;; in-emacs is the prefix arg, will be interpreted as read-only
12310 (org-follow-vm-link folder article in-emacs)))
12312 ((string= type "wl")
12313 (let (folder article)
12314 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12315 (error "Error in Wanderlust link"))
12316 (setq folder (match-string 1 path)
12317 article (match-string 3 path))
12318 (org-follow-wl-link folder article)))
12320 ((string= type "mhe")
12321 (let (folder article)
12322 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12323 (error "Error in MHE link"))
12324 (setq folder (match-string 1 path)
12325 article (match-string 3 path))
12326 (org-follow-mhe-link folder article)))
12328 ((string= type "rmail")
12329 (let (folder article)
12330 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12331 (error "Error in RMAIL link"))
12332 (setq folder (match-string 1 path)
12333 article (match-string 3 path))
12334 (org-follow-rmail-link folder article)))
12336 ((string= type "shell")
12337 (let ((cmd path))
12338 (if (or (not org-confirm-shell-link-function)
12339 (funcall org-confirm-shell-link-function
12340 (format "Execute \"%s\" in shell? "
12341 (org-add-props cmd nil
12342 'face 'org-warning))))
12343 (progn
12344 (message "Executing %s" cmd)
12345 (shell-command cmd))
12346 (error "Abort"))))
12348 ((string= type "elisp")
12349 (let ((cmd path))
12350 (if (or (not org-confirm-elisp-link-function)
12351 (funcall org-confirm-elisp-link-function
12352 (format "Execute \"%s\" as elisp? "
12353 (org-add-props cmd nil
12354 'face 'org-warning))))
12355 (message "%s => %s" cmd (eval (read cmd)))
12356 (error "Abort"))))
12359 (browse-url-at-point)))))
12360 (move-marker org-open-link-marker nil)))
12362 ;;; File search
12364 (defvar org-create-file-search-functions nil
12365 "List of functions to construct the right search string for a file link.
12366 These functions are called in turn with point at the location to
12367 which the link should point.
12369 A function in the hook should first test if it would like to
12370 handle this file type, for example by checking the major-mode or
12371 the file extension. If it decides not to handle this file, it
12372 should just return nil to give other functions a chance. If it
12373 does handle the file, it must return the search string to be used
12374 when following the link. The search string will be part of the
12375 file link, given after a double colon, and `org-open-at-point'
12376 will automatically search for it. If special measures must be
12377 taken to make the search successful, another function should be
12378 added to the companion hook `org-execute-file-search-functions',
12379 which see.
12381 A function in this hook may also use `setq' to set the variable
12382 `description' to provide a suggestion for the descriptive text to
12383 be used for this link when it gets inserted into an Org-mode
12384 buffer with \\[org-insert-link].")
12386 (defvar org-execute-file-search-functions nil
12387 "List of functions to execute a file search triggered by a link.
12389 Functions added to this hook must accept a single argument, the
12390 search string that was part of the file link, the part after the
12391 double colon. The function must first check if it would like to
12392 handle this search, for example by checking the major-mode or the
12393 file extension. If it decides not to handle this search, it
12394 should just return nil to give other functions a chance. If it
12395 does handle the search, it must return a non-nil value to keep
12396 other functions from trying.
12398 Each function can access the current prefix argument through the
12399 variable `current-prefix-argument'. Note that a single prefix is
12400 used to force opening a link in Emacs, so it may be good to only
12401 use a numeric or double prefix to guide the search function.
12403 In case this is needed, a function in this hook can also restore
12404 the window configuration before `org-open-at-point' was called using:
12406 (set-window-configuration org-window-config-before-follow-link)")
12408 (defun org-link-search (s &optional type avoid-pos)
12409 "Search for a link search option.
12410 If S is surrounded by forward slashes, it is interpreted as a
12411 regular expression. In org-mode files, this will create an `org-occur'
12412 sparse tree. In ordinary files, `occur' will be used to list matches.
12413 If the current buffer is in `dired-mode', grep will be used to search
12414 in all files. If AVOID-POS is given, ignore matches near that position."
12415 (let ((case-fold-search t)
12416 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12417 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12418 (append '(("") (" ") ("\t") ("\n"))
12419 org-emphasis-alist)
12420 "\\|") "\\)"))
12421 (pos (point))
12422 (pre "") (post "")
12423 words re0 re1 re2 re3 re4 re5 re2a reall)
12424 (cond
12425 ;; First check if there are any special
12426 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12427 ;; Now try the builtin stuff
12428 ((save-excursion
12429 (goto-char (point-min))
12430 (and
12431 (re-search-forward
12432 (concat "<<" (regexp-quote s0) ">>") nil t)
12433 (setq pos (match-beginning 0))))
12434 ;; There is an exact target for this
12435 (goto-char pos))
12436 ((string-match "^/\\(.*\\)/$" s)
12437 ;; A regular expression
12438 (cond
12439 ((org-mode-p)
12440 (org-occur (match-string 1 s)))
12441 ;;((eq major-mode 'dired-mode)
12442 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12443 (t (org-do-occur (match-string 1 s)))))
12445 ;; A normal search strings
12446 (when (equal (string-to-char s) ?*)
12447 ;; Anchor on headlines, post may include tags.
12448 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
12449 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
12450 s (substring s 1)))
12451 (remove-text-properties
12452 0 (length s)
12453 '(face nil mouse-face nil keymap nil fontified nil) s)
12454 ;; Make a series of regular expressions to find a match
12455 (setq words (org-split-string s "[ \n\r\t]+")
12456 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
12457 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
12458 "\\)" markers)
12459 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
12460 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
12461 re1 (concat pre re2 post)
12462 re3 (concat pre re4 post)
12463 re5 (concat pre ".*" re4)
12464 re2 (concat pre re2)
12465 re2a (concat pre re2a)
12466 re4 (concat pre re4)
12467 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
12468 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
12469 re5 "\\)"
12471 (cond
12472 ((eq type 'org-occur) (org-occur reall))
12473 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
12474 (t (goto-char (point-min))
12475 (if (or (org-search-not-self 1 re0 nil t)
12476 (org-search-not-self 1 re1 nil t)
12477 (org-search-not-self 1 re2 nil t)
12478 (org-search-not-self 1 re2a nil t)
12479 (org-search-not-self 1 re3 nil t)
12480 (org-search-not-self 1 re4 nil t)
12481 (org-search-not-self 1 re5 nil t)
12483 (goto-char (match-beginning 1))
12484 (goto-char pos)
12485 (error "No match")))))
12487 ;; Normal string-search
12488 (goto-char (point-min))
12489 (if (search-forward s nil t)
12490 (goto-char (match-beginning 0))
12491 (error "No match"))))
12492 (and (org-mode-p) (org-show-context 'link-search))))
12494 (defun org-search-not-self (group &rest args)
12495 "Execute `re-search-forward', but only accept matches that do not
12496 enclose the position of `org-open-link-marker'."
12497 (let ((m org-open-link-marker))
12498 (catch 'exit
12499 (while (apply 're-search-forward args)
12500 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
12501 (goto-char (match-end group))
12502 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
12503 (> (match-beginning 0) (marker-position m))
12504 (< (match-end 0) (marker-position m)))
12505 (save-match-data
12506 (or (not (org-in-regexp
12507 org-bracket-link-analytic-regexp 1))
12508 (not (match-end 4)) ; no description
12509 (and (<= (match-beginning 4) (point))
12510 (>= (match-end 4) (point))))))
12511 (throw 'exit (point))))))))
12513 (defun org-get-buffer-for-internal-link (buffer)
12514 "Return a buffer to be used for displaying the link target of internal links."
12515 (cond
12516 ((not org-display-internal-link-with-indirect-buffer)
12517 buffer)
12518 ((string-match "(Clone)$" (buffer-name buffer))
12519 (message "Buffer is already a clone, not making another one")
12520 ;; we also do not modify visibility in this case
12521 buffer)
12522 (t ; make a new indirect buffer for displaying the link
12523 (let* ((bn (buffer-name buffer))
12524 (ibn (concat bn "(Clone)"))
12525 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
12526 (with-current-buffer ib (org-overview))
12527 ib))))
12529 (defun org-do-occur (regexp &optional cleanup)
12530 "Call the Emacs command `occur'.
12531 If CLEANUP is non-nil, remove the printout of the regular expression
12532 in the *Occur* buffer. This is useful if the regex is long and not useful
12533 to read."
12534 (occur regexp)
12535 (when cleanup
12536 (let ((cwin (selected-window)) win beg end)
12537 (when (setq win (get-buffer-window "*Occur*"))
12538 (select-window win))
12539 (goto-char (point-min))
12540 (when (re-search-forward "match[a-z]+" nil t)
12541 (setq beg (match-end 0))
12542 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
12543 (setq end (1- (match-beginning 0)))))
12544 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
12545 (goto-char (point-min))
12546 (select-window cwin))))
12548 ;;; The mark ring for links jumps
12550 (defvar org-mark-ring nil
12551 "Mark ring for positions before jumps in Org-mode.")
12552 (defvar org-mark-ring-last-goto nil
12553 "Last position in the mark ring used to go back.")
12554 ;; Fill and close the ring
12555 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
12556 (loop for i from 1 to org-mark-ring-length do
12557 (push (make-marker) org-mark-ring))
12558 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
12559 org-mark-ring)
12561 (defun org-mark-ring-push (&optional pos buffer)
12562 "Put the current position or POS into the mark ring and rotate it."
12563 (interactive)
12564 (setq pos (or pos (point)))
12565 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
12566 (move-marker (car org-mark-ring)
12567 (or pos (point))
12568 (or buffer (current-buffer)))
12569 (message
12570 (substitute-command-keys
12571 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
12573 (defun org-mark-ring-goto (&optional n)
12574 "Jump to the previous position in the mark ring.
12575 With prefix arg N, jump back that many stored positions. When
12576 called several times in succession, walk through the entire ring.
12577 Org-mode commands jumping to a different position in the current file,
12578 or to another Org-mode file, automatically push the old position
12579 onto the ring."
12580 (interactive "p")
12581 (let (p m)
12582 (if (eq last-command this-command)
12583 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
12584 (setq p org-mark-ring))
12585 (setq org-mark-ring-last-goto p)
12586 (setq m (car p))
12587 (switch-to-buffer (marker-buffer m))
12588 (goto-char m)
12589 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
12591 (defun org-remove-angle-brackets (s)
12592 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
12593 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
12595 (defun org-add-angle-brackets (s)
12596 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
12597 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
12600 ;;; Following specific links
12602 (defun org-follow-timestamp-link ()
12603 (cond
12604 ((org-at-date-range-p t)
12605 (let ((org-agenda-start-on-weekday)
12606 (t1 (match-string 1))
12607 (t2 (match-string 2)))
12608 (setq t1 (time-to-days (org-time-string-to-time t1))
12609 t2 (time-to-days (org-time-string-to-time t2)))
12610 (org-agenda-list nil t1 (1+ (- t2 t1)))))
12611 ((org-at-timestamp-p t)
12612 (org-agenda-list nil (time-to-days (org-time-string-to-time
12613 (substring (match-string 1) 0 10)))
12615 (t (error "This should not happen"))))
12618 (defun org-follow-bbdb-link (name)
12619 "Follow a BBDB link to NAME."
12620 (require 'bbdb)
12621 (let ((inhibit-redisplay (not debug-on-error))
12622 (bbdb-electric-p nil))
12623 (catch 'exit
12624 ;; Exact match on name
12625 (bbdb-name (concat "\\`" name "\\'") nil)
12626 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12627 ;; Exact match on name
12628 (bbdb-company (concat "\\`" name "\\'") nil)
12629 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12630 ;; Partial match on name
12631 (bbdb-name name nil)
12632 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12633 ;; Partial match on company
12634 (bbdb-company name nil)
12635 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12636 ;; General match including network address and notes
12637 (bbdb name nil)
12638 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
12639 (delete-window (get-buffer-window "*BBDB*"))
12640 (error "No matching BBDB record")))))
12642 (defun org-follow-info-link (name)
12643 "Follow an info file & node link to NAME."
12644 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
12645 (string-match "\\(.*\\)" name))
12646 (progn
12647 (require 'info)
12648 (if (match-string 2 name) ; If there isn't a node, choose "Top"
12649 (Info-find-node (match-string 1 name) (match-string 2 name))
12650 (Info-find-node (match-string 1 name) "Top")))
12651 (message (concat "Could not open: " name))))
12653 (defun org-follow-gnus-link (&optional group article)
12654 "Follow a Gnus link to GROUP and ARTICLE."
12655 (require 'gnus)
12656 (funcall (cdr (assq 'gnus org-link-frame-setup)))
12657 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
12658 (cond ((and group article)
12659 (gnus-group-read-group 1 nil group)
12660 (gnus-summary-goto-article (string-to-number article) nil t))
12661 (group (gnus-group-jump-to-group group))))
12663 (defun org-follow-vm-link (&optional folder article readonly)
12664 "Follow a VM link to FOLDER and ARTICLE."
12665 (require 'vm)
12666 (setq article (org-add-angle-brackets article))
12667 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
12668 ;; ange-ftp or efs or tramp access
12669 (let ((user (or (match-string 1 folder) (user-login-name)))
12670 (host (match-string 2 folder))
12671 (file (match-string 3 folder)))
12672 (cond
12673 ((featurep 'tramp)
12674 ;; use tramp to access the file
12675 (if (featurep 'xemacs)
12676 (setq folder (format "[%s@%s]%s" user host file))
12677 (setq folder (format "/%s@%s:%s" user host file))))
12679 ;; use ange-ftp or efs
12680 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
12681 (setq folder (format "/%s@%s:%s" user host file))))))
12682 (when folder
12683 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
12684 (sit-for 0.1)
12685 (when article
12686 (vm-select-folder-buffer)
12687 (widen)
12688 (let ((case-fold-search t))
12689 (goto-char (point-min))
12690 (if (not (re-search-forward
12691 (concat "^" "message-id: *" (regexp-quote article))))
12692 (error "Could not find the specified message in this folder"))
12693 (vm-isearch-update)
12694 (vm-isearch-narrow)
12695 (vm-beginning-of-message)
12696 (vm-summarize)))))
12698 (defun org-follow-wl-link (folder article)
12699 "Follow a Wanderlust link to FOLDER and ARTICLE."
12700 (if (and (string= folder "%")
12701 article
12702 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
12703 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
12704 ;; Thus, we recompose folder and article ids.
12705 (setq folder (format "%s#%s" folder (match-string 1 article))
12706 article (match-string 3 article)))
12707 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
12708 (error "No such folder: %s" folder))
12709 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
12710 (and article
12711 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
12712 (wl-summary-redisplay)))
12714 (defun org-follow-rmail-link (folder article)
12715 "Follow an RMAIL link to FOLDER and ARTICLE."
12716 (setq article (org-add-angle-brackets article))
12717 (let (message-number)
12718 (save-excursion
12719 (save-window-excursion
12720 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
12721 (setq message-number
12722 (save-restriction
12723 (widen)
12724 (goto-char (point-max))
12725 (if (re-search-backward
12726 (concat "^Message-ID:\\s-+" (regexp-quote
12727 (or article "")))
12728 nil t)
12729 (rmail-what-message))))))
12730 (if message-number
12731 (progn
12732 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
12733 (rmail-show-message message-number)
12734 message-number)
12735 (error "Message not found"))))
12737 ;;; mh-e integration based on planner-mode
12738 (defun org-mhe-get-message-real-folder ()
12739 "Return the name of the current message real folder, so if you use
12740 sequences, it will now work."
12741 (save-excursion
12742 (let* ((folder
12743 (if (equal major-mode 'mh-folder-mode)
12744 mh-current-folder
12745 ;; Refer to the show buffer
12746 mh-show-folder-buffer))
12747 (end-index
12748 (if (boundp 'mh-index-folder)
12749 (min (length mh-index-folder) (length folder))))
12751 ;; a simple test on mh-index-data does not work, because
12752 ;; mh-index-data is always nil in a show buffer.
12753 (if (and (boundp 'mh-index-folder)
12754 (string= mh-index-folder (substring folder 0 end-index)))
12755 (if (equal major-mode 'mh-show-mode)
12756 (save-window-excursion
12757 (let (pop-up-frames)
12758 (when (buffer-live-p (get-buffer folder))
12759 (progn
12760 (pop-to-buffer folder)
12761 (org-mhe-get-message-folder-from-index)
12764 (org-mhe-get-message-folder-from-index)
12766 folder
12770 (defun org-mhe-get-message-folder-from-index ()
12771 "Returns the name of the message folder in a index folder buffer."
12772 (save-excursion
12773 (mh-index-previous-folder)
12774 (re-search-forward "^\\(+.*\\)$" nil t)
12775 (message (match-string 1))))
12777 (defun org-mhe-get-message-folder ()
12778 "Return the name of the current message folder. Be careful if you
12779 use sequences."
12780 (save-excursion
12781 (if (equal major-mode 'mh-folder-mode)
12782 mh-current-folder
12783 ;; Refer to the show buffer
12784 mh-show-folder-buffer)))
12786 (defun org-mhe-get-message-num ()
12787 "Return the number of the current message. Be careful if you
12788 use sequences."
12789 (save-excursion
12790 (if (equal major-mode 'mh-folder-mode)
12791 (mh-get-msg-num nil)
12792 ;; Refer to the show buffer
12793 (mh-show-buffer-message-number))))
12795 (defun org-mhe-get-header (header)
12796 "Return a header of the message in folder mode. This will create a
12797 show buffer for the corresponding message. If you have a more clever
12798 idea..."
12799 (let* ((folder (org-mhe-get-message-folder))
12800 (num (org-mhe-get-message-num))
12801 (buffer (get-buffer-create (concat "show-" folder)))
12802 (header-field))
12803 (with-current-buffer buffer
12804 (mh-display-msg num folder)
12805 (if (equal major-mode 'mh-folder-mode)
12806 (mh-header-display)
12807 (mh-show-header-display))
12808 (set-buffer buffer)
12809 (setq header-field (mh-get-header-field header))
12810 (if (equal major-mode 'mh-folder-mode)
12811 (mh-show)
12812 (mh-show-show))
12813 header-field)))
12815 (defun org-follow-mhe-link (folder article)
12816 "Follow an MHE link to FOLDER and ARTICLE.
12817 If ARTICLE is nil FOLDER is shown. If the configuration variable
12818 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
12819 ARTICLE is searched in all folders. Indexed searches (swish++,
12820 namazu, and others supported by MH-E) will always search in all
12821 folders."
12822 (require 'mh-e)
12823 (require 'mh-search)
12824 (require 'mh-utils)
12825 (mh-find-path)
12826 (if (not article)
12827 (mh-visit-folder (mh-normalize-folder-name folder))
12828 (setq article (org-add-angle-brackets article))
12829 (mh-search-choose)
12830 (if (equal mh-searcher 'pick)
12831 (progn
12832 (mh-search folder (list "--message-id" article))
12833 (when (and org-mhe-search-all-folders
12834 (not (org-mhe-get-message-real-folder)))
12835 (kill-this-buffer)
12836 (mh-search "+" (list "--message-id" article))))
12837 (mh-search "+" article))
12838 (if (org-mhe-get-message-real-folder)
12839 (mh-show-msg 1)
12840 (kill-this-buffer)
12841 (error "Message not found"))))
12843 ;;; BibTeX links
12845 ;; Use the custom search meachnism to construct and use search strings for
12846 ;; file links to BibTeX database entries.
12848 (defun org-create-file-search-in-bibtex ()
12849 "Create the search string and description for a BibTeX database entry."
12850 (when (eq major-mode 'bibtex-mode)
12851 ;; yes, we want to construct this search string.
12852 ;; Make a good description for this entry, using names, year and the title
12853 ;; Put it into the `description' variable which is dynamically scoped.
12854 (let ((bibtex-autokey-names 1)
12855 (bibtex-autokey-names-stretch 1)
12856 (bibtex-autokey-name-case-convert-function 'identity)
12857 (bibtex-autokey-name-separator " & ")
12858 (bibtex-autokey-additional-names " et al.")
12859 (bibtex-autokey-year-length 4)
12860 (bibtex-autokey-name-year-separator " ")
12861 (bibtex-autokey-titlewords 3)
12862 (bibtex-autokey-titleword-separator " ")
12863 (bibtex-autokey-titleword-case-convert-function 'identity)
12864 (bibtex-autokey-titleword-length 'infty)
12865 (bibtex-autokey-year-title-separator ": "))
12866 (setq description (bibtex-generate-autokey)))
12867 ;; Now parse the entry, get the key and return it.
12868 (save-excursion
12869 (bibtex-beginning-of-entry)
12870 (cdr (assoc "=key=" (bibtex-parse-entry))))))
12872 (defun org-execute-file-search-in-bibtex (s)
12873 "Find the link search string S as a key for a database entry."
12874 (when (eq major-mode 'bibtex-mode)
12875 ;; Yes, we want to do the search in this file.
12876 ;; We construct a regexp that searches for "@entrytype{" followed by the key
12877 (goto-char (point-min))
12878 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
12879 (regexp-quote s) "[ \t\n]*,") nil t)
12880 (goto-char (match-beginning 0)))
12881 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
12882 ;; Use double prefix to indicate that any web link should be browsed
12883 (let ((b (current-buffer)) (p (point)))
12884 ;; Restore the window configuration because we just use the web link
12885 (set-window-configuration org-window-config-before-follow-link)
12886 (save-excursion (set-buffer b) (goto-char p)
12887 (bibtex-url)))
12888 (recenter 0)) ; Move entry start to beginning of window
12889 ;; return t to indicate that the search is done.
12892 ;; Finally add the functions to the right hooks.
12893 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
12894 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
12896 ;; end of Bibtex link setup
12898 ;;; Following file links
12900 (defun org-open-file (path &optional in-emacs line search)
12901 "Open the file at PATH.
12902 First, this expands any special file name abbreviations. Then the
12903 configuration variable `org-file-apps' is checked if it contains an
12904 entry for this file type, and if yes, the corresponding command is launched.
12905 If no application is found, Emacs simply visits the file.
12906 With optional argument IN-EMACS, Emacs will visit the file.
12907 Optional LINE specifies a line to go to, optional SEARCH a string to
12908 search for. If LINE or SEARCH is given, the file will always be
12909 opened in Emacs.
12910 If the file does not exist, an error is thrown."
12911 (setq in-emacs (or in-emacs line search))
12912 (let* ((file (if (equal path "")
12913 buffer-file-name
12914 (substitute-in-file-name (expand-file-name path))))
12915 (apps (append org-file-apps (org-default-apps)))
12916 (remp (and (assq 'remote apps) (org-file-remote-p file)))
12917 (dirp (if remp nil (file-directory-p file)))
12918 (dfile (downcase file))
12919 (old-buffer (current-buffer))
12920 (old-pos (point))
12921 (old-mode major-mode)
12922 ext cmd)
12923 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
12924 (setq ext (match-string 1 dfile))
12925 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
12926 (setq ext (match-string 1 dfile))))
12927 (if in-emacs
12928 (setq cmd 'emacs)
12929 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
12930 (and dirp (cdr (assoc 'directory apps)))
12931 (cdr (assoc ext apps))
12932 (cdr (assoc t apps)))))
12933 (when (eq cmd 'mailcap)
12934 (require 'mailcap)
12935 (mailcap-parse-mailcaps)
12936 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
12937 (command (mailcap-mime-info mime-type)))
12938 (if (stringp command)
12939 (setq cmd command)
12940 (setq cmd 'emacs))))
12941 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
12942 (not (file-exists-p file))
12943 (not org-open-non-existing-files))
12944 (error "No such file: %s" file))
12945 (cond
12946 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
12947 ;; Remove quotes around the file name - we'll use shell-quote-argument.
12948 (if (string-match "['\"]%s['\"]" cmd)
12949 (setq cmd (replace-match "%s" t t cmd)))
12950 (setq cmd (format cmd (shell-quote-argument file)))
12951 (save-window-excursion
12952 (start-process-shell-command cmd nil cmd)))
12953 ((or (stringp cmd)
12954 (eq cmd 'emacs))
12955 (funcall (cdr (assq 'file org-link-frame-setup)) file)
12956 (widen)
12957 (if line (goto-line line)
12958 (if search (org-link-search search))))
12959 ((consp cmd)
12960 (eval cmd))
12961 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
12962 (and (org-mode-p) (eq old-mode 'org-mode)
12963 (or (not (equal old-buffer (current-buffer)))
12964 (not (equal old-pos (point))))
12965 (org-mark-ring-push old-pos old-buffer))))
12967 (defun org-default-apps ()
12968 "Return the default applications for this operating system."
12969 (cond
12970 ((eq system-type 'darwin)
12971 org-file-apps-defaults-macosx)
12972 ((eq system-type 'windows-nt)
12973 org-file-apps-defaults-windowsnt)
12974 (t org-file-apps-defaults-gnu)))
12976 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
12977 (defun org-file-remote-p (file)
12978 "Test whether FILE specifies a location on a remote system.
12979 Return non-nil if the location is indeed remote.
12981 For example, the filename \"/user@host:/foo\" specifies a location
12982 on the system \"/user@host:\"."
12983 (cond ((fboundp 'file-remote-p)
12984 (file-remote-p file))
12985 ((fboundp 'tramp-handle-file-remote-p)
12986 (tramp-handle-file-remote-p file))
12987 ((and (boundp 'ange-ftp-name-format)
12988 (string-match (car ange-ftp-name-format) file))
12990 (t nil)))
12993 ;;;; Hooks for remember.el, and refiling
12995 ;;;###autoload
12996 (defun org-remember-insinuate ()
12997 "Setup remember.el for use wiht Org-mode."
12998 (require 'remember)
12999 (setq remember-annotation-functions '(org-remember-annotation))
13000 (setq remember-handler-functions '(org-remember-handler))
13001 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13003 ;;;###autoload
13004 (defun org-remember-annotation ()
13005 "Return a link to the current location as an annotation for remember.el.
13006 If you are using Org-mode files as target for data storage with
13007 remember.el, then the annotations should include a link compatible with the
13008 conventions in Org-mode. This function returns such a link."
13009 (org-store-link nil))
13011 (defconst org-remember-help
13012 "Select a destination location for the note.
13013 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13014 RET on headline -> Store as sublevel entry to current headline
13015 RET at beg-of-buf -> Append to file as level 2 headline
13016 <left>/<right> -> before/after current headline, same headings level")
13018 (defvar org-remember-previous-location nil)
13019 (defvar org-force-remember-template-char) ;; dynamically scoped
13021 (defun org-select-remember-template (&optional use-char)
13022 (when org-remember-templates
13023 (let* ((templates (mapcar (lambda (x)
13024 (if (stringp (car x))
13025 (append (list (nth 1 x) (car x)) (cddr x))
13026 (append (list (car x) "") (cdr x))))
13027 org-remember-templates))
13028 (char (or use-char
13029 (cond
13030 ((= (length templates) 1)
13031 (caar templates))
13032 ((and (boundp 'org-force-remember-template-char)
13033 org-force-remember-template-char)
13034 (if (stringp org-force-remember-template-char)
13035 (string-to-char org-force-remember-template-char)
13036 org-force-remember-template-char))
13038 (message "Select template: %s"
13039 (mapconcat
13040 (lambda (x)
13041 (cond
13042 ((not (string-match "\\S-" (nth 1 x)))
13043 (format "[%c]" (car x)))
13044 ((equal (downcase (car x))
13045 (downcase (aref (nth 1 x) 0)))
13046 (format "[%c]%s" (car x)
13047 (substring (nth 1 x) 1)))
13048 (t (format "[%c]%s" (car x) (nth 1 x)))))
13049 templates " "))
13050 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13051 (when (equal char0 ?\C-g)
13052 (jump-to-register remember-register)
13053 (kill-buffer remember-buffer))
13054 char0))))))
13055 (cddr (assoc char templates)))))
13057 (defvar x-last-selected-text)
13058 (defvar x-last-selected-text-primary)
13060 ;;;###autoload
13061 (defun org-remember-apply-template (&optional use-char skip-interactive)
13062 "Initialize *remember* buffer with template, invoke `org-mode'.
13063 This function should be placed into `remember-mode-hook' and in fact requires
13064 to be run from that hook to function properly."
13065 (unless (fboundp 'remember-finalize)
13066 (defalias 'remember-finalize 'remember-buffer))
13067 (if org-remember-templates
13068 (let* ((entry (org-select-remember-template use-char))
13069 (tpl (car entry))
13070 (plist-p (if org-store-link-plist t nil))
13071 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13072 (string-match "\\S-" (nth 1 entry)))
13073 (nth 1 entry)
13074 org-default-notes-file))
13075 (headline (nth 2 entry))
13076 (v-c (or (and (eq window-system 'x)
13077 (fboundp 'x-cut-buffer-or-selection-value)
13078 (x-cut-buffer-or-selection-value))
13079 (org-bound-and-true-p x-last-selected-text)
13080 (org-bound-and-true-p x-last-selected-text-primary)
13081 (and (> (length kill-ring) 0) (current-kill 0))))
13082 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13083 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13084 (v-u (concat "[" (substring v-t 1 -1) "]"))
13085 (v-U (concat "[" (substring v-T 1 -1) "]"))
13086 ;; `initial' and `annotation' are bound in `remember'
13087 (v-i (if (boundp 'initial) initial))
13088 (v-a (if (and (boundp 'annotation) annotation)
13089 (if (equal annotation "[[]]") "" annotation)
13090 ""))
13091 (v-A (if (and v-a
13092 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13093 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13094 v-a))
13095 (v-n user-full-name)
13096 (org-startup-folded nil)
13097 org-time-was-given org-end-time-was-given x prompt char time pos)
13098 (setq org-store-link-plist
13099 (append (list :annotation v-a :initial v-i)
13100 org-store-link-plist))
13101 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13102 (erase-buffer)
13103 (insert (substitute-command-keys
13104 (format
13105 "## Filing location: Select interactively, default, or last used:
13106 ## %s to select file and header location interactively.
13107 ## %s \"%s\" -> \"* %s\"
13108 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13109 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13110 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13111 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13112 (abbreviate-file-name (or file org-default-notes-file))
13113 (or headline "")
13114 (or (car org-remember-previous-location) "???")
13115 (or (cdr org-remember-previous-location) "???"))))
13116 (insert tpl) (goto-char (point-min))
13117 ;; Simple %-escapes
13118 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13119 (when (and initial (equal (match-string 0) "%i"))
13120 (save-match-data
13121 (let* ((lead (buffer-substring
13122 (point-at-bol) (match-beginning 0))))
13123 (setq v-i (mapconcat 'identity
13124 (org-split-string initial "\n")
13125 (concat "\n" lead))))))
13126 (replace-match
13127 (or (eval (intern (concat "v-" (match-string 1)))) "")
13128 t t))
13130 ;; %[] Insert contents of a file.
13131 (goto-char (point-min))
13132 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13133 (let ((start (match-beginning 0))
13134 (end (match-end 0))
13135 (filename (expand-file-name (match-string 1))))
13136 (goto-char start)
13137 (delete-region start end)
13138 (condition-case error
13139 (insert-file-contents filename)
13140 (error (insert (format "%%![Couldn't insert %s: %s]"
13141 filename error))))))
13142 ;; %() embedded elisp
13143 (goto-char (point-min))
13144 (while (re-search-forward "%\\((.+)\\)" nil t)
13145 (goto-char (match-beginning 0))
13146 (let ((template-start (point)))
13147 (forward-char 1)
13148 (let ((result
13149 (condition-case error
13150 (eval (read (current-buffer)))
13151 (error (format "%%![Error: %s]" error)))))
13152 (delete-region template-start (point))
13153 (insert result))))
13155 ;; From the property list
13156 (when plist-p
13157 (goto-char (point-min))
13158 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13159 (and (setq x (or (plist-get org-store-link-plist
13160 (intern (match-string 1))) ""))
13161 (replace-match x t t))))
13163 ;; Turn on org-mode in the remember buffer, set local variables
13164 (org-mode)
13165 (org-set-local 'org-finish-function 'remember-finalize)
13166 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13167 (org-set-local 'org-default-notes-file file))
13168 (if (and headline (stringp headline) (string-match "\\S-" headline))
13169 (org-set-local 'org-remember-default-headline headline))
13170 ;; Interactive template entries
13171 (goto-char (point-min))
13172 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([guUtT]\\)?" nil t)
13173 (setq char (if (match-end 3) (match-string 3))
13174 prompt (if (match-end 2) (match-string 2)))
13175 (goto-char (match-beginning 0))
13176 (replace-match "")
13177 (cond
13178 ((member char '("G" "g"))
13179 (let* ((org-last-tags-completion-table
13180 (org-global-tags-completion-table
13181 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13182 (org-add-colon-after-tag-completion t)
13183 (ins (completing-read
13184 (if prompt (concat prompt ": ") "Tags: ")
13185 'org-tags-completion-function nil nil nil
13186 'org-tags-history)))
13187 (setq ins (mapconcat 'identity
13188 (org-split-string ins (org-re "[^[:alnum:]]+"))
13189 ":"))
13190 (when (string-match "\\S-" ins)
13191 (or (equal (char-before) ?:) (insert ":"))
13192 (insert ins)
13193 (or (equal (char-after) ?:) (insert ":")))))
13194 (char
13195 (setq org-time-was-given (equal (upcase char) char))
13196 (setq time (org-read-date (equal (upcase char) "U") t nil
13197 prompt))
13198 (org-insert-time-stamp time org-time-was-given
13199 (member char '("u" "U"))
13200 nil nil (list org-end-time-was-given)))
13202 (insert (read-string
13203 (if prompt (concat prompt ": ") "Enter string"))))))
13204 (goto-char (point-min))
13205 (if (re-search-forward "%\\?" nil t)
13206 (replace-match "")
13207 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13208 (org-mode)
13209 (org-set-local 'org-finish-function 'remember-finalize)))
13211 ;;;###autoload
13212 (defun org-remember (&optional goto org-force-remember-template-char)
13213 "Call `remember'. If this is already a remember buffer, re-apply template.
13214 If there is an active region, make sure remember uses it as initial content
13215 of the remember buffer.
13217 When called interactively with a `C-u' prefix argument GOTO, don't remember
13218 anything, just go to the file/headline where the selected templated usually
13219 stores its notes.
13221 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13222 associated with a template in `org-remember-tempates'."
13223 (interactive "P")
13224 (if (equal goto '(4))
13225 (org-go-to-remember-target)
13226 (if (eq org-finish-function 'remember-buffer)
13227 (progn
13228 (when (< (length org-remember-templates) 2)
13229 (error "No other template available"))
13230 (erase-buffer)
13231 (let ((annotation (plist-get org-store-link-plist :annotation))
13232 (initial (plist-get org-store-link-plist :initial)))
13233 (org-remember-apply-template))
13234 (message "Press C-c C-c to remember data"))
13235 (if (org-region-active-p)
13236 (remember (buffer-substring (point) (mark)))
13237 (call-interactively 'remember)))))
13239 (defun org-go-to-remember-target (&optional template-key)
13240 "Go to the target location of a remember template.
13241 The user is queried for the template."
13242 (interactive)
13243 (let* ((entry (org-select-remember-template template-key))
13244 (file (nth 1 entry))
13245 (heading (nth 2 entry))
13246 visiting)
13247 (unless (and file (stringp file) (string-match "\\S-" file))
13248 (setq file org-default-notes-file))
13249 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13250 (setq heading org-remember-default-headline))
13251 (setq visiting (org-find-base-buffer-visiting file))
13252 (if (not visiting) (find-file-noselect file))
13253 (switch-to-buffer (or visiting (get-file-buffer file)))
13254 (widen)
13255 (goto-char (point-min))
13256 (if (re-search-forward
13257 (concat "^\\*+[ \t]+" (regexp-quote heading)
13258 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13259 nil t)
13260 (goto-char (match-beginning 0))
13261 (error "Target headline not found: %s" heading))))
13263 (defvar org-note-abort nil) ; dynamically scoped
13265 ;;;###autoload
13266 (defun org-remember-handler ()
13267 "Store stuff from remember.el into an org file.
13268 First prompts for an org file. If the user just presses return, the value
13269 of `org-default-notes-file' is used.
13270 Then the command offers the headings tree of the selected file in order to
13271 file the text at a specific location.
13272 You can either immediately press RET to get the note appended to the
13273 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13274 find a better place. Then press RET or <left> or <right> in insert the note.
13276 Key Cursor position Note gets inserted
13277 -----------------------------------------------------------------------------
13278 RET buffer-start as level 1 heading at end of file
13279 RET on headline as sublevel of the heading at cursor
13280 RET no heading at cursor position, level taken from context.
13281 Or use prefix arg to specify level manually.
13282 <left> on headline as same level, before current heading
13283 <right> on headline as same level, after current heading
13285 So the fastest way to store the note is to press RET RET to append it to
13286 the default file. This way your current train of thought is not
13287 interrupted, in accordance with the principles of remember.el.
13288 You can also get the fast execution without prompting by using
13289 C-u C-c C-c to exit the remember buffer. See also the variable
13290 `org-remember-store-without-prompt'.
13292 Before being stored away, the function ensures that the text has a
13293 headline, i.e. a first line that starts with a \"*\". If not, a headline
13294 is constructed from the current date and some additional data.
13296 If the variable `org-adapt-indentation' is non-nil, the entire text is
13297 also indented so that it starts in the same column as the headline
13298 \(i.e. after the stars).
13300 See also the variable `org-reverse-note-order'."
13301 (goto-char (point-min))
13302 (while (looking-at "^[ \t]*\n\\|^##.*\n")
13303 (replace-match ""))
13304 (goto-char (point-max))
13305 (catch 'quit
13306 (if org-note-abort (throw 'quit nil))
13307 (let* ((txt (buffer-substring (point-min) (point-max)))
13308 (fastp (org-xor (equal current-prefix-arg '(4))
13309 org-remember-store-without-prompt))
13310 (file (if fastp org-default-notes-file (org-get-org-file)))
13311 (heading org-remember-default-headline)
13312 (visiting (org-find-base-buffer-visiting file))
13313 (org-startup-folded nil)
13314 (org-startup-align-all-tables nil)
13315 (org-goto-start-pos 1)
13316 spos exitcmd level indent reversed)
13317 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
13318 (setq file (car org-remember-previous-location)
13319 heading (cdr org-remember-previous-location)))
13320 (setq current-prefix-arg nil)
13321 ;; Modify text so that it becomes a nice subtree which can be inserted
13322 ;; into an org tree.
13323 (let* ((lines (split-string txt "\n"))
13324 first)
13325 (setq first (car lines) lines (cdr lines))
13326 (if (string-match "^\\*+ " first)
13327 ;; Is already a headline
13328 (setq indent nil)
13329 ;; We need to add a headline: Use time and first buffer line
13330 (setq lines (cons first lines)
13331 first (concat "* " (current-time-string)
13332 " (" (remember-buffer-desc) ")")
13333 indent " "))
13334 (if (and org-adapt-indentation indent)
13335 (setq lines (mapcar
13336 (lambda (x)
13337 (if (string-match "\\S-" x)
13338 (concat indent x) x))
13339 lines)))
13340 (setq txt (concat first "\n"
13341 (mapconcat 'identity lines "\n"))))
13342 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
13343 (setq txt (replace-match "\n\n" t t txt))
13344 (if (string-match "[ \t\n]*\\'" txt)
13345 (setq txt (replace-match "\n" t t txt))))
13346 ;; Find the file
13347 (if (not visiting) (find-file-noselect file))
13348 (with-current-buffer (or visiting (get-file-buffer file))
13349 (unless (org-mode-p)
13350 (error "Target files for remember notes must be in Org-mode"))
13351 (save-excursion
13352 (save-restriction
13353 (widen)
13354 (and (goto-char (point-min))
13355 (not (re-search-forward "^\\* " nil t))
13356 (insert "\n* " (or heading "Notes") "\n"))
13357 (setq reversed (org-notes-order-reversed-p))
13359 ;; Find the default location
13360 (when (and heading (stringp heading) (string-match "\\S-" heading))
13361 (goto-char (point-min))
13362 (if (re-search-forward
13363 (concat "^\\*+[ \t]+" (regexp-quote heading)
13364 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13365 nil t)
13366 (setq org-goto-start-pos (match-beginning 0))
13367 (when fastp
13368 (goto-char (point-max))
13369 (unless (bolp) (newline))
13370 (insert "* " heading "\n")
13371 (setq org-goto-start-pos (point-at-bol 0)))))
13373 ;; Ask the User for a location
13374 (if fastp
13375 (setq spos org-goto-start-pos
13376 exitcmd 'return)
13377 (setq spos (org-get-location (current-buffer) org-remember-help)
13378 exitcmd (cdr spos)
13379 spos (car spos)))
13380 (if (not spos) (throw 'quit nil)) ; return nil to show we did
13381 ; not handle this note
13382 (goto-char spos)
13383 (cond ((org-on-heading-p t)
13384 (org-back-to-heading t)
13385 (setq level (funcall outline-level))
13386 (cond
13387 ((eq exitcmd 'return)
13388 ;; sublevel of current
13389 (setq org-remember-previous-location
13390 (cons (abbreviate-file-name file)
13391 (org-get-heading 'notags)))
13392 (if reversed
13393 (outline-next-heading)
13394 (org-end-of-subtree)
13395 (if (not (bolp))
13396 (if (looking-at "[ \t]*\n")
13397 (beginning-of-line 2)
13398 (end-of-line 1)
13399 (insert "\n"))))
13400 (org-paste-subtree (org-get-legal-level level 1) txt))
13401 ((eq exitcmd 'left)
13402 ;; before current
13403 (org-paste-subtree level txt))
13404 ((eq exitcmd 'right)
13405 ;; after current
13406 (org-end-of-subtree t)
13407 (org-paste-subtree level txt))
13408 (t (error "This should not happen"))))
13410 ((and (bobp) (not reversed))
13411 ;; Put it at the end, one level below level 1
13412 (save-restriction
13413 (widen)
13414 (goto-char (point-max))
13415 (if (not (bolp)) (newline))
13416 (org-paste-subtree (org-get-legal-level 1 1) txt)))
13418 ((and (bobp) reversed)
13419 ;; Put it at the start, as level 1
13420 (save-restriction
13421 (widen)
13422 (goto-char (point-min))
13423 (re-search-forward "^\\*+ " nil t)
13424 (beginning-of-line 1)
13425 (org-paste-subtree 1 txt)))
13427 ;; Put it right there, with automatic level determined by
13428 ;; org-paste-subtree or from prefix arg
13429 (org-paste-subtree
13430 (if (numberp current-prefix-arg) current-prefix-arg)
13431 txt)))
13432 (when remember-save-after-remembering
13433 (save-buffer)
13434 (if (not visiting) (kill-buffer (current-buffer)))))))))
13435 t) ;; return t to indicate that we took care of this note.
13437 (defun org-get-org-file ()
13438 "Read a filename, with default directory `org-directory'."
13439 (let ((default (or org-default-notes-file remember-data-file)))
13440 (read-file-name (format "File name [%s]: " default)
13441 (file-name-as-directory org-directory)
13442 default)))
13444 (defun org-notes-order-reversed-p ()
13445 "Check if the current file should receive notes in reversed order."
13446 (cond
13447 ((not org-reverse-note-order) nil)
13448 ((eq t org-reverse-note-order) t)
13449 ((not (listp org-reverse-note-order)) nil)
13450 (t (catch 'exit
13451 (let ((all org-reverse-note-order)
13452 entry)
13453 (while (setq entry (pop all))
13454 (if (string-match (car entry) buffer-file-name)
13455 (throw 'exit (cdr entry))))
13456 nil)))))
13458 ;;; Refiling
13460 (defvar org-refile-target-table nil
13461 "The list of refile targets, created by `org-refile'.")
13463 (defvar org-agenda-new-buffers nil
13464 "Buffers created to visit agenda files.")
13466 (defun org-get-refile-targets ()
13467 "Produce a table with refile targets."
13468 (let ((entries org-refile-targets)
13469 org-agenda-new-files targets txt re files f desc descre)
13470 (while (setq entry (pop entries))
13471 (setq files (car entry) desc (cdr entry))
13472 (cond
13473 ((null files) (setq files (list (current-buffer))))
13474 ((eq files 'org-agenda-files)
13475 (setq files (org-agenda-files 'unrestricted)))
13476 ((and (symbolp files) (fboundp files))
13477 (setq files (funcall files)))
13478 ((and (symbolp files) (boundp files))
13479 (setq files (symbol-value files))))
13480 (if (stringp files) (setq files (list files)))
13481 (cond
13482 ((eq (car desc) :tag)
13483 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
13484 ((eq (car desc) :todo)
13485 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
13486 ((eq (car desc) :regexp)
13487 (setq descre (cdr desc)))
13488 ((eq (car desc) :level)
13489 (setq descre (concat "^\\*\\{" (number-to-string
13490 (if org-odd-levels-only
13491 (1- (* 2 (cdr desc)))
13492 (cdr desc)))
13493 "\\}[ \t]")))
13494 (t (error "Bad refiling target description %s" desc)))
13495 (while (setq f (pop files))
13496 (save-excursion
13497 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
13498 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
13499 (save-excursion
13500 (save-restriction
13501 (widen)
13502 (goto-char (point-min))
13503 (while (re-search-forward descre nil t)
13504 (goto-char (point-at-bol))
13505 (when (looking-at org-complex-heading-regexp)
13506 (setq txt (match-string 4)
13507 re (concat "^" (regexp-quote
13508 (buffer-substring (match-beginning 1)
13509 (match-end 4)))))
13510 (if (match-end 5) (setq re (concat re "[ \t]+"
13511 (regexp-quote
13512 (match-string 5)))))
13513 (setq re (concat re "[ \t]*$"))
13514 (push (list txt f re (point)) targets))
13515 (goto-char (point-at-eol))))))))
13516 (org-release-buffers org-agenda-new-buffers)
13517 (nreverse targets)))
13519 (defun org-refile (&optional reversed-or-update)
13520 "Move the entry at point to another heading.
13521 The list of target headings is compiled using the information in
13522 `org-refile-targets', which see. This list is created upon first use, and
13523 you can update it by calling this command with a double prefix (`C-u C-u').
13525 At the target location, the entry is filed as a subitem of the target heading.
13526 Depending on `org-reverse-note-order', the new subitem will either be the
13527 first of the last subitem. A single C-u prefix will toggle the value of this
13528 variable for the duration of the command."
13529 (interactive "P")
13530 (if (equal reversed-or-update '(16))
13531 (progn
13532 (setq org-refile-target-table (org-get-refile-targets))
13533 (message "Refile targets updated (%d targets)"
13534 (length org-refile-target-table)))
13535 (when (or (not org-refile-target-table)
13536 (and (= (length org-refile-targets) 1)
13537 (not (caar org-refile-targets))))
13538 (setq org-refile-target-table (org-get-refile-targets)))
13539 (unless org-refile-target-table
13540 (error "No refile targets"))
13541 (let* ((cbuf (current-buffer))
13542 (filename (buffer-file-name (buffer-base-buffer cbuf)))
13543 (fname (and filename (file-truename filename)))
13544 (tbl (mapcar
13545 (lambda (x)
13546 (if (not (equal fname (file-truename (nth 1 x))))
13547 (cons (concat (car x) " (" (file-name-nondirectory
13548 (nth 1 x)) ")")
13549 (cdr x))
13551 org-refile-target-table))
13552 (completion-ignore-case t)
13553 pos it nbuf file re level reversed)
13554 (when (setq it (completing-read "Refile to: " tbl
13555 nil t nil 'org-refile-history))
13556 (setq it (assoc it tbl)
13557 file (nth 1 it)
13558 re (nth 2 it))
13559 (org-copy-special)
13560 (save-excursion
13561 (set-buffer (setq nbuf (or (find-buffer-visiting file)
13562 (find-file-noselect file))))
13563 (setq reversed (org-notes-order-reversed-p))
13564 (if (equal reversed-or-update '(16)) (setq reversed (not reversed)))
13565 (save-excursion
13566 (save-restriction
13567 (widen)
13568 (goto-char (point-min))
13569 (unless (re-search-forward re nil t)
13570 (error "Cannot find target location - try again with `C-u' prefix."))
13571 (goto-char (match-beginning 0))
13572 (looking-at outline-regexp)
13573 (setq level (org-get-legal-level (funcall outline-level) 1))
13574 (goto-char (or (save-excursion
13575 (if reversed
13576 (outline-next-heading)
13577 (outline-get-next-sibling)))
13578 (point-max)))
13579 (org-paste-subtree level))))
13580 (org-cut-special)
13581 (message "Entry refiled to \"%s\"" (car it))))))
13583 ;;;; Dynamic blocks
13585 (defun org-find-dblock (name)
13586 "Find the first dynamic block with name NAME in the buffer.
13587 If not found, stay at current position and return nil."
13588 (let (pos)
13589 (save-excursion
13590 (goto-char (point-min))
13591 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
13592 nil t)
13593 (match-beginning 0))))
13594 (if pos (goto-char pos))
13595 pos))
13597 (defconst org-dblock-start-re
13598 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
13599 "Matches the startline of a dynamic block, with parameters.")
13601 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
13602 "Matches the end of a dyhamic block.")
13604 (defun org-create-dblock (plist)
13605 "Create a dynamic block section, with parameters taken from PLIST.
13606 PLIST must containe a :name entry which is used as name of the block."
13607 (unless (bolp) (newline))
13608 (let ((name (plist-get plist :name)))
13609 (insert "#+BEGIN: " name)
13610 (while plist
13611 (if (eq (car plist) :name)
13612 (setq plist (cddr plist))
13613 (insert " " (prin1-to-string (pop plist)))))
13614 (insert "\n\n#+END:\n")
13615 (beginning-of-line -2)))
13617 (defun org-prepare-dblock ()
13618 "Prepare dynamic block for refresh.
13619 This empties the block, puts the cursor at the insert position and returns
13620 the property list including an extra property :name with the block name."
13621 (unless (looking-at org-dblock-start-re)
13622 (error "Not at a dynamic block"))
13623 (let* ((begdel (1+ (match-end 0)))
13624 (name (org-no-properties (match-string 1)))
13625 (params (append (list :name name)
13626 (read (concat "(" (match-string 3) ")")))))
13627 (unless (re-search-forward org-dblock-end-re nil t)
13628 (error "Dynamic block not terminated"))
13629 (delete-region begdel (match-beginning 0))
13630 (goto-char begdel)
13631 (open-line 1)
13632 params))
13634 (defun org-map-dblocks (&optional command)
13635 "Apply COMMAND to all dynamic blocks in the current buffer.
13636 If COMMAND is not given, use `org-update-dblock'."
13637 (let ((cmd (or command 'org-update-dblock))
13638 pos)
13639 (save-excursion
13640 (goto-char (point-min))
13641 (while (re-search-forward org-dblock-start-re nil t)
13642 (goto-char (setq pos (match-beginning 0)))
13643 (condition-case nil
13644 (funcall cmd)
13645 (error (message "Error during update of dynamic block")))
13646 (goto-char pos)
13647 (unless (re-search-forward org-dblock-end-re nil t)
13648 (error "Dynamic block not terminated"))))))
13650 (defun org-dblock-update (&optional arg)
13651 "User command for updating dynamic blocks.
13652 Update the dynamic block at point. With prefix ARG, update all dynamic
13653 blocks in the buffer."
13654 (interactive "P")
13655 (if arg
13656 (org-update-all-dblocks)
13657 (or (looking-at org-dblock-start-re)
13658 (org-beginning-of-dblock))
13659 (org-update-dblock)))
13661 (defun org-update-dblock ()
13662 "Update the dynamic block at point
13663 This means to empty the block, parse for parameters and then call
13664 the correct writing function."
13665 (save-window-excursion
13666 (let* ((pos (point))
13667 (line (org-current-line))
13668 (params (org-prepare-dblock))
13669 (name (plist-get params :name))
13670 (cmd (intern (concat "org-dblock-write:" name))))
13671 (message "Updating dynamic block `%s' at line %d..." name line)
13672 (funcall cmd params)
13673 (message "Updating dynamic block `%s' at line %d...done" name line)
13674 (goto-char pos))))
13676 (defun org-beginning-of-dblock ()
13677 "Find the beginning of the dynamic block at point.
13678 Error if there is no scuh block at point."
13679 (let ((pos (point))
13680 beg)
13681 (end-of-line 1)
13682 (if (and (re-search-backward org-dblock-start-re nil t)
13683 (setq beg (match-beginning 0))
13684 (re-search-forward org-dblock-end-re nil t)
13685 (> (match-end 0) pos))
13686 (goto-char beg)
13687 (goto-char pos)
13688 (error "Not in a dynamic block"))))
13690 (defun org-update-all-dblocks ()
13691 "Update all dynamic blocks in the buffer.
13692 This function can be used in a hook."
13693 (when (org-mode-p)
13694 (org-map-dblocks 'org-update-dblock)))
13697 ;;;; Completion
13699 (defconst org-additional-option-like-keywords
13700 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
13701 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
13702 "BEGIN_EXAMPLE" "END_EXAMPLE"))
13704 (defun org-complete (&optional arg)
13705 "Perform completion on word at point.
13706 At the beginning of a headline, this completes TODO keywords as given in
13707 `org-todo-keywords'.
13708 If the current word is preceded by a backslash, completes the TeX symbols
13709 that are supported for HTML support.
13710 If the current word is preceded by \"#+\", completes special words for
13711 setting file options.
13712 In the line after \"#+STARTUP:, complete valid keywords.\"
13713 At all other locations, this simply calls the value of
13714 `org-completion-fallback-command'."
13715 (interactive "P")
13716 (org-without-partial-completion
13717 (catch 'exit
13718 (let* ((end (point))
13719 (beg1 (save-excursion
13720 (skip-chars-backward (org-re "[:alnum:]_@"))
13721 (point)))
13722 (beg (save-excursion
13723 (skip-chars-backward "a-zA-Z0-9_:$")
13724 (point)))
13725 (confirm (lambda (x) (stringp (car x))))
13726 (searchhead (equal (char-before beg) ?*))
13727 (tag (and (equal (char-before beg1) ?:)
13728 (equal (char-after (point-at-bol)) ?*)))
13729 (prop (and (equal (char-before beg1) ?:)
13730 (not (equal (char-after (point-at-bol)) ?*))))
13731 (texp (equal (char-before beg) ?\\))
13732 (link (equal (char-before beg) ?\[))
13733 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
13734 beg)
13735 "#+"))
13736 (startup (string-match "^#\\+STARTUP:.*"
13737 (buffer-substring (point-at-bol) (point))))
13738 (completion-ignore-case opt)
13739 (type nil)
13740 (tbl nil)
13741 (table (cond
13742 (opt
13743 (setq type :opt)
13744 (append
13745 (mapcar
13746 (lambda (x)
13747 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
13748 (cons (match-string 2 x) (match-string 1 x)))
13749 (org-split-string (org-get-current-options) "\n"))
13750 (mapcar 'list org-additional-option-like-keywords)))
13751 (startup
13752 (setq type :startup)
13753 org-startup-options)
13754 (link (append org-link-abbrev-alist-local
13755 org-link-abbrev-alist))
13756 (texp
13757 (setq type :tex)
13758 org-html-entities)
13759 ((string-match "\\`\\*+[ \t]+\\'"
13760 (buffer-substring (point-at-bol) beg))
13761 (setq type :todo)
13762 (mapcar 'list org-todo-keywords-1))
13763 (searchhead
13764 (setq type :searchhead)
13765 (save-excursion
13766 (goto-char (point-min))
13767 (while (re-search-forward org-todo-line-regexp nil t)
13768 (push (list
13769 (org-make-org-heading-search-string
13770 (match-string 3) t))
13771 tbl)))
13772 tbl)
13773 (tag (setq type :tag beg beg1)
13774 (or org-tag-alist (org-get-buffer-tags)))
13775 (prop (setq type :prop beg beg1)
13776 (mapcar 'list (org-buffer-property-keys)))
13777 (t (progn
13778 (call-interactively org-completion-fallback-command)
13779 (throw 'exit nil)))))
13780 (pattern (buffer-substring-no-properties beg end))
13781 (completion (try-completion pattern table confirm)))
13782 (cond ((eq completion t)
13783 (if (not (assoc (upcase pattern) table))
13784 (message "Already complete")
13785 (if (equal type :opt)
13786 (insert (substring (cdr (assoc (upcase pattern) table))
13787 (length pattern)))
13788 (if (memq type '(:tag :prop)) (insert ":")))))
13789 ((null completion)
13790 (message "Can't find completion for \"%s\"" pattern)
13791 (ding))
13792 ((not (string= pattern completion))
13793 (delete-region beg end)
13794 (if (string-match " +$" completion)
13795 (setq completion (replace-match "" t t completion)))
13796 (insert completion)
13797 (if (get-buffer-window "*Completions*")
13798 (delete-window (get-buffer-window "*Completions*")))
13799 (if (assoc completion table)
13800 (if (eq type :todo) (insert " ")
13801 (if (memq type '(:tag :prop)) (insert ":"))))
13802 (if (and (equal type :opt) (assoc completion table))
13803 (message "%s" (substitute-command-keys
13804 "Press \\[org-complete] again to insert example settings"))))
13806 (message "Making completion list...")
13807 (let ((list (sort (all-completions pattern table confirm)
13808 'string<)))
13809 (with-output-to-temp-buffer "*Completions*"
13810 (condition-case nil
13811 ;; Protection needed for XEmacs and emacs 21
13812 (display-completion-list list pattern)
13813 (error (display-completion-list list)))))
13814 (message "Making completion list...%s" "done")))))))
13816 ;;;; TODO, DEADLINE, Comments
13818 (defun org-toggle-comment ()
13819 "Change the COMMENT state of an entry."
13820 (interactive)
13821 (save-excursion
13822 (org-back-to-heading)
13823 (let (case-fold-search)
13824 (if (looking-at (concat outline-regexp
13825 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
13826 (replace-match "" t t nil 1)
13827 (if (looking-at outline-regexp)
13828 (progn
13829 (goto-char (match-end 0))
13830 (insert org-comment-string " ")))))))
13832 (defvar org-last-todo-state-is-todo nil
13833 "This is non-nil when the last TODO state change led to a TODO state.
13834 If the last change removed the TODO tag or switched to DONE, then
13835 this is nil.")
13837 (defvar org-setting-tags nil) ; dynamically skiped
13839 ;; FIXME: better place
13840 (defun org-property-or-variable-value (var &optional inherit)
13841 "Check if there is a property fixing the value of VAR.
13842 If yes, return this value. If not, return the current value of the variable."
13843 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13844 (if (and prop (stringp prop) (string-match "\\S-" prop))
13845 (read prop)
13846 (symbol-value var))))
13848 (defun org-parse-local-options (string var)
13849 "Parse STRING for startup setting relevant for variable VAR."
13850 (let ((rtn (symbol-value var))
13851 e opts)
13852 (save-match-data
13853 (if (or (not string) (not (string-match "\\S-" string)))
13855 (setq opts (delq nil (mapcar (lambda (x)
13856 (setq e (assoc x org-startup-options))
13857 (if (eq (nth 1 e) var) e nil))
13858 (org-split-string string "[ \t]+"))))
13859 (if (not opts)
13861 (setq rtn nil)
13862 (while (setq e (pop opts))
13863 (if (not (nth 3 e))
13864 (setq rtn (nth 2 e))
13865 (if (not (listp rtn)) (setq rtn nil))
13866 (push (nth 2 e) rtn)))
13867 rtn)))))
13869 (defvar org-blocker-hook nil
13870 "Hook for functions that are allowed to block a state change.
13872 Each function gets as its single argument a property list, see
13873 `org-trigger-hook' for more information about this list.
13875 If any of the functions in this hook returns nil, the state change
13876 is blocked.")
13878 (defvar org-trigger-hook nil
13879 "Hook for functions that are triggered by a state change.
13881 Each function gets as its single argument a property list with at least
13882 the following elements:
13884 (:type type-of-change :position pos-at-entry-start
13885 :from old-state :to new-state)
13887 Depending on the type, more properties may be present.
13889 This mechanism is currently implemented for:
13891 TODO state changes
13892 ------------------
13893 :type todo-state-change
13894 :from previous state (keyword as a string), or nil
13895 :to new state (keyword as a string), or nil")
13898 (defun org-todo (&optional arg)
13899 "Change the TODO state of an item.
13900 The state of an item is given by a keyword at the start of the heading,
13901 like
13902 *** TODO Write paper
13903 *** DONE Call mom
13905 The different keywords are specified in the variable `org-todo-keywords'.
13906 By default the available states are \"TODO\" and \"DONE\".
13907 So for this example: when the item starts with TODO, it is changed to DONE.
13908 When it starts with DONE, the DONE is removed. And when neither TODO nor
13909 DONE are present, add TODO at the beginning of the heading.
13911 With C-u prefix arg, use completion to determine the new state.
13912 With numeric prefix arg, switch to that state.
13914 For calling through lisp, arg is also interpreted in the following way:
13915 'none -> empty state
13916 \"\"(empty string) -> switch to empty state
13917 'done -> switch to DONE
13918 'nextset -> switch to the next set of keywords
13919 'previousset -> switch to the previous set of keywords
13920 \"WAITING\" -> switch to the specified keyword, but only if it
13921 really is a member of `org-todo-keywords'."
13922 (interactive "P")
13923 (save-excursion
13924 (catch 'exit
13925 (org-back-to-heading)
13926 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
13927 (or (looking-at (concat " +" org-todo-regexp " *"))
13928 (looking-at " *"))
13929 (let* ((match-data (match-data))
13930 (startpos (point-at-bol))
13931 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
13932 (org-log-done (org-parse-local-options logging 'org-log-done))
13933 (org-log-repeat (org-parse-local-options logging 'org-log-repeat))
13934 (this (match-string 1))
13935 (hl-pos (match-beginning 0))
13936 (head (org-get-todo-sequence-head this))
13937 (ass (assoc head org-todo-kwd-alist))
13938 (interpret (nth 1 ass))
13939 (done-word (nth 3 ass))
13940 (final-done-word (nth 4 ass))
13941 (last-state (or this ""))
13942 (completion-ignore-case t)
13943 (member (member this org-todo-keywords-1))
13944 (tail (cdr member))
13945 (state (cond
13946 ((and org-todo-key-trigger
13947 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
13948 (and (not arg) org-use-fast-todo-selection
13949 (not (eq org-use-fast-todo-selection 'prefix)))))
13950 ;; Use fast selection
13951 (org-fast-todo-selection))
13952 ((and (equal arg '(4))
13953 (or (not org-use-fast-todo-selection)
13954 (not org-todo-key-trigger)))
13955 ;; Read a state with completion
13956 (completing-read "State: " (mapcar (lambda(x) (list x))
13957 org-todo-keywords-1)
13958 nil t))
13959 ((eq arg 'right)
13960 (if this
13961 (if tail (car tail) nil)
13962 (car org-todo-keywords-1)))
13963 ((eq arg 'left)
13964 (if (equal member org-todo-keywords-1)
13966 (if this
13967 (nth (- (length org-todo-keywords-1) (length tail) 2)
13968 org-todo-keywords-1)
13969 (org-last org-todo-keywords-1))))
13970 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
13971 (setq arg nil))) ; hack to fall back to cycling
13972 (arg
13973 ;; user or caller requests a specific state
13974 (cond
13975 ((equal arg "") nil)
13976 ((eq arg 'none) nil)
13977 ((eq arg 'done) (or done-word (car org-done-keywords)))
13978 ((eq arg 'nextset)
13979 (or (car (cdr (member head org-todo-heads)))
13980 (car org-todo-heads)))
13981 ((eq arg 'previousset)
13982 (let ((org-todo-heads (reverse org-todo-heads)))
13983 (or (car (cdr (member head org-todo-heads)))
13984 (car org-todo-heads))))
13985 ((car (member arg org-todo-keywords-1)))
13986 ((nth (1- (prefix-numeric-value arg))
13987 org-todo-keywords-1))))
13988 ((null member) (or head (car org-todo-keywords-1)))
13989 ((equal this final-done-word) nil) ;; -> make empty
13990 ((null tail) nil) ;; -> first entry
13991 ((eq interpret 'sequence)
13992 (car tail))
13993 ((memq interpret '(type priority))
13994 (if (eq this-command last-command)
13995 (car tail)
13996 (if (> (length tail) 0)
13997 (or done-word (car org-done-keywords))
13998 nil)))
13999 (t nil)))
14000 (next (if state (concat " " state " ") " "))
14001 (change-plist (list :type 'todo-state-change :from this :to state
14002 :position startpos))
14003 dostates)
14004 (when org-blocker-hook
14005 (unless (save-excursion
14006 (save-match-data
14007 (run-hook-with-args-until-failure
14008 'org-blocker-hook change-plist)))
14009 (if (interactive-p)
14010 (error "TODO state change from %s to %s blocked" this state)
14011 ;; fail silently
14012 (message "TODO state change from %s to %s blocked" this state)
14013 (throw 'exit nil))))
14014 (store-match-data match-data)
14015 (replace-match next t t)
14016 (unless (pos-visible-in-window-p hl-pos)
14017 (message "TODO state changed to %s" (org-trim next)))
14018 (unless head
14019 (setq head (org-get-todo-sequence-head state)
14020 ass (assoc head org-todo-kwd-alist)
14021 interpret (nth 1 ass)
14022 done-word (nth 3 ass)
14023 final-done-word (nth 4 ass)))
14024 (when (memq arg '(nextset previousset))
14025 (message "Keyword-Set %d/%d: %s"
14026 (- (length org-todo-sets) -1
14027 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14028 (length org-todo-sets)
14029 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14030 (setq org-last-todo-state-is-todo
14031 (not (member state org-done-keywords)))
14032 (when (and org-log-done (not (memq arg '(nextset previousset))))
14033 (setq dostates (and (listp org-log-done) (memq 'state org-log-done)
14034 (or (not org-todo-log-states)
14035 (member state org-todo-log-states))))
14037 (cond
14038 ((and state (member state org-not-done-keywords)
14039 (not (member this org-not-done-keywords)))
14040 ;; This is now a todo state and was not one before
14041 ;; Remove any CLOSED timestamp, and possibly log the state change
14042 (org-add-planning-info nil nil 'closed)
14043 (and dostates (org-add-log-maybe 'state state 'findpos)))
14044 ((and state dostates)
14045 ;; This is a non-nil state, and we need to log it
14046 (org-add-log-maybe 'state state 'findpos))
14047 ((and (member state org-done-keywords)
14048 (not (member this org-done-keywords)))
14049 ;; It is now done, and it was not done before
14050 (org-add-planning-info 'closed (org-current-time))
14051 (org-add-log-maybe 'done state 'findpos))))
14052 ;; Fixup tag positioning
14053 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14054 (run-hooks 'org-after-todo-state-change-hook)
14055 (and (member state org-done-keywords) (org-auto-repeat-maybe))
14056 (if (and arg (not (member state org-done-keywords)))
14057 (setq head (org-get-todo-sequence-head state)))
14058 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14059 ;; Fixup cursor location if close to the keyword
14060 (if (and (outline-on-heading-p)
14061 (not (bolp))
14062 (save-excursion (beginning-of-line 1)
14063 (looking-at org-todo-line-regexp))
14064 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14065 (progn
14066 (goto-char (or (match-end 2) (match-end 1)))
14067 (just-one-space)))
14068 (when org-trigger-hook
14069 (save-excursion
14070 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14072 (defun org-get-todo-sequence-head (kwd)
14073 "Return the head of the TODO sequence to which KWD belongs.
14074 If KWD is not set, check if there is a text property remembering the
14075 right sequence."
14076 (let (p)
14077 (cond
14078 ((not kwd)
14079 (or (get-text-property (point-at-bol) 'org-todo-head)
14080 (progn
14081 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14082 nil (point-at-eol)))
14083 (get-text-property p 'org-todo-head))))
14084 ((not (member kwd org-todo-keywords-1))
14085 (car org-todo-keywords-1))
14086 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14088 (defun org-fast-todo-selection ()
14089 "Fast TODO keyword selection with single keys.
14090 Returns the new TODO keyword, or nil if no state change should occur."
14091 (let* ((fulltable org-todo-key-alist)
14092 (done-keywords org-done-keywords) ;; needed for the faces.
14093 (maxlen (apply 'max (mapcar
14094 (lambda (x)
14095 (if (stringp (car x)) (string-width (car x)) 0))
14096 fulltable)))
14097 (expert nil)
14098 (fwidth (+ maxlen 3 1 3))
14099 (ncol (/ (- (window-width) 4) fwidth))
14100 tg cnt e c tbl
14101 groups ingroup)
14102 (save-window-excursion
14103 (if expert
14104 (set-buffer (get-buffer-create " *Org todo*"))
14105 ; (delete-other-windows)
14106 ; (split-window-vertically)
14107 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14108 (erase-buffer)
14109 (org-set-local 'org-done-keywords done-keywords)
14110 (setq tbl fulltable cnt 0)
14111 (while (setq e (pop tbl))
14112 (cond
14113 ((equal e '(:startgroup))
14114 (push '() groups) (setq ingroup t)
14115 (when (not (= cnt 0))
14116 (setq cnt 0)
14117 (insert "\n"))
14118 (insert "{ "))
14119 ((equal e '(:endgroup))
14120 (setq ingroup nil cnt 0)
14121 (insert "}\n"))
14123 (setq tg (car e) c (cdr e))
14124 (if ingroup (push tg (car groups)))
14125 (setq tg (org-add-props tg nil 'face
14126 (org-get-todo-face tg)))
14127 (if (and (= cnt 0) (not ingroup)) (insert " "))
14128 (insert "[" c "] " tg (make-string
14129 (- fwidth 4 (length tg)) ?\ ))
14130 (when (= (setq cnt (1+ cnt)) ncol)
14131 (insert "\n")
14132 (if ingroup (insert " "))
14133 (setq cnt 0)))))
14134 (insert "\n")
14135 (goto-char (point-min))
14136 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14137 (fit-window-to-buffer))
14138 (message "[a-z..]:Set [SPC]:clear")
14139 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14140 (cond
14141 ((or (= c ?\C-g)
14142 (and (= c ?q) (not (rassoc c fulltable))))
14143 (setq quit-flag t))
14144 ((= c ?\ ) nil)
14145 ((setq e (rassoc c fulltable) tg (car e))
14147 (t (setq quit-flag t))))))
14149 (defun org-get-repeat ()
14150 "Check if tere is a deadline/schedule with repeater in this entry."
14151 (save-match-data
14152 (save-excursion
14153 (org-back-to-heading t)
14154 (if (re-search-forward
14155 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
14156 (match-string 1)))))
14158 (defvar org-last-changed-timestamp)
14159 (defvar org-log-post-message)
14160 (defun org-auto-repeat-maybe ()
14161 "Check if the current headline contains a repeated deadline/schedule.
14162 If yes, set TODO state back to what it was and change the base date
14163 of repeating deadline/scheduled time stamps to new date.
14164 This function should be run in the `org-after-todo-state-change-hook'."
14165 ;; last-state is dynamically scoped into this function
14166 (let* ((repeat (org-get-repeat))
14167 (aa (assoc last-state org-todo-kwd-alist))
14168 (interpret (nth 1 aa))
14169 (head (nth 2 aa))
14170 (done-word (nth 3 aa))
14171 (whata '(("d" . day) ("m" . month) ("y" . year)))
14172 (msg "Entry repeats: ")
14173 (org-log-done)
14174 re type n what ts)
14175 (when repeat
14176 (org-todo (if (eq interpret 'type) last-state head))
14177 (when (and org-log-repeat
14178 (not (memq 'org-add-log-note
14179 (default-value 'post-command-hook))))
14180 ;; Make sure a note is taken
14181 (let ((org-log-done '(done)))
14182 (org-add-log-maybe 'done (or done-word (car org-done-keywords))
14183 'findpos)))
14184 (org-back-to-heading t)
14185 (org-add-planning-info nil nil 'closed)
14186 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
14187 org-deadline-time-regexp "\\)"))
14188 (while (re-search-forward
14189 re (save-excursion (outline-next-heading) (point)) t)
14190 (setq type (if (match-end 1) org-scheduled-string org-deadline-string)
14191 ts (match-string (if (match-end 2) 2 4)))
14192 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
14193 (setq n (string-to-number (match-string 1 ts))
14194 what (match-string 2 ts))
14195 (if (equal what "w") (setq n (* n 7) what "d"))
14196 (org-timestamp-change n (cdr (assoc what whata))))
14197 (setq msg (concat msg type org-last-changed-timestamp " ")))
14198 (setq org-log-post-message msg)
14199 (message msg))))
14201 (defun org-show-todo-tree (arg)
14202 "Make a compact tree which shows all headlines marked with TODO.
14203 The tree will show the lines where the regexp matches, and all higher
14204 headlines above the match.
14205 With \\[universal-argument] prefix, also show the DONE entries.
14206 With a numeric prefix N, construct a sparse tree for the Nth element
14207 of `org-todo-keywords-1'."
14208 (interactive "P")
14209 (let ((case-fold-search nil)
14210 (kwd-re
14211 (cond ((null arg) org-not-done-regexp)
14212 ((equal arg '(4))
14213 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
14214 (mapcar 'list org-todo-keywords-1))))
14215 (concat "\\("
14216 (mapconcat 'identity (org-split-string kwd "|") "\\|")
14217 "\\)\\>")))
14218 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
14219 (regexp-quote (nth (1- (prefix-numeric-value arg))
14220 org-todo-keywords-1)))
14221 (t (error "Invalid prefix argument: %s" arg)))))
14222 (message "%d TODO entries found"
14223 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
14225 (defun org-deadline (&optional remove)
14226 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
14227 With argument REMOVE, remove any deadline from the item."
14228 (interactive "P")
14229 (if remove
14230 (progn
14231 (org-add-planning-info nil nil 'deadline)
14232 (message "Item no longer has a deadline."))
14233 (org-add-planning-info 'deadline nil 'closed)))
14235 (defun org-schedule (&optional remove)
14236 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
14237 With argument REMOVE, remove any scheduling date from the item."
14238 (interactive "P")
14239 (if remove
14240 (progn
14241 (org-add-planning-info nil nil 'scheduled)
14242 (message "Item is no longer scheduled."))
14243 (org-add-planning-info 'scheduled nil 'closed)))
14245 (defun org-add-planning-info (what &optional time &rest remove)
14246 "Insert new timestamp with keyword in the line directly after the headline.
14247 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
14248 If non is given, the user is prompted for a date.
14249 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
14250 be removed."
14251 (interactive)
14252 (let (org-time-was-given org-end-time-was-given)
14253 (when what (setq time (or time (org-read-date nil 'to-time))))
14254 (when (and org-insert-labeled-timestamps-at-point
14255 (member what '(scheduled deadline)))
14256 (insert
14257 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
14258 (org-insert-time-stamp time org-time-was-given
14259 nil nil nil (list org-end-time-was-given))
14260 (setq what nil))
14261 (save-excursion
14262 (save-restriction
14263 (let (col list elt ts buffer-invisibility-spec)
14264 (org-back-to-heading t)
14265 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
14266 (goto-char (match-end 1))
14267 (setq col (current-column))
14268 (goto-char (match-end 0))
14269 (if (eobp) (insert "\n") (forward-char 1))
14270 (if (and (not (looking-at outline-regexp))
14271 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
14272 "[^\r\n]*"))
14273 (not (equal (match-string 1) org-clock-string)))
14274 (narrow-to-region (match-beginning 0) (match-end 0))
14275 (insert-before-markers "\n")
14276 (backward-char 1)
14277 (narrow-to-region (point) (point))
14278 (indent-to-column col))
14279 ;; Check if we have to remove something.
14280 (setq list (cons what remove))
14281 (while list
14282 (setq elt (pop list))
14283 (goto-char (point-min))
14284 (when (or (and (eq elt 'scheduled)
14285 (re-search-forward org-scheduled-time-regexp nil t))
14286 (and (eq elt 'deadline)
14287 (re-search-forward org-deadline-time-regexp nil t))
14288 (and (eq elt 'closed)
14289 (re-search-forward org-closed-time-regexp nil t)))
14290 (replace-match "")
14291 (if (looking-at "--+<[^>]+>") (replace-match ""))
14292 (if (looking-at " +") (replace-match ""))))
14293 (goto-char (point-max))
14294 (when what
14295 (insert
14296 (if (not (equal (char-before) ?\ )) " " "")
14297 (cond ((eq what 'scheduled) org-scheduled-string)
14298 ((eq what 'deadline) org-deadline-string)
14299 ((eq what 'closed) org-closed-string))
14300 " ")
14301 (setq ts (org-insert-time-stamp
14302 time
14303 (or org-time-was-given
14304 (and (eq what 'closed) org-log-done-with-time))
14305 (eq what 'closed)
14306 nil nil (list org-end-time-was-given)))
14307 (end-of-line 1))
14308 (goto-char (point-min))
14309 (widen)
14310 (if (looking-at "[ \t]+\r?\n")
14311 (replace-match ""))
14312 ts)))))
14314 (defvar org-log-note-marker (make-marker))
14315 (defvar org-log-note-purpose nil)
14316 (defvar org-log-note-state nil)
14317 (defvar org-log-note-window-configuration nil)
14318 (defvar org-log-note-return-to (make-marker))
14319 (defvar org-log-post-message nil
14320 "Message to be displayed after a log note has been stored.
14321 The auto-repeater uses this.")
14323 (defun org-add-log-maybe (&optional purpose state findpos)
14324 "Set up the post command hook to take a note."
14325 (save-excursion
14326 (when (and (listp org-log-done)
14327 (memq purpose org-log-done))
14328 (when findpos
14329 (org-back-to-heading t)
14330 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
14331 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
14332 "[^\r\n]*\\)?"))
14333 (goto-char (match-end 0))
14334 (unless org-log-states-order-reversed
14335 (and (= (char-after) ?\n) (forward-char 1))
14336 (org-skip-over-state-notes)
14337 (skip-chars-backward " \t\n\r")))
14338 (move-marker org-log-note-marker (point))
14339 (setq org-log-note-purpose purpose)
14340 (setq org-log-note-state state)
14341 (add-hook 'post-command-hook 'org-add-log-note 'append))))
14343 (defun org-skip-over-state-notes ()
14344 "Skip past the list of State notes in an entry."
14345 (if (looking-at "\n[ \t]*- State") (forward-char 1))
14346 (while (looking-at "[ \t]*- State")
14347 (condition-case nil
14348 (org-next-item)
14349 (error (org-end-of-item)))))
14351 (defun org-add-log-note (&optional purpose)
14352 "Pop up a window for taking a note, and add this note later at point."
14353 (remove-hook 'post-command-hook 'org-add-log-note)
14354 (setq org-log-note-window-configuration (current-window-configuration))
14355 (delete-other-windows)
14356 (move-marker org-log-note-return-to (point))
14357 (switch-to-buffer (marker-buffer org-log-note-marker))
14358 (goto-char org-log-note-marker)
14359 (org-switch-to-buffer-other-window "*Org Note*")
14360 (erase-buffer)
14361 (let ((org-inhibit-startup t)) (org-mode))
14362 (insert (format "# Insert note for %s.
14363 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
14364 (cond
14365 ((eq org-log-note-purpose 'clock-out) "stopped clock")
14366 ((eq org-log-note-purpose 'done) "closed todo item")
14367 ((eq org-log-note-purpose 'state)
14368 (format "state change to \"%s\"" org-log-note-state))
14369 (t (error "This should not happen")))))
14370 (org-set-local 'org-finish-function 'org-store-log-note))
14372 (defun org-store-log-note ()
14373 "Finish taking a log note, and insert it to where it belongs."
14374 (let ((txt (buffer-string))
14375 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
14376 lines ind)
14377 (kill-buffer (current-buffer))
14378 (while (string-match "\\`#.*\n[ \t\n]*" txt)
14379 (setq txt (replace-match "" t t txt)))
14380 (if (string-match "\\s-+\\'" txt)
14381 (setq txt (replace-match "" t t txt)))
14382 (setq lines (org-split-string txt "\n"))
14383 (when (and note (string-match "\\S-" note))
14384 (setq note
14385 (org-replace-escapes
14386 note
14387 (list (cons "%u" (user-login-name))
14388 (cons "%U" user-full-name)
14389 (cons "%t" (format-time-string
14390 (org-time-stamp-format 'long 'inactive)
14391 (current-time)))
14392 (cons "%s" (if org-log-note-state
14393 (concat "\"" org-log-note-state "\"")
14394 "")))))
14395 (if lines (setq note (concat note " \\\\")))
14396 (push note lines))
14397 (when (or current-prefix-arg org-note-abort) (setq lines nil))
14398 (when lines
14399 (save-excursion
14400 (set-buffer (marker-buffer org-log-note-marker))
14401 (save-excursion
14402 (goto-char org-log-note-marker)
14403 (move-marker org-log-note-marker nil)
14404 (end-of-line 1)
14405 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
14406 (indent-relative nil)
14407 (insert "- " (pop lines))
14408 (org-indent-line-function)
14409 (beginning-of-line 1)
14410 (looking-at "[ \t]*")
14411 (setq ind (concat (match-string 0) " "))
14412 (end-of-line 1)
14413 (while lines (insert "\n" ind (pop lines)))))))
14414 (set-window-configuration org-log-note-window-configuration)
14415 (with-current-buffer (marker-buffer org-log-note-return-to)
14416 (goto-char org-log-note-return-to))
14417 (move-marker org-log-note-return-to nil)
14418 (and org-log-post-message (message org-log-post-message)))
14420 ;; FIXME: what else would be useful?
14421 ;; - priority
14422 ;; - date
14424 (defun org-sparse-tree (&optional arg)
14425 "Create a sparse tree, prompt for the details.
14426 This command can create sparse trees. You first need to select the type
14427 of match used to create the tree:
14429 t Show entries with a specific TODO keyword.
14430 T Show entries selected by a tags match.
14431 p Enter a property name and its value (both with completion on existing
14432 names/values) and show entries with that property.
14433 r Show entries matching a regular expression"
14434 (interactive "P")
14435 (let (ans kwd value)
14436 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines")
14437 (setq ans (read-char-exclusive))
14438 (cond
14439 ((equal ans ?d)
14440 (call-interactively 'org-check-deadlines))
14441 ((equal ans ?t)
14442 (org-show-todo-tree '(4)))
14443 ((equal ans ?T)
14444 (call-interactively 'org-tags-sparse-tree))
14445 ((member ans '(?p ?P))
14446 (setq kwd (completing-read "Property: "
14447 (mapcar 'list (org-buffer-property-keys))))
14448 (setq value (completing-read "Value: "
14449 (mapcar 'list (org-property-values kwd))))
14450 (unless (string-match "\\`{.*}\\'" value)
14451 (setq value (concat "\"" value "\"")))
14452 (org-tags-sparse-tree arg (concat kwd "=" value)))
14453 ((member ans '(?r ?R ?/))
14454 (call-interactively 'org-occur))
14455 (t (error "No such sparse tree command \"%c\"" ans)))))
14457 (defvar org-occur-highlights nil)
14458 (make-variable-buffer-local 'org-occur-highlights)
14460 (defun org-occur (regexp &optional keep-previous callback)
14461 "Make a compact tree which shows all matches of REGEXP.
14462 The tree will show the lines where the regexp matches, and all higher
14463 headlines above the match. It will also show the heading after the match,
14464 to make sure editing the matching entry is easy.
14465 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
14466 call to `org-occur' will be kept, to allow stacking of calls to this
14467 command.
14468 If CALLBACK is non-nil, it is a function which is called to confirm
14469 that the match should indeed be shown."
14470 (interactive "sRegexp: \nP")
14471 (or keep-previous (org-remove-occur-highlights nil nil t))
14472 (let ((cnt 0))
14473 (save-excursion
14474 (goto-char (point-min))
14475 (if (or (not keep-previous) ; do not want to keep
14476 (not org-occur-highlights)) ; no previous matches
14477 ;; hide everything
14478 (org-overview))
14479 (while (re-search-forward regexp nil t)
14480 (when (or (not callback)
14481 (save-match-data (funcall callback)))
14482 (setq cnt (1+ cnt))
14483 (when org-highlight-sparse-tree-matches
14484 (org-highlight-new-match (match-beginning 0) (match-end 0)))
14485 (org-show-context 'occur-tree))))
14486 (when org-remove-highlights-with-change
14487 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
14488 nil 'local))
14489 (unless org-sparse-tree-open-archived-trees
14490 (org-hide-archived-subtrees (point-min) (point-max)))
14491 (run-hooks 'org-occur-hook)
14492 (if (interactive-p)
14493 (message "%d match(es) for regexp %s" cnt regexp))
14494 cnt))
14496 (defun org-show-context (&optional key)
14497 "Make sure point and context and visible.
14498 How much context is shown depends upon the variables
14499 `org-show-hierarchy-above', `org-show-following-heading'. and
14500 `org-show-siblings'."
14501 (let ((heading-p (org-on-heading-p t))
14502 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
14503 (following-p (org-get-alist-option org-show-following-heading key))
14504 (entry-p (org-get-alist-option org-show-entry-below key))
14505 (siblings-p (org-get-alist-option org-show-siblings key)))
14506 (catch 'exit
14507 ;; Show heading or entry text
14508 (if (and heading-p (not entry-p))
14509 (org-flag-heading nil) ; only show the heading
14510 (and (or entry-p (org-invisible-p) (org-invisible-p2))
14511 (org-show-hidden-entry))) ; show entire entry
14512 (when following-p
14513 ;; Show next sibling, or heading below text
14514 (save-excursion
14515 (and (if heading-p (org-goto-sibling) (outline-next-heading))
14516 (org-flag-heading nil))))
14517 (when siblings-p (org-show-siblings))
14518 (when hierarchy-p
14519 ;; show all higher headings, possibly with siblings
14520 (save-excursion
14521 (while (and (condition-case nil
14522 (progn (org-up-heading-all 1) t)
14523 (error nil))
14524 (not (bobp)))
14525 (org-flag-heading nil)
14526 (when siblings-p (org-show-siblings))))))))
14528 (defun org-reveal (&optional siblings)
14529 "Show current entry, hierarchy above it, and the following headline.
14530 This can be used to show a consistent set of context around locations
14531 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
14532 not t for the search context.
14534 With optional argument SIBLINGS, on each level of the hierarchy all
14535 siblings are shown. This repairs the tree structure to what it would
14536 look like when opened with hierarchical calls to `org-cycle'."
14537 (interactive "P")
14538 (let ((org-show-hierarchy-above t)
14539 (org-show-following-heading t)
14540 (org-show-siblings (if siblings t org-show-siblings)))
14541 (org-show-context nil)))
14543 (defun org-highlight-new-match (beg end)
14544 "Highlight from BEG to END and mark the highlight is an occur headline."
14545 (let ((ov (org-make-overlay beg end)))
14546 (org-overlay-put ov 'face 'secondary-selection)
14547 (push ov org-occur-highlights)))
14549 (defun org-remove-occur-highlights (&optional beg end noremove)
14550 "Remove the occur highlights from the buffer.
14551 BEG and END are ignored. If NOREMOVE is nil, remove this function
14552 from the `before-change-functions' in the current buffer."
14553 (interactive)
14554 (unless org-inhibit-highlight-removal
14555 (mapc 'org-delete-overlay org-occur-highlights)
14556 (setq org-occur-highlights nil)
14557 (unless noremove
14558 (remove-hook 'before-change-functions
14559 'org-remove-occur-highlights 'local))))
14561 ;;;; Priorities
14563 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14564 "Regular expression matching the priority indicator.")
14566 (defvar org-remove-priority-next-time nil)
14568 (defun org-priority-up ()
14569 "Increase the priority of the current item."
14570 (interactive)
14571 (org-priority 'up))
14573 (defun org-priority-down ()
14574 "Decrease the priority of the current item."
14575 (interactive)
14576 (org-priority 'down))
14578 (defun org-priority (&optional action)
14579 "Change the priority of an item by ARG.
14580 ACTION can be `set', `up', `down', or a character."
14581 (interactive)
14582 (setq action (or action 'set))
14583 (let (current new news have remove)
14584 (save-excursion
14585 (org-back-to-heading)
14586 (if (looking-at org-priority-regexp)
14587 (setq current (string-to-char (match-string 2))
14588 have t)
14589 (setq current org-default-priority))
14590 (cond
14591 ((or (eq action 'set) (integerp action))
14592 (if (integerp action)
14593 (setq new action)
14594 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
14595 (setq new (read-char-exclusive)))
14596 (if (and (= (upcase org-highest-priority) org-highest-priority)
14597 (= (upcase org-lowest-priority) org-lowest-priority))
14598 (setq new (upcase new)))
14599 (cond ((equal new ?\ ) (setq remove t))
14600 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14601 (error "Priority must be between `%c' and `%c'"
14602 org-highest-priority org-lowest-priority))))
14603 ((eq action 'up)
14604 (if (and (not have) (eq last-command this-command))
14605 (setq new org-lowest-priority)
14606 (setq new (if (and org-priority-start-cycle-with-default (not have))
14607 org-default-priority (1- current)))))
14608 ((eq action 'down)
14609 (if (and (not have) (eq last-command this-command))
14610 (setq new org-highest-priority)
14611 (setq new (if (and org-priority-start-cycle-with-default (not have))
14612 org-default-priority (1+ current)))))
14613 (t (error "Invalid action")))
14614 (if (or (< (upcase new) org-highest-priority)
14615 (> (upcase new) org-lowest-priority))
14616 (setq remove t))
14617 (setq news (format "%c" new))
14618 (if have
14619 (if remove
14620 (replace-match "" t t nil 1)
14621 (replace-match news t t nil 2))
14622 (if remove
14623 (error "No priority cookie found in line")
14624 (looking-at org-todo-line-regexp)
14625 (if (match-end 2)
14626 (progn
14627 (goto-char (match-end 2))
14628 (insert " [#" news "]"))
14629 (goto-char (match-beginning 3))
14630 (insert "[#" news "] ")))))
14631 (org-preserve-lc (org-set-tags nil 'align))
14632 (if remove
14633 (message "Priority removed")
14634 (message "Priority of current item set to %s" news))))
14637 (defun org-get-priority (s)
14638 "Find priority cookie and return priority."
14639 (save-match-data
14640 (if (not (string-match org-priority-regexp s))
14641 (* 1000 (- org-lowest-priority org-default-priority))
14642 (* 1000 (- org-lowest-priority
14643 (string-to-char (match-string 2 s)))))))
14645 ;;;; Tags
14647 (defun org-scan-tags (action matcher &optional todo-only)
14648 "Scan headline tags with inheritance and produce output ACTION.
14649 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
14650 evaluated, testing if a given set of tags qualifies a headline for
14651 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
14652 are included in the output."
14653 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
14654 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14655 (org-re
14656 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
14657 (props (list 'face nil
14658 'done-face 'org-done
14659 'undone-face nil
14660 'mouse-face 'highlight
14661 'org-not-done-regexp org-not-done-regexp
14662 'org-todo-regexp org-todo-regexp
14663 'keymap org-agenda-keymap
14664 'help-echo
14665 (format "mouse-2 or RET jump to org file %s"
14666 (abbreviate-file-name
14667 (or (buffer-file-name (buffer-base-buffer))
14668 (buffer-name (buffer-base-buffer)))))))
14669 (case-fold-search nil)
14670 lspos
14671 tags tags-list tags-alist (llast 0) rtn level category i txt
14672 todo marker entry priority)
14673 (save-excursion
14674 (goto-char (point-min))
14675 (when (eq action 'sparse-tree)
14676 (org-overview)
14677 (org-remove-occur-highlights))
14678 (while (re-search-forward re nil t)
14679 (catch :skip
14680 (setq todo (if (match-end 1) (match-string 2))
14681 tags (if (match-end 4) (match-string 4)))
14682 (goto-char (setq lspos (1+ (match-beginning 0))))
14683 (setq level (org-reduced-level (funcall outline-level))
14684 category (org-get-category))
14685 (setq i llast llast level)
14686 ;; remove tag lists from same and sublevels
14687 (while (>= i level)
14688 (when (setq entry (assoc i tags-alist))
14689 (setq tags-alist (delete entry tags-alist)))
14690 (setq i (1- i)))
14691 ;; add the nex tags
14692 (when tags
14693 (setq tags (mapcar 'downcase (org-split-string tags ":"))
14694 tags-alist
14695 (cons (cons level tags) tags-alist)))
14696 ;; compile tags for current headline
14697 (setq tags-list
14698 (if org-use-tag-inheritance
14699 (apply 'append (mapcar 'cdr tags-alist))
14700 tags))
14701 (when (and (or (not todo-only) (member todo org-not-done-keywords))
14702 (eval matcher)
14703 (or (not org-agenda-skip-archived-trees)
14704 (not (member org-archive-tag tags-list))))
14705 (and (eq action 'agenda) (org-agenda-skip))
14706 ;; list this headline
14708 (if (eq action 'sparse-tree)
14709 (progn
14710 (and org-highlight-sparse-tree-matches
14711 (org-get-heading) (match-end 0)
14712 (org-highlight-new-match
14713 (match-beginning 0) (match-beginning 1)))
14714 (org-show-context 'tags-tree))
14715 (setq txt (org-format-agenda-item
14717 (concat
14718 (if org-tags-match-list-sublevels
14719 (make-string (1- level) ?.) "")
14720 (org-get-heading))
14721 category tags-list)
14722 priority (org-get-priority txt))
14723 (goto-char lspos)
14724 (setq marker (org-agenda-new-marker))
14725 (org-add-props txt props
14726 'org-marker marker 'org-hd-marker marker 'org-category category
14727 'priority priority 'type "tagsmatch")
14728 (push txt rtn))
14729 ;; if we are to skip sublevels, jump to end of subtree
14730 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
14731 (when (and (eq action 'sparse-tree)
14732 (not org-sparse-tree-open-archived-trees))
14733 (org-hide-archived-subtrees (point-min) (point-max)))
14734 (nreverse rtn)))
14736 (defvar todo-only) ;; dynamically scoped
14738 (defun org-tags-sparse-tree (&optional todo-only match)
14739 "Create a sparse tree according to tags string MATCH.
14740 MATCH can contain positive and negative selection of tags, like
14741 \"+WORK+URGENT-WITHBOSS\".
14742 If optional argument TODO_ONLY is non-nil, only select lines that are
14743 also TODO lines."
14744 (interactive "P")
14745 (org-prepare-agenda-buffers (list (current-buffer)))
14746 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14748 (defvar org-cached-props nil)
14749 (defun org-cached-entry-get (pom property)
14750 (if (or (eq t org-use-property-inheritance)
14751 (member property org-use-property-inheritance))
14752 ;; Caching is not possible, check it directly
14753 (org-entry-get pom property 'inherit)
14754 ;; Get all properties, so that we can do complicated checks easily
14755 (cdr (assoc property (or org-cached-props
14756 (setq org-cached-props
14757 (org-entry-properties pom)))))))
14759 (defun org-global-tags-completion-table (&optional files)
14760 "Return the list of all tags in all agenda buffer/files."
14761 (save-excursion
14762 (org-uniquify
14763 (apply 'append
14764 (mapcar
14765 (lambda (file)
14766 (set-buffer (find-file-noselect file))
14767 (org-get-buffer-tags))
14768 (if (and files (car files))
14769 files
14770 (org-agenda-files)))))))
14772 (defun org-make-tags-matcher (match)
14773 "Create the TAGS//TODO matcher form for the selection string MATCH."
14774 ;; todo-only is scoped dynamically into this function, and the function
14775 ;; may change it it the matcher asksk for it.
14776 (unless match
14777 ;; Get a new match request, with completion
14778 (let ((org-last-tags-completion-table
14779 (org-global-tags-completion-table)))
14780 (setq match (completing-read
14781 "Match: " 'org-tags-completion-function nil nil nil
14782 'org-tags-history))))
14784 ;; Parse the string and create a lisp form
14785 (let ((match0 match)
14786 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]+\"\\)\\|[[:alnum:]_@]+\\)"))
14787 minus tag mm
14788 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14789 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
14790 (if (string-match "/+" match)
14791 ;; match contains also a todo-matching request
14792 (progn
14793 (setq tagsmatch (substring match 0 (match-beginning 0))
14794 todomatch (substring match (match-end 0)))
14795 (if (string-match "^!" todomatch)
14796 (setq todo-only t todomatch (substring todomatch 1)))
14797 (if (string-match "^\\s-*$" todomatch)
14798 (setq todomatch nil)))
14799 ;; only matching tags
14800 (setq tagsmatch match todomatch nil))
14802 ;; Make the tags matcher
14803 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14804 (setq tagsmatcher t)
14805 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14806 (while (setq term (pop orterms))
14807 (while (and (equal (substring term -1) "\\") orterms)
14808 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14809 (while (string-match re term)
14810 (setq minus (and (match-end 1)
14811 (equal (match-string 1 term) "-"))
14812 tag (match-string 2 term)
14813 re-p (equal (string-to-char tag) ?{)
14814 level-p (match-end 3)
14815 prop-p (match-end 4)
14816 mm (cond
14817 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14818 (level-p `(= level ,(string-to-number
14819 (match-string 3 term))))
14820 (prop-p
14821 (setq pn (match-string 4 term)
14822 pv (match-string 5 term)
14823 cat-p (equal pn "CATEGORY")
14824 re-p (equal (string-to-char pv) ?{)
14825 pv (substring pv 1 -1))
14826 (if (equal pn "CATEGORY")
14827 (setq gv '(get-text-property (point) 'org-category))
14828 (setq gv `(org-cached-entry-get nil ,pn)))
14829 (if re-p
14830 `(string-match ,pv (or ,gv ""))
14831 `(equal ,pv ,gv)))
14832 (t `(member ,(downcase tag) tags-list)))
14833 mm (if minus (list 'not mm) mm)
14834 term (substring term (match-end 0)))
14835 (push mm tagsmatcher))
14836 (push (if (> (length tagsmatcher) 1)
14837 (cons 'and tagsmatcher)
14838 (car tagsmatcher))
14839 orlist)
14840 (setq tagsmatcher nil))
14841 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14842 (setq tagsmatcher
14843 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14845 ;; Make the todo matcher
14846 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14847 (setq todomatcher t)
14848 (setq orterms (org-split-string todomatch "|") orlist nil)
14849 (while (setq term (pop orterms))
14850 (while (string-match re term)
14851 (setq minus (and (match-end 1)
14852 (equal (match-string 1 term) "-"))
14853 kwd (match-string 2 term)
14854 re-p (equal (string-to-char kwd) ?{)
14855 term (substring term (match-end 0))
14856 mm (if re-p
14857 `(string-match ,(substring kwd 1 -1) todo)
14858 (list 'equal 'todo kwd))
14859 mm (if minus (list 'not mm) mm))
14860 (push mm todomatcher))
14861 (push (if (> (length todomatcher) 1)
14862 (cons 'and todomatcher)
14863 (car todomatcher))
14864 orlist)
14865 (setq todomatcher nil))
14866 (setq todomatcher (if (> (length orlist) 1)
14867 (cons 'or orlist) (car orlist))))
14869 ;; Return the string and lisp forms of the matcher
14870 (setq matcher (if todomatcher
14871 (list 'and tagsmatcher todomatcher)
14872 tagsmatcher))
14873 (cons match0 matcher)))
14875 (defun org-match-any-p (re list)
14876 "Does re match any element of list?"
14877 (setq list (mapcar (lambda (x) (string-match re x)) list))
14878 (delq nil list))
14880 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
14881 (defvar org-tags-overlay (org-make-overlay 1 1))
14882 (org-detach-overlay org-tags-overlay)
14884 (defun org-align-tags-here (to-col)
14885 ;; Assumes that this is a headline
14886 (let ((pos (point)) (col (current-column)) tags)
14887 (beginning-of-line 1)
14888 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14889 (< pos (match-beginning 2)))
14890 (progn
14891 (setq tags (match-string 2))
14892 (goto-char (match-beginning 1))
14893 (insert " ")
14894 (delete-region (point) (1+ (match-end 0)))
14895 (backward-char 1)
14896 (move-to-column
14897 (max (1+ (current-column))
14898 (1+ col)
14899 (if (> to-col 0)
14900 to-col
14901 (- (abs to-col) (length tags))))
14903 (insert tags)
14904 (move-to-column (min (current-column) col) t))
14905 (goto-char pos))))
14907 (defun org-set-tags (&optional arg just-align)
14908 "Set the tags for the current headline.
14909 With prefix ARG, realign all tags in headings in the current buffer."
14910 (interactive "P")
14911 (let* ((re (concat "^" outline-regexp))
14912 (current (org-get-tags-string))
14913 (col (current-column))
14914 (org-setting-tags t)
14915 table current-tags inherited-tags ; computed below when needed
14916 tags p0 c0 c1 rpl)
14917 (if arg
14918 (save-excursion
14919 (goto-char (point-min))
14920 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14921 (while (re-search-forward re nil t)
14922 (org-set-tags nil t)
14923 (end-of-line 1)))
14924 (message "All tags realigned to column %d" org-tags-column))
14925 (if just-align
14926 (setq tags current)
14927 ;; Get a new set of tags from the user
14928 (save-excursion
14929 (setq table (or org-tag-alist (org-get-buffer-tags))
14930 org-last-tags-completion-table table
14931 current-tags (org-split-string current ":")
14932 inherited-tags (nreverse
14933 (nthcdr (length current-tags)
14934 (nreverse (org-get-tags-at))))
14935 tags
14936 (if (or (eq t org-use-fast-tag-selection)
14937 (and org-use-fast-tag-selection
14938 (delq nil (mapcar 'cdr table))))
14939 (org-fast-tag-selection
14940 current-tags inherited-tags table
14941 (if org-fast-tag-selection-include-todo org-todo-key-alist))
14942 (let ((org-add-colon-after-tag-completion t))
14943 (org-trim
14944 (org-without-partial-completion
14945 (completing-read "Tags: " 'org-tags-completion-function
14946 nil nil current 'org-tags-history)))))))
14947 (while (string-match "[-+&]+" tags)
14948 ;; No boolean logic, just a list
14949 (setq tags (replace-match ":" t t tags))))
14951 (if (string-match "\\`[\t ]*\\'" tags)
14952 (setq tags "")
14953 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14954 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14956 ;; Insert new tags at the correct column
14957 (beginning-of-line 1)
14958 (cond
14959 ((and (equal current "") (equal tags "")))
14960 ((re-search-forward
14961 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14962 (point-at-eol) t)
14963 (if (equal tags "")
14964 (setq rpl "")
14965 (goto-char (match-beginning 0))
14966 (setq c0 (current-column) p0 (point)
14967 c1 (max (1+ c0) (if (> org-tags-column 0)
14968 org-tags-column
14969 (- (- org-tags-column) (length tags))))
14970 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14971 (replace-match rpl t t)
14972 (and (not (featurep 'xemacs)) c0 (tabify p0 (point)))
14973 tags)
14974 (t (error "Tags alignment failed")))
14975 (move-to-column col)
14976 (unless just-align
14977 (run-hooks 'org-after-tags-change-hook)))))
14979 (defun org-change-tag-in-region (beg end tag off)
14980 "Add or remove TAG for each entry in the region.
14981 This works in the agenda, and also in an org-mode buffer."
14982 (interactive
14983 (list (region-beginning) (region-end)
14984 (let ((org-last-tags-completion-table
14985 (if (org-mode-p)
14986 (org-get-buffer-tags)
14987 (org-global-tags-completion-table))))
14988 (completing-read
14989 "Tag: " 'org-tags-completion-function nil nil nil
14990 'org-tags-history))
14991 (progn
14992 (message "[s]et or [r]emove? ")
14993 (equal (read-char-exclusive) ?r))))
14994 (if (fboundp 'deactivate-mark) (deactivate-mark))
14995 (let ((agendap (equal major-mode 'org-agenda-mode))
14996 l1 l2 m buf pos newhead (cnt 0))
14997 (goto-char end)
14998 (setq l2 (1- (org-current-line)))
14999 (goto-char beg)
15000 (setq l1 (org-current-line))
15001 (loop for l from l1 to l2 do
15002 (goto-line l)
15003 (setq m (get-text-property (point) 'org-hd-marker))
15004 (when (or (and (org-mode-p) (org-on-heading-p))
15005 (and agendap m))
15006 (setq buf (if agendap (marker-buffer m) (current-buffer))
15007 pos (if agendap m (point)))
15008 (with-current-buffer buf
15009 (save-excursion
15010 (save-restriction
15011 (goto-char pos)
15012 (setq cnt (1+ cnt))
15013 (org-toggle-tag tag (if off 'off 'on))
15014 (setq newhead (org-get-heading)))))
15015 (and agendap (org-agenda-change-all-lines newhead m))))
15016 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15018 (defun org-tags-completion-function (string predicate &optional flag)
15019 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15020 (confirm (lambda (x) (stringp (car x)))))
15021 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15022 (setq s1 (match-string 1 string)
15023 s2 (match-string 2 string))
15024 (setq s1 "" s2 string))
15025 (cond
15026 ((eq flag nil)
15027 ;; try completion
15028 (setq rtn (try-completion s2 ctable confirm))
15029 (if (stringp rtn)
15030 (setq rtn
15031 (concat s1 s2 (substring rtn (length s2))
15032 (if (and org-add-colon-after-tag-completion
15033 (assoc rtn ctable))
15034 ":" ""))))
15035 rtn)
15036 ((eq flag t)
15037 ;; all-completions
15038 (all-completions s2 ctable confirm)
15040 ((eq flag 'lambda)
15041 ;; exact match?
15042 (assoc s2 ctable)))
15045 (defun org-fast-tag-insert (kwd tags face &optional end)
15046 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15047 (insert (format "%-12s" (concat kwd ":"))
15048 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15049 (or end "")))
15051 (defun org-fast-tag-show-exit (flag)
15052 (save-excursion
15053 (goto-line 3)
15054 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15055 (replace-match ""))
15056 (when flag
15057 (end-of-line 1)
15058 (move-to-column (- (window-width) 19) t)
15059 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15061 (defun org-set-current-tags-overlay (current prefix)
15062 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15063 (if (featurep 'xemacs)
15064 (org-overlay-display org-tags-overlay (concat prefix s)
15065 'secondary-selection)
15066 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15067 (org-overlay-display org-tags-overlay (concat prefix s)))))
15069 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15070 "Fast tag selection with single keys.
15071 CURRENT is the current list of tags in the headline, INHERITED is the
15072 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15073 possibly with grouping information. TODO-TABLE is a similar table with
15074 TODO keywords, should these have keys assigned to them.
15075 If the keys are nil, a-z are automatically assigned.
15076 Returns the new tags string, or nil to not change the current settings."
15077 (let* ((fulltable (append table todo-table))
15078 (maxlen (apply 'max (mapcar
15079 (lambda (x)
15080 (if (stringp (car x)) (string-width (car x)) 0))
15081 fulltable)))
15082 (buf (current-buffer))
15083 (expert (eq org-fast-tag-selection-single-key 'expert))
15084 (buffer-tags nil)
15085 (fwidth (+ maxlen 3 1 3))
15086 (ncol (/ (- (window-width) 4) fwidth))
15087 (i-face 'org-done)
15088 (c-face 'org-todo)
15089 tg cnt e c char c1 c2 ntable tbl rtn
15090 ov-start ov-end ov-prefix
15091 (exit-after-next org-fast-tag-selection-single-key)
15092 (done-keywords org-done-keywords)
15093 groups ingroup)
15094 (save-excursion
15095 (beginning-of-line 1)
15096 (if (looking-at
15097 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15098 (setq ov-start (match-beginning 1)
15099 ov-end (match-end 1)
15100 ov-prefix "")
15101 (setq ov-start (1- (point-at-eol))
15102 ov-end (1+ ov-start))
15103 (skip-chars-forward "^\n\r")
15104 (setq ov-prefix
15105 (concat
15106 (buffer-substring (1- (point)) (point))
15107 (if (> (current-column) org-tags-column)
15109 (make-string (- org-tags-column (current-column)) ?\ ))))))
15110 (org-move-overlay org-tags-overlay ov-start ov-end)
15111 (save-window-excursion
15112 (if expert
15113 (set-buffer (get-buffer-create " *Org tags*"))
15114 (delete-other-windows)
15115 (split-window-vertically)
15116 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
15117 (erase-buffer)
15118 (org-set-local 'org-done-keywords done-keywords)
15119 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15120 (org-fast-tag-insert "Current" current c-face "\n\n")
15121 (org-fast-tag-show-exit exit-after-next)
15122 (org-set-current-tags-overlay current ov-prefix)
15123 (setq tbl fulltable char ?a cnt 0)
15124 (while (setq e (pop tbl))
15125 (cond
15126 ((equal e '(:startgroup))
15127 (push '() groups) (setq ingroup t)
15128 (when (not (= cnt 0))
15129 (setq cnt 0)
15130 (insert "\n"))
15131 (insert "{ "))
15132 ((equal e '(:endgroup))
15133 (setq ingroup nil cnt 0)
15134 (insert "}\n"))
15136 (setq tg (car e) c2 nil)
15137 (if (cdr e)
15138 (setq c (cdr e))
15139 ;; automatically assign a character.
15140 (setq c1 (string-to-char
15141 (downcase (substring
15142 tg (if (= (string-to-char tg) ?@) 1 0)))))
15143 (if (or (rassoc c1 ntable) (rassoc c1 table))
15144 (while (or (rassoc char ntable) (rassoc char table))
15145 (setq char (1+ char)))
15146 (setq c2 c1))
15147 (setq c (or c2 char)))
15148 (if ingroup (push tg (car groups)))
15149 (setq tg (org-add-props tg nil 'face
15150 (cond
15151 ((not (assoc tg table))
15152 (org-get-todo-face tg))
15153 ((member tg current) c-face)
15154 ((member tg inherited) i-face)
15155 (t nil))))
15156 (if (and (= cnt 0) (not ingroup)) (insert " "))
15157 (insert "[" c "] " tg (make-string
15158 (- fwidth 4 (length tg)) ?\ ))
15159 (push (cons tg c) ntable)
15160 (when (= (setq cnt (1+ cnt)) ncol)
15161 (insert "\n")
15162 (if ingroup (insert " "))
15163 (setq cnt 0)))))
15164 (setq ntable (nreverse ntable))
15165 (insert "\n")
15166 (goto-char (point-min))
15167 (if (and (not expert) (fboundp 'fit-window-to-buffer))
15168 (fit-window-to-buffer))
15169 (setq rtn
15170 (catch 'exit
15171 (while t
15172 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
15173 (if groups " [!] no groups" " [!]groups")
15174 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15175 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15176 (cond
15177 ((= c ?\r) (throw 'exit t))
15178 ((= c ?!)
15179 (setq groups (not groups))
15180 (goto-char (point-min))
15181 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15182 ((= c ?\C-c)
15183 (if (not expert)
15184 (org-fast-tag-show-exit
15185 (setq exit-after-next (not exit-after-next)))
15186 (setq expert nil)
15187 (delete-other-windows)
15188 (split-window-vertically)
15189 (org-switch-to-buffer-other-window " *Org tags*")
15190 (and (fboundp 'fit-window-to-buffer)
15191 (fit-window-to-buffer))))
15192 ((or (= c ?\C-g)
15193 (and (= c ?q) (not (rassoc c ntable))))
15194 (org-detach-overlay org-tags-overlay)
15195 (setq quit-flag t))
15196 ((= c ?\ )
15197 (setq current nil)
15198 (if exit-after-next (setq exit-after-next 'now)))
15199 ((= c ?\t)
15200 (condition-case nil
15201 (setq tg (completing-read
15202 "Tag: "
15203 (or buffer-tags
15204 (with-current-buffer buf
15205 (org-get-buffer-tags)))))
15206 (quit (setq tg "")))
15207 (when (string-match "\\S-" tg)
15208 (add-to-list 'buffer-tags (list tg))
15209 (if (member tg current)
15210 (setq current (delete tg current))
15211 (push tg current)))
15212 (if exit-after-next (setq exit-after-next 'now)))
15213 ((setq e (rassoc c todo-table) tg (car e))
15214 (with-current-buffer buf
15215 (save-excursion (org-todo tg)))
15216 (if exit-after-next (setq exit-after-next 'now)))
15217 ((setq e (rassoc c ntable) tg (car e))
15218 (if (member tg current)
15219 (setq current (delete tg current))
15220 (loop for g in groups do
15221 (if (member tg g)
15222 (mapc (lambda (x)
15223 (setq current (delete x current)))
15224 g)))
15225 (push tg current))
15226 (if exit-after-next (setq exit-after-next 'now))))
15228 ;; Create a sorted list
15229 (setq current
15230 (sort current
15231 (lambda (a b)
15232 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15233 (if (eq exit-after-next 'now) (throw 'exit t))
15234 (goto-char (point-min))
15235 (beginning-of-line 2)
15236 (delete-region (point) (point-at-eol))
15237 (org-fast-tag-insert "Current" current c-face)
15238 (org-set-current-tags-overlay current ov-prefix)
15239 (while (re-search-forward
15240 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
15241 (setq tg (match-string 1))
15242 (add-text-properties
15243 (match-beginning 1) (match-end 1)
15244 (list 'face
15245 (cond
15246 ((member tg current) c-face)
15247 ((member tg inherited) i-face)
15248 (t (get-text-property (match-beginning 1) 'face))))))
15249 (goto-char (point-min)))))
15250 (org-detach-overlay org-tags-overlay)
15251 (if rtn
15252 (mapconcat 'identity current ":")
15253 nil))))
15255 (defun org-get-tags-string ()
15256 "Get the TAGS string in the current headline."
15257 (unless (org-on-heading-p t)
15258 (error "Not on a heading"))
15259 (save-excursion
15260 (beginning-of-line 1)
15261 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15262 (org-match-string-no-properties 1)
15263 "")))
15265 (defun org-get-tags ()
15266 "Get the list of tags specified in the current headline."
15267 (org-split-string (org-get-tags-string) ":"))
15269 (defun org-get-buffer-tags ()
15270 "Get a table of all tags used in the buffer, for completion."
15271 (let (tags)
15272 (save-excursion
15273 (goto-char (point-min))
15274 (while (re-search-forward
15275 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
15276 (when (equal (char-after (point-at-bol 0)) ?*)
15277 (mapc (lambda (x) (add-to-list 'tags x))
15278 (org-split-string (org-match-string-no-properties 1) ":")))))
15279 (mapcar 'list tags)))
15282 ;;;; Properties
15284 ;;; Setting and retrieving properties
15286 (defconst org-special-properties
15287 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
15288 "TIMESTAMP" "TIMESTAMP_IA")
15289 "The special properties valid in Org-mode.
15291 These are properties that are not defined in the property drawer,
15292 but in some other way.")
15294 (defconst org-default-properties
15295 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
15296 "LOCATION" "LOGGING" "COLUMNS")
15297 "Some properties that are used by Org-mode for various purposes.
15298 Being in this list makes sure that they are offered for completion.")
15300 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15301 "Regular expression matching the first line of a property drawer.")
15303 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15304 "Regular expression matching the first line of a property drawer.")
15306 (defun org-property-action ()
15307 "Do an action on properties."
15308 (interactive)
15309 (let (c)
15310 (org-at-property-p)
15311 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15312 (setq c (read-char-exclusive))
15313 (cond
15314 ((equal c ?s)
15315 (call-interactively 'org-set-property))
15316 ((equal c ?d)
15317 (call-interactively 'org-delete-property))
15318 ((equal c ?D)
15319 (call-interactively 'org-delete-property-globally))
15320 ((equal c ?c)
15321 (call-interactively 'org-compute-property-at-point))
15322 (t (error "No such property action %c" c)))))
15324 (defun org-at-property-p ()
15325 "Is the cursor in a property line?"
15326 ;; FIXME: Does not check if we are actually in the drawer.
15327 ;; FIXME: also returns true on any drawers.....
15328 ;; This is used by C-c C-c for property action.
15329 (save-excursion
15330 (beginning-of-line 1)
15331 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
15333 (defmacro org-with-point-at (pom &rest body)
15334 "Move to buffer and point of point-or-marker POM for the duration of BODY."
15335 (declare (indent 1) (debug t))
15336 `(save-excursion
15337 (if (markerp pom) (set-buffer (marker-buffer pom)))
15338 (save-excursion
15339 (goto-char (or pom (point)))
15340 ,@body)))
15342 (defun org-get-property-block (&optional beg end force)
15343 "Return the (beg . end) range of the body of the property drawer.
15344 BEG and END can be beginning and end of subtree, if not given
15345 they will be found.
15346 If the drawer does not exist and FORCE is non-nil, create the drawer."
15347 (catch 'exit
15348 (save-excursion
15349 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
15350 (end (or end (progn (outline-next-heading) (point)))))
15351 (goto-char beg)
15352 (if (re-search-forward org-property-start-re end t)
15353 (setq beg (1+ (match-end 0)))
15354 (if force
15355 (save-excursion
15356 (org-insert-property-drawer)
15357 (setq end (progn (outline-next-heading) (point))))
15358 (throw 'exit nil))
15359 (goto-char beg)
15360 (if (re-search-forward org-property-start-re end t)
15361 (setq beg (1+ (match-end 0)))))
15362 (if (re-search-forward org-property-end-re end t)
15363 (setq end (match-beginning 0))
15364 (or force (throw 'exit nil))
15365 (goto-char beg)
15366 (setq end beg)
15367 (org-indent-line-function)
15368 (insert ":END:\n"))
15369 (cons beg end)))))
15371 (defun org-entry-properties (&optional pom which)
15372 "Get all properties of the entry at point-or-marker POM.
15373 This includes the TODO keyword, the tags, time strings for deadline,
15374 scheduled, and clocking, and any additional properties defined in the
15375 entry. The return value is an alist, keys may occur multiple times
15376 if the property key was used several times.
15377 POM may also be nil, in which case the current entry is used.
15378 If WHICH is nil or `all', get all properties. If WHICH is
15379 `special' or `standard', only get that subclass."
15380 (setq which (or which 'all))
15381 (org-with-point-at pom
15382 (let ((clockstr (substring org-clock-string 0 -1))
15383 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
15384 beg end range props sum-props key value string)
15385 (save-excursion
15386 (when (condition-case nil (org-back-to-heading t) (error nil))
15387 (setq beg (point))
15388 (setq sum-props (get-text-property (point) 'org-summaries))
15389 (outline-next-heading)
15390 (setq end (point))
15391 (when (memq which '(all special))
15392 ;; Get the special properties, like TODO and tags
15393 (goto-char beg)
15394 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15395 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15396 (when (looking-at org-priority-regexp)
15397 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15398 (when (and (setq value (org-get-tags-string))
15399 (string-match "\\S-" value))
15400 (push (cons "TAGS" value) props))
15401 (when (setq value (org-get-tags-at))
15402 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
15403 props))
15404 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15405 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
15406 string (if (equal key clockstr)
15407 (org-no-properties
15408 (org-trim
15409 (buffer-substring
15410 (match-beginning 3) (goto-char (point-at-eol)))))
15411 (substring (org-match-string-no-properties 3) 1 -1)))
15412 (unless key
15413 (if (= (char-after (match-beginning 3)) ?\[)
15414 (setq key "TIMESTAMP_IA")
15415 (setq key "TIMESTAMP")))
15416 (when (or (equal key clockstr) (not (assoc key props)))
15417 (push (cons key string) props)))
15421 (when (memq which '(all standard))
15422 ;; Get the standard properties, like :PORP: ...
15423 (setq range (org-get-property-block beg end))
15424 (when range
15425 (goto-char (car range))
15426 (while (re-search-forward
15427 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15428 (cdr range) t)
15429 (setq key (org-match-string-no-properties 1)
15430 value (org-trim (or (org-match-string-no-properties 2) "")))
15431 (unless (member key excluded)
15432 (push (cons key (or value "")) props)))))
15433 (append sum-props (nreverse props)))))))
15435 (defun org-entry-get (pom property &optional inherit)
15436 "Get value of PROPERTY for entry at point-or-marker POM.
15437 If INHERIT is non-nil and the entry does not have the property,
15438 then also check higher levels of the hierarchy.
15439 If the property is present but empty, the return value is the empty string.
15440 If the property is not present at all, nil is returned."
15441 (org-with-point-at pom
15442 (if inherit
15443 (org-entry-get-with-inheritance property)
15444 (if (member property org-special-properties)
15445 ;; We need a special property. Use brute force, get all properties.
15446 (cdr (assoc property (org-entry-properties nil 'special)))
15447 (let ((range (org-get-property-block)))
15448 (if (and range
15449 (goto-char (car range))
15450 (re-search-forward
15451 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
15452 (cdr range) t))
15453 ;; Found the property, return it.
15454 (if (match-end 1)
15455 (org-match-string-no-properties 1)
15456 "")))))))
15458 (defun org-entry-delete (pom property)
15459 "Delete the property PROPERTY from entry at point-or-marker POM."
15460 (org-with-point-at pom
15461 (if (member property org-special-properties)
15462 nil ; cannot delete these properties.
15463 (let ((range (org-get-property-block)))
15464 (if (and range
15465 (goto-char (car range))
15466 (re-search-forward
15467 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
15468 (cdr range) t))
15469 (progn
15470 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15472 nil)))))
15474 ;; Multi-values properties are properties that contain multiple values
15475 ;; These values are assumed to be single words, separated by whitespace.
15476 (defun org-entry-add-to-multivalued-property (pom property value)
15477 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15478 (let* ((old (org-entry-get pom property))
15479 (values (and old (org-split-string old "[ \t]"))))
15480 (unless (member value values)
15481 (setq values (cons value values))
15482 (org-entry-put pom property
15483 (mapconcat 'identity values " ")))))
15485 (defun org-entry-remove-from-multivalued-property (pom property value)
15486 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15487 (let* ((old (org-entry-get pom property))
15488 (values (and old (org-split-string old "[ \t]"))))
15489 (when (member value values)
15490 (setq values (delete value values))
15491 (org-entry-put pom property
15492 (mapconcat 'identity values " ")))))
15494 (defun org-entry-member-in-multivalued-property (pom property value)
15495 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15496 (let* ((old (org-entry-get pom property))
15497 (values (and old (org-split-string old "[ \t]"))))
15498 (member value values)))
15500 (defvar org-entry-property-inherited-from (make-marker))
15502 (defun org-entry-get-with-inheritance (property)
15503 "Get entry property, and search higher levels if not present."
15504 (let (tmp)
15505 (save-excursion
15506 (save-restriction
15507 (widen)
15508 (catch 'ex
15509 (while t
15510 (when (setq tmp (org-entry-get nil property))
15511 (org-back-to-heading t)
15512 (move-marker org-entry-property-inherited-from (point))
15513 (throw 'ex tmp))
15514 (or (org-up-heading-safe) (throw 'ex nil)))))
15515 (or tmp (cdr (assoc property org-local-properties))
15516 (cdr (assoc property org-global-properties))))))
15518 (defun org-entry-put (pom property value)
15519 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15520 (org-with-point-at pom
15521 (org-back-to-heading t)
15522 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15523 range)
15524 (cond
15525 ((equal property "TODO")
15526 (when (and (stringp value) (string-match "\\S-" value)
15527 (not (member value org-todo-keywords-1)))
15528 (error "\"%s\" is not a valid TODO state" value))
15529 (if (or (not value)
15530 (not (string-match "\\S-" value)))
15531 (setq value 'none))
15532 (org-todo value)
15533 (org-set-tags nil 'align))
15534 ((equal property "PRIORITY")
15535 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15536 (string-to-char value) ?\ ))
15537 (org-set-tags nil 'align))
15538 ((equal property "SCHEDULED")
15539 (if (re-search-forward org-scheduled-time-regexp end t)
15540 (cond
15541 ((eq value 'earlier) (org-timestamp-change -1 'day))
15542 ((eq value 'later) (org-timestamp-change 1 'day))
15543 (t (call-interactively 'org-schedule)))
15544 (call-interactively 'org-schedule)))
15545 ((equal property "DEADLINE")
15546 (if (re-search-forward org-deadline-time-regexp end t)
15547 (cond
15548 ((eq value 'earlier) (org-timestamp-change -1 'day))
15549 ((eq value 'later) (org-timestamp-change 1 'day))
15550 (t (call-interactively 'org-deadline)))
15551 (call-interactively 'org-deadline)))
15552 ((member property org-special-properties)
15553 (error "The %s property can not yet be set with `org-entry-put'"
15554 property))
15555 (t ; a non-special property
15556 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15557 (setq range (org-get-property-block beg end 'force))
15558 (goto-char (car range))
15559 (if (re-search-forward
15560 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
15561 (progn
15562 (delete-region (match-beginning 1) (match-end 1))
15563 (goto-char (match-beginning 1)))
15564 (goto-char (cdr range))
15565 (insert "\n")
15566 (backward-char 1)
15567 (org-indent-line-function)
15568 (insert ":" property ":"))
15569 (and value (insert " " value))
15570 (org-indent-line-function)))))))
15572 (defun org-buffer-property-keys (&optional include-specials include-defaults)
15573 "Get all property keys in the current buffer.
15574 With INCLUDE-SPECIALS, also list the special properties that relect things
15575 like tags and TODO state.
15576 With INCLUDE-DEFAULTS, also include properties that has special meaning
15577 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING."
15578 (let (rtn range)
15579 (save-excursion
15580 (save-restriction
15581 (widen)
15582 (goto-char (point-min))
15583 (while (re-search-forward org-property-start-re nil t)
15584 (setq range (org-get-property-block))
15585 (goto-char (car range))
15586 (while (re-search-forward
15587 (org-re "^[ \t]*:\\([[:alnum:]_-]+\\):")
15588 (cdr range) t)
15589 (add-to-list 'rtn (org-match-string-no-properties 1)))
15590 (outline-next-heading))))
15592 (when include-specials
15593 (setq rtn (append org-special-properties rtn)))
15595 (when include-defaults
15596 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
15598 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15600 (defun org-property-values (key)
15601 "Return a list of all values of property KEY."
15602 (save-excursion
15603 (save-restriction
15604 (widen)
15605 (goto-char (point-min))
15606 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
15607 values)
15608 (while (re-search-forward re nil t)
15609 (add-to-list 'values (org-trim (match-string 1))))
15610 (delete "" values)))))
15612 (defun org-insert-property-drawer ()
15613 "Insert a property drawer into the current entry."
15614 (interactive)
15615 (org-back-to-heading t)
15616 (looking-at outline-regexp)
15617 (let ((indent (- (match-end 0)(match-beginning 0)))
15618 (beg (point))
15619 (re (concat "^[ \t]*" org-keyword-time-regexp))
15620 end hiddenp)
15621 (outline-next-heading)
15622 (setq end (point))
15623 (goto-char beg)
15624 (while (re-search-forward re end t))
15625 (setq hiddenp (org-invisible-p))
15626 (end-of-line 1)
15627 (and (equal (char-after) ?\n) (forward-char 1))
15628 (org-skip-over-state-notes)
15629 (skip-chars-backward " \t\n\r")
15630 (if (eq (char-before) ?*) (forward-char 1))
15631 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15632 (beginning-of-line 0)
15633 (indent-to-column indent)
15634 (beginning-of-line 2)
15635 (indent-to-column indent)
15636 (beginning-of-line 0)
15637 (if hiddenp
15638 (save-excursion
15639 (org-back-to-heading t)
15640 (hide-entry))
15641 (org-flag-drawer t))))
15643 (defun org-set-property (property value)
15644 "In the current entry, set PROPERTY to VALUE.
15645 When called interactively, this will prompt for a property name, offering
15646 completion on existing and default properties. And then it will prompt
15647 for a value, offering competion either on allowed values (via an inherited
15648 xxx_ALL property) or on existing values in other instances of this property
15649 in the current file."
15650 (interactive
15651 (let* ((prop (completing-read
15652 "Property: " (mapcar 'list (org-buffer-property-keys nil t))))
15653 (cur (org-entry-get nil prop))
15654 (allowed (org-property-get-allowed-values nil prop 'table))
15655 (existing (mapcar 'list (org-property-values prop)))
15656 (val (if allowed
15657 (completing-read "Value: " allowed nil 'req-match)
15658 (completing-read
15659 (concat "Value" (if (and cur (string-match "\\S-" cur))
15660 (concat "[" cur "]") "")
15661 ": ")
15662 existing nil nil "" nil cur))))
15663 (list prop (if (equal val "") cur val))))
15664 (unless (equal (org-entry-get nil property) value)
15665 (org-entry-put nil property value)))
15667 (defun org-delete-property (property)
15668 "In the current entry, delete PROPERTY."
15669 (interactive
15670 (let* ((prop (completing-read
15671 "Property: " (org-entry-properties nil 'standard))))
15672 (list prop)))
15673 (message (concat "Property " property
15674 (if (org-entry-delete nil property)
15675 " deleted"
15676 " was not present in the entry"))))
15678 (defun org-delete-property-globally (property)
15679 "Remove PROPERTY globally, from all entries."
15680 (interactive
15681 (let* ((prop (completing-read
15682 "Globally remove property: "
15683 (mapcar 'list (org-buffer-property-keys)))))
15684 (list prop)))
15685 (save-excursion
15686 (save-restriction
15687 (widen)
15688 (goto-char (point-min))
15689 (let ((cnt 0))
15690 (while (re-search-forward
15691 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
15692 nil t)
15693 (setq cnt (1+ cnt))
15694 (replace-match ""))
15695 (message "Property \"%s\" removed from %d entries" property cnt)))))
15697 (defvar org-columns-current-fmt-compiled) ; defined below
15699 (defun org-compute-property-at-point ()
15700 "Compute the property at point.
15701 This looks for an enclosing column format, extracts the operator and
15702 then applies it to the proerty in the column format's scope."
15703 (interactive)
15704 (unless (org-at-property-p)
15705 (error "Not at a property"))
15706 (let ((prop (org-match-string-no-properties 2)))
15707 (org-columns-get-format-and-top-level)
15708 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15709 (error "No operator defined for property %s" prop))
15710 (org-columns-compute prop)))
15712 (defun org-property-get-allowed-values (pom property &optional table)
15713 "Get allowed values for the property PROPERTY.
15714 When TABLE is non-nil, return an alist that can directly be used for
15715 completion."
15716 (let (vals)
15717 (cond
15718 ((equal property "TODO")
15719 (setq vals (org-with-point-at pom
15720 (append org-todo-keywords-1 '("")))))
15721 ((equal property "PRIORITY")
15722 (let ((n org-lowest-priority))
15723 (while (>= n org-highest-priority)
15724 (push (char-to-string n) vals)
15725 (setq n (1- n)))))
15726 ((member property org-special-properties))
15728 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15730 (when (and vals (string-match "\\S-" vals))
15731 (setq vals (car (read-from-string (concat "(" vals ")"))))
15732 (setq vals (mapcar (lambda (x)
15733 (cond ((stringp x) x)
15734 ((numberp x) (number-to-string x))
15735 ((symbolp x) (symbol-name x))
15736 (t "???")))
15737 vals)))))
15738 (if table (mapcar 'list vals) vals)))
15740 (defun org-property-previous-allowed-value (&optional previous)
15741 "Switch to the next allowed value for this property."
15742 (interactive)
15743 (org-property-next-allowed-value t))
15745 (defun org-property-next-allowed-value (&optional previous)
15746 "Switch to the next allowed value for this property."
15747 (interactive)
15748 (unless (org-at-property-p)
15749 (error "Not at a property"))
15750 (let* ((key (match-string 2))
15751 (value (match-string 3))
15752 (allowed (or (org-property-get-allowed-values (point) key)
15753 (and (member value '("[ ]" "[-]" "[X]"))
15754 '("[ ]" "[X]"))))
15755 nval)
15756 (unless allowed
15757 (error "Allowed values for this property have not been defined"))
15758 (if previous (setq allowed (reverse allowed)))
15759 (if (member value allowed)
15760 (setq nval (car (cdr (member value allowed)))))
15761 (setq nval (or nval (car allowed)))
15762 (if (equal nval value)
15763 (error "Only one allowed value for this property"))
15764 (org-at-property-p)
15765 (replace-match (concat " :" key ": " nval) t t)
15766 (org-indent-line-function)
15767 (beginning-of-line 1)
15768 (skip-chars-forward " \t")))
15770 (defun org-find-entry-with-id (ident)
15771 "Locate the entry that contains the ID property with exact value IDENT.
15772 IDENT can be a string, a symbol or a number, this function will search for
15773 the string representation of it.
15774 Return the position where this entry starts, or nil if there is no such entry."
15775 (let ((id (cond
15776 ((stringp ident) ident)
15777 ((symbol-name ident) (symbol-name ident))
15778 ((numberp ident) (number-to-string ident))
15779 (t (error "IDENT %s must be a string, symbol or number" ident))))
15780 (case-fold-search nil))
15781 (save-excursion
15782 (save-restriction
15783 (goto-char (point-min))
15784 (when (re-search-forward
15785 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15786 nil t)
15787 (org-back-to-heading)
15788 (point))))))
15790 ;;; Column View
15792 (defvar org-columns-overlays nil
15793 "Holds the list of current column overlays.")
15795 (defvar org-columns-current-fmt nil
15796 "Local variable, holds the currently active column format.")
15797 (defvar org-columns-current-fmt-compiled nil
15798 "Local variable, holds the currently active column format.
15799 This is the compiled version of the format.")
15800 (defvar org-columns-current-widths nil
15801 "Loval variable, holds the currently widths of fields.")
15802 (defvar org-columns-current-maxwidths nil
15803 "Loval variable, holds the currently active maximum column widths.")
15804 (defvar org-columns-begin-marker (make-marker)
15805 "Points to the position where last a column creation command was called.")
15806 (defvar org-columns-top-level-marker (make-marker)
15807 "Points to the position where current columns region starts.")
15809 (defvar org-columns-map (make-sparse-keymap)
15810 "The keymap valid in column display.")
15812 (defun org-columns-content ()
15813 "Switch to contents view while in columns view."
15814 (interactive)
15815 (org-overview)
15816 (org-content))
15818 (org-defkey org-columns-map "c" 'org-columns-content)
15819 (org-defkey org-columns-map "o" 'org-overview)
15820 (org-defkey org-columns-map "e" 'org-columns-edit-value)
15821 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
15822 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
15823 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
15824 (org-defkey org-columns-map "v" 'org-columns-show-value)
15825 (org-defkey org-columns-map "q" 'org-columns-quit)
15826 (org-defkey org-columns-map "r" 'org-columns-redo)
15827 (org-defkey org-columns-map [left] 'backward-char)
15828 (org-defkey org-columns-map "\M-b" 'backward-char)
15829 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
15830 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
15831 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
15832 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
15833 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
15834 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
15835 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
15836 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
15837 (org-defkey org-columns-map "<" 'org-columns-narrow)
15838 (org-defkey org-columns-map ">" 'org-columns-widen)
15839 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
15840 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
15841 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
15842 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
15844 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
15845 '("Column"
15846 ["Edit property" org-columns-edit-value t]
15847 ["Next allowed value" org-columns-next-allowed-value t]
15848 ["Previous allowed value" org-columns-previous-allowed-value t]
15849 ["Show full value" org-columns-show-value t]
15850 ["Edit allowed values" org-columns-edit-allowed t]
15851 "--"
15852 ["Edit column attributes" org-columns-edit-attributes t]
15853 ["Increase column width" org-columns-widen t]
15854 ["Decrease column width" org-columns-narrow t]
15855 "--"
15856 ["Move column right" org-columns-move-right t]
15857 ["Move column left" org-columns-move-left t]
15858 ["Add column" org-columns-new t]
15859 ["Delete column" org-columns-delete t]
15860 "--"
15861 ["CONTENTS" org-columns-content t]
15862 ["OVERVIEW" org-overview t]
15863 ["Refresh columns display" org-columns-redo t]
15864 "--"
15865 ["Open link" org-columns-open-link t]
15866 "--"
15867 ["Quit" org-columns-quit t]))
15869 (defun org-columns-new-overlay (beg end &optional string face)
15870 "Create a new column overlay and add it to the list."
15871 (let ((ov (org-make-overlay beg end)))
15872 (org-overlay-put ov 'face (or face 'secondary-selection))
15873 (org-overlay-display ov string face)
15874 (push ov org-columns-overlays)
15875 ov))
15877 (defun org-columns-display-here (&optional props)
15878 "Overlay the current line with column display."
15879 (interactive)
15880 (let* ((fmt org-columns-current-fmt-compiled)
15881 (beg (point-at-bol))
15882 (level-face (save-excursion
15883 (beginning-of-line 1)
15884 (and (looking-at "\\(\\**\\)\\(\\* \\)")
15885 (org-get-level-face 2))))
15886 (color (list :foreground
15887 (face-attribute (or level-face 'default) :foreground)))
15888 props pom property ass width f string ov column val modval)
15889 ;; Check if the entry is in another buffer.
15890 (unless props
15891 (if (eq major-mode 'org-agenda-mode)
15892 (setq pom (or (get-text-property (point) 'org-hd-marker)
15893 (get-text-property (point) 'org-marker))
15894 props (if pom (org-entry-properties pom) nil))
15895 (setq props (org-entry-properties nil))))
15896 ;; Walk the format
15897 (while (setq column (pop fmt))
15898 (setq property (car column)
15899 ass (if (equal property "ITEM")
15900 (cons "ITEM"
15901 (save-match-data
15902 (org-no-properties
15903 (org-remove-tabs
15904 (buffer-substring-no-properties
15905 (point-at-bol) (point-at-eol))))))
15906 (assoc property props))
15907 width (or (cdr (assoc property org-columns-current-maxwidths))
15908 (nth 2 column)
15909 (length property))
15910 f (format "%%-%d.%ds | " width width)
15911 val (or (cdr ass) "")
15912 modval (if (equal property "ITEM")
15913 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
15914 string (format f (or modval val)))
15915 ;; Create the overlay
15916 (org-unmodified
15917 (setq ov (org-columns-new-overlay
15918 beg (setq beg (1+ beg)) string
15919 (list color 'org-column)))
15920 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
15921 (org-overlay-put ov 'keymap org-columns-map)
15922 (org-overlay-put ov 'org-columns-key property)
15923 (org-overlay-put ov 'org-columns-value (cdr ass))
15924 (org-overlay-put ov 'org-columns-value-modified modval)
15925 (org-overlay-put ov 'org-columns-pom pom)
15926 (org-overlay-put ov 'org-columns-format f))
15927 (if (or (not (char-after beg))
15928 (equal (char-after beg) ?\n))
15929 (let ((inhibit-read-only t))
15930 (save-excursion
15931 (goto-char beg)
15932 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
15933 ;; Make the rest of the line disappear.
15934 (org-unmodified
15935 (setq ov (org-columns-new-overlay beg (point-at-eol)))
15936 (org-overlay-put ov 'invisible t)
15937 (org-overlay-put ov 'keymap org-columns-map)
15938 (org-overlay-put ov 'intangible t)
15939 (push ov org-columns-overlays)
15940 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
15941 (org-overlay-put ov 'keymap org-columns-map)
15942 (push ov org-columns-overlays)
15943 (let ((inhibit-read-only t))
15944 (put-text-property (max (point-min) (1- (point-at-bol)))
15945 (min (point-max) (1+ (point-at-eol)))
15946 'read-only "Type `e' to edit property")))))
15948 (defvar org-previous-header-line-format nil
15949 "The header line format before column view was turned on.")
15950 (defvar org-columns-inhibit-recalculation nil
15951 "Inhibit recomputing of columns on column view startup.")
15954 (defvar header-line-format)
15955 (defun org-columns-display-here-title ()
15956 "Overlay the newline before the current line with the table title."
15957 (interactive)
15958 (let ((fmt org-columns-current-fmt-compiled)
15959 string (title "")
15960 property width f column str widths)
15961 (while (setq column (pop fmt))
15962 (setq property (car column)
15963 str (or (nth 1 column) property)
15964 width (or (cdr (assoc property org-columns-current-maxwidths))
15965 (nth 2 column)
15966 (length str))
15967 widths (push width widths)
15968 f (format "%%-%d.%ds | " width width)
15969 string (format f str)
15970 title (concat title string)))
15971 (setq title (concat
15972 (org-add-props " " nil 'display '(space :align-to 0))
15973 (org-add-props title nil 'face '(:weight bold :underline t))))
15974 (org-set-local 'org-previous-header-line-format header-line-format)
15975 (org-set-local 'org-columns-current-widths (nreverse widths))
15976 (setq header-line-format title)))
15978 (defun org-columns-remove-overlays ()
15979 "Remove all currently active column overlays."
15980 (interactive)
15981 (when (marker-buffer org-columns-begin-marker)
15982 (with-current-buffer (marker-buffer org-columns-begin-marker)
15983 (when (local-variable-p 'org-previous-header-line-format)
15984 (setq header-line-format org-previous-header-line-format)
15985 (kill-local-variable 'org-previous-header-line-format))
15986 (move-marker org-columns-begin-marker nil)
15987 (move-marker org-columns-top-level-marker nil)
15988 (org-unmodified
15989 (mapc 'org-delete-overlay org-columns-overlays)
15990 (setq org-columns-overlays nil)
15991 (let ((inhibit-read-only t))
15992 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
15994 (defun org-columns-cleanup-item (item fmt)
15995 "Remove from ITEM what is a column in the format FMT."
15996 (if (not org-complex-heading-regexp)
15997 item
15998 (when (string-match org-complex-heading-regexp item)
15999 (concat
16000 (org-add-props (concat (match-string 1 item) " ") nil
16001 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16002 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16003 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16004 " " (match-string 4 item)
16005 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16007 (defun org-columns-show-value ()
16008 "Show the full value of the property."
16009 (interactive)
16010 (let ((value (get-char-property (point) 'org-columns-value)))
16011 (message "Value is: %s" (or value ""))))
16013 (defun org-columns-quit ()
16014 "Remove the column overlays and in this way exit column editing."
16015 (interactive)
16016 (org-unmodified
16017 (org-columns-remove-overlays)
16018 (let ((inhibit-read-only t))
16019 (remove-text-properties (point-min) (point-max) '(read-only t))))
16020 (when (eq major-mode 'org-agenda-mode)
16021 (message
16022 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16024 (defun org-columns-check-computed ()
16025 "Check if this column value is computed.
16026 If yes, throw an error indicating that changing it does not make sense."
16027 (let ((val (get-char-property (point) 'org-columns-value)))
16028 (when (and (stringp val)
16029 (get-char-property 0 'org-computed val))
16030 (error "This value is computed from the entry's children"))))
16032 (defun org-columns-todo (&optional arg)
16033 "Change the TODO state during column view."
16034 (interactive "P")
16035 (org-columns-edit-value "TODO"))
16037 (defun org-columns-set-tags-or-toggle (&optional arg)
16038 "Toggle checkbox at point, or set tags for current headline."
16039 (interactive "P")
16040 (if (string-match "\\`\\[[ xX-]\\]\\'"
16041 (get-char-property (point) 'org-columns-value))
16042 (org-columns-next-allowed-value)
16043 (org-columns-edit-value "TAGS")))
16045 (defun org-columns-edit-value (&optional key)
16046 "Edit the value of the property at point in column view.
16047 Where possible, use the standard interface for changing this line."
16048 (interactive)
16049 (org-columns-check-computed)
16050 (let* ((external-key key)
16051 (col (current-column))
16052 (key (or key (get-char-property (point) 'org-columns-key)))
16053 (value (get-char-property (point) 'org-columns-value))
16054 (bol (point-at-bol)) (eol (point-at-eol))
16055 (pom (or (get-text-property bol 'org-hd-marker)
16056 (point))) ; keep despite of compiler waring
16057 (line-overlays
16058 (delq nil (mapcar (lambda (x)
16059 (and (eq (overlay-buffer x) (current-buffer))
16060 (>= (overlay-start x) bol)
16061 (<= (overlay-start x) eol)
16063 org-columns-overlays)))
16064 nval eval allowed)
16065 (cond
16066 ((equal key "ITEM")
16067 (setq eval '(org-with-point-at pom
16068 (org-edit-headline))))
16069 ((equal key "TODO")
16070 (setq eval '(org-with-point-at pom
16071 (let ((current-prefix-arg
16072 (if external-key current-prefix-arg '(4))))
16073 (call-interactively 'org-todo)))))
16074 ((equal key "PRIORITY")
16075 (setq eval '(org-with-point-at pom
16076 (call-interactively 'org-priority))))
16077 ((equal key "TAGS")
16078 (setq eval '(org-with-point-at pom
16079 (let ((org-fast-tag-selection-single-key
16080 (if (eq org-fast-tag-selection-single-key 'expert)
16081 t org-fast-tag-selection-single-key)))
16082 (call-interactively 'org-set-tags)))))
16083 ((equal key "DEADLINE")
16084 (setq eval '(org-with-point-at pom
16085 (call-interactively 'org-deadline))))
16086 ((equal key "SCHEDULED")
16087 (setq eval '(org-with-point-at pom
16088 (call-interactively 'org-schedule))))
16090 (setq allowed (org-property-get-allowed-values pom key 'table))
16091 (if allowed
16092 (setq nval (completing-read "Value: " allowed nil t))
16093 (setq nval (read-string "Edit: " value)))
16094 (setq nval (org-trim nval))
16095 (when (not (equal nval value))
16096 (setq eval '(org-entry-put pom key nval)))))
16097 (when eval
16098 (let ((inhibit-read-only t))
16099 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
16100 (unwind-protect
16101 (progn
16102 (setq org-columns-overlays
16103 (org-delete-all line-overlays org-columns-overlays))
16104 (mapc 'org-delete-overlay line-overlays)
16105 (org-columns-eval eval))
16106 (org-columns-display-here))))
16107 (move-to-column col)
16108 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
16109 (org-columns-update key))))
16111 (defun org-edit-headline () ; FIXME: this is not columns specific
16112 "Edit the current headline, the part without TODO keyword, TAGS."
16113 (org-back-to-heading)
16114 (when (looking-at org-todo-line-regexp)
16115 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
16116 (txt (match-string 3))
16117 (post "")
16118 txt2)
16119 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
16120 (setq post (match-string 0 txt)
16121 txt (substring txt 0 (match-beginning 0))))
16122 (setq txt2 (read-string "Edit: " txt))
16123 (when (not (equal txt txt2))
16124 (beginning-of-line 1)
16125 (insert pre txt2 post)
16126 (delete-region (point) (point-at-eol))
16127 (org-set-tags nil t)))))
16129 (defun org-columns-edit-allowed ()
16130 "Edit the list of allowed values for the current property."
16131 (interactive)
16132 (let* ((key (get-char-property (point) 'org-columns-key))
16133 (key1 (concat key "_ALL"))
16134 (allowed (org-entry-get (point) key1 t))
16135 nval)
16136 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
16137 (setq nval (read-string "Allowed: " allowed))
16138 (org-entry-put
16139 (cond ((marker-position org-entry-property-inherited-from)
16140 org-entry-property-inherited-from)
16141 ((marker-position org-columns-top-level-marker)
16142 org-columns-top-level-marker))
16143 key1 nval)))
16145 (defmacro org-no-warnings (&rest body)
16146 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
16148 (defun org-columns-eval (form)
16149 (let (hidep)
16150 (save-excursion
16151 (beginning-of-line 1)
16152 ;; `next-line' is needed here, because it skips invisible line.
16153 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
16154 (setq hidep (org-on-heading-p 1)))
16155 (eval form)
16156 (and hidep (hide-entry))))
16158 (defun org-columns-previous-allowed-value ()
16159 "Switch to the previous allowed value for this column."
16160 (interactive)
16161 (org-columns-next-allowed-value t))
16163 (defun org-columns-next-allowed-value (&optional previous)
16164 "Switch to the next allowed value for this column."
16165 (interactive)
16166 (org-columns-check-computed)
16167 (let* ((col (current-column))
16168 (key (get-char-property (point) 'org-columns-key))
16169 (value (get-char-property (point) 'org-columns-value))
16170 (bol (point-at-bol)) (eol (point-at-eol))
16171 (pom (or (get-text-property bol 'org-hd-marker)
16172 (point))) ; keep despite of compiler waring
16173 (line-overlays
16174 (delq nil (mapcar (lambda (x)
16175 (and (eq (overlay-buffer x) (current-buffer))
16176 (>= (overlay-start x) bol)
16177 (<= (overlay-start x) eol)
16179 org-columns-overlays)))
16180 (allowed (or (org-property-get-allowed-values pom key)
16181 (and (equal
16182 (nth 4 (assoc key org-columns-current-fmt-compiled))
16183 'checkbox) '("[ ]" "[X]"))))
16184 nval)
16185 (when (equal key "ITEM")
16186 (error "Cannot edit item headline from here"))
16187 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
16188 (error "Allowed values for this property have not been defined"))
16189 (if (member key '("SCHEDULED" "DEADLINE"))
16190 (setq nval (if previous 'earlier 'later))
16191 (if previous (setq allowed (reverse allowed)))
16192 (if (member value allowed)
16193 (setq nval (car (cdr (member value allowed)))))
16194 (setq nval (or nval (car allowed)))
16195 (if (equal nval value)
16196 (error "Only one allowed value for this property")))
16197 (let ((inhibit-read-only t))
16198 (remove-text-properties (1- bol) eol '(read-only t))
16199 (unwind-protect
16200 (progn
16201 (setq org-columns-overlays
16202 (org-delete-all line-overlays org-columns-overlays))
16203 (mapc 'org-delete-overlay line-overlays)
16204 (org-columns-eval '(org-entry-put pom key nval)))
16205 (org-columns-display-here)))
16206 (move-to-column col)
16207 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
16208 (org-columns-update key))))
16210 (defun org-verify-version (task)
16211 (cond
16212 ((eq task 'columns)
16213 (if (or (featurep 'xemacs)
16214 (< emacs-major-version 22))
16215 (error "Emacs 22 is required for the columns feature")))))
16217 (defun org-columns-open-link (&optional arg)
16218 (interactive "P")
16219 (let ((key (get-char-property (point) 'org-columns-key))
16220 (value (get-char-property (point) 'org-columns-value)))
16221 (org-open-link-from-string arg)))
16223 (defun org-open-link-from-string (s &optional arg)
16224 "Open a link in the string S, as if it was in Org-mode."
16225 (interactive)
16226 (with-temp-buffer
16227 (let ((org-inhibit-startup t))
16228 (org-mode)
16229 (insert s)
16230 (goto-char (point-min))
16231 (org-open-at-point arg))))
16233 (defun org-columns-get-format-and-top-level ()
16234 (let (fmt)
16235 (when (condition-case nil (org-back-to-heading) (error nil))
16236 (move-marker org-entry-property-inherited-from nil)
16237 (setq fmt (org-entry-get nil "COLUMNS" t)))
16238 (setq fmt (or fmt org-columns-default-format))
16239 (org-set-local 'org-columns-current-fmt fmt)
16240 (org-columns-compile-format fmt)
16241 (if (marker-position org-entry-property-inherited-from)
16242 (move-marker org-columns-top-level-marker
16243 org-entry-property-inherited-from)
16244 (move-marker org-columns-top-level-marker (point)))
16245 fmt))
16247 (defun org-columns ()
16248 "Turn on column view on an org-mode file."
16249 (interactive)
16250 (org-verify-version 'columns)
16251 (org-columns-remove-overlays)
16252 (move-marker org-columns-begin-marker (point))
16253 (let (beg end fmt cache maxwidths)
16254 (setq fmt (org-columns-get-format-and-top-level))
16255 (save-excursion
16256 (goto-char org-columns-top-level-marker)
16257 (setq beg (point))
16258 (unless org-columns-inhibit-recalculation
16259 (org-columns-compute-all))
16260 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
16261 (point-max)))
16262 (goto-char beg)
16263 ;; Get and cache the properties
16264 (while (re-search-forward (concat "^" outline-regexp) end t)
16265 (push (cons (org-current-line) (org-entry-properties)) cache))
16266 (when cache
16267 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16268 (org-set-local 'org-columns-current-maxwidths maxwidths)
16269 (org-columns-display-here-title)
16270 (mapc (lambda (x)
16271 (goto-line (car x))
16272 (org-columns-display-here (cdr x)))
16273 cache)))))
16275 (defun org-columns-new (&optional prop title width op fmt)
16276 "Insert a new column, to the leeft o the current column."
16277 (interactive)
16278 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
16279 cell)
16280 (setq prop (completing-read
16281 "Property: " (mapcar 'list (org-buffer-property-keys t))
16282 nil nil prop))
16283 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
16284 (setq width (read-string "Column width: " (if width (number-to-string width))))
16285 (if (string-match "\\S-" width)
16286 (setq width (string-to-number width))
16287 (setq width nil))
16288 (setq fmt (completing-read "Summary [none]: "
16289 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox"))
16290 nil t))
16291 (if (string-match "\\S-" fmt)
16292 (setq fmt (intern fmt))
16293 (setq fmt nil))
16294 (if (eq fmt 'none) (setq fmt nil))
16295 (if editp
16296 (progn
16297 (setcar editp prop)
16298 (setcdr editp (list title width nil fmt)))
16299 (setq cell (nthcdr (1- (current-column))
16300 org-columns-current-fmt-compiled))
16301 (setcdr cell (cons (list prop title width nil fmt)
16302 (cdr cell))))
16303 (org-columns-store-format)
16304 (org-columns-redo)))
16306 (defun org-columns-delete ()
16307 "Delete the column at point from columns view."
16308 (interactive)
16309 (let* ((n (current-column))
16310 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
16311 (when (y-or-n-p
16312 (format "Are you sure you want to remove column \"%s\"? " title))
16313 (setq org-columns-current-fmt-compiled
16314 (delq (nth n org-columns-current-fmt-compiled)
16315 org-columns-current-fmt-compiled))
16316 (org-columns-store-format)
16317 (org-columns-redo)
16318 (if (>= (current-column) (length org-columns-current-fmt-compiled))
16319 (backward-char 1)))))
16321 (defun org-columns-edit-attributes ()
16322 "Edit the attributes of the current column."
16323 (interactive)
16324 (let* ((n (current-column))
16325 (info (nth n org-columns-current-fmt-compiled)))
16326 (apply 'org-columns-new info)))
16328 (defun org-columns-widen (arg)
16329 "Make the column wider by ARG characters."
16330 (interactive "p")
16331 (let* ((n (current-column))
16332 (entry (nth n org-columns-current-fmt-compiled))
16333 (width (or (nth 2 entry)
16334 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
16335 (setq width (max 1 (+ width arg)))
16336 (setcar (nthcdr 2 entry) width)
16337 (org-columns-store-format)
16338 (org-columns-redo)))
16340 (defun org-columns-narrow (arg)
16341 "Make the column nrrower by ARG characters."
16342 (interactive "p")
16343 (org-columns-widen (- arg)))
16345 (defun org-columns-move-right ()
16346 "Swap this column with the one to the right."
16347 (interactive)
16348 (let* ((n (current-column))
16349 (cell (nthcdr n org-columns-current-fmt-compiled))
16351 (when (>= n (1- (length org-columns-current-fmt-compiled)))
16352 (error "Cannot shift this column further to the right"))
16353 (setq e (car cell))
16354 (setcar cell (car (cdr cell)))
16355 (setcdr cell (cons e (cdr (cdr cell))))
16356 (org-columns-store-format)
16357 (org-columns-redo)
16358 (forward-char 1)))
16360 (defun org-columns-move-left ()
16361 "Swap this column with the one to the left."
16362 (interactive)
16363 (let* ((n (current-column)))
16364 (when (= n 0)
16365 (error "Cannot shift this column further to the left"))
16366 (backward-char 1)
16367 (org-columns-move-right)
16368 (backward-char 1)))
16370 (defun org-columns-store-format ()
16371 "Store the text version of the current columns format in appropriate place.
16372 This is either in the COLUMNS property of the node starting the current column
16373 display, or in the #+COLUMNS line of the current buffer."
16374 (let (fmt (cnt 0))
16375 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
16376 (org-set-local 'org-columns-current-fmt fmt)
16377 (if (marker-position org-columns-top-level-marker)
16378 (save-excursion
16379 (goto-char org-columns-top-level-marker)
16380 (if (and (org-at-heading-p)
16381 (org-entry-get nil "COLUMNS"))
16382 (org-entry-put nil "COLUMNS" fmt)
16383 (goto-char (point-min))
16384 ;; Overwrite all #+COLUMNS lines....
16385 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
16386 (setq cnt (1+ cnt))
16387 (replace-match (concat "#+COLUMNS: " fmt) t t))
16388 (unless (> cnt 0)
16389 (goto-char (point-min))
16390 (or (org-on-heading-p t) (outline-next-heading))
16391 (let ((inhibit-read-only t))
16392 (insert-before-markers "#+COLUMNS: " fmt "\n")))
16393 (org-set-local 'org-columns-default-format fmt))))))
16395 (defvar org-overriding-columns-format nil
16396 "When set, overrides any other definition.")
16397 (defvar org-agenda-view-columns-initially nil
16398 "When set, switch to columns view immediately after creating the agenda.")
16400 (defun org-agenda-columns ()
16401 "Turn on column view in the agenda."
16402 (interactive)
16403 (org-verify-version 'columns)
16404 (org-columns-remove-overlays)
16405 (move-marker org-columns-begin-marker (point))
16406 (let (fmt cache maxwidths m)
16407 (cond
16408 ((and (local-variable-p 'org-overriding-columns-format)
16409 org-overriding-columns-format)
16410 (setq fmt org-overriding-columns-format))
16411 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
16412 (setq fmt (org-entry-get m "COLUMNS" t)))
16413 ((and (boundp 'org-columns-current-fmt)
16414 (local-variable-p 'org-columns-current-fmt)
16415 org-columns-current-fmt)
16416 (setq fmt org-columns-current-fmt))
16417 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
16418 (setq m (get-text-property m 'org-hd-marker))
16419 (setq fmt (org-entry-get m "COLUMNS" t))))
16420 (setq fmt (or fmt org-columns-default-format))
16421 (org-set-local 'org-columns-current-fmt fmt)
16422 (org-columns-compile-format fmt)
16423 (save-excursion
16424 ;; Get and cache the properties
16425 (goto-char (point-min))
16426 (while (not (eobp))
16427 (when (setq m (or (get-text-property (point) 'org-hd-marker)
16428 (get-text-property (point) 'org-marker)))
16429 (push (cons (org-current-line) (org-entry-properties m)) cache))
16430 (beginning-of-line 2))
16431 (when cache
16432 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16433 (org-set-local 'org-columns-current-maxwidths maxwidths)
16434 (org-columns-display-here-title)
16435 (mapc (lambda (x)
16436 (goto-line (car x))
16437 (org-columns-display-here (cdr x)))
16438 cache)))))
16440 (defun org-columns-get-autowidth-alist (s cache)
16441 "Derive the maximum column widths from the format and the cache."
16442 (let ((start 0) rtn)
16443 (while (string-match (org-re "%\\([[:alpha:]]\\S-*\\)") s start)
16444 (push (cons (match-string 1 s) 1) rtn)
16445 (setq start (match-end 0)))
16446 (mapc (lambda (x)
16447 (setcdr x (apply 'max
16448 (mapcar
16449 (lambda (y)
16450 (length (or (cdr (assoc (car x) (cdr y))) " ")))
16451 cache))))
16452 rtn)
16453 rtn))
16455 (defun org-columns-compute-all ()
16456 "Compute all columns that have operators defined."
16457 (org-unmodified
16458 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
16459 (let ((columns org-columns-current-fmt-compiled) col)
16460 (while (setq col (pop columns))
16461 (when (nth 3 col)
16462 (save-excursion
16463 (org-columns-compute (car col)))))))
16465 (defun org-columns-update (property)
16466 "Recompute PROPERTY, and update the columns display for it."
16467 (org-columns-compute property)
16468 (let (fmt val pos)
16469 (save-excursion
16470 (mapc (lambda (ov)
16471 (when (equal (org-overlay-get ov 'org-columns-key) property)
16472 (setq pos (org-overlay-start ov))
16473 (goto-char pos)
16474 (when (setq val (cdr (assoc property
16475 (get-text-property
16476 (point-at-bol) 'org-summaries))))
16477 (setq fmt (org-overlay-get ov 'org-columns-format))
16478 (org-overlay-put ov 'org-columns-value val)
16479 (org-overlay-put ov 'display (format fmt val)))))
16480 org-columns-overlays))))
16482 (defun org-columns-compute (property)
16483 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
16484 (interactive)
16485 (let* ((re (concat "^" outline-regexp))
16486 (lmax 30) ; Does anyone use deeper levels???
16487 (lsum (make-vector lmax 0))
16488 (lflag (make-vector lmax nil))
16489 (level 0)
16490 (ass (assoc property org-columns-current-fmt-compiled))
16491 (format (nth 4 ass))
16492 (printf (nth 5 ass))
16493 (beg org-columns-top-level-marker)
16494 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
16495 (save-excursion
16496 ;; Find the region to compute
16497 (goto-char beg)
16498 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
16499 (goto-char end)
16500 ;; Walk the tree from the back and do the computations
16501 (while (re-search-backward re beg t)
16502 (setq sumpos (match-beginning 0)
16503 last-level level
16504 level (org-outline-level)
16505 val (org-entry-get nil property)
16506 valflag (and val (string-match "\\S-" val)))
16507 (cond
16508 ((< level last-level)
16509 ;; put the sum of lower levels here as a property
16510 (setq sum (aref lsum last-level) ; current sum
16511 flag (aref lflag last-level) ; any valid entries from children?
16512 str (org-column-number-to-string sum format printf)
16513 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
16514 useval (if flag str1 (if valflag val ""))
16515 sum-alist (get-text-property sumpos 'org-summaries))
16516 (if (assoc property sum-alist)
16517 (setcdr (assoc property sum-alist) useval)
16518 (push (cons property useval) sum-alist)
16519 (org-unmodified
16520 (add-text-properties sumpos (1+ sumpos)
16521 (list 'org-summaries sum-alist))))
16522 (when val
16523 (org-entry-put nil property (if flag str val)))
16524 ;; add current to current level accumulator
16525 (when (or flag valflag)
16526 (aset lsum level (+ (aref lsum level)
16527 (if flag sum (org-column-string-to-number
16528 (if flag str val) format))))
16529 (aset lflag level t))
16530 ;; clear accumulators for deeper levels
16531 (loop for l from (1+ level) to (1- lmax) do
16532 (aset lsum l 0)
16533 (aset lflag l nil)))
16534 ((>= level last-level)
16535 ;; add what we have here to the accumulator for this level
16536 (aset lsum level (+ (aref lsum level)
16537 (org-column-string-to-number (or val "0") format)))
16538 (and valflag (aset lflag level t)))
16539 (t (error "This should not happen")))))))
16541 (defun org-columns-redo ()
16542 "Construct the column display again."
16543 (interactive)
16544 (message "Recomputing columns...")
16545 (save-excursion
16546 (if (marker-position org-columns-begin-marker)
16547 (goto-char org-columns-begin-marker))
16548 (org-columns-remove-overlays)
16549 (if (org-mode-p)
16550 (call-interactively 'org-columns)
16551 (call-interactively 'org-agenda-columns)))
16552 (message "Recomputing columns...done"))
16554 (defun org-columns-not-in-agenda ()
16555 (if (eq major-mode 'org-agenda-mode)
16556 (error "This command is only allowed in Org-mode buffers")))
16559 (defun org-string-to-number (s)
16560 "Convert string to number, and interpret hh:mm:ss."
16561 (if (not (string-match ":" s))
16562 (string-to-number s)
16563 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
16564 (while l
16565 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
16566 sum)))
16568 (defun org-column-number-to-string (n fmt printf)
16569 "Convert a computed column number to a string value, according to FMT."
16570 (cond
16571 ((eq fmt 'add_times)
16572 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
16573 (format "%d:%02d" h m)))
16574 ((eq fmt 'checkbox)
16575 (cond ((= n (floor n)) "[X]")
16576 ((> n 1.) "[-]")
16577 (t "[ ]")))
16578 (printf (format printf n))
16579 ((eq fmt 'currency)
16580 (format "%.2f" n))
16581 (t (number-to-string n))))
16583 (defun org-column-string-to-number (s fmt)
16584 "Convert a column value to a number that can be used for column computing."
16585 (cond
16586 ((string-match ":" s)
16587 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
16588 (while l
16589 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
16590 sum))
16591 ((eq fmt 'checkbox)
16592 (if (equal s "[X]") 1. 0.000001))
16593 (t (string-to-number s))))
16595 (defun org-columns-uncompile-format (cfmt)
16596 "Turn the compiled columns format back into a string representation."
16597 (let ((rtn "") e s prop title op width fmt printf)
16598 (while (setq e (pop cfmt))
16599 (setq prop (car e)
16600 title (nth 1 e)
16601 width (nth 2 e)
16602 op (nth 3 e)
16603 fmt (nth 4 e)
16604 printf (nth 5 e))
16605 (cond
16606 ((eq fmt 'add_times) (setq op ":"))
16607 ((eq fmt 'checkbox) (setq op "X"))
16608 ((eq fmt 'add_numbers) (setq op "+"))
16609 ((eq fmt 'currency) (setq op "$")))
16610 (if (and op printf) (setq op (concat op ";" printf)))
16611 (if (equal title prop) (setq title nil))
16612 (setq s (concat "%" (if width (number-to-string width))
16613 prop
16614 (if title (concat "(" title ")"))
16615 (if op (concat "{" op "}"))))
16616 (setq rtn (concat rtn " " s)))
16617 (org-trim rtn)))
16619 (defun org-columns-compile-format (fmt)
16620 "Turn a column format string into an alist of specifications.
16621 The alist has one entry for each column in the format. The elements of
16622 that list are:
16623 property the property
16624 title the title field for the columns
16625 width the column width in characters, can be nil for automatic
16626 operator the operator if any
16627 format the output format for computed results, derived from operator
16628 printf a printf format for computed values"
16629 (let ((start 0) width prop title op f printf)
16630 (setq org-columns-current-fmt-compiled nil)
16631 (while (string-match
16632 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
16633 fmt start)
16634 (setq start (match-end 0)
16635 width (match-string 1 fmt)
16636 prop (match-string 2 fmt)
16637 title (or (match-string 3 fmt) prop)
16638 op (match-string 4 fmt)
16639 f nil
16640 printf nil)
16641 (if width (setq width (string-to-number width)))
16642 (when (and op (string-match ";" op))
16643 (setq printf (substring op (match-end 0))
16644 op (substring op 0 (match-beginning 0))))
16645 (cond
16646 ((equal op "+") (setq f 'add_numbers))
16647 ((equal op "$") (setq f 'currency))
16648 ((equal op ":") (setq f 'add_times))
16649 ((equal op "X") (setq f 'checkbox)))
16650 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
16651 (setq org-columns-current-fmt-compiled
16652 (nreverse org-columns-current-fmt-compiled))))
16655 ;;; Dynamic block for Column view
16657 (defun org-columns-capture-view ()
16658 "Get the column view of the current buffer and return it as a list.
16659 The list will contains the title row and all other rows. Each row is
16660 a list of fields."
16661 (save-excursion
16662 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
16663 (n (length title)) row tbl)
16664 (goto-char (point-min))
16665 (while (re-search-forward "^\\*+ " nil t)
16666 (when (get-char-property (match-beginning 0) 'org-columns-key)
16667 (setq row nil)
16668 (loop for i from 0 to (1- n) do
16669 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
16670 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
16672 row))
16673 (setq row (nreverse row))
16674 (push row tbl)))
16675 (append (list title 'hline) (nreverse tbl)))))
16677 (defun org-dblock-write:columnview (params)
16678 "Write the column view table.
16679 PARAMS is a property list of parameters:
16681 :width enforce same column widths with <N> specifiers.
16682 :id the :ID: property of the entry where the columns view
16683 should be built, as a string. When `local', call locally.
16684 When `global' call column view with the cursor at the beginning
16685 of the buffer (usually this means that the whole buffer switches
16686 to column view).
16687 :hlines When t, insert a hline before each item. When a number, insert
16688 a hline before each level <= that number.
16689 :vlines When t, make each column a colgroup to enforce vertical lines."
16690 (let ((pos (move-marker (make-marker) (point)))
16691 (hlines (plist-get params :hlines))
16692 (vlines (plist-get params :vlines))
16693 tbl id idpos nfields tmp)
16694 (save-excursion
16695 (save-restriction
16696 (when (setq id (plist-get params :id))
16697 (cond ((not id) nil)
16698 ((eq id 'global) (goto-char (point-min)))
16699 ((eq id 'local) nil)
16700 ((setq idpos (org-find-entry-with-id id))
16701 (goto-char idpos))
16702 (t (error "Cannot find entry with :ID: %s" id))))
16703 (org-columns)
16704 (setq tbl (org-columns-capture-view))
16705 (setq nfields (length (car tbl)))
16706 (org-columns-quit)))
16707 (goto-char pos)
16708 (move-marker pos nil)
16709 (when tbl
16710 (when (plist-get params :hlines)
16711 (setq tmp nil)
16712 (while tbl
16713 (if (eq (car tbl) 'hline)
16714 (push (pop tbl) tmp)
16715 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
16716 (if (and (not (eq (car tmp) 'hline))
16717 (or (eq hlines t)
16718 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
16719 (push 'hline tmp)))
16720 (push (pop tbl) tmp)))
16721 (setq tbl (nreverse tmp)))
16722 (when vlines
16723 (setq tbl (mapcar (lambda (x)
16724 (if (eq 'hline x) x (cons "" x)))
16725 tbl))
16726 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
16727 (setq pos (point))
16728 (insert (org-listtable-to-string tbl))
16729 (when (plist-get params :width)
16730 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
16731 org-columns-current-widths "|")))
16732 (goto-char pos)
16733 (org-table-align))))
16735 (defun org-listtable-to-string (tbl)
16736 "Convert a listtable TBL to a string that contains the Org-mode table.
16737 The table still need to be alligned. The resulting string has no leading
16738 and tailing newline characters."
16739 (mapconcat
16740 (lambda (x)
16741 (cond
16742 ((listp x)
16743 (concat "|" (mapconcat 'identity x "|") "|"))
16744 ((eq x 'hline) "|-|")
16745 (t (error "Garbage in listtable: %s" x))))
16746 tbl "\n"))
16748 (defun org-insert-columns-dblock ()
16749 "Create a dynamic block capturing a column view table."
16750 (interactive)
16751 (let ((defaults '(:name "columnview" :hlines 1))
16752 (id (completing-read
16753 "Capture columns (local, global, entry with :ID: property) [local]: "
16754 (append '(("global") ("local"))
16755 (mapcar 'list (org-property-values "ID"))))))
16756 (if (equal id "") (setq id 'local))
16757 (if (equal id "global") (setq id 'global))
16758 (setq defaults (append defaults (list :id id)))
16759 (org-create-dblock defaults)
16760 (org-update-dblock)))
16762 ;;;; Timestamps
16764 (defvar org-last-changed-timestamp nil)
16765 (defvar org-time-was-given) ; dynamically scoped parameter
16766 (defvar org-end-time-was-given) ; dynamically scoped parameter
16767 (defvar org-ts-what) ; dynamically scoped parameter
16769 (defun org-time-stamp (arg)
16770 "Prompt for a date/time and insert a time stamp.
16771 If the user specifies a time like HH:MM, or if this command is called
16772 with a prefix argument, the time stamp will contain date and time.
16773 Otherwise, only the date will be included. All parts of a date not
16774 specified by the user will be filled in from the current date/time.
16775 So if you press just return without typing anything, the time stamp
16776 will represent the current date/time. If there is already a timestamp
16777 at the cursor, it will be modified."
16778 (interactive "P")
16779 (let* ((ts nil)
16780 (default-time
16781 ;; Default time is either today, or, when entering a range,
16782 ;; the range start.
16783 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16784 (save-excursion
16785 (re-search-backward
16786 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16787 (- (point) 20) t)))
16788 (apply 'encode-time (org-parse-time-string (match-string 1)))
16789 (current-time)))
16790 (default-input (and ts (org-get-compact-tod ts)))
16791 org-time-was-given org-end-time-was-given time)
16792 (cond
16793 ((and (org-at-timestamp-p)
16794 (eq last-command 'org-time-stamp)
16795 (eq this-command 'org-time-stamp))
16796 (insert "--")
16797 (setq time (let ((this-command this-command))
16798 (org-read-date arg 'totime nil nil default-time default-input)))
16799 (org-insert-time-stamp time (or org-time-was-given arg)))
16800 ((org-at-timestamp-p)
16801 (setq time (let ((this-command this-command))
16802 (org-read-date arg 'totime nil nil default-time default-input)))
16803 (when (org-at-timestamp-p) ; just to get the match data
16804 (replace-match "")
16805 (setq org-last-changed-timestamp
16806 (org-insert-time-stamp
16807 time (or org-time-was-given arg)
16808 nil nil nil (list org-end-time-was-given))))
16809 (message "Timestamp updated"))
16811 (setq time (let ((this-command this-command))
16812 (org-read-date arg 'totime nil nil default-time default-input)))
16813 (org-insert-time-stamp time (or org-time-was-given arg)
16814 nil nil nil (list org-end-time-was-given))))))
16816 ;; FIXME: can we use this for something else????
16817 ;; like computing time differences?????
16818 (defun org-get-compact-tod (s)
16819 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16820 (let* ((t1 (match-string 1 s))
16821 (h1 (string-to-number (match-string 2 s)))
16822 (m1 (string-to-number (match-string 3 s)))
16823 (t2 (and (match-end 4) (match-string 5 s)))
16824 (h2 (and t2 (string-to-number (match-string 6 s))))
16825 (m2 (and t2 (string-to-number (match-string 7 s))))
16826 dh dm)
16827 (if (not t2)
16829 (setq dh (- h2 h1) dm (- m2 m1))
16830 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16831 (concat t1 "+" (number-to-string dh)
16832 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
16834 (defun org-time-stamp-inactive (&optional arg)
16835 "Insert an inactive time stamp.
16836 An inactive time stamp is enclosed in square brackets instead of angle
16837 brackets. It is inactive in the sense that it does not trigger agenda entries,
16838 does not link to the calendar and cannot be changed with the S-cursor keys.
16839 So these are more for recording a certain time/date."
16840 (interactive "P")
16841 (let (org-time-was-given org-end-time-was-given time)
16842 (setq time (org-read-date arg 'totime))
16843 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
16844 nil nil (list org-end-time-was-given))))
16846 (defvar org-date-ovl (org-make-overlay 1 1))
16847 (org-overlay-put org-date-ovl 'face 'org-warning)
16848 (org-detach-overlay org-date-ovl)
16850 (defvar org-ans1) ; dynamically scoped parameter
16851 (defvar org-ans2) ; dynamically scoped parameter
16853 (defvar org-plain-time-of-day-regexp) ; defined below
16855 (defvar org-read-date-overlay nil)
16856 (defvar org-dcst nil) ; dynamically scoped
16858 (defun org-read-date (&optional with-time to-time from-string prompt
16859 default-time default-input)
16860 "Read a date, possibly a time, and make things smooth for the user.
16861 The prompt will suggest to enter an ISO date, but you can also enter anything
16862 which will at least partially be understood by `parse-time-string'.
16863 Unrecognized parts of the date will default to the current day, month, year,
16864 hour and minute. If this command is called to replace a timestamp at point,
16865 of to enter the second timestamp of a range, the default time is taken from the
16866 existing stamp. For example,
16867 3-2-5 --> 2003-02-05
16868 feb 15 --> currentyear-02-15
16869 sep 12 9 --> 2009-09-12
16870 12:45 --> today 12:45
16871 22 sept 0:34 --> currentyear-09-22 0:34
16872 12 --> currentyear-currentmonth-12
16873 Fri --> nearest Friday (today or later)
16874 etc.
16876 Furthermore you can specify a relative date by giving, as the *first* thing
16877 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
16878 change in days weeks, months, years.
16879 With a single plus or minus, the date is relative to today. With a double
16880 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16881 +4d --> four days from today
16882 +4 --> same as above
16883 +2w --> two weeks from today
16884 ++5 --> five days from default date
16886 The function understands only English month and weekday abbreviations,
16887 but this can be configured with the variables `parse-time-months' and
16888 `parse-time-weekdays'.
16890 While prompting, a calendar is popped up - you can also select the
16891 date with the mouse (button 1). The calendar shows a period of three
16892 months. To scroll it to other months, use the keys `>' and `<'.
16893 If you don't like the calendar, turn it off with
16894 \(setq org-read-date-popup-calendar nil)
16896 With optional argument TO-TIME, the date will immediately be converted
16897 to an internal time.
16898 With an optional argument WITH-TIME, the prompt will suggest to also
16899 insert a time. Note that when WITH-TIME is not set, you can still
16900 enter a time, and this function will inform the calling routine about
16901 this change. The calling routine may then choose to change the format
16902 used to insert the time stamp into the buffer to include the time.
16903 With optional argument FROM-STRING, read from this string instead from
16904 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16905 the time/date that is used for everything that is not specified by the
16906 user."
16907 (require 'parse-time)
16908 (let* ((org-time-stamp-rounding-minutes
16909 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
16910 (org-dcst org-display-custom-times)
16911 (ct (org-current-time))
16912 (def (or default-time ct))
16913 (defdecode (decode-time def))
16914 (dummy (progn
16915 (when (< (nth 2 defdecode) org-extend-today-until)
16916 (setcar (nthcdr 2 defdecode) -1)
16917 (setcar (nthcdr 1 defdecode) 59)
16918 (setq def (apply 'encode-time defdecode)
16919 defdecode (decode-time def)))))
16920 (calendar-move-hook nil)
16921 (view-diary-entries-initially nil)
16922 (view-calendar-holidays-initially nil)
16923 (timestr (format-time-string
16924 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
16925 (prompt (concat (if prompt (concat prompt " ") "")
16926 (format "Date+time [%s]: " timestr)))
16927 ans (org-ans0 "") org-ans1 org-ans2 final)
16929 (cond
16930 (from-string (setq ans from-string))
16931 (org-read-date-popup-calendar
16932 (save-excursion
16933 (save-window-excursion
16934 (calendar)
16935 (calendar-forward-day (- (time-to-days def)
16936 (calendar-absolute-from-gregorian
16937 (calendar-current-date))))
16938 (org-eval-in-calendar nil t)
16939 (let* ((old-map (current-local-map))
16940 (map (copy-keymap calendar-mode-map))
16941 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
16942 (org-defkey map (kbd "RET") 'org-calendar-select)
16943 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
16944 'org-calendar-select-mouse)
16945 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
16946 'org-calendar-select-mouse)
16947 (org-defkey minibuffer-local-map [(meta shift left)]
16948 (lambda () (interactive)
16949 (org-eval-in-calendar '(calendar-backward-month 1))))
16950 (org-defkey minibuffer-local-map [(meta shift right)]
16951 (lambda () (interactive)
16952 (org-eval-in-calendar '(calendar-forward-month 1))))
16953 (org-defkey minibuffer-local-map [(meta shift up)]
16954 (lambda () (interactive)
16955 (org-eval-in-calendar '(calendar-backward-year 1))))
16956 (org-defkey minibuffer-local-map [(meta shift down)]
16957 (lambda () (interactive)
16958 (org-eval-in-calendar '(calendar-forward-year 1))))
16959 (org-defkey minibuffer-local-map [(shift up)]
16960 (lambda () (interactive)
16961 (org-eval-in-calendar '(calendar-backward-week 1))))
16962 (org-defkey minibuffer-local-map [(shift down)]
16963 (lambda () (interactive)
16964 (org-eval-in-calendar '(calendar-forward-week 1))))
16965 (org-defkey minibuffer-local-map [(shift left)]
16966 (lambda () (interactive)
16967 (org-eval-in-calendar '(calendar-backward-day 1))))
16968 (org-defkey minibuffer-local-map [(shift right)]
16969 (lambda () (interactive)
16970 (org-eval-in-calendar '(calendar-forward-day 1))))
16971 (org-defkey minibuffer-local-map ">"
16972 (lambda () (interactive)
16973 (org-eval-in-calendar '(scroll-calendar-left 1))))
16974 (org-defkey minibuffer-local-map "<"
16975 (lambda () (interactive)
16976 (org-eval-in-calendar '(scroll-calendar-right 1))))
16977 (unwind-protect
16978 (progn
16979 (use-local-map map)
16980 (add-hook 'post-command-hook 'org-read-date-display)
16981 (setq org-ans0 (read-string prompt default-input nil nil))
16982 ;; org-ans0: from prompt
16983 ;; org-ans1: from mouse click
16984 ;; org-ans2: from calendar motion
16985 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16986 (remove-hook 'post-command-hook 'org-read-date-display)
16987 (use-local-map old-map)
16988 (when org-read-date-overlay
16989 (org-delete-overlay org-read-date-overlay)
16990 (setq org-read-date-overlay nil)))))))
16992 (t ; Naked prompt only
16993 (unwind-protect
16994 (setq ans (read-string prompt default-input nil timestr))
16995 (when org-read-date-overlay
16996 (org-delete-overlay org-read-date-overlay)
16997 (setq org-read-date-overlay nil)))))
16999 (setq final (org-read-date-analyze ans def defdecode))
17001 (if to-time
17002 (apply 'encode-time final)
17003 (if (and (boundp 'org-time-was-given) org-time-was-given)
17004 (format "%04d-%02d-%02d %02d:%02d"
17005 (nth 5 final) (nth 4 final) (nth 3 final)
17006 (nth 2 final) (nth 1 final))
17007 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17008 (defvar def)
17009 (defvar defdecode)
17010 (defvar with-time)
17011 (defun org-read-date-display ()
17012 "Display the currrent date prompt interpretation in the minibuffer."
17013 (when org-read-date-display-live
17014 (when org-read-date-overlay
17015 (org-delete-overlay org-read-date-overlay))
17016 (let ((p (point)))
17017 (end-of-line 1)
17018 (while (not (equal (buffer-substring
17019 (max (point-min) (- (point) 4)) (point))
17020 " "))
17021 (insert " "))
17022 (goto-char p))
17023 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17024 " " (or org-ans1 org-ans2)))
17025 (org-end-time-was-given nil)
17026 (f (org-read-date-analyze ans def defdecode))
17027 (fmts (if org-dcst
17028 org-time-stamp-custom-formats
17029 org-time-stamp-formats))
17030 (fmt (if (or with-time
17031 (and (boundp 'org-time-was-given) org-time-was-given))
17032 (cdr fmts)
17033 (car fmts)))
17034 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
17035 (when (and org-end-time-was-given
17036 (string-match org-plain-time-of-day-regexp txt))
17037 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17038 org-end-time-was-given
17039 (substring txt (match-end 0)))))
17040 (setq org-read-date-overlay
17041 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17042 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
17044 (defun org-read-date-analyze (ans def defdecode)
17045 "Analyze the combined answer of the date prompt."
17046 ;; FIXME: cleanup and comment
17047 (let (delta deltan deltaw deltadef year month day
17048 hour minute second wday pm h2 m2 tl wday1)
17050 (when (setq delta (org-read-date-get-relative ans (current-time) def))
17051 (setq ans (replace-match "" t t ans)
17052 deltan (car delta)
17053 deltaw (nth 1 delta)
17054 deltadef (nth 2 delta)))
17056 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
17057 (when (string-match
17058 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17059 (setq year (if (match-end 2)
17060 (string-to-number (match-string 2 ans))
17061 (string-to-number (format-time-string "%Y")))
17062 month (string-to-number (match-string 3 ans))
17063 day (string-to-number (match-string 4 ans)))
17064 (if (< year 100) (setq year (+ 2000 year)))
17065 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17066 t nil ans)))
17067 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17068 ;; If there is a time with am/pm, and *no* time without it, we convert
17069 ;; so that matching will be successful.
17070 (loop for i from 1 to 2 do ; twice, for end time as well
17071 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17072 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17073 (setq hour (string-to-number (match-string 1 ans))
17074 minute (if (match-end 3)
17075 (string-to-number (match-string 3 ans))
17077 pm (equal ?p
17078 (string-to-char (downcase (match-string 4 ans)))))
17079 (if (and (= hour 12) (not pm))
17080 (setq hour 0)
17081 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17082 (setq ans (replace-match (format "%02d:%02d" hour minute)
17083 t t ans))))
17085 ;; Check if a time range is given as a duration
17086 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17087 (setq hour (string-to-number (match-string 1 ans))
17088 h2 (+ hour (string-to-number (match-string 3 ans)))
17089 minute (string-to-number (match-string 2 ans))
17090 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
17091 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17092 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
17094 ;; Check if there is a time range
17095 (when (boundp 'org-end-time-was-given)
17096 (setq org-time-was-given nil)
17097 (when (and (string-match org-plain-time-of-day-regexp ans)
17098 (match-end 8))
17099 (setq org-end-time-was-given (match-string 8 ans))
17100 (setq ans (concat (substring ans 0 (match-beginning 7))
17101 (substring ans (match-end 7))))))
17103 (setq tl (parse-time-string ans)
17104 day (or (nth 3 tl) (nth 3 defdecode))
17105 month (or (nth 4 tl)
17106 (if (and org-read-date-prefer-future
17107 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
17108 (1+ (nth 4 defdecode))
17109 (nth 4 defdecode)))
17110 year (or (nth 5 tl)
17111 (if (and org-read-date-prefer-future
17112 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
17113 (1+ (nth 5 defdecode))
17114 (nth 5 defdecode)))
17115 hour (or (nth 2 tl) (nth 2 defdecode))
17116 minute (or (nth 1 tl) (nth 1 defdecode))
17117 second (or (nth 0 tl) 0)
17118 wday (nth 6 tl))
17119 (when deltan
17120 (unless deltadef
17121 (let ((now (decode-time (current-time))))
17122 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17123 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17124 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17125 ((equal deltaw "m") (setq month (+ month deltan)))
17126 ((equal deltaw "y") (setq year (+ year deltan)))))
17127 (when (and wday (not (nth 3 tl)))
17128 ;; Weekday was given, but no day, so pick that day in the week
17129 ;; on or after the derived date.
17130 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17131 (unless (equal wday wday1)
17132 (setq day (+ day (% (- wday wday1 -7) 7)))))
17133 (if (and (boundp 'org-time-was-given)
17134 (nth 2 tl))
17135 (setq org-time-was-given t))
17136 (if (< year 100) (setq year (+ 2000 year)))
17137 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
17138 (list second minute hour day month year)))
17140 (defvar parse-time-weekdays)
17142 (defun org-read-date-get-relative (s today default)
17143 "Check string S for special relative date string.
17144 TODAY and DEFAULT are internal times, for today and for a default.
17145 Return shift list (N what def-flag)
17146 WHAT is \"d\", \"w\", \"m\", or \"y\" for day. week, month, year.
17147 N is the number if WHATs to shift
17148 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17149 the DEFAULT date rather than TODAY."
17150 (when (string-match
17151 (concat
17152 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
17153 "\\([0-9]+\\)?"
17154 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17155 "\\([ \t]\\|$\\)") s)
17156 (let* ((dir (if (match-end 1)
17157 (string-to-char (substring (match-string 1 s) -1))
17158 ?+))
17159 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17160 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17161 (what (if (match-end 3) (match-string 3 s) "d"))
17162 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17163 (date (if rel default today))
17164 (wday (nth 6 (decode-time date)))
17165 delta)
17166 (if wday1
17167 (progn
17168 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17169 (if (= dir ?-) (setq delta (- delta 7)))
17170 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17171 (list delta "d" rel))
17172 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17174 (defun org-eval-in-calendar (form &optional keepdate)
17175 "Eval FORM in the calendar window and return to current window.
17176 Also, store the cursor date in variable org-ans2."
17177 (let ((sw (selected-window)))
17178 (select-window (get-buffer-window "*Calendar*"))
17179 (eval form)
17180 (when (and (not keepdate) (calendar-cursor-to-date))
17181 (let* ((date (calendar-cursor-to-date))
17182 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17183 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17184 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17185 (select-window sw)))
17187 ; ;; Update the prompt to show new default date
17188 ; (save-excursion
17189 ; (goto-char (point-min))
17190 ; (when (and org-ans2
17191 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
17192 ; (get-text-property (match-end 0) 'field))
17193 ; (let ((inhibit-read-only t))
17194 ; (replace-match (concat "[" org-ans2 "]") t t)
17195 ; (add-text-properties (point-min) (1+ (match-end 0))
17196 ; (text-properties-at (1+ (point-min)))))))))
17198 (defun org-calendar-select ()
17199 "Return to `org-read-date' with the date currently selected.
17200 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17201 (interactive)
17202 (when (calendar-cursor-to-date)
17203 (let* ((date (calendar-cursor-to-date))
17204 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17205 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17206 (if (active-minibuffer-window) (exit-minibuffer))))
17208 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17209 "Insert a date stamp for the date given by the internal TIME.
17210 WITH-HM means, use the stamp format that includes the time of the day.
17211 INACTIVE means use square brackets instead of angular ones, so that the
17212 stamp will not contribute to the agenda.
17213 PRE and POST are optional strings to be inserted before and after the
17214 stamp.
17215 The command returns the inserted time stamp."
17216 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17217 stamp)
17218 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17219 (insert-before-markers (or pre ""))
17220 (insert-before-markers (setq stamp (format-time-string fmt time)))
17221 (when (listp extra)
17222 (setq extra (car extra))
17223 (if (and (stringp extra)
17224 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17225 (setq extra (format "-%02d:%02d"
17226 (string-to-number (match-string 1 extra))
17227 (string-to-number (match-string 2 extra))))
17228 (setq extra nil)))
17229 (when extra
17230 (backward-char 1)
17231 (insert-before-markers extra)
17232 (forward-char 1))
17233 (insert-before-markers (or post ""))
17234 stamp))
17236 (defun org-toggle-time-stamp-overlays ()
17237 "Toggle the use of custom time stamp formats."
17238 (interactive)
17239 (setq org-display-custom-times (not org-display-custom-times))
17240 (unless org-display-custom-times
17241 (let ((p (point-min)) (bmp (buffer-modified-p)))
17242 (while (setq p (next-single-property-change p 'display))
17243 (if (and (get-text-property p 'display)
17244 (eq (get-text-property p 'face) 'org-date))
17245 (remove-text-properties
17246 p (setq p (next-single-property-change p 'display))
17247 '(display t))))
17248 (set-buffer-modified-p bmp)))
17249 (if (featurep 'xemacs)
17250 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17251 (org-restart-font-lock)
17252 (setq org-table-may-need-update t)
17253 (if org-display-custom-times
17254 (message "Time stamps are overlayed with custom format")
17255 (message "Time stamp overlays removed")))
17257 (defun org-display-custom-time (beg end)
17258 "Overlay modified time stamp format over timestamp between BED and END."
17259 (let* ((ts (buffer-substring beg end))
17260 t1 w1 with-hm tf time str w2 (off 0))
17261 (save-match-data
17262 (setq t1 (org-parse-time-string ts t))
17263 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
17264 (setq off (- (match-end 0) (match-beginning 0)))))
17265 (setq end (- end off))
17266 (setq w1 (- end beg)
17267 with-hm (and (nth 1 t1) (nth 2 t1))
17268 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17269 time (org-fix-decoded-time t1)
17270 str (org-add-props
17271 (format-time-string
17272 (substring tf 1 -1) (apply 'encode-time time))
17273 nil 'mouse-face 'highlight)
17274 w2 (length str))
17275 (if (not (= w2 w1))
17276 (add-text-properties (1+ beg) (+ 2 beg)
17277 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17278 (if (featurep 'xemacs)
17279 (progn
17280 (put-text-property beg end 'invisible t)
17281 (put-text-property beg end 'end-glyph (make-glyph str)))
17282 (put-text-property beg end 'display str))))
17284 (defun org-translate-time (string)
17285 "Translate all timestamps in STRING to custom format.
17286 But do this only if the variable `org-display-custom-times' is set."
17287 (when org-display-custom-times
17288 (save-match-data
17289 (let* ((start 0)
17290 (re org-ts-regexp-both)
17291 t1 with-hm inactive tf time str beg end)
17292 (while (setq start (string-match re string start))
17293 (setq beg (match-beginning 0)
17294 end (match-end 0)
17295 t1 (save-match-data
17296 (org-parse-time-string (substring string beg end) t))
17297 with-hm (and (nth 1 t1) (nth 2 t1))
17298 inactive (equal (substring string beg (1+ beg)) "[")
17299 tf (funcall (if with-hm 'cdr 'car)
17300 org-time-stamp-custom-formats)
17301 time (org-fix-decoded-time t1)
17302 str (format-time-string
17303 (concat
17304 (if inactive "[" "<") (substring tf 1 -1)
17305 (if inactive "]" ">"))
17306 (apply 'encode-time time))
17307 string (replace-match str t t string)
17308 start (+ start (length str)))))))
17309 string)
17311 (defun org-fix-decoded-time (time)
17312 "Set 0 instead of nil for the first 6 elements of time.
17313 Don't touch the rest."
17314 (let ((n 0))
17315 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17317 (defun org-days-to-time (timestamp-string)
17318 "Difference between TIMESTAMP-STRING and now in days."
17319 (- (time-to-days (org-time-string-to-time timestamp-string))
17320 (time-to-days (current-time))))
17322 (defun org-deadline-close (timestamp-string &optional ndays)
17323 "Is the time in TIMESTAMP-STRING close to the current date?"
17324 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17325 (and (< (org-days-to-time timestamp-string) ndays)
17326 (not (org-entry-is-done-p))))
17328 (defun org-get-wdays (ts)
17329 "Get the deadline lead time appropriate for timestring TS."
17330 (cond
17331 ((<= org-deadline-warning-days 0)
17332 ;; 0 or negative, enforce this value no matter what
17333 (- org-deadline-warning-days))
17334 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
17335 ;; lead time is specified.
17336 (floor (* (string-to-number (match-string 1 ts))
17337 (cdr (assoc (match-string 2 ts)
17338 '(("d" . 1) ("w" . 7)
17339 ("m" . 30.4) ("y" . 365.25)))))))
17340 ;; go for the default.
17341 (t org-deadline-warning-days)))
17343 (defun org-calendar-select-mouse (ev)
17344 "Return to `org-read-date' with the date currently selected.
17345 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17346 (interactive "e")
17347 (mouse-set-point ev)
17348 (when (calendar-cursor-to-date)
17349 (let* ((date (calendar-cursor-to-date))
17350 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17351 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17352 (if (active-minibuffer-window) (exit-minibuffer))))
17354 (defun org-check-deadlines (ndays)
17355 "Check if there are any deadlines due or past due.
17356 A deadline is considered due if it happens within `org-deadline-warning-days'
17357 days from today's date. If the deadline appears in an entry marked DONE,
17358 it is not shown. The prefix arg NDAYS can be used to test that many
17359 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17360 (interactive "P")
17361 (let* ((org-warn-days
17362 (cond
17363 ((equal ndays '(4)) 100000)
17364 (ndays (prefix-numeric-value ndays))
17365 (t (abs org-deadline-warning-days))))
17366 (case-fold-search nil)
17367 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17368 (callback
17369 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17371 (message "%d deadlines past-due or due within %d days"
17372 (org-occur regexp nil callback)
17373 org-warn-days)))
17375 (defun org-evaluate-time-range (&optional to-buffer)
17376 "Evaluate a time range by computing the difference between start and end.
17377 Normally the result is just printed in the echo area, but with prefix arg
17378 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17379 If the time range is actually in a table, the result is inserted into the
17380 next column.
17381 For time difference computation, a year is assumed to be exactly 365
17382 days in order to avoid rounding problems."
17383 (interactive "P")
17385 (org-clock-update-time-maybe)
17386 (save-excursion
17387 (unless (org-at-date-range-p t)
17388 (goto-char (point-at-bol))
17389 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17390 (if (not (org-at-date-range-p t))
17391 (error "Not at a time-stamp range, and none found in current line")))
17392 (let* ((ts1 (match-string 1))
17393 (ts2 (match-string 2))
17394 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17395 (match-end (match-end 0))
17396 (time1 (org-time-string-to-time ts1))
17397 (time2 (org-time-string-to-time ts2))
17398 (t1 (time-to-seconds time1))
17399 (t2 (time-to-seconds time2))
17400 (diff (abs (- t2 t1)))
17401 (negative (< (- t2 t1) 0))
17402 ;; (ys (floor (* 365 24 60 60)))
17403 (ds (* 24 60 60))
17404 (hs (* 60 60))
17405 (fy "%dy %dd %02d:%02d")
17406 (fy1 "%dy %dd")
17407 (fd "%dd %02d:%02d")
17408 (fd1 "%dd")
17409 (fh "%02d:%02d")
17410 y d h m align)
17411 (if havetime
17412 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17414 d (floor (/ diff ds)) diff (mod diff ds)
17415 h (floor (/ diff hs)) diff (mod diff hs)
17416 m (floor (/ diff 60)))
17417 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17419 d (floor (+ (/ diff ds) 0.5))
17420 h 0 m 0))
17421 (if (not to-buffer)
17422 (message (org-make-tdiff-string y d h m))
17423 (if (org-at-table-p)
17424 (progn
17425 (goto-char match-end)
17426 (setq align t)
17427 (and (looking-at " *|") (goto-char (match-end 0))))
17428 (goto-char match-end))
17429 (if (looking-at
17430 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17431 (replace-match ""))
17432 (if negative (insert " -"))
17433 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17434 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17435 (insert " " (format fh h m))))
17436 (if align (org-table-align))
17437 (message "Time difference inserted")))))
17439 (defun org-make-tdiff-string (y d h m)
17440 (let ((fmt "")
17441 (l nil))
17442 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17443 l (push y l)))
17444 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17445 l (push d l)))
17446 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17447 l (push h l)))
17448 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17449 l (push m l)))
17450 (apply 'format fmt (nreverse l))))
17452 (defun org-time-string-to-time (s)
17453 (apply 'encode-time (org-parse-time-string s)))
17455 (defun org-time-string-to-absolute (s &optional daynr)
17456 "Convert a time stamp to an absolute day number.
17457 If there is a specifyer for a cyclic time stamp, get the closest date to
17458 DAYNR."
17459 (cond
17460 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17461 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17462 daynr
17463 (+ daynr 1000)))
17464 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
17465 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17466 (time-to-days (current-time))) (match-string 0 s)))
17467 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
17469 (defun org-time-from-absolute (d)
17470 "Return the time corresponding to date D.
17471 D may be an absolute day number, or a calendar-type list (month day year)."
17472 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17473 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17475 (defun org-calendar-holiday ()
17476 "List of holidays, for Diary display in Org-mode."
17477 (require 'holidays)
17478 (let ((hl (funcall
17479 (if (fboundp 'calendar-check-holidays)
17480 'calendar-check-holidays 'check-calendar-holidays) date)))
17481 (if hl (mapconcat 'identity hl "; "))))
17483 (defun org-diary-sexp-entry (sexp entry date)
17484 "Process a SEXP diary ENTRY for DATE."
17485 (require 'diary-lib)
17486 (let ((result (if calendar-debug-sexp
17487 (let ((stack-trace-on-error t))
17488 (eval (car (read-from-string sexp))))
17489 (condition-case nil
17490 (eval (car (read-from-string sexp)))
17491 (error
17492 (beep)
17493 (message "Bad sexp at line %d in %s: %s"
17494 (org-current-line)
17495 (buffer-file-name) sexp)
17496 (sleep-for 2))))))
17497 (cond ((stringp result) result)
17498 ((and (consp result)
17499 (stringp (cdr result))) (cdr result))
17500 (result entry)
17501 (t nil))))
17503 (defun org-diary-to-ical-string (frombuf)
17504 "Get iCalendar entries from diary entries in buffer FROMBUF.
17505 This uses the icalendar.el library."
17506 (let* ((tmpdir (if (featurep 'xemacs)
17507 (temp-directory)
17508 temporary-file-directory))
17509 (tmpfile (make-temp-name
17510 (expand-file-name "orgics" tmpdir)))
17511 buf rtn b e)
17512 (save-excursion
17513 (set-buffer frombuf)
17514 (icalendar-export-region (point-min) (point-max) tmpfile)
17515 (setq buf (find-buffer-visiting tmpfile))
17516 (set-buffer buf)
17517 (goto-char (point-min))
17518 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17519 (setq b (match-beginning 0)))
17520 (goto-char (point-max))
17521 (if (re-search-backward "^END:VEVENT" nil t)
17522 (setq e (match-end 0)))
17523 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17524 (kill-buffer buf)
17525 (kill-buffer frombuf)
17526 (delete-file tmpfile)
17527 rtn))
17529 (defun org-closest-date (start current change)
17530 "Find the date closest to CURRENT that is consistent with START and CHANGE."
17531 ;; Make the proper lists from the dates
17532 (catch 'exit
17533 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
17534 dn dw sday cday n1 n2
17535 d m y y1 y2 date1 date2 nmonths nm ny m2)
17537 (setq start (org-date-to-gregorian start)
17538 current (org-date-to-gregorian
17539 (if org-agenda-repeating-timestamp-show-all
17540 current
17541 (time-to-days (current-time))))
17542 sday (calendar-absolute-from-gregorian start)
17543 cday (calendar-absolute-from-gregorian current))
17545 (if (<= cday sday) (throw 'exit sday))
17547 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
17548 (setq dn (string-to-number (match-string 1 change))
17549 dw (cdr (assoc (match-string 2 change) a1)))
17550 (error "Invalid change specifyer: %s" change))
17551 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17552 (cond
17553 ((eq dw 'day)
17554 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17555 n2 (+ n1 dn)))
17556 ((eq dw 'year)
17557 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17558 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17559 (setq date1 (list m d y1)
17560 n1 (calendar-absolute-from-gregorian date1)
17561 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17562 n2 (calendar-absolute-from-gregorian date2)))
17563 ((eq dw 'month)
17564 ;; approx number of month between the tow dates
17565 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17566 ;; How often does dn fit in there?
17567 (setq d (nth 1 start) m (car start) y (nth 2 start)
17568 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17569 m (+ m nm)
17570 ny (floor (/ m 12))
17571 y (+ y ny)
17572 m (- m (* ny 12)))
17573 (while (> m 12) (setq m (- m 12) y (1+ y)))
17574 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17575 (setq m2 (+ m dn) y2 y)
17576 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17577 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17578 (while (< n2 cday)
17579 (setq n1 n2 m m2 y y2)
17580 (setq m2 (+ m dn) y2 y)
17581 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17582 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17584 (if org-agenda-repeating-timestamp-show-all
17585 (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)
17586 (if (= cday n1) n1 n2)))))
17588 (defun org-date-to-gregorian (date)
17589 "Turn any specification of DATE into a gregorian date for the calendar."
17590 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17591 ((and (listp date) (= (length date) 3)) date)
17592 ((stringp date)
17593 (setq date (org-parse-time-string date))
17594 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17595 ((listp date)
17596 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17598 (defun org-parse-time-string (s &optional nodefault)
17599 "Parse the standard Org-mode time string.
17600 This should be a lot faster than the normal `parse-time-string'.
17601 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17602 hour and minute fields will be nil if not given."
17603 (if (string-match org-ts-regexp0 s)
17604 (list 0
17605 (if (or (match-beginning 8) (not nodefault))
17606 (string-to-number (or (match-string 8 s) "0")))
17607 (if (or (match-beginning 7) (not nodefault))
17608 (string-to-number (or (match-string 7 s) "0")))
17609 (string-to-number (match-string 4 s))
17610 (string-to-number (match-string 3 s))
17611 (string-to-number (match-string 2 s))
17612 nil nil nil)
17613 (make-list 9 0)))
17615 (defun org-timestamp-up (&optional arg)
17616 "Increase the date item at the cursor by one.
17617 If the cursor is on the year, change the year. If it is on the month or
17618 the day, change that.
17619 With prefix ARG, change by that many units."
17620 (interactive "p")
17621 (org-timestamp-change (prefix-numeric-value arg)))
17623 (defun org-timestamp-down (&optional arg)
17624 "Decrease the date item at the cursor by one.
17625 If the cursor is on the year, change the year. If it is on the month or
17626 the day, change that.
17627 With prefix ARG, change by that many units."
17628 (interactive "p")
17629 (org-timestamp-change (- (prefix-numeric-value arg))))
17631 (defun org-timestamp-up-day (&optional arg)
17632 "Increase the date in the time stamp by one day.
17633 With prefix ARG, change that many days."
17634 (interactive "p")
17635 (if (and (not (org-at-timestamp-p t))
17636 (org-on-heading-p))
17637 (org-todo 'up)
17638 (org-timestamp-change (prefix-numeric-value arg) 'day)))
17640 (defun org-timestamp-down-day (&optional arg)
17641 "Decrease the date in the time stamp by one day.
17642 With prefix ARG, change that many days."
17643 (interactive "p")
17644 (if (and (not (org-at-timestamp-p t))
17645 (org-on-heading-p))
17646 (org-todo 'down)
17647 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
17649 (defsubst org-pos-in-match-range (pos n)
17650 (and (match-beginning n)
17651 (<= (match-beginning n) pos)
17652 (>= (match-end n) pos)))
17654 (defun org-at-timestamp-p (&optional inactive-ok)
17655 "Determine if the cursor is in or at a timestamp."
17656 (interactive)
17657 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17658 (pos (point))
17659 (ans (or (looking-at tsr)
17660 (save-excursion
17661 (skip-chars-backward "^[<\n\r\t")
17662 (if (> (point) (point-min)) (backward-char 1))
17663 (and (looking-at tsr)
17664 (> (- (match-end 0) pos) -1))))))
17665 (and ans
17666 (boundp 'org-ts-what)
17667 (setq org-ts-what
17668 (cond
17669 ((= pos (match-beginning 0)) 'bracket)
17670 ((= pos (1- (match-end 0))) 'bracket)
17671 ((org-pos-in-match-range pos 2) 'year)
17672 ((org-pos-in-match-range pos 3) 'month)
17673 ((org-pos-in-match-range pos 7) 'hour)
17674 ((org-pos-in-match-range pos 8) 'minute)
17675 ((or (org-pos-in-match-range pos 4)
17676 (org-pos-in-match-range pos 5)) 'day)
17677 ((and (> pos (or (match-end 8) (match-end 5)))
17678 (< pos (match-end 0)))
17679 (- pos (or (match-end 8) (match-end 5))))
17680 (t 'day))))
17681 ans))
17683 (defun org-toggle-timestamp-type ()
17685 (interactive)
17686 (when (org-at-timestamp-p t)
17687 (save-excursion
17688 (goto-char (match-beginning 0))
17689 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
17690 (goto-char (1- (match-end 0)))
17691 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
17692 (message "Timestamp is now %sactive"
17693 (if (equal (char-before) ?>) "in" ""))))
17695 (defun org-timestamp-change (n &optional what)
17696 "Change the date in the time stamp at point.
17697 The date will be changed by N times WHAT. WHAT can be `day', `month',
17698 `year', `minute', `second'. If WHAT is not given, the cursor position
17699 in the timestamp determines what will be changed."
17700 (let ((pos (point))
17701 with-hm inactive
17702 org-ts-what
17703 extra
17704 ts time time0)
17705 (if (not (org-at-timestamp-p t))
17706 (error "Not at a timestamp"))
17707 (if (and (not what) (eq org-ts-what 'bracket))
17708 (org-toggle-timestamp-type)
17709 (if (and (not what) (not (eq org-ts-what 'day))
17710 org-display-custom-times
17711 (get-text-property (point) 'display)
17712 (not (get-text-property (1- (point)) 'display)))
17713 (setq org-ts-what 'day))
17714 (setq org-ts-what (or what org-ts-what)
17715 inactive (= (char-after (match-beginning 0)) ?\[)
17716 ts (match-string 0))
17717 (replace-match "")
17718 (if (string-match
17719 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
17721 (setq extra (match-string 1 ts)))
17722 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17723 (setq with-hm t))
17724 (setq time0 (org-parse-time-string ts))
17725 (setq time
17726 (encode-time (or (car time0) 0)
17727 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17728 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17729 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17730 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17731 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17732 (nthcdr 6 time0)))
17733 (when (integerp org-ts-what)
17734 (setq extra (org-modify-ts-extra extra org-ts-what n)))
17735 (if (eq what 'calendar)
17736 (let ((cal-date (org-get-date-from-calendar)))
17737 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17738 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17739 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17740 (setcar time0 (or (car time0) 0))
17741 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17742 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17743 (setq time (apply 'encode-time time0))))
17744 (setq org-last-changed-timestamp
17745 (org-insert-time-stamp time with-hm inactive nil nil extra))
17746 (org-clock-update-time-maybe)
17747 (goto-char pos)
17748 ;; Try to recenter the calendar window, if any
17749 (if (and org-calendar-follow-timestamp-change
17750 (get-buffer-window "*Calendar*" t)
17751 (memq org-ts-what '(day month year)))
17752 (org-recenter-calendar (time-to-days time))))))
17754 ;; FIXME: does not yet work for lead times
17755 (defun org-modify-ts-extra (s pos n)
17756 "Change the different parts of the lead-time and repeat fields in timestamp."
17757 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17758 ng h m new)
17759 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17760 (cond
17761 ((or (org-pos-in-match-range pos 2)
17762 (org-pos-in-match-range pos 3))
17763 (setq m (string-to-number (match-string 3 s))
17764 h (string-to-number (match-string 2 s)))
17765 (if (org-pos-in-match-range pos 2)
17766 (setq h (+ h n))
17767 (setq m (+ m n)))
17768 (if (< m 0) (setq m (+ m 60) h (1- h)))
17769 (if (> m 59) (setq m (- m 60) h (1+ h)))
17770 (setq h (min 24 (max 0 h)))
17771 (setq ng 1 new (format "-%02d:%02d" h m)))
17772 ((org-pos-in-match-range pos 6)
17773 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17774 ((org-pos-in-match-range pos 5)
17775 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
17777 (when ng
17778 (setq s (concat
17779 (substring s 0 (match-beginning ng))
17781 (substring s (match-end ng))))))
17784 (defun org-recenter-calendar (date)
17785 "If the calendar is visible, recenter it to DATE."
17786 (let* ((win (selected-window))
17787 (cwin (get-buffer-window "*Calendar*" t))
17788 (calendar-move-hook nil))
17789 (when cwin
17790 (select-window cwin)
17791 (calendar-goto-date (if (listp date) date
17792 (calendar-gregorian-from-absolute date)))
17793 (select-window win))))
17795 (defun org-goto-calendar (&optional arg)
17796 "Go to the Emacs calendar at the current date.
17797 If there is a time stamp in the current line, go to that date.
17798 A prefix ARG can be used to force the current date."
17799 (interactive "P")
17800 (let ((tsr org-ts-regexp) diff
17801 (calendar-move-hook nil)
17802 (view-calendar-holidays-initially nil)
17803 (view-diary-entries-initially nil))
17804 (if (or (org-at-timestamp-p)
17805 (save-excursion
17806 (beginning-of-line 1)
17807 (looking-at (concat ".*" tsr))))
17808 (let ((d1 (time-to-days (current-time)))
17809 (d2 (time-to-days
17810 (org-time-string-to-time (match-string 1)))))
17811 (setq diff (- d2 d1))))
17812 (calendar)
17813 (calendar-goto-today)
17814 (if (and diff (not arg)) (calendar-forward-day diff))))
17816 (defun org-get-date-from-calendar ()
17817 "Return a list (month day year) of date at point in calendar."
17818 (with-current-buffer "*Calendar*"
17819 (save-match-data
17820 (calendar-cursor-to-date))))
17822 (defun org-date-from-calendar ()
17823 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17824 If there is already a time stamp at the cursor position, update it."
17825 (interactive)
17826 (if (org-at-timestamp-p t)
17827 (org-timestamp-change 0 'calendar)
17828 (let ((cal-date (org-get-date-from-calendar)))
17829 (org-insert-time-stamp
17830 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17832 ;; Make appt aware of appointments from the agenda
17833 ;;;###autoload
17834 (defun org-agenda-to-appt (&optional filter)
17835 "Activate appointments found in `org-agenda-files'.
17836 When prefixed, prompt for a regular expression and use it as a
17837 filter: only add entries if they match this regular expression.
17839 FILTER can be a string. In this case, use this string as a
17840 regular expression to filter results.
17842 FILTER can also be an alist, with the car of each cell being
17843 either 'headline or 'category. For example:
17845 '((headline \"IMPORTANT\")
17846 (category \"Work\"))
17848 will only add headlines containing IMPORTANT or headlines
17849 belonging to the category \"Work\"."
17850 (interactive "P")
17851 (require 'calendar)
17852 (if (equal filter '(4))
17853 (setq filter (read-from-minibuffer "Regexp filter: ")))
17854 (let* ((cnt 0) ; count added events
17855 (org-agenda-new-buffers nil)
17856 (today (org-date-to-gregorian
17857 (time-to-days (current-time))))
17858 (files (org-agenda-files)) entries file)
17859 ;; Get all entries which may contain an appt
17860 (while (setq file (pop files))
17861 (setq entries
17862 (append entries
17863 (org-agenda-get-day-entries
17864 file today
17865 :timestamp :scheduled :deadline))))
17866 (setq entries (delq nil entries))
17867 ;; Map thru entries and find if they pass thru the filter
17868 (mapc
17869 (lambda(x)
17870 (let* ((evt (org-trim (get-text-property 1 'txt x)))
17871 (cat (get-text-property 1 'org-category x))
17872 (tod (get-text-property 1 'time-of-day x))
17873 (ok (or (null filter)
17874 (and (stringp filter) (string-match filter evt))
17875 (and (listp filter)
17876 (or (string-match
17877 (cadr (assoc 'category filter)) cat)
17878 (string-match
17879 (cadr (assoc 'headline filter)) evt))))))
17880 ;; FIXME: Shall we remove text-properties for the appt text?
17881 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
17882 (when (and ok tod)
17883 (setq tod (number-to-string tod)
17884 tod (when (string-match
17885 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
17886 (concat (match-string 1 tod) ":"
17887 (match-string 2 tod))))
17888 (appt-add tod evt)
17889 (setq cnt (1+ cnt))))) entries)
17890 (org-release-buffers org-agenda-new-buffers)
17891 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" ""))))
17893 ;;; The clock for measuring work time.
17895 (defvar org-mode-line-string "")
17896 (put 'org-mode-line-string 'risky-local-variable t)
17898 (defvar org-mode-line-timer nil)
17899 (defvar org-clock-heading "")
17900 (defvar org-clock-start-time "")
17902 (defun org-update-mode-line ()
17903 (let* ((delta (- (time-to-seconds (current-time))
17904 (time-to-seconds org-clock-start-time)))
17905 (h (floor delta 3600))
17906 (m (floor (- delta (* 3600 h)) 60)))
17907 (setq org-mode-line-string
17908 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
17909 'help-echo "Org-mode clock is running"))
17910 (force-mode-line-update)))
17912 (defvar org-clock-marker (make-marker)
17913 "Marker recording the last clock-in.")
17914 (defvar org-clock-mode-line-entry nil
17915 "Information for the modeline about the running clock.")
17917 (defun org-clock-in ()
17918 "Start the clock on the current item.
17919 If necessary, clock-out of the currently active clock."
17920 (interactive)
17921 (org-clock-out t)
17922 (let (ts)
17923 (save-excursion
17924 (org-back-to-heading t)
17925 (if (and org-clock-heading-function
17926 (functionp org-clock-heading-function))
17927 (setq org-clock-heading (funcall org-clock-heading-function))
17928 (if (looking-at org-complex-heading-regexp)
17929 (setq org-clock-heading (match-string 4))
17930 (setq org-clock-heading "???")))
17931 (setq org-clock-heading (propertize org-clock-heading 'face nil))
17932 (org-clock-find-position)
17934 (insert "\n") (backward-char 1)
17935 (indent-relative)
17936 (insert org-clock-string " ")
17937 (setq org-clock-start-time (current-time))
17938 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
17939 (move-marker org-clock-marker (point) (buffer-base-buffer))
17940 (or global-mode-string (setq global-mode-string '("")))
17941 (or (memq 'org-mode-line-string global-mode-string)
17942 (setq global-mode-string
17943 (append global-mode-string '(org-mode-line-string))))
17944 (org-update-mode-line)
17945 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
17946 (message "Clock started at %s" ts))))
17948 (defun org-clock-find-position ()
17949 "Find the location where the next clock line should be inserted."
17950 (org-back-to-heading t)
17951 (catch 'exit
17952 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
17953 (re (concat "^[ \t]*" org-clock-string))
17954 (cnt 0)
17955 first last)
17956 (goto-char beg)
17957 (when (eobp) (newline) (setq end (max (point) end)))
17958 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
17959 ;; we seem to have a CLOCK drawer, so go there.
17960 (beginning-of-line 2)
17961 (throw 'exit t))
17962 ;; Lets count the CLOCK lines
17963 (goto-char beg)
17964 (while (re-search-forward re end t)
17965 (setq first (or first (match-beginning 0))
17966 last (match-beginning 0)
17967 cnt (1+ cnt)))
17968 (when (and (integerp org-clock-into-drawer)
17969 (>= (1+ cnt) org-clock-into-drawer))
17970 ;; Wrap current entries into a new drawer
17971 (goto-char last)
17972 (beginning-of-line 2)
17973 (if (org-at-item-p) (org-end-of-item))
17974 (insert ":END:\n")
17975 (beginning-of-line 0)
17976 (org-indent-line-function)
17977 (goto-char first)
17978 (insert ":CLOCK:\n")
17979 (beginning-of-line 0)
17980 (org-indent-line-function)
17981 (org-flag-drawer t)
17982 (beginning-of-line 2)
17983 (throw 'exit nil))
17985 (goto-char beg)
17986 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
17987 (not (equal (match-string 1) org-clock-string)))
17988 ;; Planning info, skip to after it
17989 (beginning-of-line 2)
17990 (or (bolp) (newline)))
17991 (when (eq t org-clock-into-drawer)
17992 (insert ":CLOCK:\n:END:\n")
17993 (beginning-of-line -1)
17994 (org-indent-line-function)
17995 (org-flag-drawer t)
17996 (beginning-of-line 2)
17997 (org-indent-line-function)))))
17999 (defun org-clock-out (&optional fail-quietly)
18000 "Stop the currently running clock.
18001 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
18002 (interactive)
18003 (catch 'exit
18004 (if (not (marker-buffer org-clock-marker))
18005 (if fail-quietly (throw 'exit t) (error "No active clock")))
18006 (let (ts te s h m)
18007 (save-excursion
18008 (set-buffer (marker-buffer org-clock-marker))
18009 (goto-char org-clock-marker)
18010 (beginning-of-line 1)
18011 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18012 (equal (match-string 1) org-clock-string))
18013 (setq ts (match-string 2))
18014 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
18015 (goto-char (match-end 0))
18016 (delete-region (point) (point-at-eol))
18017 (insert "--")
18018 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18019 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
18020 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
18021 h (floor (/ s 3600))
18022 s (- s (* 3600 h))
18023 m (floor (/ s 60))
18024 s (- s (* 60 s)))
18025 (insert " => " (format "%2d:%02d" h m))
18026 (move-marker org-clock-marker nil)
18027 (let* ((logging (save-match-data (org-entry-get nil "LOGGING" t)))
18028 (org-log-done (org-parse-local-options logging 'org-log-done))
18029 (org-log-repeat (org-parse-local-options logging 'org-log-repeat)))
18030 (org-add-log-maybe 'clock-out))
18031 (when org-mode-line-timer
18032 (cancel-timer org-mode-line-timer)
18033 (setq org-mode-line-timer nil))
18034 (setq global-mode-string
18035 (delq 'org-mode-line-string global-mode-string))
18036 (force-mode-line-update)
18037 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
18039 (defun org-clock-cancel ()
18040 "Cancel the running clock be removing the start timestamp."
18041 (interactive)
18042 (if (not (marker-buffer org-clock-marker))
18043 (error "No active clock"))
18044 (save-excursion
18045 (set-buffer (marker-buffer org-clock-marker))
18046 (goto-char org-clock-marker)
18047 (delete-region (1- (point-at-bol)) (point-at-eol)))
18048 (setq global-mode-string
18049 (delq 'org-mode-line-string global-mode-string))
18050 (force-mode-line-update)
18051 (message "Clock canceled"))
18053 (defun org-clock-goto (&optional delete-windows)
18054 "Go to the currently clocked-in entry."
18055 (interactive "P")
18056 (if (not (marker-buffer org-clock-marker))
18057 (error "No active clock"))
18058 (switch-to-buffer-other-window
18059 (marker-buffer org-clock-marker))
18060 (if delete-windows (delete-other-windows))
18061 (goto-char org-clock-marker)
18062 (org-show-entry)
18063 (org-back-to-heading)
18064 (recenter))
18066 (defvar org-clock-file-total-minutes nil
18067 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
18068 (make-variable-buffer-local 'org-clock-file-total-minutes)
18070 (defun org-clock-sum (&optional tstart tend)
18071 "Sum the times for each subtree.
18072 Puts the resulting times in minutes as a text property on each headline."
18073 (interactive)
18074 (let* ((bmp (buffer-modified-p))
18075 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
18076 org-clock-string
18077 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
18078 (lmax 30)
18079 (ltimes (make-vector lmax 0))
18080 (t1 0)
18081 (level 0)
18082 ts te dt
18083 time)
18084 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
18085 (save-excursion
18086 (goto-char (point-max))
18087 (while (re-search-backward re nil t)
18088 (cond
18089 ((match-end 2)
18090 ;; Two time stamps
18091 (setq ts (match-string 2)
18092 te (match-string 3)
18093 ts (time-to-seconds
18094 (apply 'encode-time (org-parse-time-string ts)))
18095 te (time-to-seconds
18096 (apply 'encode-time (org-parse-time-string te)))
18097 ts (if tstart (max ts tstart) ts)
18098 te (if tend (min te tend) te)
18099 dt (- te ts)
18100 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
18101 ((match-end 4)
18102 ;; A naket time
18103 (setq t1 (+ t1 (string-to-number (match-string 5))
18104 (* 60 (string-to-number (match-string 4))))))
18105 (t ;; A headline
18106 (setq level (- (match-end 1) (match-beginning 1)))
18107 (when (or (> t1 0) (> (aref ltimes level) 0))
18108 (loop for l from 0 to level do
18109 (aset ltimes l (+ (aref ltimes l) t1)))
18110 (setq t1 0 time (aref ltimes level))
18111 (loop for l from level to (1- lmax) do
18112 (aset ltimes l 0))
18113 (goto-char (match-beginning 0))
18114 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
18115 (setq org-clock-file-total-minutes (aref ltimes 0)))
18116 (set-buffer-modified-p bmp)))
18118 (defun org-clock-display (&optional total-only)
18119 "Show subtree times in the entire buffer.
18120 If TOTAL-ONLY is non-nil, only show the total time for the entire file
18121 in the echo area."
18122 (interactive)
18123 (org-remove-clock-overlays)
18124 (let (time h m p)
18125 (org-clock-sum)
18126 (unless total-only
18127 (save-excursion
18128 (goto-char (point-min))
18129 (while (or (and (equal (setq p (point)) (point-min))
18130 (get-text-property p :org-clock-minutes))
18131 (setq p (next-single-property-change
18132 (point) :org-clock-minutes)))
18133 (goto-char p)
18134 (when (setq time (get-text-property p :org-clock-minutes))
18135 (org-put-clock-overlay time (funcall outline-level))))
18136 (setq h (/ org-clock-file-total-minutes 60)
18137 m (- org-clock-file-total-minutes (* 60 h)))
18138 ;; Arrange to remove the overlays upon next change.
18139 (when org-remove-highlights-with-change
18140 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
18141 nil 'local))))
18142 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
18144 (defvar org-clock-overlays nil)
18145 (make-variable-buffer-local 'org-clock-overlays)
18147 (defun org-put-clock-overlay (time &optional level)
18148 "Put an overlays on the current line, displaying TIME.
18149 If LEVEL is given, prefix time with a corresponding number of stars.
18150 This creates a new overlay and stores it in `org-clock-overlays', so that it
18151 will be easy to remove."
18152 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
18153 (l (if level (org-get-legal-level level 0) 0))
18154 (off 0)
18155 ov tx)
18156 (move-to-column c)
18157 (unless (eolp) (skip-chars-backward "^ \t"))
18158 (skip-chars-backward " \t")
18159 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
18160 tx (concat (buffer-substring (1- (point)) (point))
18161 (make-string (+ off (max 0 (- c (current-column)))) ?.)
18162 (org-add-props (format "%s %2d:%02d%s"
18163 (make-string l ?*) h m
18164 (make-string (- 10 l) ?\ ))
18165 '(face secondary-selection))
18166 ""))
18167 (if (not (featurep 'xemacs))
18168 (org-overlay-put ov 'display tx)
18169 (org-overlay-put ov 'invisible t)
18170 (org-overlay-put ov 'end-glyph (make-glyph tx)))
18171 (push ov org-clock-overlays)))
18173 (defun org-remove-clock-overlays (&optional beg end noremove)
18174 "Remove the occur highlights from the buffer.
18175 BEG and END are ignored. If NOREMOVE is nil, remove this function
18176 from the `before-change-functions' in the current buffer."
18177 (interactive)
18178 (unless org-inhibit-highlight-removal
18179 (mapc 'org-delete-overlay org-clock-overlays)
18180 (setq org-clock-overlays nil)
18181 (unless noremove
18182 (remove-hook 'before-change-functions
18183 'org-remove-clock-overlays 'local))))
18185 (defun org-clock-out-if-current ()
18186 "Clock out if the current entry contains the running clock.
18187 This is used to stop the clock after a TODO entry is marked DONE,
18188 and is only done if the variable `org-clock-out-when-done' is not nil."
18189 (when (and org-clock-out-when-done
18190 (member state org-done-keywords)
18191 (equal (marker-buffer org-clock-marker) (current-buffer))
18192 (< (point) org-clock-marker)
18193 (> (save-excursion (outline-next-heading) (point))
18194 org-clock-marker))
18195 ;; Clock out, but don't accept a logging message for this.
18196 (let ((org-log-done (if (and (listp org-log-done)
18197 (member 'clock-out org-log-done))
18198 '(done)
18199 org-log-done)))
18200 (org-clock-out))))
18202 (add-hook 'org-after-todo-state-change-hook
18203 'org-clock-out-if-current)
18205 (defun org-check-running-clock ()
18206 "Check if the current buffer contains the running clock.
18207 If yes, offer to stop it and to save the buffer with the changes."
18208 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
18209 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
18210 (buffer-name))))
18211 (org-clock-out)
18212 (when (y-or-n-p "Save changed buffer?")
18213 (save-buffer))))
18215 (defun org-clock-report (&optional arg)
18216 "Create a table containing a report about clocked time.
18217 If the cursor is inside an existing clocktable block, then the table
18218 will be updated. If not, a new clocktable will be inserted.
18219 When called with a prefix argument, move to the first clock table in the
18220 buffer and update it."
18221 (interactive "P")
18222 (org-remove-clock-overlays)
18223 (when arg (org-find-dblock "clocktable"))
18224 (if (org-in-clocktable-p)
18225 (goto-char (org-in-clocktable-p))
18226 (org-create-dblock (list :name "clocktable"
18227 :maxlevel 2 :scope 'file)))
18228 (org-update-dblock))
18230 (defun org-in-clocktable-p ()
18231 "Check if the cursor is in a clocktable."
18232 (let ((pos (point)) start)
18233 (save-excursion
18234 (end-of-line 1)
18235 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
18236 (setq start (match-beginning 0))
18237 (re-search-forward "^#\\+END:.*" nil t)
18238 (>= (match-end 0) pos)
18239 start))))
18241 (defun org-clock-update-time-maybe ()
18242 "If this is a CLOCK line, update it and return t.
18243 Otherwise, return nil."
18244 (interactive)
18245 (save-excursion
18246 (beginning-of-line 1)
18247 (skip-chars-forward " \t")
18248 (when (looking-at org-clock-string)
18249 (let ((re (concat "[ \t]*" org-clock-string
18250 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
18251 "\\([ \t]*=>.*\\)?"))
18252 ts te h m s)
18253 (if (not (looking-at re))
18255 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
18256 (end-of-line 1)
18257 (setq ts (match-string 1)
18258 te (match-string 2))
18259 (setq s (- (time-to-seconds
18260 (apply 'encode-time (org-parse-time-string te)))
18261 (time-to-seconds
18262 (apply 'encode-time (org-parse-time-string ts))))
18263 h (floor (/ s 3600))
18264 s (- s (* 3600 h))
18265 m (floor (/ s 60))
18266 s (- s (* 60 s)))
18267 (insert " => " (format "%2d:%02d" h m))
18268 t)))))
18270 (defun org-clock-special-range (key &optional time as-strings)
18271 "Return two times bordering a special time range.
18272 Key is a symbol specifying the range and can be one of `today', `yesterday',
18273 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
18274 A week starts Monday 0:00 and ends Sunday 24:00.
18275 The range is determined relative to TIME. TIME defaults to the current time.
18276 The return value is a cons cell with two internal times like the ones
18277 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
18278 the returned times will be formatted strings."
18279 (let* ((tm (decode-time (or time (current-time))))
18280 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
18281 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
18282 (dow (nth 6 tm))
18283 s1 m1 h1 d1 month1 y1 diff ts te fm)
18284 (cond
18285 ((eq key 'today)
18286 (setq h 0 m 0 h1 24 m1 0))
18287 ((eq key 'yesterday)
18288 (setq d (1- d) h 0 m 0 h1 24 m1 0))
18289 ((eq key 'thisweek)
18290 (setq diff (if (= dow 0) 6 (1- dow))
18291 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18292 ((eq key 'lastweek)
18293 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
18294 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18295 ((eq key 'thismonth)
18296 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
18297 ((eq key 'lastmonth)
18298 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
18299 ((eq key 'thisyear)
18300 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
18301 ((eq key 'lastyear)
18302 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
18303 (t (error "No such time block %s" key)))
18304 (setq ts (encode-time s m h d month y)
18305 te (encode-time (or s1 s) (or m1 m) (or h1 h)
18306 (or d1 d) (or month1 month) (or y1 y)))
18307 (setq fm (cdr org-time-stamp-formats))
18308 (if as-strings
18309 (cons (format-time-string fm ts) (format-time-string fm te))
18310 (cons ts te))))
18312 (defun org-dblock-write:clocktable (params)
18313 "Write the standard clocktable."
18314 (let ((hlchars '((1 . "*") (2 . "/")))
18315 (emph nil)
18316 (ins (make-marker))
18317 (total-time nil)
18318 ipos time h m p level hlc hdl maxlevel
18319 ts te cc block beg end pos scope tbl tostring multifile)
18320 (setq scope (plist-get params :scope)
18321 tostring (plist-get params :tostring)
18322 multifile (plist-get params :multifile)
18323 maxlevel (or (plist-get params :maxlevel) 3)
18324 emph (plist-get params :emphasize)
18325 ts (plist-get params :tstart)
18326 te (plist-get params :tend)
18327 block (plist-get params :block))
18328 (when block
18329 (setq cc (org-clock-special-range block nil t)
18330 ts (car cc) te (cdr cc)))
18331 (if ts (setq ts (time-to-seconds
18332 (apply 'encode-time (org-parse-time-string ts)))))
18333 (if te (setq te (time-to-seconds
18334 (apply 'encode-time (org-parse-time-string te)))))
18335 (move-marker ins (point))
18336 (setq ipos (point))
18338 ;; Get the right scope
18339 (setq pos (point))
18340 (save-restriction
18341 (cond
18342 ((not scope))
18343 ((eq scope 'file) (widen))
18344 ((eq scope 'subtree) (org-narrow-to-subtree))
18345 ((eq scope 'tree)
18346 (while (org-up-heading-safe))
18347 (org-narrow-to-subtree))
18348 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
18349 (symbol-name scope)))
18350 (setq level (string-to-number (match-string 1 (symbol-name scope))))
18351 (catch 'exit
18352 (while (org-up-heading-safe)
18353 (looking-at outline-regexp)
18354 (if (<= (org-reduced-level (funcall outline-level)) level)
18355 (throw 'exit nil))))
18356 (org-narrow-to-subtree))
18357 ((or (listp scope) (eq scope 'agenda))
18358 (let* ((files (if (listp scope) scope (org-agenda-files)))
18359 (scope 'agenda)
18360 (p1 (copy-sequence params))
18361 file)
18362 (plist-put p1 :tostring t)
18363 (plist-put p1 :multifile t)
18364 (plist-put p1 :scope 'file)
18365 (org-prepare-agenda-buffers files)
18366 (while (setq file (pop files))
18367 (with-current-buffer (find-buffer-visiting file)
18368 (push (org-clocktable-add-file
18369 file (org-dblock-write:clocktable p1)) tbl)
18370 (setq total-time (+ (or total-time 0)
18371 org-clock-file-total-minutes)))))))
18372 (goto-char pos)
18374 (unless (eq scope 'agenda)
18375 (org-clock-sum ts te)
18376 (goto-char (point-min))
18377 (while (setq p (next-single-property-change (point) :org-clock-minutes))
18378 (goto-char p)
18379 (when (setq time (get-text-property p :org-clock-minutes))
18380 (save-excursion
18381 (beginning-of-line 1)
18382 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
18383 (setq level (org-reduced-level
18384 (- (match-end 1) (match-beginning 1))))
18385 (<= level maxlevel))
18386 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
18387 hdl (match-string 2)
18388 h (/ time 60)
18389 m (- time (* 60 h)))
18390 (if (and (not multifile) (= level 1)) (push "|-" tbl))
18391 (push (concat
18392 "| " (int-to-string level) "|" hlc hdl hlc " |"
18393 (make-string (1- level) ?|)
18394 hlc (format "%d:%02d" h m) hlc
18395 " |") tbl))))))
18396 (setq tbl (nreverse tbl))
18397 (if tostring
18398 (if tbl (mapconcat 'identity tbl "\n") nil)
18399 (goto-char ins)
18400 (insert-before-markers
18401 "Clock summary at ["
18402 (substring
18403 (format-time-string (cdr org-time-stamp-formats))
18404 1 -1)
18405 "]."
18406 (if block
18407 (format " Considered range is /%s/." block)
18409 "\n\n"
18410 (if (eq scope 'agenda) "|File" "")
18411 "|L|Headline|Time|\n")
18412 (setq total-time (or total-time org-clock-file-total-minutes)
18413 h (/ total-time 60)
18414 m (- total-time (* 60 h)))
18415 (insert-before-markers
18416 "|-\n|"
18417 (if (eq scope 'agenda) "|" "")
18419 "*Total time*| "
18420 (format "*%d:%02d*" h m)
18421 "|\n|-\n")
18422 (setq tbl (delq nil tbl))
18423 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
18424 (equal (substring (car tbl) 0 2) "|-"))
18425 (pop tbl))
18426 (insert-before-markers (mapconcat
18427 'identity (delq nil tbl)
18428 (if (eq scope 'agenda) "\n|-\n" "\n")))
18429 (backward-delete-char 1)
18430 (goto-char ipos)
18431 (skip-chars-forward "^|")
18432 (org-table-align)))))
18434 (defun org-clocktable-add-file (file table)
18435 (if table
18436 (let ((lines (org-split-string table "\n"))
18437 (ff (file-name-nondirectory file)))
18438 (mapconcat 'identity
18439 (mapcar (lambda (x)
18440 (if (string-match org-table-dataline-regexp x)
18441 (concat "|" ff x)
18443 lines)
18444 "\n"))))
18446 ;; FIXME: I don't think anybody uses this, ask David
18447 (defun org-collect-clock-time-entries ()
18448 "Return an internal list with clocking information.
18449 This list has one entry for each CLOCK interval.
18450 FIXME: describe the elements."
18451 (interactive)
18452 (let ((re (concat "^[ \t]*" org-clock-string
18453 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
18454 rtn beg end next cont level title total closedp leafp
18455 clockpos titlepos h m donep)
18456 (save-excursion
18457 (org-clock-sum)
18458 (goto-char (point-min))
18459 (while (re-search-forward re nil t)
18460 (setq clockpos (match-beginning 0)
18461 beg (match-string 1) end (match-string 2)
18462 cont (match-end 0))
18463 (setq beg (apply 'encode-time (org-parse-time-string beg))
18464 end (apply 'encode-time (org-parse-time-string end)))
18465 (org-back-to-heading t)
18466 (setq donep (org-entry-is-done-p))
18467 (setq titlepos (point)
18468 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
18469 h (/ total 60) m (- total (* 60 h))
18470 total (cons h m))
18471 (looking-at "\\(\\*+\\) +\\(.*\\)")
18472 (setq level (- (match-end 1) (match-beginning 1))
18473 title (org-match-string-no-properties 2))
18474 (save-excursion (outline-next-heading) (setq next (point)))
18475 (setq closedp (re-search-forward org-closed-time-regexp next t))
18476 (goto-char next)
18477 (setq leafp (and (looking-at "^\\*+ ")
18478 (<= (- (match-end 0) (point)) level)))
18479 (push (list beg end clockpos closedp donep
18480 total title titlepos level leafp)
18481 rtn)
18482 (goto-char cont)))
18483 (nreverse rtn)))
18485 ;;;; Agenda, and Diary Integration
18487 ;;; Define the Org-agenda-mode
18489 (defvar org-agenda-mode-map (make-sparse-keymap)
18490 "Keymap for `org-agenda-mode'.")
18492 (defvar org-agenda-menu) ; defined later in this file.
18493 (defvar org-agenda-follow-mode nil)
18494 (defvar org-agenda-show-log nil)
18495 (defvar org-agenda-redo-command nil)
18496 (defvar org-agenda-mode-hook nil)
18497 (defvar org-agenda-type nil)
18498 (defvar org-agenda-force-single-file nil)
18500 (defun org-agenda-mode ()
18501 "Mode for time-sorted view on action items in Org-mode files.
18503 The following commands are available:
18505 \\{org-agenda-mode-map}"
18506 (interactive)
18507 (kill-all-local-variables)
18508 (setq org-agenda-undo-list nil
18509 org-agenda-pending-undo-list nil)
18510 (setq major-mode 'org-agenda-mode)
18511 ;; Keep global-font-lock-mode from turning on font-lock-mode
18512 (org-set-local 'font-lock-global-modes (list 'not major-mode))
18513 (setq mode-name "Org-Agenda")
18514 (use-local-map org-agenda-mode-map)
18515 (easy-menu-add org-agenda-menu)
18516 (if org-startup-truncated (setq truncate-lines t))
18517 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
18518 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
18519 ;; Make sure properties are removed when copying text
18520 (when (boundp 'buffer-substring-filters)
18521 (org-set-local 'buffer-substring-filters
18522 (cons (lambda (x)
18523 (set-text-properties 0 (length x) nil x) x)
18524 buffer-substring-filters)))
18525 (unless org-agenda-keep-modes
18526 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
18527 org-agenda-show-log nil))
18528 (easy-menu-change
18529 '("Agenda") "Agenda Files"
18530 (append
18531 (list
18532 (vector
18533 (if (get 'org-agenda-files 'org-restrict)
18534 "Restricted to single file"
18535 "Edit File List")
18536 '(org-edit-agenda-file-list)
18537 (not (get 'org-agenda-files 'org-restrict)))
18538 "--")
18539 (mapcar 'org-file-menu-entry (org-agenda-files))))
18540 (org-agenda-set-mode-name)
18541 (apply
18542 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
18543 (list 'org-agenda-mode-hook)))
18545 (substitute-key-definition 'undo 'org-agenda-undo
18546 org-agenda-mode-map global-map)
18547 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
18548 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
18549 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
18550 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
18551 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
18552 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
18553 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
18554 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
18555 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
18556 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
18557 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
18558 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
18559 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
18560 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
18561 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
18562 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
18563 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
18564 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
18565 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
18566 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
18567 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
18568 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
18569 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
18570 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
18571 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
18572 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
18573 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
18574 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
18575 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
18577 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
18578 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
18579 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
18580 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
18581 (while l (org-defkey org-agenda-mode-map
18582 (int-to-string (pop l)) 'digit-argument)))
18584 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
18585 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
18586 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
18587 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
18588 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
18589 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
18590 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
18591 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
18592 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
18593 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
18594 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
18595 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
18596 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
18597 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
18598 (org-defkey org-agenda-mode-map "n" 'next-line)
18599 (org-defkey org-agenda-mode-map "p" 'previous-line)
18600 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
18601 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
18602 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
18603 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
18604 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
18605 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
18606 (eval-after-load "calendar"
18607 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
18608 'org-calendar-goto-agenda))
18609 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
18610 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
18611 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
18612 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
18613 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
18614 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
18615 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
18616 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
18617 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
18618 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
18619 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
18620 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18621 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
18622 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
18623 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
18624 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
18625 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
18626 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
18627 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
18628 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
18629 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
18630 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
18632 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
18633 "Local keymap for agenda entries from Org-mode.")
18635 (org-defkey org-agenda-keymap
18636 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
18637 (org-defkey org-agenda-keymap
18638 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
18639 (when org-agenda-mouse-1-follows-link
18640 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
18641 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
18642 '("Agenda"
18643 ("Agenda Files")
18644 "--"
18645 ["Show" org-agenda-show t]
18646 ["Go To (other window)" org-agenda-goto t]
18647 ["Go To (this window)" org-agenda-switch-to t]
18648 ["Follow Mode" org-agenda-follow-mode
18649 :style toggle :selected org-agenda-follow-mode :active t]
18650 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
18651 "--"
18652 ["Cycle TODO" org-agenda-todo t]
18653 ["Archive subtree" org-agenda-archive t]
18654 ["Delete subtree" org-agenda-kill t]
18655 "--"
18656 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
18657 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
18658 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
18659 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
18660 "--"
18661 ("Tags and Properties"
18662 ["Show all Tags" org-agenda-show-tags t]
18663 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
18664 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
18665 "--"
18666 ["Column View" org-columns t])
18667 ("Date/Schedule"
18668 ["Schedule" org-agenda-schedule t]
18669 ["Set Deadline" org-agenda-deadline t]
18670 "--"
18671 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
18672 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
18673 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
18674 ("Clock"
18675 ["Clock in" org-agenda-clock-in t]
18676 ["Clock out" org-agenda-clock-out t]
18677 ["Clock cancel" org-agenda-clock-cancel t]
18678 ["Goto running clock" org-clock-goto t])
18679 ("Priority"
18680 ["Set Priority" org-agenda-priority t]
18681 ["Increase Priority" org-agenda-priority-up t]
18682 ["Decrease Priority" org-agenda-priority-down t]
18683 ["Show Priority" org-agenda-show-priority t])
18684 ("Calendar/Diary"
18685 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
18686 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
18687 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
18688 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
18689 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
18690 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
18691 "--"
18692 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
18693 "--"
18694 ("View"
18695 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
18696 :style radio :selected (equal org-agenda-ndays 1)]
18697 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
18698 :style radio :selected (equal org-agenda-ndays 7)]
18699 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
18700 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
18701 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
18702 :style radio :selected (member org-agenda-ndays '(365 366))]
18703 "--"
18704 ["Show Logbook entries" org-agenda-log-mode
18705 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
18706 ["Include Diary" org-agenda-toggle-diary
18707 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
18708 ["Use Time Grid" org-agenda-toggle-time-grid
18709 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
18710 ["Write view to file" org-write-agenda t]
18711 ["Rebuild buffer" org-agenda-redo t]
18712 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
18713 "--"
18714 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
18715 "--"
18716 ["Quit" org-agenda-quit t]
18717 ["Exit and Release Buffers" org-agenda-exit t]
18720 ;;; Agenda undo
18722 (defvar org-agenda-allow-remote-undo t
18723 "Non-nil means, allow remote undo from the agenda buffer.")
18724 (defvar org-agenda-undo-list nil
18725 "List of undoable operations in the agenda since last refresh.")
18726 (defvar org-agenda-undo-has-started-in nil
18727 "Buffers that have already seen `undo-start' in the current undo sequence.")
18728 (defvar org-agenda-pending-undo-list nil
18729 "In a series of undo commands, this is the list of remaning undo items.")
18731 (defmacro org-if-unprotected (&rest body)
18732 "Execute BODY if there is no `org-protected' text property at point."
18733 (declare (debug t))
18734 `(unless (get-text-property (point) 'org-protected)
18735 ,@body))
18737 (defmacro org-with-remote-undo (_buffer &rest _body)
18738 "Execute BODY while recording undo information in two buffers."
18739 (declare (indent 1) (debug t))
18740 `(let ((_cline (org-current-line))
18741 (_cmd this-command)
18742 (_buf1 (current-buffer))
18743 (_buf2 ,_buffer)
18744 (_undo1 buffer-undo-list)
18745 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
18746 _c1 _c2)
18747 ,@_body
18748 (when org-agenda-allow-remote-undo
18749 (setq _c1 (org-verify-change-for-undo
18750 _undo1 (with-current-buffer _buf1 buffer-undo-list))
18751 _c2 (org-verify-change-for-undo
18752 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
18753 (when (or _c1 _c2)
18754 ;; make sure there are undo boundaries
18755 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
18756 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
18757 ;; remember which buffer to undo
18758 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
18759 org-agenda-undo-list)))))
18761 (defun org-agenda-undo ()
18762 "Undo a remote editing step in the agenda.
18763 This undoes changes both in the agenda buffer and in the remote buffer
18764 that have been changed along."
18765 (interactive)
18766 (or org-agenda-allow-remote-undo
18767 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
18768 (if (not (eq this-command last-command))
18769 (setq org-agenda-undo-has-started-in nil
18770 org-agenda-pending-undo-list org-agenda-undo-list))
18771 (if (not org-agenda-pending-undo-list)
18772 (error "No further undo information"))
18773 (let* ((entry (pop org-agenda-pending-undo-list))
18774 buf line cmd rembuf)
18775 (setq cmd (pop entry) line (pop entry))
18776 (setq rembuf (nth 2 entry))
18777 (org-with-remote-undo rembuf
18778 (while (bufferp (setq buf (pop entry)))
18779 (if (pop entry)
18780 (with-current-buffer buf
18781 (let ((last-undo-buffer buf)
18782 (inhibit-read-only t))
18783 (unless (memq buf org-agenda-undo-has-started-in)
18784 (push buf org-agenda-undo-has-started-in)
18785 (make-local-variable 'pending-undo-list)
18786 (undo-start))
18787 (while (and pending-undo-list
18788 (listp pending-undo-list)
18789 (not (car pending-undo-list)))
18790 (pop pending-undo-list))
18791 (undo-more 1))))))
18792 (goto-line line)
18793 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
18795 (defun org-verify-change-for-undo (l1 l2)
18796 "Verify that a real change occurred between the undo lists L1 and L2."
18797 (while (and l1 (listp l1) (null (car l1))) (pop l1))
18798 (while (and l2 (listp l2) (null (car l2))) (pop l2))
18799 (not (eq l1 l2)))
18801 ;;; Agenda dispatch
18803 (defvar org-agenda-restrict nil)
18804 (defvar org-agenda-restrict-begin (make-marker))
18805 (defvar org-agenda-restrict-end (make-marker))
18806 (defvar org-agenda-last-dispatch-buffer nil)
18807 (defvar org-agenda-overriding-restriction nil)
18809 ;;;###autoload
18810 (defun org-agenda (arg &optional keys restriction)
18811 "Dispatch agenda commands to collect entries to the agenda buffer.
18812 Prompts for a command to execute. Any prefix arg will be passed
18813 on to the selected command. The default selections are:
18815 a Call `org-agenda-list' to display the agenda for current day or week.
18816 t Call `org-todo-list' to display the global todo list.
18817 T Call `org-todo-list' to display the global todo list, select only
18818 entries with a specific TODO keyword (the user gets a prompt).
18819 m Call `org-tags-view' to display headlines with tags matching
18820 a condition (the user is prompted for the condition).
18821 M Like `m', but select only TODO entries, no ordinary headlines.
18822 L Create a timeline for the current buffer.
18823 e Export views to associated files.
18825 More commands can be added by configuring the variable
18826 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
18827 searches can be pre-defined in this way.
18829 If the current buffer is in Org-mode and visiting a file, you can also
18830 first press `<' once to indicate that the agenda should be temporarily
18831 \(until the next use of \\[org-agenda]) restricted to the current file.
18832 Pressing `<' twice means to restrict to the current subtree or region
18833 \(if active)."
18834 (interactive "P")
18835 (catch 'exit
18836 (let* ((prefix-descriptions nil)
18837 (org-agenda-custom-commands
18838 ;; normalize different versions
18839 (delq nil
18840 (mapcar
18841 (lambda (x)
18842 (cond ((stringp (cdr x))
18843 (push x prefix-descriptions)
18844 nil)
18845 ((stringp (nth 1 x)) x)
18846 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
18847 (t (cons (car x) (cons "" (cdr x))))))
18848 org-agenda-custom-commands)))
18849 (buf (current-buffer))
18850 (bfn (buffer-file-name (buffer-base-buffer)))
18851 entry key type match lprops ans)
18852 ;; Turn off restriction unless there is an overriding one
18853 (unless org-agenda-overriding-restriction
18854 (put 'org-agenda-files 'org-restrict nil)
18855 (setq org-agenda-restrict nil)
18856 (move-marker org-agenda-restrict-begin nil)
18857 (move-marker org-agenda-restrict-end nil))
18858 ;; Delete old local properties
18859 (put 'org-agenda-redo-command 'org-lprops nil)
18860 ;; Remember where this call originated
18861 (setq org-agenda-last-dispatch-buffer (current-buffer))
18862 (unless keys
18863 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
18864 keys (car ans)
18865 restriction (cdr ans)))
18866 ;; Estabish the restriction, if any
18867 (when (and (not org-agenda-overriding-restriction) restriction)
18868 (put 'org-agenda-files 'org-restrict (list bfn))
18869 (cond
18870 ((eq restriction 'region)
18871 (setq org-agenda-restrict t)
18872 (move-marker org-agenda-restrict-begin (region-beginning))
18873 (move-marker org-agenda-restrict-end (region-end)))
18874 ((eq restriction 'subtree)
18875 (save-excursion
18876 (setq org-agenda-restrict t)
18877 (org-back-to-heading t)
18878 (move-marker org-agenda-restrict-begin (point))
18879 (move-marker org-agenda-restrict-end
18880 (progn (org-end-of-subtree t)))))))
18882 (require 'calendar) ; FIXME: can we avoid this for some commands?
18883 ;; For example the todo list should not need it (but does...)
18884 (cond
18885 ((setq entry (assoc keys org-agenda-custom-commands))
18886 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
18887 (progn
18888 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
18889 (put 'org-agenda-redo-command 'org-lprops lprops)
18890 (cond
18891 ((eq type 'agenda)
18892 (org-let lprops '(org-agenda-list current-prefix-arg)))
18893 ((eq type 'alltodo)
18894 (org-let lprops '(org-todo-list current-prefix-arg)))
18895 ((eq type 'stuck)
18896 (org-let lprops '(org-agenda-list-stuck-projects
18897 current-prefix-arg)))
18898 ((eq type 'tags)
18899 (org-let lprops '(org-tags-view current-prefix-arg match)))
18900 ((eq type 'tags-todo)
18901 (org-let lprops '(org-tags-view '(4) match)))
18902 ((eq type 'todo)
18903 (org-let lprops '(org-todo-list match)))
18904 ((eq type 'tags-tree)
18905 (org-check-for-org-mode)
18906 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
18907 ((eq type 'todo-tree)
18908 (org-check-for-org-mode)
18909 (org-let lprops
18910 '(org-occur (concat "^" outline-regexp "[ \t]*"
18911 (regexp-quote match) "\\>"))))
18912 ((eq type 'occur-tree)
18913 (org-check-for-org-mode)
18914 (org-let lprops '(org-occur match)))
18915 ((functionp type)
18916 (org-let lprops '(funcall type match)))
18917 ((fboundp type)
18918 (org-let lprops '(funcall type match)))
18919 (t (error "Invalid custom agenda command type %s" type))))
18920 (org-run-agenda-series (nth 1 entry) (cddr entry))))
18921 ((equal keys "C") (customize-variable 'org-agenda-custom-commands))
18922 ((equal keys "a") (call-interactively 'org-agenda-list))
18923 ((equal keys "t") (call-interactively 'org-todo-list))
18924 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
18925 ((equal keys "m") (call-interactively 'org-tags-view))
18926 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
18927 ((equal keys "e") (call-interactively 'org-store-agenda-views))
18928 ((equal keys "L")
18929 (unless (org-mode-p)
18930 (error "This is not an Org-mode file"))
18931 (unless restriction
18932 (put 'org-agenda-files 'org-restrict (list bfn))
18933 (org-call-with-arg 'org-timeline arg)))
18934 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
18935 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
18936 ((equal keys "!") (customize-variable 'org-stuck-projects))
18937 (t (error "Invalid agenda key"))))))
18939 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
18940 "The user interface for selecting an agenda command."
18941 (catch 'exit
18942 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
18943 (restrict-ok (and bfn (org-mode-p)))
18944 (region-p (org-region-active-p))
18945 (custom org-agenda-custom-commands)
18946 (selstring "")
18947 restriction second-time
18948 c entry key type match prefixes rmheader header-end custom1 desc)
18949 (save-window-excursion
18950 (delete-other-windows)
18951 (org-switch-to-buffer-other-window " *Agenda Commands*")
18952 (erase-buffer)
18953 (insert (eval-when-compile
18954 (let ((header
18956 Press key for an agenda command: < Buffer,subtree/region restriction
18957 -------------------------------- > Remove restriction
18958 a Agenda for current week or day e Export agenda views
18959 t List of all TODO entries T Entries with special TODO kwd
18960 m Match a TAGS query M Like m, but only TODO entries
18961 L Timeline for current buffer # List stuck projects (!=configure)
18962 / Multi-occur C Configure custom agenda commands
18964 (start 0))
18965 (while (string-match
18966 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
18967 header start)
18968 (setq start (match-end 0))
18969 (add-text-properties (match-beginning 2) (match-end 2)
18970 '(face bold) header))
18971 header)))
18972 (setq header-end (move-marker (make-marker) (point)))
18973 (while t
18974 (setq custom1 custom)
18975 (when (eq rmheader t)
18976 (goto-line 1)
18977 (re-search-forward ":" nil t)
18978 (delete-region (match-end 0) (point-at-eol))
18979 (forward-char 1)
18980 (looking-at "-+")
18981 (delete-region (match-end 0) (point-at-eol))
18982 (move-marker header-end (match-end 0)))
18983 (goto-char header-end)
18984 (delete-region (point) (point-max))
18985 (while (setq entry (pop custom1))
18986 (setq key (car entry) desc (nth 1 entry)
18987 type (nth 2 entry) match (nth 3 entry))
18988 (if (> (length key) 1)
18989 (add-to-list 'prefixes (string-to-char key))
18990 (insert
18991 (format
18992 "\n%-4s%-14s: %s"
18993 (org-add-props (copy-sequence key)
18994 '(face bold))
18995 (cond
18996 ((string-match "\\S-" desc) desc)
18997 ((eq type 'agenda) "Agenda for current week or day")
18998 ((eq type 'alltodo) "List of all TODO entries")
18999 ((eq type 'stuck) "List of stuck projects")
19000 ((eq type 'todo) "TODO keyword")
19001 ((eq type 'tags) "Tags query")
19002 ((eq type 'tags-todo) "Tags (TODO)")
19003 ((eq type 'tags-tree) "Tags tree")
19004 ((eq type 'todo-tree) "TODO kwd tree")
19005 ((eq type 'occur-tree) "Occur tree")
19006 ((functionp type) (if (symbolp type)
19007 (symbol-name type)
19008 "Lambda expression"))
19009 (t "???"))
19010 (cond
19011 ((stringp match)
19012 (org-add-props match nil 'face 'org-warning))
19013 (match
19014 (format "set of %d commands" (length match)))
19015 (t ""))))))
19016 (when prefixes
19017 (mapc (lambda (x)
19018 (insert
19019 (format "\n%s %s"
19020 (org-add-props (char-to-string x)
19021 nil 'face 'bold)
19022 (or (cdr (assoc (concat selstring (char-to-string x))
19023 prefix-descriptions))
19024 "Prefix key"))))
19025 prefixes))
19026 (goto-char (point-min))
19027 (when (fboundp 'fit-window-to-buffer)
19028 (if second-time
19029 (if (not (pos-visible-in-window-p (point-max)))
19030 (fit-window-to-buffer))
19031 (setq second-time t)
19032 (fit-window-to-buffer)))
19033 (message "Press key for agenda command%s:"
19034 (if (or restrict-ok org-agenda-overriding-restriction)
19035 (if org-agenda-overriding-restriction
19036 " (restriction lock active)"
19037 (if restriction
19038 (format " (restricted to %s)" restriction)
19039 " (unrestricted)"))
19040 ""))
19041 (setq c (read-char-exclusive))
19042 (message "")
19043 (cond
19044 ((assoc (char-to-string c) custom)
19045 (setq selstring (concat selstring (char-to-string c)))
19046 (throw 'exit (cons selstring restriction)))
19047 ((memq c prefixes)
19048 (setq selstring (concat selstring (char-to-string c))
19049 prefixes nil
19050 rmheader (or rmheader t)
19051 custom (delq nil (mapcar
19052 (lambda (x)
19053 (if (or (= (length (car x)) 1)
19054 (/= (string-to-char (car x)) c))
19056 (cons (substring (car x) 1) (cdr x))))
19057 custom))))
19058 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
19059 (message "Restriction is only possible in Org-mode buffers")
19060 (ding) (sit-for 1))
19061 ((eq c ?1)
19062 (org-agenda-remove-restriction-lock 'noupdate)
19063 (setq restriction 'buffer))
19064 ((eq c ?0)
19065 (org-agenda-remove-restriction-lock 'noupdate)
19066 (setq restriction (if region-p 'region 'subtree)))
19067 ((eq c ?<)
19068 (org-agenda-remove-restriction-lock 'noupdate)
19069 (setq restriction
19070 (cond
19071 ((eq restriction 'buffer)
19072 (if region-p 'region 'subtree))
19073 ((memq restriction '(subtree region))
19074 nil)
19075 (t 'buffer))))
19076 ((eq c ?>)
19077 (org-agenda-remove-restriction-lock 'noupdate)
19078 (setq restriction nil))
19079 ((and (equal selstring "") (memq c '(?a ?t ?m ?L ?C ?e ?T ?M ?# ?/)))
19080 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
19081 ((equal c ?q) (error "Abort"))
19082 (t (error "Invalid key %c" c))))))))
19084 (defun org-run-agenda-series (name series)
19085 (org-prepare-agenda name)
19086 (let* ((org-agenda-multi t)
19087 (redo (list 'org-run-agenda-series name (list 'quote series)))
19088 (cmds (car series))
19089 (gprops (nth 1 series))
19090 match ;; The byte compiler incorrectly complains about this. Keep it!
19091 cmd type lprops)
19092 (while (setq cmd (pop cmds))
19093 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
19094 (cond
19095 ((eq type 'agenda)
19096 (org-let2 gprops lprops
19097 '(call-interactively 'org-agenda-list)))
19098 ((eq type 'alltodo)
19099 (org-let2 gprops lprops
19100 '(call-interactively 'org-todo-list)))
19101 ((eq type 'stuck)
19102 (org-let2 gprops lprops
19103 '(call-interactively 'org-agenda-list-stuck-projects)))
19104 ((eq type 'tags)
19105 (org-let2 gprops lprops
19106 '(org-tags-view current-prefix-arg match)))
19107 ((eq type 'tags-todo)
19108 (org-let2 gprops lprops
19109 '(org-tags-view '(4) match)))
19110 ((eq type 'todo)
19111 (org-let2 gprops lprops
19112 '(org-todo-list match)))
19113 ((fboundp type)
19114 (org-let2 gprops lprops
19115 '(funcall type match)))
19116 (t (error "Invalid type in command series"))))
19117 (widen)
19118 (setq org-agenda-redo-command redo)
19119 (goto-char (point-min)))
19120 (org-finalize-agenda))
19122 ;;;###autoload
19123 (defmacro org-batch-agenda (cmd-key &rest parameters)
19124 "Run an agenda command in batch mode and send the result to STDOUT.
19125 If CMD-KEY is a string of length 1, it is used as a key in
19126 `org-agenda-custom-commands' and triggers this command. If it is a
19127 longer string is is used as a tags/todo match string.
19128 Paramters are alternating variable names and values that will be bound
19129 before running the agenda command."
19130 (let (pars)
19131 (while parameters
19132 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19133 (if (> (length cmd-key) 2)
19134 (eval (list 'let (nreverse pars)
19135 (list 'org-tags-view nil cmd-key)))
19136 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19137 (set-buffer org-agenda-buffer-name)
19138 (princ (org-encode-for-stdout (buffer-string)))))
19140 (defun org-encode-for-stdout (string)
19141 (if (fboundp 'encode-coding-string)
19142 (encode-coding-string string buffer-file-coding-system)
19143 string))
19145 (defvar org-agenda-info nil)
19147 ;;;###autoload
19148 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
19149 "Run an agenda command in batch mode and send the result to STDOUT.
19150 If CMD-KEY is a string of length 1, it is used as a key in
19151 `org-agenda-custom-commands' and triggers this command. If it is a
19152 longer string is is used as a tags/todo match string.
19153 Paramters are alternating variable names and values that will be bound
19154 before running the agenda command.
19156 The output gives a line for each selected agenda item. Each
19157 item is a list of comma-separated values, like this:
19159 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
19161 category The category of the item
19162 head The headline, without TODO kwd, TAGS and PRIORITY
19163 type The type of the agenda entry, can be
19164 todo selected in TODO match
19165 tagsmatch selected in tags match
19166 diary imported from diary
19167 deadline a deadline on given date
19168 scheduled scheduled on given date
19169 timestamp entry has timestamp on given date
19170 closed entry was closed on given date
19171 upcoming-deadline warning about deadline
19172 past-scheduled forwarded scheduled item
19173 block entry has date block including g. date
19174 todo The todo keyword, if any
19175 tags All tags including inherited ones, separated by colons
19176 date The relevant date, like 2007-2-14
19177 time The time, like 15:00-16:50
19178 extra Sting with extra planning info
19179 priority-l The priority letter if any was given
19180 priority-n The computed numerical priority
19181 agenda-day The day in the agenda where this is listed"
19183 (let (pars)
19184 (while parameters
19185 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19186 (push (list 'org-agenda-remove-tags t) pars)
19187 (if (> (length cmd-key) 2)
19188 (eval (list 'let (nreverse pars)
19189 (list 'org-tags-view nil cmd-key)))
19190 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19191 (set-buffer org-agenda-buffer-name)
19192 (let* ((lines (org-split-string (buffer-string) "\n"))
19193 line)
19194 (while (setq line (pop lines))
19195 (catch 'next
19196 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
19197 (setq org-agenda-info
19198 (org-fix-agenda-info (text-properties-at 0 line)))
19199 (princ
19200 (org-encode-for-stdout
19201 (mapconcat 'org-agenda-export-csv-mapper
19202 '(org-category txt type todo tags date time-of-day extra
19203 priority-letter priority agenda-day)
19204 ",")))
19205 (princ "\n"))))))
19207 (defun org-fix-agenda-info (props)
19208 "Make sure all properties on an agenda item have a canonical form,
19209 so the the export commands caneasily use it."
19210 (let (tmp re)
19211 (when (setq tmp (plist-get props 'tags))
19212 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
19213 (when (setq tmp (plist-get props 'date))
19214 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19215 (let ((calendar-date-display-form '(year "-" month "-" day)))
19216 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
19218 (setq tmp (calendar-date-string tmp)))
19219 (setq props (plist-put props 'date tmp)))
19220 (when (setq tmp (plist-get props 'day))
19221 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19222 (let ((calendar-date-display-form '(year "-" month "-" day)))
19223 (setq tmp (calendar-date-string tmp)))
19224 (setq props (plist-put props 'day tmp))
19225 (setq props (plist-put props 'agenda-day tmp)))
19226 (when (setq tmp (plist-get props 'txt))
19227 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
19228 (plist-put props 'priority-letter (match-string 1 tmp))
19229 (setq tmp (replace-match "" t t tmp)))
19230 (when (and (setq re (plist-get props 'org-todo-regexp))
19231 (setq re (concat "\\`\\.*" re " ?"))
19232 (string-match re tmp))
19233 (plist-put props 'todo (match-string 1 tmp))
19234 (setq tmp (replace-match "" t t tmp)))
19235 (plist-put props 'txt tmp)))
19236 props)
19238 (defun org-agenda-export-csv-mapper (prop)
19239 (let ((res (plist-get org-agenda-info prop)))
19240 (setq res
19241 (cond
19242 ((not res) "")
19243 ((stringp res) res)
19244 (t (prin1-to-string res))))
19245 (while (string-match "," res)
19246 (setq res (replace-match ";" t t res)))
19247 (org-trim res)))
19250 ;;;###autoload
19251 (defun org-store-agenda-views (&rest parameters)
19252 (interactive)
19253 (eval (list 'org-batch-store-agenda-views)))
19255 ;; FIXME, why is this a macro?????
19256 ;;;###autoload
19257 (defmacro org-batch-store-agenda-views (&rest parameters)
19258 "Run all custom agenda commands that have a file argument."
19259 (let ((cmds org-agenda-custom-commands)
19260 (pop-up-frames nil)
19261 (dir default-directory)
19262 pars cmd thiscmdkey files opts)
19263 (while parameters
19264 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19265 (setq pars (reverse pars))
19266 (save-window-excursion
19267 (while cmds
19268 (setq cmd (pop cmds)
19269 thiscmdkey (car cmd)
19270 opts (nth 3 cmd)
19271 files (nth 4 cmd))
19272 (if (stringp files) (setq files (list files)))
19273 (when files
19274 (eval (list 'let (append org-agenda-exporter-settings opts pars)
19275 (list 'org-agenda nil thiscmdkey)))
19276 (set-buffer org-agenda-buffer-name)
19277 (while files
19278 (eval (list 'let (append org-agenda-exporter-settings opts pars)
19279 (list 'org-write-agenda
19280 (expand-file-name (pop files) dir) t))))
19281 (and (get-buffer org-agenda-buffer-name)
19282 (kill-buffer org-agenda-buffer-name)))))))
19284 (defun org-write-agenda (file &optional nosettings)
19285 "Write the current buffer (an agenda view) as a file.
19286 Depending on the extension of the file name, plain text (.txt),
19287 HTML (.html or .htm) or Postscript (.ps) is produced.
19288 If NOSETTINGS is given, do not scope the settings of
19289 `org-agenda-exporter-settings' into the export commands. This is used when
19290 the settings have already been scoped and we do not wish to overrule other,
19291 higher priority settings."
19292 (interactive "FWrite agenda to file: ")
19293 (if (not (file-writable-p file))
19294 (error "Cannot write agenda to file %s" file))
19295 (cond
19296 ((string-match "\\.html?\\'" file) (require 'htmlize))
19297 ((string-match "\\.ps\\'" file) (require 'ps-print)))
19298 (org-let (if nosettings nil org-agenda-exporter-settings)
19299 '(save-excursion
19300 (save-window-excursion
19301 (cond
19302 ((string-match "\\.html?\\'" file)
19303 (set-buffer (htmlize-buffer (current-buffer)))
19305 (when (and org-agenda-export-html-style
19306 (string-match "<style>" org-agenda-export-html-style))
19307 ;; replace <style> section with org-agenda-export-html-style
19308 (goto-char (point-min))
19309 (kill-region (- (search-forward "<style") 6)
19310 (search-forward "</style>"))
19311 (insert org-agenda-export-html-style))
19312 (write-file file)
19313 (kill-buffer (current-buffer))
19314 (message "HTML written to %s" file))
19315 ((string-match "\\.ps\\'" file)
19316 (ps-print-buffer-with-faces file)
19317 (message "Postscript written to %s" file))
19319 (let ((bs (buffer-string)))
19320 (find-file file)
19321 (insert bs)
19322 (save-buffer 0)
19323 (kill-buffer (current-buffer))
19324 (message "Plain text written to %s" file))))))
19325 (set-buffer org-agenda-buffer-name)))
19327 (defmacro org-no-read-only (&rest body)
19328 "Inhibit read-only for BODY."
19329 `(let ((inhibit-read-only t)) ,@body))
19331 (defun org-check-for-org-mode ()
19332 "Make sure current buffer is in org-mode. Error if not."
19333 (or (org-mode-p)
19334 (error "Cannot execute org-mode agenda command on buffer in %s."
19335 major-mode)))
19337 (defun org-fit-agenda-window ()
19338 "Fit the window to the buffer size."
19339 (and (memq org-agenda-window-setup '(reorganize-frame))
19340 (fboundp 'fit-window-to-buffer)
19341 (fit-window-to-buffer
19343 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
19344 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
19346 ;;; Agenda file list
19348 (defun org-agenda-files (&optional unrestricted)
19349 "Get the list of agenda files.
19350 Optional UNRESTRICTED means return the full list even if a restriction
19351 is currently in place."
19352 (let ((files
19353 (cond
19354 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
19355 ((stringp org-agenda-files) (org-read-agenda-file-list))
19356 ((listp org-agenda-files) org-agenda-files)
19357 (t (error "Invalid value of `org-agenda-files'")))))
19358 (setq files (apply 'append
19359 (mapcar (lambda (f)
19360 (if (file-directory-p f)
19361 (directory-files f t "\\.org\\'")
19362 (list f)))
19363 files)))
19364 (if org-agenda-skip-unavailable-files
19365 (delq nil
19366 (mapcar (function
19367 (lambda (file)
19368 (and (file-readable-p file) file)))
19369 files))
19370 files))) ; `org-check-agenda-file' will remove them from the list
19372 (defun org-edit-agenda-file-list ()
19373 "Edit the list of agenda files.
19374 Depending on setup, this either uses customize to edit the variable
19375 `org-agenda-files', or it visits the file that is holding the list. In the
19376 latter case, the buffer is set up in a way that saving it automatically kills
19377 the buffer and restores the previous window configuration."
19378 (interactive)
19379 (if (stringp org-agenda-files)
19380 (let ((cw (current-window-configuration)))
19381 (find-file org-agenda-files)
19382 (org-set-local 'org-window-configuration cw)
19383 (org-add-hook 'after-save-hook
19384 (lambda ()
19385 (set-window-configuration
19386 (prog1 org-window-configuration
19387 (kill-buffer (current-buffer))))
19388 (org-install-agenda-files-menu)
19389 (message "New agenda file list installed"))
19390 nil 'local)
19391 (message (substitute-command-keys
19392 "Edit list and finish with \\[save-buffer]")))
19393 (customize-variable 'org-agenda-files)))
19395 (defun org-store-new-agenda-file-list (list)
19396 "Set new value for the agenda file list and save it correcly."
19397 (if (stringp org-agenda-files)
19398 (let ((f org-agenda-files) b)
19399 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
19400 (with-temp-file f
19401 (insert (mapconcat 'identity list "\n") "\n")))
19402 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
19403 (setq org-agenda-files list)
19404 (customize-save-variable 'org-agenda-files org-agenda-files))))
19406 (defun org-read-agenda-file-list ()
19407 "Read the list of agenda files from a file."
19408 (when (stringp org-agenda-files)
19409 (with-temp-buffer
19410 (insert-file-contents org-agenda-files)
19411 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
19414 ;;;###autoload
19415 (defun org-cycle-agenda-files ()
19416 "Cycle through the files in `org-agenda-files'.
19417 If the current buffer visits an agenda file, find the next one in the list.
19418 If the current buffer does not, find the first agenda file."
19419 (interactive)
19420 (let* ((fs (org-agenda-files t))
19421 (files (append fs (list (car fs))))
19422 (tcf (if buffer-file-name (file-truename buffer-file-name)))
19423 file)
19424 (unless files (error "No agenda files"))
19425 (catch 'exit
19426 (while (setq file (pop files))
19427 (if (equal (file-truename file) tcf)
19428 (when (car files)
19429 (find-file (car files))
19430 (throw 'exit t))))
19431 (find-file (car fs)))
19432 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
19434 (defun org-agenda-file-to-front (&optional to-end)
19435 "Move/add the current file to the top of the agenda file list.
19436 If the file is not present in the list, it is added to the front. If it is
19437 present, it is moved there. With optional argument TO-END, add/move to the
19438 end of the list."
19439 (interactive "P")
19440 (let ((org-agenda-skip-unavailable-files nil)
19441 (file-alist (mapcar (lambda (x)
19442 (cons (file-truename x) x))
19443 (org-agenda-files t)))
19444 (ctf (file-truename buffer-file-name))
19445 x had)
19446 (setq x (assoc ctf file-alist) had x)
19448 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
19449 (if to-end
19450 (setq file-alist (append (delq x file-alist) (list x)))
19451 (setq file-alist (cons x (delq x file-alist))))
19452 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
19453 (org-install-agenda-files-menu)
19454 (message "File %s to %s of agenda file list"
19455 (if had "moved" "added") (if to-end "end" "front"))))
19457 (defun org-remove-file (&optional file)
19458 "Remove current file from the list of files in variable `org-agenda-files'.
19459 These are the files which are being checked for agenda entries.
19460 Optional argument FILE means, use this file instead of the current."
19461 (interactive)
19462 (let* ((org-agenda-skip-unavailable-files nil)
19463 (file (or file buffer-file-name))
19464 (true-file (file-truename file))
19465 (afile (abbreviate-file-name file))
19466 (files (delq nil (mapcar
19467 (lambda (x)
19468 (if (equal true-file
19469 (file-truename x))
19470 nil x))
19471 (org-agenda-files t)))))
19472 (if (not (= (length files) (length (org-agenda-files t))))
19473 (progn
19474 (org-store-new-agenda-file-list files)
19475 (org-install-agenda-files-menu)
19476 (message "Removed file: %s" afile))
19477 (message "File was not in list: %s" afile))))
19479 (defun org-file-menu-entry (file)
19480 (vector file (list 'find-file file) t))
19482 (defun org-check-agenda-file (file)
19483 "Make sure FILE exists. If not, ask user what to do."
19484 (when (not (file-exists-p file))
19485 (message "non-existent file %s. [R]emove from list or [A]bort?"
19486 (abbreviate-file-name file))
19487 (let ((r (downcase (read-char-exclusive))))
19488 (cond
19489 ((equal r ?r)
19490 (org-remove-file file)
19491 (throw 'nextfile t))
19492 (t (error "Abort"))))))
19494 ;;; Agenda prepare and finalize
19496 (defvar org-agenda-multi nil) ; dynammically scoped
19497 (defvar org-agenda-buffer-name "*Org Agenda*")
19498 (defvar org-pre-agenda-window-conf nil)
19499 (defvar org-agenda-name nil)
19500 (defun org-prepare-agenda (&optional name)
19501 (setq org-todo-keywords-for-agenda nil)
19502 (setq org-done-keywords-for-agenda nil)
19503 (if org-agenda-multi
19504 (progn
19505 (setq buffer-read-only nil)
19506 (goto-char (point-max))
19507 (unless (or (bobp) org-agenda-compact-blocks)
19508 (insert "\n" (make-string (window-width) ?=) "\n"))
19509 (narrow-to-region (point) (point-max)))
19510 (org-agenda-maybe-reset-markers 'force)
19511 (org-prepare-agenda-buffers (org-agenda-files))
19512 (setq org-todo-keywords-for-agenda
19513 (org-uniquify org-todo-keywords-for-agenda))
19514 (setq org-done-keywords-for-agenda
19515 (org-uniquify org-done-keywords-for-agenda))
19516 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
19517 (awin (get-buffer-window abuf)))
19518 (cond
19519 ((equal (current-buffer) abuf) nil)
19520 (awin (select-window awin))
19521 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
19522 ((equal org-agenda-window-setup 'current-window)
19523 (switch-to-buffer abuf))
19524 ((equal org-agenda-window-setup 'other-window)
19525 (org-switch-to-buffer-other-window abuf))
19526 ((equal org-agenda-window-setup 'other-frame)
19527 (switch-to-buffer-other-frame abuf))
19528 ((equal org-agenda-window-setup 'reorganize-frame)
19529 (delete-other-windows)
19530 (org-switch-to-buffer-other-window abuf))))
19531 (setq buffer-read-only nil)
19532 (erase-buffer)
19533 (org-agenda-mode)
19534 (and name (not org-agenda-name)
19535 (org-set-local 'org-agenda-name name)))
19536 (setq buffer-read-only nil))
19538 (defun org-finalize-agenda ()
19539 "Finishing touch for the agenda buffer, called just before displaying it."
19540 (unless org-agenda-multi
19541 (save-excursion
19542 (let ((inhibit-read-only t))
19543 (goto-char (point-min))
19544 (while (org-activate-bracket-links (point-max))
19545 (add-text-properties (match-beginning 0) (match-end 0)
19546 '(face org-link)))
19547 (org-agenda-align-tags)
19548 (unless org-agenda-with-colors
19549 (remove-text-properties (point-min) (point-max) '(face nil))))
19550 (if (and (boundp 'org-overriding-columns-format)
19551 org-overriding-columns-format)
19552 (org-set-local 'org-overriding-columns-format
19553 org-overriding-columns-format))
19554 (if (and (boundp 'org-agenda-view-columns-initially)
19555 org-agenda-view-columns-initially)
19556 (org-agenda-columns))
19557 (when org-agenda-fontify-priorities
19558 (org-fontify-priorities))
19559 (run-hooks 'org-finalize-agenda-hook))))
19561 (defun org-fontify-priorities ()
19562 "Make highest priority lines bold, and lowest italic."
19563 (interactive)
19564 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
19565 (org-delete-overlay o)))
19566 (org-overlays-in (point-min) (point-max)))
19567 (save-excursion
19568 (let ((inhibit-read-only t)
19569 b e p ov h l)
19570 (goto-char (point-min))
19571 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
19572 (setq h (or (get-char-property (point) 'org-highest-priority)
19573 org-highest-priority)
19574 l (or (get-char-property (point) 'org-lowest-priority)
19575 org-lowest-priority)
19576 p (string-to-char (match-string 1))
19577 b (match-beginning 0) e (point-at-eol)
19578 ov (org-make-overlay b e))
19579 (org-overlay-put
19580 ov 'face
19581 (cond ((listp org-agenda-fontify-priorities)
19582 (cdr (assoc p org-agenda-fontify-priorities)))
19583 ((equal p l) 'italic)
19584 ((equal p h) 'bold)))
19585 (org-overlay-put ov 'org-type 'org-priority)))))
19587 (defun org-prepare-agenda-buffers (files)
19588 "Create buffers for all agenda files, protect archived trees and comments."
19589 (interactive)
19590 (let ((pa '(:org-archived t))
19591 (pc '(:org-comment t))
19592 (pall '(:org-archived t :org-comment t))
19593 (inhibit-read-only t)
19594 (rea (concat ":" org-archive-tag ":"))
19595 bmp file re)
19596 (save-excursion
19597 (save-restriction
19598 (while (setq file (pop files))
19599 (if (bufferp file)
19600 (set-buffer file)
19601 (org-check-agenda-file file)
19602 (set-buffer (org-get-agenda-file-buffer file)))
19603 (widen)
19604 (setq bmp (buffer-modified-p))
19605 (org-refresh-category-properties)
19606 (setq org-todo-keywords-for-agenda
19607 (append org-todo-keywords-for-agenda org-todo-keywords-1))
19608 (setq org-done-keywords-for-agenda
19609 (append org-done-keywords-for-agenda org-done-keywords))
19610 (save-excursion
19611 (remove-text-properties (point-min) (point-max) pall)
19612 (when org-agenda-skip-archived-trees
19613 (goto-char (point-min))
19614 (while (re-search-forward rea nil t)
19615 (if (org-on-heading-p t)
19616 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
19617 (goto-char (point-min))
19618 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
19619 (while (re-search-forward re nil t)
19620 (add-text-properties
19621 (match-beginning 0) (org-end-of-subtree t) pc)))
19622 (set-buffer-modified-p bmp))))))
19624 (defvar org-agenda-skip-function nil
19625 "Function to be called at each match during agenda construction.
19626 If this function returns nil, the current match should not be skipped.
19627 Otherwise, the function must return a position from where the search
19628 should be continued.
19629 This may also be a Lisp form, it will be evaluated.
19630 Never set this variable using `setq' or so, because then it will apply
19631 to all future agenda commands. Instead, bind it with `let' to scope
19632 it dynamically into the agenda-constructing command. A good way to set
19633 it is through options in org-agenda-custom-commands.")
19635 (defun org-agenda-skip ()
19636 "Throw to `:skip' in places that should be skipped.
19637 Also moves point to the end of the skipped region, so that search can
19638 continue from there."
19639 (let ((p (point-at-bol)) to fp)
19640 (and org-agenda-skip-archived-trees
19641 (get-text-property p :org-archived)
19642 (org-end-of-subtree t)
19643 (throw :skip t))
19644 (and (get-text-property p :org-comment)
19645 (org-end-of-subtree t)
19646 (throw :skip t))
19647 (if (equal (char-after p) ?#) (throw :skip t))
19648 (when (and (or (setq fp (functionp org-agenda-skip-function))
19649 (consp org-agenda-skip-function))
19650 (setq to (save-excursion
19651 (save-match-data
19652 (if fp
19653 (funcall org-agenda-skip-function)
19654 (eval org-agenda-skip-function))))))
19655 (goto-char to)
19656 (throw :skip t))))
19658 (defvar org-agenda-markers nil
19659 "List of all currently active markers created by `org-agenda'.")
19660 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
19661 "Creation time of the last agenda marker.")
19663 (defun org-agenda-new-marker (&optional pos)
19664 "Return a new agenda marker.
19665 Org-mode keeps a list of these markers and resets them when they are
19666 no longer in use."
19667 (let ((m (copy-marker (or pos (point)))))
19668 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
19669 (push m org-agenda-markers)
19672 (defun org-agenda-maybe-reset-markers (&optional force)
19673 "Reset markers created by `org-agenda'. But only if they are old enough."
19674 (if (or (and force (not org-agenda-multi))
19675 (> (- (time-to-seconds (current-time))
19676 org-agenda-last-marker-time)
19678 (while org-agenda-markers
19679 (move-marker (pop org-agenda-markers) nil))))
19681 (defun org-get-agenda-file-buffer (file)
19682 "Get a buffer visiting FILE. If the buffer needs to be created, add
19683 it to the list of buffers which might be released later."
19684 (let ((buf (org-find-base-buffer-visiting file)))
19685 (if buf
19686 buf ; just return it
19687 ;; Make a new buffer and remember it
19688 (setq buf (find-file-noselect file))
19689 (if buf (push buf org-agenda-new-buffers))
19690 buf)))
19692 (defun org-release-buffers (blist)
19693 "Release all buffers in list, asking the user for confirmation when needed.
19694 When a buffer is unmodified, it is just killed. When modified, it is saved
19695 \(if the user agrees) and then killed."
19696 (let (buf file)
19697 (while (setq buf (pop blist))
19698 (setq file (buffer-file-name buf))
19699 (when (and (buffer-modified-p buf)
19700 file
19701 (y-or-n-p (format "Save file %s? " file)))
19702 (with-current-buffer buf (save-buffer)))
19703 (kill-buffer buf))))
19705 (defun org-get-category (&optional pos)
19706 "Get the category applying to position POS."
19707 (get-text-property (or pos (point)) 'org-category))
19709 ;;; Agenda timeline
19711 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
19713 (defun org-timeline (&optional include-all)
19714 "Show a time-sorted view of the entries in the current org file.
19715 Only entries with a time stamp of today or later will be listed. With
19716 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
19717 under the current date.
19718 If the buffer contains an active region, only check the region for
19719 dates."
19720 (interactive "P")
19721 (require 'calendar)
19722 (org-compile-prefix-format 'timeline)
19723 (org-set-sorting-strategy 'timeline)
19724 (let* ((dopast t)
19725 (dotodo include-all)
19726 (doclosed org-agenda-show-log)
19727 (entry buffer-file-name)
19728 (date (calendar-current-date))
19729 (beg (if (org-region-active-p) (region-beginning) (point-min)))
19730 (end (if (org-region-active-p) (region-end) (point-max)))
19731 (day-numbers (org-get-all-dates beg end 'no-ranges
19732 t doclosed ; always include today
19733 org-timeline-show-empty-dates))
19734 (org-deadline-warning-days 0)
19735 (org-agenda-only-exact-dates t)
19736 (today (time-to-days (current-time)))
19737 (past t)
19738 args
19739 s e rtn d emptyp)
19740 (setq org-agenda-redo-command
19741 (list 'progn
19742 (list 'org-switch-to-buffer-other-window (current-buffer))
19743 (list 'org-timeline (list 'quote include-all))))
19744 (if (not dopast)
19745 ;; Remove past dates from the list of dates.
19746 (setq day-numbers (delq nil (mapcar (lambda(x)
19747 (if (>= x today) x nil))
19748 day-numbers))))
19749 (org-prepare-agenda (concat "Timeline "
19750 (file-name-nondirectory buffer-file-name)))
19751 (if doclosed (push :closed args))
19752 (push :timestamp args)
19753 (push :deadline args)
19754 (push :scheduled args)
19755 (push :sexp args)
19756 (if dotodo (push :todo args))
19757 (while (setq d (pop day-numbers))
19758 (if (and (listp d) (eq (car d) :omitted))
19759 (progn
19760 (setq s (point))
19761 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
19762 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
19763 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
19764 (if (and (>= d today)
19765 dopast
19766 past)
19767 (progn
19768 (setq past nil)
19769 (insert (make-string 79 ?-) "\n")))
19770 (setq date (calendar-gregorian-from-absolute d))
19771 (setq s (point))
19772 (setq rtn (and (not emptyp)
19773 (apply 'org-agenda-get-day-entries entry
19774 date args)))
19775 (if (or rtn (equal d today) org-timeline-show-empty-dates)
19776 (progn
19777 (insert
19778 (if (stringp org-agenda-format-date)
19779 (format-time-string org-agenda-format-date
19780 (org-time-from-absolute date))
19781 (funcall org-agenda-format-date date))
19782 "\n")
19783 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
19784 (put-text-property s (1- (point)) 'org-date-line t)
19785 (if (equal d today)
19786 (put-text-property s (1- (point)) 'org-today t))
19787 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
19788 (put-text-property s (1- (point)) 'day d)))))
19789 (goto-char (point-min))
19790 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
19791 (point-min)))
19792 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
19793 (org-finalize-agenda)
19794 (setq buffer-read-only t)))
19796 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
19797 "Return a list of all relevant day numbers from BEG to END buffer positions.
19798 If NO-RANGES is non-nil, include only the start and end dates of a range,
19799 not every single day in the range. If FORCE-TODAY is non-nil, make
19800 sure that TODAY is included in the list. If INACTIVE is non-nil, also
19801 inactive time stamps (those in square brackets) are included.
19802 When EMPTY is non-nil, also include days without any entries."
19803 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
19804 dates dates1 date day day1 day2 ts1 ts2)
19805 (if force-today
19806 (setq dates (list (time-to-days (current-time)))))
19807 (save-excursion
19808 (goto-char beg)
19809 (while (re-search-forward re end t)
19810 (setq day (time-to-days (org-time-string-to-time
19811 (substring (match-string 1) 0 10))))
19812 (or (memq day dates) (push day dates)))
19813 (unless no-ranges
19814 (goto-char beg)
19815 (while (re-search-forward org-tr-regexp end t)
19816 (setq ts1 (substring (match-string 1) 0 10)
19817 ts2 (substring (match-string 2) 0 10)
19818 day1 (time-to-days (org-time-string-to-time ts1))
19819 day2 (time-to-days (org-time-string-to-time ts2)))
19820 (while (< (setq day1 (1+ day1)) day2)
19821 (or (memq day1 dates) (push day1 dates)))))
19822 (setq dates (sort dates '<))
19823 (when empty
19824 (while (setq day (pop dates))
19825 (setq day2 (car dates))
19826 (push day dates1)
19827 (when (and day2 empty)
19828 (if (or (eq empty t)
19829 (and (numberp empty) (<= (- day2 day) empty)))
19830 (while (< (setq day (1+ day)) day2)
19831 (push (list day) dates1))
19832 (push (cons :omitted (- day2 day)) dates1))))
19833 (setq dates (nreverse dates1)))
19834 dates)))
19836 ;;; Agenda Daily/Weekly
19838 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
19839 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
19840 (defvar org-agenda-last-arguments nil
19841 "The arguments of the previous call to org-agenda")
19842 (defvar org-starting-day nil) ; local variable in the agenda buffer
19843 (defvar org-agenda-span nil) ; local variable in the agenda buffer
19844 (defvar org-include-all-loc nil) ; local variable
19845 (defvar org-agenda-remove-date nil) ; dynamically scoped
19847 ;;;###autoload
19848 (defun org-agenda-list (&optional include-all start-day ndays)
19849 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
19850 The view will be for the current day or week, but from the overview buffer
19851 you will be able to go to other days/weeks.
19853 With one \\[universal-argument] prefix argument INCLUDE-ALL,
19854 all unfinished TODO items will also be shown, before the agenda.
19855 This feature is considered obsolete, please use the TODO list or a block
19856 agenda instead.
19858 With a numeric prefix argument in an interactive call, the agenda will
19859 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
19860 the number of days. NDAYS defaults to `org-agenda-ndays'.
19862 START-DAY defaults to TODAY, or to the most recent match for the weekday
19863 given in `org-agenda-start-on-weekday'."
19864 (interactive "P")
19865 (if (and (integerp include-all) (> include-all 0))
19866 (setq ndays include-all include-all nil))
19867 (setq ndays (or ndays org-agenda-ndays)
19868 start-day (or start-day org-agenda-start-day))
19869 (if org-agenda-overriding-arguments
19870 (setq include-all (car org-agenda-overriding-arguments)
19871 start-day (nth 1 org-agenda-overriding-arguments)
19872 ndays (nth 2 org-agenda-overriding-arguments)))
19873 (if (stringp start-day)
19874 ;; Convert to an absolute day number
19875 (setq start-day (time-to-days (org-read-date nil t start-day))))
19876 (setq org-agenda-last-arguments (list include-all start-day ndays))
19877 (org-compile-prefix-format 'agenda)
19878 (org-set-sorting-strategy 'agenda)
19879 (require 'calendar)
19880 (let* ((org-agenda-start-on-weekday
19881 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
19882 org-agenda-start-on-weekday nil))
19883 (thefiles (org-agenda-files))
19884 (files thefiles)
19885 (today (time-to-days
19886 (time-subtract (current-time)
19887 (list 0 (* 3600 org-extend-today-until) 0))))
19888 (sd (or start-day today))
19889 (start (if (or (null org-agenda-start-on-weekday)
19890 (< org-agenda-ndays 7))
19892 (let* ((nt (calendar-day-of-week
19893 (calendar-gregorian-from-absolute sd)))
19894 (n1 org-agenda-start-on-weekday)
19895 (d (- nt n1)))
19896 (- sd (+ (if (< d 0) 7 0) d)))))
19897 (day-numbers (list start))
19898 (day-cnt 0)
19899 (inhibit-redisplay (not debug-on-error))
19900 s e rtn rtnall file date d start-pos end-pos todayp nd)
19901 (setq org-agenda-redo-command
19902 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
19903 ;; Make the list of days
19904 (setq ndays (or ndays org-agenda-ndays)
19905 nd ndays)
19906 (while (> ndays 1)
19907 (push (1+ (car day-numbers)) day-numbers)
19908 (setq ndays (1- ndays)))
19909 (setq day-numbers (nreverse day-numbers))
19910 (org-prepare-agenda "Day/Week")
19911 (org-set-local 'org-starting-day (car day-numbers))
19912 (org-set-local 'org-include-all-loc include-all)
19913 (org-set-local 'org-agenda-span
19914 (org-agenda-ndays-to-span nd))
19915 (when (and (or include-all org-agenda-include-all-todo)
19916 (member today day-numbers))
19917 (setq files thefiles
19918 rtnall nil)
19919 (while (setq file (pop files))
19920 (catch 'nextfile
19921 (org-check-agenda-file file)
19922 (setq date (calendar-gregorian-from-absolute today)
19923 rtn (org-agenda-get-day-entries
19924 file date :todo))
19925 (setq rtnall (append rtnall rtn))))
19926 (when rtnall
19927 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
19928 (add-text-properties (point-min) (1- (point))
19929 (list 'face 'org-agenda-structure))
19930 (insert (org-finalize-agenda-entries rtnall) "\n")))
19931 (unless org-agenda-compact-blocks
19932 (setq s (point))
19933 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
19934 "-agenda:\n")
19935 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
19936 'org-date-line t)))
19937 (while (setq d (pop day-numbers))
19938 (setq date (calendar-gregorian-from-absolute d)
19939 s (point))
19940 (if (or (setq todayp (= d today))
19941 (and (not start-pos) (= d sd)))
19942 (setq start-pos (point))
19943 (if (and start-pos (not end-pos))
19944 (setq end-pos (point))))
19945 (setq files thefiles
19946 rtnall nil)
19947 (while (setq file (pop files))
19948 (catch 'nextfile
19949 (org-check-agenda-file file)
19950 (if org-agenda-show-log
19951 (setq rtn (org-agenda-get-day-entries
19952 file date
19953 :deadline :scheduled :timestamp :sexp :closed))
19954 (setq rtn (org-agenda-get-day-entries
19955 file date
19956 :deadline :scheduled :sexp :timestamp)))
19957 (setq rtnall (append rtnall rtn))))
19958 (if org-agenda-include-diary
19959 (progn
19960 (require 'diary-lib)
19961 (setq rtn (org-get-entries-from-diary date))
19962 (setq rtnall (append rtnall rtn))))
19963 (if (or rtnall org-agenda-show-all-dates)
19964 (progn
19965 (setq day-cnt (1+ day-cnt))
19966 (insert
19967 (if (stringp org-agenda-format-date)
19968 (format-time-string org-agenda-format-date
19969 (org-time-from-absolute date))
19970 (funcall org-agenda-format-date date))
19971 "\n")
19972 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
19973 (put-text-property s (1- (point)) 'org-date-line t)
19974 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
19975 (if todayp (put-text-property s (1- (point)) 'org-today t))
19976 (if rtnall (insert
19977 (org-finalize-agenda-entries
19978 (org-agenda-add-time-grid-maybe
19979 rtnall nd todayp))
19980 "\n"))
19981 (put-text-property s (1- (point)) 'day d)
19982 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
19983 (goto-char (point-min))
19984 (org-fit-agenda-window)
19985 (unless (and (pos-visible-in-window-p (point-min))
19986 (pos-visible-in-window-p (point-max)))
19987 (goto-char (1- (point-max)))
19988 (recenter -1)
19989 (if (not (pos-visible-in-window-p (or start-pos 1)))
19990 (progn
19991 (goto-char (or start-pos 1))
19992 (recenter 1))))
19993 (goto-char (or start-pos 1))
19994 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
19995 (org-finalize-agenda)
19996 (setq buffer-read-only t)
19997 (message "")))
19999 (defun org-agenda-ndays-to-span (n)
20000 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
20002 ;;; Agenda TODO list
20004 (defvar org-select-this-todo-keyword nil)
20005 (defvar org-last-arg nil)
20007 ;;;###autoload
20008 (defun org-todo-list (arg)
20009 "Show all TODO entries from all agenda file in a single list.
20010 The prefix arg can be used to select a specific TODO keyword and limit
20011 the list to these. When using \\[universal-argument], you will be prompted
20012 for a keyword. A numeric prefix directly selects the Nth keyword in
20013 `org-todo-keywords-1'."
20014 (interactive "P")
20015 (require 'calendar)
20016 (org-compile-prefix-format 'todo)
20017 (org-set-sorting-strategy 'todo)
20018 (org-prepare-agenda "TODO")
20019 (let* ((today (time-to-days (current-time)))
20020 (date (calendar-gregorian-from-absolute today))
20021 (kwds org-todo-keywords-for-agenda)
20022 (completion-ignore-case t)
20023 (org-select-this-todo-keyword
20024 (if (stringp arg) arg
20025 (and arg (integerp arg) (> arg 0)
20026 (nth (1- arg) kwds))))
20027 rtn rtnall files file pos)
20028 (when (equal arg '(4))
20029 (setq org-select-this-todo-keyword
20030 (completing-read "Keyword (or KWD1|K2D2|...): "
20031 (mapcar 'list kwds) nil nil)))
20032 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
20033 (org-set-local 'org-last-arg arg)
20034 (setq org-agenda-redo-command
20035 '(org-todo-list (or current-prefix-arg org-last-arg)))
20036 (setq files (org-agenda-files)
20037 rtnall nil)
20038 (while (setq file (pop files))
20039 (catch 'nextfile
20040 (org-check-agenda-file file)
20041 (setq rtn (org-agenda-get-day-entries file date :todo))
20042 (setq rtnall (append rtnall rtn))))
20043 (if org-agenda-overriding-header
20044 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20045 nil 'face 'org-agenda-structure) "\n")
20046 (insert "Global list of TODO items of type: ")
20047 (add-text-properties (point-min) (1- (point))
20048 (list 'face 'org-agenda-structure))
20049 (setq pos (point))
20050 (insert (or org-select-this-todo-keyword "ALL") "\n")
20051 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20052 (setq pos (point))
20053 (unless org-agenda-multi
20054 (insert "Available with `N r': (0)ALL")
20055 (let ((n 0) s)
20056 (mapc (lambda (x)
20057 (setq s (format "(%d)%s" (setq n (1+ n)) x))
20058 (if (> (+ (current-column) (string-width s) 1) (frame-width))
20059 (insert "\n "))
20060 (insert " " s))
20061 kwds))
20062 (insert "\n"))
20063 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20064 (when rtnall
20065 (insert (org-finalize-agenda-entries rtnall) "\n"))
20066 (goto-char (point-min))
20067 (org-fit-agenda-window)
20068 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
20069 (org-finalize-agenda)
20070 (setq buffer-read-only t)))
20072 ;;; Agenda tags match
20074 ;;;###autoload
20075 (defun org-tags-view (&optional todo-only match)
20076 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
20077 The prefix arg TODO-ONLY limits the search to TODO entries."
20078 (interactive "P")
20079 (org-compile-prefix-format 'tags)
20080 (org-set-sorting-strategy 'tags)
20081 (let* ((org-tags-match-list-sublevels
20082 (if todo-only t org-tags-match-list-sublevels))
20083 (completion-ignore-case t)
20084 rtn rtnall files file pos matcher
20085 buffer)
20086 (setq matcher (org-make-tags-matcher match)
20087 match (car matcher) matcher (cdr matcher))
20088 (org-prepare-agenda (concat "TAGS " match))
20089 (setq org-agenda-redo-command
20090 (list 'org-tags-view (list 'quote todo-only)
20091 (list 'if 'current-prefix-arg nil match)))
20092 (setq files (org-agenda-files)
20093 rtnall nil)
20094 (while (setq file (pop files))
20095 (catch 'nextfile
20096 (org-check-agenda-file file)
20097 (setq buffer (if (file-exists-p file)
20098 (org-get-agenda-file-buffer file)
20099 (error "No such file %s" file)))
20100 (if (not buffer)
20101 ;; If file does not exist, merror message to agenda
20102 (setq rtn (list
20103 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
20104 rtnall (append rtnall rtn))
20105 (with-current-buffer buffer
20106 (unless (org-mode-p)
20107 (error "Agenda file %s is not in `org-mode'" file))
20108 (save-excursion
20109 (save-restriction
20110 (if org-agenda-restrict
20111 (narrow-to-region org-agenda-restrict-begin
20112 org-agenda-restrict-end)
20113 (widen))
20114 (setq rtn (org-scan-tags 'agenda matcher todo-only))
20115 (setq rtnall (append rtnall rtn))))))))
20116 (if org-agenda-overriding-header
20117 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20118 nil 'face 'org-agenda-structure) "\n")
20119 (insert "Headlines with TAGS match: ")
20120 (add-text-properties (point-min) (1- (point))
20121 (list 'face 'org-agenda-structure))
20122 (setq pos (point))
20123 (insert match "\n")
20124 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20125 (setq pos (point))
20126 (unless org-agenda-multi
20127 (insert "Press `C-u r' to search again with new search string\n"))
20128 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20129 (when rtnall
20130 (insert (org-finalize-agenda-entries rtnall) "\n"))
20131 (goto-char (point-min))
20132 (org-fit-agenda-window)
20133 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
20134 (org-finalize-agenda)
20135 (setq buffer-read-only t)))
20137 ;;; Agenda Finding stuck projects
20139 (defvar org-agenda-skip-regexp nil
20140 "Regular expression used in skipping subtrees for the agenda.
20141 This is basically a temporary global variable that can be set and then
20142 used by user-defined selections using `org-agenda-skip-function'.")
20144 (defvar org-agenda-overriding-header nil
20145 "When this is set during todo and tags searches, will replace header.")
20147 (defun org-agenda-skip-subtree-when-regexp-matches ()
20148 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
20149 If yes, it returns the end position of this tree, causing agenda commands
20150 to skip this subtree. This is a function that can be put into
20151 `org-agenda-skip-function' for the duration of a command."
20152 (let ((end (save-excursion (org-end-of-subtree t)))
20153 skip)
20154 (save-excursion
20155 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
20156 (and skip end)))
20158 (defun org-agenda-skip-entry-if (&rest conditions)
20159 "Skip entry if any of CONDITIONS is true.
20160 See `org-agenda-skip-if for details."
20161 (org-agenda-skip-if nil conditions))
20163 (defun org-agenda-skip-subtree-if (&rest conditions)
20164 "Skip entry if any of CONDITIONS is true.
20165 See `org-agenda-skip-if for details."
20166 (org-agenda-skip-if t conditions))
20168 (defun org-agenda-skip-if (subtree conditions)
20169 "Checks current entity for CONDITIONS.
20170 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
20171 the entry, i.e. the text before the next heading is checked.
20173 CONDITIONS is a list of symbols, boolean OR is used to combine the results
20174 from different tests. Valid conditions are:
20176 scheduled Check if there is a scheduled cookie
20177 notscheduled Check if there is no scheduled cookie
20178 deadline Check if there is a deadline
20179 notdeadline Check if there is no deadline
20180 regexp Check if regexp matches
20181 notregexp Check if regexp does not match.
20183 The regexp is taken from the conditions list, it must com right after the
20184 `regexp' of `notregexp' element.
20186 If any of these conditions is met, this function returns the end point of
20187 the entity, causing the search to continue from there. This is a function
20188 that can be put into `org-agenda-skip-function' for the duration of a command."
20189 (let (beg end m)
20190 (org-back-to-heading t)
20191 (setq beg (point)
20192 end (if subtree
20193 (progn (org-end-of-subtree t) (point))
20194 (progn (outline-next-heading) (1- (point)))))
20195 (goto-char beg)
20196 (and
20198 (and (memq 'scheduled conditions)
20199 (re-search-forward org-scheduled-time-regexp end t))
20200 (and (memq 'notscheduled conditions)
20201 (not (re-search-forward org-scheduled-time-regexp end t)))
20202 (and (memq 'deadline conditions)
20203 (re-search-forward org-deadline-time-regexp end t))
20204 (and (memq 'notdeadline conditions)
20205 (not (re-search-forward org-deadline-time-regexp end t)))
20206 (and (setq m (memq 'regexp conditions))
20207 (stringp (nth 1 m))
20208 (re-search-forward (nth 1 m) end t))
20209 (and (setq m (memq 'notregexp conditions))
20210 (stringp (nth 1 m))
20211 (not (re-search-forward (nth 1 m) end t))))
20212 end)))
20214 ;;;###autoload
20215 (defun org-agenda-list-stuck-projects (&rest ignore)
20216 "Create agenda view for projects that are stuck.
20217 Stuck projects are project that have no next actions. For the definitions
20218 of what a project is and how to check if it stuck, customize the variable
20219 `org-stuck-projects'.
20220 MATCH is being ignored."
20221 (interactive)
20222 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
20223 ;; FIXME: we could have used org-agenda-skip-if here.
20224 (org-agenda-overriding-header "List of stuck projects: ")
20225 (matcher (nth 0 org-stuck-projects))
20226 (todo (nth 1 org-stuck-projects))
20227 (todo-wds (if (member "*" todo)
20228 (progn
20229 (org-prepare-agenda-buffers (org-agenda-files))
20230 (org-delete-all
20231 org-done-keywords-for-agenda
20232 (copy-sequence org-todo-keywords-for-agenda)))
20233 todo))
20234 (todo-re (concat "^\\*+[ \t]+\\("
20235 (mapconcat 'identity todo-wds "\\|")
20236 "\\)\\>"))
20237 (tags (nth 2 org-stuck-projects))
20238 (tags-re (if (member "*" tags)
20239 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
20240 (concat "^\\*+ .*:\\("
20241 (mapconcat 'identity tags "\\|")
20242 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
20243 (gen-re (nth 3 org-stuck-projects))
20244 (re-list
20245 (delq nil
20246 (list
20247 (if todo todo-re)
20248 (if tags tags-re)
20249 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
20250 gen-re)))))
20251 (setq org-agenda-skip-regexp
20252 (if re-list
20253 (mapconcat 'identity re-list "\\|")
20254 (error "No information how to identify unstuck projects")))
20255 (org-tags-view nil matcher)
20256 (with-current-buffer org-agenda-buffer-name
20257 (setq org-agenda-redo-command
20258 '(org-agenda-list-stuck-projects
20259 (or current-prefix-arg org-last-arg))))))
20261 ;;; Diary integration
20263 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
20265 (defun org-get-entries-from-diary (date)
20266 "Get the (Emacs Calendar) diary entries for DATE."
20267 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
20268 (diary-display-hook '(fancy-diary-display))
20269 (pop-up-frames nil)
20270 (list-diary-entries-hook
20271 (cons 'org-diary-default-entry list-diary-entries-hook))
20272 (diary-file-name-prefix-function nil) ; turn this feature off
20273 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
20274 entries
20275 (org-disable-agenda-to-diary t))
20276 (save-excursion
20277 (save-window-excursion
20278 (funcall (if (fboundp 'diary-list-entries)
20279 'diary-list-entries 'list-diary-entries)
20280 date 1)))
20281 (if (not (get-buffer fancy-diary-buffer))
20282 (setq entries nil)
20283 (with-current-buffer fancy-diary-buffer
20284 (setq buffer-read-only nil)
20285 (if (zerop (buffer-size))
20286 ;; No entries
20287 (setq entries nil)
20288 ;; Omit the date and other unnecessary stuff
20289 (org-agenda-cleanup-fancy-diary)
20290 ;; Add prefix to each line and extend the text properties
20291 (if (zerop (buffer-size))
20292 (setq entries nil)
20293 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
20294 (set-buffer-modified-p nil)
20295 (kill-buffer fancy-diary-buffer)))
20296 (when entries
20297 (setq entries (org-split-string entries "\n"))
20298 (setq entries
20299 (mapcar
20300 (lambda (x)
20301 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
20302 ;; Extend the text properties to the beginning of the line
20303 (org-add-props x (text-properties-at (1- (length x)) x)
20304 'type "diary" 'date date))
20305 entries)))))
20307 (defun org-agenda-cleanup-fancy-diary ()
20308 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
20309 This gets rid of the date, the underline under the date, and
20310 the dummy entry installed by `org-mode' to ensure non-empty diary for each
20311 date. It also removes lines that contain only whitespace."
20312 (goto-char (point-min))
20313 (if (looking-at ".*?:[ \t]*")
20314 (progn
20315 (replace-match "")
20316 (re-search-forward "\n=+$" nil t)
20317 (replace-match "")
20318 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
20319 (re-search-forward "\n=+$" nil t)
20320 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
20321 (goto-char (point-min))
20322 (while (re-search-forward "^ +\n" nil t)
20323 (replace-match ""))
20324 (goto-char (point-min))
20325 (if (re-search-forward "^Org-mode dummy\n?" nil t)
20326 (replace-match "")))
20328 ;; Make sure entries from the diary have the right text properties.
20329 (eval-after-load "diary-lib"
20330 '(if (boundp 'diary-modify-entry-list-string-function)
20331 ;; We can rely on the hook, nothing to do
20333 ;; Hook not avaiable, must use advice to make this work
20334 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
20335 "Make the position visible."
20336 (if (and org-disable-agenda-to-diary ;; called from org-agenda
20337 (stringp string)
20338 buffer-file-name)
20339 (setq string (org-modify-diary-entry-string string))))))
20341 (defun org-modify-diary-entry-string (string)
20342 "Add text properties to string, allowing org-mode to act on it."
20343 (org-add-props string nil
20344 'mouse-face 'highlight
20345 'keymap org-agenda-keymap
20346 'help-echo (if buffer-file-name
20347 (format "mouse-2 or RET jump to diary file %s"
20348 (abbreviate-file-name buffer-file-name))
20350 'org-agenda-diary-link t
20351 'org-marker (org-agenda-new-marker (point-at-bol))))
20353 (defun org-diary-default-entry ()
20354 "Add a dummy entry to the diary.
20355 Needed to avoid empty dates which mess up holiday display."
20356 ;; Catch the error if dealing with the new add-to-diary-alist
20357 (when org-disable-agenda-to-diary
20358 (condition-case nil
20359 (add-to-diary-list original-date "Org-mode dummy" "")
20360 (error
20361 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
20363 ;;;###autoload
20364 (defun org-diary (&rest args)
20365 "Return diary information from org-files.
20366 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
20367 It accesses org files and extracts information from those files to be
20368 listed in the diary. The function accepts arguments specifying what
20369 items should be listed. The following arguments are allowed:
20371 :timestamp List the headlines of items containing a date stamp or
20372 date range matching the selected date. Deadlines will
20373 also be listed, on the expiration day.
20375 :sexp List entries resulting from diary-like sexps.
20377 :deadline List any deadlines past due, or due within
20378 `org-deadline-warning-days'. The listing occurs only
20379 in the diary for *today*, not at any other date. If
20380 an entry is marked DONE, it is no longer listed.
20382 :scheduled List all items which are scheduled for the given date.
20383 The diary for *today* also contains items which were
20384 scheduled earlier and are not yet marked DONE.
20386 :todo List all TODO items from the org-file. This may be a
20387 long list - so this is not turned on by default.
20388 Like deadlines, these entries only show up in the
20389 diary for *today*, not at any other date.
20391 The call in the diary file should look like this:
20393 &%%(org-diary) ~/path/to/some/orgfile.org
20395 Use a separate line for each org file to check. Or, if you omit the file name,
20396 all files listed in `org-agenda-files' will be checked automatically:
20398 &%%(org-diary)
20400 If you don't give any arguments (as in the example above), the default
20401 arguments (:deadline :scheduled :timestamp :sexp) are used.
20402 So the example above may also be written as
20404 &%%(org-diary :deadline :timestamp :sexp :scheduled)
20406 The function expects the lisp variables `entry' and `date' to be provided
20407 by the caller, because this is how the calendar works. Don't use this
20408 function from a program - use `org-agenda-get-day-entries' instead."
20409 (org-agenda-maybe-reset-markers)
20410 (org-compile-prefix-format 'agenda)
20411 (org-set-sorting-strategy 'agenda)
20412 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
20413 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
20414 (list entry)
20415 (org-agenda-files t)))
20416 file rtn results)
20417 (org-prepare-agenda-buffers files)
20418 ;; If this is called during org-agenda, don't return any entries to
20419 ;; the calendar. Org Agenda will list these entries itself.
20420 (if org-disable-agenda-to-diary (setq files nil))
20421 (while (setq file (pop files))
20422 (setq rtn (apply 'org-agenda-get-day-entries file date args))
20423 (setq results (append results rtn)))
20424 (if results
20425 (concat (org-finalize-agenda-entries results) "\n"))))
20427 ;;; Agenda entry finders
20429 (defun org-agenda-get-day-entries (file date &rest args)
20430 "Does the work for `org-diary' and `org-agenda'.
20431 FILE is the path to a file to be checked for entries. DATE is date like
20432 the one returned by `calendar-current-date'. ARGS are symbols indicating
20433 which kind of entries should be extracted. For details about these, see
20434 the documentation of `org-diary'."
20435 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
20436 (let* ((org-startup-folded nil)
20437 (org-startup-align-all-tables nil)
20438 (buffer (if (file-exists-p file)
20439 (org-get-agenda-file-buffer file)
20440 (error "No such file %s" file)))
20441 arg results rtn)
20442 (if (not buffer)
20443 ;; If file does not exist, make sure an error message ends up in diary
20444 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
20445 (with-current-buffer buffer
20446 (unless (org-mode-p)
20447 (error "Agenda file %s is not in `org-mode'" file))
20448 (let ((case-fold-search nil))
20449 (save-excursion
20450 (save-restriction
20451 (if org-agenda-restrict
20452 (narrow-to-region org-agenda-restrict-begin
20453 org-agenda-restrict-end)
20454 (widen))
20455 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
20456 (while (setq arg (pop args))
20457 (cond
20458 ((and (eq arg :todo)
20459 (equal date (calendar-current-date)))
20460 (setq rtn (org-agenda-get-todos))
20461 (setq results (append results rtn)))
20462 ((eq arg :timestamp)
20463 (setq rtn (org-agenda-get-blocks))
20464 (setq results (append results rtn))
20465 (setq rtn (org-agenda-get-timestamps))
20466 (setq results (append results rtn)))
20467 ((eq arg :sexp)
20468 (setq rtn (org-agenda-get-sexps))
20469 (setq results (append results rtn)))
20470 ((eq arg :scheduled)
20471 (setq rtn (org-agenda-get-scheduled))
20472 (setq results (append results rtn)))
20473 ((eq arg :closed)
20474 (setq rtn (org-agenda-get-closed))
20475 (setq results (append results rtn)))
20476 ((eq arg :deadline)
20477 (setq rtn (org-agenda-get-deadlines))
20478 (setq results (append results rtn))))))))
20479 results))))
20481 (defun org-entry-is-todo-p ()
20482 (member (org-get-todo-state) org-not-done-keywords))
20484 (defun org-entry-is-done-p ()
20485 (member (org-get-todo-state) org-done-keywords))
20487 (defun org-get-todo-state ()
20488 (save-excursion
20489 (org-back-to-heading t)
20490 (and (looking-at org-todo-line-regexp)
20491 (match-end 2)
20492 (match-string 2))))
20494 (defun org-at-date-range-p (&optional inactive-ok)
20495 "Is the cursor inside a date range?"
20496 (interactive)
20497 (save-excursion
20498 (catch 'exit
20499 (let ((pos (point)))
20500 (skip-chars-backward "^[<\r\n")
20501 (skip-chars-backward "<[")
20502 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
20503 (>= (match-end 0) pos)
20504 (throw 'exit t))
20505 (skip-chars-backward "^<[\r\n")
20506 (skip-chars-backward "<[")
20507 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
20508 (>= (match-end 0) pos)
20509 (throw 'exit t)))
20510 nil)))
20512 (defun org-agenda-get-todos ()
20513 "Return the TODO information for agenda display."
20514 (let* ((props (list 'face nil
20515 'done-face 'org-done
20516 'org-not-done-regexp org-not-done-regexp
20517 'org-todo-regexp org-todo-regexp
20518 'mouse-face 'highlight
20519 'keymap org-agenda-keymap
20520 'help-echo
20521 (format "mouse-2 or RET jump to org file %s"
20522 (abbreviate-file-name buffer-file-name))))
20523 ;; FIXME: get rid of the \n at some point but watch out
20524 (regexp (concat "^\\*+[ \t]+\\("
20525 (if org-select-this-todo-keyword
20526 (if (equal org-select-this-todo-keyword "*")
20527 org-todo-regexp
20528 (concat "\\<\\("
20529 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
20530 "\\)\\>"))
20531 org-not-done-regexp)
20532 "[^\n\r]*\\)"))
20533 marker priority category tags
20534 ee txt beg end)
20535 (goto-char (point-min))
20536 (while (re-search-forward regexp nil t)
20537 (catch :skip
20538 (save-match-data
20539 (beginning-of-line)
20540 (setq beg (point) end (progn (outline-next-heading) (point)))
20541 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
20542 (re-search-forward org-ts-regexp end t))
20543 (and org-agenda-todo-ignore-scheduled (goto-char beg)
20544 (re-search-forward org-scheduled-time-regexp end t))
20545 (and org-agenda-todo-ignore-deadlines (goto-char beg)
20546 (re-search-forward org-deadline-time-regexp end t)
20547 (org-deadline-close (match-string 1))))
20548 (goto-char (1+ beg))
20549 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
20550 (throw :skip nil)))
20551 (goto-char beg)
20552 (org-agenda-skip)
20553 (goto-char (match-beginning 1))
20554 (setq marker (org-agenda-new-marker (match-beginning 0))
20555 category (org-get-category)
20556 tags (org-get-tags-at (point))
20557 txt (org-format-agenda-item "" (match-string 1) category tags)
20558 priority (1+ (org-get-priority txt)))
20559 (org-add-props txt props
20560 'org-marker marker 'org-hd-marker marker
20561 'priority priority 'org-category category
20562 'type "todo")
20563 (push txt ee)
20564 (if org-agenda-todo-list-sublevels
20565 (goto-char (match-end 1))
20566 (org-end-of-subtree 'invisible))))
20567 (nreverse ee)))
20569 (defconst org-agenda-no-heading-message
20570 "No heading for this item in buffer or region.")
20572 (defun org-agenda-get-timestamps ()
20573 "Return the date stamp information for agenda display."
20574 (let* ((props (list 'face nil
20575 'org-not-done-regexp org-not-done-regexp
20576 'org-todo-regexp org-todo-regexp
20577 'mouse-face 'highlight
20578 'keymap org-agenda-keymap
20579 'help-echo
20580 (format "mouse-2 or RET jump to org file %s"
20581 (abbreviate-file-name buffer-file-name))))
20582 (d1 (calendar-absolute-from-gregorian date))
20583 (remove-re
20584 (concat
20585 (regexp-quote
20586 (format-time-string
20587 "<%Y-%m-%d"
20588 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20589 ".*?>"))
20590 (regexp
20591 (concat
20592 (regexp-quote
20593 (substring
20594 (format-time-string
20595 (car org-time-stamp-formats)
20596 (apply 'encode-time ; DATE bound by calendar
20597 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
20598 0 11))
20599 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
20600 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
20601 marker hdmarker deadlinep scheduledp donep tmp priority category
20602 ee txt timestr tags b0 b3 e3 head)
20603 (goto-char (point-min))
20604 (while (re-search-forward regexp nil t)
20605 (setq b0 (match-beginning 0)
20606 b3 (match-beginning 3) e3 (match-end 3))
20607 (catch :skip
20608 (and (org-at-date-range-p) (throw :skip nil))
20609 (org-agenda-skip)
20610 (if (and (match-end 1)
20611 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
20612 (throw :skip nil))
20613 (if (and e3
20614 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
20615 (throw :skip nil))
20616 (setq marker (org-agenda-new-marker b0)
20617 category (org-get-category b0)
20618 tmp (buffer-substring (max (point-min)
20619 (- b0 org-ds-keyword-length))
20621 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
20622 deadlinep (string-match org-deadline-regexp tmp)
20623 scheduledp (string-match org-scheduled-regexp tmp)
20624 donep (org-entry-is-done-p))
20625 (if (or scheduledp deadlinep) (throw :skip t))
20626 (if (string-match ">" timestr)
20627 ;; substring should only run to end of time stamp
20628 (setq timestr (substring timestr 0 (match-end 0))))
20629 (save-excursion
20630 (if (re-search-backward "^\\*+ " nil t)
20631 (progn
20632 (goto-char (match-beginning 0))
20633 (setq hdmarker (org-agenda-new-marker)
20634 tags (org-get-tags-at))
20635 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
20636 (setq head (match-string 1))
20637 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
20638 (setq txt (org-format-agenda-item
20639 nil head category tags timestr nil
20640 remove-re)))
20641 (setq txt org-agenda-no-heading-message))
20642 (setq priority (org-get-priority txt))
20643 (org-add-props txt props
20644 'org-marker marker 'org-hd-marker hdmarker)
20645 (org-add-props txt nil 'priority priority
20646 'org-category category 'date date
20647 'type "timestamp")
20648 (push txt ee))
20649 (outline-next-heading)))
20650 (nreverse ee)))
20652 (defun org-agenda-get-sexps ()
20653 "Return the sexp information for agenda display."
20654 (require 'diary-lib)
20655 (let* ((props (list 'face nil
20656 'mouse-face 'highlight
20657 'keymap org-agenda-keymap
20658 'help-echo
20659 (format "mouse-2 or RET jump to org file %s"
20660 (abbreviate-file-name buffer-file-name))))
20661 (regexp "^&?%%(")
20662 marker category ee txt tags entry result beg b sexp sexp-entry)
20663 (goto-char (point-min))
20664 (while (re-search-forward regexp nil t)
20665 (catch :skip
20666 (org-agenda-skip)
20667 (setq beg (match-beginning 0))
20668 (goto-char (1- (match-end 0)))
20669 (setq b (point))
20670 (forward-sexp 1)
20671 (setq sexp (buffer-substring b (point)))
20672 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
20673 (org-trim (match-string 1))
20674 ""))
20675 (setq result (org-diary-sexp-entry sexp sexp-entry date))
20676 (when result
20677 (setq marker (org-agenda-new-marker beg)
20678 category (org-get-category beg))
20680 (if (string-match "\\S-" result)
20681 (setq txt result)
20682 (setq txt "SEXP entry returned empty string"))
20684 (setq txt (org-format-agenda-item
20685 "" txt category tags 'time))
20686 (org-add-props txt props 'org-marker marker)
20687 (org-add-props txt nil
20688 'org-category category 'date date
20689 'type "sexp")
20690 (push txt ee))))
20691 (nreverse ee)))
20693 (defun org-agenda-get-closed ()
20694 "Return the logged TODO entries for agenda display."
20695 (let* ((props (list 'mouse-face 'highlight
20696 'org-not-done-regexp org-not-done-regexp
20697 'org-todo-regexp org-todo-regexp
20698 'keymap org-agenda-keymap
20699 'help-echo
20700 (format "mouse-2 or RET jump to org file %s"
20701 (abbreviate-file-name buffer-file-name))))
20702 (regexp (concat
20703 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
20704 (regexp-quote
20705 (substring
20706 (format-time-string
20707 (car org-time-stamp-formats)
20708 (apply 'encode-time ; DATE bound by calendar
20709 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
20710 1 11))))
20711 marker hdmarker priority category tags closedp
20712 ee txt timestr)
20713 (goto-char (point-min))
20714 (while (re-search-forward regexp nil t)
20715 (catch :skip
20716 (org-agenda-skip)
20717 (setq marker (org-agenda-new-marker (match-beginning 0))
20718 closedp (equal (match-string 1) org-closed-string)
20719 category (org-get-category (match-beginning 0))
20720 timestr (buffer-substring (match-beginning 0) (point-at-eol))
20721 ;; donep (org-entry-is-done-p)
20723 (if (string-match "\\]" timestr)
20724 ;; substring should only run to end of time stamp
20725 (setq timestr (substring timestr 0 (match-end 0))))
20726 (save-excursion
20727 (if (re-search-backward "^\\*+ " nil t)
20728 (progn
20729 (goto-char (match-beginning 0))
20730 (setq hdmarker (org-agenda-new-marker)
20731 tags (org-get-tags-at))
20732 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
20733 (setq txt (org-format-agenda-item
20734 (if closedp "Closed: " "Clocked: ")
20735 (match-string 1) category tags timestr)))
20736 (setq txt org-agenda-no-heading-message))
20737 (setq priority 100000)
20738 (org-add-props txt props
20739 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
20740 'priority priority 'org-category category
20741 'type "closed" 'date date
20742 'undone-face 'org-warning 'done-face 'org-done)
20743 (push txt ee))
20744 (outline-next-heading)))
20745 (nreverse ee)))
20747 (defun org-agenda-get-deadlines ()
20748 "Return the deadline information for agenda display."
20749 (let* ((props (list 'mouse-face 'highlight
20750 'org-not-done-regexp org-not-done-regexp
20751 'org-todo-regexp org-todo-regexp
20752 'keymap org-agenda-keymap
20753 'help-echo
20754 (format "mouse-2 or RET jump to org file %s"
20755 (abbreviate-file-name buffer-file-name))))
20756 (regexp org-deadline-time-regexp)
20757 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
20758 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
20759 d2 diff dfrac wdays pos pos1 category tags
20760 ee txt head face s upcomingp donep timestr)
20761 (goto-char (point-min))
20762 (while (re-search-forward regexp nil t)
20763 (catch :skip
20764 (org-agenda-skip)
20765 (setq s (match-string 1)
20766 pos (1- (match-beginning 1))
20767 d2 (org-time-string-to-absolute (match-string 1) d1)
20768 diff (- d2 d1)
20769 wdays (org-get-wdays s)
20770 dfrac (/ (* 1.0 (- wdays diff)) wdays)
20771 upcomingp (and todayp (> diff 0)))
20772 ;; When to show a deadline in the calendar:
20773 ;; If the expiration is within wdays warning time.
20774 ;; Past-due deadlines are only shown on the current date
20775 (if (or (and (<= diff wdays)
20776 (and todayp (not org-agenda-only-exact-dates)))
20777 (= diff 0))
20778 (save-excursion
20779 (setq category (org-get-category))
20780 (if (re-search-backward "^\\*+[ \t]+" nil t)
20781 (progn
20782 (goto-char (match-end 0))
20783 (setq pos1 (match-beginning 0))
20784 (setq tags (org-get-tags-at pos1))
20785 (setq head (buffer-substring-no-properties
20786 (point)
20787 (progn (skip-chars-forward "^\r\n")
20788 (point))))
20789 (setq donep (string-match org-looking-at-done-regexp head))
20790 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
20791 (setq timestr
20792 (concat (substring s (match-beginning 1)) " "))
20793 (setq timestr 'time))
20794 (if (and donep
20795 (or org-agenda-skip-deadline-if-done
20796 (not (= diff 0))))
20797 (setq txt nil)
20798 (setq txt (org-format-agenda-item
20799 (if (= diff 0)
20800 (car org-agenda-deadline-leaders)
20801 (format (nth 1 org-agenda-deadline-leaders)
20802 diff))
20803 head category tags timestr))))
20804 (setq txt org-agenda-no-heading-message))
20805 (when txt
20806 (setq face (org-agenda-deadline-face dfrac))
20807 (org-add-props txt props
20808 'org-marker (org-agenda-new-marker pos)
20809 'org-hd-marker (org-agenda-new-marker pos1)
20810 'priority (+ (if upcomingp (floor (* dfrac 10.)) 100)
20811 (org-get-priority txt))
20812 'org-category category
20813 'type (if upcomingp "upcoming-deadline" "deadline")
20814 'date (if upcomingp date d2)
20815 'face (if donep 'org-done face)
20816 'undone-face face 'done-face 'org-done)
20817 (push txt ee))))))
20818 (nreverse ee)))
20820 (defun org-agenda-deadline-face (fraction)
20821 "Return the face to displaying a deadline item.
20822 FRACTION is what fraction of the head-warning time has passed."
20823 (let ((faces org-agenda-deadline-faces) f)
20824 (catch 'exit
20825 (while (setq f (pop faces))
20826 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
20828 (defun org-agenda-get-scheduled ()
20829 "Return the scheduled information for agenda display."
20830 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
20831 'org-todo-regexp org-todo-regexp
20832 'done-face 'org-done
20833 'mouse-face 'highlight
20834 'keymap org-agenda-keymap
20835 'help-echo
20836 (format "mouse-2 or RET jump to org file %s"
20837 (abbreviate-file-name buffer-file-name))))
20838 (regexp org-scheduled-time-regexp)
20839 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
20840 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
20841 d2 diff pos pos1 category tags
20842 ee txt head pastschedp donep face timestr s)
20843 (goto-char (point-min))
20844 (while (re-search-forward regexp nil t)
20845 (catch :skip
20846 (org-agenda-skip)
20847 (setq s (match-string 1)
20848 pos (1- (match-beginning 1))
20849 d2 (org-time-string-to-absolute (match-string 1) d1)
20850 diff (- d2 d1))
20851 (setq pastschedp (and todayp (< diff 0)))
20852 ;; When to show a scheduled item in the calendar:
20853 ;; If it is on or past the date.
20854 (if (or (and (< diff 0)
20855 (and todayp (not org-agenda-only-exact-dates)))
20856 (= diff 0))
20857 (save-excursion
20858 (setq category (org-get-category))
20859 (if (re-search-backward "^\\*+[ \t]+" nil t)
20860 (progn
20861 (goto-char (match-end 0))
20862 (setq pos1 (match-beginning 0))
20863 (setq tags (org-get-tags-at))
20864 (setq head (buffer-substring-no-properties
20865 (point)
20866 (progn (skip-chars-forward "^\r\n") (point))))
20867 (setq donep (string-match org-looking-at-done-regexp head))
20868 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
20869 (setq timestr
20870 (concat (substring s (match-beginning 1)) " "))
20871 (setq timestr 'time))
20872 (if (and donep
20873 (or org-agenda-skip-scheduled-if-done
20874 (not (= diff 0))))
20875 (setq txt nil)
20876 (setq txt (org-format-agenda-item
20877 (if (= diff 0)
20878 (car org-agenda-scheduled-leaders)
20879 (format (nth 1 org-agenda-scheduled-leaders)
20880 (- 1 diff)))
20881 head category tags timestr))))
20882 (setq txt org-agenda-no-heading-message))
20883 (when txt
20884 (setq face (if pastschedp
20885 'org-scheduled-previously
20886 'org-scheduled-today))
20887 (org-add-props txt props
20888 'undone-face face
20889 'face (if donep 'org-done face)
20890 'org-marker (org-agenda-new-marker pos)
20891 'org-hd-marker (org-agenda-new-marker pos1)
20892 'type (if pastschedp "past-scheduled" "scheduled")
20893 'date (if pastschedp d2 date)
20894 'priority (+ 94 (- 5 diff) (org-get-priority txt))
20895 'org-category category)
20896 (push txt ee))))))
20897 (nreverse ee)))
20899 (defun org-agenda-get-blocks ()
20900 "Return the date-range information for agenda display."
20901 (let* ((props (list 'face nil
20902 'org-not-done-regexp org-not-done-regexp
20903 'org-todo-regexp org-todo-regexp
20904 'mouse-face 'highlight
20905 'keymap org-agenda-keymap
20906 'help-echo
20907 (format "mouse-2 or RET jump to org file %s"
20908 (abbreviate-file-name buffer-file-name))))
20909 (regexp org-tr-regexp)
20910 (d0 (calendar-absolute-from-gregorian date))
20911 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
20912 donep head)
20913 (goto-char (point-min))
20914 (while (re-search-forward regexp nil t)
20915 (catch :skip
20916 (org-agenda-skip)
20917 (setq pos (point))
20918 (setq timestr (match-string 0)
20919 s1 (match-string 1)
20920 s2 (match-string 2)
20921 d1 (time-to-days (org-time-string-to-time s1))
20922 d2 (time-to-days (org-time-string-to-time s2)))
20923 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
20924 ;; Only allow days between the limits, because the normal
20925 ;; date stamps will catch the limits.
20926 (save-excursion
20927 (setq marker (org-agenda-new-marker (point)))
20928 (setq category (org-get-category))
20929 (if (re-search-backward "^\\*+ " nil t)
20930 (progn
20931 (goto-char (match-beginning 0))
20932 (setq hdmarker (org-agenda-new-marker (point)))
20933 (setq tags (org-get-tags-at))
20934 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
20935 (setq head (match-string 1))
20936 (and org-agenda-skip-timestamp-if-done
20937 (org-entry-is-done-p)
20938 (throw :skip t))
20939 (setq txt (org-format-agenda-item
20940 (format (if (= d1 d2) "" "(%d/%d): ")
20941 (1+ (- d0 d1)) (1+ (- d2 d1)))
20942 head category tags
20943 (if (= d0 d1) timestr))))
20944 (setq txt org-agenda-no-heading-message))
20945 (org-add-props txt props
20946 'org-marker marker 'org-hd-marker hdmarker
20947 'type "block" 'date date
20948 'priority (org-get-priority txt) 'org-category category)
20949 (push txt ee)))
20950 (goto-char pos)))
20951 ;; Sort the entries by expiration date.
20952 (nreverse ee)))
20954 ;;; Agenda presentation and sorting
20956 (defconst org-plain-time-of-day-regexp
20957 (concat
20958 "\\(\\<[012]?[0-9]"
20959 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
20960 "\\(--?"
20961 "\\(\\<[012]?[0-9]"
20962 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
20963 "\\)?")
20964 "Regular expression to match a plain time or time range.
20965 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
20966 groups carry important information:
20967 0 the full match
20968 1 the first time, range or not
20969 8 the second time, if it is a range.")
20971 (defconst org-plain-time-extension-regexp
20972 (concat
20973 "\\(\\<[012]?[0-9]"
20974 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
20975 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
20976 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
20977 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
20978 groups carry important information:
20979 0 the full match
20980 7 hours of duration
20981 9 minutes of duration")
20983 (defconst org-stamp-time-of-day-regexp
20984 (concat
20985 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
20986 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
20987 "\\(--?"
20988 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
20989 "Regular expression to match a timestamp time or time range.
20990 After a match, the following groups carry important information:
20991 0 the full match
20992 1 date plus weekday, for backreferencing to make sure both times on same day
20993 2 the first time, range or not
20994 4 the second time, if it is a range.")
20996 (defvar org-prefix-has-time nil
20997 "A flag, set by `org-compile-prefix-format'.
20998 The flag is set if the currently compiled format contains a `%t'.")
20999 (defvar org-prefix-has-tag nil
21000 "A flag, set by `org-compile-prefix-format'.
21001 The flag is set if the currently compiled format contains a `%T'.")
21003 (defun org-format-agenda-item (extra txt &optional category tags dotime
21004 noprefix remove-re)
21005 "Format TXT to be inserted into the agenda buffer.
21006 In particular, it adds the prefix and corresponding text properties. EXTRA
21007 must be a string and replaces the `%s' specifier in the prefix format.
21008 CATEGORY (string, symbol or nil) may be used to overrule the default
21009 category taken from local variable or file name. It will replace the `%c'
21010 specifier in the format. DOTIME, when non-nil, indicates that a
21011 time-of-day should be extracted from TXT for sorting of this entry, and for
21012 the `%t' specifier in the format. When DOTIME is a string, this string is
21013 searched for a time before TXT is. NOPREFIX is a flag and indicates that
21014 only the correctly processes TXT should be returned - this is used by
21015 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
21016 Any match of REMOVE-RE will be removed from TXT."
21017 (save-match-data
21018 ;; Diary entries sometimes have extra whitespace at the beginning
21019 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
21020 (let* ((category (or category
21021 org-category
21022 (if buffer-file-name
21023 (file-name-sans-extension
21024 (file-name-nondirectory buffer-file-name))
21025 "")))
21026 (tag (if tags (nth (1- (length tags)) tags) ""))
21027 time ; time and tag are needed for the eval of the prefix format
21028 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
21029 (time-of-day (and dotime (org-get-time-of-day ts)))
21030 stamp plain s0 s1 s2 rtn srp)
21031 (when (and dotime time-of-day org-prefix-has-time)
21032 ;; Extract starting and ending time and move them to prefix
21033 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
21034 (setq plain (string-match org-plain-time-of-day-regexp ts)))
21035 (setq s0 (match-string 0 ts)
21036 srp (and stamp (match-end 3))
21037 s1 (match-string (if plain 1 2) ts)
21038 s2 (match-string (if plain 8 (if srp 4 6)) ts))
21040 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
21041 ;; them, we might want to remove them there to avoid duplication.
21042 ;; The user can turn this off with a variable.
21043 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
21044 (string-match (concat (regexp-quote s0) " *") txt)
21045 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
21046 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
21047 (= (match-beginning 0) 0)
21049 (setq txt (replace-match "" nil nil txt))))
21050 ;; Normalize the time(s) to 24 hour
21051 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
21052 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
21054 (when (and s1 (not s2) org-agenda-default-appointment-duration
21055 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
21056 (let ((m (+ (string-to-number (match-string 2 s1))
21057 (* 60 (string-to-number (match-string 1 s1)))
21058 org-agenda-default-appointment-duration))
21060 (setq h (/ m 60) m (- m (* h 60)))
21061 (setq s2 (format "%02d:%02d" h m))))
21063 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
21064 txt)
21065 ;; Tags are in the string
21066 (if (or (eq org-agenda-remove-tags t)
21067 (and org-agenda-remove-tags
21068 org-prefix-has-tag))
21069 (setq txt (replace-match "" t t txt))
21070 (setq txt (replace-match
21071 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
21072 (match-string 2 txt))
21073 t t txt))))
21075 (when remove-re
21076 (while (string-match remove-re txt)
21077 (setq txt (replace-match "" t t txt))))
21079 ;; Create the final string
21080 (if noprefix
21081 (setq rtn txt)
21082 ;; Prepare the variables needed in the eval of the compiled format
21083 (setq time (cond (s2 (concat s1 "-" s2))
21084 (s1 (concat s1 "......"))
21085 (t ""))
21086 extra (or extra "")
21087 category (if (symbolp category) (symbol-name category) category))
21088 ;; Evaluate the compiled format
21089 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
21091 ;; And finally add the text properties
21092 (org-add-props rtn nil
21093 'org-category (downcase category) 'tags tags
21094 'org-highest-priority org-highest-priority
21095 'org-lowest-priority org-lowest-priority
21096 'prefix-length (- (length rtn) (length txt))
21097 'time-of-day time-of-day
21098 'txt txt
21099 'time time
21100 'extra extra
21101 'dotime dotime))))
21103 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
21104 (defvar org-agenda-sorting-strategy-selected nil)
21106 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
21107 (catch 'exit
21108 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
21109 ((and todayp (member 'today (car org-agenda-time-grid))))
21110 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
21111 ((member 'weekly (car org-agenda-time-grid)))
21112 (t (throw 'exit list)))
21113 (let* ((have (delq nil (mapcar
21114 (lambda (x) (get-text-property 1 'time-of-day x))
21115 list)))
21116 (string (nth 1 org-agenda-time-grid))
21117 (gridtimes (nth 2 org-agenda-time-grid))
21118 (req (car org-agenda-time-grid))
21119 (remove (member 'remove-match req))
21120 new time)
21121 (if (and (member 'require-timed req) (not have))
21122 ;; don't show empty grid
21123 (throw 'exit list))
21124 (while (setq time (pop gridtimes))
21125 (unless (and remove (member time have))
21126 (setq time (int-to-string time))
21127 (push (org-format-agenda-item
21128 nil string "" nil
21129 (concat (substring time 0 -2) ":" (substring time -2)))
21130 new)
21131 (put-text-property
21132 1 (length (car new)) 'face 'org-time-grid (car new))))
21133 (if (member 'time-up org-agenda-sorting-strategy-selected)
21134 (append new list)
21135 (append list new)))))
21137 (defun org-compile-prefix-format (key)
21138 "Compile the prefix format into a Lisp form that can be evaluated.
21139 The resulting form is returned and stored in the variable
21140 `org-prefix-format-compiled'."
21141 (setq org-prefix-has-time nil org-prefix-has-tag nil)
21142 (let ((s (cond
21143 ((stringp org-agenda-prefix-format)
21144 org-agenda-prefix-format)
21145 ((assq key org-agenda-prefix-format)
21146 (cdr (assq key org-agenda-prefix-format)))
21147 (t " %-12:c%?-12t% s")))
21148 (start 0)
21149 varform vars var e c f opt)
21150 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
21151 s start)
21152 (setq var (cdr (assoc (match-string 4 s)
21153 '(("c" . category) ("t" . time) ("s" . extra)
21154 ("T" . tag))))
21155 c (or (match-string 3 s) "")
21156 opt (match-beginning 1)
21157 start (1+ (match-beginning 0)))
21158 (if (equal var 'time) (setq org-prefix-has-time t))
21159 (if (equal var 'tag) (setq org-prefix-has-tag t))
21160 (setq f (concat "%" (match-string 2 s) "s"))
21161 (if opt
21162 (setq varform
21163 `(if (equal "" ,var)
21165 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
21166 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
21167 (setq s (replace-match "%s" t nil s))
21168 (push varform vars))
21169 (setq vars (nreverse vars))
21170 (setq org-prefix-format-compiled `(format ,s ,@vars))))
21172 (defun org-set-sorting-strategy (key)
21173 (if (symbolp (car org-agenda-sorting-strategy))
21174 ;; the old format
21175 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
21176 (setq org-agenda-sorting-strategy-selected
21177 (or (cdr (assq key org-agenda-sorting-strategy))
21178 (cdr (assq 'agenda org-agenda-sorting-strategy))
21179 '(time-up category-keep priority-down)))))
21181 (defun org-get-time-of-day (s &optional string mod24)
21182 "Check string S for a time of day.
21183 If found, return it as a military time number between 0 and 2400.
21184 If not found, return nil.
21185 The optional STRING argument forces conversion into a 5 character wide string
21186 HH:MM."
21187 (save-match-data
21188 (when
21189 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
21190 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
21191 (let* ((h (string-to-number (match-string 1 s)))
21192 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
21193 (ampm (if (match-end 4) (downcase (match-string 4 s))))
21194 (am-p (equal ampm "am"))
21195 (h1 (cond ((not ampm) h)
21196 ((= h 12) (if am-p 0 12))
21197 (t (+ h (if am-p 0 12)))))
21198 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
21199 (mod h1 24) h1))
21200 (t0 (+ (* 100 h2) m))
21201 (t1 (concat (if (>= h1 24) "+" " ")
21202 (if (< t0 100) "0" "")
21203 (if (< t0 10) "0" "")
21204 (int-to-string t0))))
21205 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
21207 (defun org-finalize-agenda-entries (list &optional nosort)
21208 "Sort and concatenate the agenda items."
21209 (setq list (mapcar 'org-agenda-highlight-todo list))
21210 (if nosort
21211 list
21212 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
21214 (defun org-agenda-highlight-todo (x)
21215 (let (re pl)
21216 (if (eq x 'line)
21217 (save-excursion
21218 (beginning-of-line 1)
21219 (setq re (get-text-property (point) 'org-todo-regexp))
21220 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
21221 (and (looking-at (concat "[ \t]*\\.*" re))
21222 (add-text-properties (match-beginning 0) (match-end 0)
21223 (list 'face (org-get-todo-face 0)))))
21224 (setq re (concat (get-text-property 0 'org-todo-regexp x))
21225 pl (get-text-property 0 'prefix-length x))
21226 (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
21227 (add-text-properties
21228 (or (match-end 1) (match-end 0)) (match-end 0)
21229 (list 'face (org-get-todo-face (match-string 2 x)))
21231 x)))
21233 (defsubst org-cmp-priority (a b)
21234 "Compare the priorities of string A and B."
21235 (let ((pa (or (get-text-property 1 'priority a) 0))
21236 (pb (or (get-text-property 1 'priority b) 0)))
21237 (cond ((> pa pb) +1)
21238 ((< pa pb) -1)
21239 (t nil))))
21241 (defsubst org-cmp-category (a b)
21242 "Compare the string values of categories of strings A and B."
21243 (let ((ca (or (get-text-property 1 'org-category a) ""))
21244 (cb (or (get-text-property 1 'org-category b) "")))
21245 (cond ((string-lessp ca cb) -1)
21246 ((string-lessp cb ca) +1)
21247 (t nil))))
21249 (defsubst org-cmp-tag (a b)
21250 "Compare the string values of categories of strings A and B."
21251 (let ((ta (car (last (get-text-property 1 'tags a))))
21252 (tb (car (last (get-text-property 1 'tags b)))))
21253 (cond ((not ta) +1)
21254 ((not tb) -1)
21255 ((string-lessp ta tb) -1)
21256 ((string-lessp tb ta) +1)
21257 (t nil))))
21259 (defsubst org-cmp-time (a b)
21260 "Compare the time-of-day values of strings A and B."
21261 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
21262 (ta (or (get-text-property 1 'time-of-day a) def))
21263 (tb (or (get-text-property 1 'time-of-day b) def)))
21264 (cond ((< ta tb) -1)
21265 ((< tb ta) +1)
21266 (t nil))))
21268 (defun org-entries-lessp (a b)
21269 "Predicate for sorting agenda entries."
21270 ;; The following variables will be used when the form is evaluated.
21271 ;; So even though the compiler complains, keep them.
21272 (let* ((time-up (org-cmp-time a b))
21273 (time-down (if time-up (- time-up) nil))
21274 (priority-up (org-cmp-priority a b))
21275 (priority-down (if priority-up (- priority-up) nil))
21276 (category-up (org-cmp-category a b))
21277 (category-down (if category-up (- category-up) nil))
21278 (category-keep (if category-up +1 nil))
21279 (tag-up (org-cmp-tag a b))
21280 (tag-down (if tag-up (- tag-up) nil)))
21281 (cdr (assoc
21282 (eval (cons 'or org-agenda-sorting-strategy-selected))
21283 '((-1 . t) (1 . nil) (nil . nil))))))
21285 ;;; Agenda restriction lock
21287 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
21288 "Overlay to mark the headline to which arenda commands are restricted.")
21289 (org-overlay-put org-agenda-restriction-lock-overlay
21290 'face 'org-agenda-restriction-lock)
21291 (org-overlay-put org-agenda-restriction-lock-overlay
21292 'help-echo "Agendas are currently limited to this subtree.")
21293 (org-detach-overlay org-agenda-restriction-lock-overlay)
21294 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
21295 "Overlay marking the agenda restriction line in speedbar.")
21296 (org-overlay-put org-speedbar-restriction-lock-overlay
21297 'face 'org-agenda-restriction-lock)
21298 (org-overlay-put org-speedbar-restriction-lock-overlay
21299 'help-echo "Agendas are currently limited to this item.")
21300 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21302 (defun org-agenda-set-restriction-lock (&optional type)
21303 "Set restriction lock for agenda, to current subtree or file.
21304 Restriction will be the file if TYPE is `file', or if type is the
21305 universal prefix '(4), or if the cursor is before the first headline
21306 in the file. Otherwise, restriction will be to the current subtree."
21307 (interactive "P")
21308 (and (equal type '(4)) (setq type 'file))
21309 (setq type (cond
21310 (type type)
21311 ((org-at-heading-p) 'subtree)
21312 ((condition-case nil (org-back-to-heading t) (error nil))
21313 'subtree)
21314 (t 'file)))
21315 (if (eq type 'subtree)
21316 (progn
21317 (setq org-agenda-restrict t)
21318 (setq org-agenda-overriding-restriction 'subtree)
21319 (put 'org-agenda-files 'org-restrict
21320 (list (buffer-file-name (buffer-base-buffer))))
21321 (org-back-to-heading t)
21322 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
21323 (move-marker org-agenda-restrict-begin (point))
21324 (move-marker org-agenda-restrict-end
21325 (save-excursion (org-end-of-subtree t)))
21326 (message "Locking agenda restriction to subtree"))
21327 (put 'org-agenda-files 'org-restrict
21328 (list (buffer-file-name (buffer-base-buffer))))
21329 (setq org-agenda-restrict nil)
21330 (setq org-agenda-overriding-restriction 'file)
21331 (move-marker org-agenda-restrict-begin nil)
21332 (move-marker org-agenda-restrict-end nil)
21333 (message "Locking agenda restriction to file"))
21334 (setq current-prefix-arg nil)
21335 (org-agenda-maybe-redo))
21337 (defun org-agenda-remove-restriction-lock (&optional noupdate)
21338 "Remove the agenda restriction lock."
21339 (interactive "P")
21340 (org-detach-overlay org-agenda-restriction-lock-overlay)
21341 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21342 (setq org-agenda-overriding-restriction nil)
21343 (setq org-agenda-restrict nil)
21344 (put 'org-agenda-files 'org-restrict nil)
21345 (move-marker org-agenda-restrict-begin nil)
21346 (move-marker org-agenda-restrict-end nil)
21347 (setq current-prefix-arg nil)
21348 (message "Agenda restriction lock removed")
21349 (or noupdate (org-agenda-maybe-redo)))
21351 (defun org-agenda-maybe-redo ()
21352 "If there is any window showing the agenda view, update it."
21353 (let ((w (get-buffer-window org-agenda-buffer-name t))
21354 (w0 (selected-window)))
21355 (when w
21356 (select-window w)
21357 (org-agenda-redo)
21358 (select-window w0)
21359 (if org-agenda-overriding-restriction
21360 (message "Agenda view shifted to new %s restriction"
21361 org-agenda-overriding-restriction)
21362 (message "Agenda restriction lock removed")))))
21364 ;;; Agenda commands
21366 (defun org-agenda-check-type (error &rest types)
21367 "Check if agenda buffer is of allowed type.
21368 If ERROR is non-nil, throw an error, otherwise just return nil."
21369 (if (memq org-agenda-type types)
21371 (if error
21372 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
21373 nil)))
21375 (defun org-agenda-quit ()
21376 "Exit agenda by removing the window or the buffer."
21377 (interactive)
21378 (let ((buf (current-buffer)))
21379 (if (not (one-window-p)) (delete-window))
21380 (kill-buffer buf)
21381 (org-agenda-maybe-reset-markers 'force)
21382 (org-columns-remove-overlays))
21383 ;; Maybe restore the pre-agenda window configuration.
21384 (and org-agenda-restore-windows-after-quit
21385 (not (eq org-agenda-window-setup 'other-frame))
21386 org-pre-agenda-window-conf
21387 (set-window-configuration org-pre-agenda-window-conf)))
21389 (defun org-agenda-exit ()
21390 "Exit agenda by removing the window or the buffer.
21391 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
21392 Org-mode buffers visited directly by the user will not be touched."
21393 (interactive)
21394 (org-release-buffers org-agenda-new-buffers)
21395 (setq org-agenda-new-buffers nil)
21396 (org-agenda-quit))
21398 (defun org-agenda-execute (arg)
21399 "Execute another agenda command, keeping same window.\\<global-map>
21400 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
21401 (interactive "P")
21402 (let ((org-agenda-window-setup 'current-window))
21403 (org-agenda arg)))
21405 (defun org-save-all-org-buffers ()
21406 "Save all Org-mode buffers without user confirmation."
21407 (interactive)
21408 (message "Saving all Org-mode buffers...")
21409 (save-some-buffers t 'org-mode-p)
21410 (message "Saving all Org-mode buffers... done"))
21412 (defun org-agenda-redo ()
21413 "Rebuild Agenda.
21414 When this is the global TODO list, a prefix argument will be interpreted."
21415 (interactive)
21416 (let* ((org-agenda-keep-modes t)
21417 (line (org-current-line))
21418 (window-line (- line (org-current-line (window-start))))
21419 (lprops (get 'org-agenda-redo-command 'org-lprops)))
21420 (message "Rebuilding agenda buffer...")
21421 (org-let lprops '(eval org-agenda-redo-command))
21422 (setq org-agenda-undo-list nil
21423 org-agenda-pending-undo-list nil)
21424 (message "Rebuilding agenda buffer...done")
21425 (goto-line line)
21426 (recenter window-line)))
21428 (defun org-agenda-goto-date (date)
21429 "Jump to DATE in agenda."
21430 (interactive (list (org-read-date)))
21431 (org-agenda-list nil date))
21433 (defun org-agenda-goto-today ()
21434 "Go to today."
21435 (interactive)
21436 (org-agenda-check-type t 'timeline 'agenda)
21437 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
21438 (cond
21439 (tdpos (goto-char tdpos))
21440 ((eq org-agenda-type 'agenda)
21441 (let* ((sd (time-to-days
21442 (time-subtract (current-time)
21443 (list 0 (* 3600 org-extend-today-until) 0))))
21444 (comp (org-agenda-compute-time-span sd org-agenda-span))
21445 (org-agenda-overriding-arguments org-agenda-last-arguments))
21446 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
21447 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
21448 (org-agenda-redo)
21449 (org-agenda-find-same-or-today-or-agenda)))
21450 (t (error "Cannot find today")))))
21452 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
21453 (goto-char
21454 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
21455 (text-property-any (point-min) (point-max) 'org-today t)
21456 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
21457 (point-min))))
21459 (defun org-agenda-later (arg)
21460 "Go forward in time by thee current span.
21461 With prefix ARG, go forward that many times the current span."
21462 (interactive "p")
21463 (org-agenda-check-type t 'agenda)
21464 (let* ((span org-agenda-span)
21465 (sd org-starting-day)
21466 (greg (calendar-gregorian-from-absolute sd))
21467 (cnt (get-text-property (point) 'org-day-cnt))
21468 greg2 nd)
21469 (cond
21470 ((eq span 'day)
21471 (setq sd (+ arg sd) nd 1))
21472 ((eq span 'week)
21473 (setq sd (+ (* 7 arg) sd) nd 7))
21474 ((eq span 'month)
21475 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
21476 sd (calendar-absolute-from-gregorian greg2))
21477 (setcar greg2 (1+ (car greg2)))
21478 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
21479 ((eq span 'year)
21480 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
21481 sd (calendar-absolute-from-gregorian greg2))
21482 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
21483 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
21484 (let ((org-agenda-overriding-arguments
21485 (list (car org-agenda-last-arguments) sd nd t)))
21486 (org-agenda-redo)
21487 (org-agenda-find-same-or-today-or-agenda cnt))))
21489 (defun org-agenda-earlier (arg)
21490 "Go backward in time by the current span.
21491 With prefix ARG, go backward that many times the current span."
21492 (interactive "p")
21493 (org-agenda-later (- arg)))
21495 (defun org-agenda-day-view ()
21496 "Switch to daily view for agenda."
21497 (interactive)
21498 (setq org-agenda-ndays 1)
21499 (org-agenda-change-time-span 'day))
21500 (defun org-agenda-week-view ()
21501 "Switch to daily view for agenda."
21502 (interactive)
21503 (setq org-agenda-ndays 7)
21504 (org-agenda-change-time-span 'week))
21505 (defun org-agenda-month-view ()
21506 "Switch to daily view for agenda."
21507 (interactive)
21508 (org-agenda-change-time-span 'month))
21509 (defun org-agenda-year-view ()
21510 "Switch to daily view for agenda."
21511 (interactive)
21512 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
21513 (org-agenda-change-time-span 'year)
21514 (error "Abort")))
21516 (defun org-agenda-change-time-span (span)
21517 "Change the agenda view to SPAN.
21518 SPAN may be `day', `week', `month', `year'."
21519 (org-agenda-check-type t 'agenda)
21520 (if (equal org-agenda-span span)
21521 (error "Viewing span is already \"%s\"" span))
21522 (let* ((sd (or (get-text-property (point) 'day)
21523 org-starting-day))
21524 (computed (org-agenda-compute-time-span sd span))
21525 (org-agenda-overriding-arguments
21526 (list (car org-agenda-last-arguments)
21527 (car computed) (cdr computed) t)))
21528 (org-agenda-redo)
21529 (org-agenda-find-same-or-today-or-agenda))
21530 (org-agenda-set-mode-name)
21531 (message "Switched to %s view" span))
21533 (defun org-agenda-compute-time-span (sd span)
21534 "Compute starting date and number of days for agenda.
21535 SPAN may be `day', `week', `month', `year'. The return value
21536 is a cons cell with the starting date and the number of days,
21537 so that the date SD will be in that range."
21538 (let* ((greg (calendar-gregorian-from-absolute sd))
21540 (cond
21541 ((eq span 'day)
21542 (setq nd 1))
21543 ((eq span 'week)
21544 (let* ((nt (calendar-day-of-week
21545 (calendar-gregorian-from-absolute sd)))
21546 (d (if org-agenda-start-on-weekday
21547 (- nt org-agenda-start-on-weekday)
21548 0)))
21549 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
21550 (setq nd 7)))
21551 ((eq span 'month)
21552 (setq sd (calendar-absolute-from-gregorian
21553 (list (car greg) 1 (nth 2 greg)))
21554 nd (- (calendar-absolute-from-gregorian
21555 (list (1+ (car greg)) 1 (nth 2 greg)))
21556 sd)))
21557 ((eq span 'year)
21558 (setq sd (calendar-absolute-from-gregorian
21559 (list 1 1 (nth 2 greg)))
21560 nd (- (calendar-absolute-from-gregorian
21561 (list 1 1 (1+ (nth 2 greg))))
21562 sd))))
21563 (cons sd nd)))
21565 ;; FIXME: does not work if user makes date format that starts with a blank
21566 (defun org-agenda-next-date-line (&optional arg)
21567 "Jump to the next line indicating a date in agenda buffer."
21568 (interactive "p")
21569 (org-agenda-check-type t 'agenda 'timeline)
21570 (beginning-of-line 1)
21571 (if (looking-at "^\\S-") (forward-char 1))
21572 (if (not (re-search-forward "^\\S-" nil t arg))
21573 (progn
21574 (backward-char 1)
21575 (error "No next date after this line in this buffer")))
21576 (goto-char (match-beginning 0)))
21578 (defun org-agenda-previous-date-line (&optional arg)
21579 "Jump to the previous line indicating a date in agenda buffer."
21580 (interactive "p")
21581 (org-agenda-check-type t 'agenda 'timeline)
21582 (beginning-of-line 1)
21583 (if (not (re-search-backward "^\\S-" nil t arg))
21584 (error "No previous date before this line in this buffer")))
21586 ;; Initialize the highlight
21587 (defvar org-hl (org-make-overlay 1 1))
21588 (org-overlay-put org-hl 'face 'highlight)
21590 (defun org-highlight (begin end &optional buffer)
21591 "Highlight a region with overlay."
21592 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
21593 org-hl begin end (or buffer (current-buffer))))
21595 (defun org-unhighlight ()
21596 "Detach overlay INDEX."
21597 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
21599 ;; FIXME this is currently not used.
21600 (defun org-highlight-until-next-command (beg end &optional buffer)
21601 (org-highlight beg end buffer)
21602 (add-hook 'pre-command-hook 'org-unhighlight-once))
21603 (defun org-unhighlight-once ()
21604 (remove-hook 'pre-command-hook 'org-unhighlight-once)
21605 (org-unhighlight))
21607 (defun org-agenda-follow-mode ()
21608 "Toggle follow mode in an agenda buffer."
21609 (interactive)
21610 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
21611 (org-agenda-set-mode-name)
21612 (message "Follow mode is %s"
21613 (if org-agenda-follow-mode "on" "off")))
21615 (defun org-agenda-log-mode ()
21616 "Toggle log mode in an agenda buffer."
21617 (interactive)
21618 (org-agenda-check-type t 'agenda 'timeline)
21619 (setq org-agenda-show-log (not org-agenda-show-log))
21620 (org-agenda-set-mode-name)
21621 (org-agenda-redo)
21622 (message "Log mode is %s"
21623 (if org-agenda-show-log "on" "off")))
21625 (defun org-agenda-toggle-diary ()
21626 "Toggle diary inclusion in an agenda buffer."
21627 (interactive)
21628 (org-agenda-check-type t 'agenda)
21629 (setq org-agenda-include-diary (not org-agenda-include-diary))
21630 (org-agenda-redo)
21631 (org-agenda-set-mode-name)
21632 (message "Diary inclusion turned %s"
21633 (if org-agenda-include-diary "on" "off")))
21635 (defun org-agenda-toggle-time-grid ()
21636 "Toggle time grid in an agenda buffer."
21637 (interactive)
21638 (org-agenda-check-type t 'agenda)
21639 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
21640 (org-agenda-redo)
21641 (org-agenda-set-mode-name)
21642 (message "Time-grid turned %s"
21643 (if org-agenda-use-time-grid "on" "off")))
21645 (defun org-agenda-set-mode-name ()
21646 "Set the mode name to indicate all the small mode settings."
21647 (setq mode-name
21648 (concat "Org-Agenda"
21649 (if (equal org-agenda-ndays 1) " Day" "")
21650 (if (equal org-agenda-ndays 7) " Week" "")
21651 (if org-agenda-follow-mode " Follow" "")
21652 (if org-agenda-include-diary " Diary" "")
21653 (if org-agenda-use-time-grid " Grid" "")
21654 (if org-agenda-show-log " Log" "")))
21655 (force-mode-line-update))
21657 (defun org-agenda-post-command-hook ()
21658 (and (eolp) (not (bolp)) (backward-char 1))
21659 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
21660 (if (and org-agenda-follow-mode
21661 (get-text-property (point) 'org-marker))
21662 (org-agenda-show)))
21664 (defun org-agenda-show-priority ()
21665 "Show the priority of the current item.
21666 This priority is composed of the main priority given with the [#A] cookies,
21667 and by additional input from the age of a schedules or deadline entry."
21668 (interactive)
21669 (let* ((pri (get-text-property (point-at-bol) 'priority)))
21670 (message "Priority is %d" (if pri pri -1000))))
21672 (defun org-agenda-show-tags ()
21673 "Show the tags applicable to the current item."
21674 (interactive)
21675 (let* ((tags (get-text-property (point-at-bol) 'tags)))
21676 (if tags
21677 (message "Tags are :%s:"
21678 (org-no-properties (mapconcat 'identity tags ":")))
21679 (message "No tags associated with this line"))))
21681 (defun org-agenda-goto (&optional highlight)
21682 "Go to the Org-mode file which contains the item at point."
21683 (interactive)
21684 (let* ((marker (or (get-text-property (point) 'org-marker)
21685 (org-agenda-error)))
21686 (buffer (marker-buffer marker))
21687 (pos (marker-position marker)))
21688 (switch-to-buffer-other-window buffer)
21689 (widen)
21690 (goto-char pos)
21691 (when (org-mode-p)
21692 (org-show-context 'agenda)
21693 (save-excursion
21694 (and (outline-next-heading)
21695 (org-flag-heading nil)))) ; show the next heading
21696 (run-hooks 'org-agenda-after-show-hook)
21697 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
21699 (defvar org-agenda-after-show-hook nil
21700 "Normal hook run after an item has been shown from the agenda.
21701 Point is in the buffer where the item originated.")
21703 (defun org-agenda-kill ()
21704 "Kill the entry or subtree belonging to the current agenda entry."
21705 (interactive)
21706 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
21707 (let* ((marker (or (get-text-property (point) 'org-marker)
21708 (org-agenda-error)))
21709 (buffer (marker-buffer marker))
21710 (pos (marker-position marker))
21711 (type (get-text-property (point) 'type))
21712 dbeg dend (n 0) conf)
21713 (org-with-remote-undo buffer
21714 (with-current-buffer buffer
21715 (save-excursion
21716 (goto-char pos)
21717 (if (and (org-mode-p) (not (member type '("sexp"))))
21718 (setq dbeg (progn (org-back-to-heading t) (point))
21719 dend (org-end-of-subtree t t))
21720 (setq dbeg (point-at-bol)
21721 dend (min (point-max) (1+ (point-at-eol)))))
21722 (goto-char dbeg)
21723 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
21724 (setq conf (or (eq t org-agenda-confirm-kill)
21725 (and (numberp org-agenda-confirm-kill)
21726 (> n org-agenda-confirm-kill))))
21727 (and conf
21728 (not (y-or-n-p
21729 (format "Delete entry with %d lines in buffer \"%s\"? "
21730 n (buffer-name buffer))))
21731 (error "Abort"))
21732 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
21733 (with-current-buffer buffer (delete-region dbeg dend))
21734 (message "Agenda item and source killed"))))
21736 (defun org-agenda-archive ()
21737 "Kill the entry or subtree belonging to the current agenda entry."
21738 (interactive)
21739 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
21740 (let* ((marker (or (get-text-property (point) 'org-marker)
21741 (org-agenda-error)))
21742 (buffer (marker-buffer marker))
21743 (pos (marker-position marker)))
21744 (org-with-remote-undo buffer
21745 (with-current-buffer buffer
21746 (if (org-mode-p)
21747 (save-excursion
21748 (goto-char pos)
21749 (org-remove-subtree-entries-from-agenda)
21750 (org-back-to-heading t)
21751 (org-archive-subtree))
21752 (error "Archiving works only in Org-mode files"))))))
21754 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
21755 "Remove all lines in the agenda that correspond to a given subtree.
21756 The subtree is the one in buffer BUF, starting at BEG and ending at END.
21757 If this information is not given, the function uses the tree at point."
21758 (let ((buf (or buf (current-buffer))) m p)
21759 (save-excursion
21760 (unless (and beg end)
21761 (org-back-to-heading t)
21762 (setq beg (point))
21763 (org-end-of-subtree t)
21764 (setq end (point)))
21765 (set-buffer (get-buffer org-agenda-buffer-name))
21766 (save-excursion
21767 (goto-char (point-max))
21768 (beginning-of-line 1)
21769 (while (not (bobp))
21770 (when (and (setq m (get-text-property (point) 'org-marker))
21771 (equal buf (marker-buffer m))
21772 (setq p (marker-position m))
21773 (>= p beg)
21774 (<= p end))
21775 (let ((inhibit-read-only t))
21776 (delete-region (point-at-bol) (1+ (point-at-eol)))))
21777 (beginning-of-line 0))))))
21779 (defun org-agenda-open-link ()
21780 "Follow the link in the current line, if any."
21781 (interactive)
21782 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
21783 (save-excursion
21784 (save-restriction
21785 (narrow-to-region (point-at-bol) (point-at-eol))
21786 (org-open-at-point))))
21788 (defun org-agenda-copy-local-variable (var)
21789 "Get a variable from a referenced buffer and install it here."
21790 (let ((m (get-text-property (point) 'org-marker)))
21791 (when (and m (buffer-live-p (marker-buffer m)))
21792 (org-set-local var (with-current-buffer (marker-buffer m)
21793 (symbol-value var))))))
21795 (defun org-agenda-switch-to (&optional delete-other-windows)
21796 "Go to the Org-mode file which contains the item at point."
21797 (interactive)
21798 (let* ((marker (or (get-text-property (point) 'org-marker)
21799 (org-agenda-error)))
21800 (buffer (marker-buffer marker))
21801 (pos (marker-position marker)))
21802 (switch-to-buffer buffer)
21803 (and delete-other-windows (delete-other-windows))
21804 (widen)
21805 (goto-char pos)
21806 (when (org-mode-p)
21807 (org-show-context 'agenda)
21808 (save-excursion
21809 (and (outline-next-heading)
21810 (org-flag-heading nil)))))) ; show the next heading
21812 (defun org-agenda-goto-mouse (ev)
21813 "Go to the Org-mode file which contains the item at the mouse click."
21814 (interactive "e")
21815 (mouse-set-point ev)
21816 (org-agenda-goto))
21818 (defun org-agenda-show ()
21819 "Display the Org-mode file which contains the item at point."
21820 (interactive)
21821 (let ((win (selected-window)))
21822 (org-agenda-goto t)
21823 (select-window win)))
21825 (defun org-agenda-recenter (arg)
21826 "Display the Org-mode file which contains the item at point and recenter."
21827 (interactive "P")
21828 (let ((win (selected-window)))
21829 (org-agenda-goto t)
21830 (recenter arg)
21831 (select-window win)))
21833 (defun org-agenda-show-mouse (ev)
21834 "Display the Org-mode file which contains the item at the mouse click."
21835 (interactive "e")
21836 (mouse-set-point ev)
21837 (org-agenda-show))
21839 (defun org-agenda-check-no-diary ()
21840 "Check if the entry is a diary link and abort if yes."
21841 (if (get-text-property (point) 'org-agenda-diary-link)
21842 (org-agenda-error)))
21844 (defun org-agenda-error ()
21845 (error "Command not allowed in this line"))
21847 (defun org-agenda-tree-to-indirect-buffer ()
21848 "Show the subtree corresponding to the current entry in an indirect buffer.
21849 This calls the command `org-tree-to-indirect-buffer' from the original
21850 Org-mode buffer.
21851 With numerical prefix arg ARG, go up to this level and then take that tree.
21852 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
21853 dedicated frame)."
21854 (interactive)
21855 (org-agenda-check-no-diary)
21856 (let* ((marker (or (get-text-property (point) 'org-marker)
21857 (org-agenda-error)))
21858 (buffer (marker-buffer marker))
21859 (pos (marker-position marker)))
21860 (with-current-buffer buffer
21861 (save-excursion
21862 (goto-char pos)
21863 (call-interactively 'org-tree-to-indirect-buffer)))))
21865 (defvar org-last-heading-marker (make-marker)
21866 "Marker pointing to the headline that last changed its TODO state
21867 by a remote command from the agenda.")
21869 (defun org-agenda-todo-nextset ()
21870 "Switch TODO entry to next sequence."
21871 (interactive)
21872 (org-agenda-todo 'nextset))
21874 (defun org-agenda-todo-previousset ()
21875 "Switch TODO entry to previous sequence."
21876 (interactive)
21877 (org-agenda-todo 'previousset))
21879 (defun org-agenda-todo (&optional arg)
21880 "Cycle TODO state of line at point, also in Org-mode file.
21881 This changes the line at point, all other lines in the agenda referring to
21882 the same tree node, and the headline of the tree node in the Org-mode file."
21883 (interactive "P")
21884 (org-agenda-check-no-diary)
21885 (let* ((col (current-column))
21886 (marker (or (get-text-property (point) 'org-marker)
21887 (org-agenda-error)))
21888 (buffer (marker-buffer marker))
21889 (pos (marker-position marker))
21890 (hdmarker (get-text-property (point) 'org-hd-marker))
21891 (inhibit-read-only t)
21892 newhead)
21893 (org-with-remote-undo buffer
21894 (with-current-buffer buffer
21895 (widen)
21896 (goto-char pos)
21897 (org-show-context 'agenda)
21898 (save-excursion
21899 (and (outline-next-heading)
21900 (org-flag-heading nil))) ; show the next heading
21901 (org-todo arg)
21902 (and (bolp) (forward-char 1))
21903 (setq newhead (org-get-heading))
21904 (save-excursion
21905 (org-back-to-heading)
21906 (move-marker org-last-heading-marker (point))))
21907 (beginning-of-line 1)
21908 (save-excursion
21909 (org-agenda-change-all-lines newhead hdmarker 'fixface))
21910 (move-to-column col))))
21912 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
21913 "Change all lines in the agenda buffer which match HDMARKER.
21914 The new content of the line will be NEWHEAD (as modified by
21915 `org-format-agenda-item'). HDMARKER is checked with
21916 `equal' against all `org-hd-marker' text properties in the file.
21917 If FIXFACE is non-nil, the face of each item is modified acording to
21918 the new TODO state."
21919 (let* ((inhibit-read-only t)
21920 props m pl undone-face done-face finish new dotime cat tags)
21921 (save-excursion
21922 (goto-char (point-max))
21923 (beginning-of-line 1)
21924 (while (not finish)
21925 (setq finish (bobp))
21926 (when (and (setq m (get-text-property (point) 'org-hd-marker))
21927 (equal m hdmarker))
21928 (setq props (text-properties-at (point))
21929 dotime (get-text-property (point) 'dotime)
21930 cat (get-text-property (point) 'org-category)
21931 tags (get-text-property (point) 'tags)
21932 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
21933 pl (get-text-property (point) 'prefix-length)
21934 undone-face (get-text-property (point) 'undone-face)
21935 done-face (get-text-property (point) 'done-face))
21936 (move-to-column pl)
21937 (cond
21938 ((equal new "")
21939 (beginning-of-line 1)
21940 (and (looking-at ".*\n?") (replace-match "")))
21941 ((looking-at ".*")
21942 (replace-match new t t)
21943 (beginning-of-line 1)
21944 (add-text-properties (point-at-bol) (point-at-eol) props)
21945 (when fixface
21946 (add-text-properties
21947 (point-at-bol) (point-at-eol)
21948 (list 'face
21949 (if org-last-todo-state-is-todo
21950 undone-face done-face))))
21951 (org-agenda-highlight-todo 'line)
21952 (beginning-of-line 1))
21953 (t (error "Line update did not work"))))
21954 (beginning-of-line 0)))
21955 (org-finalize-agenda)))
21957 (defun org-agenda-align-tags (&optional line)
21958 "Align all tags in agenda items to `org-agenda-tags-column'."
21959 (let ((inhibit-read-only t) l c)
21960 (save-excursion
21961 (goto-char (if line (point-at-bol) (point-min)))
21962 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
21963 (if line (point-at-eol) nil) t)
21964 (add-text-properties
21965 (match-beginning 2) (match-end 2)
21966 (list 'face (list 'org-tag (get-text-property
21967 (match-beginning 2) 'face))))
21968 (setq l (- (match-end 2) (match-beginning 2))
21969 c (if (< org-agenda-tags-column 0)
21970 (- (abs org-agenda-tags-column) l)
21971 org-agenda-tags-column))
21972 (delete-region (match-beginning 1) (match-end 1))
21973 (goto-char (match-beginning 1))
21974 (insert (org-add-props
21975 (make-string (max 1 (- c (current-column))) ?\ )
21976 (text-properties-at (point))))))))
21978 (defun org-agenda-priority-up ()
21979 "Increase the priority of line at point, also in Org-mode file."
21980 (interactive)
21981 (org-agenda-priority 'up))
21983 (defun org-agenda-priority-down ()
21984 "Decrease the priority of line at point, also in Org-mode file."
21985 (interactive)
21986 (org-agenda-priority 'down))
21988 (defun org-agenda-priority (&optional force-direction)
21989 "Set the priority of line at point, also in Org-mode file.
21990 This changes the line at point, all other lines in the agenda referring to
21991 the same tree node, and the headline of the tree node in the Org-mode file."
21992 (interactive)
21993 (org-agenda-check-no-diary)
21994 (let* ((marker (or (get-text-property (point) 'org-marker)
21995 (org-agenda-error)))
21996 (hdmarker (get-text-property (point) 'org-hd-marker))
21997 (buffer (marker-buffer hdmarker))
21998 (pos (marker-position hdmarker))
21999 (inhibit-read-only t)
22000 newhead)
22001 (org-with-remote-undo buffer
22002 (with-current-buffer buffer
22003 (widen)
22004 (goto-char pos)
22005 (org-show-context 'agenda)
22006 (save-excursion
22007 (and (outline-next-heading)
22008 (org-flag-heading nil))) ; show the next heading
22009 (funcall 'org-priority force-direction)
22010 (end-of-line 1)
22011 (setq newhead (org-get-heading)))
22012 (org-agenda-change-all-lines newhead hdmarker)
22013 (beginning-of-line 1))))
22015 (defun org-get-tags-at (&optional pos)
22016 "Get a list of all headline tags applicable at POS.
22017 POS defaults to point. If tags are inherited, the list contains
22018 the targets in the same sequence as the headlines appear, i.e.
22019 the tags of the current headline come last."
22020 (interactive)
22021 (let (tags lastpos)
22022 (save-excursion
22023 (save-restriction
22024 (widen)
22025 (goto-char (or pos (point)))
22026 (save-match-data
22027 (org-back-to-heading t)
22028 (condition-case nil
22029 (while (not (equal lastpos (point)))
22030 (setq lastpos (point))
22031 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
22032 (setq tags (append (org-split-string
22033 (org-match-string-no-properties 1) ":")
22034 tags)))
22035 (or org-use-tag-inheritance (error ""))
22036 (org-up-heading-all 1))
22037 (error nil))))
22038 tags)))
22040 ;; FIXME: should fix the tags property of the agenda line.
22041 (defun org-agenda-set-tags ()
22042 "Set tags for the current headline."
22043 (interactive)
22044 (org-agenda-check-no-diary)
22045 (if (and (org-region-active-p) (interactive-p))
22046 (call-interactively 'org-change-tag-in-region)
22047 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22048 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22049 (org-agenda-error)))
22050 (buffer (marker-buffer hdmarker))
22051 (pos (marker-position hdmarker))
22052 (inhibit-read-only t)
22053 newhead)
22054 (org-with-remote-undo buffer
22055 (with-current-buffer buffer
22056 (widen)
22057 (goto-char pos)
22058 (save-excursion
22059 (org-show-context 'agenda))
22060 (save-excursion
22061 (and (outline-next-heading)
22062 (org-flag-heading nil))) ; show the next heading
22063 (goto-char pos)
22064 (call-interactively 'org-set-tags)
22065 (end-of-line 1)
22066 (setq newhead (org-get-heading)))
22067 (org-agenda-change-all-lines newhead hdmarker)
22068 (beginning-of-line 1)))))
22070 (defun org-agenda-toggle-archive-tag ()
22071 "Toggle the archive tag for the current entry."
22072 (interactive)
22073 (org-agenda-check-no-diary)
22074 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22075 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22076 (org-agenda-error)))
22077 (buffer (marker-buffer hdmarker))
22078 (pos (marker-position hdmarker))
22079 (inhibit-read-only t)
22080 newhead)
22081 (org-with-remote-undo buffer
22082 (with-current-buffer buffer
22083 (widen)
22084 (goto-char pos)
22085 (org-show-context 'agenda)
22086 (save-excursion
22087 (and (outline-next-heading)
22088 (org-flag-heading nil))) ; show the next heading
22089 (call-interactively 'org-toggle-archive-tag)
22090 (end-of-line 1)
22091 (setq newhead (org-get-heading)))
22092 (org-agenda-change-all-lines newhead hdmarker)
22093 (beginning-of-line 1))))
22095 (defun org-agenda-date-later (arg &optional what)
22096 "Change the date of this item to one day later."
22097 (interactive "p")
22098 (org-agenda-check-type t 'agenda 'timeline)
22099 (org-agenda-check-no-diary)
22100 (let* ((marker (or (get-text-property (point) 'org-marker)
22101 (org-agenda-error)))
22102 (buffer (marker-buffer marker))
22103 (pos (marker-position marker)))
22104 (org-with-remote-undo buffer
22105 (with-current-buffer buffer
22106 (widen)
22107 (goto-char pos)
22108 (if (not (org-at-timestamp-p))
22109 (error "Cannot find time stamp"))
22110 (org-timestamp-change arg (or what 'day)))
22111 (org-agenda-show-new-time marker org-last-changed-timestamp))
22112 (message "Time stamp changed to %s" org-last-changed-timestamp)))
22114 (defun org-agenda-date-earlier (arg &optional what)
22115 "Change the date of this item to one day earlier."
22116 (interactive "p")
22117 (org-agenda-date-later (- arg) what))
22119 (defun org-agenda-show-new-time (marker stamp &optional prefix)
22120 "Show new date stamp via text properties."
22121 ;; We use text properties to make this undoable
22122 (let ((inhibit-read-only t))
22123 (setq stamp (concat " " prefix " => " stamp))
22124 (save-excursion
22125 (goto-char (point-max))
22126 (while (not (bobp))
22127 (when (equal marker (get-text-property (point) 'org-marker))
22128 (move-to-column (- (window-width) (length stamp)) t)
22129 (if (featurep 'xemacs)
22130 ;; Use `duplicable' property to trigger undo recording
22131 (let ((ex (make-extent nil nil))
22132 (gl (make-glyph stamp)))
22133 (set-glyph-face gl 'secondary-selection)
22134 (set-extent-properties
22135 ex (list 'invisible t 'end-glyph gl 'duplicable t))
22136 (insert-extent ex (1- (point)) (point-at-eol)))
22137 (add-text-properties
22138 (1- (point)) (point-at-eol)
22139 (list 'display (org-add-props stamp nil
22140 'face 'secondary-selection))))
22141 (beginning-of-line 1))
22142 (beginning-of-line 0)))))
22144 (defun org-agenda-date-prompt (arg)
22145 "Change the date of this item. Date is prompted for, with default today.
22146 The prefix ARG is passed to the `org-time-stamp' command and can therefore
22147 be used to request time specification in the time stamp."
22148 (interactive "P")
22149 (org-agenda-check-type t 'agenda 'timeline)
22150 (org-agenda-check-no-diary)
22151 (let* ((marker (or (get-text-property (point) 'org-marker)
22152 (org-agenda-error)))
22153 (buffer (marker-buffer marker))
22154 (pos (marker-position marker)))
22155 (org-with-remote-undo buffer
22156 (with-current-buffer buffer
22157 (widen)
22158 (goto-char pos)
22159 (if (not (org-at-timestamp-p))
22160 (error "Cannot find time stamp"))
22161 (org-time-stamp arg)
22162 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
22164 (defun org-agenda-schedule (arg)
22165 "Schedule the item at point."
22166 (interactive "P")
22167 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22168 (org-agenda-check-no-diary)
22169 (let* ((marker (or (get-text-property (point) 'org-marker)
22170 (org-agenda-error)))
22171 (buffer (marker-buffer marker))
22172 (pos (marker-position marker))
22173 (org-insert-labeled-timestamps-at-point nil)
22175 (org-with-remote-undo buffer
22176 (with-current-buffer buffer
22177 (widen)
22178 (goto-char pos)
22179 (setq ts (org-schedule arg)))
22180 (org-agenda-show-new-time marker ts "S"))
22181 (message "Item scheduled for %s" ts)))
22183 (defun org-agenda-deadline (arg)
22184 "Schedule the item at point."
22185 (interactive "P")
22186 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22187 (org-agenda-check-no-diary)
22188 (let* ((marker (or (get-text-property (point) 'org-marker)
22189 (org-agenda-error)))
22190 (buffer (marker-buffer marker))
22191 (pos (marker-position marker))
22192 (org-insert-labeled-timestamps-at-point nil)
22194 (org-with-remote-undo buffer
22195 (with-current-buffer buffer
22196 (widen)
22197 (goto-char pos)
22198 (setq ts (org-deadline arg)))
22199 (org-agenda-show-new-time marker ts "S"))
22200 (message "Deadline for this item set to %s" ts)))
22202 (defun org-get-heading (&optional no-tags)
22203 "Return the heading of the current entry, without the stars."
22204 (save-excursion
22205 (org-back-to-heading t)
22206 (if (looking-at
22207 (if no-tags
22208 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
22209 "\\*+[ \t]+\\([^\r\n]*\\)"))
22210 (match-string 1) "")))
22212 (defun org-agenda-clock-in (&optional arg)
22213 "Start the clock on the currently selected item."
22214 (interactive "P")
22215 (org-agenda-check-no-diary)
22216 (let* ((marker (or (get-text-property (point) 'org-marker)
22217 (org-agenda-error)))
22218 (pos (marker-position marker)))
22219 (org-with-remote-undo (marker-buffer marker)
22220 (with-current-buffer (marker-buffer marker)
22221 (widen)
22222 (goto-char pos)
22223 (org-clock-in)))))
22225 (defun org-agenda-clock-out (&optional arg)
22226 "Stop the currently running clock."
22227 (interactive "P")
22228 (unless (marker-buffer org-clock-marker)
22229 (error "No running clock"))
22230 (org-with-remote-undo (marker-buffer org-clock-marker)
22231 (org-clock-out)))
22233 (defun org-agenda-clock-cancel (&optional arg)
22234 "Cancel the currently running clock."
22235 (interactive "P")
22236 (unless (marker-buffer org-clock-marker)
22237 (error "No running clock"))
22238 (org-with-remote-undo (marker-buffer org-clock-marker)
22239 (org-clock-cancel)))
22241 (defun org-agenda-diary-entry ()
22242 "Make a diary entry, like the `i' command from the calendar.
22243 All the standard commands work: block, weekly etc."
22244 (interactive)
22245 (org-agenda-check-type t 'agenda 'timeline)
22246 (require 'diary-lib)
22247 (let* ((char (progn
22248 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
22249 (read-char-exclusive)))
22250 (cmd (cdr (assoc char
22251 '((?d . insert-diary-entry)
22252 (?w . insert-weekly-diary-entry)
22253 (?m . insert-monthly-diary-entry)
22254 (?y . insert-yearly-diary-entry)
22255 (?a . insert-anniversary-diary-entry)
22256 (?b . insert-block-diary-entry)
22257 (?c . insert-cyclic-diary-entry)))))
22258 (oldf (symbol-function 'calendar-cursor-to-date))
22259 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
22260 (point (point))
22261 (mark (or (mark t) (point))))
22262 (unless cmd
22263 (error "No command associated with <%c>" char))
22264 (unless (and (get-text-property point 'day)
22265 (or (not (equal ?b char))
22266 (get-text-property mark 'day)))
22267 (error "Don't know which date to use for diary entry"))
22268 ;; We implement this by hacking the `calendar-cursor-to-date' function
22269 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
22270 (let ((calendar-mark-ring
22271 (list (calendar-gregorian-from-absolute
22272 (or (get-text-property mark 'day)
22273 (get-text-property point 'day))))))
22274 (unwind-protect
22275 (progn
22276 (fset 'calendar-cursor-to-date
22277 (lambda (&optional error)
22278 (calendar-gregorian-from-absolute
22279 (get-text-property point 'day))))
22280 (call-interactively cmd))
22281 (fset 'calendar-cursor-to-date oldf)))))
22284 (defun org-agenda-execute-calendar-command (cmd)
22285 "Execute a calendar command from the agenda, with the date associated to
22286 the cursor position."
22287 (org-agenda-check-type t 'agenda 'timeline)
22288 (require 'diary-lib)
22289 (unless (get-text-property (point) 'day)
22290 (error "Don't know which date to use for calendar command"))
22291 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
22292 (point (point))
22293 (date (calendar-gregorian-from-absolute
22294 (get-text-property point 'day)))
22295 ;; the following 3 vars are needed in the calendar
22296 (displayed-day (extract-calendar-day date))
22297 (displayed-month (extract-calendar-month date))
22298 (displayed-year (extract-calendar-year date)))
22299 (unwind-protect
22300 (progn
22301 (fset 'calendar-cursor-to-date
22302 (lambda (&optional error)
22303 (calendar-gregorian-from-absolute
22304 (get-text-property point 'day))))
22305 (call-interactively cmd))
22306 (fset 'calendar-cursor-to-date oldf))))
22308 (defun org-agenda-phases-of-moon ()
22309 "Display the phases of the moon for the 3 months around the cursor date."
22310 (interactive)
22311 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
22313 (defun org-agenda-holidays ()
22314 "Display the holidays for the 3 months around the cursor date."
22315 (interactive)
22316 (org-agenda-execute-calendar-command 'list-calendar-holidays))
22318 (defun org-agenda-sunrise-sunset (arg)
22319 "Display sunrise and sunset for the cursor date.
22320 Latitude and longitude can be specified with the variables
22321 `calendar-latitude' and `calendar-longitude'. When called with prefix
22322 argument, latitude and longitude will be prompted for."
22323 (interactive "P")
22324 (let ((calendar-longitude (if arg nil calendar-longitude))
22325 (calendar-latitude (if arg nil calendar-latitude))
22326 (calendar-location-name
22327 (if arg "the given coordinates" calendar-location-name)))
22328 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
22330 (defun org-agenda-goto-calendar ()
22331 "Open the Emacs calendar with the date at the cursor."
22332 (interactive)
22333 (org-agenda-check-type t 'agenda 'timeline)
22334 (let* ((day (or (get-text-property (point) 'day)
22335 (error "Don't know which date to open in calendar")))
22336 (date (calendar-gregorian-from-absolute day))
22337 (calendar-move-hook nil)
22338 (view-calendar-holidays-initially nil)
22339 (view-diary-entries-initially nil))
22340 (calendar)
22341 (calendar-goto-date date)))
22343 (defun org-calendar-goto-agenda ()
22344 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
22345 This is a command that has to be installed in `calendar-mode-map'."
22346 (interactive)
22347 (org-agenda-list nil (calendar-absolute-from-gregorian
22348 (calendar-cursor-to-date))
22349 nil))
22351 (defun org-agenda-convert-date ()
22352 (interactive)
22353 (org-agenda-check-type t 'agenda 'timeline)
22354 (let ((day (get-text-property (point) 'day))
22355 date s)
22356 (unless day
22357 (error "Don't know which date to convert"))
22358 (setq date (calendar-gregorian-from-absolute day))
22359 (setq s (concat
22360 "Gregorian: " (calendar-date-string date) "\n"
22361 "ISO: " (calendar-iso-date-string date) "\n"
22362 "Day of Yr: " (calendar-day-of-year-string date) "\n"
22363 "Julian: " (calendar-julian-date-string date) "\n"
22364 "Astron. JD: " (calendar-astro-date-string date)
22365 " (Julian date number at noon UTC)\n"
22366 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
22367 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
22368 "French: " (calendar-french-date-string date) "\n"
22369 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
22370 "Mayan: " (calendar-mayan-date-string date) "\n"
22371 "Coptic: " (calendar-coptic-date-string date) "\n"
22372 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
22373 "Persian: " (calendar-persian-date-string date) "\n"
22374 "Chinese: " (calendar-chinese-date-string date) "\n"))
22375 (with-output-to-temp-buffer "*Dates*"
22376 (princ s))
22377 (if (fboundp 'fit-window-to-buffer)
22378 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
22381 ;;;; Embedded LaTeX
22383 (defvar org-cdlatex-mode-map (make-sparse-keymap)
22384 "Keymap for the minor `org-cdlatex-mode'.")
22386 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
22387 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
22388 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
22389 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
22390 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
22392 (defvar org-cdlatex-texmathp-advice-is-done nil
22393 "Flag remembering if we have applied the advice to texmathp already.")
22395 (define-minor-mode org-cdlatex-mode
22396 "Toggle the minor `org-cdlatex-mode'.
22397 This mode supports entering LaTeX environment and math in LaTeX fragments
22398 in Org-mode.
22399 \\{org-cdlatex-mode-map}"
22400 nil " OCDL" nil
22401 (when org-cdlatex-mode (require 'cdlatex))
22402 (unless org-cdlatex-texmathp-advice-is-done
22403 (setq org-cdlatex-texmathp-advice-is-done t)
22404 (defadvice texmathp (around org-math-always-on activate)
22405 "Always return t in org-mode buffers.
22406 This is because we want to insert math symbols without dollars even outside
22407 the LaTeX math segments. If Orgmode thinks that point is actually inside
22408 en embedded LaTeX fragement, let texmathp do its job.
22409 \\[org-cdlatex-mode-map]"
22410 (interactive)
22411 (let (p)
22412 (cond
22413 ((not (org-mode-p)) ad-do-it)
22414 ((eq this-command 'cdlatex-math-symbol)
22415 (setq ad-return-value t
22416 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
22418 (let ((p (org-inside-LaTeX-fragment-p)))
22419 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
22420 (setq ad-return-value t
22421 texmathp-why '("Org-mode embedded math" . 0))
22422 (if p ad-do-it)))))))))
22424 (defun turn-on-org-cdlatex ()
22425 "Unconditionally turn on `org-cdlatex-mode'."
22426 (org-cdlatex-mode 1))
22428 (defun org-inside-LaTeX-fragment-p ()
22429 "Test if point is inside a LaTeX fragment.
22430 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
22431 sequence appearing also before point.
22432 Even though the matchers for math are configurable, this function assumes
22433 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
22434 delimiters are skipped when they have been removed by customization.
22435 The return value is nil, or a cons cell with the delimiter and
22436 and the position of this delimiter.
22438 This function does a reasonably good job, but can locally be fooled by
22439 for example currency specifications. For example it will assume being in
22440 inline math after \"$22.34\". The LaTeX fragment formatter will only format
22441 fragments that are properly closed, but during editing, we have to live
22442 with the uncertainty caused by missing closing delimiters. This function
22443 looks only before point, not after."
22444 (catch 'exit
22445 (let ((pos (point))
22446 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
22447 (lim (progn
22448 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
22449 (point)))
22450 dd-on str (start 0) m re)
22451 (goto-char pos)
22452 (when dodollar
22453 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
22454 re (nth 1 (assoc "$" org-latex-regexps)))
22455 (while (string-match re str start)
22456 (cond
22457 ((= (match-end 0) (length str))
22458 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
22459 ((= (match-end 0) (- (length str) 5))
22460 (throw 'exit nil))
22461 (t (setq start (match-end 0))))))
22462 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
22463 (goto-char pos)
22464 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
22465 (and (match-beginning 2) (throw 'exit nil))
22466 ;; count $$
22467 (while (re-search-backward "\\$\\$" lim t)
22468 (setq dd-on (not dd-on)))
22469 (goto-char pos)
22470 (if dd-on (cons "$$" m))))))
22473 (defun org-try-cdlatex-tab ()
22474 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
22475 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
22476 - inside a LaTeX fragment, or
22477 - after the first word in a line, where an abbreviation expansion could
22478 insert a LaTeX environment."
22479 (when org-cdlatex-mode
22480 (cond
22481 ((save-excursion
22482 (skip-chars-backward "a-zA-Z0-9*")
22483 (skip-chars-backward " \t")
22484 (bolp))
22485 (cdlatex-tab) t)
22486 ((org-inside-LaTeX-fragment-p)
22487 (cdlatex-tab) t)
22488 (t nil))))
22490 (defun org-cdlatex-underscore-caret (&optional arg)
22491 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
22492 Revert to the normal definition outside of these fragments."
22493 (interactive "P")
22494 (if (org-inside-LaTeX-fragment-p)
22495 (call-interactively 'cdlatex-sub-superscript)
22496 (let (org-cdlatex-mode)
22497 (call-interactively (key-binding (vector last-input-event))))))
22499 (defun org-cdlatex-math-modify (&optional arg)
22500 "Execute `cdlatex-math-modify' in LaTeX fragments.
22501 Revert to the normal definition outside of these fragments."
22502 (interactive "P")
22503 (if (org-inside-LaTeX-fragment-p)
22504 (call-interactively 'cdlatex-math-modify)
22505 (let (org-cdlatex-mode)
22506 (call-interactively (key-binding (vector last-input-event))))))
22508 (defvar org-latex-fragment-image-overlays nil
22509 "List of overlays carrying the images of latex fragments.")
22510 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
22512 (defun org-remove-latex-fragment-image-overlays ()
22513 "Remove all overlays with LaTeX fragment images in current buffer."
22514 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
22515 (setq org-latex-fragment-image-overlays nil))
22517 (defun org-preview-latex-fragment (&optional subtree)
22518 "Preview the LaTeX fragment at point, or all locally or globally.
22519 If the cursor is in a LaTeX fragment, create the image and overlay
22520 it over the source code. If there is no fragment at point, display
22521 all fragments in the current text, from one headline to the next. With
22522 prefix SUBTREE, display all fragments in the current subtree. With a
22523 double prefix `C-u C-u', or when the cursor is before the first headline,
22524 display all fragments in the buffer.
22525 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
22526 (interactive "P")
22527 (org-remove-latex-fragment-image-overlays)
22528 (save-excursion
22529 (save-restriction
22530 (let (beg end at msg)
22531 (cond
22532 ((or (equal subtree '(16))
22533 (not (save-excursion
22534 (re-search-backward (concat "^" outline-regexp) nil t))))
22535 (setq beg (point-min) end (point-max)
22536 msg "Creating images for buffer...%s"))
22537 ((equal subtree '(4))
22538 (org-back-to-heading)
22539 (setq beg (point) end (org-end-of-subtree t)
22540 msg "Creating images for subtree...%s"))
22542 (if (setq at (org-inside-LaTeX-fragment-p))
22543 (goto-char (max (point-min) (- (cdr at) 2)))
22544 (org-back-to-heading))
22545 (setq beg (point) end (progn (outline-next-heading) (point))
22546 msg (if at "Creating image...%s"
22547 "Creating images for entry...%s"))))
22548 (message msg "")
22549 (narrow-to-region beg end)
22550 (goto-char beg)
22551 (org-format-latex
22552 (concat "ltxpng/" (file-name-sans-extension
22553 (file-name-nondirectory
22554 buffer-file-name)))
22555 default-directory 'overlays msg at 'forbuffer)
22556 (message msg "done. Use `C-c C-c' to remove images.")))))
22558 (defvar org-latex-regexps
22559 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
22560 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
22561 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
22562 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
22563 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
22564 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
22565 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
22566 "Regular expressions for matching embedded LaTeX.")
22568 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
22569 "Replace LaTeX fragments with links to an image, and produce images."
22570 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
22571 (let* ((prefixnodir (file-name-nondirectory prefix))
22572 (absprefix (expand-file-name prefix dir))
22573 (todir (file-name-directory absprefix))
22574 (opt org-format-latex-options)
22575 (matchers (plist-get opt :matchers))
22576 (re-list org-latex-regexps)
22577 (cnt 0) txt link beg end re e checkdir
22578 m n block linkfile movefile ov)
22579 ;; Check if there are old images files with this prefix, and remove them
22580 (when (file-directory-p todir)
22581 (mapc 'delete-file
22582 (directory-files
22583 todir 'full
22584 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
22585 ;; Check the different regular expressions
22586 (while (setq e (pop re-list))
22587 (setq m (car e) re (nth 1 e) n (nth 2 e)
22588 block (if (nth 3 e) "\n\n" ""))
22589 (when (member m matchers)
22590 (goto-char (point-min))
22591 (while (re-search-forward re nil t)
22592 (when (or (not at) (equal (cdr at) (match-beginning n)))
22593 (setq txt (match-string n)
22594 beg (match-beginning n) end (match-end n)
22595 cnt (1+ cnt)
22596 linkfile (format "%s_%04d.png" prefix cnt)
22597 movefile (format "%s_%04d.png" absprefix cnt)
22598 link (concat block "[[file:" linkfile "]]" block))
22599 (if msg (message msg cnt))
22600 (goto-char beg)
22601 (unless checkdir ; make sure the directory exists
22602 (setq checkdir t)
22603 (or (file-directory-p todir) (make-directory todir)))
22604 (org-create-formula-image
22605 txt movefile opt forbuffer)
22606 (if overlays
22607 (progn
22608 (setq ov (org-make-overlay beg end))
22609 (if (featurep 'xemacs)
22610 (progn
22611 (org-overlay-put ov 'invisible t)
22612 (org-overlay-put
22613 ov 'end-glyph
22614 (make-glyph (vector 'png :file movefile))))
22615 (org-overlay-put
22616 ov 'display
22617 (list 'image :type 'png :file movefile :ascent 'center)))
22618 (push ov org-latex-fragment-image-overlays)
22619 (goto-char end))
22620 (delete-region beg end)
22621 (insert link))))))))
22623 ;; This function borrows from Ganesh Swami's latex2png.el
22624 (defun org-create-formula-image (string tofile options buffer)
22625 (let* ((tmpdir (if (featurep 'xemacs)
22626 (temp-directory)
22627 temporary-file-directory))
22628 (texfilebase (make-temp-name
22629 (expand-file-name "orgtex" tmpdir)))
22630 (texfile (concat texfilebase ".tex"))
22631 (dvifile (concat texfilebase ".dvi"))
22632 (pngfile (concat texfilebase ".png"))
22633 (fnh (face-attribute 'default :height nil))
22634 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
22635 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
22636 (fg (or (plist-get options (if buffer :foreground :html-foreground))
22637 "Black"))
22638 (bg (or (plist-get options (if buffer :background :html-background))
22639 "Transparent")))
22640 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
22641 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
22642 (with-temp-file texfile
22643 (insert org-format-latex-header
22644 "\n\\begin{document}\n" string "\n\\end{document}\n"))
22645 (let ((dir default-directory))
22646 (condition-case nil
22647 (progn
22648 (cd tmpdir)
22649 (call-process "latex" nil nil nil texfile))
22650 (error nil))
22651 (cd dir))
22652 (if (not (file-exists-p dvifile))
22653 (progn (message "Failed to create dvi file from %s" texfile) nil)
22654 (call-process "dvipng" nil nil nil
22655 "-E" "-fg" fg "-bg" bg
22656 "-D" dpi
22657 ;;"-x" scale "-y" scale
22658 "-T" "tight"
22659 "-o" pngfile
22660 dvifile)
22661 (if (not (file-exists-p pngfile))
22662 (progn (message "Failed to create png file from %s" texfile) nil)
22663 ;; Use the requested file name and clean up
22664 (copy-file pngfile tofile 'replace)
22665 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
22666 (delete-file (concat texfilebase e)))
22667 pngfile))))
22669 (defun org-dvipng-color (attr)
22670 "Return an rgb color specification for dvipng."
22671 (apply 'format "rgb %s %s %s"
22672 (mapcar 'org-normalize-color
22673 (color-values (face-attribute 'default attr nil)))))
22675 (defun org-normalize-color (value)
22676 "Return string to be used as color value for an RGB component."
22677 (format "%g" (/ value 65535.0)))
22679 ;;;; Exporting
22681 ;;; Variables, constants, and parameter plists
22683 (defconst org-level-max 20)
22685 (defvar org-export-html-preamble nil
22686 "Preamble, to be inserted just after <body>. Set by publishing functions.")
22687 (defvar org-export-html-postamble nil
22688 "Preamble, to be inserted just before </body>. Set by publishing functions.")
22689 (defvar org-export-html-auto-preamble t
22690 "Should default preamble be inserted? Set by publishing functions.")
22691 (defvar org-export-html-auto-postamble t
22692 "Should default postamble be inserted? Set by publishing functions.")
22693 (defvar org-current-export-file nil) ; dynamically scoped parameter
22694 (defvar org-current-export-dir nil) ; dynamically scoped parameter
22697 (defconst org-export-plist-vars
22698 '((:language . org-export-default-language)
22699 (:customtime . org-display-custom-times)
22700 (:headline-levels . org-export-headline-levels)
22701 (:section-numbers . org-export-with-section-numbers)
22702 (:table-of-contents . org-export-with-toc)
22703 (:preserve-breaks . org-export-preserve-breaks)
22704 (:archived-trees . org-export-with-archived-trees)
22705 (:emphasize . org-export-with-emphasize)
22706 (:sub-superscript . org-export-with-sub-superscripts)
22707 (:special-strings . org-export-with-special-strings)
22708 (:footnotes . org-export-with-footnotes)
22709 (:drawers . org-export-with-drawers)
22710 (:tags . org-export-with-tags)
22711 (:TeX-macros . org-export-with-TeX-macros)
22712 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
22713 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
22714 (:fixed-width . org-export-with-fixed-width)
22715 (:timestamps . org-export-with-timestamps)
22716 (:author-info . org-export-author-info)
22717 (:time-stamp-file . org-export-time-stamp-file)
22718 (:tables . org-export-with-tables)
22719 (:table-auto-headline . org-export-highlight-first-table-line)
22720 (:style . org-export-html-style)
22721 (:agenda-style . org-agenda-export-html-style)
22722 (:convert-org-links . org-export-html-link-org-files-as-html)
22723 (:inline-images . org-export-html-inline-images)
22724 (:html-extension . org-export-html-extension)
22725 (:html-table-tag . org-export-html-table-tag)
22726 (:expand-quoted-html . org-export-html-expand)
22727 (:timestamp . org-export-html-with-timestamp)
22728 (:publishing-directory . org-export-publishing-directory)
22729 (:preamble . org-export-html-preamble)
22730 (:postamble . org-export-html-postamble)
22731 (:auto-preamble . org-export-html-auto-preamble)
22732 (:auto-postamble . org-export-html-auto-postamble)
22733 (:author . user-full-name)
22734 (:email . user-mail-address)))
22736 (defun org-default-export-plist ()
22737 "Return the property list with default settings for the export variables."
22738 (let ((l org-export-plist-vars) rtn e)
22739 (while (setq e (pop l))
22740 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
22741 rtn))
22743 (defun org-infile-export-plist ()
22744 "Return the property list with file-local settings for export."
22745 (save-excursion
22746 (goto-char 0)
22747 (let ((re (org-make-options-regexp
22748 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
22749 p key val text options)
22750 (while (re-search-forward re nil t)
22751 (setq key (org-match-string-no-properties 1)
22752 val (org-match-string-no-properties 2))
22753 (cond
22754 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
22755 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
22756 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
22757 ((string-equal key "DATE") (setq p (plist-put p :date val)))
22758 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
22759 ((string-equal key "TEXT")
22760 (setq text (if text (concat text "\n" val) val)))
22761 ((string-equal key "OPTIONS") (setq options val))))
22762 (setq p (plist-put p :text text))
22763 (when options
22764 (let ((op '(("H" . :headline-levels)
22765 ("num" . :section-numbers)
22766 ("toc" . :table-of-contents)
22767 ("\\n" . :preserve-breaks)
22768 ("@" . :expand-quoted-html)
22769 (":" . :fixed-width)
22770 ("|" . :tables)
22771 ("^" . :sub-superscript)
22772 ("-" . :special-strings)
22773 ("f" . :footnotes)
22774 ("d" . :drawers)
22775 ("tags" . :tags)
22776 ("*" . :emphasize)
22777 ("TeX" . :TeX-macros)
22778 ("LaTeX" . :LaTeX-fragments)
22779 ("skip" . :skip-before-1st-heading)
22780 ("author" . :author-info)
22781 ("timestamp" . :time-stamp-file)))
22783 (while (setq o (pop op))
22784 (if (string-match (concat (regexp-quote (car o))
22785 ":\\([^ \t\n\r;,.]*\\)")
22786 options)
22787 (setq p (plist-put p (cdr o)
22788 (car (read-from-string
22789 (match-string 1 options)))))))))
22790 p)))
22792 (defun org-export-directory (type plist)
22793 (let* ((val (plist-get plist :publishing-directory))
22794 (dir (if (listp val)
22795 (or (cdr (assoc type val)) ".")
22796 val)))
22797 dir))
22799 (defun org-skip-comments (lines)
22800 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
22801 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
22802 (re2 "^\\(\\*+\\)[ \t\n\r]")
22803 (case-fold-search nil)
22804 rtn line level)
22805 (while (setq line (pop lines))
22806 (cond
22807 ((and (string-match re1 line)
22808 (setq level (- (match-end 1) (match-beginning 1))))
22809 ;; Beginning of a COMMENT subtree. Skip it.
22810 (while (and (setq line (pop lines))
22811 (or (not (string-match re2 line))
22812 (> (- (match-end 1) (match-beginning 1)) level))))
22813 (setq lines (cons line lines)))
22814 ((string-match "^#" line)
22815 ;; an ordinary comment line
22817 ((and org-export-table-remove-special-lines
22818 (string-match "^[ \t]*|" line)
22819 (or (string-match "^[ \t]*| *[!_^] *|" line)
22820 (and (string-match "| *<[0-9]+> *|" line)
22821 (not (string-match "| *[^ <|]" line)))))
22822 ;; a special table line that should be removed
22824 (t (setq rtn (cons line rtn)))))
22825 (nreverse rtn)))
22827 (defun org-export (&optional arg)
22828 (interactive)
22829 (let ((help "[t] insert the export option template
22830 \[v] limit export to visible part of outline tree
22832 \[a] export as ASCII
22834 \[h] export as HTML
22835 \[H] export as HTML to temporary buffer
22836 \[R] export region as HTML
22837 \[b] export as HTML and browse immediately
22838 \[x] export as XOXO
22840 \[l] export as LaTeX
22841 \[L] export as LaTeX to temporary buffer
22843 \[i] export current file as iCalendar file
22844 \[I] export all agenda files as iCalendar files
22845 \[c] export agenda files into combined iCalendar file
22847 \[F] publish current file
22848 \[P] publish current project
22849 \[X] publish... (project will be prompted for)
22850 \[A] publish all projects")
22851 (cmds
22852 '((?t . org-insert-export-options-template)
22853 (?v . org-export-visible)
22854 (?a . org-export-as-ascii)
22855 (?h . org-export-as-html)
22856 (?b . org-export-as-html-and-open)
22857 (?H . org-export-as-html-to-buffer)
22858 (?R . org-export-region-as-html)
22859 (?x . org-export-as-xoxo)
22860 (?l . org-export-as-latex)
22861 (?L . org-export-as-latex-to-buffer)
22862 (?i . org-export-icalendar-this-file)
22863 (?I . org-export-icalendar-all-agenda-files)
22864 (?c . org-export-icalendar-combine-agenda-files)
22865 (?F . org-publish-current-file)
22866 (?P . org-publish-current-project)
22867 (?X . org-publish)
22868 (?A . org-publish-all)))
22869 r1 r2 ass)
22870 (save-window-excursion
22871 (delete-other-windows)
22872 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
22873 (princ help))
22874 (message "Select command: ")
22875 (setq r1 (read-char-exclusive)))
22876 (setq r2 (if (< r1 27) (+ r1 96) r1))
22877 (if (setq ass (assq r2 cmds))
22878 (call-interactively (cdr ass))
22879 (error "No command associated with key %c" r1))))
22881 (defconst org-html-entities
22882 '(("nbsp")
22883 ("iexcl")
22884 ("cent")
22885 ("pound")
22886 ("curren")
22887 ("yen")
22888 ("brvbar")
22889 ("vert" . "&#124;")
22890 ("sect")
22891 ("uml")
22892 ("copy")
22893 ("ordf")
22894 ("laquo")
22895 ("not")
22896 ("shy")
22897 ("reg")
22898 ("macr")
22899 ("deg")
22900 ("plusmn")
22901 ("sup2")
22902 ("sup3")
22903 ("acute")
22904 ("micro")
22905 ("para")
22906 ("middot")
22907 ("odot"."o")
22908 ("star"."*")
22909 ("cedil")
22910 ("sup1")
22911 ("ordm")
22912 ("raquo")
22913 ("frac14")
22914 ("frac12")
22915 ("frac34")
22916 ("iquest")
22917 ("Agrave")
22918 ("Aacute")
22919 ("Acirc")
22920 ("Atilde")
22921 ("Auml")
22922 ("Aring") ("AA"."&Aring;")
22923 ("AElig")
22924 ("Ccedil")
22925 ("Egrave")
22926 ("Eacute")
22927 ("Ecirc")
22928 ("Euml")
22929 ("Igrave")
22930 ("Iacute")
22931 ("Icirc")
22932 ("Iuml")
22933 ("ETH")
22934 ("Ntilde")
22935 ("Ograve")
22936 ("Oacute")
22937 ("Ocirc")
22938 ("Otilde")
22939 ("Ouml")
22940 ("times")
22941 ("Oslash")
22942 ("Ugrave")
22943 ("Uacute")
22944 ("Ucirc")
22945 ("Uuml")
22946 ("Yacute")
22947 ("THORN")
22948 ("szlig")
22949 ("agrave")
22950 ("aacute")
22951 ("acirc")
22952 ("atilde")
22953 ("auml")
22954 ("aring")
22955 ("aelig")
22956 ("ccedil")
22957 ("egrave")
22958 ("eacute")
22959 ("ecirc")
22960 ("euml")
22961 ("igrave")
22962 ("iacute")
22963 ("icirc")
22964 ("iuml")
22965 ("eth")
22966 ("ntilde")
22967 ("ograve")
22968 ("oacute")
22969 ("ocirc")
22970 ("otilde")
22971 ("ouml")
22972 ("divide")
22973 ("oslash")
22974 ("ugrave")
22975 ("uacute")
22976 ("ucirc")
22977 ("uuml")
22978 ("yacute")
22979 ("thorn")
22980 ("yuml")
22981 ("fnof")
22982 ("Alpha")
22983 ("Beta")
22984 ("Gamma")
22985 ("Delta")
22986 ("Epsilon")
22987 ("Zeta")
22988 ("Eta")
22989 ("Theta")
22990 ("Iota")
22991 ("Kappa")
22992 ("Lambda")
22993 ("Mu")
22994 ("Nu")
22995 ("Xi")
22996 ("Omicron")
22997 ("Pi")
22998 ("Rho")
22999 ("Sigma")
23000 ("Tau")
23001 ("Upsilon")
23002 ("Phi")
23003 ("Chi")
23004 ("Psi")
23005 ("Omega")
23006 ("alpha")
23007 ("beta")
23008 ("gamma")
23009 ("delta")
23010 ("epsilon")
23011 ("varepsilon"."&epsilon;")
23012 ("zeta")
23013 ("eta")
23014 ("theta")
23015 ("iota")
23016 ("kappa")
23017 ("lambda")
23018 ("mu")
23019 ("nu")
23020 ("xi")
23021 ("omicron")
23022 ("pi")
23023 ("rho")
23024 ("sigmaf") ("varsigma"."&sigmaf;")
23025 ("sigma")
23026 ("tau")
23027 ("upsilon")
23028 ("phi")
23029 ("chi")
23030 ("psi")
23031 ("omega")
23032 ("thetasym") ("vartheta"."&thetasym;")
23033 ("upsih")
23034 ("piv")
23035 ("bull") ("bullet"."&bull;")
23036 ("hellip") ("dots"."&hellip;")
23037 ("prime")
23038 ("Prime")
23039 ("oline")
23040 ("frasl")
23041 ("weierp")
23042 ("image")
23043 ("real")
23044 ("trade")
23045 ("alefsym")
23046 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
23047 ("uarr") ("uparrow"."&uarr;")
23048 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
23049 ("darr")("downarrow"."&darr;")
23050 ("harr") ("leftrightarrow"."&harr;")
23051 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
23052 ("lArr") ("Leftarrow"."&lArr;")
23053 ("uArr") ("Uparrow"."&uArr;")
23054 ("rArr") ("Rightarrow"."&rArr;")
23055 ("dArr") ("Downarrow"."&dArr;")
23056 ("hArr") ("Leftrightarrow"."&hArr;")
23057 ("forall")
23058 ("part") ("partial"."&part;")
23059 ("exist") ("exists"."&exist;")
23060 ("empty") ("emptyset"."&empty;")
23061 ("nabla")
23062 ("isin") ("in"."&isin;")
23063 ("notin")
23064 ("ni")
23065 ("prod")
23066 ("sum")
23067 ("minus")
23068 ("lowast") ("ast"."&lowast;")
23069 ("radic")
23070 ("prop") ("proptp"."&prop;")
23071 ("infin") ("infty"."&infin;")
23072 ("ang") ("angle"."&ang;")
23073 ("and") ("wedge"."&and;")
23074 ("or") ("vee"."&or;")
23075 ("cap")
23076 ("cup")
23077 ("int")
23078 ("there4")
23079 ("sim")
23080 ("cong") ("simeq"."&cong;")
23081 ("asymp")("approx"."&asymp;")
23082 ("ne") ("neq"."&ne;")
23083 ("equiv")
23084 ("le")
23085 ("ge")
23086 ("sub") ("subset"."&sub;")
23087 ("sup") ("supset"."&sup;")
23088 ("nsub")
23089 ("sube")
23090 ("supe")
23091 ("oplus")
23092 ("otimes")
23093 ("perp")
23094 ("sdot") ("cdot"."&sdot;")
23095 ("lceil")
23096 ("rceil")
23097 ("lfloor")
23098 ("rfloor")
23099 ("lang")
23100 ("rang")
23101 ("loz") ("Diamond"."&loz;")
23102 ("spades") ("spadesuit"."&spades;")
23103 ("clubs") ("clubsuit"."&clubs;")
23104 ("hearts") ("diamondsuit"."&hearts;")
23105 ("diams") ("diamondsuit"."&diams;")
23106 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
23107 ("quot")
23108 ("amp")
23109 ("lt")
23110 ("gt")
23111 ("OElig")
23112 ("oelig")
23113 ("Scaron")
23114 ("scaron")
23115 ("Yuml")
23116 ("circ")
23117 ("tilde")
23118 ("ensp")
23119 ("emsp")
23120 ("thinsp")
23121 ("zwnj")
23122 ("zwj")
23123 ("lrm")
23124 ("rlm")
23125 ("ndash")
23126 ("mdash")
23127 ("lsquo")
23128 ("rsquo")
23129 ("sbquo")
23130 ("ldquo")
23131 ("rdquo")
23132 ("bdquo")
23133 ("dagger")
23134 ("Dagger")
23135 ("permil")
23136 ("lsaquo")
23137 ("rsaquo")
23138 ("euro")
23140 ("arccos"."arccos")
23141 ("arcsin"."arcsin")
23142 ("arctan"."arctan")
23143 ("arg"."arg")
23144 ("cos"."cos")
23145 ("cosh"."cosh")
23146 ("cot"."cot")
23147 ("coth"."coth")
23148 ("csc"."csc")
23149 ("deg"."deg")
23150 ("det"."det")
23151 ("dim"."dim")
23152 ("exp"."exp")
23153 ("gcd"."gcd")
23154 ("hom"."hom")
23155 ("inf"."inf")
23156 ("ker"."ker")
23157 ("lg"."lg")
23158 ("lim"."lim")
23159 ("liminf"."liminf")
23160 ("limsup"."limsup")
23161 ("ln"."ln")
23162 ("log"."log")
23163 ("max"."max")
23164 ("min"."min")
23165 ("Pr"."Pr")
23166 ("sec"."sec")
23167 ("sin"."sin")
23168 ("sinh"."sinh")
23169 ("sup"."sup")
23170 ("tan"."tan")
23171 ("tanh"."tanh")
23173 "Entities for TeX->HTML translation.
23174 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
23175 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
23176 In that case, \"\\ent\" will be translated to \"&other;\".
23177 The list contains HTML entities for Latin-1, Greek and other symbols.
23178 It is supplemented by a number of commonly used TeX macros with appropriate
23179 translations. There is currently no way for users to extend this.")
23181 ;;; General functions for all backends
23183 (defun org-cleaned-string-for-export (string &rest parameters)
23184 "Cleanup a buffer STRING so that links can be created safely."
23185 (interactive)
23186 (let* ((re-radio (and org-target-link-regexp
23187 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
23188 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
23189 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
23190 (re-archive (concat ":" org-archive-tag ":"))
23191 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
23192 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
23193 (htmlp (plist-get parameters :for-html))
23194 (asciip (plist-get parameters :for-ascii))
23195 (latexp (plist-get parameters :for-LaTeX))
23196 (commentsp (plist-get parameters :comments))
23197 (archived-trees (plist-get parameters :archived-trees))
23198 (inhibit-read-only t)
23199 (drawers org-drawers)
23200 (exp-drawers (plist-get parameters :drawers))
23201 (outline-regexp "\\*+ ")
23202 a b xx
23203 rtn p)
23204 (with-current-buffer (get-buffer-create " org-mode-tmp")
23205 (erase-buffer)
23206 (insert string)
23207 ;; Remove license-to-kill stuff
23208 (while (setq p (text-property-any (point-min) (point-max)
23209 :org-license-to-kill t))
23210 (delete-region p (next-single-property-change p :org-license-to-kill)))
23212 (let ((org-inhibit-startup t)) (org-mode))
23213 (untabify (point-min) (point-max))
23215 ;; Get the correct stuff before the first headline
23216 (when (plist-get parameters :skip-before-1st-heading)
23217 (goto-char (point-min))
23218 (when (re-search-forward "^\\*+[ \t]" nil t)
23219 (delete-region (point-min) (match-beginning 0))
23220 (goto-char (point-min))
23221 (insert "\n")))
23222 (when (plist-get parameters :add-text)
23223 (goto-char (point-min))
23224 (insert (plist-get parameters :add-text) "\n"))
23226 ;; Get rid of archived trees
23227 (when (not (eq archived-trees t))
23228 (goto-char (point-min))
23229 (while (re-search-forward re-archive nil t)
23230 (if (not (org-on-heading-p t))
23231 (org-end-of-subtree t)
23232 (beginning-of-line 1)
23233 (setq a (if archived-trees
23234 (1+ (point-at-eol)) (point))
23235 b (org-end-of-subtree t))
23236 (if (> b a) (delete-region a b)))))
23238 ;; Get rid of drawers
23239 (unless (eq t exp-drawers)
23240 (goto-char (point-min))
23241 (let ((re (concat "^[ \t]*:\\("
23242 (mapconcat
23243 'identity
23244 (org-delete-all exp-drawers
23245 (copy-sequence drawers))
23246 "\\|")
23247 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
23248 (while (re-search-forward re nil t)
23249 (replace-match ""))))
23251 ;; Find targets in comments and move them out of comments,
23252 ;; but mark them as targets that should be invisible
23253 (goto-char (point-min))
23254 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
23255 (replace-match "\\1(INVISIBLE)"))
23257 ;; Protect backend specific stuff, throw away the others.
23258 (let ((formatters
23259 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
23260 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
23261 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
23262 fmt)
23263 (goto-char (point-min))
23264 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
23265 (goto-char (match-end 0))
23266 (while (not (looking-at "#\\+END_EXAMPLE"))
23267 (insert ": ")
23268 (beginning-of-line 2)))
23269 (goto-char (point-min))
23270 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
23271 (add-text-properties (match-beginning 0) (match-end 0)
23272 '(org-protected t)))
23273 (while formatters
23274 (setq fmt (pop formatters))
23275 (when (car fmt)
23276 (goto-char (point-min))
23277 (while (re-search-forward (concat "^#\\+" (cadr fmt)
23278 ":[ \t]*\\(.*\\)") nil t)
23279 (replace-match "\\1" t)
23280 (add-text-properties
23281 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
23282 '(org-protected t))))
23283 (goto-char (point-min))
23284 (while (re-search-forward
23285 (concat "^#\\+"
23286 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
23287 (cadddr fmt) "\\>.*\n?") nil t)
23288 (if (car fmt)
23289 (add-text-properties (match-beginning 1) (1+ (match-end 1))
23290 '(org-protected t))
23291 (delete-region (match-beginning 0) (match-end 0))))))
23293 ;; Protect quoted subtrees
23294 (goto-char (point-min))
23295 (while (re-search-forward re-quote nil t)
23296 (goto-char (match-beginning 0))
23297 (end-of-line 1)
23298 (add-text-properties (point) (org-end-of-subtree t)
23299 '(org-protected t)))
23301 ;; Protect verbatim elements
23302 (goto-char (point-min))
23303 (while (re-search-forward org-verbatim-re nil t)
23304 (add-text-properties (match-beginning 4) (match-end 4)
23305 '(org-protected t))
23306 (goto-char (1+ (match-end 4))))
23308 ;; Remove subtrees that are commented
23309 (goto-char (point-min))
23310 (while (re-search-forward re-commented nil t)
23311 (goto-char (match-beginning 0))
23312 (delete-region (point) (org-end-of-subtree t)))
23314 ;; Remove special table lines
23315 (when org-export-table-remove-special-lines
23316 (goto-char (point-min))
23317 (while (re-search-forward "^[ \t]*|" nil t)
23318 (beginning-of-line 1)
23319 (if (or (looking-at "[ \t]*| *[!_^] *|")
23320 (and (looking-at ".*?| *<[0-9]+> *|")
23321 (not (looking-at ".*?| *[^ <|]"))))
23322 (delete-region (max (point-min) (1- (point-at-bol)))
23323 (point-at-eol))
23324 (end-of-line 1))))
23326 ;; Specific LaTeX stuff
23327 (when latexp
23328 (require 'org-export-latex nil)
23329 (org-export-latex-cleaned-string))
23331 (when asciip
23332 (org-export-ascii-clean-string))
23334 ;; Specific HTML stuff
23335 (when htmlp
23336 ;; Convert LaTeX fragments to images
23337 (when (plist-get parameters :LaTeX-fragments)
23338 (org-format-latex
23339 (concat "ltxpng/" (file-name-sans-extension
23340 (file-name-nondirectory
23341 org-current-export-file)))
23342 org-current-export-dir nil "Creating LaTeX image %s"))
23343 (message "Exporting..."))
23345 ;; Remove or replace comments
23346 (goto-char (point-min))
23347 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
23348 (if commentsp
23349 (progn (add-text-properties
23350 (match-beginning 0) (match-end 0) '(org-protected t))
23351 (replace-match (format commentsp (match-string 1)) t t))
23352 (replace-match "")))
23354 ;; Find matches for radio targets and turn them into internal links
23355 (goto-char (point-min))
23356 (when re-radio
23357 (while (re-search-forward re-radio nil t)
23358 (org-if-unprotected
23359 (replace-match "\\1[[\\2]]"))))
23361 ;; Find all links that contain a newline and put them into a single line
23362 (goto-char (point-min))
23363 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
23364 (org-if-unprotected
23365 (replace-match "\\1 \\3")
23366 (goto-char (match-beginning 0))))
23369 ;; Normalize links: Convert angle and plain links into bracket links
23370 ;; Expand link abbreviations
23371 (goto-char (point-min))
23372 (while (re-search-forward re-plain-link nil t)
23373 (goto-char (1- (match-end 0)))
23374 (org-if-unprotected
23375 (let* ((s (concat (match-string 1) "[[" (match-string 2)
23376 ":" (match-string 3) "]]")))
23377 ;; added 'org-link face to links
23378 (put-text-property 0 (length s) 'face 'org-link s)
23379 (replace-match s t t))))
23380 (goto-char (point-min))
23381 (while (re-search-forward re-angle-link nil t)
23382 (goto-char (1- (match-end 0)))
23383 (org-if-unprotected
23384 (let* ((s (concat (match-string 1) "[[" (match-string 2)
23385 ":" (match-string 3) "]]")))
23386 (put-text-property 0 (length s) 'face 'org-link s)
23387 (replace-match s t t))))
23388 (goto-char (point-min))
23389 (while (re-search-forward org-bracket-link-regexp nil t)
23390 (org-if-unprotected
23391 (let* ((s (concat "[[" (setq xx (save-match-data
23392 (org-link-expand-abbrev (match-string 1))))
23394 (if (match-end 3)
23395 (match-string 2)
23396 (concat "[" xx "]"))
23397 "]")))
23398 (put-text-property 0 (length s) 'face 'org-link s)
23399 (replace-match s t t))))
23401 ;; Find multiline emphasis and put them into single line
23402 (when (plist-get parameters :emph-multiline)
23403 (goto-char (point-min))
23404 (while (re-search-forward org-emph-re nil t)
23405 (if (not (= (char-after (match-beginning 3))
23406 (char-after (match-beginning 4))))
23407 (org-if-unprotected
23408 (subst-char-in-region (match-beginning 0) (match-end 0)
23409 ?\n ?\ t)
23410 (goto-char (1- (match-end 0))))
23411 (goto-char (1+ (match-beginning 0))))))
23413 (setq rtn (buffer-string)))
23414 (kill-buffer " org-mode-tmp")
23415 rtn))
23417 (defun org-export-grab-title-from-buffer ()
23418 "Get a title for the current document, from looking at the buffer."
23419 (let ((inhibit-read-only t))
23420 (save-excursion
23421 (goto-char (point-min))
23422 (let ((end (save-excursion (outline-next-heading) (point))))
23423 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
23424 ;; Mark the line so that it will not be exported as normal text.
23425 (org-unmodified
23426 (add-text-properties (match-beginning 0) (match-end 0)
23427 (list :org-license-to-kill t)))
23428 ;; Return the title string
23429 (org-trim (match-string 0)))))))
23431 (defun org-export-get-title-from-subtree ()
23432 "Return subtree title and exclude it from export."
23433 (let (title (m (mark)))
23434 (save-excursion
23435 (goto-char (region-beginning))
23436 (when (and (org-at-heading-p)
23437 (>= (org-end-of-subtree t t) (region-end)))
23438 ;; This is a subtree, we take the title from the first heading
23439 (goto-char (region-beginning))
23440 (looking-at org-todo-line-regexp)
23441 (setq title (match-string 3))
23442 (org-unmodified
23443 (add-text-properties (point) (1+ (point-at-eol))
23444 (list :org-license-to-kill t)))))
23445 title))
23447 (defun org-solidify-link-text (s &optional alist)
23448 "Take link text and make a safe target out of it."
23449 (save-match-data
23450 (let* ((rtn
23451 (mapconcat
23452 'identity
23453 (org-split-string s "[ \t\r\n]+") "--"))
23454 (a (assoc rtn alist)))
23455 (or (cdr a) rtn))))
23457 (defun org-get-min-level (lines)
23458 "Get the minimum level in LINES."
23459 (let ((re "^\\(\\*+\\) ") l min)
23460 (catch 'exit
23461 (while (setq l (pop lines))
23462 (if (string-match re l)
23463 (throw 'exit (org-tr-level (length (match-string 1 l))))))
23464 1)))
23466 ;; Variable holding the vector with section numbers
23467 (defvar org-section-numbers (make-vector org-level-max 0))
23469 (defun org-init-section-numbers ()
23470 "Initialize the vector for the section numbers."
23471 (let* ((level -1)
23472 (numbers (nreverse (org-split-string "" "\\.")))
23473 (depth (1- (length org-section-numbers)))
23474 (i depth) number-string)
23475 (while (>= i 0)
23476 (if (> i level)
23477 (aset org-section-numbers i 0)
23478 (setq number-string (or (car numbers) "0"))
23479 (if (string-match "\\`[A-Z]\\'" number-string)
23480 (aset org-section-numbers i
23481 (- (string-to-char number-string) ?A -1))
23482 (aset org-section-numbers i (string-to-number number-string)))
23483 (pop numbers))
23484 (setq i (1- i)))))
23486 (defun org-section-number (&optional level)
23487 "Return a string with the current section number.
23488 When LEVEL is non-nil, increase section numbers on that level."
23489 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
23490 (when level
23491 (when (> level -1)
23492 (aset org-section-numbers
23493 level (1+ (aref org-section-numbers level))))
23494 (setq idx (1+ level))
23495 (while (<= idx depth)
23496 (if (not (= idx 1))
23497 (aset org-section-numbers idx 0))
23498 (setq idx (1+ idx))))
23499 (setq idx 0)
23500 (while (<= idx depth)
23501 (setq n (aref org-section-numbers idx))
23502 (setq string (concat string (if (not (string= string "")) "." "")
23503 (int-to-string n)))
23504 (setq idx (1+ idx)))
23505 (save-match-data
23506 (if (string-match "\\`\\([@0]\\.\\)+" string)
23507 (setq string (replace-match "" t nil string)))
23508 (if (string-match "\\(\\.0\\)+\\'" string)
23509 (setq string (replace-match "" t nil string))))
23510 string))
23512 ;;; ASCII export
23514 (defvar org-last-level nil) ; dynamically scoped variable
23515 (defvar org-min-level nil) ; dynamically scoped variable
23516 (defvar org-levels-open nil) ; dynamically scoped parameter
23517 (defvar org-ascii-current-indentation nil) ; For communication
23519 (defun org-export-as-ascii (arg)
23520 "Export the outline as a pretty ASCII file.
23521 If there is an active region, export only the region.
23522 The prefix ARG specifies how many levels of the outline should become
23523 underlined headlines. The default is 3."
23524 (interactive "P")
23525 (setq-default org-todo-line-regexp org-todo-line-regexp)
23526 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
23527 (org-infile-export-plist)))
23528 (region-p (org-region-active-p))
23529 (subtree-p
23530 (when region-p
23531 (save-excursion
23532 (goto-char (region-beginning))
23533 (and (org-at-heading-p)
23534 (>= (org-end-of-subtree t t) (region-end))))))
23535 (custom-times org-display-custom-times)
23536 (org-ascii-current-indentation '(0 . 0))
23537 (level 0) line txt
23538 (umax nil)
23539 (umax-toc nil)
23540 (case-fold-search nil)
23541 (filename (concat (file-name-as-directory
23542 (org-export-directory :ascii opt-plist))
23543 (file-name-sans-extension
23544 (or (and subtree-p
23545 (org-entry-get (region-beginning)
23546 "EXPORT_FILE_NAME" t))
23547 (file-name-nondirectory buffer-file-name)))
23548 ".txt"))
23549 (filename (if (equal (file-truename filename)
23550 (file-truename buffer-file-name))
23551 (concat filename ".txt")
23552 filename))
23553 (buffer (find-file-noselect filename))
23554 (org-levels-open (make-vector org-level-max nil))
23555 (odd org-odd-levels-only)
23556 (date (plist-get opt-plist :date))
23557 (author (plist-get opt-plist :author))
23558 (title (or (and subtree-p (org-export-get-title-from-subtree))
23559 (plist-get opt-plist :title)
23560 (and (not
23561 (plist-get opt-plist :skip-before-1st-heading))
23562 (org-export-grab-title-from-buffer))
23563 (file-name-sans-extension
23564 (file-name-nondirectory buffer-file-name))))
23565 (email (plist-get opt-plist :email))
23566 (language (plist-get opt-plist :language))
23567 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
23568 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
23569 (todo nil)
23570 (lang-words nil)
23571 (region
23572 (buffer-substring
23573 (if (org-region-active-p) (region-beginning) (point-min))
23574 (if (org-region-active-p) (region-end) (point-max))))
23575 (lines (org-split-string
23576 (org-cleaned-string-for-export
23577 region
23578 :for-ascii t
23579 :skip-before-1st-heading
23580 (plist-get opt-plist :skip-before-1st-heading)
23581 :drawers (plist-get opt-plist :drawers)
23582 :verbatim-multiline t
23583 :archived-trees
23584 (plist-get opt-plist :archived-trees)
23585 :add-text (plist-get opt-plist :text))
23586 "\n"))
23587 thetoc have-headings first-heading-pos
23588 table-open table-buffer)
23590 (let ((inhibit-read-only t))
23591 (org-unmodified
23592 (remove-text-properties (point-min) (point-max)
23593 '(:org-license-to-kill t))))
23595 (setq org-min-level (org-get-min-level lines))
23596 (setq org-last-level org-min-level)
23597 (org-init-section-numbers)
23599 (find-file-noselect filename)
23601 (setq lang-words (or (assoc language org-export-language-setup)
23602 (assoc "en" org-export-language-setup)))
23603 (switch-to-buffer-other-window buffer)
23604 (erase-buffer)
23605 (fundamental-mode)
23606 ;; create local variables for all options, to make sure all called
23607 ;; functions get the correct information
23608 (mapc (lambda (x)
23609 (set (make-local-variable (cdr x))
23610 (plist-get opt-plist (car x))))
23611 org-export-plist-vars)
23612 (org-set-local 'org-odd-levels-only odd)
23613 (setq umax (if arg (prefix-numeric-value arg)
23614 org-export-headline-levels))
23615 (setq umax-toc (if (integerp org-export-with-toc)
23616 (min org-export-with-toc umax)
23617 umax))
23619 ;; File header
23620 (if title (org-insert-centered title ?=))
23621 (insert "\n")
23622 (if (and (or author email)
23623 org-export-author-info)
23624 (insert (concat (nth 1 lang-words) ": " (or author "")
23625 (if email (concat " <" email ">") "")
23626 "\n")))
23628 (cond
23629 ((and date (string-match "%" date))
23630 (setq date (format-time-string date (current-time))))
23631 (date)
23632 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
23634 (if (and date org-export-time-stamp-file)
23635 (insert (concat (nth 2 lang-words) ": " date"\n")))
23637 (insert "\n\n")
23639 (if org-export-with-toc
23640 (progn
23641 (push (concat (nth 3 lang-words) "\n") thetoc)
23642 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
23643 (mapc '(lambda (line)
23644 (if (string-match org-todo-line-regexp
23645 line)
23646 ;; This is a headline
23647 (progn
23648 (setq have-headings t)
23649 (setq level (- (match-end 1) (match-beginning 1))
23650 level (org-tr-level level)
23651 txt (match-string 3 line)
23652 todo
23653 (or (and org-export-mark-todo-in-toc
23654 (match-beginning 2)
23655 (not (member (match-string 2 line)
23656 org-done-keywords)))
23657 ; TODO, not DONE
23658 (and org-export-mark-todo-in-toc
23659 (= level umax-toc)
23660 (org-search-todo-below
23661 line lines level))))
23662 (setq txt (org-html-expand-for-ascii txt))
23664 (while (string-match org-bracket-link-regexp txt)
23665 (setq txt
23666 (replace-match
23667 (match-string (if (match-end 2) 3 1) txt)
23668 t t txt)))
23670 (if (and (memq org-export-with-tags '(not-in-toc nil))
23671 (string-match
23672 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
23673 txt))
23674 (setq txt (replace-match "" t t txt)))
23675 (if (string-match quote-re0 txt)
23676 (setq txt (replace-match "" t t txt)))
23678 (if org-export-with-section-numbers
23679 (setq txt (concat (org-section-number level)
23680 " " txt)))
23681 (if (<= level umax-toc)
23682 (progn
23683 (push
23684 (concat
23685 (make-string
23686 (* (max 0 (- level org-min-level)) 4) ?\ )
23687 (format (if todo "%s (*)\n" "%s\n") txt))
23688 thetoc)
23689 (setq org-last-level level))
23690 ))))
23691 lines)
23692 (setq thetoc (if have-headings (nreverse thetoc) nil))))
23694 (org-init-section-numbers)
23695 (while (setq line (pop lines))
23696 ;; Remove the quoted HTML tags.
23697 (setq line (org-html-expand-for-ascii line))
23698 ;; Remove targets
23699 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
23700 (setq line (replace-match "" t t line)))
23701 ;; Replace internal links
23702 (while (string-match org-bracket-link-regexp line)
23703 (setq line (replace-match
23704 (if (match-end 3) "[\\3]" "[\\1]")
23705 t nil line)))
23706 (when custom-times
23707 (setq line (org-translate-time line)))
23708 (cond
23709 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
23710 ;; a Headline
23711 (setq first-heading-pos (or first-heading-pos (point)))
23712 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
23713 txt (match-string 2 line))
23714 (org-ascii-level-start level txt umax lines))
23716 ((and org-export-with-tables
23717 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
23718 (if (not table-open)
23719 ;; New table starts
23720 (setq table-open t table-buffer nil))
23721 ;; Accumulate lines
23722 (setq table-buffer (cons line table-buffer))
23723 (when (or (not lines)
23724 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
23725 (car lines))))
23726 (setq table-open nil
23727 table-buffer (nreverse table-buffer))
23728 (insert (mapconcat
23729 (lambda (x)
23730 (org-fix-indentation x org-ascii-current-indentation))
23731 (org-format-table-ascii table-buffer)
23732 "\n") "\n")))
23734 (setq line (org-fix-indentation line org-ascii-current-indentation))
23735 (if (and org-export-with-fixed-width
23736 (string-match "^\\([ \t]*\\)\\(:\\)" line))
23737 (setq line (replace-match "\\1" nil nil line)))
23738 (insert line "\n"))))
23740 (normal-mode)
23742 ;; insert the table of contents
23743 (when thetoc
23744 (goto-char (point-min))
23745 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
23746 (progn
23747 (goto-char (match-beginning 0))
23748 (replace-match ""))
23749 (goto-char first-heading-pos))
23750 (mapc 'insert thetoc)
23751 (or (looking-at "[ \t]*\n[ \t]*\n")
23752 (insert "\n\n")))
23754 ;; Convert whitespace place holders
23755 (goto-char (point-min))
23756 (let (beg end)
23757 (while (setq beg (next-single-property-change (point) 'org-whitespace))
23758 (setq end (next-single-property-change beg 'org-whitespace))
23759 (goto-char beg)
23760 (delete-region beg end)
23761 (insert (make-string (- end beg) ?\ ))))
23763 (save-buffer)
23764 ;; remove display and invisible chars
23765 (let (beg end)
23766 (goto-char (point-min))
23767 (while (setq beg (next-single-property-change (point) 'display))
23768 (setq end (next-single-property-change beg 'display))
23769 (delete-region beg end)
23770 (goto-char beg)
23771 (insert "=>"))
23772 (goto-char (point-min))
23773 (while (setq beg (next-single-property-change (point) 'org-cwidth))
23774 (setq end (next-single-property-change beg 'org-cwidth))
23775 (delete-region beg end)
23776 (goto-char beg)))
23777 (goto-char (point-min))))
23779 (defun org-export-ascii-clean-string ()
23780 "Do extra work for ASCII export"
23781 (goto-char (point-min))
23782 (while (re-search-forward org-verbatim-re nil t)
23783 (goto-char (match-end 2))
23784 (backward-delete-char 1) (insert "'")
23785 (goto-char (match-beginning 2))
23786 (delete-char 1) (insert "`")
23787 (goto-char (match-end 2))))
23789 (defun org-search-todo-below (line lines level)
23790 "Search the subtree below LINE for any TODO entries."
23791 (let ((rest (cdr (memq line lines)))
23792 (re org-todo-line-regexp)
23793 line lv todo)
23794 (catch 'exit
23795 (while (setq line (pop rest))
23796 (if (string-match re line)
23797 (progn
23798 (setq lv (- (match-end 1) (match-beginning 1))
23799 todo (and (match-beginning 2)
23800 (not (member (match-string 2 line)
23801 org-done-keywords))))
23802 ; TODO, not DONE
23803 (if (<= lv level) (throw 'exit nil))
23804 (if todo (throw 'exit t))))))))
23806 (defun org-html-expand-for-ascii (line)
23807 "Handle quoted HTML for ASCII export."
23808 (if org-export-html-expand
23809 (while (string-match "@<[^<>\n]*>" line)
23810 ;; We just remove the tags for now.
23811 (setq line (replace-match "" nil nil line))))
23812 line)
23814 (defun org-insert-centered (s &optional underline)
23815 "Insert the string S centered and underline it with character UNDERLINE."
23816 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
23817 (insert (make-string ind ?\ ) s "\n")
23818 (if underline
23819 (insert (make-string ind ?\ )
23820 (make-string (string-width s) underline)
23821 "\n"))))
23823 (defun org-ascii-level-start (level title umax &optional lines)
23824 "Insert a new level in ASCII export."
23825 (let (char (n (- level umax 1)) (ind 0))
23826 (if (> level umax)
23827 (progn
23828 (insert (make-string (* 2 n) ?\ )
23829 (char-to-string (nth (% n (length org-export-ascii-bullets))
23830 org-export-ascii-bullets))
23831 " " title "\n")
23832 ;; find the indentation of the next non-empty line
23833 (catch 'stop
23834 (while lines
23835 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
23836 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
23837 (throw 'stop (setq ind (org-get-indentation (car lines)))))
23838 (pop lines)))
23839 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
23840 (if (or (not (equal (char-before) ?\n))
23841 (not (equal (char-before (1- (point))) ?\n)))
23842 (insert "\n"))
23843 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
23844 (unless org-export-with-tags
23845 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
23846 (setq title (replace-match "" t t title))))
23847 (if org-export-with-section-numbers
23848 (setq title (concat (org-section-number level) " " title)))
23849 (insert title "\n" (make-string (string-width title) char) "\n")
23850 (setq org-ascii-current-indentation '(0 . 0)))))
23852 (defun org-export-visible (type arg)
23853 "Create a copy of the visible part of the current buffer, and export it.
23854 The copy is created in a temporary buffer and removed after use.
23855 TYPE is the final key (as a string) that also select the export command in
23856 the `C-c C-e' export dispatcher.
23857 As a special case, if the you type SPC at the prompt, the temporary
23858 org-mode file will not be removed but presented to you so that you can
23859 continue to use it. The prefix arg ARG is passed through to the exporting
23860 command."
23861 (interactive
23862 (list (progn
23863 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
23864 (read-char-exclusive))
23865 current-prefix-arg))
23866 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
23867 (error "Invalid export key"))
23868 (let* ((binding (cdr (assoc type
23869 '((?a . org-export-as-ascii)
23870 (?\C-a . org-export-as-ascii)
23871 (?b . org-export-as-html-and-open)
23872 (?\C-b . org-export-as-html-and-open)
23873 (?h . org-export-as-html)
23874 (?H . org-export-as-html-to-buffer)
23875 (?R . org-export-region-as-html)
23876 (?x . org-export-as-xoxo)))))
23877 (keepp (equal type ?\ ))
23878 (file buffer-file-name)
23879 (buffer (get-buffer-create "*Org Export Visible*"))
23880 s e)
23881 ;; Need to hack the drawers here.
23882 (save-excursion
23883 (goto-char (point-min))
23884 (while (re-search-forward org-drawer-regexp nil t)
23885 (goto-char (match-beginning 1))
23886 (or (org-invisible-p) (org-flag-drawer nil))))
23887 (with-current-buffer buffer (erase-buffer))
23888 (save-excursion
23889 (setq s (goto-char (point-min)))
23890 (while (not (= (point) (point-max)))
23891 (goto-char (org-find-invisible))
23892 (append-to-buffer buffer s (point))
23893 (setq s (goto-char (org-find-visible))))
23894 (org-cycle-hide-drawers 'all)
23895 (goto-char (point-min))
23896 (unless keepp
23897 ;; Copy all comment lines to the end, to make sure #+ settings are
23898 ;; still available for the second export step. Kind of a hack, but
23899 ;; does do the trick.
23900 (if (looking-at "#[^\r\n]*")
23901 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
23902 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
23903 (append-to-buffer buffer (1+ (match-beginning 0))
23904 (min (point-max) (1+ (match-end 0))))))
23905 (set-buffer buffer)
23906 (let ((buffer-file-name file)
23907 (org-inhibit-startup t))
23908 (org-mode)
23909 (show-all)
23910 (unless keepp (funcall binding arg))))
23911 (if (not keepp)
23912 (kill-buffer buffer)
23913 (switch-to-buffer-other-window buffer)
23914 (goto-char (point-min)))))
23916 (defun org-find-visible ()
23917 (let ((s (point)))
23918 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
23919 (get-char-property s 'invisible)))
23921 (defun org-find-invisible ()
23922 (let ((s (point)))
23923 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
23924 (not (get-char-property s 'invisible))))
23927 ;;; HTML export
23929 (defun org-get-current-options ()
23930 "Return a string with current options as keyword options.
23931 Does include HTML export options as well as TODO and CATEGORY stuff."
23932 (format
23933 "#+TITLE: %s
23934 #+AUTHOR: %s
23935 #+EMAIL: %s
23936 #+LANGUAGE: %s
23937 #+TEXT: Some descriptive text to be emitted. Several lines OK.
23938 #+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
23939 #+CATEGORY: %s
23940 #+SEQ_TODO: %s
23941 #+TYP_TODO: %s
23942 #+PRIORITIES: %c %c %c
23943 #+DRAWERS: %s
23944 #+STARTUP: %s %s %s %s %s
23945 #+TAGS: %s
23946 #+ARCHIVE: %s
23947 #+LINK: %s
23949 (buffer-name) (user-full-name) user-mail-address org-export-default-language
23950 org-export-headline-levels
23951 org-export-with-section-numbers
23952 org-export-with-toc
23953 org-export-preserve-breaks
23954 org-export-html-expand
23955 org-export-with-fixed-width
23956 org-export-with-tables
23957 org-export-with-sub-superscripts
23958 org-export-with-special-strings
23959 org-export-with-footnotes
23960 org-export-with-emphasize
23961 org-export-with-TeX-macros
23962 org-export-with-LaTeX-fragments
23963 org-export-skip-text-before-1st-heading
23964 org-export-with-drawers
23965 org-export-with-tags
23966 (file-name-nondirectory buffer-file-name)
23967 "TODO FEEDBACK VERIFY DONE"
23968 "Me Jason Marie DONE"
23969 org-highest-priority org-lowest-priority org-default-priority
23970 (mapconcat 'identity org-drawers " ")
23971 (cdr (assoc org-startup-folded
23972 '((nil . "showall") (t . "overview") (content . "content"))))
23973 (if org-odd-levels-only "odd" "oddeven")
23974 (if org-hide-leading-stars "hidestars" "showstars")
23975 (if org-startup-align-all-tables "align" "noalign")
23976 (cond ((eq t org-log-done) "logdone")
23977 ((not org-log-done) "nologging")
23978 ((listp org-log-done)
23979 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
23980 org-log-done " ")))
23981 (or (mapconcat (lambda (x)
23982 (cond
23983 ((equal '(:startgroup) x) "{")
23984 ((equal '(:endgroup) x) "}")
23985 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
23986 (t (car x))))
23987 (or org-tag-alist (org-get-buffer-tags)) " ") "")
23988 org-archive-location
23989 "org file:~/org/%s.org"
23992 (defun org-insert-export-options-template ()
23993 "Insert into the buffer a template with information for exporting."
23994 (interactive)
23995 (if (not (bolp)) (newline))
23996 (let ((s (org-get-current-options)))
23997 (and (string-match "#\\+CATEGORY" s)
23998 (setq s (substring s 0 (match-beginning 0))))
23999 (insert s)))
24001 (defun org-toggle-fixed-width-section (arg)
24002 "Toggle the fixed-width export.
24003 If there is no active region, the QUOTE keyword at the current headline is
24004 inserted or removed. When present, it causes the text between this headline
24005 and the next to be exported as fixed-width text, and unmodified.
24006 If there is an active region, this command adds or removes a colon as the
24007 first character of this line. If the first character of a line is a colon,
24008 this line is also exported in fixed-width font."
24009 (interactive "P")
24010 (let* ((cc 0)
24011 (regionp (org-region-active-p))
24012 (beg (if regionp (region-beginning) (point)))
24013 (end (if regionp (region-end)))
24014 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
24015 (case-fold-search nil)
24016 (re "[ \t]*\\(:\\)")
24017 off)
24018 (if regionp
24019 (save-excursion
24020 (goto-char beg)
24021 (setq cc (current-column))
24022 (beginning-of-line 1)
24023 (setq off (looking-at re))
24024 (while (> nlines 0)
24025 (setq nlines (1- nlines))
24026 (beginning-of-line 1)
24027 (cond
24028 (arg
24029 (move-to-column cc t)
24030 (insert ":\n")
24031 (forward-line -1))
24032 ((and off (looking-at re))
24033 (replace-match "" t t nil 1))
24034 ((not off) (move-to-column cc t) (insert ":")))
24035 (forward-line 1)))
24036 (save-excursion
24037 (org-back-to-heading)
24038 (if (looking-at (concat outline-regexp
24039 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
24040 (replace-match "" t t nil 1)
24041 (if (looking-at outline-regexp)
24042 (progn
24043 (goto-char (match-end 0))
24044 (insert org-quote-string " "))))))))
24046 (defun org-export-as-html-and-open (arg)
24047 "Export the outline as HTML and immediately open it with a browser.
24048 If there is an active region, export only the region.
24049 The prefix ARG specifies how many levels of the outline should become
24050 headlines. The default is 3. Lower levels will become bulleted lists."
24051 (interactive "P")
24052 (org-export-as-html arg 'hidden)
24053 (org-open-file buffer-file-name))
24055 (defun org-export-as-html-batch ()
24056 "Call `org-export-as-html', may be used in batch processing as
24057 emacs --batch
24058 --load=$HOME/lib/emacs/org.el
24059 --eval \"(setq org-export-headline-levels 2)\"
24060 --visit=MyFile --funcall org-export-as-html-batch"
24061 (org-export-as-html org-export-headline-levels 'hidden))
24063 (defun org-export-as-html-to-buffer (arg)
24064 "Call `org-exort-as-html` with output to a temporary buffer.
24065 No file is created. The prefix ARG is passed through to `org-export-as-html'."
24066 (interactive "P")
24067 (org-export-as-html arg nil nil "*Org HTML Export*")
24068 (switch-to-buffer-other-window "*Org HTML Export*"))
24070 (defun org-replace-region-by-html (beg end)
24071 "Assume the current region has org-mode syntax, and convert it to HTML.
24072 This can be used in any buffer. For example, you could write an
24073 itemized list in org-mode syntax in an HTML buffer and then use this
24074 command to convert it."
24075 (interactive "r")
24076 (let (reg html buf pop-up-frames)
24077 (save-window-excursion
24078 (if (org-mode-p)
24079 (setq html (org-export-region-as-html
24080 beg end t 'string))
24081 (setq reg (buffer-substring beg end)
24082 buf (get-buffer-create "*Org tmp*"))
24083 (with-current-buffer buf
24084 (erase-buffer)
24085 (insert reg)
24086 (org-mode)
24087 (setq html (org-export-region-as-html
24088 (point-min) (point-max) t 'string)))
24089 (kill-buffer buf)))
24090 (delete-region beg end)
24091 (insert html)))
24093 (defun org-export-region-as-html (beg end &optional body-only buffer)
24094 "Convert region from BEG to END in org-mode buffer to HTML.
24095 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
24096 contents, and only produce the region of converted text, useful for
24097 cut-and-paste operations.
24098 If BUFFER is a buffer or a string, use/create that buffer as a target
24099 of the converted HTML. If BUFFER is the symbol `string', return the
24100 produced HTML as a string and leave not buffer behind. For example,
24101 a Lisp program could call this function in the following way:
24103 (setq html (org-export-region-as-html beg end t 'string))
24105 When called interactively, the output buffer is selected, and shown
24106 in a window. A non-interactive call will only retunr the buffer."
24107 (interactive "r\nP")
24108 (when (interactive-p)
24109 (setq buffer "*Org HTML Export*"))
24110 (let ((transient-mark-mode t) (zmacs-regions t)
24111 rtn)
24112 (goto-char end)
24113 (set-mark (point)) ;; to activate the region
24114 (goto-char beg)
24115 (setq rtn (org-export-as-html
24116 nil nil nil
24117 buffer body-only))
24118 (if (fboundp 'deactivate-mark) (deactivate-mark))
24119 (if (and (interactive-p) (bufferp rtn))
24120 (switch-to-buffer-other-window rtn)
24121 rtn)))
24123 (defvar html-table-tag nil) ; dynamically scoped into this.
24124 (defun org-export-as-html (arg &optional hidden ext-plist
24125 to-buffer body-only)
24126 "Export the outline as a pretty HTML file.
24127 If there is an active region, export only the region. The prefix
24128 ARG specifies how many levels of the outline should become
24129 headlines. The default is 3. Lower levels will become bulleted
24130 lists. When HIDDEN is non-nil, don't display the HTML buffer.
24131 EXT-PLIST is a property list with external parameters overriding
24132 org-mode's default settings, but still inferior to file-local
24133 settings. When TO-BUFFER is non-nil, create a buffer with that
24134 name and export to that buffer. If TO-BUFFER is the symbol `string',
24135 don't leave any buffer behind but just return the resulting HTML as
24136 a string. When BODY-ONLY is set, don't produce the file header and footer,
24137 simply return the content of <body>...</body>, without even
24138 the body tags themselves."
24139 (interactive "P")
24141 ;; Make sure we have a file name when we need it.
24142 (when (and (not (or to-buffer body-only))
24143 (not buffer-file-name))
24144 (if (buffer-base-buffer)
24145 (org-set-local 'buffer-file-name
24146 (with-current-buffer (buffer-base-buffer)
24147 buffer-file-name))
24148 (error "Need a file name to be able to export.")))
24150 (message "Exporting...")
24151 (setq-default org-todo-line-regexp org-todo-line-regexp)
24152 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
24153 (setq-default org-done-keywords org-done-keywords)
24154 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
24155 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24156 ext-plist
24157 (org-infile-export-plist)))
24159 (style (plist-get opt-plist :style))
24160 (link-validate (plist-get opt-plist :link-validation-function))
24161 valid thetoc have-headings first-heading-pos
24162 (odd org-odd-levels-only)
24163 (region-p (org-region-active-p))
24164 (subtree-p
24165 (when region-p
24166 (save-excursion
24167 (goto-char (region-beginning))
24168 (and (org-at-heading-p)
24169 (>= (org-end-of-subtree t t) (region-end))))))
24170 ;; The following two are dynamically scoped into other
24171 ;; routines below.
24172 (org-current-export-dir (org-export-directory :html opt-plist))
24173 (org-current-export-file buffer-file-name)
24174 (level 0) (line "") (origline "") txt todo
24175 (umax nil)
24176 (umax-toc nil)
24177 (filename (if to-buffer nil
24178 (concat (file-name-as-directory
24179 (org-export-directory :html opt-plist))
24180 (file-name-sans-extension
24181 (or (and subtree-p
24182 (org-entry-get (region-beginning)
24183 "EXPORT_FILE_NAME" t))
24184 (file-name-nondirectory buffer-file-name)))
24185 "." org-export-html-extension)))
24186 (current-dir (if buffer-file-name
24187 (file-name-directory buffer-file-name)
24188 default-directory))
24189 (buffer (if to-buffer
24190 (cond
24191 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
24192 (t (get-buffer-create to-buffer)))
24193 (find-file-noselect filename)))
24194 (org-levels-open (make-vector org-level-max nil))
24195 (date (plist-get opt-plist :date))
24196 (author (plist-get opt-plist :author))
24197 (title (or (and subtree-p (org-export-get-title-from-subtree))
24198 (plist-get opt-plist :title)
24199 (and (not
24200 (plist-get opt-plist :skip-before-1st-heading))
24201 (org-export-grab-title-from-buffer))
24202 (and buffer-file-name
24203 (file-name-sans-extension
24204 (file-name-nondirectory buffer-file-name)))
24205 "UNTITLED"))
24206 (html-table-tag (plist-get opt-plist :html-table-tag))
24207 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24208 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
24209 (inquote nil)
24210 (infixed nil)
24211 (in-local-list nil)
24212 (local-list-num nil)
24213 (local-list-indent nil)
24214 (llt org-plain-list-ordered-item-terminator)
24215 (email (plist-get opt-plist :email))
24216 (language (plist-get opt-plist :language))
24217 (lang-words nil)
24218 (target-alist nil) tg
24219 (head-count 0) cnt
24220 (start 0)
24221 (coding-system (and (boundp 'buffer-file-coding-system)
24222 buffer-file-coding-system))
24223 (coding-system-for-write (or org-export-html-coding-system
24224 coding-system))
24225 (save-buffer-coding-system (or org-export-html-coding-system
24226 coding-system))
24227 (charset (and coding-system-for-write
24228 (fboundp 'coding-system-get)
24229 (coding-system-get coding-system-for-write
24230 'mime-charset)))
24231 (region
24232 (buffer-substring
24233 (if region-p (region-beginning) (point-min))
24234 (if region-p (region-end) (point-max))))
24235 (lines
24236 (org-split-string
24237 (org-cleaned-string-for-export
24238 region
24239 :emph-multiline t
24240 :for-html t
24241 :skip-before-1st-heading
24242 (plist-get opt-plist :skip-before-1st-heading)
24243 :drawers (plist-get opt-plist :drawers)
24244 :archived-trees
24245 (plist-get opt-plist :archived-trees)
24246 :add-text
24247 (plist-get opt-plist :text)
24248 :LaTeX-fragments
24249 (plist-get opt-plist :LaTeX-fragments))
24250 "[\r\n]"))
24251 table-open type
24252 table-buffer table-orig-buffer
24253 ind start-is-num starter didclose
24254 rpl path desc descp desc1 desc2 link
24257 (let ((inhibit-read-only t))
24258 (org-unmodified
24259 (remove-text-properties (point-min) (point-max)
24260 '(:org-license-to-kill t))))
24262 (message "Exporting...")
24264 (setq org-min-level (org-get-min-level lines))
24265 (setq org-last-level org-min-level)
24266 (org-init-section-numbers)
24268 (cond
24269 ((and date (string-match "%" date))
24270 (setq date (format-time-string date (current-time))))
24271 (date)
24272 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24274 ;; Get the language-dependent settings
24275 (setq lang-words (or (assoc language org-export-language-setup)
24276 (assoc "en" org-export-language-setup)))
24278 ;; Switch to the output buffer
24279 (set-buffer buffer)
24280 (erase-buffer)
24281 (fundamental-mode)
24283 (and (fboundp 'set-buffer-file-coding-system)
24284 (set-buffer-file-coding-system coding-system-for-write))
24286 (let ((case-fold-search nil)
24287 (org-odd-levels-only odd))
24288 ;; create local variables for all options, to make sure all called
24289 ;; functions get the correct information
24290 (mapc (lambda (x)
24291 (set (make-local-variable (cdr x))
24292 (plist-get opt-plist (car x))))
24293 org-export-plist-vars)
24294 (setq umax (if arg (prefix-numeric-value arg)
24295 org-export-headline-levels))
24296 (setq umax-toc (if (integerp org-export-with-toc)
24297 (min org-export-with-toc umax)
24298 umax))
24299 (unless body-only
24300 ;; File header
24301 (insert (format
24302 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
24303 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
24304 <html xmlns=\"http://www.w3.org/1999/xhtml\"
24305 lang=\"%s\" xml:lang=\"%s\">
24306 <head>
24307 <title>%s</title>
24308 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
24309 <meta name=\"generator\" content=\"Org-mode\"/>
24310 <meta name=\"generated\" content=\"%s\"/>
24311 <meta name=\"author\" content=\"%s\"/>
24313 </head><body>
24315 language language (org-html-expand title)
24316 (or charset "iso-8859-1") date author style))
24318 (insert (or (plist-get opt-plist :preamble) ""))
24320 (when (plist-get opt-plist :auto-preamble)
24321 (if title (insert (format org-export-html-title-format
24322 (org-html-expand title))))))
24324 (if (and org-export-with-toc (not body-only))
24325 (progn
24326 (push (format "<h%d>%s</h%d>\n"
24327 org-export-html-toplevel-hlevel
24328 (nth 3 lang-words)
24329 org-export-html-toplevel-hlevel)
24330 thetoc)
24331 (push "<ul>\n<li>" thetoc)
24332 (setq lines
24333 (mapcar '(lambda (line)
24334 (if (string-match org-todo-line-regexp line)
24335 ;; This is a headline
24336 (progn
24337 (setq have-headings t)
24338 (setq level (- (match-end 1) (match-beginning 1))
24339 level (org-tr-level level)
24340 txt (save-match-data
24341 (org-html-expand
24342 (org-export-cleanup-toc-line
24343 (match-string 3 line))))
24344 todo
24345 (or (and org-export-mark-todo-in-toc
24346 (match-beginning 2)
24347 (not (member (match-string 2 line)
24348 org-done-keywords)))
24349 ; TODO, not DONE
24350 (and org-export-mark-todo-in-toc
24351 (= level umax-toc)
24352 (org-search-todo-below
24353 line lines level))))
24354 (if (string-match
24355 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
24356 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
24357 (if (string-match quote-re0 txt)
24358 (setq txt (replace-match "" t t txt)))
24359 (if org-export-with-section-numbers
24360 (setq txt (concat (org-section-number level)
24361 " " txt)))
24362 (if (<= level (max umax umax-toc))
24363 (setq head-count (+ head-count 1)))
24364 (if (<= level umax-toc)
24365 (progn
24366 (if (> level org-last-level)
24367 (progn
24368 (setq cnt (- level org-last-level))
24369 (while (>= (setq cnt (1- cnt)) 0)
24370 (push "\n<ul>\n<li>" thetoc))
24371 (push "\n" thetoc)))
24372 (if (< level org-last-level)
24373 (progn
24374 (setq cnt (- org-last-level level))
24375 (while (>= (setq cnt (1- cnt)) 0)
24376 (push "</li>\n</ul>" thetoc))
24377 (push "\n" thetoc)))
24378 ;; Check for targets
24379 (while (string-match org-target-regexp line)
24380 (setq tg (match-string 1 line)
24381 line (replace-match
24382 (concat "@<span class=\"target\">" tg "@</span> ")
24383 t t line))
24384 (push (cons (org-solidify-link-text tg)
24385 (format "sec-%d" head-count))
24386 target-alist))
24387 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
24388 (setq txt (replace-match "" t t txt)))
24389 (push
24390 (format
24391 (if todo
24392 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
24393 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
24394 head-count txt) thetoc)
24396 (setq org-last-level level))
24398 line)
24399 lines))
24400 (while (> org-last-level (1- org-min-level))
24401 (setq org-last-level (1- org-last-level))
24402 (push "</li>\n</ul>\n" thetoc))
24403 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24405 (setq head-count 0)
24406 (org-init-section-numbers)
24408 (while (setq line (pop lines) origline line)
24409 (catch 'nextline
24411 ;; end of quote section?
24412 (when (and inquote (string-match "^\\*+ " line))
24413 (insert "</pre>\n")
24414 (setq inquote nil))
24415 ;; inside a quote section?
24416 (when inquote
24417 (insert (org-html-protect line) "\n")
24418 (throw 'nextline nil))
24420 ;; verbatim lines
24421 (when (and org-export-with-fixed-width
24422 (string-match "^[ \t]*:\\(.*\\)" line))
24423 (when (not infixed)
24424 (setq infixed t)
24425 (insert "<pre>\n"))
24426 (insert (org-html-protect (match-string 1 line)) "\n")
24427 (when (and lines
24428 (not (string-match "^[ \t]*\\(:.*\\)"
24429 (car lines))))
24430 (setq infixed nil)
24431 (insert "</pre>\n"))
24432 (throw 'nextline nil))
24434 ;; Protected HTML
24435 (when (get-text-property 0 'org-protected line)
24436 (let (par)
24437 (when (re-search-backward
24438 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
24439 (setq par (match-string 1))
24440 (replace-match "\\2\n"))
24441 (insert line "\n")
24442 (while (and lines
24443 (get-text-property 0 'org-protected (car lines)))
24444 (insert (pop lines) "\n"))
24445 (and par (insert "<p>\n")))
24446 (throw 'nextline nil))
24448 ;; Horizontal line
24449 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
24450 (insert "\n<hr/>\n")
24451 (throw 'nextline nil))
24453 ;; make targets to anchors
24454 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
24455 (cond
24456 ((match-end 2)
24457 (setq line (replace-match
24458 (concat "@<a name=\""
24459 (org-solidify-link-text (match-string 1 line))
24460 "\">\\nbsp@</a>")
24461 t t line)))
24462 ((and org-export-with-toc (equal (string-to-char line) ?*))
24463 (setq line (replace-match
24464 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
24465 ; (concat "@<i>" (match-string 1 line) "@</i> ")
24466 t t line)))
24468 (setq line (replace-match
24469 (concat "@<a name=\""
24470 (org-solidify-link-text (match-string 1 line))
24471 "\" class=\"target\">" (match-string 1 line) "@</a> ")
24472 t t line)))))
24474 (setq line (org-html-handle-time-stamps line))
24476 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
24477 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
24478 ;; Also handle sub_superscripts and checkboxes
24479 (or (string-match org-table-hline-regexp line)
24480 (setq line (org-html-expand line)))
24482 ;; Format the links
24483 (setq start 0)
24484 (while (string-match org-bracket-link-analytic-regexp line start)
24485 (setq start (match-beginning 0))
24486 (setq type (if (match-end 2) (match-string 2 line) "internal"))
24487 (setq path (match-string 3 line))
24488 (setq desc1 (if (match-end 5) (match-string 5 line))
24489 desc2 (if (match-end 2) (concat type ":" path) path)
24490 descp (and desc1 (not (equal desc1 desc2)))
24491 desc (or desc1 desc2))
24492 ;; Make an image out of the description if that is so wanted
24493 (when (and descp (org-file-image-p desc))
24494 (save-match-data
24495 (if (string-match "^file:" desc)
24496 (setq desc (substring desc (match-end 0)))))
24497 (setq desc (concat "<img src=\"" desc "\"/>")))
24498 ;; FIXME: do we need to unescape here somewhere?
24499 (cond
24500 ((equal type "internal")
24501 (setq rpl
24502 (concat
24503 "<a href=\"#"
24504 (org-solidify-link-text
24505 (save-match-data (org-link-unescape path)) target-alist)
24506 "\">" desc "</a>")))
24507 ((member type '("http" "https"))
24508 ;; standard URL, just check if we need to inline an image
24509 (if (and (or (eq t org-export-html-inline-images)
24510 (and org-export-html-inline-images (not descp)))
24511 (org-file-image-p path))
24512 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
24513 (setq link (concat type ":" path))
24514 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
24515 ((member type '("ftp" "mailto" "news"))
24516 ;; standard URL
24517 (setq link (concat type ":" path))
24518 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
24519 ((string= type "file")
24520 ;; FILE link
24521 (let* ((filename path)
24522 (abs-p (file-name-absolute-p filename))
24523 thefile file-is-image-p search)
24524 (save-match-data
24525 (if (string-match "::\\(.*\\)" filename)
24526 (setq search (match-string 1 filename)
24527 filename (replace-match "" t nil filename)))
24528 (setq valid
24529 (if (functionp link-validate)
24530 (funcall link-validate filename current-dir)
24532 (setq file-is-image-p (org-file-image-p filename))
24533 (setq thefile (if abs-p (expand-file-name filename) filename))
24534 (when (and org-export-html-link-org-files-as-html
24535 (string-match "\\.org$" thefile))
24536 (setq thefile (concat (substring thefile 0
24537 (match-beginning 0))
24538 "." org-export-html-extension))
24539 (if (and search
24540 ;; make sure this is can be used as target search
24541 (not (string-match "^[0-9]*$" search))
24542 (not (string-match "^\\*" search))
24543 (not (string-match "^/.*/$" search)))
24544 (setq thefile (concat thefile "#"
24545 (org-solidify-link-text
24546 (org-link-unescape search)))))
24547 (when (string-match "^file:" desc)
24548 (setq desc (replace-match "" t t desc))
24549 (if (string-match "\\.org$" desc)
24550 (setq desc (replace-match "" t t desc))))))
24551 (setq rpl (if (and file-is-image-p
24552 (or (eq t org-export-html-inline-images)
24553 (and org-export-html-inline-images
24554 (not descp))))
24555 (concat "<img src=\"" thefile "\"/>")
24556 (concat "<a href=\"" thefile "\">" desc "</a>")))
24557 (if (not valid) (setq rpl desc))))
24558 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
24559 (setq rpl (concat "<i>&lt;" type ":"
24560 (save-match-data (org-link-unescape path))
24561 "&gt;</i>"))))
24562 (setq line (replace-match rpl t t line)
24563 start (+ start (length rpl))))
24565 ;; TODO items
24566 (if (and (string-match org-todo-line-regexp line)
24567 (match-beginning 2))
24569 (setq line
24570 (concat (substring line 0 (match-beginning 2))
24571 "<span class=\""
24572 (if (member (match-string 2 line)
24573 org-done-keywords)
24574 "done" "todo")
24575 "\">" (match-string 2 line)
24576 "</span>" (substring line (match-end 2)))))
24578 ;; Does this contain a reference to a footnote?
24579 (when org-export-with-footnotes
24580 (setq start 0)
24581 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
24582 (if (get-text-property (match-beginning 2) 'org-protected line)
24583 (setq start (match-end 2))
24584 (let ((n (match-string 2 line)))
24585 (setq line
24586 (replace-match
24587 (format
24588 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
24589 (match-string 1 line) n n n)
24590 t t line))))))
24592 (cond
24593 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24594 ;; This is a headline
24595 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24596 txt (match-string 2 line))
24597 (if (string-match quote-re0 txt)
24598 (setq txt (replace-match "" t t txt)))
24599 (if (<= level (max umax umax-toc))
24600 (setq head-count (+ head-count 1)))
24601 (when in-local-list
24602 ;; Close any local lists before inserting a new header line
24603 (while local-list-num
24604 (org-close-li)
24605 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
24606 (pop local-list-num))
24607 (setq local-list-indent nil
24608 in-local-list nil))
24609 (setq first-heading-pos (or first-heading-pos (point)))
24610 (org-html-level-start level txt umax
24611 (and org-export-with-toc (<= level umax))
24612 head-count)
24613 ;; QUOTES
24614 (when (string-match quote-re line)
24615 (insert "<pre>")
24616 (setq inquote t)))
24618 ((and org-export-with-tables
24619 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24620 (if (not table-open)
24621 ;; New table starts
24622 (setq table-open t table-buffer nil table-orig-buffer nil))
24623 ;; Accumulate lines
24624 (setq table-buffer (cons line table-buffer)
24625 table-orig-buffer (cons origline table-orig-buffer))
24626 (when (or (not lines)
24627 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24628 (car lines))))
24629 (setq table-open nil
24630 table-buffer (nreverse table-buffer)
24631 table-orig-buffer (nreverse table-orig-buffer))
24632 (org-close-par-maybe)
24633 (insert (org-format-table-html table-buffer table-orig-buffer))))
24635 ;; Normal lines
24636 (when (string-match
24637 (cond
24638 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
24639 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
24640 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
24641 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
24642 line)
24643 (setq ind (org-get-string-indentation line)
24644 start-is-num (match-beginning 4)
24645 starter (if (match-beginning 2)
24646 (substring (match-string 2 line) 0 -1))
24647 line (substring line (match-beginning 5)))
24648 (unless (string-match "[^ \t]" line)
24649 ;; empty line. Pretend indentation is large.
24650 (setq ind (if org-empty-line-terminates-plain-lists
24652 (1+ (or (car local-list-indent) 1)))))
24653 (setq didclose nil)
24654 (while (and in-local-list
24655 (or (and (= ind (car local-list-indent))
24656 (not starter))
24657 (< ind (car local-list-indent))))
24658 (setq didclose t)
24659 (org-close-li)
24660 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
24661 (pop local-list-num) (pop local-list-indent)
24662 (setq in-local-list local-list-indent))
24663 (cond
24664 ((and starter
24665 (or (not in-local-list)
24666 (> ind (car local-list-indent))))
24667 ;; Start new (level of) list
24668 (org-close-par-maybe)
24669 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
24670 (push start-is-num local-list-num)
24671 (push ind local-list-indent)
24672 (setq in-local-list t))
24673 (starter
24674 ;; continue current list
24675 (org-close-li)
24676 (insert "<li>\n"))
24677 (didclose
24678 ;; we did close a list, normal text follows: need <p>
24679 (org-open-par)))
24680 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
24681 (setq line
24682 (replace-match
24683 (if (equal (match-string 1 line) "X")
24684 "<b>[X]</b>"
24685 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
24686 t t line))))
24688 ;; Empty lines start a new paragraph. If hand-formatted lists
24689 ;; are not fully interpreted, lines starting with "-", "+", "*"
24690 ;; also start a new paragraph.
24691 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
24693 ;; Is this the start of a footnote?
24694 (when org-export-with-footnotes
24695 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
24696 (org-close-par-maybe)
24697 (let ((n (match-string 1 line)))
24698 (setq line (replace-match
24699 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
24701 ;; Check if the line break needs to be conserved
24702 (cond
24703 ((string-match "\\\\\\\\[ \t]*$" line)
24704 (setq line (replace-match "<br/>" t t line)))
24705 (org-export-preserve-breaks
24706 (setq line (concat line "<br/>"))))
24708 (insert line "\n")))))
24710 ;; Properly close all local lists and other lists
24711 (when inquote (insert "</pre>\n"))
24712 (when in-local-list
24713 ;; Close any local lists before inserting a new header line
24714 (while local-list-num
24715 (org-close-li)
24716 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
24717 (pop local-list-num))
24718 (setq local-list-indent nil
24719 in-local-list nil))
24720 (org-html-level-start 1 nil umax
24721 (and org-export-with-toc (<= level umax))
24722 head-count)
24724 (unless body-only
24725 (when (plist-get opt-plist :auto-postamble)
24726 (insert "<div id=\"postamble\">")
24727 (when (and org-export-author-info author)
24728 (insert "<p class=\"author\"> "
24729 (nth 1 lang-words) ": " author "\n")
24730 (when email
24731 (if (listp (split-string email ",+ *"))
24732 (mapc (lambda(e)
24733 (insert "<a href=\"mailto:" e "\">&lt;"
24734 e "&gt;</a>\n"))
24735 (split-string email ",+ *"))
24736 (insert "<a href=\"mailto:" email "\">&lt;"
24737 email "&gt;</a>\n")))
24738 (insert "</p>\n"))
24739 (when (and date org-export-time-stamp-file)
24740 (insert "<p class=\"date\"> "
24741 (nth 2 lang-words) ": "
24742 date "</p>\n"))
24743 (insert "</div>"))
24745 (if org-export-html-with-timestamp
24746 (insert org-export-html-html-helper-timestamp))
24747 (insert (or (plist-get opt-plist :postamble) ""))
24748 (insert "</body>\n</html>\n"))
24750 (normal-mode)
24751 (if (eq major-mode default-major-mode) (html-mode))
24753 ;; insert the table of contents
24754 (goto-char (point-min))
24755 (when thetoc
24756 (if (or (re-search-forward
24757 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
24758 (re-search-forward
24759 "\\[TABLE-OF-CONTENTS\\]" nil t))
24760 (progn
24761 (goto-char (match-beginning 0))
24762 (replace-match ""))
24763 (goto-char first-heading-pos)
24764 (when (looking-at "\\s-*</p>")
24765 (goto-char (match-end 0))
24766 (insert "\n")))
24767 (insert "<div id=\"table-of-contents\">\n")
24768 (mapc 'insert thetoc)
24769 (insert "</div>\n"))
24770 ;; remove empty paragraphs and lists
24771 (goto-char (point-min))
24772 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
24773 (replace-match ""))
24774 (goto-char (point-min))
24775 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
24776 (replace-match ""))
24777 ;; Convert whitespace place holders
24778 (goto-char (point-min))
24779 (let (beg end n)
24780 (while (setq beg (next-single-property-change (point) 'org-whitespace))
24781 (setq n (get-text-property beg 'org-whitespace)
24782 end (next-single-property-change beg 'org-whitespace))
24783 (goto-char beg)
24784 (delete-region beg end)
24785 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
24786 (make-string n ?x)))))
24788 (or to-buffer (save-buffer))
24789 (goto-char (point-min))
24790 (message "Exporting... done")
24791 (if (eq to-buffer 'string)
24792 (prog1 (buffer-substring (point-min) (point-max))
24793 (kill-buffer (current-buffer)))
24794 (current-buffer)))))
24796 (defvar org-table-colgroup-info nil)
24797 (defun org-format-table-ascii (lines)
24798 "Format a table for ascii export."
24799 (if (stringp lines)
24800 (setq lines (org-split-string lines "\n")))
24801 (if (not (string-match "^[ \t]*|" (car lines)))
24802 ;; Table made by table.el - test for spanning
24803 lines
24805 ;; A normal org table
24806 ;; Get rid of hlines at beginning and end
24807 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
24808 (setq lines (nreverse lines))
24809 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
24810 (setq lines (nreverse lines))
24811 (when org-export-table-remove-special-lines
24812 ;; Check if the table has a marking column. If yes remove the
24813 ;; column and the special lines
24814 (setq lines (org-table-clean-before-export lines)))
24815 ;; Get rid of the vertical lines except for grouping
24816 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
24817 rtn line vl1 start)
24818 (while (setq line (pop lines))
24819 (if (string-match org-table-hline-regexp line)
24820 (and (string-match "|\\(.*\\)|" line)
24821 (setq line (replace-match " \\1" t nil line)))
24822 (setq start 0 vl1 vl)
24823 (while (string-match "|" line start)
24824 (setq start (match-end 0))
24825 (or (pop vl1) (setq line (replace-match " " t t line)))))
24826 (push line rtn))
24827 (nreverse rtn))))
24829 (defun org-colgroup-info-to-vline-list (info)
24830 (let (vl new last)
24831 (while info
24832 (setq last new new (pop info))
24833 (if (or (memq last '(:end :startend))
24834 (memq new '(:start :startend)))
24835 (push t vl)
24836 (push nil vl)))
24837 (setq vl (nreverse vl))
24838 (and vl (setcar vl nil))
24839 vl))
24841 (defun org-format-table-html (lines olines)
24842 "Find out which HTML converter to use and return the HTML code."
24843 (if (stringp lines)
24844 (setq lines (org-split-string lines "\n")))
24845 (if (string-match "^[ \t]*|" (car lines))
24846 ;; A normal org table
24847 (org-format-org-table-html lines)
24848 ;; Table made by table.el - test for spanning
24849 (let* ((hlines (delq nil (mapcar
24850 (lambda (x)
24851 (if (string-match "^[ \t]*\\+-" x) x
24852 nil))
24853 lines)))
24854 (first (car hlines))
24855 (ll (and (string-match "\\S-+" first)
24856 (match-string 0 first)))
24857 (re (concat "^[ \t]*" (regexp-quote ll)))
24858 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
24859 hlines))))
24860 (if (and (not spanning)
24861 (not org-export-prefer-native-exporter-for-tables))
24862 ;; We can use my own converter with HTML conversions
24863 (org-format-table-table-html lines)
24864 ;; Need to use the code generator in table.el, with the original text.
24865 (org-format-table-table-html-using-table-generate-source olines)))))
24867 (defun org-format-org-table-html (lines &optional splice)
24868 "Format a table into HTML."
24869 ;; Get rid of hlines at beginning and end
24870 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
24871 (setq lines (nreverse lines))
24872 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
24873 (setq lines (nreverse lines))
24874 (when org-export-table-remove-special-lines
24875 ;; Check if the table has a marking column. If yes remove the
24876 ;; column and the special lines
24877 (setq lines (org-table-clean-before-export lines)))
24879 (let ((head (and org-export-highlight-first-table-line
24880 (delq nil (mapcar
24881 (lambda (x) (string-match "^[ \t]*|-" x))
24882 (cdr lines)))))
24883 (nlines 0) fnum i
24884 tbopen line fields html gr colgropen)
24885 (if splice (setq head nil))
24886 (unless splice (push (if head "<thead>" "<tbody>") html))
24887 (setq tbopen t)
24888 (while (setq line (pop lines))
24889 (catch 'next-line
24890 (if (string-match "^[ \t]*|-" line)
24891 (progn
24892 (unless splice
24893 (push (if head "</thead>" "</tbody>") html)
24894 (if lines (push "<tbody>" html) (setq tbopen nil)))
24895 (setq head nil) ;; head ends here, first time around
24896 ;; ignore this line
24897 (throw 'next-line t)))
24898 ;; Break the line into fields
24899 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
24900 (unless fnum (setq fnum (make-vector (length fields) 0)))
24901 (setq nlines (1+ nlines) i -1)
24902 (push (concat "<tr>"
24903 (mapconcat
24904 (lambda (x)
24905 (setq i (1+ i))
24906 (if (and (< i nlines)
24907 (string-match org-table-number-regexp x))
24908 (incf (aref fnum i)))
24909 (if head
24910 (concat (car org-export-table-header-tags) x
24911 (cdr org-export-table-header-tags))
24912 (concat (car org-export-table-data-tags) x
24913 (cdr org-export-table-data-tags))))
24914 fields "")
24915 "</tr>")
24916 html)))
24917 (unless splice (if tbopen (push "</tbody>" html)))
24918 (unless splice (push "</table>\n" html))
24919 (setq html (nreverse html))
24920 (unless splice
24921 ;; Put in col tags with the alignment (unfortuntely often ignored...)
24922 (push (mapconcat
24923 (lambda (x)
24924 (setq gr (pop org-table-colgroup-info))
24925 (format "%s<col align=\"%s\"></col>%s"
24926 (if (memq gr '(:start :startend))
24927 (prog1
24928 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
24929 (setq colgropen t))
24931 (if (> (/ (float x) nlines) org-table-number-fraction)
24932 "right" "left")
24933 (if (memq gr '(:end :startend))
24934 (progn (setq colgropen nil) "</colgroup>")
24935 "")))
24936 fnum "")
24937 html)
24938 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
24939 (push html-table-tag html))
24940 (concat (mapconcat 'identity html "\n") "\n")))
24942 (defun org-table-clean-before-export (lines)
24943 "Check if the table has a marking column.
24944 If yes remove the column and the special lines."
24945 (setq org-table-colgroup-info nil)
24946 (if (memq nil
24947 (mapcar
24948 (lambda (x) (or (string-match "^[ \t]*|-" x)
24949 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
24950 lines))
24951 (progn
24952 (setq org-table-clean-did-remove-column nil)
24953 (delq nil
24954 (mapcar
24955 (lambda (x)
24956 (cond
24957 ((string-match "^[ \t]*| */ *|" x)
24958 (setq org-table-colgroup-info
24959 (mapcar (lambda (x)
24960 (cond ((member x '("<" "&lt;")) :start)
24961 ((member x '(">" "&gt;")) :end)
24962 ((member x '("<>" "&lt;&gt;")) :startend)
24963 (t nil)))
24964 (org-split-string x "[ \t]*|[ \t]*")))
24965 nil)
24966 (t x)))
24967 lines)))
24968 (setq org-table-clean-did-remove-column t)
24969 (delq nil
24970 (mapcar
24971 (lambda (x)
24972 (cond
24973 ((string-match "^[ \t]*| */ *|" x)
24974 (setq org-table-colgroup-info
24975 (mapcar (lambda (x)
24976 (cond ((member x '("<" "&lt;")) :start)
24977 ((member x '(">" "&gt;")) :end)
24978 ((member x '("<>" "&lt;&gt;")) :startend)
24979 (t nil)))
24980 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
24981 nil)
24982 ((string-match "^[ \t]*| *[!_^/] *|" x)
24983 nil) ; ignore this line
24984 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
24985 (string-match "^\\([ \t]*\\)|[^|]*|" x))
24986 ;; remove the first column
24987 (replace-match "\\1|" t nil x))))
24988 lines))))
24990 (defun org-format-table-table-html (lines)
24991 "Format a table generated by table.el into HTML.
24992 This conversion does *not* use `table-generate-source' from table.el.
24993 This has the advantage that Org-mode's HTML conversions can be used.
24994 But it has the disadvantage, that no cell- or row-spanning is allowed."
24995 (let (line field-buffer
24996 (head org-export-highlight-first-table-line)
24997 fields html empty)
24998 (setq html (concat html-table-tag "\n"))
24999 (while (setq line (pop lines))
25000 (setq empty "&nbsp;")
25001 (catch 'next-line
25002 (if (string-match "^[ \t]*\\+-" line)
25003 (progn
25004 (if field-buffer
25005 (progn
25006 (setq
25007 html
25008 (concat
25009 html
25010 "<tr>"
25011 (mapconcat
25012 (lambda (x)
25013 (if (equal x "") (setq x empty))
25014 (if head
25015 (concat (car org-export-table-header-tags) x
25016 (cdr org-export-table-header-tags))
25017 (concat (car org-export-table-data-tags) x
25018 (cdr org-export-table-data-tags))))
25019 field-buffer "\n")
25020 "</tr>\n"))
25021 (setq head nil)
25022 (setq field-buffer nil)))
25023 ;; Ignore this line
25024 (throw 'next-line t)))
25025 ;; Break the line into fields and store the fields
25026 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25027 (if field-buffer
25028 (setq field-buffer (mapcar
25029 (lambda (x)
25030 (concat x "<br/>" (pop fields)))
25031 field-buffer))
25032 (setq field-buffer fields))))
25033 (setq html (concat html "</table>\n"))
25034 html))
25036 (defun org-format-table-table-html-using-table-generate-source (lines)
25037 "Format a table into html, using `table-generate-source' from table.el.
25038 This has the advantage that cell- or row-spanning is allowed.
25039 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
25040 (require 'table)
25041 (with-current-buffer (get-buffer-create " org-tmp1 ")
25042 (erase-buffer)
25043 (insert (mapconcat 'identity lines "\n"))
25044 (goto-char (point-min))
25045 (if (not (re-search-forward "|[^+]" nil t))
25046 (error "Error processing table"))
25047 (table-recognize-table)
25048 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
25049 (table-generate-source 'html " org-tmp2 ")
25050 (set-buffer " org-tmp2 ")
25051 (buffer-substring (point-min) (point-max))))
25053 (defun org-html-handle-time-stamps (s)
25054 "Format time stamps in string S, or remove them."
25055 (catch 'exit
25056 (let (r b)
25057 (while (string-match org-maybe-keyword-time-regexp s)
25058 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
25059 ;; never export CLOCK
25060 (throw 'exit ""))
25061 (or b (setq b (substring s 0 (match-beginning 0))))
25062 (if (not org-export-with-timestamps)
25063 (setq r (concat r (substring s 0 (match-beginning 0)))
25064 s (substring s (match-end 0)))
25065 (setq r (concat
25066 r (substring s 0 (match-beginning 0))
25067 (if (match-end 1)
25068 (format "@<span class=\"timestamp-kwd\">%s @</span>"
25069 (match-string 1 s)))
25070 (format " @<span class=\"timestamp\">%s@</span>"
25071 (substring
25072 (org-translate-time (match-string 3 s)) 1 -1)))
25073 s (substring s (match-end 0)))))
25074 ;; Line break if line started and ended with time stamp stuff
25075 (if (not r)
25077 (setq r (concat r s))
25078 (unless (string-match "\\S-" (concat b s))
25079 (setq r (concat r "@<br/>")))
25080 r))))
25082 (defun org-html-protect (s)
25083 ;; convert & to &amp;, < to &lt; and > to &gt;
25084 (let ((start 0))
25085 (while (string-match "&" s start)
25086 (setq s (replace-match "&amp;" t t s)
25087 start (1+ (match-beginning 0))))
25088 (while (string-match "<" s)
25089 (setq s (replace-match "&lt;" t t s)))
25090 (while (string-match ">" s)
25091 (setq s (replace-match "&gt;" t t s))))
25094 (defun org-export-cleanup-toc-line (s)
25095 "Remove tags and time staps from lines going into the toc."
25096 (when (memq org-export-with-tags '(not-in-toc nil))
25097 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
25098 (setq s (replace-match "" t t s))))
25099 (when org-export-remove-timestamps-from-toc
25100 (while (string-match org-maybe-keyword-time-regexp s)
25101 (setq s (replace-match "" t t s))))
25102 (while (string-match org-bracket-link-regexp s)
25103 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
25104 t t s)))
25107 (defun org-html-expand (string)
25108 "Prepare STRING for HTML export. Applies all active conversions.
25109 If there are links in the string, don't modify these."
25110 (let* ((re (concat org-bracket-link-regexp "\\|"
25111 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
25112 m s l res)
25113 (while (setq m (string-match re string))
25114 (setq s (substring string 0 m)
25115 l (match-string 0 string)
25116 string (substring string (match-end 0)))
25117 (push (org-html-do-expand s) res)
25118 (push l res))
25119 (push (org-html-do-expand string) res)
25120 (apply 'concat (nreverse res))))
25122 (defun org-html-do-expand (s)
25123 "Apply all active conversions to translate special ASCII to HTML."
25124 (setq s (org-html-protect s))
25125 (if org-export-html-expand
25126 (let ((start 0))
25127 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
25128 (setq s (replace-match "<\\1>" t nil s)))))
25129 (if org-export-with-emphasize
25130 (setq s (org-export-html-convert-emphasize s)))
25131 (if org-export-with-special-strings
25132 (setq s (org-export-html-convert-special-strings s)))
25133 (if org-export-with-sub-superscripts
25134 (setq s (org-export-html-convert-sub-super s)))
25135 (if org-export-with-TeX-macros
25136 (let ((start 0) wd ass)
25137 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
25138 (if (get-text-property (match-beginning 0) 'org-protected s)
25139 (setq start (match-end 0))
25140 (setq wd (match-string 1 s))
25141 (if (setq ass (assoc wd org-html-entities))
25142 (setq s (replace-match (or (cdr ass)
25143 (concat "&" (car ass) ";"))
25144 t t s))
25145 (setq start (+ start (length wd))))))))
25148 (defun org-create-multibrace-regexp (left right n)
25149 "Create a regular expression which will match a balanced sexp.
25150 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
25151 as single character strings.
25152 The regexp returned will match the entire expression including the
25153 delimiters. It will also define a single group which contains the
25154 match except for the outermost delimiters. The maximum depth of
25155 stacked delimiters is N. Escaping delimiters is not possible."
25156 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
25157 (or "\\|")
25158 (re nothing)
25159 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
25160 (while (> n 1)
25161 (setq n (1- n)
25162 re (concat re or next)
25163 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
25164 (concat left "\\(" re "\\)" right)))
25166 (defvar org-match-substring-regexp
25167 (concat
25168 "\\([^\\]\\)\\([_^]\\)\\("
25169 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
25170 "\\|"
25171 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
25172 "\\|"
25173 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
25174 "The regular expression matching a sub- or superscript.")
25176 (defvar org-match-substring-with-braces-regexp
25177 (concat
25178 "\\([^\\]\\)\\([_^]\\)\\("
25179 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
25180 "\\)")
25181 "The regular expression matching a sub- or superscript, forcing braces.")
25183 (defconst org-export-html-special-string-regexps
25184 '(("\\\\-" . "&shy;")
25185 ("---\\([^-]\\)" . "&mdash;\\1")
25186 ("--\\([^-]\\)" . "&ndash;\\1")
25187 ("\\.\\.\\." . "&hellip;"))
25188 "Regular expressions for special string conversion.")
25190 (defun org-export-html-convert-special-strings (string)
25191 "Convert special characters in STRING to HTML."
25192 (let ((all org-export-html-special-string-regexps)
25193 e a re rpl start)
25194 (while (setq a (pop all))
25195 (setq re (car a) rpl (cdr a) start 0)
25196 (while (string-match re string start)
25197 (if (get-text-property (match-beginning 0) 'org-protected string)
25198 (setq start (match-end 0))
25199 (setq string (replace-match rpl t nil string)))))
25200 string))
25202 (defun org-export-html-convert-sub-super (string)
25203 "Convert sub- and superscripts in STRING to HTML."
25204 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
25205 (while (string-match org-match-substring-regexp string s)
25206 (cond
25207 ((and requireb (match-end 8)) (setq s (match-end 2)))
25208 ((get-text-property (match-beginning 2) 'org-protected string)
25209 (setq s (match-end 2)))
25211 (setq s (match-end 1)
25212 key (if (string= (match-string 2 string) "_") "sub" "sup")
25213 c (or (match-string 8 string)
25214 (match-string 6 string)
25215 (match-string 5 string))
25216 string (replace-match
25217 (concat (match-string 1 string)
25218 "<" key ">" c "</" key ">")
25219 t t string)))))
25220 (while (string-match "\\\\\\([_^]\\)" string)
25221 (setq string (replace-match (match-string 1 string) t t string)))
25222 string))
25224 (defun org-export-html-convert-emphasize (string)
25225 "Apply emphasis."
25226 (let ((s 0) rpl)
25227 (while (string-match org-emph-re string s)
25228 (if (not (equal
25229 (substring string (match-beginning 3) (1+ (match-beginning 3)))
25230 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
25231 (setq s (match-beginning 0)
25233 (concat
25234 (match-string 1 string)
25235 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
25236 (match-string 4 string)
25237 (nth 3 (assoc (match-string 3 string)
25238 org-emphasis-alist))
25239 (match-string 5 string))
25240 string (replace-match rpl t t string)
25241 s (+ s (- (length rpl) 2)))
25242 (setq s (1+ s))))
25243 string))
25245 (defvar org-par-open nil)
25246 (defun org-open-par ()
25247 "Insert <p>, but first close previous paragraph if any."
25248 (org-close-par-maybe)
25249 (insert "\n<p>")
25250 (setq org-par-open t))
25251 (defun org-close-par-maybe ()
25252 "Close paragraph if there is one open."
25253 (when org-par-open
25254 (insert "</p>")
25255 (setq org-par-open nil)))
25256 (defun org-close-li ()
25257 "Close <li> if necessary."
25258 (org-close-par-maybe)
25259 (insert "</li>\n"))
25261 (defvar body-only) ; dynamically scoped into this.
25262 (defun org-html-level-start (level title umax with-toc head-count)
25263 "Insert a new level in HTML export.
25264 When TITLE is nil, just close all open levels."
25265 (org-close-par-maybe)
25266 (let ((l org-level-max))
25267 (while (>= l level)
25268 (if (aref org-levels-open (1- l))
25269 (progn
25270 (org-html-level-close l umax)
25271 (aset org-levels-open (1- l) nil)))
25272 (setq l (1- l)))
25273 (when title
25274 ;; If title is nil, this means this function is called to close
25275 ;; all levels, so the rest is done only if title is given
25276 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
25277 (setq title (replace-match
25278 (if org-export-with-tags
25279 (save-match-data
25280 (concat
25281 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
25282 (mapconcat 'identity (org-split-string
25283 (match-string 1 title) ":")
25284 "&nbsp;")
25285 "</span>"))
25287 t t title)))
25288 (if (> level umax)
25289 (progn
25290 (if (aref org-levels-open (1- level))
25291 (progn
25292 (org-close-li)
25293 (insert "<li>" title "<br/>\n"))
25294 (aset org-levels-open (1- level) t)
25295 (org-close-par-maybe)
25296 (insert "<ul>\n<li>" title "<br/>\n")))
25297 (aset org-levels-open (1- level) t)
25298 (if (and org-export-with-section-numbers (not body-only))
25299 (setq title (concat (org-section-number level) " " title)))
25300 (setq level (+ level org-export-html-toplevel-hlevel -1))
25301 (if with-toc
25302 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
25303 level level head-count title level))
25304 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
25305 (org-open-par)))))
25307 (defun org-html-level-close (level max-outline-level)
25308 "Terminate one level in HTML export."
25309 (if (<= level max-outline-level)
25310 (insert "</div>\n")
25311 (org-close-li)
25312 (insert "</ul>\n")))
25314 ;;; iCalendar export
25316 ;;;###autoload
25317 (defun org-export-icalendar-this-file ()
25318 "Export current file as an iCalendar file.
25319 The iCalendar file will be located in the same directory as the Org-mode
25320 file, but with extension `.ics'."
25321 (interactive)
25322 (org-export-icalendar nil buffer-file-name))
25324 ;;;###autoload
25325 (defun org-export-icalendar-all-agenda-files ()
25326 "Export all files in `org-agenda-files' to iCalendar .ics files.
25327 Each iCalendar file will be located in the same directory as the Org-mode
25328 file, but with extension `.ics'."
25329 (interactive)
25330 (apply 'org-export-icalendar nil (org-agenda-files t)))
25332 ;;;###autoload
25333 (defun org-export-icalendar-combine-agenda-files ()
25334 "Export all files in `org-agenda-files' to a single combined iCalendar file.
25335 The file is stored under the name `org-combined-agenda-icalendar-file'."
25336 (interactive)
25337 (apply 'org-export-icalendar t (org-agenda-files t)))
25339 (defun org-export-icalendar (combine &rest files)
25340 "Create iCalendar files for all elements of FILES.
25341 If COMBINE is non-nil, combine all calendar entries into a single large
25342 file and store it under the name `org-combined-agenda-icalendar-file'."
25343 (save-excursion
25344 (org-prepare-agenda-buffers files)
25345 (let* ((dir (org-export-directory
25346 :ical (list :publishing-directory
25347 org-export-publishing-directory)))
25348 file ical-file ical-buffer category started org-agenda-new-buffers)
25350 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
25351 (when combine
25352 (setq ical-file
25353 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
25354 org-combined-agenda-icalendar-file
25355 (expand-file-name org-combined-agenda-icalendar-file dir))
25356 ical-buffer (org-get-agenda-file-buffer ical-file))
25357 (set-buffer ical-buffer) (erase-buffer))
25358 (while (setq file (pop files))
25359 (catch 'nextfile
25360 (org-check-agenda-file file)
25361 (set-buffer (org-get-agenda-file-buffer file))
25362 (unless combine
25363 (setq ical-file (concat (file-name-as-directory dir)
25364 (file-name-sans-extension
25365 (file-name-nondirectory buffer-file-name))
25366 ".ics"))
25367 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
25368 (with-current-buffer ical-buffer (erase-buffer)))
25369 (setq category (or org-category
25370 (file-name-sans-extension
25371 (file-name-nondirectory buffer-file-name))))
25372 (if (symbolp category) (setq category (symbol-name category)))
25373 (let ((standard-output ical-buffer))
25374 (if combine
25375 (and (not started) (setq started t)
25376 (org-start-icalendar-file org-icalendar-combined-name))
25377 (org-start-icalendar-file category))
25378 (org-print-icalendar-entries combine)
25379 (when (or (and combine (not files)) (not combine))
25380 (org-finish-icalendar-file)
25381 (set-buffer ical-buffer)
25382 (save-buffer)
25383 (run-hooks 'org-after-save-iCalendar-file-hook)))))
25384 (org-release-buffers org-agenda-new-buffers))))
25386 (defvar org-after-save-iCalendar-file-hook nil
25387 "Hook run after an iCalendar file has been saved.
25388 The iCalendar buffer is still current when this hook is run.
25389 A good way to use this is to tell a desktop calenndar application to re-read
25390 the iCalendar file.")
25392 (defun org-print-icalendar-entries (&optional combine)
25393 "Print iCalendar entries for the current Org-mode file to `standard-output'.
25394 When COMBINE is non nil, add the category to each line."
25395 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
25396 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
25397 (dts (org-ical-ts-to-string
25398 (format-time-string (cdr org-time-stamp-formats) (current-time))
25399 "DTSTART"))
25400 hd ts ts2 state status (inc t) pos b sexp rrule
25401 scheduledp deadlinep tmp pri category entry location summary desc
25402 (sexp-buffer (get-buffer-create "*ical-tmp*")))
25403 (org-refresh-category-properties)
25404 (save-excursion
25405 (goto-char (point-min))
25406 (while (re-search-forward re1 nil t)
25407 (catch :skip
25408 (org-agenda-skip)
25409 (setq pos (match-beginning 0)
25410 ts (match-string 0)
25411 inc t
25412 hd (org-get-heading)
25413 summary (org-icalendar-cleanup-string
25414 (org-entry-get nil "SUMMARY"))
25415 desc (org-icalendar-cleanup-string
25416 (or (org-entry-get nil "DESCRIPTION")
25417 (and org-icalendar-include-body (org-get-entry)))
25418 t org-icalendar-include-body)
25419 location (org-icalendar-cleanup-string
25420 (org-entry-get nil "LOCATION"))
25421 category (org-get-category))
25422 (if (looking-at re2)
25423 (progn
25424 (goto-char (match-end 0))
25425 (setq ts2 (match-string 1) inc nil))
25426 (setq tmp (buffer-substring (max (point-min)
25427 (- pos org-ds-keyword-length))
25428 pos)
25429 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
25430 (progn
25431 (setq inc nil)
25432 (replace-match "\\1" t nil ts))
25434 deadlinep (string-match org-deadline-regexp tmp)
25435 scheduledp (string-match org-scheduled-regexp tmp)
25436 ;; donep (org-entry-is-done-p)
25438 (if (or (string-match org-tr-regexp hd)
25439 (string-match org-ts-regexp hd))
25440 (setq hd (replace-match "" t t hd)))
25441 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
25442 (setq rrule
25443 (concat "\nRRULE:FREQ="
25444 (cdr (assoc
25445 (match-string 2 ts)
25446 '(("d" . "DAILY")("w" . "WEEKLY")
25447 ("m" . "MONTHLY")("y" . "YEARLY"))))
25448 ";INTERVAL=" (match-string 1 ts)))
25449 (setq rrule ""))
25450 (setq summary (or summary hd))
25451 (if (string-match org-bracket-link-regexp summary)
25452 (setq summary
25453 (replace-match (if (match-end 3)
25454 (match-string 3 summary)
25455 (match-string 1 summary))
25456 t t summary)))
25457 (if deadlinep (setq summary (concat "DL: " summary)))
25458 (if scheduledp (setq summary (concat "S: " summary)))
25459 (if (string-match "\\`<%%" ts)
25460 (with-current-buffer sexp-buffer
25461 (insert (substring ts 1 -1) " " summary "\n"))
25462 (princ (format "BEGIN:VEVENT
25464 %s%s
25465 SUMMARY:%s%s%s
25466 CATEGORIES:%s
25467 END:VEVENT\n"
25468 (org-ical-ts-to-string ts "DTSTART")
25469 (org-ical-ts-to-string ts2 "DTEND" inc)
25470 rrule summary
25471 (if (and desc (string-match "\\S-" desc))
25472 (concat "\nDESCRIPTION: " desc) "")
25473 (if (and location (string-match "\\S-" location))
25474 (concat "\nLOCATION: " location) "")
25475 category)))))
25477 (when (and org-icalendar-include-sexps
25478 (condition-case nil (require 'icalendar) (error nil))
25479 (fboundp 'icalendar-export-region))
25480 ;; Get all the literal sexps
25481 (goto-char (point-min))
25482 (while (re-search-forward "^&?%%(" nil t)
25483 (catch :skip
25484 (org-agenda-skip)
25485 (setq b (match-beginning 0))
25486 (goto-char (1- (match-end 0)))
25487 (forward-sexp 1)
25488 (end-of-line 1)
25489 (setq sexp (buffer-substring b (point)))
25490 (with-current-buffer sexp-buffer
25491 (insert sexp "\n"))
25492 (princ (org-diary-to-ical-string sexp-buffer)))))
25494 (when org-icalendar-include-todo
25495 (goto-char (point-min))
25496 (while (re-search-forward org-todo-line-regexp nil t)
25497 (catch :skip
25498 (org-agenda-skip)
25499 (setq state (match-string 2))
25500 (setq status (if (member state org-done-keywords)
25501 "COMPLETED" "NEEDS-ACTION"))
25502 (when (and state
25503 (or (not (member state org-done-keywords))
25504 (eq org-icalendar-include-todo 'all))
25505 (not (member org-archive-tag (org-get-tags-at)))
25507 (setq hd (match-string 3)
25508 summary (org-icalendar-cleanup-string
25509 (org-entry-get nil "SUMMARY"))
25510 desc (org-icalendar-cleanup-string
25511 (or (org-entry-get nil "DESCRIPTION")
25512 (and org-icalendar-include-body (org-get-entry)))
25513 t org-icalendar-include-body)
25514 location (org-icalendar-cleanup-string
25515 (org-entry-get nil "LOCATION")))
25516 (if (string-match org-bracket-link-regexp hd)
25517 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
25518 (match-string 1 hd))
25519 t t hd)))
25520 (if (string-match org-priority-regexp hd)
25521 (setq pri (string-to-char (match-string 2 hd))
25522 hd (concat (substring hd 0 (match-beginning 1))
25523 (substring hd (match-end 1))))
25524 (setq pri org-default-priority))
25525 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
25526 (- org-lowest-priority org-highest-priority))))))
25528 (princ (format "BEGIN:VTODO
25530 SUMMARY:%s%s%s
25531 CATEGORIES:%s
25532 SEQUENCE:1
25533 PRIORITY:%d
25534 STATUS:%s
25535 END:VTODO\n"
25537 (or summary hd)
25538 (if (and location (string-match "\\S-" location))
25539 (concat "\nLOCATION: " location) "")
25540 (if (and desc (string-match "\\S-" desc))
25541 (concat "\nDESCRIPTION: " desc) "")
25542 category pri status)))))))))
25544 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
25545 "Take out stuff and quote what needs to be quoted.
25546 When IS-BODY is non-nil, assume that this is the body of an item, clean up
25547 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
25548 characters."
25549 (if (not s)
25551 (when is-body
25552 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
25553 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
25554 (while (string-match re s) (setq s (replace-match "" t t s)))
25555 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
25556 (let ((start 0))
25557 (while (string-match "\\([,;\\]\\)" s start)
25558 (setq start (+ (match-beginning 0) 2)
25559 s (replace-match "\\\\\\1" nil nil s))))
25560 (when is-body
25561 (while (string-match "[ \t]*\n[ \t]*" s)
25562 (setq s (replace-match "\\n" t t s))))
25563 (setq s (org-trim s))
25564 (if is-body
25565 (if maxlength
25566 (if (and (numberp maxlength)
25567 (> (length s) maxlength))
25568 (setq s (substring s 0 maxlength)))))
25571 (defun org-get-entry ()
25572 "Clean-up description string."
25573 (save-excursion
25574 (org-back-to-heading t)
25575 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
25577 (defun org-start-icalendar-file (name)
25578 "Start an iCalendar file by inserting the header."
25579 (let ((user user-full-name)
25580 (name (or name "unknown"))
25581 (timezone (cadr (current-time-zone))))
25582 (princ
25583 (format "BEGIN:VCALENDAR
25584 VERSION:2.0
25585 X-WR-CALNAME:%s
25586 PRODID:-//%s//Emacs with Org-mode//EN
25587 X-WR-TIMEZONE:%s
25588 CALSCALE:GREGORIAN\n" name user timezone))))
25590 (defun org-finish-icalendar-file ()
25591 "Finish an iCalendar file by inserting the END statement."
25592 (princ "END:VCALENDAR\n"))
25594 (defun org-ical-ts-to-string (s keyword &optional inc)
25595 "Take a time string S and convert it to iCalendar format.
25596 KEYWORD is added in front, to make a complete line like DTSTART....
25597 When INC is non-nil, increase the hour by two (if time string contains
25598 a time), or the day by one (if it does not contain a time)."
25599 (let ((t1 (org-parse-time-string s 'nodefault))
25600 t2 fmt have-time time)
25601 (if (and (car t1) (nth 1 t1) (nth 2 t1))
25602 (setq t2 t1 have-time t)
25603 (setq t2 (org-parse-time-string s)))
25604 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
25605 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
25606 (when inc
25607 (if have-time
25608 (if org-agenda-default-appointment-duration
25609 (setq mi (+ org-agenda-default-appointment-duration mi))
25610 (setq h (+ 2 h)))
25611 (setq d (1+ d))))
25612 (setq time (encode-time s mi h d m y)))
25613 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
25614 (concat keyword (format-time-string fmt time))))
25616 ;;; XOXO export
25618 (defun org-export-as-xoxo-insert-into (buffer &rest output)
25619 (with-current-buffer buffer
25620 (apply 'insert output)))
25621 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
25623 (defun org-export-as-xoxo (&optional buffer)
25624 "Export the org buffer as XOXO.
25625 The XOXO buffer is named *xoxo-<source buffer name>*"
25626 (interactive (list (current-buffer)))
25627 ;; A quickie abstraction
25629 ;; Output everything as XOXO
25630 (with-current-buffer (get-buffer buffer)
25631 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
25632 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
25633 (org-infile-export-plist)))
25634 (filename (concat (file-name-as-directory
25635 (org-export-directory :xoxo opt-plist))
25636 (file-name-sans-extension
25637 (file-name-nondirectory buffer-file-name))
25638 ".html"))
25639 (out (find-file-noselect filename))
25640 (last-level 1)
25641 (hanging-li nil))
25642 ;; Check the output buffer is empty.
25643 (with-current-buffer out (erase-buffer))
25644 ;; Kick off the output
25645 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
25646 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
25647 (let* ((hd (match-string-no-properties 1))
25648 (level (length hd))
25649 (text (concat
25650 (match-string-no-properties 2)
25651 (save-excursion
25652 (goto-char (match-end 0))
25653 (let ((str ""))
25654 (catch 'loop
25655 (while 't
25656 (forward-line)
25657 (if (looking-at "^[ \t]\\(.*\\)")
25658 (setq str (concat str (match-string-no-properties 1)))
25659 (throw 'loop str)))))))))
25661 ;; Handle level rendering
25662 (cond
25663 ((> level last-level)
25664 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
25666 ((< level last-level)
25667 (dotimes (- (- last-level level) 1)
25668 (if hanging-li
25669 (org-export-as-xoxo-insert-into out "</li>\n"))
25670 (org-export-as-xoxo-insert-into out "</ol>\n"))
25671 (when hanging-li
25672 (org-export-as-xoxo-insert-into out "</li>\n")
25673 (setq hanging-li nil)))
25675 ((equal level last-level)
25676 (if hanging-li
25677 (org-export-as-xoxo-insert-into out "</li>\n")))
25680 (setq last-level level)
25682 ;; And output the new li
25683 (setq hanging-li 't)
25684 (if (equal ?+ (elt text 0))
25685 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
25686 (org-export-as-xoxo-insert-into out "<li>" text))))
25688 ;; Finally finish off the ol
25689 (dotimes (- last-level 1)
25690 (if hanging-li
25691 (org-export-as-xoxo-insert-into out "</li>\n"))
25692 (org-export-as-xoxo-insert-into out "</ol>\n"))
25694 ;; Finish the buffer off and clean it up.
25695 (switch-to-buffer-other-window out)
25696 (indent-region (point-min) (point-max) nil)
25697 (save-buffer)
25698 (goto-char (point-min))
25702 ;;;; Key bindings
25704 ;; Make `C-c C-x' a prefix key
25705 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
25707 ;; TAB key with modifiers
25708 (org-defkey org-mode-map "\C-i" 'org-cycle)
25709 (org-defkey org-mode-map [(tab)] 'org-cycle)
25710 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
25711 (org-defkey org-mode-map [(meta tab)] 'org-complete)
25712 (org-defkey org-mode-map "\M-\t" 'org-complete)
25713 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
25714 ;; The following line is necessary under Suse GNU/Linux
25715 (unless (featurep 'xemacs)
25716 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
25717 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
25718 (define-key org-mode-map [backtab] 'org-shifttab)
25720 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
25721 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
25722 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
25724 ;; Cursor keys with modifiers
25725 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
25726 (org-defkey org-mode-map [(meta right)] 'org-metaright)
25727 (org-defkey org-mode-map [(meta up)] 'org-metaup)
25728 (org-defkey org-mode-map [(meta down)] 'org-metadown)
25730 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
25731 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
25732 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
25733 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
25735 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
25736 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
25737 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
25738 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
25740 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
25741 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
25743 ;;; Extra keys for tty access.
25744 ;; We only set them when really needed because otherwise the
25745 ;; menus don't show the simple keys
25747 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
25748 (not window-system))
25749 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
25750 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
25751 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
25752 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
25753 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
25754 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
25755 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
25756 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
25757 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
25758 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
25759 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
25760 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
25761 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
25762 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
25763 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
25764 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
25765 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
25766 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
25767 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
25768 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
25769 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
25770 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
25772 ;; All the other keys
25774 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
25775 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
25776 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
25777 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
25778 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
25779 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
25780 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
25781 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
25782 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
25783 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
25784 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
25785 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
25786 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
25787 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
25788 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
25789 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
25790 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
25791 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
25792 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
25793 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
25794 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
25795 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
25796 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
25797 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
25798 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
25799 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
25800 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
25801 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
25802 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
25803 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
25804 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
25805 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
25806 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
25807 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
25808 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
25809 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
25810 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
25811 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
25812 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
25813 (org-defkey org-mode-map "\C-c^" 'org-sort)
25814 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
25815 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
25816 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
25817 (org-defkey org-mode-map "\C-m" 'org-return)
25818 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
25819 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
25820 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
25821 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
25822 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
25823 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
25824 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
25825 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
25826 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
25827 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
25828 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
25829 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
25830 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
25831 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
25832 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
25833 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
25835 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
25836 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
25837 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
25838 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
25840 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
25841 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
25842 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
25843 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
25844 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
25845 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
25846 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
25847 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
25848 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
25849 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
25850 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
25851 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
25853 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
25855 (when (featurep 'xemacs)
25856 (org-defkey org-mode-map 'button3 'popup-mode-menu))
25858 (defsubst org-table-p () (org-at-table-p))
25860 (defun org-self-insert-command (N)
25861 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
25862 If the cursor is in a table looking at whitespace, the whitespace is
25863 overwritten, and the table is not marked as requiring realignment."
25864 (interactive "p")
25865 (if (and (org-table-p)
25866 (progn
25867 ;; check if we blank the field, and if that triggers align
25868 (and org-table-auto-blank-field
25869 (member last-command
25870 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
25871 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
25872 ;; got extra space, this field does not determine column width
25873 (let (org-table-may-need-update) (org-table-blank-field))
25874 ;; no extra space, this field may determine column width
25875 (org-table-blank-field)))
25877 (eq N 1)
25878 (looking-at "[^|\n]* |"))
25879 (let (org-table-may-need-update)
25880 (goto-char (1- (match-end 0)))
25881 (delete-backward-char 1)
25882 (goto-char (match-beginning 0))
25883 (self-insert-command N))
25884 (setq org-table-may-need-update t)
25885 (self-insert-command N)
25886 (org-fix-tags-on-the-fly)))
25888 (defun org-fix-tags-on-the-fly ()
25889 (when (and (equal (char-after (point-at-bol)) ?*)
25890 (org-on-heading-p))
25891 (org-align-tags-here org-tags-column)))
25893 (defun org-delete-backward-char (N)
25894 "Like `delete-backward-char', insert whitespace at field end in tables.
25895 When deleting backwards, in tables this function will insert whitespace in
25896 front of the next \"|\" separator, to keep the table aligned. The table will
25897 still be marked for re-alignment if the field did fill the entire column,
25898 because, in this case the deletion might narrow the column."
25899 (interactive "p")
25900 (if (and (org-table-p)
25901 (eq N 1)
25902 (string-match "|" (buffer-substring (point-at-bol) (point)))
25903 (looking-at ".*?|"))
25904 (let ((pos (point))
25905 (noalign (looking-at "[^|\n\r]* |"))
25906 (c org-table-may-need-update))
25907 (backward-delete-char N)
25908 (skip-chars-forward "^|")
25909 (insert " ")
25910 (goto-char (1- pos))
25911 ;; noalign: if there were two spaces at the end, this field
25912 ;; does not determine the width of the column.
25913 (if noalign (setq org-table-may-need-update c)))
25914 (backward-delete-char N)
25915 (org-fix-tags-on-the-fly)))
25917 (defun org-delete-char (N)
25918 "Like `delete-char', but insert whitespace at field end in tables.
25919 When deleting characters, in tables this function will insert whitespace in
25920 front of the next \"|\" separator, to keep the table aligned. The table will
25921 still be marked for re-alignment if the field did fill the entire column,
25922 because, in this case the deletion might narrow the column."
25923 (interactive "p")
25924 (if (and (org-table-p)
25925 (not (bolp))
25926 (not (= (char-after) ?|))
25927 (eq N 1))
25928 (if (looking-at ".*?|")
25929 (let ((pos (point))
25930 (noalign (looking-at "[^|\n\r]* |"))
25931 (c org-table-may-need-update))
25932 (replace-match (concat
25933 (substring (match-string 0) 1 -1)
25934 " |"))
25935 (goto-char pos)
25936 ;; noalign: if there were two spaces at the end, this field
25937 ;; does not determine the width of the column.
25938 (if noalign (setq org-table-may-need-update c)))
25939 (delete-char N))
25940 (delete-char N)
25941 (org-fix-tags-on-the-fly)))
25943 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
25944 (put 'org-self-insert-command 'delete-selection t)
25945 (put 'orgtbl-self-insert-command 'delete-selection t)
25946 (put 'org-delete-char 'delete-selection 'supersede)
25947 (put 'org-delete-backward-char 'delete-selection 'supersede)
25949 ;; Make `flyspell-mode' delay after some commands
25950 (put 'org-self-insert-command 'flyspell-delayed t)
25951 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
25952 (put 'org-delete-char 'flyspell-delayed t)
25953 (put 'org-delete-backward-char 'flyspell-delayed t)
25955 ;; Make pabbrev-mode expand after org-mode commands
25956 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
25957 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
25959 ;; How to do this: Measure non-white length of current string
25960 ;; If equal to column width, we should realign.
25962 (defun org-remap (map &rest commands)
25963 "In MAP, remap the functions given in COMMANDS.
25964 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
25965 (let (new old)
25966 (while commands
25967 (setq old (pop commands) new (pop commands))
25968 (if (fboundp 'command-remapping)
25969 (org-defkey map (vector 'remap old) new)
25970 (substitute-key-definition old new map global-map)))))
25972 (when (eq org-enable-table-editor 'optimized)
25973 ;; If the user wants maximum table support, we need to hijack
25974 ;; some standard editing functions
25975 (org-remap org-mode-map
25976 'self-insert-command 'org-self-insert-command
25977 'delete-char 'org-delete-char
25978 'delete-backward-char 'org-delete-backward-char)
25979 (org-defkey org-mode-map "|" 'org-force-self-insert))
25981 (defun org-shiftcursor-error ()
25982 "Throw an error because Shift-Cursor command was applied in wrong context."
25983 (error "This command is active in special context like tables, headlines or timestamps"))
25985 (defun org-shifttab (&optional arg)
25986 "Global visibility cycling or move to previous table field.
25987 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
25988 on context.
25989 See the individual commands for more information."
25990 (interactive "P")
25991 (cond
25992 ((org-at-table-p) (call-interactively 'org-table-previous-field))
25993 (arg (message "Content view to level: ")
25994 (org-content (prefix-numeric-value arg))
25995 (setq org-cycle-global-status 'overview))
25996 (t (call-interactively 'org-global-cycle))))
25998 (defun org-shiftmetaleft ()
25999 "Promote subtree or delete table column.
26000 Calls `org-promote-subtree', `org-outdent-item',
26001 or `org-table-delete-column', depending on context.
26002 See the individual commands for more information."
26003 (interactive)
26004 (cond
26005 ((org-at-table-p) (call-interactively 'org-table-delete-column))
26006 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
26007 ((org-at-item-p) (call-interactively 'org-outdent-item))
26008 (t (org-shiftcursor-error))))
26010 (defun org-shiftmetaright ()
26011 "Demote subtree or insert table column.
26012 Calls `org-demote-subtree', `org-indent-item',
26013 or `org-table-insert-column', depending on context.
26014 See the individual commands for more information."
26015 (interactive)
26016 (cond
26017 ((org-at-table-p) (call-interactively 'org-table-insert-column))
26018 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
26019 ((org-at-item-p) (call-interactively 'org-indent-item))
26020 (t (org-shiftcursor-error))))
26022 (defun org-shiftmetaup (&optional arg)
26023 "Move subtree up or kill table row.
26024 Calls `org-move-subtree-up' or `org-table-kill-row' or
26025 `org-move-item-up' depending on context. See the individual commands
26026 for more information."
26027 (interactive "P")
26028 (cond
26029 ((org-at-table-p) (call-interactively 'org-table-kill-row))
26030 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26031 ((org-at-item-p) (call-interactively 'org-move-item-up))
26032 (t (org-shiftcursor-error))))
26033 (defun org-shiftmetadown (&optional arg)
26034 "Move subtree down or insert table row.
26035 Calls `org-move-subtree-down' or `org-table-insert-row' or
26036 `org-move-item-down', depending on context. See the individual
26037 commands for more information."
26038 (interactive "P")
26039 (cond
26040 ((org-at-table-p) (call-interactively 'org-table-insert-row))
26041 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26042 ((org-at-item-p) (call-interactively 'org-move-item-down))
26043 (t (org-shiftcursor-error))))
26045 (defun org-metaleft (&optional arg)
26046 "Promote heading or move table column to left.
26047 Calls `org-do-promote' or `org-table-move-column', depending on context.
26048 With no specific context, calls the Emacs default `backward-word'.
26049 See the individual commands for more information."
26050 (interactive "P")
26051 (cond
26052 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
26053 ((or (org-on-heading-p) (org-region-active-p))
26054 (call-interactively 'org-do-promote))
26055 ((org-at-item-p) (call-interactively 'org-outdent-item))
26056 (t (call-interactively 'backward-word))))
26058 (defun org-metaright (&optional arg)
26059 "Demote subtree or move table column to right.
26060 Calls `org-do-demote' or `org-table-move-column', depending on context.
26061 With no specific context, calls the Emacs default `forward-word'.
26062 See the individual commands for more information."
26063 (interactive "P")
26064 (cond
26065 ((org-at-table-p) (call-interactively 'org-table-move-column))
26066 ((or (org-on-heading-p) (org-region-active-p))
26067 (call-interactively 'org-do-demote))
26068 ((org-at-item-p) (call-interactively 'org-indent-item))
26069 (t (call-interactively 'forward-word))))
26071 (defun org-metaup (&optional arg)
26072 "Move subtree up or move table row up.
26073 Calls `org-move-subtree-up' or `org-table-move-row' or
26074 `org-move-item-up', depending on context. See the individual commands
26075 for more information."
26076 (interactive "P")
26077 (cond
26078 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
26079 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26080 ((org-at-item-p) (call-interactively 'org-move-item-up))
26081 (t (transpose-lines 1) (beginning-of-line -1))))
26083 (defun org-metadown (&optional arg)
26084 "Move subtree down or move table row down.
26085 Calls `org-move-subtree-down' or `org-table-move-row' or
26086 `org-move-item-down', depending on context. See the individual
26087 commands for more information."
26088 (interactive "P")
26089 (cond
26090 ((org-at-table-p) (call-interactively 'org-table-move-row))
26091 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26092 ((org-at-item-p) (call-interactively 'org-move-item-down))
26093 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
26095 (defun org-shiftup (&optional arg)
26096 "Increase item in timestamp or increase priority of current headline.
26097 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
26098 depending on context. See the individual commands for more information."
26099 (interactive "P")
26100 (cond
26101 ((org-at-timestamp-p t)
26102 (call-interactively (if org-edit-timestamp-down-means-later
26103 'org-timestamp-down 'org-timestamp-up)))
26104 ((org-on-heading-p) (call-interactively 'org-priority-up))
26105 ((org-at-item-p) (call-interactively 'org-previous-item))
26106 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
26108 (defun org-shiftdown (&optional arg)
26109 "Decrease item in timestamp or decrease priority of current headline.
26110 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
26111 depending on context. See the individual commands for more information."
26112 (interactive "P")
26113 (cond
26114 ((org-at-timestamp-p t)
26115 (call-interactively (if org-edit-timestamp-down-means-later
26116 'org-timestamp-up 'org-timestamp-down)))
26117 ((org-on-heading-p) (call-interactively 'org-priority-down))
26118 (t (call-interactively 'org-next-item))))
26120 (defun org-shiftright ()
26121 "Next TODO keyword or timestamp one day later, depending on context."
26122 (interactive)
26123 (cond
26124 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
26125 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
26126 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
26127 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
26128 (t (org-shiftcursor-error))))
26130 (defun org-shiftleft ()
26131 "Previous TODO keyword or timestamp one day earlier, depending on context."
26132 (interactive)
26133 (cond
26134 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
26135 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
26136 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
26137 ((org-at-property-p)
26138 (call-interactively 'org-property-previous-allowed-value))
26139 (t (org-shiftcursor-error))))
26141 (defun org-shiftcontrolright ()
26142 "Switch to next TODO set."
26143 (interactive)
26144 (cond
26145 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
26146 (t (org-shiftcursor-error))))
26148 (defun org-shiftcontrolleft ()
26149 "Switch to previous TODO set."
26150 (interactive)
26151 (cond
26152 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
26153 (t (org-shiftcursor-error))))
26155 (defun org-ctrl-c-ret ()
26156 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
26157 (interactive)
26158 (cond
26159 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
26160 (t (call-interactively 'org-insert-heading))))
26162 (defun org-copy-special ()
26163 "Copy region in table or copy current subtree.
26164 Calls `org-table-copy' or `org-copy-subtree', depending on context.
26165 See the individual commands for more information."
26166 (interactive)
26167 (call-interactively
26168 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
26170 (defun org-cut-special ()
26171 "Cut region in table or cut current subtree.
26172 Calls `org-table-copy' or `org-cut-subtree', depending on context.
26173 See the individual commands for more information."
26174 (interactive)
26175 (call-interactively
26176 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
26178 (defun org-paste-special (arg)
26179 "Paste rectangular region into table, or past subtree relative to level.
26180 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
26181 See the individual commands for more information."
26182 (interactive "P")
26183 (if (org-at-table-p)
26184 (org-table-paste-rectangle)
26185 (org-paste-subtree arg)))
26187 (defun org-ctrl-c-ctrl-c (&optional arg)
26188 "Set tags in headline, or update according to changed information at point.
26190 This command does many different things, depending on context:
26192 - If the cursor is in a headline, prompt for tags and insert them
26193 into the current line, aligned to `org-tags-column'. When called
26194 with prefix arg, realign all tags in the current buffer.
26196 - If the cursor is in one of the special #+KEYWORD lines, this
26197 triggers scanning the buffer for these lines and updating the
26198 information.
26200 - If the cursor is inside a table, realign the table. This command
26201 works even if the automatic table editor has been turned off.
26203 - If the cursor is on a #+TBLFM line, re-apply the formulas to
26204 the entire table.
26206 - If the cursor is a the beginning of a dynamic block, update it.
26208 - If the cursor is inside a table created by the table.el package,
26209 activate that table.
26211 - If the current buffer is a remember buffer, close note and file it.
26212 with a prefix argument, file it without further interaction to the default
26213 location.
26215 - If the cursor is on a <<<target>>>, update radio targets and corresponding
26216 links in this buffer.
26218 - If the cursor is on a numbered item in a plain list, renumber the
26219 ordered list.
26221 - If the cursor is on a checkbox, toggle it."
26222 (interactive "P")
26223 (let ((org-enable-table-editor t))
26224 (cond
26225 ((or org-clock-overlays
26226 org-occur-highlights
26227 org-latex-fragment-image-overlays)
26228 (org-remove-clock-overlays)
26229 (org-remove-occur-highlights)
26230 (org-remove-latex-fragment-image-overlays)
26231 (message "Temporary highlights/overlays removed from current buffer"))
26232 ((and (local-variable-p 'org-finish-function (current-buffer))
26233 (fboundp org-finish-function))
26234 (funcall org-finish-function))
26235 ((org-at-property-p)
26236 (call-interactively 'org-property-action))
26237 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
26238 ((org-on-heading-p) (call-interactively 'org-set-tags))
26239 ((org-at-table.el-p)
26240 (require 'table)
26241 (beginning-of-line 1)
26242 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
26243 (call-interactively 'table-recognize-table))
26244 ((org-at-table-p)
26245 (org-table-maybe-eval-formula)
26246 (if arg
26247 (call-interactively 'org-table-recalculate)
26248 (org-table-maybe-recalculate-line))
26249 (call-interactively 'org-table-align))
26250 ((org-at-item-checkbox-p)
26251 (call-interactively 'org-toggle-checkbox))
26252 ((org-at-item-p)
26253 (call-interactively 'org-maybe-renumber-ordered-list))
26254 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
26255 ;; Dynamic block
26256 (beginning-of-line 1)
26257 (org-update-dblock))
26258 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
26259 (cond
26260 ((equal (match-string 1) "TBLFM")
26261 ;; Recalculate the table before this line
26262 (save-excursion
26263 (beginning-of-line 1)
26264 (skip-chars-backward " \r\n\t")
26265 (if (org-at-table-p)
26266 (org-call-with-arg 'org-table-recalculate t))))
26268 (call-interactively 'org-mode-restart))))
26269 (t (error "C-c C-c can do nothing useful at this location.")))))
26271 (defun org-mode-restart ()
26272 "Restart Org-mode, to scan again for special lines.
26273 Also updates the keyword regular expressions."
26274 (interactive)
26275 (let ((org-inhibit-startup t)) (org-mode))
26276 (message "Org-mode restarted to refresh keyword and special line setup"))
26278 (defun org-kill-note-or-show-branches ()
26279 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
26280 (interactive)
26281 (if (not org-finish-function)
26282 (call-interactively 'show-branches)
26283 (let ((org-note-abort t))
26284 (funcall org-finish-function))))
26286 (defun org-return ()
26287 "Goto next table row or insert a newline.
26288 Calls `org-table-next-row' or `newline', depending on context.
26289 See the individual commands for more information."
26290 (interactive)
26291 (cond
26292 ((bobp) (newline))
26293 ((org-at-table-p)
26294 (org-table-justify-field-maybe)
26295 (call-interactively 'org-table-next-row))
26296 (t (newline))))
26299 (defun org-ctrl-c-minus ()
26300 "Insert separator line in table or modify bullet type in list.
26301 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
26302 depending on context."
26303 (interactive)
26304 (cond
26305 ((org-at-table-p)
26306 (call-interactively 'org-table-insert-hline))
26307 ((org-on-heading-p)
26308 ;; Convert to item
26309 (save-excursion
26310 (beginning-of-line 1)
26311 (if (looking-at "\\*+ ")
26312 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
26313 ((org-in-item-p)
26314 (call-interactively 'org-cycle-list-bullet))
26315 (t (error "`C-c -' does have no function here."))))
26317 (defun org-meta-return (&optional arg)
26318 "Insert a new heading or wrap a region in a table.
26319 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
26320 See the individual commands for more information."
26321 (interactive "P")
26322 (cond
26323 ((org-at-table-p)
26324 (call-interactively 'org-table-wrap-region))
26325 (t (call-interactively 'org-insert-heading))))
26327 ;;; Menu entries
26329 ;; Define the Org-mode menus
26330 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
26331 '("Tbl"
26332 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
26333 ["Next Field" org-cycle (org-at-table-p)]
26334 ["Previous Field" org-shifttab (org-at-table-p)]
26335 ["Next Row" org-return (org-at-table-p)]
26336 "--"
26337 ["Blank Field" org-table-blank-field (org-at-table-p)]
26338 ["Edit Field" org-table-edit-field (org-at-table-p)]
26339 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
26340 "--"
26341 ("Column"
26342 ["Move Column Left" org-metaleft (org-at-table-p)]
26343 ["Move Column Right" org-metaright (org-at-table-p)]
26344 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
26345 ["Insert Column" org-shiftmetaright (org-at-table-p)])
26346 ("Row"
26347 ["Move Row Up" org-metaup (org-at-table-p)]
26348 ["Move Row Down" org-metadown (org-at-table-p)]
26349 ["Delete Row" org-shiftmetaup (org-at-table-p)]
26350 ["Insert Row" org-shiftmetadown (org-at-table-p)]
26351 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
26352 "--"
26353 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
26354 ("Rectangle"
26355 ["Copy Rectangle" org-copy-special (org-at-table-p)]
26356 ["Cut Rectangle" org-cut-special (org-at-table-p)]
26357 ["Paste Rectangle" org-paste-special (org-at-table-p)]
26358 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
26359 "--"
26360 ("Calculate"
26361 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
26362 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
26363 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
26364 "--"
26365 ["Recalculate line" org-table-recalculate (org-at-table-p)]
26366 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
26367 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
26368 "--"
26369 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
26370 "--"
26371 ["Sum Column/Rectangle" org-table-sum
26372 (or (org-at-table-p) (org-region-active-p))]
26373 ["Which Column?" org-table-current-column (org-at-table-p)])
26374 ["Debug Formulas"
26375 org-table-toggle-formula-debugger
26376 :style toggle :selected org-table-formula-debug]
26377 ["Show Col/Row Numbers"
26378 org-table-toggle-coordinate-overlays
26379 :style toggle :selected org-table-overlay-coordinates]
26380 "--"
26381 ["Create" org-table-create (and (not (org-at-table-p))
26382 org-enable-table-editor)]
26383 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
26384 ["Import from File" org-table-import (not (org-at-table-p))]
26385 ["Export to File" org-table-export (org-at-table-p)]
26386 "--"
26387 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
26389 (easy-menu-define org-org-menu org-mode-map "Org menu"
26390 '("Org"
26391 ("Show/Hide"
26392 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
26393 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
26394 ["Sparse Tree" org-occur t]
26395 ["Reveal Context" org-reveal t]
26396 ["Show All" show-all t]
26397 "--"
26398 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
26399 "--"
26400 ["New Heading" org-insert-heading t]
26401 ("Navigate Headings"
26402 ["Up" outline-up-heading t]
26403 ["Next" outline-next-visible-heading t]
26404 ["Previous" outline-previous-visible-heading t]
26405 ["Next Same Level" outline-forward-same-level t]
26406 ["Previous Same Level" outline-backward-same-level t]
26407 "--"
26408 ["Jump" org-goto t])
26409 ("Edit Structure"
26410 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
26411 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
26412 "--"
26413 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
26414 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
26415 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
26416 "--"
26417 ["Promote Heading" org-metaleft (not (org-at-table-p))]
26418 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
26419 ["Demote Heading" org-metaright (not (org-at-table-p))]
26420 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
26421 "--"
26422 ["Sort Region/Children" org-sort (not (org-at-table-p))]
26423 "--"
26424 ["Convert to odd levels" org-convert-to-odd-levels t]
26425 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
26426 ("Editing"
26427 ["Emphasis..." org-emphasize t])
26428 ("Archive"
26429 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
26430 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
26431 ; :active t :keys "C-u C-c C-x C-a"]
26432 ["Sparse trees open ARCHIVE trees"
26433 (setq org-sparse-tree-open-archived-trees
26434 (not org-sparse-tree-open-archived-trees))
26435 :style toggle :selected org-sparse-tree-open-archived-trees]
26436 ["Cycling opens ARCHIVE trees"
26437 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
26438 :style toggle :selected org-cycle-open-archived-trees]
26439 ["Agenda includes ARCHIVE trees"
26440 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
26441 :style toggle :selected (not org-agenda-skip-archived-trees)]
26442 "--"
26443 ["Move Subtree to Archive" org-advertized-archive-subtree t]
26444 ; ["Check and Move Children" (org-archive-subtree '(4))
26445 ; :active t :keys "C-u C-c C-x C-s"]
26447 "--"
26448 ("TODO Lists"
26449 ["TODO/DONE/-" org-todo t]
26450 ("Select keyword"
26451 ["Next keyword" org-shiftright (org-on-heading-p)]
26452 ["Previous keyword" org-shiftleft (org-on-heading-p)]
26453 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
26454 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
26455 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
26456 ["Show TODO Tree" org-show-todo-tree t]
26457 ["Global TODO list" org-todo-list t]
26458 "--"
26459 ["Set Priority" org-priority t]
26460 ["Priority Up" org-shiftup t]
26461 ["Priority Down" org-shiftdown t])
26462 ("TAGS and Properties"
26463 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
26464 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
26465 "--"
26466 ["Set property" 'org-set-property t]
26467 ["Column view of properties" org-columns t]
26468 ["Insert Column View DBlock" org-insert-columns-dblock t])
26469 ("Dates and Scheduling"
26470 ["Timestamp" org-time-stamp t]
26471 ["Timestamp (inactive)" org-time-stamp-inactive t]
26472 ("Change Date"
26473 ["1 Day Later" org-shiftright t]
26474 ["1 Day Earlier" org-shiftleft t]
26475 ["1 ... Later" org-shiftup t]
26476 ["1 ... Earlier" org-shiftdown t])
26477 ["Compute Time Range" org-evaluate-time-range t]
26478 ["Schedule Item" org-schedule t]
26479 ["Deadline" org-deadline t]
26480 "--"
26481 ["Custom time format" org-toggle-time-stamp-overlays
26482 :style radio :selected org-display-custom-times]
26483 "--"
26484 ["Goto Calendar" org-goto-calendar t]
26485 ["Date from Calendar" org-date-from-calendar t])
26486 ("Logging work"
26487 ["Clock in" org-clock-in t]
26488 ["Clock out" org-clock-out t]
26489 ["Clock cancel" org-clock-cancel t]
26490 ["Goto running clock" org-clock-goto t]
26491 ["Display times" org-clock-display t]
26492 ["Create clock table" org-clock-report t]
26493 "--"
26494 ["Record DONE time"
26495 (progn (setq org-log-done (not org-log-done))
26496 (message "Switching to %s will %s record a timestamp"
26497 (car org-done-keywords)
26498 (if org-log-done "automatically" "not")))
26499 :style toggle :selected org-log-done])
26500 "--"
26501 ["Agenda Command..." org-agenda t]
26502 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
26503 ("File List for Agenda")
26504 ("Special views current file"
26505 ["TODO Tree" org-show-todo-tree t]
26506 ["Check Deadlines" org-check-deadlines t]
26507 ["Timeline" org-timeline t]
26508 ["Tags Tree" org-tags-sparse-tree t])
26509 "--"
26510 ("Hyperlinks"
26511 ["Store Link (Global)" org-store-link t]
26512 ["Insert Link" org-insert-link t]
26513 ["Follow Link" org-open-at-point t]
26514 "--"
26515 ["Next link" org-next-link t]
26516 ["Previous link" org-previous-link t]
26517 "--"
26518 ["Descriptive Links"
26519 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
26520 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
26521 ["Literal Links"
26522 (progn
26523 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
26524 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
26525 "--"
26526 ["Export/Publish..." org-export t]
26527 ("LaTeX"
26528 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
26529 :selected org-cdlatex-mode]
26530 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
26531 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
26532 ["Modify math symbol" org-cdlatex-math-modify
26533 (org-inside-LaTeX-fragment-p)]
26534 ["Export LaTeX fragments as images"
26535 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
26536 :style toggle :selected org-export-with-LaTeX-fragments])
26537 "--"
26538 ("Documentation"
26539 ["Show Version" org-version t]
26540 ["Info Documentation" org-info t])
26541 ("Customize"
26542 ["Browse Org Group" org-customize t]
26543 "--"
26544 ["Expand This Menu" org-create-customize-menu
26545 (fboundp 'customize-menu-create)])
26546 "--"
26547 ["Refresh setup" org-mode-restart t]
26550 (defun org-info (&optional node)
26551 "Read documentation for Org-mode in the info system.
26552 With optional NODE, go directly to that node."
26553 (interactive)
26554 (require 'info)
26555 (Info-goto-node (format "(org)%s" (or node ""))))
26557 (defun org-install-agenda-files-menu ()
26558 (let ((bl (buffer-list)))
26559 (save-excursion
26560 (while bl
26561 (set-buffer (pop bl))
26562 (if (org-mode-p) (setq bl nil)))
26563 (when (org-mode-p)
26564 (easy-menu-change
26565 '("Org") "File List for Agenda"
26566 (append
26567 (list
26568 ["Edit File List" (org-edit-agenda-file-list) t]
26569 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
26570 ["Remove Current File from List" org-remove-file t]
26571 ["Cycle through agenda files" org-cycle-agenda-files t]
26572 ["Occur in all agenda files" org-occur-in-agenda-files t]
26573 "--")
26574 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
26576 ;;;; Documentation
26578 (defun org-customize ()
26579 "Call the customize function with org as argument."
26580 (interactive)
26581 (customize-browse 'org))
26583 (defun org-create-customize-menu ()
26584 "Create a full customization menu for Org-mode, insert it into the menu."
26585 (interactive)
26586 (if (fboundp 'customize-menu-create)
26587 (progn
26588 (easy-menu-change
26589 '("Org") "Customize"
26590 `(["Browse Org group" org-customize t]
26591 "--"
26592 ,(customize-menu-create 'org)
26593 ["Set" Custom-set t]
26594 ["Save" Custom-save t]
26595 ["Reset to Current" Custom-reset-current t]
26596 ["Reset to Saved" Custom-reset-saved t]
26597 ["Reset to Standard Settings" Custom-reset-standard t]))
26598 (message "\"Org\"-menu now contains full customization menu"))
26599 (error "Cannot expand menu (outdated version of cus-edit.el)")))
26601 ;;;; Miscellaneous stuff
26604 ;;; Generally useful functions
26606 (defun org-context ()
26607 "Return a list of contexts of the current cursor position.
26608 If several contexts apply, all are returned.
26609 Each context entry is a list with a symbol naming the context, and
26610 two positions indicating start and end of the context. Possible
26611 contexts are:
26613 :headline anywhere in a headline
26614 :headline-stars on the leading stars in a headline
26615 :todo-keyword on a TODO keyword (including DONE) in a headline
26616 :tags on the TAGS in a headline
26617 :priority on the priority cookie in a headline
26618 :item on the first line of a plain list item
26619 :item-bullet on the bullet/number of a plain list item
26620 :checkbox on the checkbox in a plain list item
26621 :table in an org-mode table
26622 :table-special on a special filed in a table
26623 :table-table in a table.el table
26624 :link on a hyperlink
26625 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
26626 :target on a <<target>>
26627 :radio-target on a <<<radio-target>>>
26628 :latex-fragment on a LaTeX fragment
26629 :latex-preview on a LaTeX fragment with overlayed preview image
26631 This function expects the position to be visible because it uses font-lock
26632 faces as a help to recognize the following contexts: :table-special, :link,
26633 and :keyword."
26634 (let* ((f (get-text-property (point) 'face))
26635 (faces (if (listp f) f (list f)))
26636 (p (point)) clist o)
26637 ;; First the large context
26638 (cond
26639 ((org-on-heading-p t)
26640 (push (list :headline (point-at-bol) (point-at-eol)) clist)
26641 (when (progn
26642 (beginning-of-line 1)
26643 (looking-at org-todo-line-tags-regexp))
26644 (push (org-point-in-group p 1 :headline-stars) clist)
26645 (push (org-point-in-group p 2 :todo-keyword) clist)
26646 (push (org-point-in-group p 4 :tags) clist))
26647 (goto-char p)
26648 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
26649 (if (looking-at "\\[#[A-Z0-9]\\]")
26650 (push (org-point-in-group p 0 :priority) clist)))
26652 ((org-at-item-p)
26653 (push (org-point-in-group p 2 :item-bullet) clist)
26654 (push (list :item (point-at-bol)
26655 (save-excursion (org-end-of-item) (point)))
26656 clist)
26657 (and (org-at-item-checkbox-p)
26658 (push (org-point-in-group p 0 :checkbox) clist)))
26660 ((org-at-table-p)
26661 (push (list :table (org-table-begin) (org-table-end)) clist)
26662 (if (memq 'org-formula faces)
26663 (push (list :table-special
26664 (previous-single-property-change p 'face)
26665 (next-single-property-change p 'face)) clist)))
26666 ((org-at-table-p 'any)
26667 (push (list :table-table) clist)))
26668 (goto-char p)
26670 ;; Now the small context
26671 (cond
26672 ((org-at-timestamp-p)
26673 (push (org-point-in-group p 0 :timestamp) clist))
26674 ((memq 'org-link faces)
26675 (push (list :link
26676 (previous-single-property-change p 'face)
26677 (next-single-property-change p 'face)) clist))
26678 ((memq 'org-special-keyword faces)
26679 (push (list :keyword
26680 (previous-single-property-change p 'face)
26681 (next-single-property-change p 'face)) clist))
26682 ((org-on-target-p)
26683 (push (org-point-in-group p 0 :target) clist)
26684 (goto-char (1- (match-beginning 0)))
26685 (if (looking-at org-radio-target-regexp)
26686 (push (org-point-in-group p 0 :radio-target) clist))
26687 (goto-char p))
26688 ((setq o (car (delq nil
26689 (mapcar
26690 (lambda (x)
26691 (if (memq x org-latex-fragment-image-overlays) x))
26692 (org-overlays-at (point))))))
26693 (push (list :latex-fragment
26694 (org-overlay-start o) (org-overlay-end o)) clist)
26695 (push (list :latex-preview
26696 (org-overlay-start o) (org-overlay-end o)) clist))
26697 ((org-inside-LaTeX-fragment-p)
26698 ;; FIXME: positions wrong.
26699 (push (list :latex-fragment (point) (point)) clist)))
26701 (setq clist (nreverse (delq nil clist)))
26702 clist))
26704 ;; FIXME: Compare with at-regexp-p Do we need both?
26705 (defun org-in-regexp (re &optional nlines visually)
26706 "Check if point is inside a match of regexp.
26707 Normally only the current line is checked, but you can include NLINES extra
26708 lines both before and after point into the search.
26709 If VISUALLY is set, require that the cursor is not after the match but
26710 really on, so that the block visually is on the match."
26711 (catch 'exit
26712 (let ((pos (point))
26713 (eol (point-at-eol (+ 1 (or nlines 0))))
26714 (inc (if visually 1 0)))
26715 (save-excursion
26716 (beginning-of-line (- 1 (or nlines 0)))
26717 (while (re-search-forward re eol t)
26718 (if (and (<= (match-beginning 0) pos)
26719 (>= (+ inc (match-end 0)) pos))
26720 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
26722 (defun org-at-regexp-p (regexp)
26723 "Is point inside a match of REGEXP in the current line?"
26724 (catch 'exit
26725 (save-excursion
26726 (let ((pos (point)) (end (point-at-eol)))
26727 (beginning-of-line 1)
26728 (while (re-search-forward regexp end t)
26729 (if (and (<= (match-beginning 0) pos)
26730 (>= (match-end 0) pos))
26731 (throw 'exit t)))
26732 nil))))
26734 (defun org-occur-in-agenda-files (regexp &optional nlines)
26735 "Call `multi-occur' with buffers for all agenda files."
26736 (interactive "sOrg-files matching: \np")
26737 (let* ((files (org-agenda-files))
26738 (tnames (mapcar 'file-truename files))
26739 (extra org-agenda-multi-occur-extra-files)
26741 (while (setq f (pop extra))
26742 (unless (member (file-truename f) tnames)
26743 (add-to-list 'files f 'append)
26744 (add-to-list 'tnames (file-truename f) 'append)))
26745 (multi-occur
26746 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
26747 regexp)))
26749 (defun org-uniquify (list)
26750 "Remove duplicate elements from LIST."
26751 (let (res)
26752 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
26753 res))
26755 (defun org-delete-all (elts list)
26756 "Remove all elements in ELTS from LIST."
26757 (while elts
26758 (setq list (delete (pop elts) list)))
26759 list)
26761 (defun org-point-in-group (point group &optional context)
26762 "Check if POINT is in match-group GROUP.
26763 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
26764 match. If the match group does ot exist or point is not inside it,
26765 return nil."
26766 (and (match-beginning group)
26767 (>= point (match-beginning group))
26768 (<= point (match-end group))
26769 (if context
26770 (list context (match-beginning group) (match-end group))
26771 t)))
26773 (defun org-switch-to-buffer-other-window (&rest args)
26774 "Switch to buffer in a second window on the current frame.
26775 In particular, do not allow pop-up frames."
26776 (let (pop-up-frames special-display-buffer-names special-display-regexps
26777 special-display-function)
26778 (apply 'switch-to-buffer-other-window args)))
26780 (defun org-combine-plists (&rest plists)
26781 "Create a single property list from all plists in PLISTS.
26782 The process starts by copying the first list, and then setting properties
26783 from the other lists. Settings in the last list are the most significant
26784 ones and overrule settings in the other lists."
26785 (let ((rtn (copy-sequence (pop plists)))
26786 p v ls)
26787 (while plists
26788 (setq ls (pop plists))
26789 (while ls
26790 (setq p (pop ls) v (pop ls))
26791 (setq rtn (plist-put rtn p v))))
26792 rtn))
26794 (defun org-move-line-down (arg)
26795 "Move the current line down. With prefix argument, move it past ARG lines."
26796 (interactive "p")
26797 (let ((col (current-column))
26798 beg end pos)
26799 (beginning-of-line 1) (setq beg (point))
26800 (beginning-of-line 2) (setq end (point))
26801 (beginning-of-line (+ 1 arg))
26802 (setq pos (move-marker (make-marker) (point)))
26803 (insert (delete-and-extract-region beg end))
26804 (goto-char pos)
26805 (move-to-column col)))
26807 (defun org-move-line-up (arg)
26808 "Move the current line up. With prefix argument, move it past ARG lines."
26809 (interactive "p")
26810 (let ((col (current-column))
26811 beg end pos)
26812 (beginning-of-line 1) (setq beg (point))
26813 (beginning-of-line 2) (setq end (point))
26814 (beginning-of-line (- arg))
26815 (setq pos (move-marker (make-marker) (point)))
26816 (insert (delete-and-extract-region beg end))
26817 (goto-char pos)
26818 (move-to-column col)))
26820 (defun org-replace-escapes (string table)
26821 "Replace %-escapes in STRING with values in TABLE.
26822 TABLE is an association list with keys like \"%a\" and string values.
26823 The sequences in STRING may contain normal field width and padding information,
26824 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
26825 so values can contain further %-escapes if they are define later in TABLE."
26826 (let ((case-fold-search nil)
26827 e re rpl)
26828 (while (setq e (pop table))
26829 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
26830 (while (string-match re string)
26831 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
26832 (cdr e)))
26833 (setq string (replace-match rpl t t string))))
26834 string))
26837 (defun org-sublist (list start end)
26838 "Return a section of LIST, from START to END.
26839 Counting starts at 1."
26840 (let (rtn (c start))
26841 (setq list (nthcdr (1- start) list))
26842 (while (and list (<= c end))
26843 (push (pop list) rtn)
26844 (setq c (1+ c)))
26845 (nreverse rtn)))
26847 (defun org-find-base-buffer-visiting (file)
26848 "Like `find-buffer-visiting' but alway return the base buffer and
26849 not an indirect buffer"
26850 (let ((buf (find-buffer-visiting file)))
26851 (if buf
26852 (or (buffer-base-buffer buf) buf)
26853 nil)))
26855 (defun org-image-file-name-regexp ()
26856 "Return regexp matching the file names of images."
26857 (if (fboundp 'image-file-name-regexp)
26858 (image-file-name-regexp)
26859 (let ((image-file-name-extensions
26860 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
26861 "xbm" "xpm" "pbm" "pgm" "ppm")))
26862 (concat "\\."
26863 (regexp-opt (nconc (mapcar 'upcase
26864 image-file-name-extensions)
26865 image-file-name-extensions)
26867 "\\'"))))
26869 (defun org-file-image-p (file)
26870 "Return non-nil if FILE is an image."
26871 (save-match-data
26872 (string-match (org-image-file-name-regexp) file)))
26874 ;;; Paragraph filling stuff.
26875 ;; We want this to be just right, so use the full arsenal.
26877 (defun org-indent-line-function ()
26878 "Indent line like previous, but further if previous was headline or item."
26879 (interactive)
26880 (let* ((pos (point))
26881 (itemp (org-at-item-p))
26882 column bpos bcol tpos tcol bullet btype bullet-type)
26883 ;; Find the previous relevant line
26884 (beginning-of-line 1)
26885 (cond
26886 ((looking-at "#") (setq column 0))
26887 ((looking-at "\\*+ ") (setq column 0))
26889 (beginning-of-line 0)
26890 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
26891 (beginning-of-line 0))
26892 (cond
26893 ((looking-at "\\*+[ \t]+")
26894 (goto-char (match-end 0))
26895 (setq column (current-column)))
26896 ((org-in-item-p)
26897 (org-beginning-of-item)
26898 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
26899 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
26900 (setq bpos (match-beginning 1) tpos (match-end 0)
26901 bcol (progn (goto-char bpos) (current-column))
26902 tcol (progn (goto-char tpos) (current-column))
26903 bullet (match-string 1)
26904 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
26905 (if (not itemp)
26906 (setq column tcol)
26907 (goto-char pos)
26908 (beginning-of-line 1)
26909 (if (looking-at "\\S-")
26910 (progn
26911 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
26912 (setq bullet (match-string 1)
26913 btype (if (string-match "[0-9]" bullet) "n" bullet))
26914 (setq column (if (equal btype bullet-type) bcol tcol)))
26915 (setq column (org-get-indentation)))))
26916 (t (setq column (org-get-indentation))))))
26917 (goto-char pos)
26918 (if (<= (current-column) (current-indentation))
26919 (indent-line-to column)
26920 (save-excursion (indent-line-to column)))
26921 (setq column (current-column))
26922 (beginning-of-line 1)
26923 (if (looking-at
26924 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
26925 (replace-match (concat "\\1" (format org-property-format
26926 (match-string 2) (match-string 3)))
26927 t nil))
26928 (move-to-column column)))
26930 (defun org-set-autofill-regexps ()
26931 (interactive)
26932 ;; In the paragraph separator we include headlines, because filling
26933 ;; text in a line directly attached to a headline would otherwise
26934 ;; fill the headline as well.
26935 (org-set-local 'comment-start-skip "^#+[ \t]*")
26936 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
26937 ;; The paragraph starter includes hand-formatted lists.
26938 (org-set-local 'paragraph-start
26939 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
26940 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
26941 ;; But only if the user has not turned off tables or fixed-width regions
26942 (org-set-local
26943 'auto-fill-inhibit-regexp
26944 (concat "\\*+ \\|#\\+"
26945 "\\|[ \t]*" org-keyword-time-regexp
26946 (if (or org-enable-table-editor org-enable-fixed-width-editor)
26947 (concat
26948 "\\|[ \t]*["
26949 (if org-enable-table-editor "|" "")
26950 (if org-enable-fixed-width-editor ":" "")
26951 "]"))))
26952 ;; We use our own fill-paragraph function, to make sure that tables
26953 ;; and fixed-width regions are not wrapped. That function will pass
26954 ;; through to `fill-paragraph' when appropriate.
26955 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
26956 ; Adaptive filling: To get full control, first make sure that
26957 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
26958 (org-set-local 'adaptive-fill-regexp "\000")
26959 (org-set-local 'adaptive-fill-function
26960 'org-adaptive-fill-function))
26962 (defun org-fill-paragraph (&optional justify)
26963 "Re-align a table, pass through to fill-paragraph if no table."
26964 (let ((table-p (org-at-table-p))
26965 (table.el-p (org-at-table.el-p)))
26966 (cond ((and (equal (char-after (point-at-bol)) ?*)
26967 (save-excursion (goto-char (point-at-bol))
26968 (looking-at outline-regexp)))
26969 t) ; skip headlines
26970 (table.el-p t) ; skip table.el tables
26971 (table-p (org-table-align) t) ; align org-mode tables
26972 (t nil)))) ; call paragraph-fill
26974 ;; For reference, this is the default value of adaptive-fill-regexp
26975 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
26977 (defun org-adaptive-fill-function ()
26978 "Return a fill prefix for org-mode files.
26979 In particular, this makes sure hanging paragraphs for hand-formatted lists
26980 work correctly."
26981 (cond ((looking-at "#[ \t]+")
26982 (match-string 0))
26983 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
26984 (save-excursion
26985 (goto-char (match-end 0))
26986 (make-string (current-column) ?\ )))
26987 (t nil)))
26989 ;;;; Functions extending outline functionality
26991 (defun org-beginning-of-line (&optional arg)
26992 "Go to the beginning of the current line. If that is invisible, continue
26993 to a visible line beginning. This makes the function of C-a more intuitive.
26994 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
26995 first attempt, and only move to after the tags when the cursor is already
26996 beyond the end of the headline."
26997 (interactive "P")
26998 (let ((pos (point)))
26999 (beginning-of-line 1)
27000 (if (bobp)
27002 (backward-char 1)
27003 (if (org-invisible-p)
27004 (while (and (not (bobp)) (org-invisible-p))
27005 (backward-char 1)
27006 (beginning-of-line 1))
27007 (forward-char 1)))
27008 (when org-special-ctrl-a/e
27009 (cond
27010 ((and (looking-at org-todo-line-regexp)
27011 (= (char-after (match-end 1)) ?\ ))
27012 (goto-char
27013 (if (eq org-special-ctrl-a/e t)
27014 (cond ((> pos (match-beginning 3)) (match-beginning 3))
27015 ((= pos (point)) (match-beginning 3))
27016 (t (point)))
27017 (cond ((> pos (point)) (point))
27018 ((not (eq last-command this-command)) (point))
27019 (t (match-beginning 3))))))
27020 ((org-at-item-p)
27021 (goto-char
27022 (if (eq org-special-ctrl-a/e t)
27023 (cond ((> pos (match-end 4)) (match-end 4))
27024 ((= pos (point)) (match-end 4))
27025 (t (point)))
27026 (cond ((> pos (point)) (point))
27027 ((not (eq last-command this-command)) (point))
27028 (t (match-end 4))))))))))
27030 (defun org-end-of-line (&optional arg)
27031 "Go to the end of the line.
27032 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27033 first attempt, and only move to after the tags when the cursor is already
27034 beyond the end of the headline."
27035 (interactive "P")
27036 (if (or (not org-special-ctrl-a/e)
27037 (not (org-on-heading-p)))
27038 (end-of-line arg)
27039 (let ((pos (point)))
27040 (beginning-of-line 1)
27041 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
27042 (if (eq org-special-ctrl-a/e t)
27043 (if (or (< pos (match-beginning 1))
27044 (= pos (match-end 0)))
27045 (goto-char (match-beginning 1))
27046 (goto-char (match-end 0)))
27047 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
27048 (goto-char (match-end 0))
27049 (goto-char (match-beginning 1))))
27050 (end-of-line arg)))))
27052 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
27053 (define-key org-mode-map "\C-e" 'org-end-of-line)
27055 (defun org-invisible-p ()
27056 "Check if point is at a character currently not visible."
27057 ;; Early versions of noutline don't have `outline-invisible-p'.
27058 (if (fboundp 'outline-invisible-p)
27059 (outline-invisible-p)
27060 (get-char-property (point) 'invisible)))
27062 (defun org-invisible-p2 ()
27063 "Check if point is at a character currently not visible."
27064 (save-excursion
27065 (if (and (eolp) (not (bobp))) (backward-char 1))
27066 ;; Early versions of noutline don't have `outline-invisible-p'.
27067 (if (fboundp 'outline-invisible-p)
27068 (outline-invisible-p)
27069 (get-char-property (point) 'invisible))))
27071 (defalias 'org-back-to-heading 'outline-back-to-heading)
27072 (defalias 'org-on-heading-p 'outline-on-heading-p)
27073 (defalias 'org-at-heading-p 'outline-on-heading-p)
27074 (defun org-at-heading-or-item-p ()
27075 (or (org-on-heading-p) (org-at-item-p)))
27077 (defun org-on-target-p ()
27078 (or (org-in-regexp org-radio-target-regexp)
27079 (org-in-regexp org-target-regexp)))
27081 (defun org-up-heading-all (arg)
27082 "Move to the heading line of which the present line is a subheading.
27083 This function considers both visible and invisible heading lines.
27084 With argument, move up ARG levels."
27085 (if (fboundp 'outline-up-heading-all)
27086 (outline-up-heading-all arg) ; emacs 21 version of outline.el
27087 (outline-up-heading arg t))) ; emacs 22 version of outline.el
27089 (defun org-up-heading-safe ()
27090 "Move to the heading line of which the present line is a subheading.
27091 This version will not throw an error. It will return the level of the
27092 headline found, or nil if no higher level is found."
27093 (let ((pos (point)) start-level level
27094 (re (concat "^" outline-regexp)))
27095 (catch 'exit
27096 (outline-back-to-heading t)
27097 (setq start-level (funcall outline-level))
27098 (if (equal start-level 1) (throw 'exit nil))
27099 (while (re-search-backward re nil t)
27100 (setq level (funcall outline-level))
27101 (if (< level start-level) (throw 'exit level)))
27102 nil)))
27104 (defun org-goto-sibling (&optional previous)
27105 "Goto the next sibling, even if it is invisible.
27106 When PREVIOUS is set, go to the previous sibling instead. Returns t
27107 when a sibling was found. When none is found, return nil and don't
27108 move point."
27109 (let ((fun (if previous 're-search-backward 're-search-forward))
27110 (pos (point))
27111 (re (concat "^" outline-regexp))
27112 level l)
27113 (when (condition-case nil (org-back-to-heading t) (error nil))
27114 (setq level (funcall outline-level))
27115 (catch 'exit
27116 (or previous (forward-char 1))
27117 (while (funcall fun re nil t)
27118 (setq l (funcall outline-level))
27119 (when (< l level) (goto-char pos) (throw 'exit nil))
27120 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
27121 (goto-char pos)
27122 nil))))
27124 (defun org-show-siblings ()
27125 "Show all siblings of the current headline."
27126 (save-excursion
27127 (while (org-goto-sibling) (org-flag-heading nil)))
27128 (save-excursion
27129 (while (org-goto-sibling 'previous)
27130 (org-flag-heading nil))))
27132 (defun org-show-hidden-entry ()
27133 "Show an entry where even the heading is hidden."
27134 (save-excursion
27135 (org-show-entry)))
27137 (defun org-flag-heading (flag &optional entry)
27138 "Flag the current heading. FLAG non-nil means make invisible.
27139 When ENTRY is non-nil, show the entire entry."
27140 (save-excursion
27141 (org-back-to-heading t)
27142 ;; Check if we should show the entire entry
27143 (if entry
27144 (progn
27145 (org-show-entry)
27146 (save-excursion
27147 (and (outline-next-heading)
27148 (org-flag-heading nil))))
27149 (outline-flag-region (max (point-min) (1- (point)))
27150 (save-excursion (outline-end-of-heading) (point))
27151 flag))))
27153 (defun org-end-of-subtree (&optional invisible-OK to-heading)
27154 ;; This is an exact copy of the original function, but it uses
27155 ;; `org-back-to-heading', to make it work also in invisible
27156 ;; trees. And is uses an invisible-OK argument.
27157 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
27158 (org-back-to-heading invisible-OK)
27159 (let ((first t)
27160 (level (funcall outline-level)))
27161 (while (and (not (eobp))
27162 (or first (> (funcall outline-level) level)))
27163 (setq first nil)
27164 (outline-next-heading))
27165 (unless to-heading
27166 (if (memq (preceding-char) '(?\n ?\^M))
27167 (progn
27168 ;; Go to end of line before heading
27169 (forward-char -1)
27170 (if (memq (preceding-char) '(?\n ?\^M))
27171 ;; leave blank line before heading
27172 (forward-char -1))))))
27173 (point))
27175 (defun org-show-subtree ()
27176 "Show everything after this heading at deeper levels."
27177 (outline-flag-region
27178 (point)
27179 (save-excursion
27180 (outline-end-of-subtree) (outline-next-heading) (point))
27181 nil))
27183 (defun org-show-entry ()
27184 "Show the body directly following this heading.
27185 Show the heading too, if it is currently invisible."
27186 (interactive)
27187 (save-excursion
27188 (condition-case nil
27189 (progn
27190 (org-back-to-heading t)
27191 (outline-flag-region
27192 (max (point-min) (1- (point)))
27193 (save-excursion
27194 (re-search-forward
27195 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
27196 (or (match-beginning 1) (point-max)))
27197 nil))
27198 (error nil))))
27200 (defun org-make-options-regexp (kwds)
27201 "Make a regular expression for keyword lines."
27202 (concat
27204 "#?[ \t]*\\+\\("
27205 (mapconcat 'regexp-quote kwds "\\|")
27206 "\\):[ \t]*"
27207 "\\(.+\\)"))
27209 ;; Make isearch reveal the necessary context
27210 (defun org-isearch-end ()
27211 "Reveal context after isearch exits."
27212 (when isearch-success ; only if search was successful
27213 (if (featurep 'xemacs)
27214 ;; Under XEmacs, the hook is run in the correct place,
27215 ;; we directly show the context.
27216 (org-show-context 'isearch)
27217 ;; In Emacs the hook runs *before* restoring the overlays.
27218 ;; So we have to use a one-time post-command-hook to do this.
27219 ;; (Emacs 22 has a special variable, see function `org-mode')
27220 (unless (and (boundp 'isearch-mode-end-hook-quit)
27221 isearch-mode-end-hook-quit)
27222 ;; Only when the isearch was not quitted.
27223 (org-add-hook 'post-command-hook 'org-isearch-post-command
27224 'append 'local)))))
27226 (defun org-isearch-post-command ()
27227 "Remove self from hook, and show context."
27228 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
27229 (org-show-context 'isearch))
27232 ;;;; Integration with and fixes for other packages
27234 ;;; Imenu support
27236 (defvar org-imenu-markers nil
27237 "All markers currently used by Imenu.")
27238 (make-variable-buffer-local 'org-imenu-markers)
27240 (defun org-imenu-new-marker (&optional pos)
27241 "Return a new marker for use by Imenu, and remember the marker."
27242 (let ((m (make-marker)))
27243 (move-marker m (or pos (point)))
27244 (push m org-imenu-markers)
27247 (defun org-imenu-get-tree ()
27248 "Produce the index for Imenu."
27249 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
27250 (setq org-imenu-markers nil)
27251 (let* ((n org-imenu-depth)
27252 (re (concat "^" outline-regexp))
27253 (subs (make-vector (1+ n) nil))
27254 (last-level 0)
27255 m tree level head)
27256 (save-excursion
27257 (save-restriction
27258 (widen)
27259 (goto-char (point-max))
27260 (while (re-search-backward re nil t)
27261 (setq level (org-reduced-level (funcall outline-level)))
27262 (when (<= level n)
27263 (looking-at org-complex-heading-regexp)
27264 (setq head (org-match-string-no-properties 4)
27265 m (org-imenu-new-marker))
27266 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
27267 (if (>= level last-level)
27268 (push (cons head m) (aref subs level))
27269 (push (cons head (aref subs (1+ level))) (aref subs level))
27270 (loop for i from (1+ level) to n do (aset subs i nil)))
27271 (setq last-level level)))))
27272 (aref subs 1)))
27274 (eval-after-load "imenu"
27275 '(progn
27276 (add-hook 'imenu-after-jump-hook
27277 (lambda () (org-show-context 'org-goto)))))
27279 ;; Speedbar support
27281 (defun org-speedbar-set-agenda-restriction ()
27282 "Restrict future agenda commands to the location at point in speedbar.
27283 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
27284 (interactive)
27285 (let (p m tp np dir txt w)
27286 (cond
27287 ((setq p (text-property-any (point-at-bol) (point-at-eol)
27288 'org-imenu t))
27289 (setq m (get-text-property p 'org-imenu-marker))
27290 (save-excursion
27291 (save-restriction
27292 (set-buffer (marker-buffer m))
27293 (goto-char m)
27294 (org-agenda-set-restriction-lock 'subtree))))
27295 ((setq p (text-property-any (point-at-bol) (point-at-eol)
27296 'speedbar-function 'speedbar-find-file))
27297 (setq tp (previous-single-property-change
27298 (1+ p) 'speedbar-function)
27299 np (next-single-property-change
27300 tp 'speedbar-function)
27301 dir (speedbar-line-directory)
27302 txt (buffer-substring-no-properties (or tp (point-min))
27303 (or np (point-max))))
27304 (save-excursion
27305 (save-restriction
27306 (set-buffer (find-file-noselect
27307 (let ((default-directory dir))
27308 (expand-file-name txt))))
27309 (unless (org-mode-p)
27310 (error "Cannot restrict to non-Org-mode file"))
27311 (org-agenda-set-restriction-lock 'file))))
27312 (t (error "Don't know how to restrict Org-mode's agenda")))
27313 (org-move-overlay org-speedbar-restriction-lock-overlay
27314 (point-at-bol) (point-at-eol))
27315 (setq current-prefix-arg nil)
27316 (org-agenda-maybe-redo)))
27318 (eval-after-load "speedbar"
27319 '(progn
27320 (speedbar-add-supported-extension ".org")
27321 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
27322 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
27323 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
27324 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
27325 (add-hook 'speedbar-visiting-tag-hook
27326 (lambda () (org-show-context 'org-goto)))))
27329 ;;; Fixes and Hacks
27331 ;; Make flyspell not check words in links, to not mess up our keymap
27332 (defun org-mode-flyspell-verify ()
27333 "Don't let flyspell put overlays at active buttons."
27334 (not (get-text-property (point) 'keymap)))
27336 ;; Make `bookmark-jump' show the jump location if it was hidden.
27337 (eval-after-load "bookmark"
27338 '(if (boundp 'bookmark-after-jump-hook)
27339 ;; We can use the hook
27340 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
27341 ;; Hook not available, use advice
27342 (defadvice bookmark-jump (after org-make-visible activate)
27343 "Make the position visible."
27344 (org-bookmark-jump-unhide))))
27346 (defun org-bookmark-jump-unhide ()
27347 "Unhide the current position, to show the bookmark location."
27348 (and (org-mode-p)
27349 (or (org-invisible-p)
27350 (save-excursion (goto-char (max (point-min) (1- (point))))
27351 (org-invisible-p)))
27352 (org-show-context 'bookmark-jump)))
27354 ;; Fix a bug in htmlize where there are text properties (face nil)
27355 (eval-after-load "htmlize"
27356 '(progn
27357 (defadvice htmlize-faces-in-buffer (after org-no-nil-faces activate)
27358 "Make sure there are no nil faces"
27359 (setq ad-return-value (delq nil ad-return-value)))))
27361 ;; Make session.el ignore our circular variable
27362 (eval-after-load "session"
27363 '(add-to-list 'session-globals-exclude 'org-mark-ring))
27365 ;;;; Experimental code
27367 (defun org-closed-in-range ()
27368 "Sparse tree of items closed in a certain time range.
27369 Still experimental, may disappear in the future."
27370 (interactive)
27371 ;; Get the time interval from the user.
27372 (let* ((time1 (time-to-seconds
27373 (org-read-date nil 'to-time nil "Starting date: ")))
27374 (time2 (time-to-seconds
27375 (org-read-date nil 'to-time nil "End date:")))
27376 ;; callback function
27377 (callback (lambda ()
27378 (let ((time
27379 (time-to-seconds
27380 (apply 'encode-time
27381 (org-parse-time-string
27382 (match-string 1))))))
27383 ;; check if time in interval
27384 (and (>= time time1) (<= time time2))))))
27385 ;; make tree, check each match with the callback
27386 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
27388 ;;;; Finish up
27390 (provide 'org)
27392 (run-hooks 'org-load-hook)
27394 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
27395 ;;; org.el ends here