Delete some unnecessary files.
[org-mode.git] / org.el
blob007870871e4a5082d7de8216d66f81a9397a40a1
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;; Version: 5.20
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.20"
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 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\(\\+[0-9]+[dwmy]\\)"
328 "Regular expression for specifying repeated events.
329 After a match, group 1 contains the repeat expression.")
331 (defgroup org-structure nil
332 "Options concerning the general structure of Org-mode files."
333 :tag "Org Structure"
334 :group 'org)
336 (defgroup org-reveal-location nil
337 "Options about how to make context of a location visible."
338 :tag "Org Reveal Location"
339 :group 'org-structure)
341 (defconst org-context-choice
342 '(choice
343 (const :tag "Always" t)
344 (const :tag "Never" nil)
345 (repeat :greedy t :tag "Individual contexts"
346 (cons
347 (choice :tag "Context"
348 (const agenda)
349 (const org-goto)
350 (const occur-tree)
351 (const tags-tree)
352 (const link-search)
353 (const mark-goto)
354 (const bookmark-jump)
355 (const isearch)
356 (const default))
357 (boolean))))
358 "Contexts for the reveal options.")
360 (defcustom org-show-hierarchy-above '((default . t))
361 "Non-nil means, show full hierarchy when revealing a location.
362 Org-mode often shows locations in an org-mode file which might have
363 been invisible before. When this is set, the hierarchy of headings
364 above the exposed location is shown.
365 Turning this off for example for sparse trees makes them very compact.
366 Instead of t, this can also be an alist specifying this option for different
367 contexts. Valid contexts are
368 agenda when exposing an entry from the agenda
369 org-goto when using the command `org-goto' on key C-c C-j
370 occur-tree when using the command `org-occur' on key C-c /
371 tags-tree when constructing a sparse tree based on tags matches
372 link-search when exposing search matches associated with a link
373 mark-goto when exposing the jump goal of a mark
374 bookmark-jump when exposing a bookmark location
375 isearch when exiting from an incremental search
376 default default for all contexts not set explicitly"
377 :group 'org-reveal-location
378 :type org-context-choice)
380 (defcustom org-show-following-heading '((default . nil))
381 "Non-nil means, show following heading when revealing a location.
382 Org-mode often shows locations in an org-mode file which might have
383 been invisible before. When this is set, the heading following the
384 match is shown.
385 Turning this off for example for sparse trees makes them very compact,
386 but makes it harder to edit the location of the match. In such a case,
387 use the command \\[org-reveal] to show more context.
388 Instead of t, this can also be an alist specifying this option for different
389 contexts. See `org-show-hierarchy-above' for valid contexts."
390 :group 'org-reveal-location
391 :type org-context-choice)
393 (defcustom org-show-siblings '((default . nil) (isearch t))
394 "Non-nil means, show all sibling heading when revealing a location.
395 Org-mode often shows locations in an org-mode file which might have
396 been invisible before. When this is set, the sibling of the current entry
397 heading are all made visible. If `org-show-hierarchy-above' is t,
398 the same happens on each level of the hierarchy above the current entry.
400 By default this is on for the isearch context, off for all other contexts.
401 Turning this off for example for sparse trees makes them very compact,
402 but makes it harder to edit the location of the match. In such a case,
403 use the command \\[org-reveal] to show more context.
404 Instead of t, this can also be an alist specifying this option for different
405 contexts. See `org-show-hierarchy-above' for valid contexts."
406 :group 'org-reveal-location
407 :type org-context-choice)
409 (defcustom org-show-entry-below '((default . nil))
410 "Non-nil means, show the entry below a headline when revealing a location.
411 Org-mode often shows locations in an org-mode file which might have
412 been invisible before. When this is set, the text below the headline that is
413 exposed is also shown.
415 By default this is off for all contexts.
416 Instead of t, this can also be an alist specifying this option for different
417 contexts. See `org-show-hierarchy-above' for valid contexts."
418 :group 'org-reveal-location
419 :type org-context-choice)
421 (defgroup org-cycle nil
422 "Options concerning visibility cycling in Org-mode."
423 :tag "Org Cycle"
424 :group 'org-structure)
426 (defcustom org-drawers '("PROPERTIES" "CLOCK")
427 "Names of drawers. Drawers are not opened by cycling on the headline above.
428 Drawers only open with a TAB on the drawer line itself. A drawer looks like
429 this:
430 :DRAWERNAME:
431 .....
432 :END:
433 The drawer \"PROPERTIES\" is special for capturing properties through
434 the property API.
436 Drawers can be defined on the per-file basis with a line like:
438 #+DRAWERS: HIDDEN STATE PROPERTIES"
439 :group 'org-structure
440 :type '(repeat (string :tag "Drawer Name")))
442 (defcustom org-cycle-global-at-bob nil
443 "Cycle globally if cursor is at beginning of buffer and not at a headline.
444 This makes it possible to do global cycling without having to use S-TAB or
445 C-u TAB. For this special case to work, the first line of the buffer
446 must not be a headline - it may be empty ot some other text. When used in
447 this way, `org-cycle-hook' is disables temporarily, to make sure the
448 cursor stays at the beginning of the buffer.
449 When this option is nil, don't do anything special at the beginning
450 of the buffer."
451 :group 'org-cycle
452 :type 'boolean)
454 (defcustom org-cycle-emulate-tab t
455 "Where should `org-cycle' emulate TAB.
456 nil Never
457 white Only in completely white lines
458 whitestart Only at the beginning of lines, before the first non-white char
459 t Everywhere except in headlines
460 exc-hl-bol Everywhere except at the start of a headline
461 If TAB is used in a place where it does not emulate TAB, the current subtree
462 visibility is cycled."
463 :group 'org-cycle
464 :type '(choice (const :tag "Never" nil)
465 (const :tag "Only in completely white lines" white)
466 (const :tag "Before first char in a line" whitestart)
467 (const :tag "Everywhere except in headlines" t)
468 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
471 (defcustom org-cycle-separator-lines 2
472 "Number of empty lines needed to keep an empty line between collapsed trees.
473 If you leave an empty line between the end of a subtree and the following
474 headline, this empty line is hidden when the subtree is folded.
475 Org-mode will leave (exactly) one empty line visible if the number of
476 empty lines is equal or larger to the number given in this variable.
477 So the default 2 means, at least 2 empty lines after the end of a subtree
478 are needed to produce free space between a collapsed subtree and the
479 following headline.
481 Special case: when 0, never leave empty lines in collapsed view."
482 :group 'org-cycle
483 :type 'integer)
485 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
486 org-cycle-hide-drawers
487 org-cycle-show-empty-lines
488 org-optimize-window-after-visibility-change)
489 "Hook that is run after `org-cycle' has changed the buffer visibility.
490 The function(s) in this hook must accept a single argument which indicates
491 the new state that was set by the most recent `org-cycle' command. The
492 argument is a symbol. After a global state change, it can have the values
493 `overview', `content', or `all'. After a local state change, it can have
494 the values `folded', `children', or `subtree'."
495 :group 'org-cycle
496 :type 'hook)
498 (defgroup org-edit-structure nil
499 "Options concerning structure editing in Org-mode."
500 :tag "Org Edit Structure"
501 :group 'org-structure)
503 (defcustom org-special-ctrl-a/e nil
504 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
505 When t, `C-a' will bring back the cursor to the beginning of the
506 headline text, i.e. after the stars and after a possible TODO keyword.
507 In an item, this will be the position after the bullet.
508 When the cursor is already at that position, another `C-a' will bring
509 it to the beginning of the line.
510 `C-e' will jump to the end of the headline, ignoring the presence of tags
511 in the headline. A second `C-e' will then jump to the true end of the
512 line, after any tags.
513 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
514 and only a directly following, identical keypress will bring the cursor
515 to the special positions."
516 :group 'org-edit-structure
517 :type '(choice
518 (const :tag "off" nil)
519 (const :tag "after bullet first" t)
520 (const :tag "border first" reversed)))
522 (if (fboundp 'defvaralias)
523 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
525 (defcustom org-special-ctrl-k nil
526 "Non-nil means `C-k' will behave specially in headlines.
527 When nil, `C-k' will call the default `kill-line' command.
528 When t, the following will happen while the cursor is in the headline:
530 - When the cursor is at the beginning of a headline, kill the entire
531 line and possible the folded subtree below the line.
532 - When in the middle of the headline text, kill the headline up to the tags.
533 - When after the headline text, kill the tags."
534 :group 'org-edit-structure
535 :type 'boolean)
537 (defcustom org-odd-levels-only nil
538 "Non-nil means, skip even levels and only use odd levels for the outline.
539 This has the effect that two stars are being added/taken away in
540 promotion/demotion commands. It also influences how levels are
541 handled by the exporters.
542 Changing it requires restart of `font-lock-mode' to become effective
543 for fontification also in regions already fontified.
544 You may also set this on a per-file basis by adding one of the following
545 lines to the buffer:
547 #+STARTUP: odd
548 #+STARTUP: oddeven"
549 :group 'org-edit-structure
550 :group 'org-font-lock
551 :type 'boolean)
553 (defcustom org-adapt-indentation t
554 "Non-nil means, adapt indentation when promoting and demoting.
555 When this is set and the *entire* text in an entry is indented, the
556 indentation is increased by one space in a demotion command, and
557 decreased by one in a promotion command. If any line in the entry
558 body starts at column 0, indentation is not changed at all."
559 :group 'org-edit-structure
560 :type 'boolean)
562 (defcustom org-blank-before-new-entry '((heading . nil)
563 (plain-list-item . nil))
564 "Should `org-insert-heading' leave a blank line before new heading/item?
565 The value is an alist, with `heading' and `plain-list-item' as car,
566 and a boolean flag as cdr."
567 :group 'org-edit-structure
568 :type '(list
569 (cons (const heading) (boolean))
570 (cons (const plain-list-item) (boolean))))
572 (defcustom org-insert-heading-hook nil
573 "Hook being run after inserting a new heading."
574 :group 'org-edit-structure
575 :type 'hook)
577 (defcustom org-enable-fixed-width-editor t
578 "Non-nil means, lines starting with \":\" are treated as fixed-width.
579 This currently only means, they are never auto-wrapped.
580 When nil, such lines will be treated like ordinary lines.
581 See also the QUOTE keyword."
582 :group 'org-edit-structure
583 :type 'boolean)
585 (defcustom org-goto-auto-isearch t
586 "Non-nil means, typing characters in org-goto starts incremental search."
587 :group 'org-edit-structure
588 :type 'boolean)
590 (defgroup org-sparse-trees nil
591 "Options concerning sparse trees in Org-mode."
592 :tag "Org Sparse Trees"
593 :group 'org-structure)
595 (defcustom org-highlight-sparse-tree-matches t
596 "Non-nil means, highlight all matches that define a sparse tree.
597 The highlights will automatically disappear the next time the buffer is
598 changed by an edit command."
599 :group 'org-sparse-trees
600 :type 'boolean)
602 (defcustom org-remove-highlights-with-change t
603 "Non-nil means, any change to the buffer will remove temporary highlights.
604 Such highlights are created by `org-occur' and `org-clock-display'.
605 When nil, `C-c C-c needs to be used to get rid of the highlights.
606 The highlights created by `org-preview-latex-fragment' always need
607 `C-c C-c' to be removed."
608 :group 'org-sparse-trees
609 :group 'org-time
610 :type 'boolean)
613 (defcustom org-occur-hook '(org-first-headline-recenter)
614 "Hook that is run after `org-occur' has constructed a sparse tree.
615 This can be used to recenter the window to show as much of the structure
616 as possible."
617 :group 'org-sparse-trees
618 :type 'hook)
620 (defgroup org-plain-lists nil
621 "Options concerning plain lists in Org-mode."
622 :tag "Org Plain lists"
623 :group 'org-structure)
625 (defcustom org-cycle-include-plain-lists nil
626 "Non-nil means, include plain lists into visibility cycling.
627 This means that during cycling, plain list items will *temporarily* be
628 interpreted as outline headlines with a level given by 1000+i where i is the
629 indentation of the bullet. In all other operations, plain list items are
630 not seen as headlines. For example, you cannot assign a TODO keyword to
631 such an item."
632 :group 'org-plain-lists
633 :type 'boolean)
635 (defcustom org-plain-list-ordered-item-terminator t
636 "The character that makes a line with leading number an ordered list item.
637 Valid values are ?. and ?\). To get both terminators, use t. While
638 ?. may look nicer, it creates the danger that a line with leading
639 number may be incorrectly interpreted as an item. ?\) therefore is
640 the safe choice."
641 :group 'org-plain-lists
642 :type '(choice (const :tag "dot like in \"2.\"" ?.)
643 (const :tag "paren like in \"2)\"" ?\))
644 (const :tab "both" t)))
646 (defcustom org-auto-renumber-ordered-lists t
647 "Non-nil means, automatically renumber ordered plain lists.
648 Renumbering happens when the sequence have been changed with
649 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
650 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
651 :group 'org-plain-lists
652 :type 'boolean)
654 (defcustom org-provide-checkbox-statistics t
655 "Non-nil means, update checkbox statistics after insert and toggle.
656 When this is set, checkbox statistics is updated each time you either insert
657 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
658 with \\[org-ctrl-c-ctrl-c\\]."
659 :group 'org-plain-lists
660 :type 'boolean)
662 (defgroup org-archive nil
663 "Options concerning archiving in Org-mode."
664 :tag "Org Archive"
665 :group 'org-structure)
667 (defcustom org-archive-tag "ARCHIVE"
668 "The tag that marks a subtree as archived.
669 An archived subtree does not open during visibility cycling, and does
670 not contribute to the agenda listings.
671 After changing this, font-lock must be restarted in the relevant buffers to
672 get the proper fontification."
673 :group 'org-archive
674 :group 'org-keywords
675 :type 'string)
677 (defcustom org-agenda-skip-archived-trees t
678 "Non-nil means, the agenda will skip any items located in archived trees.
679 An archived tree is a tree marked with the tag ARCHIVE."
680 :group 'org-archive
681 :group 'org-agenda-skip
682 :type 'boolean)
684 (defcustom org-cycle-open-archived-trees nil
685 "Non-nil means, `org-cycle' will open archived trees.
686 An archived tree is a tree marked with the tag ARCHIVE.
687 When nil, archived trees will stay folded. You can still open them with
688 normal outline commands like `show-all', but not with the cycling commands."
689 :group 'org-archive
690 :group 'org-cycle
691 :type 'boolean)
693 (defcustom org-sparse-tree-open-archived-trees nil
694 "Non-nil means sparse tree construction shows matches in archived trees.
695 When nil, matches in these trees are highlighted, but the trees are kept in
696 collapsed state."
697 :group 'org-archive
698 :group 'org-sparse-trees
699 :type 'boolean)
701 (defcustom org-archive-location "%s_archive::"
702 "The location where subtrees should be archived.
703 This string consists of two parts, separated by a double-colon.
705 The first part is a file name - when omitted, archiving happens in the same
706 file. %s will be replaced by the current file name (without directory part).
707 Archiving to a different file is useful to keep archived entries from
708 contributing to the Org-mode Agenda.
710 The part after the double colon is a headline. The archived entries will be
711 filed under that headline. When omitted, the subtrees are simply filed away
712 at the end of the file, as top-level entries.
714 Here are a few examples:
715 \"%s_archive::\"
716 If the current file is Projects.org, archive in file
717 Projects.org_archive, as top-level trees. This is the default.
719 \"::* Archived Tasks\"
720 Archive in the current file, under the top-level headline
721 \"* Archived Tasks\".
723 \"~/org/archive.org::\"
724 Archive in file ~/org/archive.org (absolute path), as top-level trees.
726 \"basement::** Finished Tasks\"
727 Archive in file ./basement (relative path), as level 3 trees
728 below the level 2 heading \"** Finished Tasks\".
730 You may set this option on a per-file basis by adding to the buffer a
731 line like
733 #+ARCHIVE: basement::** Finished Tasks"
734 :group 'org-archive
735 :type 'string)
737 (defcustom org-archive-mark-done t
738 "Non-nil means, mark entries as DONE when they are moved to the archive file.
739 This can be a string to set the keyword to use. When t, Org-mode will
740 use the first keyword in its list that means done."
741 :group 'org-archive
742 :type '(choice
743 (const :tag "No" nil)
744 (const :tag "Yes" t)
745 (string :tag "Use this keyword")))
747 (defcustom org-archive-stamp-time t
748 "Non-nil means, add a time stamp to entries moved to an archive file.
749 This variable is obsolete and has no effect anymore, instead add ot remove
750 `time' from the variablle `org-archive-save-context-info'."
751 :group 'org-archive
752 :type 'boolean)
754 (defcustom org-archive-save-context-info '(time file olpath category todo itags)
755 "Parts of context info that should be stored as properties when archiving.
756 When a subtree is moved to an archive file, it looses information given by
757 context, like inherited tags, the category, and possibly also the TODO
758 state (depending on the variable `org-archive-mark-done').
759 This variable can be a list of any of the following symbols:
761 time The time of archiving.
762 file The file where the entry originates.
763 itags The local tags, in the headline of the subtree.
764 ltags The tags the subtree inherits from further up the hierarchy.
765 todo The pre-archive TODO state.
766 category The category, taken from file name or #+CATEGORY lines.
767 olpath The outline path to the item. These are all headlines above
768 the current item, separated by /, like a file path.
770 For each symbol present in the list, a property will be created in
771 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
772 information."
773 :group 'org-archive
774 :type '(set :greedy t
775 (const :tag "Time" time)
776 (const :tag "File" file)
777 (const :tag "Category" category)
778 (const :tag "TODO state" todo)
779 (const :tag "TODO state" priority)
780 (const :tag "Inherited tags" itags)
781 (const :tag "Outline path" olpath)
782 (const :tag "Local tags" ltags)))
784 (defgroup org-imenu-and-speedbar nil
785 "Options concerning imenu and speedbar in Org-mode."
786 :tag "Org Imenu and Speedbar"
787 :group 'org-structure)
789 (defcustom org-imenu-depth 2
790 "The maximum level for Imenu access to Org-mode headlines.
791 This also applied for speedbar access."
792 :group 'org-imenu-and-speedbar
793 :type 'number)
795 (defgroup org-table nil
796 "Options concerning tables in Org-mode."
797 :tag "Org Table"
798 :group 'org)
800 (defcustom org-enable-table-editor 'optimized
801 "Non-nil means, lines starting with \"|\" are handled by the table editor.
802 When nil, such lines will be treated like ordinary lines.
804 When equal to the symbol `optimized', the table editor will be optimized to
805 do the following:
806 - Automatic overwrite mode in front of whitespace in table fields.
807 This makes the structure of the table stay in tact as long as the edited
808 field does not exceed the column width.
809 - Minimize the number of realigns. Normally, the table is aligned each time
810 TAB or RET are pressed to move to another field. With optimization this
811 happens only if changes to a field might have changed the column width.
812 Optimization requires replacing the functions `self-insert-command',
813 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
814 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
815 very good at guessing when a re-align will be necessary, but you can always
816 force one with \\[org-ctrl-c-ctrl-c].
818 If you would like to use the optimized version in Org-mode, but the
819 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
821 This variable can be used to turn on and off the table editor during a session,
822 but in order to toggle optimization, a restart is required.
824 See also the variable `org-table-auto-blank-field'."
825 :group 'org-table
826 :type '(choice
827 (const :tag "off" nil)
828 (const :tag "on" t)
829 (const :tag "on, optimized" optimized)))
831 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
832 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
833 In the optimized version, the table editor takes over all simple keys that
834 normally just insert a character. In tables, the characters are inserted
835 in a way to minimize disturbing the table structure (i.e. in overwrite mode
836 for empty fields). Outside tables, the correct binding of the keys is
837 restored.
839 The default for this option is t if the optimized version is also used in
840 Org-mode. See the variable `org-enable-table-editor' for details. Changing
841 this variable requires a restart of Emacs to become effective."
842 :group 'org-table
843 :type 'boolean)
845 (defcustom orgtbl-radio-table-templates
846 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
847 % END RECEIVE ORGTBL %n
848 \\begin{comment}
849 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
850 | | |
851 \\end{comment}\n")
852 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
853 @c END RECEIVE ORGTBL %n
854 @ignore
855 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
856 | | |
857 @end ignore\n")
858 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
859 <!-- END RECEIVE ORGTBL %n -->
860 <!--
861 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
862 | | |
863 -->\n"))
864 "Templates for radio tables in different major modes.
865 All occurrences of %n in a template will be replaced with the name of the
866 table, obtained by prompting the user."
867 :group 'org-table
868 :type '(repeat
869 (list (symbol :tag "Major mode")
870 (string :tag "Format"))))
872 (defgroup org-table-settings nil
873 "Settings for tables in Org-mode."
874 :tag "Org Table Settings"
875 :group 'org-table)
877 (defcustom org-table-default-size "5x2"
878 "The default size for newly created tables, Columns x Rows."
879 :group 'org-table-settings
880 :type 'string)
882 (defcustom org-table-number-regexp
883 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
884 "Regular expression for recognizing numbers in table columns.
885 If a table column contains mostly numbers, it will be aligned to the
886 right. If not, it will be aligned to the left.
888 The default value of this option is a regular expression which allows
889 anything which looks remotely like a number as used in scientific
890 context. For example, all of the following will be considered a
891 number:
892 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
894 Other options offered by the customize interface are more restrictive."
895 :group 'org-table-settings
896 :type '(choice
897 (const :tag "Positive Integers"
898 "^[0-9]+$")
899 (const :tag "Integers"
900 "^[-+]?[0-9]+$")
901 (const :tag "Floating Point Numbers"
902 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
903 (const :tag "Floating Point Number or Integer"
904 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
905 (const :tag "Exponential, Floating point, Integer"
906 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
907 (const :tag "Very General Number-Like, including hex"
908 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
909 (string :tag "Regexp:")))
911 (defcustom org-table-number-fraction 0.5
912 "Fraction of numbers in a column required to make the column align right.
913 In a column all non-white fields are considered. If at least this
914 fraction of fields is matched by `org-table-number-fraction',
915 alignment to the right border applies."
916 :group 'org-table-settings
917 :type 'number)
919 (defgroup org-table-editing nil
920 "Behavior of tables during editing in Org-mode."
921 :tag "Org Table Editing"
922 :group 'org-table)
924 (defcustom org-table-automatic-realign t
925 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
926 When nil, aligning is only done with \\[org-table-align], or after column
927 removal/insertion."
928 :group 'org-table-editing
929 :type 'boolean)
931 (defcustom org-table-auto-blank-field t
932 "Non-nil means, automatically blank table field when starting to type into it.
933 This only happens when typing immediately after a field motion
934 command (TAB, S-TAB or RET).
935 Only relevant when `org-enable-table-editor' is equal to `optimized'."
936 :group 'org-table-editing
937 :type 'boolean)
939 (defcustom org-table-tab-jumps-over-hlines t
940 "Non-nil means, tab in the last column of a table with jump over a hline.
941 If a horizontal separator line is following the current line,
942 `org-table-next-field' can either create a new row before that line, or jump
943 over the line. When this option is nil, a new line will be created before
944 this line."
945 :group 'org-table-editing
946 :type 'boolean)
948 (defcustom org-table-tab-recognizes-table.el t
949 "Non-nil means, TAB will automatically notice a table.el table.
950 When it sees such a table, it moves point into it and - if necessary -
951 calls `table-recognize-table'."
952 :group 'org-table-editing
953 :type 'boolean)
955 (defgroup org-table-calculation nil
956 "Options concerning tables in Org-mode."
957 :tag "Org Table Calculation"
958 :group 'org-table)
960 (defcustom org-table-use-standard-references t
961 "Should org-mode work with table refrences like B3 instead of @3$2?
962 Possible values are:
963 nil never use them
964 from accept as input, do not present for editing
965 t: accept as input and present for editing"
966 :group 'org-table-calculation
967 :type '(choice
968 (const :tag "Never, don't even check unser input for them" nil)
969 (const :tag "Always, both as user input, and when editing" t)
970 (const :tag "Convert user input, don't offer during editing" 'from)))
972 (defcustom org-table-copy-increment t
973 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
974 :group 'org-table-calculation
975 :type 'boolean)
977 (defcustom org-calc-default-modes
978 '(calc-internal-prec 12
979 calc-float-format (float 5)
980 calc-angle-mode deg
981 calc-prefer-frac nil
982 calc-symbolic-mode nil
983 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
984 calc-display-working-message t
986 "List with Calc mode settings for use in calc-eval for table formulas.
987 The list must contain alternating symbols (Calc modes variables and values).
988 Don't remove any of the default settings, just change the values. Org-mode
989 relies on the variables to be present in the list."
990 :group 'org-table-calculation
991 :type 'plist)
993 (defcustom org-table-formula-evaluate-inline t
994 "Non-nil means, TAB and RET evaluate a formula in current table field.
995 If the current field starts with an equal sign, it is assumed to be a formula
996 which should be evaluated as described in the manual and in the documentation
997 string of the command `org-table-eval-formula'. This feature requires the
998 Emacs calc package.
999 When this variable is nil, formula calculation is only available through
1000 the command \\[org-table-eval-formula]."
1001 :group 'org-table-calculation
1002 :type 'boolean)
1004 (defcustom org-table-formula-use-constants t
1005 "Non-nil means, interpret constants in formulas in tables.
1006 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1007 by the value given in `org-table-formula-constants', or by a value obtained
1008 from the `constants.el' package."
1009 :group 'org-table-calculation
1010 :type 'boolean)
1012 (defcustom org-table-formula-constants nil
1013 "Alist with constant names and values, for use in table formulas.
1014 The car of each element is a name of a constant, without the `$' before it.
1015 The cdr is the value as a string. For example, if you'd like to use the
1016 speed of light in a formula, you would configure
1018 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1020 and then use it in an equation like `$1*$c'.
1022 Constants can also be defined on a per-file basis using a line like
1024 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
1025 :group 'org-table-calculation
1026 :type '(repeat
1027 (cons (string :tag "name")
1028 (string :tag "value"))))
1030 (defvar org-table-formula-constants-local nil
1031 "Local version of `org-table-formula-constants'.")
1032 (make-variable-buffer-local 'org-table-formula-constants-local)
1034 (defcustom org-table-allow-automatic-line-recalculation t
1035 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1036 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1037 :group 'org-table-calculation
1038 :type 'boolean)
1040 (defgroup org-link nil
1041 "Options concerning links in Org-mode."
1042 :tag "Org Link"
1043 :group 'org)
1045 (defvar org-link-abbrev-alist-local nil
1046 "Buffer-local version of `org-link-abbrev-alist', which see.
1047 The value of this is taken from the #+LINK lines.")
1048 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1050 (defcustom org-link-abbrev-alist nil
1051 "Alist of link abbreviations.
1052 The car of each element is a string, to be replaced at the start of a link.
1053 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1054 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1056 [[linkkey:tag][description]]
1058 If REPLACE is a string, the tag will simply be appended to create the link.
1059 If the string contains \"%s\", the tag will be inserted there.
1061 REPLACE may also be a function that will be called with the tag as the
1062 only argument to create the link, which should be returned as a string.
1064 See the manual for examples."
1065 :group 'org-link
1066 :type 'alist)
1068 (defcustom org-descriptive-links t
1069 "Non-nil means, hide link part and only show description of bracket links.
1070 Bracket links are like [[link][descritpion]]. This variable sets the initial
1071 state in new org-mode buffers. The setting can then be toggled on a
1072 per-buffer basis from the Org->Hyperlinks menu."
1073 :group 'org-link
1074 :type 'boolean)
1076 (defcustom org-link-file-path-type 'adaptive
1077 "How the path name in file links should be stored.
1078 Valid values are:
1080 relative Relative to the current directory, i.e. the directory of the file
1081 into which the link is being inserted.
1082 absolute Absolute path, if possible with ~ for home directory.
1083 noabbrev Absolute path, no abbreviation of home directory.
1084 adaptive Use relative path for files in the current directory and sub-
1085 directories of it. For other files, use an absolute path."
1086 :group 'org-link
1087 :type '(choice
1088 (const relative)
1089 (const absolute)
1090 (const noabbrev)
1091 (const adaptive)))
1093 (defcustom org-activate-links '(bracket angle plain radio tag date)
1094 "Types of links that should be activated in Org-mode files.
1095 This is a list of symbols, each leading to the activation of a certain link
1096 type. In principle, it does not hurt to turn on most link types - there may
1097 be a small gain when turning off unused link types. The types are:
1099 bracket The recommended [[link][description]] or [[link]] links with hiding.
1100 angular Links in angular brackes that may contain whitespace like
1101 <bbdb:Carsten Dominik>.
1102 plain Plain links in normal text, no whitespace, like http://google.com.
1103 radio Text that is matched by a radio target, see manual for details.
1104 tag Tag settings in a headline (link to tag search).
1105 date Time stamps (link to calendar).
1107 Changing this variable requires a restart of Emacs to become effective."
1108 :group 'org-link
1109 :type '(set (const :tag "Double bracket links (new style)" bracket)
1110 (const :tag "Angular bracket links (old style)" angular)
1111 (const :tag "plain text links" plain)
1112 (const :tag "Radio target matches" radio)
1113 (const :tag "Tags" tag)
1114 (const :tag "Tags" target)
1115 (const :tag "Timestamps" date)))
1117 (defgroup org-link-store nil
1118 "Options concerning storing links in Org-mode"
1119 :tag "Org Store Link"
1120 :group 'org-link)
1122 (defcustom org-email-link-description-format "Email %c: %.30s"
1123 "Format of the description part of a link to an email or usenet message.
1124 The following %-excapes will be replaced by corresponding information:
1126 %F full \"From\" field
1127 %f name, taken from \"From\" field, address if no name
1128 %T full \"To\" field
1129 %t first name in \"To\" field, address if no name
1130 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1131 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1132 %s subject
1133 %m message-id.
1135 You may use normal field width specification between the % and the letter.
1136 This is for example useful to limit the length of the subject.
1138 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1139 :group 'org-link-store
1140 :type 'string)
1142 (defcustom org-from-is-user-regexp
1143 (let (r1 r2)
1144 (when (and user-mail-address (not (string= user-mail-address "")))
1145 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1146 (when (and user-full-name (not (string= user-full-name "")))
1147 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1148 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1149 "Regexp mached against the \"From:\" header of an email or usenet message.
1150 It should match if the message is from the user him/herself."
1151 :group 'org-link-store
1152 :type 'regexp)
1154 (defcustom org-context-in-file-links t
1155 "Non-nil means, file links from `org-store-link' contain context.
1156 A search string will be added to the file name with :: as separator and
1157 used to find the context when the link is activated by the command
1158 `org-open-at-point'.
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 (defcustom org-keep-stored-link-after-insertion nil
1165 "Non-nil means, keep link in list for entire session.
1167 The command `org-store-link' adds a link pointing to the current
1168 location to an internal list. These links accumulate during a session.
1169 The command `org-insert-link' can be used to insert links into any
1170 Org-mode file (offering completion for all stored links). When this
1171 option is nil, every link which has been inserted once using \\[org-insert-link]
1172 will be removed from the list, to make completing the unused links
1173 more efficient."
1174 :group 'org-link-store
1175 :type 'boolean)
1177 (defcustom org-usenet-links-prefer-google nil
1178 "Non-nil means, `org-store-link' will create web links to Google groups.
1179 When nil, Gnus will be used for such links.
1180 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1181 negates this setting for the duration of the command."
1182 :group 'org-link-store
1183 :type 'boolean)
1185 (defgroup org-link-follow nil
1186 "Options concerning following links in Org-mode"
1187 :tag "Org Follow Link"
1188 :group 'org-link)
1190 (defcustom org-tab-follows-link nil
1191 "Non-nil means, on links TAB will follow the link.
1192 Needs to be set before org.el is loaded."
1193 :group 'org-link-follow
1194 :type 'boolean)
1196 (defcustom org-return-follows-link nil
1197 "Non-nil means, on links RET will follow the link.
1198 Needs to be set before org.el is loaded."
1199 :group 'org-link-follow
1200 :type 'boolean)
1202 (defcustom org-mouse-1-follows-link t
1203 "Non-nil means, mouse-1 on a link will follow the link.
1204 A longer mouse click will still set point. Does not wortk on XEmacs.
1205 Needs to be set before org.el is loaded."
1206 :group 'org-link-follow
1207 :type 'boolean)
1209 (defcustom org-mark-ring-length 4
1210 "Number of different positions to be recorded in the ring
1211 Changing this requires a restart of Emacs to work correctly."
1212 :group 'org-link-follow
1213 :type 'interger)
1215 (defcustom org-link-frame-setup
1216 '((vm . vm-visit-folder-other-frame)
1217 (gnus . gnus-other-frame)
1218 (file . find-file-other-window))
1219 "Setup the frame configuration for following links.
1220 When following a link with Emacs, it may often be useful to display
1221 this link in another window or frame. This variable can be used to
1222 set this up for the different types of links.
1223 For VM, use any of
1224 `vm-visit-folder'
1225 `vm-visit-folder-other-frame'
1226 For Gnus, use any of
1227 `gnus'
1228 `gnus-other-frame'
1229 For FILE, use any of
1230 `find-file'
1231 `find-file-other-window'
1232 `find-file-other-frame'
1233 For the calendar, use the variable `calendar-setup'.
1234 For BBDB, it is currently only possible to display the matches in
1235 another window."
1236 :group 'org-link-follow
1237 :type '(list
1238 (cons (const vm)
1239 (choice
1240 (const vm-visit-folder)
1241 (const vm-visit-folder-other-window)
1242 (const vm-visit-folder-other-frame)))
1243 (cons (const gnus)
1244 (choice
1245 (const gnus)
1246 (const gnus-other-frame)))
1247 (cons (const file)
1248 (choice
1249 (const find-file)
1250 (const find-file-other-window)
1251 (const find-file-other-frame)))))
1253 (defcustom org-display-internal-link-with-indirect-buffer nil
1254 "Non-nil means, use indirect buffer to display infile links.
1255 Activating internal links (from one location in a file to another location
1256 in the same file) normally just jumps to the location. When the link is
1257 activated with a C-u prefix (or with mouse-3), the link is displayed in
1258 another window. When this option is set, the other window actually displays
1259 an indirect buffer clone of the current buffer, to avoid any visibility
1260 changes to the current buffer."
1261 :group 'org-link-follow
1262 :type 'boolean)
1264 (defcustom org-open-non-existing-files nil
1265 "Non-nil means, `org-open-file' will open non-existing files.
1266 When nil, an error will be generated."
1267 :group 'org-link-follow
1268 :type 'boolean)
1270 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1271 "Function and arguments to call for following mailto links.
1272 This is a list with the first element being a lisp function, and the
1273 remaining elements being arguments to the function. In string arguments,
1274 %a will be replaced by the address, and %s will be replaced by the subject
1275 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1276 :group 'org-link-follow
1277 :type '(choice
1278 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1279 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1280 (const :tag "message-mail" (message-mail "%a" "%s"))
1281 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1283 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1284 "Non-nil means, ask for confirmation before executing shell links.
1285 Shell links can be dangerous: just think about a link
1287 [[shell:rm -rf ~/*][Google Search]]
1289 This link would show up in your Org-mode document as \"Google Search\",
1290 but really it would remove your entire home directory.
1291 Therefore we advise against setting this variable to nil.
1292 Just change it to `y-or-n-p' of you want to confirm with a
1293 single keystroke rather than having to type \"yes\"."
1294 :group 'org-link-follow
1295 :type '(choice
1296 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1297 (const :tag "with y-or-n (faster)" y-or-n-p)
1298 (const :tag "no confirmation (dangerous)" nil)))
1300 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1301 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1302 Elisp links can be dangerous: just think about a link
1304 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1306 This link would show up in your Org-mode document as \"Google Search\",
1307 but really it would remove your entire home directory.
1308 Therefore we advise against setting this variable to nil.
1309 Just change it to `y-or-n-p' of you want to confirm with a
1310 single keystroke rather than having to type \"yes\"."
1311 :group 'org-link-follow
1312 :type '(choice
1313 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1314 (const :tag "with y-or-n (faster)" y-or-n-p)
1315 (const :tag "no confirmation (dangerous)" nil)))
1317 (defconst org-file-apps-defaults-gnu
1318 '((remote . emacs)
1319 (t . mailcap))
1320 "Default file applications on a UNIX or GNU/Linux system.
1321 See `org-file-apps'.")
1323 (defconst org-file-apps-defaults-macosx
1324 '((remote . emacs)
1325 (t . "open %s")
1326 ("ps" . "gv %s")
1327 ("ps.gz" . "gv %s")
1328 ("eps" . "gv %s")
1329 ("eps.gz" . "gv %s")
1330 ("dvi" . "xdvi %s")
1331 ("fig" . "xfig %s"))
1332 "Default file applications on a MacOS X system.
1333 The system \"open\" is known as a default, but we use X11 applications
1334 for some files for which the OS does not have a good default.
1335 See `org-file-apps'.")
1337 (defconst org-file-apps-defaults-windowsnt
1338 (list
1339 '(remote . emacs)
1340 (cons t
1341 (list (if (featurep 'xemacs)
1342 'mswindows-shell-execute
1343 'w32-shell-execute)
1344 "open" 'file)))
1345 "Default file applications on a Windows NT system.
1346 The system \"open\" is used for most files.
1347 See `org-file-apps'.")
1349 (defcustom org-file-apps
1351 ("txt" . emacs)
1352 ("tex" . emacs)
1353 ("ltx" . emacs)
1354 ("org" . emacs)
1355 ("el" . emacs)
1356 ("bib" . emacs)
1358 "External applications for opening `file:path' items in a document.
1359 Org-mode uses system defaults for different file types, but
1360 you can use this variable to set the application for a given file
1361 extension. The entries in this list are cons cells where the car identifies
1362 files and the cdr the corresponding command. Possible values for the
1363 file identifier are
1364 \"ext\" A string identifying an extension
1365 `directory' Matches a directory
1366 `remote' Matches a remote file, accessible through tramp or efs.
1367 Remote files most likely should be visited through Emacs
1368 because external applications cannot handle such paths.
1369 t Default for all remaining files
1371 Possible values for the command are:
1372 `emacs' The file will be visited by the current Emacs process.
1373 `default' Use the default application for this file type.
1374 string A command to be executed by a shell; %s will be replaced
1375 by the path to the file.
1376 sexp A Lisp form which will be evaluated. The file path will
1377 be available in the Lisp variable `file'.
1378 For more examples, see the system specific constants
1379 `org-file-apps-defaults-macosx'
1380 `org-file-apps-defaults-windowsnt'
1381 `org-file-apps-defaults-gnu'."
1382 :group 'org-link-follow
1383 :type '(repeat
1384 (cons (choice :value ""
1385 (string :tag "Extension")
1386 (const :tag "Default for unrecognized files" t)
1387 (const :tag "Remote file" remote)
1388 (const :tag "Links to a directory" directory))
1389 (choice :value ""
1390 (const :tag "Visit with Emacs" emacs)
1391 (const :tag "Use system default" default)
1392 (string :tag "Command")
1393 (sexp :tag "Lisp form")))))
1395 (defcustom org-mhe-search-all-folders nil
1396 "Non-nil means, that the search for the mh-message will be extended to
1397 all folders if the message cannot be found in the folder given in the link.
1398 Searching all folders is very efficient with one of the search engines
1399 supported by MH-E, but will be slow with pick."
1400 :group 'org-link-follow
1401 :type 'boolean)
1403 (defgroup org-remember nil
1404 "Options concerning interaction with remember.el."
1405 :tag "Org Remember"
1406 :group 'org)
1408 (defcustom org-directory "~/org"
1409 "Directory with org files.
1410 This directory will be used as default to prompt for org files.
1411 Used by the hooks for remember.el."
1412 :group 'org-remember
1413 :type 'directory)
1415 (defcustom org-default-notes-file "~/.notes"
1416 "Default target for storing notes.
1417 Used by the hooks for remember.el. This can be a string, or nil to mean
1418 the value of `remember-data-file'.
1419 You can set this on a per-template basis with the variable
1420 `org-remember-templates'."
1421 :group 'org-remember
1422 :type '(choice
1423 (const :tag "Default from remember-data-file" nil)
1424 file))
1426 (defcustom org-remember-store-without-prompt t
1427 "Non-nil means, `C-c C-c' stores remember note without further promts.
1428 In this case, you need `C-u C-c C-c' to get the prompts for
1429 note file and headline.
1430 When this variable is nil, `C-c C-c' give you the prompts, and
1431 `C-u C-c C-c' trigger the fasttrack."
1432 :group 'org-remember
1433 :type 'boolean)
1435 (defcustom org-remember-interactive-interface 'refile
1436 "The interface to be used for interactive filing of remember notes.
1437 This is only used when the interactive mode for selecting a filing
1438 location is used (see the variable `org-remember-store-without-prompt').
1439 Allowed vaues are:
1440 outline The interface shows an outline of the relevant file
1441 and the correct heading is found by moving through
1442 the outline or by searching with incremental search.
1443 outline-path-completion Headlines in the current buffer are offered via
1444 completion.
1445 refile Use the refile interface, and offer headlines,
1446 possibly from different buffers."
1447 :group 'org-remember
1448 :type '(choice
1449 (const :tag "Refile" refile)
1450 (const :tag "Outline" outline)
1451 (const :tag "Outline-path-completion" outline-path-completion)))
1453 (defcustom org-goto-interface 'outline
1454 "The default interface to be used for `org-goto'.
1455 Allowed vaues are:
1456 outline The interface shows an outline of the relevant file
1457 and the correct heading is found by moving through
1458 the outline or by searching with incremental search.
1459 outline-path-completion Headlines in the current buffer are offered via
1460 completion."
1461 :group 'org-remember ; FIXME: different group for org-goto and org-refile
1462 :type '(choice
1463 (const :tag "Outline" outline)
1464 (const :tag "Outline-path-completion" outline-path-completion)))
1466 (defcustom org-remember-default-headline ""
1467 "The headline that should be the default location in the notes file.
1468 When filing remember notes, the cursor will start at that position.
1469 You can set this on a per-template basis with the variable
1470 `org-remember-templates'."
1471 :group 'org-remember
1472 :type 'string)
1474 (defcustom org-remember-templates nil
1475 "Templates for the creation of remember buffers.
1476 When nil, just let remember make the buffer.
1477 When not nil, this is a list of 5-element lists. In each entry, the first
1478 element is the name of the template, which should be a single short word.
1479 The second element is a character, a unique key to select this template.
1480 The third element is the template. The fourth element is optional and can
1481 specify a destination file for remember items created with this template.
1482 The default file is given by `org-default-notes-file'. An optional fifth
1483 element can specify the headline in that file that should be offered
1484 first when the user is asked to file the entry. The default headline is
1485 given in the variable `org-remember-default-headline'.
1487 The template specifies the structure of the remember buffer. It should have
1488 a first line starting with a star, to act as the org-mode headline.
1489 Furthermore, the following %-escapes will be replaced with content:
1491 %^{prompt} Prompt the user for a string and replace this sequence with it.
1492 A default value and a completion table ca be specified like this:
1493 %^{prompt|default|completion2|completion3|...}
1494 %t time stamp, date only
1495 %T time stamp with date and time
1496 %u, %U like the above, but inactive time stamps
1497 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1498 You may define a prompt like %^{Please specify birthday}t
1499 %n user name (taken from `user-full-name')
1500 %a annotation, normally the link created with org-store-link
1501 %i initial content, the region when remember is called with C-u.
1502 If %i is indented, the entire inserted text will be indented
1503 as well.
1504 %c content of the clipboard, or current kill ring head
1505 %^g prompt for tags, with completion on tags in target file
1506 %^G prompt for tags, with completion all tags in all agenda files
1507 %:keyword specific information for certain link types, see below
1508 %[pathname] insert the contents of the file given by `pathname'
1509 %(sexp) evaluate elisp `(sexp)' and replace with the result
1510 %! Store this note immediately after filling the template
1512 %? After completing the template, position cursor here.
1514 Apart from these general escapes, you can access information specific to the
1515 link type that is created. For example, calling `remember' in emails or gnus
1516 will record the author and the subject of the message, which you can access
1517 with %:author and %:subject, respectively. Here is a complete list of what
1518 is recorded for each link type.
1520 Link type | Available information
1521 -------------------+------------------------------------------------------
1522 bbdb | %:type %:name %:company
1523 vm, wl, mh, rmail | %:type %:subject %:message-id
1524 | %:from %:fromname %:fromaddress
1525 | %:to %:toname %:toaddress
1526 | %:fromto (either \"to NAME\" or \"from NAME\")
1527 gnus | %:group, for messages also all email fields
1528 w3, w3m | %:type %:url
1529 info | %:type %:file %:node
1530 calendar | %:type %:date"
1531 :group 'org-remember
1532 :get (lambda (var) ; Make sure all entries have 5 elements
1533 (mapcar (lambda (x)
1534 (if (not (stringp (car x))) (setq x (cons "" x)))
1535 (cond ((= (length x) 4) (append x '("")))
1536 ((= (length x) 3) (append x '("" "")))
1537 (t x)))
1538 (default-value var)))
1539 :type '(repeat
1540 :tag "enabled"
1541 (list :value ("" ?a "\n" nil nil)
1542 (string :tag "Name")
1543 (character :tag "Selection Key")
1544 (string :tag "Template")
1545 (choice
1546 (file :tag "Destination file")
1547 (const :tag "Prompt for file" nil))
1548 (choice
1549 (string :tag "Destination headline")
1550 (const :tag "Selection interface for heading")))))
1552 (defcustom org-reverse-note-order nil
1553 "Non-nil means, store new notes at the beginning of a file or entry.
1554 When nil, new notes will be filed to the end of a file or entry.
1555 This can also be a list with cons cells of regular expressions that
1556 are matched against file names, and values."
1557 :group 'org-remember
1558 :type '(choice
1559 (const :tag "Reverse always" t)
1560 (const :tag "Reverse never" nil)
1561 (repeat :tag "By file name regexp"
1562 (cons regexp boolean))))
1564 (defcustom org-refile-targets nil
1565 "Targets for refiling entries with \\[org-refile].
1566 This is list of cons cells. Each cell contains:
1567 - a specification of the files to be considered, either a list of files,
1568 or a symbol whose function or value fields will be used to retrieve
1569 a file name or a list of file names. Nil means, refile to a different
1570 heading in the current buffer.
1571 - A specification of how to find candidate refile targets. This may be
1572 any of
1573 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1574 This tag has to be present in all target headlines, inheritance will
1575 not be considered.
1576 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1577 todo keyword.
1578 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1579 headlines that are refiling targets.
1580 - a cons cell (:level . N). Any headline of level N is considered a target.
1581 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1582 ;; FIXME: what if there are a var and func with same name???
1583 :group 'org-remember
1584 :type '(repeat
1585 (cons
1586 (choice :value org-agenda-files
1587 (const :tag "All agenda files" org-agenda-files)
1588 (const :tag "Current buffer" nil)
1589 (function) (variable) (file))
1590 (choice :tag "Identify target headline by"
1591 (cons :tag "Specific tag" (const :tag) (string))
1592 (cons :tag "TODO keyword" (const :todo) (string))
1593 (cons :tag "Regular expression" (const :regexp) (regexp))
1594 (cons :tag "Level number" (const :level) (integer))
1595 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1597 (defcustom org-refile-use-outline-path nil
1598 "Non-nil means, provide refile targets as paths.
1599 So a level 3 headline will be available as level1/level2/level3.
1600 When the value is `file', also include the file name (without directory)
1601 into the path. When `full-file-path', include the full file path."
1602 :group 'org-remember
1603 :type '(choice
1604 (const :tag "Not" nil)
1605 (const :tag "Yes" t)
1606 (const :tag "Start with file name" file)
1607 (const :tag "Start with full file path" full-file-path)))
1609 (defgroup org-todo nil
1610 "Options concerning TODO items in Org-mode."
1611 :tag "Org TODO"
1612 :group 'org)
1614 (defgroup org-progress nil
1615 "Options concerning Progress logging in Org-mode."
1616 :tag "Org Progress"
1617 :group 'org-time)
1619 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1620 "List of TODO entry keyword sequences and their interpretation.
1621 \\<org-mode-map>This is a list of sequences.
1623 Each sequence starts with a symbol, either `sequence' or `type',
1624 indicating if the keywords should be interpreted as a sequence of
1625 action steps, or as different types of TODO items. The first
1626 keywords are states requiring action - these states will select a headline
1627 for inclusion into the global TODO list Org-mode produces. If one of
1628 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1629 signify that no further action is necessary. If \"|\" is not found,
1630 the last keyword is treated as the only DONE state of the sequence.
1632 The command \\[org-todo] cycles an entry through these states, and one
1633 additional state where no keyword is present. For details about this
1634 cycling, see the manual.
1636 TODO keywords and interpretation can also be set on a per-file basis with
1637 the special #+SEQ_TODO and #+TYP_TODO lines.
1639 For backward compatibility, this variable may also be just a list
1640 of keywords - in this case the interptetation (sequence or type) will be
1641 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1642 :group 'org-todo
1643 :group 'org-keywords
1644 :type '(choice
1645 (repeat :tag "Old syntax, just keywords"
1646 (string :tag "Keyword"))
1647 (repeat :tag "New syntax"
1648 (cons
1649 (choice
1650 :tag "Interpretation"
1651 (const :tag "Sequence (cycling hits every state)" sequence)
1652 (const :tag "Type (cycling directly to DONE)" type))
1653 (repeat
1654 (string :tag "Keyword"))))))
1656 (defvar org-todo-keywords-1 nil)
1657 (make-variable-buffer-local 'org-todo-keywords-1)
1658 (defvar org-todo-keywords-for-agenda nil)
1659 (defvar org-done-keywords-for-agenda nil)
1660 (defvar org-not-done-keywords nil)
1661 (make-variable-buffer-local 'org-not-done-keywords)
1662 (defvar org-done-keywords nil)
1663 (make-variable-buffer-local 'org-done-keywords)
1664 (defvar org-todo-heads nil)
1665 (make-variable-buffer-local 'org-todo-heads)
1666 (defvar org-todo-sets nil)
1667 (make-variable-buffer-local 'org-todo-sets)
1668 (defvar org-todo-log-states nil)
1669 (make-variable-buffer-local 'org-todo-log-states)
1670 (defvar org-todo-kwd-alist nil)
1671 (make-variable-buffer-local 'org-todo-kwd-alist)
1672 (defvar org-todo-key-alist nil)
1673 (make-variable-buffer-local 'org-todo-key-alist)
1674 (defvar org-todo-key-trigger nil)
1675 (make-variable-buffer-local 'org-todo-key-trigger)
1677 (defcustom org-todo-interpretation 'sequence
1678 "Controls how TODO keywords are interpreted.
1679 This variable is in principle obsolete and is only used for
1680 backward compatibility, if the interpretation of todo keywords is
1681 not given already in `org-todo-keywords'. See that variable for
1682 more information."
1683 :group 'org-todo
1684 :group 'org-keywords
1685 :type '(choice (const sequence)
1686 (const type)))
1688 (defcustom org-use-fast-todo-selection 'prefix
1689 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1690 This variable describes if and under what circumstances the cycling
1691 mechanism for TODO keywords will be replaced by a single-key, direct
1692 selection scheme.
1694 When nil, fast selection is never used.
1696 When the symbol `prefix', it will be used when `org-todo' is called with
1697 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1698 in an agenda buffer.
1700 When t, fast selection is used by default. In this case, the prefix
1701 argument forces cycling instead.
1703 In all cases, the special interface is only used if access keys have actually
1704 been assigned by the user, i.e. if keywords in the configuration are followed
1705 by a letter in parenthesis, like TODO(t)."
1706 :group 'org-todo
1707 :type '(choice
1708 (const :tag "Never" nil)
1709 (const :tag "By default" t)
1710 (const :tag "Only with C-u C-c C-t" prefix)))
1712 (defcustom org-after-todo-state-change-hook nil
1713 "Hook which is run after the state of a TODO item was changed.
1714 The new state (a string with a TODO keyword, or nil) is available in the
1715 Lisp variable `state'."
1716 :group 'org-todo
1717 :type 'hook)
1719 (defcustom org-log-done nil
1720 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1721 When the state of an entry is changed from nothing or a DONE state to
1722 a not-done TODO state, remove a previous closing date.
1724 This can also be a list of symbols indicating under which conditions
1725 the time stamp recording the action should be annotated with a short note.
1726 Valid members of this list are
1728 done Offer to record a note when marking entries done
1729 state Offer to record a note whenever changing the TODO state
1730 of an item. This is only relevant if TODO keywords are
1731 interpreted as sequence, see variable `org-todo-interpretation'.
1732 When `state' is set, this includes tracking `done'.
1733 clock-out Offer to record a note when clocking out of an item.
1735 A separate window will then pop up and allow you to type a note.
1736 After finishing with C-c C-c, the note will be added directly after the
1737 timestamp, as a plain list item. See also the variable
1738 `org-log-note-headings'.
1740 Logging can also be configured on a per-file basis by adding one of
1741 the following lines anywhere in the buffer:
1743 #+STARTUP: logdone
1744 #+STARTUP: nologging
1745 #+STARTUP: lognotedone
1746 #+STARTUP: lognotestate
1747 #+STARTUP: lognoteclock-out
1749 You can have local logging settings for a subtree by setting the LOGGING
1750 property to one or more of these keywords."
1751 :group 'org-todo
1752 :group 'org-progress
1753 :type '(choice
1754 (const :tag "off" nil)
1755 (const :tag "on" t)
1756 (set :tag "on, with notes, detailed control" :greedy t :value (done)
1757 (const :tag "when item is marked DONE" done)
1758 (const :tag "when TODO state changes" state)
1759 (const :tag "when clocking out" clock-out))))
1761 (defcustom org-log-done-with-time t
1762 "Non-nil means, the CLOSED time stamp will contain date and time.
1763 When nil, only the date will be recorded."
1764 :group 'org-progress
1765 :type 'boolean)
1767 (defcustom org-log-note-headings
1768 '((done . "CLOSING NOTE %t")
1769 (state . "State %-12s %t")
1770 (clock-out . ""))
1771 "Headings for notes added when clocking out or closing TODO items.
1772 The value is an alist, with the car being a symbol indicating the note
1773 context, and the cdr is the heading to be used. The heading may also be the
1774 empty string.
1775 %t in the heading will be replaced by a time stamp.
1776 %s will be replaced by the new TODO state, in double quotes.
1777 %u will be replaced by the user name.
1778 %U will be replaced by the full user name."
1779 :group 'org-todo
1780 :group 'org-progress
1781 :type '(list :greedy t
1782 (cons (const :tag "Heading when closing an item" done) string)
1783 (cons (const :tag
1784 "Heading when changing todo state (todo sequence only)"
1785 state) string)
1786 (cons (const :tag "Heading when clocking out" clock-out) string)))
1788 (defcustom org-log-states-order-reversed t
1789 "Non-nil means, the latest state change note will be directly after heading.
1790 When nil, the notes will be orderer according to time."
1791 :group 'org-todo
1792 :group 'org-progress
1793 :type 'boolean)
1795 (defcustom org-log-repeat t
1796 "Non-nil means, prompt for a note when REPEAT is resetting a TODO entry.
1797 When nil, no note will be taken.
1798 This option can also be set with on a per-file-basis with
1800 #+STARTUP: logrepeat
1801 #+STARTUP: nologrepeat
1803 You can have local logging settings for a subtree by setting the LOGGING
1804 property to one or more of these keywords."
1805 :group 'org-todo
1806 :group 'org-progress
1807 :type 'boolean)
1809 (defcustom org-clock-into-drawer 2
1810 "Should clocking info be wrapped into a drawer?
1811 When t, clocking info will always be inserted into a :CLOCK: drawer.
1812 If necessary, the drawer will be created.
1813 When nil, the drawer will not be created, but used when present.
1814 When an integer and the number of clocking entries in an item
1815 reaches or exceeds this number, a drawer will be created."
1816 :group 'org-todo
1817 :group 'org-progress
1818 :type '(choice
1819 (const :tag "Always" t)
1820 (const :tag "Only when drawer exists" nil)
1821 (integer :tag "When at least N clock entries")))
1823 (defcustom org-clock-out-when-done t
1824 "When t, the clock will be stopped when the relevant entry is marked DONE.
1825 Nil means, clock will keep running until stopped explicitly with
1826 `C-c C-x C-o', or until the clock is started in a different item."
1827 :group 'org-progress
1828 :type 'boolean)
1830 (defcustom org-clock-in-switch-to-state nil
1831 "Set task to a special todo state while clocking it.
1832 The value should be the state to which the entry should be switched."
1833 :group 'org-progress
1834 :group 'org-todo
1835 :type '(choice
1836 (const :tag "Don't force a state" nil)
1837 (string :tag "State")))
1839 (defgroup org-priorities nil
1840 "Priorities in Org-mode."
1841 :tag "Org Priorities"
1842 :group 'org-todo)
1844 (defcustom org-highest-priority ?A
1845 "The highest priority of TODO items. A character like ?A, ?B etc.
1846 Must have a smaller ASCII number than `org-lowest-priority'."
1847 :group 'org-priorities
1848 :type 'character)
1850 (defcustom org-lowest-priority ?C
1851 "The lowest priority of TODO items. A character like ?A, ?B etc.
1852 Must have a larger ASCII number than `org-highest-priority'."
1853 :group 'org-priorities
1854 :type 'character)
1856 (defcustom org-default-priority ?B
1857 "The default priority of TODO items.
1858 This is the priority an item get if no explicit priority is given."
1859 :group 'org-priorities
1860 :type 'character)
1862 (defcustom org-priority-start-cycle-with-default t
1863 "Non-nil means, start with default priority when starting to cycle.
1864 When this is nil, the first step in the cycle will be (depending on the
1865 command used) one higher or lower that the default priority."
1866 :group 'org-priorities
1867 :type 'boolean)
1869 (defgroup org-time nil
1870 "Options concerning time stamps and deadlines in Org-mode."
1871 :tag "Org Time"
1872 :group 'org)
1874 (defcustom org-insert-labeled-timestamps-at-point nil
1875 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1876 When nil, these labeled time stamps are forces into the second line of an
1877 entry, just after the headline. When scheduling from the global TODO list,
1878 the time stamp will always be forced into the second line."
1879 :group 'org-time
1880 :type 'boolean)
1882 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1883 "Formats for `format-time-string' which are used for time stamps.
1884 It is not recommended to change this constant.")
1886 (defcustom org-time-stamp-rounding-minutes 0
1887 "Number of minutes to round time stamps to upon insertion.
1888 When zero, insert the time unmodified. Useful rounding numbers
1889 should be factors of 60, so for example 5, 10, 15.
1890 When this is not zero, you can still force an exact time-stamp by using
1891 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1892 :group 'org-time
1893 :type 'integer)
1895 (defcustom org-display-custom-times nil
1896 "Non-nil means, overlay custom formats over all time stamps.
1897 The formats are defined through the variable `org-time-stamp-custom-formats'.
1898 To turn this on on a per-file basis, insert anywhere in the file:
1899 #+STARTUP: customtime"
1900 :group 'org-time
1901 :set 'set-default
1902 :type 'sexp)
1903 (make-variable-buffer-local 'org-display-custom-times)
1905 (defcustom org-time-stamp-custom-formats
1906 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1907 "Custom formats for time stamps. See `format-time-string' for the syntax.
1908 These are overlayed over the default ISO format if the variable
1909 `org-display-custom-times' is set. Time like %H:%M should be at the
1910 end of the second format."
1911 :group 'org-time
1912 :type 'sexp)
1914 (defun org-time-stamp-format (&optional long inactive)
1915 "Get the right format for a time string."
1916 (let ((f (if long (cdr org-time-stamp-formats)
1917 (car org-time-stamp-formats))))
1918 (if inactive
1919 (concat "[" (substring f 1 -1) "]")
1920 f)))
1922 (defcustom org-read-date-prefer-future t
1923 "Non-nil means, assume future for incomplete date input from user.
1924 This affects the following situations:
1925 1. The user gives a day, but no month.
1926 For example, if today is the 15th, and you enter \"3\", Org-mode will
1927 read this as the third of *next* month. However, if you enter \"17\",
1928 it will be considered as *this* month.
1929 2. The user gives a month but not a year.
1930 For example, if it is april and you enter \"feb 2\", this will be read
1931 as feb 2, *next* year. \"May 5\", however, will be this year.
1933 When this option is nil, the current month and year will always be used
1934 as defaults."
1935 :group 'org-time
1936 :type 'boolean)
1938 (defcustom org-read-date-display-live t
1939 "Non-nil means, display current interpretation of date prompt live.
1940 This display will be in an overlay, in the minibuffer."
1941 :group 'org-time
1942 :type 'boolean)
1944 (defcustom org-read-date-popup-calendar t
1945 "Non-nil means, pop up a calendar when prompting for a date.
1946 In the calendar, the date can be selected with mouse-1. However, the
1947 minibuffer will also be active, and you can simply enter the date as well.
1948 When nil, only the minibuffer will be available."
1949 :group 'org-time
1950 :type 'boolean)
1951 (if (fboundp 'defvaralias)
1952 (defvaralias 'org-popup-calendar-for-date-prompt
1953 'org-read-date-popup-calendar))
1955 (defcustom org-extend-today-until 0
1956 "The hour when your day really ends.
1957 This has influence for the following applications:
1958 - When switching the agenda to \"today\". It it is still earlier than
1959 the time given here, the day recognized as TODAY is actually yesterday.
1960 - When a date is read from the user and it is still before the time given
1961 here, the current date and time will be assumed to be yesterday, 23:59.
1963 FIXME:
1964 IMPORTANT: This is still a very experimental feature, it may disappear
1965 again or it may be extended to mean more things."
1966 :group 'org-time
1967 :type 'number)
1969 (defcustom org-edit-timestamp-down-means-later nil
1970 "Non-nil means, S-down will increase the time in a time stamp.
1971 When nil, S-up will increase."
1972 :group 'org-time
1973 :type 'boolean)
1975 (defcustom org-calendar-follow-timestamp-change t
1976 "Non-nil means, make the calendar window follow timestamp changes.
1977 When a timestamp is modified and the calendar window is visible, it will be
1978 moved to the new date."
1979 :group 'org-time
1980 :type 'boolean)
1982 (defcustom org-clock-heading-function nil
1983 "When non-nil, should be a function to create `org-clock-heading'.
1984 This is the string shown in the mode line when a clock is running.
1985 The function is called with point at the beginning of the headline."
1986 :group 'org-time ; FIXME: Should we have a separate group????
1987 :type 'function)
1989 (defgroup org-tags nil
1990 "Options concerning tags in Org-mode."
1991 :tag "Org Tags"
1992 :group 'org)
1994 (defcustom org-tag-alist nil
1995 "List of tags allowed in Org-mode files.
1996 When this list is nil, Org-mode will base TAG input on what is already in the
1997 buffer.
1998 The value of this variable is an alist, the car of each entry must be a
1999 keyword as a string, the cdr may be a character that is used to select
2000 that tag through the fast-tag-selection interface.
2001 See the manual for details."
2002 :group 'org-tags
2003 :type '(repeat
2004 (choice
2005 (cons (string :tag "Tag name")
2006 (character :tag "Access char"))
2007 (const :tag "Start radio group" (:startgroup))
2008 (const :tag "End radio group" (:endgroup)))))
2010 (defcustom org-use-fast-tag-selection 'auto
2011 "Non-nil means, use fast tag selection scheme.
2012 This is a special interface to select and deselect tags with single keys.
2013 When nil, fast selection is never used.
2014 When the symbol `auto', fast selection is used if and only if selection
2015 characters for tags have been configured, either through the variable
2016 `org-tag-alist' or through a #+TAGS line in the buffer.
2017 When t, fast selection is always used and selection keys are assigned
2018 automatically if necessary."
2019 :group 'org-tags
2020 :type '(choice
2021 (const :tag "Always" t)
2022 (const :tag "Never" nil)
2023 (const :tag "When selection characters are configured" 'auto)))
2025 (defcustom org-fast-tag-selection-single-key nil
2026 "Non-nil means, fast tag selection exits after first change.
2027 When nil, you have to press RET to exit it.
2028 During fast tag selection, you can toggle this flag with `C-c'.
2029 This variable can also have the value `expert'. In this case, the window
2030 displaying the tags menu is not even shown, until you press C-c again."
2031 :group 'org-tags
2032 :type '(choice
2033 (const :tag "No" nil)
2034 (const :tag "Yes" t)
2035 (const :tag "Expert" expert)))
2037 (defvar org-fast-tag-selection-include-todo nil
2038 "Non-nil means, fast tags selection interface will also offer TODO states.
2039 This is an undocumented feature, you should not rely on it.")
2041 (defcustom org-tags-column -80
2042 "The column to which tags should be indented in a headline.
2043 If this number is positive, it specifies the column. If it is negative,
2044 it means that the tags should be flushright to that column. For example,
2045 -80 works well for a normal 80 character screen."
2046 :group 'org-tags
2047 :type 'integer)
2049 (defcustom org-auto-align-tags t
2050 "Non-nil means, realign tags after pro/demotion of TODO state change.
2051 These operations change the length of a headline and therefore shift
2052 the tags around. With this options turned on, after each such operation
2053 the tags are again aligned to `org-tags-column'."
2054 :group 'org-tags
2055 :type 'boolean)
2057 (defcustom org-use-tag-inheritance t
2058 "Non-nil means, tags in levels apply also for sublevels.
2059 When nil, only the tags directly given in a specific line apply there.
2060 If you turn off this option, you very likely want to turn on the
2061 companion option `org-tags-match-list-sublevels'."
2062 :group 'org-tags
2063 :type 'boolean)
2065 (defcustom org-tags-match-list-sublevels nil
2066 "Non-nil means list also sublevels of headlines matching tag search.
2067 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2068 the sublevels of a headline matching a tag search often also match
2069 the same search. Listing all of them can create very long lists.
2070 Setting this variable to nil causes subtrees of a match to be skipped.
2071 This option is off by default, because inheritance in on. If you turn
2072 inheritance off, you very likely want to turn this option on.
2074 As a special case, if the tag search is restricted to TODO items, the
2075 value of this variable is ignored and sublevels are always checked, to
2076 make sure all corresponding TODO items find their way into the list."
2077 :group 'org-tags
2078 :type 'boolean)
2080 (defvar org-tags-history nil
2081 "History of minibuffer reads for tags.")
2082 (defvar org-last-tags-completion-table nil
2083 "The last used completion table for tags.")
2084 (defvar org-after-tags-change-hook nil
2085 "Hook that is run after the tags in a line have changed.")
2087 (defgroup org-properties nil
2088 "Options concerning properties in Org-mode."
2089 :tag "Org Properties"
2090 :group 'org)
2092 (defcustom org-property-format "%-10s %s"
2093 "How property key/value pairs should be formatted by `indent-line'.
2094 When `indent-line' hits a property definition, it will format the line
2095 according to this format, mainly to make sure that the values are
2096 lined-up with respect to each other."
2097 :group 'org-properties
2098 :type 'string)
2100 (defcustom org-use-property-inheritance nil
2101 "Non-nil means, properties apply also for sublevels.
2102 This setting is only relevant during property searches, not when querying
2103 an entry with `org-entry-get'. To retrieve a property with inheritance,
2104 you need to call `org-entry-get' with the inheritance flag.
2105 Turning this on can cause significant overhead when doing a search, so
2106 this is turned off by default.
2107 When nil, only the properties directly given in the current entry count.
2108 The value may also be a list of properties that shouldhave inheritance.
2110 However, note that some special properties use inheritance under special
2111 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2112 and the properties ending in \"_ALL\" when they are used as descriptor
2113 for valid values of a property."
2114 :group 'org-properties
2115 :type '(choice
2116 (const :tag "Not" nil)
2117 (const :tag "Always" nil)
2118 (repeat :tag "Specific properties" (string :tag "Property"))))
2120 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2121 "The default column format, if no other format has been defined.
2122 This variable can be set on the per-file basis by inserting a line
2124 #+COLUMNS: %25ITEM ....."
2125 :group 'org-properties
2126 :type 'string)
2128 (defcustom org-global-properties nil
2129 "List of property/value pairs that can be inherited by any entry.
2130 You can set buffer-local values for this by adding lines like
2132 #+PROPERTY: NAME VALUE"
2133 :group 'org-properties
2134 :type '(repeat
2135 (cons (string :tag "Property")
2136 (string :tag "Value"))))
2138 (defvar org-local-properties nil
2139 "List of property/value pairs that can be inherited by any entry.
2140 Valid for the current buffer.
2141 This variable is populated from #+PROPERTY lines.")
2143 (defgroup org-agenda nil
2144 "Options concerning agenda views in Org-mode."
2145 :tag "Org Agenda"
2146 :group 'org)
2148 (defvar org-category nil
2149 "Variable used by org files to set a category for agenda display.
2150 Such files should use a file variable to set it, for example
2152 # -*- mode: org; org-category: \"ELisp\"
2154 or contain a special line
2156 #+CATEGORY: ELisp
2158 If the file does not specify a category, then file's base name
2159 is used instead.")
2160 (make-variable-buffer-local 'org-category)
2162 (defcustom org-agenda-files nil
2163 "The files to be used for agenda display.
2164 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2165 \\[org-remove-file]. You can also use customize to edit the list.
2167 If an entry is a directory, all files in that directory that are matched by
2168 `org-agenda-file-regexp' will be part of the file list.
2170 If the value of the variable is not a list but a single file name, then
2171 the list of agenda files is actually stored and maintained in that file, one
2172 agenda file per line."
2173 :group 'org-agenda
2174 :type '(choice
2175 (repeat :tag "List of files and directories" file)
2176 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2178 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2179 "Regular expression to match files for `org-agenda-files'.
2180 If any element in the list in that variable contains a directory instead
2181 of a normal file, all files in that directory that are matched by this
2182 regular expression will be included."
2183 :group 'org-agenda
2184 :type 'regexp)
2186 (defcustom org-agenda-skip-unavailable-files nil
2187 "t means to just skip non-reachable files in `org-agenda-files'.
2188 Nil means to remove them, after a query, from the list."
2189 :group 'org-agenda
2190 :type 'boolean)
2192 (defcustom org-agenda-multi-occur-extra-files nil
2193 "List of extra files to be searched by `org-occur-in-agenda-files'.
2194 The files in `org-agenda-files' are always searched."
2195 :group 'org-agenda
2196 :type '(repeat file))
2198 (defcustom org-agenda-confirm-kill 1
2199 "When set, remote killing from the agenda buffer needs confirmation.
2200 When t, a confirmation is always needed. When a number N, confirmation is
2201 only needed when the text to be killed contains more than N non-white lines."
2202 :group 'org-agenda
2203 :type '(choice
2204 (const :tag "Never" nil)
2205 (const :tag "Always" t)
2206 (number :tag "When more than N lines")))
2208 (defcustom org-calendar-to-agenda-key [?c]
2209 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2210 The command `org-calendar-goto-agenda' will be bound to this key. The
2211 default is the character `c' because then `c' can be used to switch back and
2212 forth between agenda and calendar."
2213 :group 'org-agenda
2214 :type 'sexp)
2216 (defcustom org-agenda-compact-blocks nil
2217 "Non-nil means, make the block agenda more compact.
2218 This is done by leaving out unnecessary lines."
2219 :group 'org-agenda
2220 :type nil)
2222 (defgroup org-agenda-export nil
2223 "Options concerning exporting agenda views in Org-mode."
2224 :tag "Org Agenda Export"
2225 :group 'org-agenda)
2227 (defcustom org-agenda-with-colors t
2228 "Non-nil means, use colors in agenda views."
2229 :group 'org-agenda-export
2230 :type 'boolean)
2232 (defcustom org-agenda-exporter-settings nil
2233 "Alist of variable/value pairs that should be active during agenda export.
2234 This is a good place to set uptions for ps-print and for htmlize."
2235 :group 'org-agenda-export
2236 :type '(repeat
2237 (list
2238 (variable)
2239 (sexp :tag "Value"))))
2241 (defcustom org-agenda-export-html-style ""
2242 "The style specification for exported HTML Agenda files.
2243 If this variable contains a string, it will replace the default <style>
2244 section as produced by `htmlize'.
2245 Since there are different ways of setting style information, this variable
2246 needs to contain the full HTML structure to provide a style, including the
2247 surrounding HTML tags. The style specifications should include definitions
2248 the fonts used by the agenda, here is an example:
2250 <style type=\"text/css\">
2251 p { font-weight: normal; color: gray; }
2252 .org-agenda-structure {
2253 font-size: 110%;
2254 color: #003399;
2255 font-weight: 600;
2257 .org-todo {
2258 color: #cc6666;Week-agenda:
2259 font-weight: bold;
2261 .org-done {
2262 color: #339933;
2264 .title { text-align: center; }
2265 .todo, .deadline { color: red; }
2266 .done { color: green; }
2267 </style>
2269 or, if you want to keep the style in a file,
2271 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2273 As the value of this option simply gets inserted into the HTML <head> header,
2274 you can \"misuse\" it to also add other text to the header. However,
2275 <style>...</style> is required, if not present the variable will be ignored."
2276 :group 'org-agenda-export
2277 :group 'org-export-html
2278 :type 'string)
2280 (defgroup org-agenda-custom-commands nil
2281 "Options concerning agenda views in Org-mode."
2282 :tag "Org Agenda Custom Commands"
2283 :group 'org-agenda)
2285 (defcustom org-agenda-custom-commands nil
2286 "Custom commands for the agenda.
2287 These commands will be offered on the splash screen displayed by the
2288 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2290 (key desc type match options files)
2292 key The key (one or more characters as a string) to be associated
2293 with the command.
2294 desc A description of the commend, when omitted or nil, a default
2295 description is built using MATCH.
2296 type The command type, any of the following symbols:
2297 todo Entries with a specific TODO keyword, in all agenda files.
2298 tags Tags match in all agenda files.
2299 tags-todo Tags match in all agenda files, TODO entries only.
2300 todo-tree Sparse tree of specific TODO keyword in *current* file.
2301 tags-tree Sparse tree with all tags matches in *current* file.
2302 occur-tree Occur sparse tree for *current* file.
2303 ... A user-defined function.
2304 match What to search for:
2305 - a single keyword for TODO keyword searches
2306 - a tags match expression for tags searches
2307 - a regular expression for occur searches
2308 options A list of option settings, similar to that in a let form, so like
2309 this: ((opt1 val1) (opt2 val2) ...)
2310 files A list of files file to write the produced agenda buffer to
2311 with the command `org-store-agenda-views'.
2312 If a file name ends in \".html\", an HTML version of the buffer
2313 is written out. If it ends in \".ps\", a postscript version is
2314 produced. Otherwide, only the plain text is written to the file.
2316 You can also define a set of commands, to create a composite agenda buffer.
2317 In this case, an entry looks like this:
2319 (key desc (cmd1 cmd2 ...) general-options file)
2321 where
2323 desc A description string to be displayed in the dispatcher menu.
2324 cmd An agenda command, similar to the above. However, tree commands
2325 are no allowed, but instead you can get agenda and global todo list.
2326 So valid commands for a set are:
2327 (agenda)
2328 (alltodo)
2329 (stuck)
2330 (todo \"match\" options files)
2331 (tags \"match\" options files)
2332 (tags-todo \"match\" options files)
2334 Each command can carry a list of options, and another set of options can be
2335 given for the whole set of commands. Individual command options take
2336 precedence over the general options.
2338 When using several characters as key to a command, the first characters
2339 are prefix commands. For the dispatcher to display useful information, you
2340 should provide a description for the prefix, like
2342 (setq org-agenda-custom-commands
2343 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2344 (\"hl\" tags \"+HOME+Lisa\")
2345 (\"hp\" tags \"+HOME+Peter\")
2346 (\"hk\" tags \"+HOME+Kim\")))"
2347 :group 'org-agenda-custom-commands
2348 :type '(repeat
2349 (choice :value ("a" "" tags "" nil)
2350 (list :tag "Single command"
2351 (string :tag "Access Key(s) ")
2352 (option (string :tag "Description"))
2353 (choice
2354 (const :tag "Agenda" agenda)
2355 (const :tag "TODO list" alltodo)
2356 (const :tag "Stuck projects" stuck)
2357 (const :tag "Tags search (all agenda files)" tags)
2358 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2359 (const :tag "TODO keyword search (all agenda files)" todo)
2360 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2361 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2362 (const :tag "Occur tree (current buffer)" occur-tree)
2363 (sexp :tag "Other, user-defined function"))
2364 (string :tag "Match")
2365 (repeat :tag "Local options"
2366 (list (variable :tag "Option") (sexp :tag "Value")))
2367 (option (repeat :tag "Export" (file :tag "Export to"))))
2368 (list :tag "Command series, all agenda files"
2369 (string :tag "Access Key(s)")
2370 (string :tag "Description ")
2371 (repeat
2372 (choice
2373 (const :tag "Agenda" (agenda))
2374 (const :tag "TODO list" (alltodo))
2375 (const :tag "Stuck projects" (stuck))
2376 (list :tag "Tags search"
2377 (const :format "" tags)
2378 (string :tag "Match")
2379 (repeat :tag "Local options"
2380 (list (variable :tag "Option")
2381 (sexp :tag "Value"))))
2383 (list :tag "Tags search, TODO entries only"
2384 (const :format "" tags-todo)
2385 (string :tag "Match")
2386 (repeat :tag "Local options"
2387 (list (variable :tag "Option")
2388 (sexp :tag "Value"))))
2390 (list :tag "TODO keyword search"
2391 (const :format "" todo)
2392 (string :tag "Match")
2393 (repeat :tag "Local options"
2394 (list (variable :tag "Option")
2395 (sexp :tag "Value"))))
2397 (list :tag "Other, user-defined function"
2398 (symbol :tag "function")
2399 (string :tag "Match")
2400 (repeat :tag "Local options"
2401 (list (variable :tag "Option")
2402 (sexp :tag "Value"))))))
2404 (repeat :tag "General options"
2405 (list (variable :tag "Option")
2406 (sexp :tag "Value")))
2407 (option (repeat :tag "Export" (file :tag "Export to"))))
2408 (cons :tag "Prefix key documentation"
2409 (string :tag "Access Key(s)")
2410 (string :tag "Description ")))))
2412 (defcustom org-stuck-projects
2413 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2414 "How to identify stuck projects.
2415 This is a list of four items:
2416 1. A tags/todo matcher string that is used to identify a project.
2417 The entire tree below a headline matched by this is considered one project.
2418 2. A list of TODO keywords identifying non-stuck projects.
2419 If the project subtree contains any headline with one of these todo
2420 keywords, the project is considered to be not stuck. If you specify
2421 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2422 3. A list of tags identifying non-stuck projects.
2423 If the project subtree contains any headline with one of these tags,
2424 the project is considered to be not stuck. If you specify \"*\" as
2425 a tag, any tag will mark the project unstuck.
2426 4. An arbitrary regular expression matching non-stuck projects.
2428 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2429 or `C-c a #' to produce the list."
2430 :group 'org-agenda-custom-commands
2431 :type '(list
2432 (string :tag "Tags/TODO match to identify a project")
2433 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2434 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2435 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2438 (defgroup org-agenda-skip nil
2439 "Options concerning skipping parts of agenda files."
2440 :tag "Org Agenda Skip"
2441 :group 'org-agenda)
2443 (defcustom org-agenda-todo-list-sublevels t
2444 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2445 When nil, the sublevels of a TODO entry are not checked, resulting in
2446 potentially much shorter TODO lists."
2447 :group 'org-agenda-skip
2448 :group 'org-todo
2449 :type 'boolean)
2451 (defcustom org-agenda-todo-ignore-with-date nil
2452 "Non-nil means, don't show entries with a date in the global todo list.
2453 You can use this if you prefer to mark mere appointments with a TODO keyword,
2454 but don't want them to show up in the TODO list.
2455 When this is set, it also covers deadlines and scheduled items, the settings
2456 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2457 will be ignored."
2458 :group 'org-agenda-skip
2459 :group 'org-todo
2460 :type 'boolean)
2462 (defcustom org-agenda-todo-ignore-scheduled nil
2463 "Non-nil means, don't show scheduled entries in the global todo list.
2464 The idea behind this is that by scheduling it, you have already taken care
2465 of this item.
2466 See also `org-agenda-todo-ignore-with-date'."
2467 :group 'org-agenda-skip
2468 :group 'org-todo
2469 :type 'boolean)
2471 (defcustom org-agenda-todo-ignore-deadlines nil
2472 "Non-nil means, don't show near deadline entries in the global todo list.
2473 Near means closer than `org-deadline-warning-days' days.
2474 The idea behind this is that such items will appear in the agenda anyway.
2475 See also `org-agenda-todo-ignore-with-date'."
2476 :group 'org-agenda-skip
2477 :group 'org-todo
2478 :type 'boolean)
2480 (defcustom org-agenda-skip-scheduled-if-done nil
2481 "Non-nil means don't show scheduled items in agenda when they are done.
2482 This is relevant for the daily/weekly agenda, not for the TODO list. And
2483 it applies only to the actual date of the scheduling. Warnings about
2484 an item with a past scheduling dates are always turned off when the item
2485 is DONE."
2486 :group 'org-agenda-skip
2487 :type 'boolean)
2489 (defcustom org-agenda-skip-deadline-if-done nil
2490 "Non-nil means don't show deadines when the corresponding item is done.
2491 When nil, the deadline is still shown and should give you a happy feeling.
2492 This is relevant for the daily/weekly agenda. And it applied only to the
2493 actualy date of the deadline. Warnings about approching and past-due
2494 deadlines are always turned off when the item is DONE."
2495 :group 'org-agenda-skip
2496 :type 'boolean)
2498 (defcustom org-agenda-skip-timestamp-if-done nil
2499 "Non-nil means don't select item by timestamp or -range if it is DONE."
2500 :group 'org-agenda-skip
2501 :type 'boolean)
2503 (defcustom org-timeline-show-empty-dates 3
2504 "Non-nil means, `org-timeline' also shows dates without an entry.
2505 When nil, only the days which actually have entries are shown.
2506 When t, all days between the first and the last date are shown.
2507 When an integer, show also empty dates, but if there is a gap of more than
2508 N days, just insert a special line indicating the size of the gap."
2509 :group 'org-agenda-skip
2510 :type '(choice
2511 (const :tag "None" nil)
2512 (const :tag "All" t)
2513 (number :tag "at most")))
2516 (defgroup org-agenda-startup nil
2517 "Options concerning initial settings in the Agenda in Org Mode."
2518 :tag "Org Agenda Startup"
2519 :group 'org-agenda)
2521 (defcustom org-finalize-agenda-hook nil
2522 "Hook run just before displaying an agenda buffer."
2523 :group 'org-agenda-startup
2524 :type 'hook)
2526 (defcustom org-agenda-mouse-1-follows-link nil
2527 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2528 A longer mouse click will still set point. Does not wortk on XEmacs.
2529 Needs to be set before org.el is loaded."
2530 :group 'org-agenda-startup
2531 :type 'boolean)
2533 (defcustom org-agenda-start-with-follow-mode nil
2534 "The initial value of follow-mode in a newly created agenda window."
2535 :group 'org-agenda-startup
2536 :type 'boolean)
2538 (defgroup org-agenda-windows nil
2539 "Options concerning the windows used by the Agenda in Org Mode."
2540 :tag "Org Agenda Windows"
2541 :group 'org-agenda)
2543 (defcustom org-agenda-window-setup 'reorganize-frame
2544 "How the agenda buffer should be displayed.
2545 Possible values for this option are:
2547 current-window Show agenda in the current window, keeping all other windows.
2548 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2549 other-window Use `switch-to-buffer-other-window' to display agenda.
2550 reorganize-frame Show only two windows on the current frame, the current
2551 window and the agenda.
2552 See also the variable `org-agenda-restore-windows-after-quit'."
2553 :group 'org-agenda-windows
2554 :type '(choice
2555 (const current-window)
2556 (const other-frame)
2557 (const other-window)
2558 (const reorganize-frame)))
2560 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2561 "The min and max height of the agenda window as a fraction of frame height.
2562 The value of the variable is a cons cell with two numbers between 0 and 1.
2563 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2564 :group 'org-agenda-windows
2565 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2567 (defcustom org-agenda-restore-windows-after-quit nil
2568 "Non-nil means, restore window configuration open exiting agenda.
2569 Before the window configuration is changed for displaying the agenda,
2570 the current status is recorded. When the agenda is exited with
2571 `q' or `x' and this option is set, the old state is restored. If
2572 `org-agenda-window-setup' is `other-frame', the value of this
2573 option will be ignored.."
2574 :group 'org-agenda-windows
2575 :type 'boolean)
2577 (defcustom org-indirect-buffer-display 'other-window
2578 "How should indirect tree buffers be displayed?
2579 This applies to indirect buffers created with the commands
2580 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2581 Valid values are:
2582 current-window Display in the current window
2583 other-window Just display in another window.
2584 dedicated-frame Create one new frame, and re-use it each time.
2585 new-frame Make a new frame each time. Note that in this case
2586 previously-made indirect buffers are kept, and you need to
2587 kill these buffers yourself."
2588 :group 'org-structure
2589 :group 'org-agenda-windows
2590 :type '(choice
2591 (const :tag "In current window" current-window)
2592 (const :tag "In current frame, other window" other-window)
2593 (const :tag "Each time a new frame" new-frame)
2594 (const :tag "One dedicated frame" dedicated-frame)))
2596 (defgroup org-agenda-daily/weekly nil
2597 "Options concerning the daily/weekly agenda."
2598 :tag "Org Agenda Daily/Weekly"
2599 :group 'org-agenda)
2601 (defcustom org-agenda-ndays 7
2602 "Number of days to include in overview display.
2603 Should be 1 or 7."
2604 :group 'org-agenda-daily/weekly
2605 :type 'number)
2607 (defcustom org-agenda-start-on-weekday 1
2608 "Non-nil means, start the overview always on the specified weekday.
2609 0 denotes Sunday, 1 denotes Monday etc.
2610 When nil, always start on the current day."
2611 :group 'org-agenda-daily/weekly
2612 :type '(choice (const :tag "Today" nil)
2613 (number :tag "Weekday No.")))
2615 (defcustom org-agenda-show-all-dates t
2616 "Non-nil means, `org-agenda' shows every day in the selected range.
2617 When nil, only the days which actually have entries are shown."
2618 :group 'org-agenda-daily/weekly
2619 :type 'boolean)
2621 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2622 "Format string for displaying dates in the agenda.
2623 Used by the daily/weekly agenda and by the timeline. This should be
2624 a format string understood by `format-time-string', or a function returning
2625 the formatted date as a string. The function must take a single argument,
2626 a calendar-style date list like (month day year)."
2627 :group 'org-agenda-daily/weekly
2628 :type '(choice
2629 (string :tag "Format string")
2630 (function :tag "Function")))
2632 (defun org-agenda-format-date-aligned (date)
2633 "Format a date string for display in the daily/weekly agenda, or timeline.
2634 This function makes sure that dates are aligned for easy reading."
2635 (format "%-9s %2d %s %4d"
2636 (calendar-day-name date)
2637 (extract-calendar-day date)
2638 (calendar-month-name (extract-calendar-month date))
2639 (extract-calendar-year date)))
2641 (defcustom org-agenda-include-diary nil
2642 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2643 :group 'org-agenda-daily/weekly
2644 :type 'boolean)
2646 (defcustom org-agenda-include-all-todo nil
2647 "Set means weekly/daily agenda will always contain all TODO entries.
2648 The TODO entries will be listed at the top of the agenda, before
2649 the entries for specific days."
2650 :group 'org-agenda-daily/weekly
2651 :type 'boolean)
2653 (defcustom org-agenda-repeating-timestamp-show-all t
2654 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2655 When nil, only one occurence is shown, either today or the
2656 nearest into the future."
2657 :group 'org-agenda-daily/weekly
2658 :type 'boolean)
2660 (defcustom org-deadline-warning-days 14
2661 "No. of days before expiration during which a deadline becomes active.
2662 This variable governs the display in sparse trees and in the agenda.
2663 When negative, it means use this number (the absolute value of it)
2664 even if a deadline has a different individual lead time specified."
2665 :group 'org-time
2666 :group 'org-agenda-daily/weekly
2667 :type 'number)
2669 (defcustom org-scheduled-past-days 10000
2670 "No. of days to continue listing scheduled items that are not marked DONE.
2671 When an item is scheduled on a date, it shows up in the agenda on this
2672 day and will be listed until it is marked done for the number of days
2673 given here."
2674 :group 'org-agenda-daily/weekly
2675 :type 'number)
2677 (defgroup org-agenda-time-grid nil
2678 "Options concerning the time grid in the Org-mode Agenda."
2679 :tag "Org Agenda Time Grid"
2680 :group 'org-agenda)
2682 (defcustom org-agenda-use-time-grid t
2683 "Non-nil means, show a time grid in the agenda schedule.
2684 A time grid is a set of lines for specific times (like every two hours between
2685 8:00 and 20:00). The items scheduled for a day at specific times are
2686 sorted in between these lines.
2687 For details about when the grid will be shown, and what it will look like, see
2688 the variable `org-agenda-time-grid'."
2689 :group 'org-agenda-time-grid
2690 :type 'boolean)
2692 (defcustom org-agenda-time-grid
2693 '((daily today require-timed)
2694 "----------------"
2695 (800 1000 1200 1400 1600 1800 2000))
2697 "The settings for time grid for agenda display.
2698 This is a list of three items. The first item is again a list. It contains
2699 symbols specifying conditions when the grid should be displayed:
2701 daily if the agenda shows a single day
2702 weekly if the agenda shows an entire week
2703 today show grid on current date, independent of daily/weekly display
2704 require-timed show grid only if at least one item has a time specification
2706 The second item is a string which will be places behing the grid time.
2708 The third item is a list of integers, indicating the times that should have
2709 a grid line."
2710 :group 'org-agenda-time-grid
2711 :type
2712 '(list
2713 (set :greedy t :tag "Grid Display Options"
2714 (const :tag "Show grid in single day agenda display" daily)
2715 (const :tag "Show grid in weekly agenda display" weekly)
2716 (const :tag "Always show grid for today" today)
2717 (const :tag "Show grid only if any timed entries are present"
2718 require-timed)
2719 (const :tag "Skip grid times already present in an entry"
2720 remove-match))
2721 (string :tag "Grid String")
2722 (repeat :tag "Grid Times" (integer :tag "Time"))))
2724 (defgroup org-agenda-sorting nil
2725 "Options concerning sorting in the Org-mode Agenda."
2726 :tag "Org Agenda Sorting"
2727 :group 'org-agenda)
2729 (defconst org-sorting-choice
2730 '(choice
2731 (const time-up) (const time-down)
2732 (const category-keep) (const category-up) (const category-down)
2733 (const tag-down) (const tag-up)
2734 (const priority-up) (const priority-down))
2735 "Sorting choices.")
2737 (defcustom org-agenda-sorting-strategy
2738 '((agenda time-up category-keep priority-down)
2739 (todo category-keep priority-down)
2740 (tags category-keep priority-down))
2741 "Sorting structure for the agenda items of a single day.
2742 This is a list of symbols which will be used in sequence to determine
2743 if an entry should be listed before another entry. The following
2744 symbols are recognized:
2746 time-up Put entries with time-of-day indications first, early first
2747 time-down Put entries with time-of-day indications first, late first
2748 category-keep Keep the default order of categories, corresponding to the
2749 sequence in `org-agenda-files'.
2750 category-up Sort alphabetically by category, A-Z.
2751 category-down Sort alphabetically by category, Z-A.
2752 tag-up Sort alphabetically by last tag, A-Z.
2753 tag-down Sort alphabetically by last tag, Z-A.
2754 priority-up Sort numerically by priority, high priority last.
2755 priority-down Sort numerically by priority, high priority first.
2757 The different possibilities will be tried in sequence, and testing stops
2758 if one comparison returns a \"not-equal\". For example, the default
2759 '(time-up category-keep priority-down)
2760 means: Pull out all entries having a specified time of day and sort them,
2761 in order to make a time schedule for the current day the first thing in the
2762 agenda listing for the day. Of the entries without a time indication, keep
2763 the grouped in categories, don't sort the categories, but keep them in
2764 the sequence given in `org-agenda-files'. Within each category sort by
2765 priority.
2767 Leaving out `category-keep' would mean that items will be sorted across
2768 categories by priority.
2770 Instead of a single list, this can also be a set of list for specific
2771 contents, with a context symbol in the car of the list, any of
2772 `agenda', `todo', `tags' for the corresponding agenda views."
2773 :group 'org-agenda-sorting
2774 :type `(choice
2775 (repeat :tag "General" ,org-sorting-choice)
2776 (list :tag "Individually"
2777 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2778 (repeat ,org-sorting-choice))
2779 (cons (const :tag "Strategy for TODO lists" todo)
2780 (repeat ,org-sorting-choice))
2781 (cons (const :tag "Strategy for Tags matches" tags)
2782 (repeat ,org-sorting-choice)))))
2784 (defcustom org-sort-agenda-notime-is-late t
2785 "Non-nil means, items without time are considered late.
2786 This is only relevant for sorting. When t, items which have no explicit
2787 time like 15:30 will be considered as 99:01, i.e. later than any items which
2788 do have a time. When nil, the default time is before 0:00. You can use this
2789 option to decide if the schedule for today should come before or after timeless
2790 agenda entries."
2791 :group 'org-agenda-sorting
2792 :type 'boolean)
2794 (defgroup org-agenda-line-format nil
2795 "Options concerning the entry prefix in the Org-mode agenda display."
2796 :tag "Org Agenda Line Format"
2797 :group 'org-agenda)
2799 (defcustom org-agenda-prefix-format
2800 '((agenda . " %-12:c%?-12t% s")
2801 (timeline . " % s")
2802 (todo . " %-12:c")
2803 (tags . " %-12:c"))
2804 "Format specifications for the prefix of items in the agenda views.
2805 An alist with four entries, for the different agenda types. The keys to the
2806 sublists are `agenda', `timeline', `todo', and `tags'. The values
2807 are format strings.
2808 This format works similar to a printf format, with the following meaning:
2810 %c the category of the item, \"Diary\" for entries from the diary, or
2811 as given by the CATEGORY keyword or derived from the file name.
2812 %T the *last* tag of the item. Last because inherited tags come
2813 first in the list.
2814 %t the time-of-day specification if one applies to the entry, in the
2815 format HH:MM
2816 %s Scheduling/Deadline information, a short string
2818 All specifiers work basically like the standard `%s' of printf, but may
2819 contain two additional characters: A question mark just after the `%' and
2820 a whitespace/punctuation character just before the final letter.
2822 If the first character after `%' is a question mark, the entire field
2823 will only be included if the corresponding value applies to the
2824 current entry. This is useful for fields which should have fixed
2825 width when present, but zero width when absent. For example,
2826 \"%?-12t\" will result in a 12 character time field if a time of the
2827 day is specified, but will completely disappear in entries which do
2828 not contain a time.
2830 If there is punctuation or whitespace character just before the final
2831 format letter, this character will be appended to the field value if
2832 the value is not empty. For example, the format \"%-12:c\" leads to
2833 \"Diary: \" if the category is \"Diary\". If the category were be
2834 empty, no additional colon would be interted.
2836 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2837 - Indent the line with two space characters
2838 - Give the category in a 12 chars wide field, padded with whitespace on
2839 the right (because of `-'). Append a colon if there is a category
2840 (because of `:').
2841 - If there is a time-of-day, put it into a 12 chars wide field. If no
2842 time, don't put in an empty field, just skip it (because of '?').
2843 - Finally, put the scheduling information and append a whitespace.
2845 As another example, if you don't want the time-of-day of entries in
2846 the prefix, you could use:
2848 (setq org-agenda-prefix-format \" %-11:c% s\")
2850 See also the variables `org-agenda-remove-times-when-in-prefix' and
2851 `org-agenda-remove-tags'."
2852 :type '(choice
2853 (string :tag "General format")
2854 (list :greedy t :tag "View dependent"
2855 (cons (const agenda) (string :tag "Format"))
2856 (cons (const timeline) (string :tag "Format"))
2857 (cons (const todo) (string :tag "Format"))
2858 (cons (const tags) (string :tag "Format"))))
2859 :group 'org-agenda-line-format)
2861 (defvar org-prefix-format-compiled nil
2862 "The compiled version of the most recently used prefix format.
2863 See the variable `org-agenda-prefix-format'.")
2865 (defcustom org-agenda-todo-keyword-format "%-1s"
2866 "Format for the TODO keyword in agenda lines.
2867 Set this to something like \"%-12s\" if you want all TODO keywords
2868 to occupy a fixed space in the agenda display."
2869 :group 'org-agenda-line-format
2870 :type 'string)
2872 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
2873 "Text preceeding scheduled items in the agenda view.
2874 This is a list with two strings. The first applies when the item is
2875 scheduled on the current day. The second applies when it has been scheduled
2876 previously, it may contain a %d to capture how many days ago the item was
2877 scheduled."
2878 :group 'org-agenda-line-format
2879 :type '(list
2880 (string :tag "Scheduled today ")
2881 (string :tag "Scheduled previously")))
2883 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
2884 "Text preceeding deadline items in the agenda view.
2885 This is a list with two strings. The first applies when the item has its
2886 deadline on the current day. The second applies when it is in the past or
2887 in the future, it may contain %d to capture how many days away the deadline
2888 is (was)."
2889 :group 'org-agenda-line-format
2890 :type '(list
2891 (string :tag "Deadline today ")
2892 (string :tag "Deadline relative")))
2894 (defcustom org-agenda-remove-times-when-in-prefix t
2895 "Non-nil means, remove duplicate time specifications in agenda items.
2896 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2897 time-of-day specification in a headline or diary entry is extracted and
2898 placed into the prefix. If this option is non-nil, the original specification
2899 \(a timestamp or -range, or just a plain time(range) specification like
2900 11:30-4pm) will be removed for agenda display. This makes the agenda less
2901 cluttered.
2902 The option can be t or nil. It may also be the symbol `beg', indicating
2903 that the time should only be removed what it is located at the beginning of
2904 the headline/diary entry."
2905 :group 'org-agenda-line-format
2906 :type '(choice
2907 (const :tag "Always" t)
2908 (const :tag "Never" nil)
2909 (const :tag "When at beginning of entry" beg)))
2912 (defcustom org-agenda-default-appointment-duration nil
2913 "Default duration for appointments that only have a starting time.
2914 When nil, no duration is specified in such cases.
2915 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
2916 :group 'org-agenda-line-format
2917 :type '(choice
2918 (integer :tag "Minutes")
2919 (const :tag "No default duration")))
2922 (defcustom org-agenda-remove-tags nil
2923 "Non-nil means, remove the tags from the headline copy in the agenda.
2924 When this is the symbol `prefix', only remove tags when
2925 `org-agenda-prefix-format' contains a `%T' specifier."
2926 :group 'org-agenda-line-format
2927 :type '(choice
2928 (const :tag "Always" t)
2929 (const :tag "Never" nil)
2930 (const :tag "When prefix format contains %T" prefix)))
2932 (if (fboundp 'defvaralias)
2933 (defvaralias 'org-agenda-remove-tags-when-in-prefix
2934 'org-agenda-remove-tags))
2936 (defcustom org-agenda-tags-column -80
2937 "Shift tags in agenda items to this column.
2938 If this number is positive, it specifies the column. If it is negative,
2939 it means that the tags should be flushright to that column. For example,
2940 -80 works well for a normal 80 character screen."
2941 :group 'org-agenda-line-format
2942 :type 'integer)
2944 (if (fboundp 'defvaralias)
2945 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
2947 (defcustom org-agenda-fontify-priorities t
2948 "Non-nil means, highlight low and high priorities in agenda.
2949 When t, the highest priority entries are bold, lowest priority italic.
2950 This may also be an association list of priority faces. The face may be
2951 a names face, or a list like `(:background \"Red\")'."
2952 :group 'org-agenda-line-format
2953 :type '(choice
2954 (const :tag "Never" nil)
2955 (const :tag "Defaults" t)
2956 (repeat :tag "Specify"
2957 (list (character :tag "Priority" :value ?A)
2958 (sexp :tag "face")))))
2960 (defgroup org-latex nil
2961 "Options for embedding LaTeX code into Org-mode"
2962 :tag "Org LaTeX"
2963 :group 'org)
2965 (defcustom org-format-latex-options
2966 '(:foreground default :background default :scale 1.0
2967 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2968 :matchers ("begin" "$" "$$" "\\(" "\\["))
2969 "Options for creating images from LaTeX fragments.
2970 This is a property list with the following properties:
2971 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
2972 `default' means use the forground of the default face.
2973 :background the background color, or \"Transparent\".
2974 `default' means use the background of the default face.
2975 :scale a scaling factor for the size of the images
2976 :html-foreground, :html-background, :html-scale
2977 The same numbers for HTML export.
2978 :matchers a list indicating which matchers should be used to
2979 find LaTeX fragments. Valid members of this list are:
2980 \"begin\" find environments
2981 \"$\" find math expressions surrounded by $...$
2982 \"$$\" find math expressions surrounded by $$....$$
2983 \"\\(\" find math expressions surrounded by \\(...\\)
2984 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2985 :group 'org-latex
2986 :type 'plist)
2988 (defcustom org-format-latex-header "\\documentclass{article}
2989 \\usepackage{fullpage} % do not remove
2990 \\usepackage{amssymb}
2991 \\usepackage[usenames]{color}
2992 \\usepackage{amsmath}
2993 \\usepackage{latexsym}
2994 \\usepackage[mathscr]{eucal}
2995 \\pagestyle{empty} % do not remove"
2996 "The document header used for processing LaTeX fragments."
2997 :group 'org-latex
2998 :type 'string)
3000 (defgroup org-export nil
3001 "Options for exporting org-listings."
3002 :tag "Org Export"
3003 :group 'org)
3005 (defgroup org-export-general nil
3006 "General options for exporting Org-mode files."
3007 :tag "Org Export General"
3008 :group 'org-export)
3010 ;; FIXME
3011 (defvar org-export-publishing-directory nil)
3013 (defcustom org-export-with-special-strings t
3014 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3015 When this option is turned on, these strings will be exported as:
3017 Org HTML LaTeX
3018 -----+----------+--------
3019 \\- &shy; \\-
3020 -- &ndash; --
3021 --- &mdash; ---
3022 ... &hellip; \ldots
3024 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3025 :group 'org-export-translation
3026 :type 'boolean)
3028 (defcustom org-export-language-setup
3029 '(("en" "Author" "Date" "Table of Contents")
3030 ("cs" "Autor" "Datum" "Obsah")
3031 ("da" "Ophavsmand" "Dato" "Indhold")
3032 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
3033 ("es" "Autor" "Fecha" "\xcdndice")
3034 ("fr" "Auteur" "Date" "Table des mati\xe8res")
3035 ("it" "Autore" "Data" "Indice")
3036 ("nl" "Auteur" "Datum" "Inhoudsopgave")
3037 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
3038 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
3039 "Terms used in export text, translated to different languages.
3040 Use the variable `org-export-default-language' to set the language,
3041 or use the +OPTION lines for a per-file setting."
3042 :group 'org-export-general
3043 :type '(repeat
3044 (list
3045 (string :tag "HTML language tag")
3046 (string :tag "Author")
3047 (string :tag "Date")
3048 (string :tag "Table of Contents"))))
3050 (defcustom org-export-default-language "en"
3051 "The default language of HTML export, as a string.
3052 This should have an association in `org-export-language-setup'."
3053 :group 'org-export-general
3054 :type 'string)
3056 (defcustom org-export-skip-text-before-1st-heading t
3057 "Non-nil means, skip all text before the first headline when exporting.
3058 When nil, that text is exported as well."
3059 :group 'org-export-general
3060 :type 'boolean)
3062 (defcustom org-export-headline-levels 3
3063 "The last level which is still exported as a headline.
3064 Inferior levels will produce itemize lists when exported.
3065 Note that a numeric prefix argument to an exporter function overrides
3066 this setting.
3068 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
3069 :group 'org-export-general
3070 :type 'number)
3072 (defcustom org-export-with-section-numbers t
3073 "Non-nil means, add section numbers to headlines when exporting.
3075 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
3076 :group 'org-export-general
3077 :type 'boolean)
3079 (defcustom org-export-with-toc t
3080 "Non-nil means, create a table of contents in exported files.
3081 The TOC contains headlines with levels up to`org-export-headline-levels'.
3082 When an integer, include levels up to N in the toc, this may then be
3083 different from `org-export-headline-levels', but it will not be allowed
3084 to be larger than the number of headline levels.
3085 When nil, no table of contents is made.
3087 Headlines which contain any TODO items will be marked with \"(*)\" in
3088 ASCII export, and with red color in HTML output, if the option
3089 `org-export-mark-todo-in-toc' is set.
3091 In HTML output, the TOC will be clickable.
3093 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
3094 or \"toc:3\"."
3095 :group 'org-export-general
3096 :type '(choice
3097 (const :tag "No Table of Contents" nil)
3098 (const :tag "Full Table of Contents" t)
3099 (integer :tag "TOC to level")))
3101 (defcustom org-export-mark-todo-in-toc nil
3102 "Non-nil means, mark TOC lines that contain any open TODO items."
3103 :group 'org-export-general
3104 :type 'boolean)
3106 (defcustom org-export-preserve-breaks nil
3107 "Non-nil means, preserve all line breaks when exporting.
3108 Normally, in HTML output paragraphs will be reformatted. In ASCII
3109 export, line breaks will always be preserved, regardless of this variable.
3111 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3112 :group 'org-export-general
3113 :type 'boolean)
3115 (defcustom org-export-with-archived-trees 'headline
3116 "Whether subtrees with the ARCHIVE tag should be exported.
3117 This can have three different values
3118 nil Do not export, pretend this tree is not present
3119 t Do export the entire tree
3120 headline Only export the headline, but skip the tree below it."
3121 :group 'org-export-general
3122 :group 'org-archive
3123 :type '(choice
3124 (const :tag "not at all" nil)
3125 (const :tag "headline only" 'headline)
3126 (const :tag "entirely" t)))
3128 (defcustom org-export-author-info t
3129 "Non-nil means, insert author name and email into the exported file.
3131 This option can also be set with the +OPTIONS line,
3132 e.g. \"author-info:nil\"."
3133 :group 'org-export-general
3134 :type 'boolean)
3136 (defcustom org-export-time-stamp-file t
3137 "Non-nil means, insert a time stamp into the exported file.
3138 The time stamp shows when the file was created.
3140 This option can also be set with the +OPTIONS line,
3141 e.g. \"timestamp:nil\"."
3142 :group 'org-export-general
3143 :type 'boolean)
3145 (defcustom org-export-with-timestamps t
3146 "If nil, do not export time stamps and associated keywords."
3147 :group 'org-export-general
3148 :type 'boolean)
3150 (defcustom org-export-remove-timestamps-from-toc t
3151 "If nil, remove timestamps from the table of contents entries."
3152 :group 'org-export-general
3153 :type 'boolean)
3155 (defcustom org-export-with-tags 'not-in-toc
3156 "If nil, do not export tags, just remove them from headlines.
3157 If this is the symbol `not-in-toc', tags will be removed from table of
3158 contents entries, but still be shown in the headlines of the document.
3160 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3161 :group 'org-export-general
3162 :type '(choice
3163 (const :tag "Off" nil)
3164 (const :tag "Not in TOC" not-in-toc)
3165 (const :tag "On" t)))
3167 (defcustom org-export-with-drawers nil
3168 "Non-nil means, export with drawers like the property drawer.
3169 When t, all drawers are exported. This may also be a list of
3170 drawer names to export."
3171 :group 'org-export-general
3172 :type '(choice
3173 (const :tag "All drawers" t)
3174 (const :tag "None" nil)
3175 (repeat :tag "Selected drawers"
3176 (string :tag "Drawer name"))))
3178 (defgroup org-export-translation nil
3179 "Options for translating special ascii sequences for the export backends."
3180 :tag "Org Export Translation"
3181 :group 'org-export)
3183 (defcustom org-export-with-emphasize t
3184 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3185 If the export target supports emphasizing text, the word will be
3186 typeset in bold, italic, or underlined, respectively. Works only for
3187 single words, but you can say: I *really* *mean* *this*.
3188 Not all export backends support this.
3190 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3191 :group 'org-export-translation
3192 :type 'boolean)
3194 (defcustom org-export-with-footnotes t
3195 "If nil, export [1] as a footnote marker.
3196 Lines starting with [1] will be formatted as footnotes.
3198 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3199 :group 'org-export-translation
3200 :type 'boolean)
3202 (defcustom org-export-with-sub-superscripts t
3203 "Non-nil means, interpret \"_\" and \"^\" for export.
3204 When this option is turned on, you can use TeX-like syntax for sub- and
3205 superscripts. Several characters after \"_\" or \"^\" will be
3206 considered as a single item - so grouping with {} is normally not
3207 needed. For example, the following things will be parsed as single
3208 sub- or superscripts.
3210 10^24 or 10^tau several digits will be considered 1 item.
3211 10^-12 or 10^-tau a leading sign with digits or a word
3212 x^2-y^3 will be read as x^2 - y^3, because items are
3213 terminated by almost any nonword/nondigit char.
3214 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3216 Still, ambiguity is possible - so when in doubt use {} to enclose the
3217 sub/superscript. If you set this variable to the symbol `{}',
3218 the braces are *required* in order to trigger interpretations as
3219 sub/superscript. This can be helpful in documents that need \"_\"
3220 frequently in plain text.
3222 Not all export backends support this, but HTML does.
3224 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3225 :group 'org-export-translation
3226 :type '(choice
3227 (const :tag "Always interpret" t)
3228 (const :tag "Only with braces" {})
3229 (const :tag "Never interpret" nil)))
3231 (defcustom org-export-with-special-strings t
3232 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3233 When this option is turned on, these strings will be exported as:
3235 \\- : &shy;
3236 -- : &ndash;
3237 --- : &mdash;
3239 Not all export backends support this, but HTML does.
3241 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3242 :group 'org-export-translation
3243 :type 'boolean)
3245 (defcustom org-export-with-TeX-macros t
3246 "Non-nil means, interpret simple TeX-like macros when exporting.
3247 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3248 No only real TeX macros will work here, but the standard HTML entities
3249 for math can be used as macro names as well. For a list of supported
3250 names in HTML export, see the constant `org-html-entities'.
3251 Not all export backends support this.
3253 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3254 :group 'org-export-translation
3255 :group 'org-export-latex
3256 :type 'boolean)
3258 (defcustom org-export-with-LaTeX-fragments nil
3259 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3260 When set, the exporter will find LaTeX environments if the \\begin line is
3261 the first non-white thing on a line. It will also find the math delimiters
3262 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3263 display math.
3265 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3266 :group 'org-export-translation
3267 :group 'org-export-latex
3268 :type 'boolean)
3270 (defcustom org-export-with-fixed-width t
3271 "Non-nil means, lines starting with \":\" will be in fixed width font.
3272 This can be used to have pre-formatted text, fragments of code etc. For
3273 example:
3274 : ;; Some Lisp examples
3275 : (while (defc cnt)
3276 : (ding))
3277 will be looking just like this in also HTML. See also the QUOTE keyword.
3278 Not all export backends support this.
3280 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3281 :group 'org-export-translation
3282 :type 'boolean)
3284 (defcustom org-match-sexp-depth 3
3285 "Number of stacked braces for sub/superscript matching.
3286 This has to be set before loading org.el to be effective."
3287 :group 'org-export-translation
3288 :type 'integer)
3290 (defgroup org-export-tables nil
3291 "Options for exporting tables in Org-mode."
3292 :tag "Org Export Tables"
3293 :group 'org-export)
3295 (defcustom org-export-with-tables t
3296 "If non-nil, lines starting with \"|\" define a table.
3297 For example:
3299 | Name | Address | Birthday |
3300 |-------------+----------+-----------|
3301 | Arthur Dent | England | 29.2.2100 |
3303 Not all export backends support this.
3305 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3306 :group 'org-export-tables
3307 :type 'boolean)
3309 (defcustom org-export-highlight-first-table-line t
3310 "Non-nil means, highlight the first table line.
3311 In HTML export, this means use <th> instead of <td>.
3312 In tables created with table.el, this applies to the first table line.
3313 In Org-mode tables, all lines before the first horizontal separator
3314 line will be formatted with <th> tags."
3315 :group 'org-export-tables
3316 :type 'boolean)
3318 (defcustom org-export-table-remove-special-lines t
3319 "Remove special lines and marking characters in calculating tables.
3320 This removes the special marking character column from tables that are set
3321 up for spreadsheet calculations. It also removes the entire lines
3322 marked with `!', `_', or `^'. The lines with `$' are kept, because
3323 the values of constants may be useful to have."
3324 :group 'org-export-tables
3325 :type 'boolean)
3327 (defcustom org-export-prefer-native-exporter-for-tables nil
3328 "Non-nil means, always export tables created with table.el natively.
3329 Natively means, use the HTML code generator in table.el.
3330 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3331 the table does not use row- or column-spanning). This has the
3332 advantage, that the automatic HTML conversions for math symbols and
3333 sub/superscripts can be applied. Org-mode's HTML generator is also
3334 much faster."
3335 :group 'org-export-tables
3336 :type 'boolean)
3338 (defgroup org-export-ascii nil
3339 "Options specific for ASCII export of Org-mode files."
3340 :tag "Org Export ASCII"
3341 :group 'org-export)
3343 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3344 "Characters for underlining headings in ASCII export.
3345 In the given sequence, these characters will be used for level 1, 2, ..."
3346 :group 'org-export-ascii
3347 :type '(repeat character))
3349 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3350 "Bullet characters for headlines converted to lists in ASCII export.
3351 The first character is used for the first lest level generated in this
3352 way, and so on. If there are more levels than characters given here,
3353 the list will be repeated.
3354 Note that plain lists will keep the same bullets as the have in the
3355 Org-mode file."
3356 :group 'org-export-ascii
3357 :type '(repeat character))
3359 (defgroup org-export-xml nil
3360 "Options specific for XML export of Org-mode files."
3361 :tag "Org Export XML"
3362 :group 'org-export)
3364 (defgroup org-export-html nil
3365 "Options specific for HTML export of Org-mode files."
3366 :tag "Org Export HTML"
3367 :group 'org-export)
3369 (defcustom org-export-html-coding-system nil
3371 :group 'org-export-html
3372 :type 'coding-system)
3374 (defcustom org-export-html-extension "html"
3375 "The extension for exported HTML files."
3376 :group 'org-export-html
3377 :type 'string)
3379 (defcustom org-export-html-style
3380 "<style type=\"text/css\">
3381 html {
3382 font-family: Times, serif;
3383 font-size: 12pt;
3385 .title { text-align: center; }
3386 .todo { color: red; }
3387 .done { color: green; }
3388 .timestamp { color: grey }
3389 .timestamp-kwd { color: CadetBlue }
3390 .tag { background-color:lightblue; font-weight:normal }
3391 .target { background-color: lavender; }
3392 pre {
3393 border: 1pt solid #AEBDCC;
3394 background-color: #F3F5F7;
3395 padding: 5pt;
3396 font-family: courier, monospace;
3398 table { border-collapse: collapse; }
3399 td, th {
3400 vertical-align: top;
3401 <!--border: 1pt solid #ADB9CC;-->
3403 </style>"
3404 "The default style specification for exported HTML files.
3405 Since there are different ways of setting style information, this variable
3406 needs to contain the full HTML structure to provide a style, including the
3407 surrounding HTML tags. The style specifications should include definitions
3408 for new classes todo, done, title, and deadline. For example, legal values
3409 would be:
3411 <style type=\"text/css\">
3412 p { font-weight: normal; color: gray; }
3413 h1 { color: black; }
3414 .title { text-align: center; }
3415 .todo, .deadline { color: red; }
3416 .done { color: green; }
3417 </style>
3419 or, if you want to keep the style in a file,
3421 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3423 As the value of this option simply gets inserted into the HTML <head> header,
3424 you can \"misuse\" it to add arbitrary text to the header."
3425 :group 'org-export-html
3426 :type 'string)
3429 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3430 "Format for typesetting the document title in HTML export."
3431 :group 'org-export-html
3432 :type 'string)
3434 (defcustom org-export-html-toplevel-hlevel 2
3435 "The <H> level for level 1 headings in HTML export."
3436 :group 'org-export-html
3437 :type 'string)
3439 (defcustom org-export-html-link-org-files-as-html t
3440 "Non-nil means, make file links to `file.org' point to `file.html'.
3441 When org-mode is exporting an org-mode file to HTML, links to
3442 non-html files are directly put into a href tag in HTML.
3443 However, links to other Org-mode files (recognized by the
3444 extension `.org.) should become links to the corresponding html
3445 file, assuming that the linked org-mode file will also be
3446 converted to HTML.
3447 When nil, the links still point to the plain `.org' file."
3448 :group 'org-export-html
3449 :type 'boolean)
3451 (defcustom org-export-html-inline-images 'maybe
3452 "Non-nil means, inline images into exported HTML pages.
3453 This is done using an <img> tag. When nil, an anchor with href is used to
3454 link to the image. If this option is `maybe', then images in links with
3455 an empty description will be inlined, while images with a description will
3456 be linked only."
3457 :group 'org-export-html
3458 :type '(choice (const :tag "Never" nil)
3459 (const :tag "Always" t)
3460 (const :tag "When there is no description" maybe)))
3462 ;; FIXME: rename
3463 (defcustom org-export-html-expand t
3464 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3465 When nil, these tags will be exported as plain text and therefore
3466 not be interpreted by a browser.
3468 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3469 :group 'org-export-html
3470 :type 'boolean)
3472 (defcustom org-export-html-table-tag
3473 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3474 "The HTML tag that is used to start a table.
3475 This must be a <table> tag, but you may change the options like
3476 borders and spacing."
3477 :group 'org-export-html
3478 :type 'string)
3480 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3481 "The opening tag for table header fields.
3482 This is customizable so that alignment options can be specified."
3483 :group 'org-export-tables
3484 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3486 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3487 "The opening tag for table data fields.
3488 This is customizable so that alignment options can be specified."
3489 :group 'org-export-tables
3490 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3492 (defcustom org-export-html-with-timestamp nil
3493 "If non-nil, write `org-export-html-html-helper-timestamp'
3494 into the exported HTML text. Otherwise, the buffer will just be saved
3495 to a file."
3496 :group 'org-export-html
3497 :type 'boolean)
3499 (defcustom org-export-html-html-helper-timestamp
3500 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3501 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3502 :group 'org-export-html
3503 :type 'string)
3505 (defgroup org-export-icalendar nil
3506 "Options specific for iCalendar export of Org-mode files."
3507 :tag "Org Export iCalendar"
3508 :group 'org-export)
3510 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3511 "The file name for the iCalendar file covering all agenda files.
3512 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3513 The file name should be absolute, the file will be overwritten without warning."
3514 :group 'org-export-icalendar
3515 :type 'file)
3517 (defcustom org-icalendar-include-todo nil
3518 "Non-nil means, export to iCalendar files should also cover TODO items."
3519 :group 'org-export-icalendar
3520 :type '(choice
3521 (const :tag "None" nil)
3522 (const :tag "Unfinished" t)
3523 (const :tag "All" all)))
3525 (defcustom org-icalendar-include-sexps t
3526 "Non-nil means, export to iCalendar files should also cover sexp entries.
3527 These are entries like in the diary, but directly in an Org-mode file."
3528 :group 'org-export-icalendar
3529 :type 'boolean)
3531 (defcustom org-icalendar-include-body 100
3532 "Amount of text below headline to be included in iCalendar export.
3533 This is a number of characters that should maximally be included.
3534 Properties, scheduling and clocking lines will always be removed.
3535 The text will be inserted into the DESCRIPTION field."
3536 :group 'org-export-icalendar
3537 :type '(choice
3538 (const :tag "Nothing" nil)
3539 (const :tag "Everything" t)
3540 (integer :tag "Max characters")))
3542 (defcustom org-icalendar-combined-name "OrgMode"
3543 "Calendar name for the combined iCalendar representing all agenda files."
3544 :group 'org-export-icalendar
3545 :type 'string)
3547 (defgroup org-font-lock nil
3548 "Font-lock settings for highlighting in Org-mode."
3549 :tag "Org Font Lock"
3550 :group 'org)
3552 (defcustom org-level-color-stars-only nil
3553 "Non-nil means fontify only the stars in each headline.
3554 When nil, the entire headline is fontified.
3555 Changing it requires restart of `font-lock-mode' to become effective
3556 also in regions already fontified."
3557 :group 'org-font-lock
3558 :type 'boolean)
3560 (defcustom org-hide-leading-stars nil
3561 "Non-nil means, hide the first N-1 stars in a headline.
3562 This works by using the face `org-hide' for these stars. This
3563 face is white for a light background, and black for a dark
3564 background. You may have to customize the face `org-hide' to
3565 make this work.
3566 Changing it requires restart of `font-lock-mode' to become effective
3567 also in regions already fontified.
3568 You may also set this on a per-file basis by adding one of the following
3569 lines to the buffer:
3571 #+STARTUP: hidestars
3572 #+STARTUP: showstars"
3573 :group 'org-font-lock
3574 :type 'boolean)
3576 (defcustom org-fontify-done-headline nil
3577 "Non-nil means, change the face of a headline if it is marked DONE.
3578 Normally, only the TODO/DONE keyword indicates the state of a headline.
3579 When this is non-nil, the headline after the keyword is set to the
3580 `org-headline-done' as an additional indication."
3581 :group 'org-font-lock
3582 :type 'boolean)
3584 (defcustom org-fontify-emphasized-text t
3585 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3586 Changing this variable requires a restart of Emacs to take effect."
3587 :group 'org-font-lock
3588 :type 'boolean)
3590 (defcustom org-highlight-latex-fragments-and-specials nil
3591 "Non-nil means, fontify what is treated specially by the exporters."
3592 :group 'org-font-lock
3593 :type 'boolean)
3595 (defcustom org-hide-emphasis-markers nil
3596 "Non-nil mean font-lock should hide the emphasis marker characters."
3597 :group 'org-font-lock
3598 :type 'boolean)
3600 (defvar org-emph-re nil
3601 "Regular expression for matching emphasis.")
3602 (defvar org-verbatim-re nil
3603 "Regular expression for matching verbatim text.")
3604 (defvar org-emphasis-regexp-components) ; defined just below
3605 (defvar org-emphasis-alist) ; defined just below
3606 (defun org-set-emph-re (var val)
3607 "Set variable and compute the emphasis regular expression."
3608 (set var val)
3609 (when (and (boundp 'org-emphasis-alist)
3610 (boundp 'org-emphasis-regexp-components)
3611 org-emphasis-alist org-emphasis-regexp-components)
3612 (let* ((e org-emphasis-regexp-components)
3613 (pre (car e))
3614 (post (nth 1 e))
3615 (border (nth 2 e))
3616 (body (nth 3 e))
3617 (nl (nth 4 e))
3618 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3619 (body1 (concat body "*?"))
3620 (markers (mapconcat 'car org-emphasis-alist ""))
3621 (vmarkers (mapconcat
3622 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3623 org-emphasis-alist "")))
3624 ;; make sure special characters appear at the right position in the class
3625 (if (string-match "\\^" markers)
3626 (setq markers (concat (replace-match "" t t markers) "^")))
3627 (if (string-match "-" markers)
3628 (setq markers (concat (replace-match "" t t markers) "-")))
3629 (if (string-match "\\^" vmarkers)
3630 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3631 (if (string-match "-" vmarkers)
3632 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3633 (if (> nl 0)
3634 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3635 (int-to-string nl) "\\}")))
3636 ;; Make the regexp
3637 (setq org-emph-re
3638 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3639 "\\("
3640 "\\([" markers "]\\)"
3641 "\\("
3642 "[^" border "]\\|"
3643 "[^" border (if (and nil stacked) markers) "]"
3644 body1
3645 "[^" border (if (and nil stacked) markers) "]"
3646 "\\)"
3647 "\\3\\)"
3648 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3649 (setq org-verbatim-re
3650 (concat "\\([" pre "]\\|^\\)"
3651 "\\("
3652 "\\([" vmarkers "]\\)"
3653 "\\("
3654 "[^" border "]\\|"
3655 "[^" border "]"
3656 body1
3657 "[^" border "]"
3658 "\\)"
3659 "\\3\\)"
3660 "\\([" post "]\\|$\\)")))))
3662 (defcustom org-emphasis-regexp-components
3663 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3664 "Components used to build the regular expression for emphasis.
3665 This is a list with 6 entries. Terminology: In an emphasis string
3666 like \" *strong word* \", we call the initial space PREMATCH, the final
3667 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3668 and \"trong wor\" is the body. The different components in this variable
3669 specify what is allowed/forbidden in each part:
3671 pre Chars allowed as prematch. Beginning of line will be allowed too.
3672 post Chars allowed as postmatch. End of line will be allowed too.
3673 border The chars *forbidden* as border characters.
3674 body-regexp A regexp like \".\" to match a body character. Don't use
3675 non-shy groups here, and don't allow newline here.
3676 newline The maximum number of newlines allowed in an emphasis exp.
3678 Use customize to modify this, or restart Emacs after changing it."
3679 :group 'org-font-lock
3680 :set 'org-set-emph-re
3681 :type '(list
3682 (sexp :tag "Allowed chars in pre ")
3683 (sexp :tag "Allowed chars in post ")
3684 (sexp :tag "Forbidden chars in border ")
3685 (sexp :tag "Regexp for body ")
3686 (integer :tag "number of newlines allowed")
3687 (option (boolean :tag "Stacking (DISABLED) "))))
3689 (defcustom org-emphasis-alist
3690 '(("*" bold "<b>" "</b>")
3691 ("/" italic "<i>" "</i>")
3692 ("_" underline "<u>" "</u>")
3693 ("=" org-code "<code>" "</code>" verbatim)
3694 ("~" org-verbatim "" "" verbatim)
3695 ("+" (:strike-through t) "<del>" "</del>")
3697 "Special syntax for emphasized text.
3698 Text starting and ending with a special character will be emphasized, for
3699 example *bold*, _underlined_ and /italic/. This variable sets the marker
3700 characters, the face to be used by font-lock for highlighting in Org-mode
3701 Emacs buffers, and the HTML tags to be used for this.
3702 Use customize to modify this, or restart Emacs after changing it."
3703 :group 'org-font-lock
3704 :set 'org-set-emph-re
3705 :type '(repeat
3706 (list
3707 (string :tag "Marker character")
3708 (choice
3709 (face :tag "Font-lock-face")
3710 (plist :tag "Face property list"))
3711 (string :tag "HTML start tag")
3712 (string :tag "HTML end tag")
3713 (option (const verbatim)))))
3715 ;;; The faces
3717 (defgroup org-faces nil
3718 "Faces in Org-mode."
3719 :tag "Org Faces"
3720 :group 'org-font-lock)
3722 (defun org-compatible-face (inherits specs)
3723 "Make a compatible face specification.
3724 If INHERITS is an existing face and if the Emacs version supports it,
3725 just inherit the face. If not, use SPECS to define the face.
3726 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3727 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3728 to the top of the list. The `min-colors' attribute will be removed from
3729 any other entries, and any resulting duplicates will be removed entirely."
3730 (cond
3731 ((and inherits (facep inherits)
3732 (not (featurep 'xemacs)) (> emacs-major-version 22))
3733 ;; In Emacs 23, we use inheritance where possible.
3734 ;; We only do this in Emacs 23, because only there the outline
3735 ;; faces have been changed to the original org-mode-level-faces.
3736 (list (list t :inherit inherits)))
3737 ((or (featurep 'xemacs) (< emacs-major-version 22))
3738 ;; These do not understand the `min-colors' attribute.
3739 (let (r e a)
3740 (while (setq e (pop specs))
3741 (cond
3742 ((memq (car e) '(t default)) (push e r))
3743 ((setq a (member '(min-colors 8) (car e)))
3744 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3745 (cdr e)))))
3746 ((setq a (assq 'min-colors (car e)))
3747 (setq e (cons (delq a (car e)) (cdr e)))
3748 (or (assoc (car e) r) (push e r)))
3749 (t (or (assoc (car e) r) (push e r)))))
3750 (nreverse r)))
3751 (t specs)))
3752 (put 'org-compatible-face 'lisp-indent-function 1)
3754 (defface org-hide
3755 '((((background light)) (:foreground "white"))
3756 (((background dark)) (:foreground "black")))
3757 "Face used to hide leading stars in headlines.
3758 The forground color of this face should be equal to the background
3759 color of the frame."
3760 :group 'org-faces)
3762 (defface org-level-1 ;; font-lock-function-name-face
3763 (org-compatible-face 'outline-1
3764 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3765 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3766 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3767 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3768 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3769 (t (:bold t))))
3770 "Face used for level 1 headlines."
3771 :group 'org-faces)
3773 (defface org-level-2 ;; font-lock-variable-name-face
3774 (org-compatible-face 'outline-2
3775 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3776 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3777 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3778 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3779 (t (:bold t))))
3780 "Face used for level 2 headlines."
3781 :group 'org-faces)
3783 (defface org-level-3 ;; font-lock-keyword-face
3784 (org-compatible-face 'outline-3
3785 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3786 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3787 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3788 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3789 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3790 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3791 (t (:bold t))))
3792 "Face used for level 3 headlines."
3793 :group 'org-faces)
3795 (defface org-level-4 ;; font-lock-comment-face
3796 (org-compatible-face 'outline-4
3797 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3798 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3799 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3800 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3801 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3802 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3803 (t (:bold t))))
3804 "Face used for level 4 headlines."
3805 :group 'org-faces)
3807 (defface org-level-5 ;; font-lock-type-face
3808 (org-compatible-face 'outline-5
3809 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3810 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3811 (((class color) (min-colors 8)) (:foreground "green"))))
3812 "Face used for level 5 headlines."
3813 :group 'org-faces)
3815 (defface org-level-6 ;; font-lock-constant-face
3816 (org-compatible-face 'outline-6
3817 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3818 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3819 (((class color) (min-colors 8)) (:foreground "magenta"))))
3820 "Face used for level 6 headlines."
3821 :group 'org-faces)
3823 (defface org-level-7 ;; font-lock-builtin-face
3824 (org-compatible-face 'outline-7
3825 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3826 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3827 (((class color) (min-colors 8)) (:foreground "blue"))))
3828 "Face used for level 7 headlines."
3829 :group 'org-faces)
3831 (defface org-level-8 ;; font-lock-string-face
3832 (org-compatible-face 'outline-8
3833 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3834 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3835 (((class color) (min-colors 8)) (:foreground "green"))))
3836 "Face used for level 8 headlines."
3837 :group 'org-faces)
3839 (defface org-special-keyword ;; font-lock-string-face
3840 (org-compatible-face nil
3841 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3842 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3843 (t (:italic t))))
3844 "Face used for special keywords."
3845 :group 'org-faces)
3847 (defface org-drawer ;; font-lock-function-name-face
3848 (org-compatible-face nil
3849 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3850 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3851 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3852 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3853 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3854 (t (:bold t))))
3855 "Face used for drawers."
3856 :group 'org-faces)
3858 (defface org-property-value nil
3859 "Face used for the value of a property."
3860 :group 'org-faces)
3862 (defface org-column
3863 (org-compatible-face nil
3864 '((((class color) (min-colors 16) (background light))
3865 (:background "grey90"))
3866 (((class color) (min-colors 16) (background dark))
3867 (:background "grey30"))
3868 (((class color) (min-colors 8))
3869 (:background "cyan" :foreground "black"))
3870 (t (:inverse-video t))))
3871 "Face for column display of entry properties."
3872 :group 'org-faces)
3874 (when (fboundp 'set-face-attribute)
3875 ;; Make sure that a fixed-width face is used when we have a column table.
3876 (set-face-attribute 'org-column nil
3877 :height (face-attribute 'default :height)
3878 :family (face-attribute 'default :family)))
3880 (defface org-warning
3881 (org-compatible-face 'font-lock-warning-face
3882 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3883 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3884 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3885 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3886 (t (:bold t))))
3887 "Face for deadlines and TODO keywords."
3888 :group 'org-faces)
3890 (defface org-archived ; similar to shadow
3891 (org-compatible-face 'shadow
3892 '((((class color grayscale) (min-colors 88) (background light))
3893 (:foreground "grey50"))
3894 (((class color grayscale) (min-colors 88) (background dark))
3895 (:foreground "grey70"))
3896 (((class color) (min-colors 8) (background light))
3897 (:foreground "green"))
3898 (((class color) (min-colors 8) (background dark))
3899 (:foreground "yellow"))))
3900 "Face for headline with the ARCHIVE tag."
3901 :group 'org-faces)
3903 (defface org-link
3904 '((((class color) (background light)) (:foreground "Purple" :underline t))
3905 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3906 (t (:underline t)))
3907 "Face for links."
3908 :group 'org-faces)
3910 (defface org-ellipsis
3911 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
3912 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
3913 (t (:strike-through t)))
3914 "Face for the ellipsis in folded text."
3915 :group 'org-faces)
3917 (defface org-target
3918 '((((class color) (background light)) (:underline t))
3919 (((class color) (background dark)) (:underline t))
3920 (t (:underline t)))
3921 "Face for links."
3922 :group 'org-faces)
3924 (defface org-date
3925 '((((class color) (background light)) (:foreground "Purple" :underline t))
3926 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3927 (t (:underline t)))
3928 "Face for links."
3929 :group 'org-faces)
3931 (defface org-sexp-date
3932 '((((class color) (background light)) (:foreground "Purple"))
3933 (((class color) (background dark)) (:foreground "Cyan"))
3934 (t (:underline t)))
3935 "Face for links."
3936 :group 'org-faces)
3938 (defface org-tag
3939 '((t (:bold t)))
3940 "Face for tags."
3941 :group 'org-faces)
3943 (defface org-todo ; font-lock-warning-face
3944 (org-compatible-face nil
3945 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3946 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3947 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3948 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3949 (t (:inverse-video t :bold t))))
3950 "Face for TODO keywords."
3951 :group 'org-faces)
3953 (defface org-done ;; font-lock-type-face
3954 (org-compatible-face nil
3955 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
3956 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
3957 (((class color) (min-colors 8)) (:foreground "green"))
3958 (t (:bold t))))
3959 "Face used for todo keywords that indicate DONE items."
3960 :group 'org-faces)
3962 (defface org-headline-done ;; font-lock-string-face
3963 (org-compatible-face nil
3964 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3965 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3966 (((class color) (min-colors 8) (background light)) (:bold nil))))
3967 "Face used to indicate that a headline is DONE.
3968 This face is only used if `org-fontify-done-headline' is set. If applies
3969 to the part of the headline after the DONE keyword."
3970 :group 'org-faces)
3972 (defcustom org-todo-keyword-faces nil
3973 "Faces for specific TODO keywords.
3974 This is a list of cons cells, with TODO keywords in the car
3975 and faces in the cdr. The face can be a symbol, or a property
3976 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
3977 :group 'org-faces
3978 :group 'org-todo
3979 :type '(repeat
3980 (cons
3981 (string :tag "keyword")
3982 (sexp :tag "face"))))
3984 (defface org-table ;; font-lock-function-name-face
3985 (org-compatible-face nil
3986 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3987 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3988 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3989 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3990 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
3991 (((class color) (min-colors 8) (background dark)))))
3992 "Face used for tables."
3993 :group 'org-faces)
3995 (defface org-formula
3996 (org-compatible-face nil
3997 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3998 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3999 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4000 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
4001 (t (:bold t :italic t))))
4002 "Face for formulas."
4003 :group 'org-faces)
4005 (defface org-code
4006 (org-compatible-face nil
4007 '((((class color grayscale) (min-colors 88) (background light))
4008 (:foreground "grey50"))
4009 (((class color grayscale) (min-colors 88) (background dark))
4010 (:foreground "grey70"))
4011 (((class color) (min-colors 8) (background light))
4012 (:foreground "green"))
4013 (((class color) (min-colors 8) (background dark))
4014 (:foreground "yellow"))))
4015 "Face for fixed-with text like code snippets."
4016 :group 'org-faces
4017 :version "22.1")
4019 (defface org-verbatim
4020 (org-compatible-face nil
4021 '((((class color grayscale) (min-colors 88) (background light))
4022 (:foreground "grey50" :underline t))
4023 (((class color grayscale) (min-colors 88) (background dark))
4024 (:foreground "grey70" :underline t))
4025 (((class color) (min-colors 8) (background light))
4026 (:foreground "green" :underline t))
4027 (((class color) (min-colors 8) (background dark))
4028 (:foreground "yellow" :underline t))))
4029 "Face for fixed-with text like code snippets."
4030 :group 'org-faces
4031 :version "22.1")
4033 (defface org-agenda-structure ;; font-lock-function-name-face
4034 (org-compatible-face nil
4035 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4036 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4037 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4038 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4039 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4040 (t (:bold t))))
4041 "Face used in agenda for captions and dates."
4042 :group 'org-faces)
4044 (defface org-scheduled-today
4045 (org-compatible-face nil
4046 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
4047 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
4048 (((class color) (min-colors 8)) (:foreground "green"))
4049 (t (:bold t :italic t))))
4050 "Face for items scheduled for a certain day."
4051 :group 'org-faces)
4053 (defface org-scheduled-previously
4054 (org-compatible-face nil
4055 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4056 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4057 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4058 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4059 (t (:bold t))))
4060 "Face for items scheduled previously, and not yet done."
4061 :group 'org-faces)
4063 (defface org-upcoming-deadline
4064 (org-compatible-face nil
4065 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4066 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4067 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4068 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4069 (t (:bold t))))
4070 "Face for items scheduled previously, and not yet done."
4071 :group 'org-faces)
4073 (defcustom org-agenda-deadline-faces
4074 '((1.0 . org-warning)
4075 (0.5 . org-upcoming-deadline)
4076 (0.0 . default))
4077 "Faces for showing deadlines in the agenda.
4078 This is a list of cons cells. The cdr of each cell is a face to be used,
4079 and it can also just be like '(:foreground \"yellow\").
4080 Each car is a fraction of the head-warning time that must have passed for
4081 this the face in the cdr to be used for display. The numbers must be
4082 given in descending order. The head-warning time is normally taken
4083 from `org-deadline-warning-days', but can also be specified in the deadline
4084 timestamp itself, like this:
4086 DEADLINE: <2007-08-13 Mon -8d>
4088 You may use d for days, w for weeks, m for months and y for years. Months
4089 and years will only be treated in an approximate fashion (30.4 days for a
4090 month and 365.24 days for a year)."
4091 :group 'org-faces
4092 :group 'org-agenda-daily/weekly
4093 :type '(repeat
4094 (cons
4095 (number :tag "Fraction of head-warning time passed")
4096 (sexp :tag "Face"))))
4098 ;; FIXME: this is not a good face yet.
4099 (defface org-agenda-restriction-lock
4100 (org-compatible-face nil
4101 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
4102 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
4103 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
4104 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
4105 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
4106 (t (:inverse-video t))))
4107 "Face for showing the agenda restriction lock."
4108 :group 'org-faces)
4110 (defface org-time-grid ;; font-lock-variable-name-face
4111 (org-compatible-face nil
4112 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4113 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4114 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4115 "Face used for time grids."
4116 :group 'org-faces)
4118 (defconst org-level-faces
4119 '(org-level-1 org-level-2 org-level-3 org-level-4
4120 org-level-5 org-level-6 org-level-7 org-level-8
4123 (defcustom org-n-level-faces (length org-level-faces)
4124 "The number different faces to be used for headlines.
4125 Org-mode defines 8 different headline faces, so this can be at most 8.
4126 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4127 :type 'number
4128 :group 'org-faces)
4130 ;;; Functions and variables from ther packages
4131 ;; Declared here to avoid compiler warnings
4133 (eval-and-compile
4134 (unless (fboundp 'declare-function)
4135 (defmacro declare-function (fn file &optional arglist fileonly))))
4137 ;; XEmacs only
4138 (defvar outline-mode-menu-heading)
4139 (defvar outline-mode-menu-show)
4140 (defvar outline-mode-menu-hide)
4141 (defvar zmacs-regions) ; XEmacs regions
4143 ;; Emacs only
4144 (defvar mark-active)
4146 ;; Various packages
4147 ;; FIXME: get the argument lists for the UNKNOWN stuff
4148 (declare-function add-to-diary-list "diary-lib"
4149 (date string specifier &optional marker globcolor literal))
4150 (declare-function table--at-cell-p "table" (position &optional object at-column))
4151 (declare-function Info-find-node "info" (filename nodename &optional no-going-back))
4152 (declare-function Info-goto-node "info" (nodename &optional fork))
4153 (declare-function bbdb "ext:bbdb-com" (string elidep))
4154 (declare-function bbdb-company "ext:bbdb-com" (string elidep))
4155 (declare-function bbdb-current-record "ext:bbdb-com" (&optional planning-on-modifying))
4156 (declare-function bbdb-name "ext:bbdb-com" (string elidep))
4157 (declare-function bbdb-record-getprop "ext:bbdb" (record property))
4158 (declare-function bbdb-record-name "ext:bbdb" (record))
4159 (declare-function bibtex-beginning-of-entry "bibtex" ())
4160 (declare-function bibtex-generate-autokey "bibtex" ())
4161 (declare-function bibtex-parse-entry "bibtex" (&optional content))
4162 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
4163 (defvar calc-embedded-close-formula)
4164 (defvar calc-embedded-open-formula)
4165 (declare-function calendar-astro-date-string "cal-julian" (&optional date))
4166 (declare-function calendar-bahai-date-string "cal-bahai" (&optional date))
4167 (declare-function calendar-check-holidays "holidays" (date))
4168 (declare-function calendar-chinese-date-string "cal-china" (&optional date))
4169 (declare-function calendar-coptic-date-string "cal-coptic" (&optional date))
4170 (declare-function calendar-ethiopic-date-string "cal-coptic" (&optional date))
4171 (declare-function calendar-forward-day "cal-move" (arg))
4172 (declare-function calendar-french-date-string "cal-french" (&optional date))
4173 (declare-function calendar-goto-date "cal-move" (date))
4174 (declare-function calendar-goto-today "cal-move" ())
4175 (declare-function calendar-hebrew-date-string "cal-hebrew" (&optional date))
4176 (declare-function calendar-islamic-date-string "cal-islam" (&optional date))
4177 (declare-function calendar-iso-date-string "cal-iso" (&optional date))
4178 (declare-function calendar-julian-date-string "cal-julian" (&optional date))
4179 (declare-function calendar-mayan-date-string "cal-mayan" (&optional date))
4180 (declare-function calendar-persian-date-string "cal-persia" (&optional date))
4181 (defvar calendar-mode-map)
4182 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4183 (declare-function cdlatex-tab "ext:cdlatex" ())
4184 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4185 (declare-function elmo-folder-exists-p "ext:elmo" (folder) t)
4186 (declare-function elmo-message-entity-field "ext:elmo-msgdb" (entity field &optional type))
4187 (declare-function elmo-message-field "ext:elmo" (folder number field &optional type) t)
4188 (declare-function elmo-msgdb-overview-get-entity "ext:elmo" (&rest unknown) t)
4189 (defvar font-lock-unfontify-region-function)
4190 (declare-function gnus-article-show-summary "gnus-art" ())
4191 (declare-function gnus-summary-last-subject "gnus-sum" ())
4192 (defvar gnus-other-frame-object)
4193 (defvar gnus-group-name)
4194 (defvar gnus-article-current)
4195 (defvar Info-current-file)
4196 (defvar Info-current-node)
4197 (declare-function mh-display-msg "mh-show" (msg-num folder-name))
4198 (declare-function mh-find-path "mh-utils" ())
4199 (declare-function mh-get-header-field "mh-utils" (field))
4200 (declare-function mh-get-msg-num "mh-utils" (error-if-no-message))
4201 (declare-function mh-header-display "mh-show" ())
4202 (declare-function mh-index-previous-folder "mh-search" ())
4203 (declare-function mh-normalize-folder-name "mh-utils" (folder &optional empty-string-okay dont-remove-trailing-slash return-nil-if-folder-empty))
4204 (declare-function mh-search "mh-search" (folder search-regexp &optional redo-search-flag window-config))
4205 (declare-function mh-search-choose "mh-search" (&optional searcher))
4206 (declare-function mh-show "mh-show" (&optional message redisplay-flag))
4207 (declare-function mh-show-buffer-message-number "mh-comp" (&optional buffer))
4208 (declare-function mh-show-header-display "mh-show" t t)
4209 (declare-function mh-show-msg "mh-show" (msg))
4210 (declare-function mh-show-show "mh-show" t t)
4211 (declare-function mh-visit-folder "mh-folder" (folder &optional range index-data))
4212 (defvar mh-progs)
4213 (defvar mh-current-folder)
4214 (defvar mh-show-folder-buffer)
4215 (defvar mh-index-folder)
4216 (defvar mh-searcher)
4217 (declare-function org-export-latex-cleaned-string "org-export-latex" ())
4218 (declare-function parse-time-string "parse-time" (string))
4219 (declare-function remember "remember" (&optional initial))
4220 (declare-function remember-buffer-desc "remember" ())
4221 (defvar remember-save-after-remembering)
4222 (defvar remember-data-file)
4223 (defvar remember-register)
4224 (defvar remember-buffer)
4225 (defvar remember-handler-functions)
4226 (defvar remember-annotation-functions)
4227 (declare-function rmail-narrow-to-non-pruned-header "rmail" ())
4228 (declare-function rmail-show-message "rmail" (&optional n no-summary))
4229 (declare-function rmail-what-message "rmail" ())
4230 (defvar texmathp-why)
4231 (declare-function vm-beginning-of-message "ext:vm-page" ())
4232 (declare-function vm-follow-summary-cursor "ext:vm-motion" ())
4233 (declare-function vm-get-header-contents "ext:vm-summary" (message header-name-regexp &optional clump-sep))
4234 (declare-function vm-isearch-narrow "ext:vm-search" ())
4235 (declare-function vm-isearch-update "ext:vm-search" ())
4236 (declare-function vm-select-folder-buffer "ext:vm-macro" ())
4237 (declare-function vm-su-message-id "ext:vm-summary" (m))
4238 (declare-function vm-su-subject "ext:vm-summary" (m))
4239 (declare-function vm-summarize "ext:vm-summary" (&optional display raise))
4240 (defvar vm-message-pointer)
4241 (defvar vm-folder-directory)
4242 (defvar w3m-current-url)
4243 (defvar w3m-current-title)
4244 ;; backward compatibility to old version of wl
4245 (declare-function wl-summary-buffer-msgdb "ext:wl-folder" (&rest unknown) t)
4246 (declare-function wl-folder-get-elmo-folder "ext:wl-folder" (entity &optional no-cache))
4247 (declare-function wl-summary-goto-folder-subr "ext:wl-summary" (&optional name scan-type other-window sticky interactive scoring force-exit))
4248 (declare-function wl-summary-jump-to-msg-by-message-id "ext:wl-summary" (&optional id))
4249 (declare-function wl-summary-line-from "ext:wl-summary" ())
4250 (declare-function wl-summary-line-subject "ext:wl-summary" ())
4251 (declare-function wl-summary-message-number "ext:wl-summary" ())
4252 (declare-function wl-summary-redisplay "ext:wl-summary" (&optional arg))
4253 (defvar wl-summary-buffer-elmo-folder)
4254 (defvar wl-summary-buffer-folder-name)
4255 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4257 (defvar org-latex-regexps)
4258 (defvar constants-unit-system)
4260 ;;; Variables for pre-computed regular expressions, all buffer local
4262 (defvar org-drawer-regexp nil
4263 "Matches first line of a hidden block.")
4264 (make-variable-buffer-local 'org-drawer-regexp)
4265 (defvar org-todo-regexp nil
4266 "Matches any of the TODO state keywords.")
4267 (make-variable-buffer-local 'org-todo-regexp)
4268 (defvar org-not-done-regexp nil
4269 "Matches any of the TODO state keywords except the last one.")
4270 (make-variable-buffer-local 'org-not-done-regexp)
4271 (defvar org-todo-line-regexp nil
4272 "Matches a headline and puts TODO state into group 2 if present.")
4273 (make-variable-buffer-local 'org-todo-line-regexp)
4274 (defvar org-complex-heading-regexp nil
4275 "Matches a headline and puts everything into groups:
4276 group 1: the stars
4277 group 2: The todo keyword, maybe
4278 group 3: Priority cookie
4279 group 4: True headline
4280 group 5: Tags")
4281 (make-variable-buffer-local 'org-complex-heading-regexp)
4282 (defvar org-todo-line-tags-regexp nil
4283 "Matches a headline and puts TODO state into group 2 if present.
4284 Also put tags into group 4 if tags are present.")
4285 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4286 (defvar org-nl-done-regexp nil
4287 "Matches newline followed by a headline with the DONE keyword.")
4288 (make-variable-buffer-local 'org-nl-done-regexp)
4289 (defvar org-looking-at-done-regexp nil
4290 "Matches the DONE keyword a point.")
4291 (make-variable-buffer-local 'org-looking-at-done-regexp)
4292 (defvar org-ds-keyword-length 12
4293 "Maximum length of the Deadline and SCHEDULED keywords.")
4294 (make-variable-buffer-local 'org-ds-keyword-length)
4295 (defvar org-deadline-regexp nil
4296 "Matches the DEADLINE keyword.")
4297 (make-variable-buffer-local 'org-deadline-regexp)
4298 (defvar org-deadline-time-regexp nil
4299 "Matches the DEADLINE keyword together with a time stamp.")
4300 (make-variable-buffer-local 'org-deadline-time-regexp)
4301 (defvar org-deadline-line-regexp nil
4302 "Matches the DEADLINE keyword and the rest of the line.")
4303 (make-variable-buffer-local 'org-deadline-line-regexp)
4304 (defvar org-scheduled-regexp nil
4305 "Matches the SCHEDULED keyword.")
4306 (make-variable-buffer-local 'org-scheduled-regexp)
4307 (defvar org-scheduled-time-regexp nil
4308 "Matches the SCHEDULED keyword together with a time stamp.")
4309 (make-variable-buffer-local 'org-scheduled-time-regexp)
4310 (defvar org-closed-time-regexp nil
4311 "Matches the CLOSED keyword together with a time stamp.")
4312 (make-variable-buffer-local 'org-closed-time-regexp)
4314 (defvar org-keyword-time-regexp nil
4315 "Matches any of the 4 keywords, together with the time stamp.")
4316 (make-variable-buffer-local 'org-keyword-time-regexp)
4317 (defvar org-keyword-time-not-clock-regexp nil
4318 "Matches any of the 3 keywords, together with the time stamp.")
4319 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4320 (defvar org-maybe-keyword-time-regexp nil
4321 "Matches a timestamp, possibly preceeded by a keyword.")
4322 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4323 (defvar org-planning-or-clock-line-re nil
4324 "Matches a line with planning or clock info.")
4325 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4327 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4328 rear-nonsticky t mouse-map t fontified t)
4329 "Properties to remove when a string without properties is wanted.")
4331 (defsubst org-match-string-no-properties (num &optional string)
4332 (if (featurep 'xemacs)
4333 (let ((s (match-string num string)))
4334 (remove-text-properties 0 (length s) org-rm-props s)
4336 (match-string-no-properties num string)))
4338 (defsubst org-no-properties (s)
4339 (if (fboundp 'set-text-properties)
4340 (set-text-properties 0 (length s) nil s)
4341 (remove-text-properties 0 (length s) org-rm-props s))
4344 (defsubst org-get-alist-option (option key)
4345 (cond ((eq key t) t)
4346 ((eq option t) t)
4347 ((assoc key option) (cdr (assoc key option)))
4348 (t (cdr (assq 'default option)))))
4350 (defsubst org-inhibit-invisibility ()
4351 "Modified `buffer-invisibility-spec' for Emacs 21.
4352 Some ops with invisible text do not work correctly on Emacs 21. For these
4353 we turn off invisibility temporarily. Use this in a `let' form."
4354 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4356 (defsubst org-set-local (var value)
4357 "Make VAR local in current buffer and set it to VALUE."
4358 (set (make-variable-buffer-local var) value))
4360 (defsubst org-mode-p ()
4361 "Check if the current buffer is in Org-mode."
4362 (eq major-mode 'org-mode))
4364 (defsubst org-last (list)
4365 "Return the last element of LIST."
4366 (car (last list)))
4368 (defun org-let (list &rest body)
4369 (eval (cons 'let (cons list body))))
4370 (put 'org-let 'lisp-indent-function 1)
4372 (defun org-let2 (list1 list2 &rest body)
4373 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4374 (put 'org-let2 'lisp-indent-function 2)
4375 (defconst org-startup-options
4376 '(("fold" org-startup-folded t)
4377 ("overview" org-startup-folded t)
4378 ("nofold" org-startup-folded nil)
4379 ("showall" org-startup-folded nil)
4380 ("content" org-startup-folded content)
4381 ("hidestars" org-hide-leading-stars t)
4382 ("showstars" org-hide-leading-stars nil)
4383 ("odd" org-odd-levels-only t)
4384 ("oddeven" org-odd-levels-only nil)
4385 ("align" org-startup-align-all-tables t)
4386 ("noalign" org-startup-align-all-tables nil)
4387 ("customtime" org-display-custom-times t)
4388 ("logging" org-log-done t)
4389 ("logdone" org-log-done t)
4390 ("nologging" org-log-done nil)
4391 ("lognotedone" org-log-done done push)
4392 ("lognotestate" org-log-done state push)
4393 ("lognoteclock-out" org-log-done clock-out push)
4394 ("logrepeat" org-log-repeat t)
4395 ("nologrepeat" org-log-repeat nil)
4396 ("constcgs" constants-unit-system cgs)
4397 ("constSI" constants-unit-system SI))
4398 "Variable associated with STARTUP options for org-mode.
4399 Each element is a list of three items: The startup options as written
4400 in the #+STARTUP line, the corresponding variable, and the value to
4401 set this variable to if the option is found. An optional forth element PUSH
4402 means to push this value onto the list in the variable.")
4404 (defun org-set-regexps-and-options ()
4405 "Precompute regular expressions for current buffer."
4406 (when (org-mode-p)
4407 (org-set-local 'org-todo-kwd-alist nil)
4408 (org-set-local 'org-todo-key-alist nil)
4409 (org-set-local 'org-todo-key-trigger nil)
4410 (org-set-local 'org-todo-keywords-1 nil)
4411 (org-set-local 'org-done-keywords nil)
4412 (org-set-local 'org-todo-heads nil)
4413 (org-set-local 'org-todo-sets nil)
4414 (org-set-local 'org-todo-log-states nil)
4415 (let ((re (org-make-options-regexp
4416 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4417 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4418 "CONSTANTS" "PROPERTY" "DRAWERS")))
4419 (splitre "[ \t]+")
4420 kwds kws0 kwsa key value cat arch tags const links hw dws
4421 tail sep kws1 prio props drawers
4422 ex log)
4423 (save-excursion
4424 (save-restriction
4425 (widen)
4426 (goto-char (point-min))
4427 (while (re-search-forward re nil t)
4428 (setq key (match-string 1) value (org-match-string-no-properties 2))
4429 (cond
4430 ((equal key "CATEGORY")
4431 (if (string-match "[ \t]+$" value)
4432 (setq value (replace-match "" t t value)))
4433 (setq cat value))
4434 ((member key '("SEQ_TODO" "TODO"))
4435 (push (cons 'sequence (org-split-string value splitre)) kwds))
4436 ((equal key "TYP_TODO")
4437 (push (cons 'type (org-split-string value splitre)) kwds))
4438 ((equal key "TAGS")
4439 (setq tags (append tags (org-split-string value splitre))))
4440 ((equal key "COLUMNS")
4441 (org-set-local 'org-columns-default-format value))
4442 ((equal key "LINK")
4443 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4444 (push (cons (match-string 1 value)
4445 (org-trim (match-string 2 value)))
4446 links)))
4447 ((equal key "PRIORITIES")
4448 (setq prio (org-split-string value " +")))
4449 ((equal key "PROPERTY")
4450 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4451 (push (cons (match-string 1 value) (match-string 2 value))
4452 props)))
4453 ((equal key "DRAWERS")
4454 (setq drawers (org-split-string value splitre)))
4455 ((equal key "CONSTANTS")
4456 (setq const (append const (org-split-string value splitre))))
4457 ((equal key "STARTUP")
4458 (let ((opts (org-split-string value splitre))
4459 l var val)
4460 (while (setq l (pop opts))
4461 (when (setq l (assoc l org-startup-options))
4462 (setq var (nth 1 l) val (nth 2 l))
4463 (if (not (nth 3 l))
4464 (set (make-local-variable var) val)
4465 (if (not (listp (symbol-value var)))
4466 (set (make-local-variable var) nil))
4467 (set (make-local-variable var) (symbol-value var))
4468 (add-to-list var val))))))
4469 ((equal key "ARCHIVE")
4470 (string-match " *$" value)
4471 (setq arch (replace-match "" t t value))
4472 (remove-text-properties 0 (length arch)
4473 '(face t fontified t) arch)))
4475 (when cat
4476 (org-set-local 'org-category (intern cat))
4477 (push (cons "CATEGORY" cat) props))
4478 (when prio
4479 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4480 (setq prio (mapcar 'string-to-char prio))
4481 (org-set-local 'org-highest-priority (nth 0 prio))
4482 (org-set-local 'org-lowest-priority (nth 1 prio))
4483 (org-set-local 'org-default-priority (nth 2 prio)))
4484 (and props (org-set-local 'org-local-properties (nreverse props)))
4485 (and drawers (org-set-local 'org-drawers drawers))
4486 (and arch (org-set-local 'org-archive-location arch))
4487 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4488 ;; Process the TODO keywords
4489 (unless kwds
4490 ;; Use the global values as if they had been given locally.
4491 (setq kwds (default-value 'org-todo-keywords))
4492 (if (stringp (car kwds))
4493 (setq kwds (list (cons org-todo-interpretation
4494 (default-value 'org-todo-keywords)))))
4495 (setq kwds (reverse kwds)))
4496 (setq kwds (nreverse kwds))
4497 (let (inter kws kw)
4498 (while (setq kws (pop kwds))
4499 (setq inter (pop kws) sep (member "|" kws)
4500 kws0 (delete "|" (copy-sequence kws))
4501 kwsa nil
4502 kws1 (mapcar
4503 (lambda (x)
4504 (if (string-match "^\\(.*?\\)\\(?:(\\(..?\\))\\)?$" x)
4505 (progn
4506 (setq kw (match-string 1 x)
4507 ex (and (match-end 2) (match-string 2 x))
4508 log (and ex (string-match "@" ex))
4509 key (and ex (substring ex 0 1)))
4510 (if (equal key "@") (setq key nil))
4511 (push (cons kw (and key (string-to-char key))) kwsa)
4512 (and log (push kw org-todo-log-states))
4514 (error "Invalid TODO keyword %s" x)))
4515 kws0)
4516 kwsa (if kwsa (append '((:startgroup))
4517 (nreverse kwsa)
4518 '((:endgroup))))
4519 hw (car kws1)
4520 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4521 tail (list inter hw (car dws) (org-last dws)))
4522 (add-to-list 'org-todo-heads hw 'append)
4523 (push kws1 org-todo-sets)
4524 (setq org-done-keywords (append org-done-keywords dws nil))
4525 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4526 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4527 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4528 (setq org-todo-sets (nreverse org-todo-sets)
4529 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4530 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4531 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4532 ;; Process the constants
4533 (when const
4534 (let (e cst)
4535 (while (setq e (pop const))
4536 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4537 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4538 (setq org-table-formula-constants-local cst)))
4540 ;; Process the tags.
4541 (when tags
4542 (let (e tgs)
4543 (while (setq e (pop tags))
4544 (cond
4545 ((equal e "{") (push '(:startgroup) tgs))
4546 ((equal e "}") (push '(:endgroup) tgs))
4547 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4548 (push (cons (match-string 1 e)
4549 (string-to-char (match-string 2 e)))
4550 tgs))
4551 (t (push (list e) tgs))))
4552 (org-set-local 'org-tag-alist nil)
4553 (while (setq e (pop tgs))
4554 (or (and (stringp (car e))
4555 (assoc (car e) org-tag-alist))
4556 (push e org-tag-alist))))))
4558 ;; Compute the regular expressions and other local variables
4559 (if (not org-done-keywords)
4560 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4561 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4562 (length org-scheduled-string)))
4563 org-drawer-regexp
4564 (concat "^[ \t]*:\\("
4565 (mapconcat 'regexp-quote org-drawers "\\|")
4566 "\\):[ \t]*$")
4567 org-not-done-keywords
4568 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4569 org-todo-regexp
4570 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4571 "\\|") "\\)\\>")
4572 org-not-done-regexp
4573 (concat "\\<\\("
4574 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4575 "\\)\\>")
4576 org-todo-line-regexp
4577 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4578 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4579 "\\)\\>\\)?[ \t]*\\(.*\\)")
4580 org-complex-heading-regexp
4581 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4582 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4583 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4584 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4585 org-nl-done-regexp
4586 (concat "\n\\*+[ \t]+"
4587 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4588 "\\)" "\\>")
4589 org-todo-line-tags-regexp
4590 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4591 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4592 (org-re
4593 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4594 org-looking-at-done-regexp
4595 (concat "^" "\\(?:"
4596 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4597 "\\>")
4598 org-deadline-regexp (concat "\\<" org-deadline-string)
4599 org-deadline-time-regexp
4600 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4601 org-deadline-line-regexp
4602 (concat "\\<\\(" org-deadline-string "\\).*")
4603 org-scheduled-regexp
4604 (concat "\\<" org-scheduled-string)
4605 org-scheduled-time-regexp
4606 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4607 org-closed-time-regexp
4608 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4609 org-keyword-time-regexp
4610 (concat "\\<\\(" org-scheduled-string
4611 "\\|" org-deadline-string
4612 "\\|" org-closed-string
4613 "\\|" org-clock-string "\\)"
4614 " *[[<]\\([^]>]+\\)[]>]")
4615 org-keyword-time-not-clock-regexp
4616 (concat "\\<\\(" org-scheduled-string
4617 "\\|" org-deadline-string
4618 "\\|" org-closed-string
4619 "\\)"
4620 " *[[<]\\([^]>]+\\)[]>]")
4621 org-maybe-keyword-time-regexp
4622 (concat "\\(\\<\\(" org-scheduled-string
4623 "\\|" org-deadline-string
4624 "\\|" org-closed-string
4625 "\\|" org-clock-string "\\)\\)?"
4626 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4627 org-planning-or-clock-line-re
4628 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4629 "\\|" org-deadline-string
4630 "\\|" org-closed-string "\\|" org-clock-string
4631 "\\)\\>\\)")
4633 (org-compute-latex-and-specials-regexp)
4634 (org-set-font-lock-defaults)))
4636 (defun org-remove-keyword-keys (list)
4637 (mapcar (lambda (x)
4638 (if (string-match "(..?)$" x)
4639 (substring x 0 (match-beginning 0))
4641 list))
4643 ;; FIXME: this could be done much better, using second characters etc.
4644 (defun org-assign-fast-keys (alist)
4645 "Assign fast keys to a keyword-key alist.
4646 Respect keys that are already there."
4647 (let (new e k c c1 c2 (char ?a))
4648 (while (setq e (pop alist))
4649 (cond
4650 ((equal e '(:startgroup)) (push e new))
4651 ((equal e '(:endgroup)) (push e new))
4653 (setq k (car e) c2 nil)
4654 (if (cdr e)
4655 (setq c (cdr e))
4656 ;; automatically assign a character.
4657 (setq c1 (string-to-char
4658 (downcase (substring
4659 k (if (= (string-to-char k) ?@) 1 0)))))
4660 (if (or (rassoc c1 new) (rassoc c1 alist))
4661 (while (or (rassoc char new) (rassoc char alist))
4662 (setq char (1+ char)))
4663 (setq c2 c1))
4664 (setq c (or c2 char)))
4665 (push (cons k c) new))))
4666 (nreverse new)))
4668 ;;; Some variables ujsed in various places
4670 (defvar org-window-configuration nil
4671 "Used in various places to store a window configuration.")
4672 (defvar org-finish-function nil
4673 "Function to be called when `C-c C-c' is used.
4674 This is for getting out of special buffers like remember.")
4677 ;; FIXME: Occasionally check by commenting these, to make sure
4678 ;; no other functions uses these, forgetting to let-bind them.
4679 (defvar entry)
4680 (defvar state)
4681 (defvar last-state)
4682 (defvar date)
4683 (defvar description)
4685 ;; Defined somewhere in this file, but used before definition.
4686 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4687 (defvar org-agenda-buffer-name)
4688 (defvar org-agenda-undo-list)
4689 (defvar org-agenda-pending-undo-list)
4690 (defvar org-agenda-overriding-header)
4691 (defvar orgtbl-mode)
4692 (defvar org-html-entities)
4693 (defvar org-struct-menu)
4694 (defvar org-org-menu)
4695 (defvar org-tbl-menu)
4696 (defvar org-agenda-keymap)
4698 ;;;; Emacs/XEmacs compatibility
4700 ;; Overlay compatibility functions
4701 (defun org-make-overlay (beg end &optional buffer)
4702 (if (featurep 'xemacs)
4703 (make-extent beg end buffer)
4704 (make-overlay beg end buffer)))
4705 (defun org-delete-overlay (ovl)
4706 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4707 (defun org-detach-overlay (ovl)
4708 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4709 (defun org-move-overlay (ovl beg end &optional buffer)
4710 (if (featurep 'xemacs)
4711 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4712 (move-overlay ovl beg end buffer)))
4713 (defun org-overlay-put (ovl prop value)
4714 (if (featurep 'xemacs)
4715 (set-extent-property ovl prop value)
4716 (overlay-put ovl prop value)))
4717 (defun org-overlay-display (ovl text &optional face evap)
4718 "Make overlay OVL display TEXT with face FACE."
4719 (if (featurep 'xemacs)
4720 (let ((gl (make-glyph text)))
4721 (and face (set-glyph-face gl face))
4722 (set-extent-property ovl 'invisible t)
4723 (set-extent-property ovl 'end-glyph gl))
4724 (overlay-put ovl 'display text)
4725 (if face (overlay-put ovl 'face face))
4726 (if evap (overlay-put ovl 'evaporate t))))
4727 (defun org-overlay-before-string (ovl text &optional face evap)
4728 "Make overlay OVL display TEXT with face FACE."
4729 (if (featurep 'xemacs)
4730 (let ((gl (make-glyph text)))
4731 (and face (set-glyph-face gl face))
4732 (set-extent-property ovl 'begin-glyph gl))
4733 (if face (org-add-props text nil 'face face))
4734 (overlay-put ovl 'before-string text)
4735 (if evap (overlay-put ovl 'evaporate t))))
4736 (defun org-overlay-get (ovl prop)
4737 (if (featurep 'xemacs)
4738 (extent-property ovl prop)
4739 (overlay-get ovl prop)))
4740 (defun org-overlays-at (pos)
4741 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4742 (defun org-overlays-in (&optional start end)
4743 (if (featurep 'xemacs)
4744 (extent-list nil start end)
4745 (overlays-in start end)))
4746 (defun org-overlay-start (o)
4747 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4748 (defun org-overlay-end (o)
4749 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4750 (defun org-find-overlays (prop &optional pos delete)
4751 "Find all overlays specifying PROP at POS or point.
4752 If DELETE is non-nil, delete all those overlays."
4753 (let ((overlays (org-overlays-at (or pos (point))))
4754 ov found)
4755 (while (setq ov (pop overlays))
4756 (if (org-overlay-get ov prop)
4757 (if delete (org-delete-overlay ov) (push ov found))))
4758 found))
4760 ;; Region compatibility
4762 (defun org-add-hook (hook function &optional append local)
4763 "Add-hook, compatible with both Emacsen."
4764 (if (and local (featurep 'xemacs))
4765 (add-local-hook hook function append)
4766 (add-hook hook function append local)))
4768 (defvar org-ignore-region nil
4769 "To temporarily disable the active region.")
4771 (defun org-region-active-p ()
4772 "Is `transient-mark-mode' on and the region active?
4773 Works on both Emacs and XEmacs."
4774 (if org-ignore-region
4776 (if (featurep 'xemacs)
4777 (and zmacs-regions (region-active-p))
4778 (if (fboundp 'use-region-p)
4779 (use-region-p)
4780 (and transient-mark-mode mark-active))))) ; Emacs 22 and before
4782 ;; Invisibility compatibility
4784 (defun org-add-to-invisibility-spec (arg)
4785 "Add elements to `buffer-invisibility-spec'.
4786 See documentation for `buffer-invisibility-spec' for the kind of elements
4787 that can be added."
4788 (cond
4789 ((fboundp 'add-to-invisibility-spec)
4790 (add-to-invisibility-spec arg))
4791 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4792 (setq buffer-invisibility-spec (list arg)))
4794 (setq buffer-invisibility-spec
4795 (cons arg buffer-invisibility-spec)))))
4797 (defun org-remove-from-invisibility-spec (arg)
4798 "Remove elements from `buffer-invisibility-spec'."
4799 (if (fboundp 'remove-from-invisibility-spec)
4800 (remove-from-invisibility-spec arg)
4801 (if (consp buffer-invisibility-spec)
4802 (setq buffer-invisibility-spec
4803 (delete arg buffer-invisibility-spec)))))
4805 (defun org-in-invisibility-spec-p (arg)
4806 "Is ARG a member of `buffer-invisibility-spec'?"
4807 (if (consp buffer-invisibility-spec)
4808 (member arg buffer-invisibility-spec)
4809 nil))
4811 ;;;; Define the Org-mode
4813 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4814 (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."))
4817 ;; We use a before-change function to check if a table might need
4818 ;; an update.
4819 (defvar org-table-may-need-update t
4820 "Indicates that a table might need an update.
4821 This variable is set by `org-before-change-function'.
4822 `org-table-align' sets it back to nil.")
4823 (defvar org-mode-map)
4824 (defvar org-mode-hook nil)
4825 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4826 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4827 (defvar org-table-buffer-is-an nil)
4828 (defconst org-outline-regexp "\\*+ ")
4830 ;;;###autoload
4831 (define-derived-mode org-mode outline-mode "Org"
4832 "Outline-based notes management and organizer, alias
4833 \"Carsten's outline-mode for keeping track of everything.\"
4835 Org-mode develops organizational tasks around a NOTES file which
4836 contains information about projects as plain text. Org-mode is
4837 implemented on top of outline-mode, which is ideal to keep the content
4838 of large files well structured. It supports ToDo items, deadlines and
4839 time stamps, which magically appear in the diary listing of the Emacs
4840 calendar. Tables are easily created with a built-in table editor.
4841 Plain text URL-like links connect to websites, emails (VM), Usenet
4842 messages (Gnus), BBDB entries, and any files related to the project.
4843 For printing and sharing of notes, an Org-mode file (or a part of it)
4844 can be exported as a structured ASCII or HTML file.
4846 The following commands are available:
4848 \\{org-mode-map}"
4850 ;; Get rid of Outline menus, they are not needed
4851 ;; Need to do this here because define-derived-mode sets up
4852 ;; the keymap so late. Still, it is a waste to call this each time
4853 ;; we switch another buffer into org-mode.
4854 (if (featurep 'xemacs)
4855 (when (boundp 'outline-mode-menu-heading)
4856 ;; Assume this is Greg's port, it used easymenu
4857 (easy-menu-remove outline-mode-menu-heading)
4858 (easy-menu-remove outline-mode-menu-show)
4859 (easy-menu-remove outline-mode-menu-hide))
4860 (define-key org-mode-map [menu-bar headings] 'undefined)
4861 (define-key org-mode-map [menu-bar hide] 'undefined)
4862 (define-key org-mode-map [menu-bar show] 'undefined))
4864 (easy-menu-add org-org-menu)
4865 (easy-menu-add org-tbl-menu)
4866 (org-install-agenda-files-menu)
4867 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4868 (org-add-to-invisibility-spec '(org-cwidth))
4869 (when (featurep 'xemacs)
4870 (org-set-local 'line-move-ignore-invisible t))
4871 (org-set-local 'outline-regexp org-outline-regexp)
4872 (org-set-local 'outline-level 'org-outline-level)
4873 (when (and org-ellipsis
4874 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4875 (fboundp 'make-glyph-code))
4876 (unless org-display-table
4877 (setq org-display-table (make-display-table)))
4878 (set-display-table-slot
4879 org-display-table 4
4880 (vconcat (mapcar
4881 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4882 org-ellipsis)))
4883 (if (stringp org-ellipsis) org-ellipsis "..."))))
4884 (setq buffer-display-table org-display-table))
4885 (org-set-regexps-and-options)
4886 ;; Calc embedded
4887 (org-set-local 'calc-embedded-open-mode "# ")
4888 (modify-syntax-entry ?# "<")
4889 (modify-syntax-entry ?@ "w")
4890 (if org-startup-truncated (setq truncate-lines t))
4891 (org-set-local 'font-lock-unfontify-region-function
4892 'org-unfontify-region)
4893 ;; Activate before-change-function
4894 (org-set-local 'org-table-may-need-update t)
4895 (org-add-hook 'before-change-functions 'org-before-change-function nil
4896 'local)
4897 ;; Check for running clock before killing a buffer
4898 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4899 ;; Paragraphs and auto-filling
4900 (org-set-autofill-regexps)
4901 (setq indent-line-function 'org-indent-line-function)
4902 (org-update-radio-target-regexp)
4904 ;; Comment characters
4905 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4906 (org-set-local 'comment-padding " ")
4908 ;; Imenu
4909 (org-set-local 'imenu-create-index-function
4910 'org-imenu-get-tree)
4912 ;; Make isearch reveal context
4913 (if (or (featurep 'xemacs)
4914 (not (boundp 'outline-isearch-open-invisible-function)))
4915 ;; Emacs 21 and XEmacs make use of the hook
4916 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4917 ;; Emacs 22 deals with this through a special variable
4918 (org-set-local 'outline-isearch-open-invisible-function
4919 (lambda (&rest ignore) (org-show-context 'isearch))))
4921 ;; If empty file that did not turn on org-mode automatically, make it to.
4922 (if (and org-insert-mode-line-in-empty-file
4923 (interactive-p)
4924 (= (point-min) (point-max)))
4925 (insert "# -*- mode: org -*-\n\n"))
4927 (unless org-inhibit-startup
4928 (when org-startup-align-all-tables
4929 (let ((bmp (buffer-modified-p)))
4930 (org-table-map-tables 'org-table-align)
4931 (set-buffer-modified-p bmp)))
4932 (org-cycle-hide-drawers 'all)
4933 (cond
4934 ((eq org-startup-folded t)
4935 (org-cycle '(4)))
4936 ((eq org-startup-folded 'content)
4937 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4938 (org-cycle '(4)) (org-cycle '(4)))))))
4940 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4942 (defsubst org-call-with-arg (command arg)
4943 "Call COMMAND interactively, but pretend prefix are was ARG."
4944 (let ((current-prefix-arg arg)) (call-interactively command)))
4946 (defsubst org-current-line (&optional pos)
4947 (save-excursion
4948 (and pos (goto-char pos))
4949 ;; works also in narrowed buffer, because we start at 1, not point-min
4950 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
4952 (defun org-current-time ()
4953 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4954 (if (> org-time-stamp-rounding-minutes 0)
4955 (let ((r org-time-stamp-rounding-minutes)
4956 (time (decode-time)))
4957 (apply 'encode-time
4958 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4959 (nthcdr 2 time))))
4960 (current-time)))
4962 (defun org-add-props (string plist &rest props)
4963 "Add text properties to entire string, from beginning to end.
4964 PLIST may be a list of properties, PROPS are individual properties and values
4965 that will be added to PLIST. Returns the string that was modified."
4966 (add-text-properties
4967 0 (length string) (if props (append plist props) plist) string)
4968 string)
4969 (put 'org-add-props 'lisp-indent-function 2)
4972 ;;;; Font-Lock stuff, including the activators
4974 (defvar org-mouse-map (make-sparse-keymap))
4975 (org-defkey org-mouse-map
4976 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4977 (org-defkey org-mouse-map
4978 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4979 (when org-mouse-1-follows-link
4980 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4981 (when org-tab-follows-link
4982 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4983 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4984 (when org-return-follows-link
4985 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
4986 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
4988 (require 'font-lock)
4990 (defconst org-non-link-chars "]\t\n\r<>")
4991 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
4992 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp" "message"))
4993 (defvar org-link-re-with-space nil
4994 "Matches a link with spaces, optional angular brackets around it.")
4995 (defvar org-link-re-with-space2 nil
4996 "Matches a link with spaces, optional angular brackets around it.")
4997 (defvar org-angle-link-re nil
4998 "Matches link with angular brackets, spaces are allowed.")
4999 (defvar org-plain-link-re nil
5000 "Matches plain link, without spaces.")
5001 (defvar org-bracket-link-regexp nil
5002 "Matches a link in double brackets.")
5003 (defvar org-bracket-link-analytic-regexp nil
5004 "Regular expression used to analyze links.
5005 Here is what the match groups contain after a match:
5006 1: http:
5007 2: http
5008 3: path
5009 4: [desc]
5010 5: desc")
5011 (defvar org-any-link-re nil
5012 "Regular expression matching any link.")
5014 (defun org-make-link-regexps ()
5015 "Update the link regular expressions.
5016 This should be called after the variable `org-link-types' has changed."
5017 (setq org-link-re-with-space
5018 (concat
5019 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5020 "\\([^" org-non-link-chars " ]"
5021 "[^" org-non-link-chars "]*"
5022 "[^" org-non-link-chars " ]\\)>?")
5023 org-link-re-with-space2
5024 (concat
5025 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5026 "\\([^" org-non-link-chars " ]"
5027 "[^]\t\n\r]*"
5028 "[^" org-non-link-chars " ]\\)>?")
5029 org-angle-link-re
5030 (concat
5031 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5032 "\\([^" org-non-link-chars " ]"
5033 "[^" org-non-link-chars "]*"
5034 "\\)>")
5035 org-plain-link-re
5036 (concat
5037 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5038 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5039 org-bracket-link-regexp
5040 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5041 org-bracket-link-analytic-regexp
5042 (concat
5043 "\\[\\["
5044 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
5045 "\\([^]]+\\)"
5046 "\\]"
5047 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5048 "\\]")
5049 org-any-link-re
5050 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5051 org-angle-link-re "\\)\\|\\("
5052 org-plain-link-re "\\)")))
5054 (org-make-link-regexps)
5056 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5057 "Regular expression for fast time stamp matching.")
5058 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
5059 "Regular expression for fast time stamp matching.")
5060 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5061 "Regular expression matching time strings for analysis.
5062 This one does not require the space after the date.")
5063 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5064 "Regular expression matching time strings for analysis.")
5065 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5066 "Regular expression matching time stamps, with groups.")
5067 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5068 "Regular expression matching time stamps (also [..]), with groups.")
5069 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5070 "Regular expression matching a time stamp range.")
5071 (defconst org-tr-regexp-both
5072 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5073 "Regular expression matching a time stamp range.")
5074 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5075 org-ts-regexp "\\)?")
5076 "Regular expression matching a time stamp or time stamp range.")
5077 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5078 org-ts-regexp-both "\\)?")
5079 "Regular expression matching a time stamp or time stamp range.
5080 The time stamps may be either active or inactive.")
5082 (defvar org-emph-face nil)
5084 (defun org-do-emphasis-faces (limit)
5085 "Run through the buffer and add overlays to links."
5086 (let (rtn)
5087 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5088 (if (not (= (char-after (match-beginning 3))
5089 (char-after (match-beginning 4))))
5090 (progn
5091 (setq rtn t)
5092 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5093 'face
5094 (nth 1 (assoc (match-string 3)
5095 org-emphasis-alist)))
5096 (add-text-properties (match-beginning 2) (match-end 2)
5097 '(font-lock-multiline t))
5098 (when org-hide-emphasis-markers
5099 (add-text-properties (match-end 4) (match-beginning 5)
5100 '(invisible org-link))
5101 (add-text-properties (match-beginning 3) (match-end 3)
5102 '(invisible org-link)))))
5103 (backward-char 1))
5104 rtn))
5106 (defun org-emphasize (&optional char)
5107 "Insert or change an emphasis, i.e. a font like bold or italic.
5108 If there is an active region, change that region to a new emphasis.
5109 If there is no region, just insert the marker characters and position
5110 the cursor between them.
5111 CHAR should be either the marker character, or the first character of the
5112 HTML tag associated with that emphasis. If CHAR is a space, the means
5113 to remove the emphasis of the selected region.
5114 If char is not given (for example in an interactive call) it
5115 will be prompted for."
5116 (interactive)
5117 (let ((eal org-emphasis-alist) e det
5118 (erc org-emphasis-regexp-components)
5119 (prompt "")
5120 (string "") beg end move tag c s)
5121 (if (org-region-active-p)
5122 (setq beg (region-beginning) end (region-end)
5123 string (buffer-substring beg end))
5124 (setq move t))
5126 (while (setq e (pop eal))
5127 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5128 c (aref tag 0))
5129 (push (cons c (string-to-char (car e))) det)
5130 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5131 (substring tag 1)))))
5132 (unless char
5133 (message "%s" (concat "Emphasis marker or tag:" prompt))
5134 (setq char (read-char-exclusive)))
5135 (setq char (or (cdr (assoc char det)) char))
5136 (if (equal char ?\ )
5137 (setq s "" move nil)
5138 (unless (assoc (char-to-string char) org-emphasis-alist)
5139 (error "No such emphasis marker: \"%c\"" char))
5140 (setq s (char-to-string char)))
5141 (while (and (> (length string) 1)
5142 (equal (substring string 0 1) (substring string -1))
5143 (assoc (substring string 0 1) org-emphasis-alist))
5144 (setq string (substring string 1 -1)))
5145 (setq string (concat s string s))
5146 (if beg (delete-region beg end))
5147 (unless (or (bolp)
5148 (string-match (concat "[" (nth 0 erc) "\n]")
5149 (char-to-string (char-before (point)))))
5150 (insert " "))
5151 (unless (string-match (concat "[" (nth 1 erc) "\n]")
5152 (char-to-string (char-after (point))))
5153 (insert " ") (backward-char 1))
5154 (insert string)
5155 (and move (backward-char 1))))
5157 (defconst org-nonsticky-props
5158 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5161 (defun org-activate-plain-links (limit)
5162 "Run through the buffer and add overlays to links."
5163 (catch 'exit
5164 (let (f)
5165 (while (re-search-forward org-plain-link-re limit t)
5166 (setq f (get-text-property (match-beginning 0) 'face))
5167 (if (or (eq f 'org-tag)
5168 (and (listp f) (memq 'org-tag f)))
5170 (add-text-properties (match-beginning 0) (match-end 0)
5171 (list 'mouse-face 'highlight
5172 'rear-nonsticky org-nonsticky-props
5173 'keymap org-mouse-map
5175 (throw 'exit t))))))
5177 (defun org-activate-code (limit)
5178 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
5179 (unless (get-text-property (match-beginning 1) 'face)
5180 (remove-text-properties (match-beginning 0) (match-end 0)
5181 '(display t invisible t intangible t))
5182 t)))
5184 (defun org-activate-angle-links (limit)
5185 "Run through the buffer and add overlays to links."
5186 (if (re-search-forward org-angle-link-re limit t)
5187 (progn
5188 (add-text-properties (match-beginning 0) (match-end 0)
5189 (list 'mouse-face 'highlight
5190 'rear-nonsticky org-nonsticky-props
5191 'keymap org-mouse-map
5193 t)))
5195 (defmacro org-maybe-intangible (props)
5196 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
5197 In emacs 21, invisible text is not avoided by the command loop, so the
5198 intangible property is needed to make sure point skips this text.
5199 In Emacs 22, this is not necessary. The intangible text property has
5200 led to problems with flyspell. These problems are fixed in flyspell.el,
5201 but we still avoid setting the property in Emacs 22 and later.
5202 We use a macro so that the test can happen at compilation time."
5203 (if (< emacs-major-version 22)
5204 `(append '(intangible t) ,props)
5205 props))
5207 (defun org-activate-bracket-links (limit)
5208 "Run through the buffer and add overlays to bracketed links."
5209 (if (re-search-forward org-bracket-link-regexp limit t)
5210 (let* ((help (concat "LINK: "
5211 (org-match-string-no-properties 1)))
5212 ;; FIXME: above we should remove the escapes.
5213 ;; but that requires another match, protecting match data,
5214 ;; a lot of overhead for font-lock.
5215 (ip (org-maybe-intangible
5216 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5217 'keymap org-mouse-map 'mouse-face 'highlight
5218 'font-lock-multiline t 'help-echo help)))
5219 (vp (list 'rear-nonsticky org-nonsticky-props
5220 'keymap org-mouse-map 'mouse-face 'highlight
5221 ' font-lock-multiline t 'help-echo help)))
5222 ;; We need to remove the invisible property here. Table narrowing
5223 ;; may have made some of this invisible.
5224 (remove-text-properties (match-beginning 0) (match-end 0)
5225 '(invisible nil))
5226 (if (match-end 3)
5227 (progn
5228 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5229 (add-text-properties (match-beginning 3) (match-end 3) vp)
5230 (add-text-properties (match-end 3) (match-end 0) ip))
5231 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5232 (add-text-properties (match-beginning 1) (match-end 1) vp)
5233 (add-text-properties (match-end 1) (match-end 0) ip))
5234 t)))
5236 (defun org-activate-dates (limit)
5237 "Run through the buffer and add overlays to dates."
5238 (if (re-search-forward org-tsr-regexp-both limit t)
5239 (progn
5240 (add-text-properties (match-beginning 0) (match-end 0)
5241 (list 'mouse-face 'highlight
5242 'rear-nonsticky org-nonsticky-props
5243 'keymap org-mouse-map))
5244 (when org-display-custom-times
5245 (if (match-end 3)
5246 (org-display-custom-time (match-beginning 3) (match-end 3)))
5247 (org-display-custom-time (match-beginning 1) (match-end 1)))
5248 t)))
5250 (defvar org-target-link-regexp nil
5251 "Regular expression matching radio targets in plain text.")
5252 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5253 "Regular expression matching a link target.")
5254 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5255 "Regular expression matching a radio target.")
5256 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5257 "Regular expression matching any target.")
5259 (defun org-activate-target-links (limit)
5260 "Run through the buffer and add overlays to target matches."
5261 (when org-target-link-regexp
5262 (let ((case-fold-search t))
5263 (if (re-search-forward org-target-link-regexp limit t)
5264 (progn
5265 (add-text-properties (match-beginning 0) (match-end 0)
5266 (list 'mouse-face 'highlight
5267 'rear-nonsticky org-nonsticky-props
5268 'keymap org-mouse-map
5269 'help-echo "Radio target link"
5270 'org-linked-text t))
5271 t)))))
5273 (defun org-update-radio-target-regexp ()
5274 "Find all radio targets in this file and update the regular expression."
5275 (interactive)
5276 (when (memq 'radio org-activate-links)
5277 (setq org-target-link-regexp
5278 (org-make-target-link-regexp (org-all-targets 'radio)))
5279 (org-restart-font-lock)))
5281 (defun org-hide-wide-columns (limit)
5282 (let (s e)
5283 (setq s (text-property-any (point) (or limit (point-max))
5284 'org-cwidth t))
5285 (when s
5286 (setq e (next-single-property-change s 'org-cwidth))
5287 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5288 (goto-char e)
5289 t)))
5291 (defvar org-latex-and-specials-regexp nil
5292 "Regular expression for highlighting export special stuff.")
5293 (defvar org-match-substring-regexp)
5294 (defvar org-match-substring-with-braces-regexp)
5295 (defvar org-export-html-special-string-regexps)
5297 (defun org-compute-latex-and-specials-regexp ()
5298 "Compute regular expression for stuff treated specially by exporters."
5299 (if (not org-highlight-latex-fragments-and-specials)
5300 (org-set-local 'org-latex-and-specials-regexp nil)
5301 (let*
5302 ((matchers (plist-get org-format-latex-options :matchers))
5303 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5304 org-latex-regexps)))
5305 (options (org-combine-plists (org-default-export-plist)
5306 (org-infile-export-plist)))
5307 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5308 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5309 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5310 (org-export-html-expand (plist-get options :expand-quoted-html))
5311 (org-export-with-special-strings (plist-get options :special-strings))
5312 (re-sub
5313 (cond
5314 ((equal org-export-with-sub-superscripts '{})
5315 (list org-match-substring-with-braces-regexp))
5316 (org-export-with-sub-superscripts
5317 (list org-match-substring-regexp))
5318 (t nil)))
5319 (re-latex
5320 (if org-export-with-LaTeX-fragments
5321 (mapcar (lambda (x) (nth 1 x)) latexs)))
5322 (re-macros
5323 (if org-export-with-TeX-macros
5324 (list (concat "\\\\"
5325 (regexp-opt
5326 (append (mapcar 'car org-html-entities)
5327 (if (boundp 'org-latex-entities)
5328 org-latex-entities nil))
5329 'words))) ; FIXME
5331 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5332 (re-special (if org-export-with-special-strings
5333 (mapcar (lambda (x) (car x))
5334 org-export-html-special-string-regexps)))
5335 (re-rest
5336 (delq nil
5337 (list
5338 (if org-export-html-expand "@<[^>\n]+>")
5339 ))))
5340 (org-set-local
5341 'org-latex-and-specials-regexp
5342 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5343 re-rest) "\\|")))))
5345 (defface org-latex-and-export-specials
5346 (let ((font (cond ((assq :inherit custom-face-attributes)
5347 '(:inherit underline))
5348 (t '(:underline t)))))
5349 `((((class grayscale) (background light))
5350 (:foreground "DimGray" ,@font))
5351 (((class grayscale) (background dark))
5352 (:foreground "LightGray" ,@font))
5353 (((class color) (background light))
5354 (:foreground "SaddleBrown"))
5355 (((class color) (background dark))
5356 (:foreground "burlywood"))
5357 (t (,@font))))
5358 "Face used to highlight math latex and other special exporter stuff."
5359 :group 'org-faces)
5361 (defun org-do-latex-and-special-faces (limit)
5362 "Run through the buffer and add overlays to links."
5363 (when org-latex-and-specials-regexp
5364 (let (rtn d)
5365 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5366 limit t))
5367 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5368 'face))
5369 '(org-code org-verbatim underline)))
5370 (progn
5371 (setq rtn t
5372 d (cond ((member (char-after (1+ (match-beginning 0)))
5373 '(?_ ?^)) 1)
5374 (t 0)))
5375 (font-lock-prepend-text-property
5376 (+ d (match-beginning 0)) (match-end 0)
5377 'face 'org-latex-and-export-specials)
5378 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5379 '(font-lock-multiline t)))))
5380 rtn)))
5382 (defun org-restart-font-lock ()
5383 "Restart font-lock-mode, to force refontification."
5384 (when (and (boundp 'font-lock-mode) font-lock-mode)
5385 (font-lock-mode -1)
5386 (font-lock-mode 1)))
5388 (defun org-all-targets (&optional radio)
5389 "Return a list of all targets in this file.
5390 With optional argument RADIO, only find radio targets."
5391 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5392 rtn)
5393 (save-excursion
5394 (goto-char (point-min))
5395 (while (re-search-forward re nil t)
5396 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5397 rtn)))
5399 (defun org-make-target-link-regexp (targets)
5400 "Make regular expression matching all strings in TARGETS.
5401 The regular expression finds the targets also if there is a line break
5402 between words."
5403 (and targets
5404 (concat
5405 "\\<\\("
5406 (mapconcat
5407 (lambda (x)
5408 (while (string-match " +" x)
5409 (setq x (replace-match "\\s-+" t t x)))
5411 targets
5412 "\\|")
5413 "\\)\\>")))
5415 (defun org-activate-tags (limit)
5416 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5417 (progn
5418 (add-text-properties (match-beginning 1) (match-end 1)
5419 (list 'mouse-face 'highlight
5420 'rear-nonsticky org-nonsticky-props
5421 'keymap org-mouse-map))
5422 t)))
5424 (defun org-outline-level ()
5425 (save-excursion
5426 (looking-at outline-regexp)
5427 (if (match-beginning 1)
5428 (+ (org-get-string-indentation (match-string 1)) 1000)
5429 (1- (- (match-end 0) (match-beginning 0))))))
5431 (defvar org-font-lock-keywords nil)
5433 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5434 "Regular expression matching a property line.")
5436 (defun org-set-font-lock-defaults ()
5437 (let* ((em org-fontify-emphasized-text)
5438 (lk org-activate-links)
5439 (org-font-lock-extra-keywords
5440 (list
5441 ;; Headlines
5442 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5443 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5444 ;; Table lines
5445 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5446 (1 'org-table t))
5447 ;; Table internals
5448 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5449 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5450 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5451 ;; Drawers
5452 (list org-drawer-regexp '(0 'org-special-keyword t))
5453 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5454 ;; Properties
5455 (list org-property-re
5456 '(1 'org-special-keyword t)
5457 '(3 'org-property-value t))
5458 (if org-format-transports-properties-p
5459 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5460 ;; Links
5461 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5462 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5463 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5464 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5465 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5466 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5467 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5468 '(org-hide-wide-columns (0 nil append))
5469 ;; TODO lines
5470 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5471 '(1 (org-get-todo-face 1) t))
5472 ;; DONE
5473 (if org-fontify-done-headline
5474 (list (concat "^[*]+ +\\<\\("
5475 (mapconcat 'regexp-quote org-done-keywords "\\|")
5476 "\\)\\(.*\\)")
5477 '(2 'org-headline-done t))
5478 nil)
5479 ;; Priorities
5480 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5481 ;; Special keywords
5482 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5483 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5484 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5485 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5486 ;; Emphasis
5487 (if em
5488 (if (featurep 'xemacs)
5489 '(org-do-emphasis-faces (0 nil append))
5490 '(org-do-emphasis-faces)))
5491 ;; Checkboxes
5492 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5493 2 'bold prepend)
5494 (if org-provide-checkbox-statistics
5495 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5496 (0 (org-get-checkbox-statistics-face) t)))
5497 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5498 '(1 'org-archived prepend))
5499 ;; Specials
5500 '(org-do-latex-and-special-faces)
5501 ;; Code
5502 '(org-activate-code (1 'org-code t))
5503 ;; COMMENT
5504 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5505 "\\|" org-quote-string "\\)\\>")
5506 '(1 'org-special-keyword t))
5507 '("^#.*" (0 'font-lock-comment-face t))
5509 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5510 ;; Now set the full font-lock-keywords
5511 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5512 (org-set-local 'font-lock-defaults
5513 '(org-font-lock-keywords t nil nil backward-paragraph))
5514 (kill-local-variable 'font-lock-keywords) nil))
5516 (defvar org-m nil)
5517 (defvar org-l nil)
5518 (defvar org-f nil)
5519 (defun org-get-level-face (n)
5520 "Get the right face for match N in font-lock matching of healdines."
5521 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5522 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5523 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5524 (cond
5525 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5526 ((eq n 2) org-f)
5527 (t (if org-level-color-stars-only nil org-f))))
5529 (defun org-get-todo-face (kwd)
5530 "Get the right face for a TODO keyword KWD.
5531 If KWD is a number, get the corresponding match group."
5532 (if (numberp kwd) (setq kwd (match-string kwd)))
5533 (or (cdr (assoc kwd org-todo-keyword-faces))
5534 (and (member kwd org-done-keywords) 'org-done)
5535 'org-todo))
5537 (defun org-unfontify-region (beg end &optional maybe_loudly)
5538 "Remove fontification and activation overlays from links."
5539 (font-lock-default-unfontify-region beg end)
5540 (let* ((buffer-undo-list t)
5541 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5542 (inhibit-modification-hooks t)
5543 deactivate-mark buffer-file-name buffer-file-truename)
5544 (remove-text-properties beg end
5545 '(mouse-face t keymap t org-linked-text t
5546 invisible t intangible t))))
5548 ;;;; Visibility cycling, including org-goto and indirect buffer
5550 ;;; Cycling
5552 (defvar org-cycle-global-status nil)
5553 (make-variable-buffer-local 'org-cycle-global-status)
5554 (defvar org-cycle-subtree-status nil)
5555 (make-variable-buffer-local 'org-cycle-subtree-status)
5557 ;;;###autoload
5558 (defun org-cycle (&optional arg)
5559 "Visibility cycling for Org-mode.
5561 - When this function is called with a prefix argument, rotate the entire
5562 buffer through 3 states (global cycling)
5563 1. OVERVIEW: Show only top-level headlines.
5564 2. CONTENTS: Show all headlines of all levels, but no body text.
5565 3. SHOW ALL: Show everything.
5567 - When point is at the beginning of a headline, rotate the subtree started
5568 by this line through 3 different states (local cycling)
5569 1. FOLDED: Only the main headline is shown.
5570 2. CHILDREN: The main headline and the direct children are shown.
5571 From this state, you can move to one of the children
5572 and zoom in further.
5573 3. SUBTREE: Show the entire subtree, including body text.
5575 - When there is a numeric prefix, go up to a heading with level ARG, do
5576 a `show-subtree' and return to the previous cursor position. If ARG
5577 is negative, go up that many levels.
5579 - When point is not at the beginning of a headline, execute
5580 `indent-relative', like TAB normally does. See the option
5581 `org-cycle-emulate-tab' for details.
5583 - Special case: if point is at the beginning of the buffer and there is
5584 no headline in line 1, this function will act as if called with prefix arg.
5585 But only if also the variable `org-cycle-global-at-bob' is t."
5586 (interactive "P")
5587 (let* ((outline-regexp
5588 (if (and (org-mode-p) org-cycle-include-plain-lists)
5589 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5590 outline-regexp))
5591 (bob-special (and org-cycle-global-at-bob (bobp)
5592 (not (looking-at outline-regexp))))
5593 (org-cycle-hook
5594 (if bob-special
5595 (delq 'org-optimize-window-after-visibility-change
5596 (copy-sequence org-cycle-hook))
5597 org-cycle-hook))
5598 (pos (point)))
5600 (if (or bob-special (equal arg '(4)))
5601 ;; special case: use global cycling
5602 (setq arg t))
5604 (cond
5606 ((org-at-table-p 'any)
5607 ;; Enter the table or move to the next field in the table
5608 (or (org-table-recognize-table.el)
5609 (progn
5610 (if arg (org-table-edit-field t)
5611 (org-table-justify-field-maybe)
5612 (call-interactively 'org-table-next-field)))))
5614 ((eq arg t) ;; Global cycling
5616 (cond
5617 ((and (eq last-command this-command)
5618 (eq org-cycle-global-status 'overview))
5619 ;; We just created the overview - now do table of contents
5620 ;; This can be slow in very large buffers, so indicate action
5621 (message "CONTENTS...")
5622 (org-content)
5623 (message "CONTENTS...done")
5624 (setq org-cycle-global-status 'contents)
5625 (run-hook-with-args 'org-cycle-hook 'contents))
5627 ((and (eq last-command this-command)
5628 (eq org-cycle-global-status 'contents))
5629 ;; We just showed the table of contents - now show everything
5630 (show-all)
5631 (message "SHOW ALL")
5632 (setq org-cycle-global-status 'all)
5633 (run-hook-with-args 'org-cycle-hook 'all))
5636 ;; Default action: go to overview
5637 (org-overview)
5638 (message "OVERVIEW")
5639 (setq org-cycle-global-status 'overview)
5640 (run-hook-with-args 'org-cycle-hook 'overview))))
5642 ((and org-drawers org-drawer-regexp
5643 (save-excursion
5644 (beginning-of-line 1)
5645 (looking-at org-drawer-regexp)))
5646 ;; Toggle block visibility
5647 (org-flag-drawer
5648 (not (get-char-property (match-end 0) 'invisible))))
5650 ((integerp arg)
5651 ;; Show-subtree, ARG levels up from here.
5652 (save-excursion
5653 (org-back-to-heading)
5654 (outline-up-heading (if (< arg 0) (- arg)
5655 (- (funcall outline-level) arg)))
5656 (org-show-subtree)))
5658 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5659 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5660 ;; At a heading: rotate between three different views
5661 (org-back-to-heading)
5662 (let ((goal-column 0) eoh eol eos)
5663 ;; First, some boundaries
5664 (save-excursion
5665 (org-back-to-heading)
5666 (save-excursion
5667 (beginning-of-line 2)
5668 (while (and (not (eobp)) ;; this is like `next-line'
5669 (get-char-property (1- (point)) 'invisible))
5670 (beginning-of-line 2)) (setq eol (point)))
5671 (outline-end-of-heading) (setq eoh (point))
5672 (org-end-of-subtree t)
5673 (unless (eobp)
5674 (skip-chars-forward " \t\n")
5675 (beginning-of-line 1) ; in case this is an item
5677 (setq eos (1- (point))))
5678 ;; Find out what to do next and set `this-command'
5679 (cond
5680 ((= eos eoh)
5681 ;; Nothing is hidden behind this heading
5682 (message "EMPTY ENTRY")
5683 (setq org-cycle-subtree-status nil)
5684 (save-excursion
5685 (goto-char eos)
5686 (outline-next-heading)
5687 (if (org-invisible-p) (org-flag-heading nil))))
5688 ((or (>= eol eos)
5689 (not (string-match "\\S-" (buffer-substring eol eos))))
5690 ;; Entire subtree is hidden in one line: open it
5691 (org-show-entry)
5692 (show-children)
5693 (message "CHILDREN")
5694 (save-excursion
5695 (goto-char eos)
5696 (outline-next-heading)
5697 (if (org-invisible-p) (org-flag-heading nil)))
5698 (setq org-cycle-subtree-status 'children)
5699 (run-hook-with-args 'org-cycle-hook 'children))
5700 ((and (eq last-command this-command)
5701 (eq org-cycle-subtree-status 'children))
5702 ;; We just showed the children, now show everything.
5703 (org-show-subtree)
5704 (message "SUBTREE")
5705 (setq org-cycle-subtree-status 'subtree)
5706 (run-hook-with-args 'org-cycle-hook 'subtree))
5708 ;; Default action: hide the subtree.
5709 (hide-subtree)
5710 (message "FOLDED")
5711 (setq org-cycle-subtree-status 'folded)
5712 (run-hook-with-args 'org-cycle-hook 'folded)))))
5714 ;; TAB emulation
5715 (buffer-read-only (org-back-to-heading))
5717 ((org-try-cdlatex-tab))
5719 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5720 (or (not (bolp))
5721 (not (looking-at outline-regexp))))
5722 (call-interactively (global-key-binding "\t")))
5724 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5725 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5726 (or (and (eq org-cycle-emulate-tab 'white)
5727 (= (match-end 0) (point-at-eol)))
5728 (and (eq org-cycle-emulate-tab 'whitestart)
5729 (>= (match-end 0) pos))))
5731 (eq org-cycle-emulate-tab t))
5732 ; (if (and (looking-at "[ \n\r\t]")
5733 ; (string-match "^[ \t]*$" (buffer-substring
5734 ; (point-at-bol) (point))))
5735 ; (progn
5736 ; (beginning-of-line 1)
5737 ; (and (looking-at "[ \t]+") (replace-match ""))))
5738 (call-interactively (global-key-binding "\t")))
5740 (t (save-excursion
5741 (org-back-to-heading)
5742 (org-cycle))))))
5744 ;;;###autoload
5745 (defun org-global-cycle (&optional arg)
5746 "Cycle the global visibility. For details see `org-cycle'."
5747 (interactive "P")
5748 (let ((org-cycle-include-plain-lists
5749 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5750 (if (integerp arg)
5751 (progn
5752 (show-all)
5753 (hide-sublevels arg)
5754 (setq org-cycle-global-status 'contents))
5755 (org-cycle '(4)))))
5757 (defun org-overview ()
5758 "Switch to overview mode, shoing only top-level headlines.
5759 Really, this shows all headlines with level equal or greater than the level
5760 of the first headline in the buffer. This is important, because if the
5761 first headline is not level one, then (hide-sublevels 1) gives confusing
5762 results."
5763 (interactive)
5764 (let ((level (save-excursion
5765 (goto-char (point-min))
5766 (if (re-search-forward (concat "^" outline-regexp) nil t)
5767 (progn
5768 (goto-char (match-beginning 0))
5769 (funcall outline-level))))))
5770 (and level (hide-sublevels level))))
5772 (defun org-content (&optional arg)
5773 "Show all headlines in the buffer, like a table of contents.
5774 With numerical argument N, show content up to level N."
5775 (interactive "P")
5776 (save-excursion
5777 ;; Visit all headings and show their offspring
5778 (and (integerp arg) (org-overview))
5779 (goto-char (point-max))
5780 (catch 'exit
5781 (while (and (progn (condition-case nil
5782 (outline-previous-visible-heading 1)
5783 (error (goto-char (point-min))))
5785 (looking-at outline-regexp))
5786 (if (integerp arg)
5787 (show-children (1- arg))
5788 (show-branches))
5789 (if (bobp) (throw 'exit nil))))))
5792 (defun org-optimize-window-after-visibility-change (state)
5793 "Adjust the window after a change in outline visibility.
5794 This function is the default value of the hook `org-cycle-hook'."
5795 (when (get-buffer-window (current-buffer))
5796 (cond
5797 ; ((eq state 'overview) (org-first-headline-recenter 1))
5798 ; ((eq state 'overview) (org-beginning-of-line))
5799 ((eq state 'content) nil)
5800 ((eq state 'all) nil)
5801 ((eq state 'folded) nil)
5802 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5803 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5805 (defun org-compact-display-after-subtree-move ()
5806 (let (beg end)
5807 (save-excursion
5808 (if (org-up-heading-safe)
5809 (progn
5810 (hide-subtree)
5811 (show-entry)
5812 (show-children)
5813 (org-cycle-show-empty-lines 'children)
5814 (org-cycle-hide-drawers 'children))
5815 (org-overview)))))
5817 (defun org-cycle-show-empty-lines (state)
5818 "Show empty lines above all visible headlines.
5819 The region to be covered depends on STATE when called through
5820 `org-cycle-hook'. Lisp program can use t for STATE to get the
5821 entire buffer covered. Note that an empty line is only shown if there
5822 are at least `org-cycle-separator-lines' empty lines before the headeline."
5823 (when (> org-cycle-separator-lines 0)
5824 (save-excursion
5825 (let* ((n org-cycle-separator-lines)
5826 (re (cond
5827 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5828 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5829 (t (let ((ns (number-to-string (- n 2))))
5830 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5831 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5832 beg end)
5833 (cond
5834 ((memq state '(overview contents t))
5835 (setq beg (point-min) end (point-max)))
5836 ((memq state '(children folded))
5837 (setq beg (point) end (progn (org-end-of-subtree t t)
5838 (beginning-of-line 2)
5839 (point)))))
5840 (when beg
5841 (goto-char beg)
5842 (while (re-search-forward re end t)
5843 (if (not (get-char-property (match-end 1) 'invisible))
5844 (outline-flag-region
5845 (match-beginning 1) (match-end 1) nil)))))))
5846 ;; Never hide empty lines at the end of the file.
5847 (save-excursion
5848 (goto-char (point-max))
5849 (outline-previous-heading)
5850 (outline-end-of-heading)
5851 (if (and (looking-at "[ \t\n]+")
5852 (= (match-end 0) (point-max)))
5853 (outline-flag-region (point) (match-end 0) nil))))
5855 (defun org-subtree-end-visible-p ()
5856 "Is the end of the current subtree visible?"
5857 (pos-visible-in-window-p
5858 (save-excursion (org-end-of-subtree t) (point))))
5860 (defun org-first-headline-recenter (&optional N)
5861 "Move cursor to the first headline and recenter the headline.
5862 Optional argument N means, put the headline into the Nth line of the window."
5863 (goto-char (point-min))
5864 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5865 (beginning-of-line)
5866 (recenter (prefix-numeric-value N))))
5868 ;;; Org-goto
5870 (defvar org-goto-window-configuration nil)
5871 (defvar org-goto-marker nil)
5872 (defvar org-goto-map
5873 (let ((map (make-sparse-keymap)))
5874 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5875 (while (setq cmd (pop cmds))
5876 (substitute-key-definition cmd cmd map global-map)))
5877 (suppress-keymap map)
5878 (org-defkey map "\C-m" 'org-goto-ret)
5879 (org-defkey map [(return)] 'org-goto-ret)
5880 (org-defkey map [(left)] 'org-goto-left)
5881 (org-defkey map [(right)] 'org-goto-right)
5882 (org-defkey map [(control ?g)] 'org-goto-quit)
5883 (org-defkey map "\C-i" 'org-cycle)
5884 (org-defkey map [(tab)] 'org-cycle)
5885 (org-defkey map [(down)] 'outline-next-visible-heading)
5886 (org-defkey map [(up)] 'outline-previous-visible-heading)
5887 (if org-goto-auto-isearch
5888 (if (fboundp 'define-key-after)
5889 (define-key-after map [t] 'org-goto-local-auto-isearch)
5890 nil)
5891 (org-defkey map "q" 'org-goto-quit)
5892 (org-defkey map "n" 'outline-next-visible-heading)
5893 (org-defkey map "p" 'outline-previous-visible-heading)
5894 (org-defkey map "f" 'outline-forward-same-level)
5895 (org-defkey map "b" 'outline-backward-same-level)
5896 (org-defkey map "u" 'outline-up-heading))
5897 (org-defkey map "/" 'org-occur)
5898 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5899 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5900 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5901 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5902 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5903 map))
5905 (defconst org-goto-help
5906 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5907 RET=jump to location [Q]uit and return to previous location
5908 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5910 (defvar org-goto-start-pos) ; dynamically scoped parameter
5912 (defun org-goto (&optional alternative-interface)
5913 "Look up a different location in the current file, keeping current visibility.
5915 When you want look-up or go to a different location in a document, the
5916 fastest way is often to fold the entire buffer and then dive into the tree.
5917 This method has the disadvantage, that the previous location will be folded,
5918 which may not be what you want.
5920 This command works around this by showing a copy of the current buffer
5921 in an indirect buffer, in overview mode. You can dive into the tree in
5922 that copy, use org-occur and incremental search to find a location.
5923 When pressing RET or `Q', the command returns to the original buffer in
5924 which the visibility is still unchanged. After RET is will also jump to
5925 the location selected in the indirect buffer and expose the
5926 the headline hierarchy above."
5927 (interactive "P")
5928 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
5929 (org-refile-use-outline-path t)
5930 (interface
5931 (if (not alternative-interface)
5932 org-goto-interface
5933 (if (eq org-goto-interface 'outline)
5934 'outline-path-completion
5935 'outline)))
5936 (org-goto-start-pos (point))
5937 (selected-point
5938 (if (eq interface 'outline)
5939 (car (org-get-location (current-buffer) org-goto-help))
5940 (nth 3 (org-refile-get-location "Goto: ")))))
5941 (if selected-point
5942 (progn
5943 (org-mark-ring-push org-goto-start-pos)
5944 (goto-char selected-point)
5945 (if (or (org-invisible-p) (org-invisible-p2))
5946 (org-show-context 'org-goto)))
5947 (message "Quit"))))
5949 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5950 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5952 (defun org-get-location (buf help)
5953 "Let the user select a location in the Org-mode buffer BUF.
5954 This function uses a recursive edit. It returns the selected position
5955 or nil."
5956 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5957 (isearch-hide-immediately nil)
5958 (isearch-search-fun-function
5959 (lambda () 'org-goto-local-search-forward-headings))
5960 (org-goto-selected-point org-goto-exit-command))
5961 (save-excursion
5962 (save-window-excursion
5963 (delete-other-windows)
5964 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5965 (switch-to-buffer
5966 (condition-case nil
5967 (make-indirect-buffer (current-buffer) "*org-goto*")
5968 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5969 (with-output-to-temp-buffer "*Help*"
5970 (princ help))
5971 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
5972 (setq buffer-read-only nil)
5973 (let ((org-startup-truncated t)
5974 (org-startup-folded nil)
5975 (org-startup-align-all-tables nil))
5976 (org-mode)
5977 (org-overview))
5978 (setq buffer-read-only t)
5979 (if (and (boundp 'org-goto-start-pos)
5980 (integer-or-marker-p org-goto-start-pos))
5981 (let ((org-show-hierarchy-above t)
5982 (org-show-siblings t)
5983 (org-show-following-heading t))
5984 (goto-char org-goto-start-pos)
5985 (and (org-invisible-p) (org-show-context)))
5986 (goto-char (point-min)))
5987 (org-beginning-of-line)
5988 (message "Select location and press RET")
5989 (use-local-map org-goto-map)
5990 (recursive-edit)
5992 (kill-buffer "*org-goto*")
5993 (cons org-goto-selected-point org-goto-exit-command)))
5995 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5996 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5997 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5998 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6000 (defun org-goto-local-search-forward-headings (string bound noerror)
6001 "Search and make sure that anu matches are in headlines."
6002 (catch 'return
6003 (while (search-forward string bound noerror)
6004 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6005 (and (member :headline context)
6006 (not (member :tags context))))
6007 (throw 'return (point))))))
6009 (defun org-goto-local-auto-isearch ()
6010 "Start isearch."
6011 (interactive)
6012 (goto-char (point-min))
6013 (let ((keys (this-command-keys)))
6014 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6015 (isearch-mode t)
6016 (isearch-process-search-char (string-to-char keys)))))
6018 (defun org-goto-ret (&optional arg)
6019 "Finish `org-goto' by going to the new location."
6020 (interactive "P")
6021 (setq org-goto-selected-point (point)
6022 org-goto-exit-command 'return)
6023 (throw 'exit nil))
6025 (defun org-goto-left ()
6026 "Finish `org-goto' by going to the new location."
6027 (interactive)
6028 (if (org-on-heading-p)
6029 (progn
6030 (beginning-of-line 1)
6031 (setq org-goto-selected-point (point)
6032 org-goto-exit-command 'left)
6033 (throw 'exit nil))
6034 (error "Not on a heading")))
6036 (defun org-goto-right ()
6037 "Finish `org-goto' by going to the new location."
6038 (interactive)
6039 (if (org-on-heading-p)
6040 (progn
6041 (setq org-goto-selected-point (point)
6042 org-goto-exit-command 'right)
6043 (throw 'exit nil))
6044 (error "Not on a heading")))
6046 (defun org-goto-quit ()
6047 "Finish `org-goto' without cursor motion."
6048 (interactive)
6049 (setq org-goto-selected-point nil)
6050 (setq org-goto-exit-command 'quit)
6051 (throw 'exit nil))
6053 ;;; Indirect buffer display of subtrees
6055 (defvar org-indirect-dedicated-frame nil
6056 "This is the frame being used for indirect tree display.")
6057 (defvar org-last-indirect-buffer nil)
6059 (defun org-tree-to-indirect-buffer (&optional arg)
6060 "Create indirect buffer and narrow it to current subtree.
6061 With numerical prefix ARG, go up to this level and then take that tree.
6062 If ARG is negative, go up that many levels.
6063 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6064 indirect buffer previously made with this command, to avoid proliferation of
6065 indirect buffers. However, when you call the command with a `C-u' prefix, or
6066 when `org-indirect-buffer-display' is `new-frame', the last buffer
6067 is kept so that you can work with several indirect buffers at the same time.
6068 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6069 requests that a new frame be made for the new buffer, so that the dedicated
6070 frame is not changed."
6071 (interactive "P")
6072 (let ((cbuf (current-buffer))
6073 (cwin (selected-window))
6074 (pos (point))
6075 beg end level heading ibuf)
6076 (save-excursion
6077 (org-back-to-heading t)
6078 (when (numberp arg)
6079 (setq level (org-outline-level))
6080 (if (< arg 0) (setq arg (+ level arg)))
6081 (while (> (setq level (org-outline-level)) arg)
6082 (outline-up-heading 1 t)))
6083 (setq beg (point)
6084 heading (org-get-heading))
6085 (org-end-of-subtree t) (setq end (point)))
6086 (if (and (buffer-live-p org-last-indirect-buffer)
6087 (not (eq org-indirect-buffer-display 'new-frame))
6088 (not arg))
6089 (kill-buffer org-last-indirect-buffer))
6090 (setq ibuf (org-get-indirect-buffer cbuf)
6091 org-last-indirect-buffer ibuf)
6092 (cond
6093 ((or (eq org-indirect-buffer-display 'new-frame)
6094 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6095 (select-frame (make-frame))
6096 (delete-other-windows)
6097 (switch-to-buffer ibuf)
6098 (org-set-frame-title heading))
6099 ((eq org-indirect-buffer-display 'dedicated-frame)
6100 (raise-frame
6101 (select-frame (or (and org-indirect-dedicated-frame
6102 (frame-live-p org-indirect-dedicated-frame)
6103 org-indirect-dedicated-frame)
6104 (setq org-indirect-dedicated-frame (make-frame)))))
6105 (delete-other-windows)
6106 (switch-to-buffer ibuf)
6107 (org-set-frame-title (concat "Indirect: " heading)))
6108 ((eq org-indirect-buffer-display 'current-window)
6109 (switch-to-buffer ibuf))
6110 ((eq org-indirect-buffer-display 'other-window)
6111 (pop-to-buffer ibuf))
6112 (t (error "Invalid value.")))
6113 (if (featurep 'xemacs)
6114 (save-excursion (org-mode) (turn-on-font-lock)))
6115 (narrow-to-region beg end)
6116 (show-all)
6117 (goto-char pos)
6118 (and (window-live-p cwin) (select-window cwin))))
6120 (defun org-get-indirect-buffer (&optional buffer)
6121 (setq buffer (or buffer (current-buffer)))
6122 (let ((n 1) (base (buffer-name buffer)) bname)
6123 (while (buffer-live-p
6124 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6125 (setq n (1+ n)))
6126 (condition-case nil
6127 (make-indirect-buffer buffer bname 'clone)
6128 (error (make-indirect-buffer buffer bname)))))
6130 (defun org-set-frame-title (title)
6131 "Set the title of the current frame to the string TITLE."
6132 ;; FIXME: how to name a single frame in XEmacs???
6133 (unless (featurep 'xemacs)
6134 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6136 ;;;; Structure editing
6138 ;;; Inserting headlines
6140 (defun org-insert-heading (&optional force-heading)
6141 "Insert a new heading or item with same depth at point.
6142 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6143 If point is at the beginning of a headline, insert a sibling before the
6144 current headline. If point is in the middle of a headline, split the headline
6145 at that position and make the rest of the headline part of the sibling below
6146 the current headline."
6147 (interactive "P")
6148 (if (= (buffer-size) 0)
6149 (insert "\n* ")
6150 (when (or force-heading (not (org-insert-item)))
6151 (let* ((head (save-excursion
6152 (condition-case nil
6153 (progn
6154 (org-back-to-heading)
6155 (match-string 0))
6156 (error "*"))))
6157 (blank (cdr (assq 'heading org-blank-before-new-entry)))
6158 pos)
6159 (cond
6160 ((and (org-on-heading-p) (bolp)
6161 (or (bobp)
6162 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6163 (open-line (if blank 2 1)))
6164 ((and (bolp)
6165 (or (bobp)
6166 (save-excursion
6167 (backward-char 1) (not (org-invisible-p)))))
6168 nil)
6169 (t (newline (if blank 2 1))))
6170 (insert head) (just-one-space)
6171 (setq pos (point))
6172 (end-of-line 1)
6173 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6174 (run-hooks 'org-insert-heading-hook)))))
6176 (defun org-insert-heading-after-current ()
6177 "Insert a new heading with same level as current, after current subtree."
6178 (interactive)
6179 (org-back-to-heading)
6180 (org-insert-heading)
6181 (org-move-subtree-down)
6182 (end-of-line 1))
6184 (defun org-insert-todo-heading (arg)
6185 "Insert a new heading with the same level and TODO state as current heading.
6186 If the heading has no TODO state, or if the state is DONE, use the first
6187 state (TODO by default). Also with prefix arg, force first state."
6188 (interactive "P")
6189 (when (not (org-insert-item 'checkbox))
6190 (org-insert-heading)
6191 (save-excursion
6192 (org-back-to-heading)
6193 (outline-previous-heading)
6194 (looking-at org-todo-line-regexp))
6195 (if (or arg
6196 (not (match-beginning 2))
6197 (member (match-string 2) org-done-keywords))
6198 (insert (car org-todo-keywords-1) " ")
6199 (insert (match-string 2) " "))))
6201 (defun org-insert-subheading (arg)
6202 "Insert a new subheading and demote it.
6203 Works for outline headings and for plain lists alike."
6204 (interactive "P")
6205 (org-insert-heading arg)
6206 (cond
6207 ((org-on-heading-p) (org-do-demote))
6208 ((org-at-item-p) (org-indent-item 1))))
6210 (defun org-insert-todo-subheading (arg)
6211 "Insert a new subheading with TODO keyword or checkbox and demote it.
6212 Works for outline headings and for plain lists alike."
6213 (interactive "P")
6214 (org-insert-todo-heading arg)
6215 (cond
6216 ((org-on-heading-p) (org-do-demote))
6217 ((org-at-item-p) (org-indent-item 1))))
6219 ;;; Promotion and Demotion
6221 (defun org-promote-subtree ()
6222 "Promote the entire subtree.
6223 See also `org-promote'."
6224 (interactive)
6225 (save-excursion
6226 (org-map-tree 'org-promote))
6227 (org-fix-position-after-promote))
6229 (defun org-demote-subtree ()
6230 "Demote the entire subtree. See `org-demote'.
6231 See also `org-promote'."
6232 (interactive)
6233 (save-excursion
6234 (org-map-tree 'org-demote))
6235 (org-fix-position-after-promote))
6238 (defun org-do-promote ()
6239 "Promote the current heading higher up the tree.
6240 If the region is active in `transient-mark-mode', promote all headings
6241 in the region."
6242 (interactive)
6243 (save-excursion
6244 (if (org-region-active-p)
6245 (org-map-region 'org-promote (region-beginning) (region-end))
6246 (org-promote)))
6247 (org-fix-position-after-promote))
6249 (defun org-do-demote ()
6250 "Demote the current heading lower down the tree.
6251 If the region is active in `transient-mark-mode', demote all headings
6252 in the region."
6253 (interactive)
6254 (save-excursion
6255 (if (org-region-active-p)
6256 (org-map-region 'org-demote (region-beginning) (region-end))
6257 (org-demote)))
6258 (org-fix-position-after-promote))
6260 (defun org-fix-position-after-promote ()
6261 "Make sure that after pro/demotion cursor position is right."
6262 (let ((pos (point)))
6263 (when (save-excursion
6264 (beginning-of-line 1)
6265 (looking-at org-todo-line-regexp)
6266 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6267 (cond ((eobp) (insert " "))
6268 ((eolp) (insert " "))
6269 ((equal (char-after) ?\ ) (forward-char 1))))))
6271 (defun org-reduced-level (l)
6272 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6274 (defun org-get-legal-level (level &optional change)
6275 "Rectify a level change under the influence of `org-odd-levels-only'
6276 LEVEL is a current level, CHANGE is by how much the level should be
6277 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6278 even level numbers will become the next higher odd number."
6279 (if org-odd-levels-only
6280 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6281 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6282 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6283 (max 1 (+ level change))))
6285 (defun org-promote ()
6286 "Promote the current heading higher up the tree.
6287 If the region is active in `transient-mark-mode', promote all headings
6288 in the region."
6289 (org-back-to-heading t)
6290 (let* ((level (save-match-data (funcall outline-level)))
6291 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
6292 (diff (abs (- level (length up-head) -1))))
6293 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6294 (replace-match up-head nil t)
6295 ;; Fixup tag positioning
6296 (and org-auto-align-tags (org-set-tags nil t))
6297 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
6299 (defun org-demote ()
6300 "Demote the current heading lower down the tree.
6301 If the region is active in `transient-mark-mode', demote all headings
6302 in the region."
6303 (org-back-to-heading t)
6304 (let* ((level (save-match-data (funcall outline-level)))
6305 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
6306 (diff (abs (- level (length down-head) -1))))
6307 (replace-match down-head nil t)
6308 ;; Fixup tag positioning
6309 (and org-auto-align-tags (org-set-tags nil t))
6310 (if org-adapt-indentation (org-fixup-indentation diff))))
6312 (defun org-map-tree (fun)
6313 "Call FUN for every heading underneath the current one."
6314 (org-back-to-heading)
6315 (let ((level (funcall outline-level)))
6316 (save-excursion
6317 (funcall fun)
6318 (while (and (progn
6319 (outline-next-heading)
6320 (> (funcall outline-level) level))
6321 (not (eobp)))
6322 (funcall fun)))))
6324 (defun org-map-region (fun beg end)
6325 "Call FUN for every heading between BEG and END."
6326 (let ((org-ignore-region t))
6327 (save-excursion
6328 (setq end (copy-marker end))
6329 (goto-char beg)
6330 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6331 (< (point) end))
6332 (funcall fun))
6333 (while (and (progn
6334 (outline-next-heading)
6335 (< (point) end))
6336 (not (eobp)))
6337 (funcall fun)))))
6339 (defun org-fixup-indentation (diff)
6340 "Change the indentation in the current entry by DIFF
6341 However, if any line in the current entry has no indentation, or if it
6342 would end up with no indentation after the change, nothing at all is done."
6343 (save-excursion
6344 (let ((end (save-excursion (outline-next-heading)
6345 (point-marker)))
6346 (prohibit (if (> diff 0)
6347 "^\\S-"
6348 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6349 col)
6350 (unless (save-excursion (end-of-line 1)
6351 (re-search-forward prohibit end t))
6352 (while (and (< (point) end)
6353 (re-search-forward "^[ \t]+" end t))
6354 (goto-char (match-end 0))
6355 (setq col (current-column))
6356 (if (< diff 0) (replace-match ""))
6357 (indent-to (+ diff col))))
6358 (move-marker end nil))))
6360 (defun org-convert-to-odd-levels ()
6361 "Convert an org-mode file with all levels allowed to one with odd levels.
6362 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6363 level 5 etc."
6364 (interactive)
6365 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6366 (let ((org-odd-levels-only nil) n)
6367 (save-excursion
6368 (goto-char (point-min))
6369 (while (re-search-forward "^\\*\\*+ " nil t)
6370 (setq n (- (length (match-string 0)) 2))
6371 (while (>= (setq n (1- n)) 0)
6372 (org-demote))
6373 (end-of-line 1))))))
6376 (defun org-convert-to-oddeven-levels ()
6377 "Convert an org-mode file with only odd levels to one with odd and even levels.
6378 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6379 section with an even level, conversion would destroy the structure of the file. An error
6380 is signaled in this case."
6381 (interactive)
6382 (goto-char (point-min))
6383 ;; First check if there are no even levels
6384 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6385 (org-show-context t)
6386 (error "Not all levels are odd in this file. Conversion not possible."))
6387 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6388 (let ((org-odd-levels-only nil) n)
6389 (save-excursion
6390 (goto-char (point-min))
6391 (while (re-search-forward "^\\*\\*+ " nil t)
6392 (setq n (/ (1- (length (match-string 0))) 2))
6393 (while (>= (setq n (1- n)) 0)
6394 (org-promote))
6395 (end-of-line 1))))))
6397 (defun org-tr-level (n)
6398 "Make N odd if required."
6399 (if org-odd-levels-only (1+ (/ n 2)) n))
6401 ;;; Vertical tree motion, cutting and pasting of subtrees
6403 (defun org-move-subtree-up (&optional arg)
6404 "Move the current subtree up past ARG headlines of the same level."
6405 (interactive "p")
6406 (org-move-subtree-down (- (prefix-numeric-value arg))))
6408 (defun org-move-subtree-down (&optional arg)
6409 "Move the current subtree down past ARG headlines of the same level."
6410 (interactive "p")
6411 (setq arg (prefix-numeric-value arg))
6412 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6413 'outline-get-last-sibling))
6414 (ins-point (make-marker))
6415 (cnt (abs arg))
6416 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6417 ;; Select the tree
6418 (org-back-to-heading)
6419 (setq beg0 (point))
6420 (save-excursion
6421 (setq ne-beg (org-back-over-empty-lines))
6422 (setq beg (point)))
6423 (save-match-data
6424 (save-excursion (outline-end-of-heading)
6425 (setq folded (org-invisible-p)))
6426 (outline-end-of-subtree))
6427 (outline-next-heading)
6428 (setq ne-end (org-back-over-empty-lines))
6429 (setq end (point))
6430 (goto-char beg0)
6431 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6432 ;; include less whitespace
6433 (save-excursion
6434 (goto-char beg)
6435 (forward-line (- ne-beg ne-end))
6436 (setq beg (point))))
6437 ;; Find insertion point, with error handling
6438 (while (> cnt 0)
6439 (or (and (funcall movfunc) (looking-at outline-regexp))
6440 (progn (goto-char beg0)
6441 (error "Cannot move past superior level or buffer limit")))
6442 (setq cnt (1- cnt)))
6443 (if (> arg 0)
6444 ;; Moving forward - still need to move over subtree
6445 (progn (org-end-of-subtree t t)
6446 (save-excursion
6447 (org-back-over-empty-lines)
6448 (or (bolp) (newline)))))
6449 (setq ne-ins (org-back-over-empty-lines))
6450 (move-marker ins-point (point))
6451 (setq txt (buffer-substring beg end))
6452 (delete-region beg end)
6453 (outline-flag-region (1- beg) beg nil)
6454 (outline-flag-region (1- (point)) (point) nil)
6455 (insert txt)
6456 (or (bolp) (insert "\n"))
6457 (setq ins-end (point))
6458 (goto-char ins-point)
6459 (org-skip-whitespace)
6460 (when (and (< arg 0)
6461 (org-first-sibling-p)
6462 (> ne-ins ne-beg))
6463 ;; Move whitespace back to beginning
6464 (save-excursion
6465 (goto-char ins-end)
6466 (let ((kill-whole-line t))
6467 (kill-line (- ne-ins ne-beg)) (point)))
6468 (insert (make-string (- ne-ins ne-beg) ?\n)))
6469 (move-marker ins-point nil)
6470 (org-compact-display-after-subtree-move)
6471 (unless folded
6472 (org-show-entry)
6473 (show-children)
6474 (org-cycle-hide-drawers 'children))))
6476 (defvar org-subtree-clip ""
6477 "Clipboard for cut and paste of subtrees.
6478 This is actually only a copy of the kill, because we use the normal kill
6479 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6481 (defvar org-subtree-clip-folded nil
6482 "Was the last copied subtree folded?
6483 This is used to fold the tree back after pasting.")
6485 (defun org-cut-subtree (&optional n)
6486 "Cut the current subtree into the clipboard.
6487 With prefix arg N, cut this many sequential subtrees.
6488 This is a short-hand for marking the subtree and then cutting it."
6489 (interactive "p")
6490 (org-copy-subtree n 'cut))
6492 (defun org-copy-subtree (&optional n cut)
6493 "Cut the current subtree into the clipboard.
6494 With prefix arg N, cut this many sequential subtrees.
6495 This is a short-hand for marking the subtree and then copying it.
6496 If CUT is non-nil, actually cut the subtree."
6497 (interactive "p")
6498 (let (beg end folded (beg0 (point)))
6499 (if (interactive-p)
6500 (org-back-to-heading nil) ; take what looks like a subtree
6501 (org-back-to-heading t)) ; take what is really there
6502 (org-back-over-empty-lines)
6503 (setq beg (point))
6504 (skip-chars-forward " \t\r\n")
6505 (save-match-data
6506 (save-excursion (outline-end-of-heading)
6507 (setq folded (org-invisible-p)))
6508 (condition-case nil
6509 (outline-forward-same-level (1- n))
6510 (error nil))
6511 (org-end-of-subtree t t))
6512 (org-back-over-empty-lines)
6513 (setq end (point))
6514 (goto-char beg0)
6515 (when (> end beg)
6516 (setq org-subtree-clip-folded folded)
6517 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6518 (setq org-subtree-clip (current-kill 0))
6519 (message "%s: Subtree(s) with %d characters"
6520 (if cut "Cut" "Copied")
6521 (length org-subtree-clip)))))
6523 (defun org-paste-subtree (&optional level tree)
6524 "Paste the clipboard as a subtree, with modification of headline level.
6525 The entire subtree is promoted or demoted in order to match a new headline
6526 level. By default, the new level is derived from the visible headings
6527 before and after the insertion point, and taken to be the inferior headline
6528 level of the two. So if the previous visible heading is level 3 and the
6529 next is level 4 (or vice versa), level 4 will be used for insertion.
6530 This makes sure that the subtree remains an independent subtree and does
6531 not swallow low level entries.
6533 You can also force a different level, either by using a numeric prefix
6534 argument, or by inserting the heading marker by hand. For example, if the
6535 cursor is after \"*****\", then the tree will be shifted to level 5.
6537 If you want to insert the tree as is, just use \\[yank].
6539 If optional TREE is given, use this text instead of the kill ring."
6540 (interactive "P")
6541 (unless (org-kill-is-subtree-p tree)
6542 (error "%s"
6543 (substitute-command-keys
6544 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6545 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6546 (^re (concat "^\\(" outline-regexp "\\)"))
6547 (re (concat "\\(" outline-regexp "\\)"))
6548 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6550 (old-level (if (string-match ^re txt)
6551 (- (match-end 0) (match-beginning 0) 1)
6552 -1))
6553 (force-level (cond (level (prefix-numeric-value level))
6554 ((string-match
6555 ^re_ (buffer-substring (point-at-bol) (point)))
6556 (- (match-end 1) (match-beginning 1)))
6557 (t nil)))
6558 (previous-level (save-excursion
6559 (condition-case nil
6560 (progn
6561 (outline-previous-visible-heading 1)
6562 (if (looking-at re)
6563 (- (match-end 0) (match-beginning 0) 1)
6565 (error 1))))
6566 (next-level (save-excursion
6567 (condition-case nil
6568 (progn
6569 (or (looking-at outline-regexp)
6570 (outline-next-visible-heading 1))
6571 (if (looking-at re)
6572 (- (match-end 0) (match-beginning 0) 1)
6574 (error 1))))
6575 (new-level (or force-level (max previous-level next-level)))
6576 (shift (if (or (= old-level -1)
6577 (= new-level -1)
6578 (= old-level new-level))
6580 (- new-level old-level)))
6581 (delta (if (> shift 0) -1 1))
6582 (func (if (> shift 0) 'org-demote 'org-promote))
6583 (org-odd-levels-only nil)
6584 beg end)
6585 ;; Remove the forced level indicator
6586 (if force-level
6587 (delete-region (point-at-bol) (point)))
6588 ;; Paste
6589 (beginning-of-line 1)
6590 (org-back-over-empty-lines) ;; FIXME: correct fix????
6591 (setq beg (point))
6592 (insert-before-markers txt) ;; FIXME: correct fix????
6593 (unless (string-match "\n\\'" txt) (insert "\n"))
6594 (setq end (point))
6595 (goto-char beg)
6596 (skip-chars-forward " \t\n\r")
6597 (setq beg (point))
6598 ;; Shift if necessary
6599 (unless (= shift 0)
6600 (save-restriction
6601 (narrow-to-region beg end)
6602 (while (not (= shift 0))
6603 (org-map-region func (point-min) (point-max))
6604 (setq shift (+ delta shift)))
6605 (goto-char (point-min))))
6606 (when (interactive-p)
6607 (message "Clipboard pasted as level %d subtree" new-level))
6608 (if (and kill-ring
6609 (eq org-subtree-clip (current-kill 0))
6610 org-subtree-clip-folded)
6611 ;; The tree was folded before it was killed/copied
6612 (hide-subtree))))
6614 (defun org-kill-is-subtree-p (&optional txt)
6615 "Check if the current kill is an outline subtree, or a set of trees.
6616 Returns nil if kill does not start with a headline, or if the first
6617 headline level is not the largest headline level in the tree.
6618 So this will actually accept several entries of equal levels as well,
6619 which is OK for `org-paste-subtree'.
6620 If optional TXT is given, check this string instead of the current kill."
6621 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6622 (start-level (and kill
6623 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6624 org-outline-regexp "\\)")
6625 kill)
6626 (- (match-end 2) (match-beginning 2) 1)))
6627 (re (concat "^" org-outline-regexp))
6628 (start (1+ (match-beginning 2))))
6629 (if (not start-level)
6630 (progn
6631 nil) ;; does not even start with a heading
6632 (catch 'exit
6633 (while (setq start (string-match re kill (1+ start)))
6634 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6635 (throw 'exit nil)))
6636 t))))
6638 (defun org-narrow-to-subtree ()
6639 "Narrow buffer to the current subtree."
6640 (interactive)
6641 (save-excursion
6642 (narrow-to-region
6643 (progn (org-back-to-heading) (point))
6644 (progn (org-end-of-subtree t t) (point)))))
6647 ;;; Outline Sorting
6649 (defun org-sort (with-case)
6650 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6651 Optional argument WITH-CASE means sort case-sensitively."
6652 (interactive "P")
6653 (if (org-at-table-p)
6654 (org-call-with-arg 'org-table-sort-lines with-case)
6655 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6657 (defvar org-priority-regexp) ; defined later in the file
6659 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6660 "Sort entries on a certain level of an outline tree.
6661 If there is an active region, the entries in the region are sorted.
6662 Else, if the cursor is before the first entry, sort the top-level items.
6663 Else, the children of the entry at point are sorted.
6665 Sorting can be alphabetically, numerically, and by date/time as given by
6666 the first time stamp in the entry. The command prompts for the sorting
6667 type unless it has been given to the function through the SORTING-TYPE
6668 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6669 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6670 called with point at the beginning of the record. It must return either
6671 a string or a number that should serve as the sorting key for that record.
6673 Comparing entries ignores case by default. However, with an optional argument
6674 WITH-CASE, the sorting considers case as well."
6675 (interactive "P")
6676 (let ((case-func (if with-case 'identity 'downcase))
6677 start beg end stars re re2
6678 txt what tmp plain-list-p)
6679 ;; Find beginning and end of region to sort
6680 (cond
6681 ((org-region-active-p)
6682 ;; we will sort the region
6683 (setq end (region-end)
6684 what "region")
6685 (goto-char (region-beginning))
6686 (if (not (org-on-heading-p)) (outline-next-heading))
6687 (setq start (point)))
6688 ((org-at-item-p)
6689 ;; we will sort this plain list
6690 (org-beginning-of-item-list) (setq start (point))
6691 (org-end-of-item-list) (setq end (point))
6692 (goto-char start)
6693 (setq plain-list-p t
6694 what "plain list"))
6695 ((or (org-on-heading-p)
6696 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6697 ;; we will sort the children of the current headline
6698 (org-back-to-heading)
6699 (setq start (point)
6700 end (progn (org-end-of-subtree t t)
6701 (org-back-over-empty-lines)
6702 (point))
6703 what "children")
6704 (goto-char start)
6705 (show-subtree)
6706 (outline-next-heading))
6708 ;; we will sort the top-level entries in this file
6709 (goto-char (point-min))
6710 (or (org-on-heading-p) (outline-next-heading))
6711 (setq start (point) end (point-max) what "top-level")
6712 (goto-char start)
6713 (show-all)))
6715 (setq beg (point))
6716 (if (>= beg end) (error "Nothing to sort"))
6718 (unless plain-list-p
6719 (looking-at "\\(\\*+\\)")
6720 (setq stars (match-string 1)
6721 re (concat "^" (regexp-quote stars) " +")
6722 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6723 txt (buffer-substring beg end))
6724 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6725 (if (and (not (equal stars "*")) (string-match re2 txt))
6726 (error "Region to sort contains a level above the first entry")))
6728 (unless sorting-type
6729 (message
6730 (if plain-list-p
6731 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6732 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
6733 what)
6734 (setq sorting-type (read-char-exclusive))
6736 (and (= (downcase sorting-type) ?f)
6737 (setq getkey-func
6738 (completing-read "Sort using function: "
6739 obarray 'fboundp t nil nil))
6740 (setq getkey-func (intern getkey-func)))
6742 (and (= (downcase sorting-type) ?r)
6743 (setq property
6744 (completing-read "Property: "
6745 (mapcar 'list (org-buffer-property-keys t))
6746 nil t))))
6748 (message "Sorting entries...")
6750 (save-restriction
6751 (narrow-to-region start end)
6753 (let ((dcst (downcase sorting-type))
6754 (now (current-time)))
6755 (sort-subr
6756 (/= dcst sorting-type)
6757 ;; This function moves to the beginning character of the "record" to
6758 ;; be sorted.
6759 (if plain-list-p
6760 (lambda nil
6761 (if (org-at-item-p) t (goto-char (point-max))))
6762 (lambda nil
6763 (if (re-search-forward re nil t)
6764 (goto-char (match-beginning 0))
6765 (goto-char (point-max)))))
6766 ;; This function moves to the last character of the "record" being
6767 ;; sorted.
6768 (if plain-list-p
6769 'org-end-of-item
6770 (lambda nil
6771 (save-match-data
6772 (condition-case nil
6773 (outline-forward-same-level 1)
6774 (error
6775 (goto-char (point-max)))))))
6777 ;; This function returns the value that gets sorted against.
6778 (if plain-list-p
6779 (lambda nil
6780 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6781 (cond
6782 ((= dcst ?n)
6783 (string-to-number (buffer-substring (match-end 0)
6784 (point-at-eol))))
6785 ((= dcst ?a)
6786 (buffer-substring (match-end 0) (point-at-eol)))
6787 ((= dcst ?t)
6788 (if (re-search-forward org-ts-regexp
6789 (point-at-eol) t)
6790 (org-time-string-to-time (match-string 0))
6791 now))
6792 ((= dcst ?f)
6793 (if getkey-func
6794 (progn
6795 (setq tmp (funcall getkey-func))
6796 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6797 tmp)
6798 (error "Invalid key function `%s'" getkey-func)))
6799 (t (error "Invalid sorting type `%c'" sorting-type)))))
6800 (lambda nil
6801 (cond
6802 ((= dcst ?n)
6803 (if (looking-at outline-regexp)
6804 (string-to-number (buffer-substring (match-end 0)
6805 (point-at-eol)))
6806 nil))
6807 ((= dcst ?a)
6808 (funcall case-func (buffer-substring (point-at-bol)
6809 (point-at-eol))))
6810 ((= dcst ?t)
6811 (if (re-search-forward org-ts-regexp
6812 (save-excursion
6813 (forward-line 2)
6814 (point)) t)
6815 (org-time-string-to-time (match-string 0))
6816 now))
6817 ((= dcst ?p)
6818 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6819 (string-to-char (match-string 2))
6820 org-default-priority))
6821 ((= dcst ?r)
6822 (or (org-entry-get nil property) ""))
6823 ((= dcst ?f)
6824 (if getkey-func
6825 (progn
6826 (setq tmp (funcall getkey-func))
6827 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6828 tmp)
6829 (error "Invalid key function `%s'" getkey-func)))
6830 (t (error "Invalid sorting type `%c'" sorting-type)))))
6832 (cond
6833 ((= dcst ?a) 'string<)
6834 ((= dcst ?t) 'time-less-p)
6835 (t nil)))))
6836 (message "Sorting entries...done")))
6838 (defun org-do-sort (table what &optional with-case sorting-type)
6839 "Sort TABLE of WHAT according to SORTING-TYPE.
6840 The user will be prompted for the SORTING-TYPE if the call to this
6841 function does not specify it. WHAT is only for the prompt, to indicate
6842 what is being sorted. The sorting key will be extracted from
6843 the car of the elements of the table.
6844 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6845 (unless sorting-type
6846 (message
6847 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6848 what)
6849 (setq sorting-type (read-char-exclusive)))
6850 (let ((dcst (downcase sorting-type))
6851 extractfun comparefun)
6852 ;; Define the appropriate functions
6853 (cond
6854 ((= dcst ?n)
6855 (setq extractfun 'string-to-number
6856 comparefun (if (= dcst sorting-type) '< '>)))
6857 ((= dcst ?a)
6858 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6859 (lambda(x) (downcase (org-sort-remove-invisible x))))
6860 comparefun (if (= dcst sorting-type)
6861 'string<
6862 (lambda (a b) (and (not (string< a b))
6863 (not (string= a b)))))))
6864 ((= dcst ?t)
6865 (setq extractfun
6866 (lambda (x)
6867 (if (string-match org-ts-regexp x)
6868 (time-to-seconds
6869 (org-time-string-to-time (match-string 0 x)))
6871 comparefun (if (= dcst sorting-type) '< '>)))
6872 (t (error "Invalid sorting type `%c'" sorting-type)))
6874 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6875 table)
6876 (lambda (a b) (funcall comparefun (car a) (car b))))))
6878 ;;;; Plain list items, including checkboxes
6880 ;;; Plain list items
6882 (defun org-at-item-p ()
6883 "Is point in a line starting a hand-formatted item?"
6884 (let ((llt org-plain-list-ordered-item-terminator))
6885 (save-excursion
6886 (goto-char (point-at-bol))
6887 (looking-at
6888 (cond
6889 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6890 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6891 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6892 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
6894 (defun org-in-item-p ()
6895 "It the cursor inside a plain list item.
6896 Does not have to be the first line."
6897 (save-excursion
6898 (condition-case nil
6899 (progn
6900 (org-beginning-of-item)
6901 (org-at-item-p)
6903 (error nil))))
6905 (defun org-insert-item (&optional checkbox)
6906 "Insert a new item at the current level.
6907 Return t when things worked, nil when we are not in an item."
6908 (when (save-excursion
6909 (condition-case nil
6910 (progn
6911 (org-beginning-of-item)
6912 (org-at-item-p)
6913 (if (org-invisible-p) (error "Invisible item"))
6915 (error nil)))
6916 (let* ((bul (match-string 0))
6917 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
6918 (match-end 0)))
6919 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
6920 pos)
6921 (cond
6922 ((and (org-at-item-p) (<= (point) eow))
6923 ;; before the bullet
6924 (beginning-of-line 1)
6925 (open-line (if blank 2 1)))
6926 ((<= (point) eow)
6927 (beginning-of-line 1))
6928 (t (newline (if blank 2 1))))
6929 (insert bul (if checkbox "[ ]" ""))
6930 (just-one-space)
6931 (setq pos (point))
6932 (end-of-line 1)
6933 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
6934 (org-maybe-renumber-ordered-list)
6935 (and checkbox (org-update-checkbox-count-maybe))
6938 ;;; Checkboxes
6940 (defun org-at-item-checkbox-p ()
6941 "Is point at a line starting a plain-list item with a checklet?"
6942 (and (org-at-item-p)
6943 (save-excursion
6944 (goto-char (match-end 0))
6945 (skip-chars-forward " \t")
6946 (looking-at "\\[[- X]\\]"))))
6948 (defun org-toggle-checkbox (&optional arg)
6949 "Toggle the checkbox in the current line."
6950 (interactive "P")
6951 (catch 'exit
6952 (let (beg end status (firstnew 'unknown))
6953 (cond
6954 ((org-region-active-p)
6955 (setq beg (region-beginning) end (region-end)))
6956 ((org-on-heading-p)
6957 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
6958 ((org-at-item-checkbox-p)
6959 (let ((pos (point)))
6960 (replace-match
6961 (cond (arg "[-]")
6962 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
6963 (t "[ ]"))
6964 t t)
6965 (goto-char pos))
6966 (throw 'exit t))
6967 (t (error "Not at a checkbox or heading, and no active region")))
6968 (save-excursion
6969 (goto-char beg)
6970 (while (< (point) end)
6971 (when (org-at-item-checkbox-p)
6972 (setq status (equal (match-string 0) "[X]"))
6973 (when (eq firstnew 'unknown)
6974 (setq firstnew (not status)))
6975 (replace-match
6976 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
6977 (beginning-of-line 2)))))
6978 (org-update-checkbox-count-maybe))
6980 (defun org-update-checkbox-count-maybe ()
6981 "Update checkbox statistics unless turned off by user."
6982 (when org-provide-checkbox-statistics
6983 (org-update-checkbox-count)))
6985 (defun org-update-checkbox-count (&optional all)
6986 "Update the checkbox statistics in the current section.
6987 This will find all statistic cookies like [57%] and [6/12] and update them
6988 with the current numbers. With optional prefix argument ALL, do this for
6989 the whole buffer."
6990 (interactive "P")
6991 (save-excursion
6992 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
6993 (beg (condition-case nil
6994 (progn (outline-back-to-heading) (point))
6995 (error (point-min))))
6996 (end (move-marker (make-marker)
6997 (progn (outline-next-heading) (point))))
6998 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
6999 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
7000 b1 e1 f1 c-on c-off lim (cstat 0))
7001 (when all
7002 (goto-char (point-min))
7003 (outline-next-heading)
7004 (setq beg (point) end (point-max)))
7005 (goto-char beg)
7006 (while (re-search-forward re end t)
7007 (setq cstat (1+ cstat)
7008 b1 (match-beginning 0)
7009 e1 (match-end 0)
7010 f1 (match-beginning 1)
7011 lim (cond
7012 ((org-on-heading-p) (outline-next-heading) (point))
7013 ((org-at-item-p) (org-end-of-item) (point))
7014 (t nil))
7015 c-on 0 c-off 0)
7016 (goto-char e1)
7017 (when lim
7018 (while (re-search-forward re-box lim t)
7019 (if (member (match-string 2) '("[ ]" "[-]"))
7020 (setq c-off (1+ c-off))
7021 (setq c-on (1+ c-on))))
7022 ; (delete-region b1 e1)
7023 (goto-char b1)
7024 (insert (if f1
7025 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
7026 (format "[%d/%d]" c-on (+ c-on c-off))))
7027 (and (looking-at "\\[.*?\\]")
7028 (replace-match ""))))
7029 (when (interactive-p)
7030 (message "Checkbox satistics updated %s (%d places)"
7031 (if all "in entire file" "in current outline entry") cstat)))))
7033 (defun org-get-checkbox-statistics-face ()
7034 "Select the face for checkbox statistics.
7035 The face will be `org-done' when all relevant boxes are checked. Otherwise
7036 it will be `org-todo'."
7037 (if (match-end 1)
7038 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
7039 (if (and (> (match-end 2) (match-beginning 2))
7040 (equal (match-string 2) (match-string 3)))
7041 'org-done
7042 'org-todo)))
7044 (defun org-get-indentation (&optional line)
7045 "Get the indentation of the current line, interpreting tabs.
7046 When LINE is given, assume it represents a line and compute its indentation."
7047 (if line
7048 (if (string-match "^ *" (org-remove-tabs line))
7049 (match-end 0))
7050 (save-excursion
7051 (beginning-of-line 1)
7052 (skip-chars-forward " \t")
7053 (current-column))))
7055 (defun org-remove-tabs (s &optional width)
7056 "Replace tabulators in S with spaces.
7057 Assumes that s is a single line, starting in column 0."
7058 (setq width (or width tab-width))
7059 (while (string-match "\t" s)
7060 (setq s (replace-match
7061 (make-string
7062 (- (* width (/ (+ (match-beginning 0) width) width))
7063 (match-beginning 0)) ?\ )
7064 t t s)))
7067 (defun org-fix-indentation (line ind)
7068 "Fix indentation in LINE.
7069 IND is a cons cell with target and minimum indentation.
7070 If the current indenation in LINE is smaller than the minimum,
7071 leave it alone. If it is larger than ind, set it to the target."
7072 (let* ((l (org-remove-tabs line))
7073 (i (org-get-indentation l))
7074 (i1 (car ind)) (i2 (cdr ind)))
7075 (if (>= i i2) (setq l (substring line i2)))
7076 (if (> i1 0)
7077 (concat (make-string i1 ?\ ) l)
7078 l)))
7080 (defcustom org-empty-line-terminates-plain-lists nil
7081 "Non-nil means, an empty line ends all plain list levels.
7082 When nil, empty lines are part of the preceeding item."
7083 :group 'org-plain-lists
7084 :type 'boolean)
7086 (defun org-beginning-of-item ()
7087 "Go to the beginning of the current hand-formatted item.
7088 If the cursor is not in an item, throw an error."
7089 (interactive)
7090 (let ((pos (point))
7091 (limit (save-excursion
7092 (condition-case nil
7093 (progn
7094 (org-back-to-heading)
7095 (beginning-of-line 2) (point))
7096 (error (point-min)))))
7097 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7098 ind ind1)
7099 (if (org-at-item-p)
7100 (beginning-of-line 1)
7101 (beginning-of-line 1)
7102 (skip-chars-forward " \t")
7103 (setq ind (current-column))
7104 (if (catch 'exit
7105 (while t
7106 (beginning-of-line 0)
7107 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
7109 (if (looking-at "[ \t]*$")
7110 (setq ind1 ind-empty)
7111 (skip-chars-forward " \t")
7112 (setq ind1 (current-column)))
7113 (if (< ind1 ind)
7114 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
7116 (goto-char pos)
7117 (error "Not in an item")))))
7119 (defun org-end-of-item ()
7120 "Go to the end of the current hand-formatted item.
7121 If the cursor is not in an item, throw an error."
7122 (interactive)
7123 (let* ((pos (point))
7124 ind1
7125 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7126 (limit (save-excursion (outline-next-heading) (point)))
7127 (ind (save-excursion
7128 (org-beginning-of-item)
7129 (skip-chars-forward " \t")
7130 (current-column)))
7131 (end (catch 'exit
7132 (while t
7133 (beginning-of-line 2)
7134 (if (eobp) (throw 'exit (point)))
7135 (if (>= (point) limit) (throw 'exit (point-at-bol)))
7136 (if (looking-at "[ \t]*$")
7137 (setq ind1 ind-empty)
7138 (skip-chars-forward " \t")
7139 (setq ind1 (current-column)))
7140 (if (<= ind1 ind)
7141 (throw 'exit (point-at-bol)))))))
7142 (if end
7143 (goto-char end)
7144 (goto-char pos)
7145 (error "Not in an item"))))
7147 (defun org-next-item ()
7148 "Move to the beginning of the next item in the current plain list.
7149 Error if not at a plain list, or if this is the last item in the list."
7150 (interactive)
7151 (let (ind ind1 (pos (point)))
7152 (org-beginning-of-item)
7153 (setq ind (org-get-indentation))
7154 (org-end-of-item)
7155 (setq ind1 (org-get-indentation))
7156 (unless (and (org-at-item-p) (= ind ind1))
7157 (goto-char pos)
7158 (error "On last item"))))
7160 (defun org-previous-item ()
7161 "Move to the beginning of the previous item in the current plain list.
7162 Error if not at a plain list, or if this is the first item in the list."
7163 (interactive)
7164 (let (beg ind ind1 (pos (point)))
7165 (org-beginning-of-item)
7166 (setq beg (point))
7167 (setq ind (org-get-indentation))
7168 (goto-char beg)
7169 (catch 'exit
7170 (while t
7171 (beginning-of-line 0)
7172 (if (looking-at "[ \t]*$")
7174 (if (<= (setq ind1 (org-get-indentation)) ind)
7175 (throw 'exit t)))))
7176 (condition-case nil
7177 (if (or (not (org-at-item-p))
7178 (< ind1 (1- ind)))
7179 (error "")
7180 (org-beginning-of-item))
7181 (error (goto-char pos)
7182 (error "On first item")))))
7184 (defun org-first-list-item-p ()
7185 "Is this heading the item in a plain list?"
7186 (unless (org-at-item-p)
7187 (error "Not at a plain list item"))
7188 (org-beginning-of-item)
7189 (= (point) (save-excursion (org-beginning-of-item-list))))
7191 (defun org-move-item-down ()
7192 "Move the plain list item at point down, i.e. swap with following item.
7193 Subitems (items with larger indentation) are considered part of the item,
7194 so this really moves item trees."
7195 (interactive)
7196 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
7197 (org-beginning-of-item)
7198 (setq beg0 (point))
7199 (save-excursion
7200 (setq ne-beg (org-back-over-empty-lines))
7201 (setq beg (point)))
7202 (goto-char beg0)
7203 (setq ind (org-get-indentation))
7204 (org-end-of-item)
7205 (setq end0 (point))
7206 (setq ind1 (org-get-indentation))
7207 (setq ne-end (org-back-over-empty-lines))
7208 (setq end (point))
7209 (goto-char beg0)
7210 (when (and (org-first-list-item-p) (< ne-end ne-beg))
7211 ;; include less whitespace
7212 (save-excursion
7213 (goto-char beg)
7214 (forward-line (- ne-beg ne-end))
7215 (setq beg (point))))
7216 (goto-char end0)
7217 (if (and (org-at-item-p) (= ind ind1))
7218 (progn
7219 (org-end-of-item)
7220 (org-back-over-empty-lines)
7221 (setq txt (buffer-substring beg end))
7222 (save-excursion
7223 (delete-region beg end))
7224 (setq pos (point))
7225 (insert txt)
7226 (goto-char pos) (org-skip-whitespace)
7227 (org-maybe-renumber-ordered-list))
7228 (goto-char pos)
7229 (error "Cannot move this item further down"))))
7231 (defun org-move-item-up (arg)
7232 "Move the plain list item at point up, i.e. swap with previous item.
7233 Subitems (items with larger indentation) are considered part of the item,
7234 so this really moves item trees."
7235 (interactive "p")
7236 (let (beg beg0 end end0 ind ind1 (pos (point)) txt
7237 ne-beg ne-end ne-ins ins-end)
7238 (org-beginning-of-item)
7239 (setq beg0 (point))
7240 (setq ind (org-get-indentation))
7241 (save-excursion
7242 (setq ne-beg (org-back-over-empty-lines))
7243 (setq beg (point)))
7244 (goto-char beg0)
7245 (org-end-of-item)
7246 (setq ne-end (org-back-over-empty-lines))
7247 (setq end (point))
7248 (goto-char beg0)
7249 (catch 'exit
7250 (while t
7251 (beginning-of-line 0)
7252 (if (looking-at "[ \t]*$")
7253 (if org-empty-line-terminates-plain-lists
7254 (progn
7255 (goto-char pos)
7256 (error "Cannot move this item further up"))
7257 nil)
7258 (if (<= (setq ind1 (org-get-indentation)) ind)
7259 (throw 'exit t)))))
7260 (condition-case nil
7261 (org-beginning-of-item)
7262 (error (goto-char beg)
7263 (error "Cannot move this item further up")))
7264 (setq ind1 (org-get-indentation))
7265 (if (and (org-at-item-p) (= ind ind1))
7266 (progn
7267 (setq ne-ins (org-back-over-empty-lines))
7268 (setq txt (buffer-substring beg end))
7269 (save-excursion
7270 (delete-region beg end))
7271 (setq pos (point))
7272 (insert txt)
7273 (setq ins-end (point))
7274 (goto-char pos) (org-skip-whitespace)
7276 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
7277 ;; Move whitespace back to beginning
7278 (save-excursion
7279 (goto-char ins-end)
7280 (let ((kill-whole-line t))
7281 (kill-line (- ne-ins ne-beg)) (point)))
7282 (insert (make-string (- ne-ins ne-beg) ?\n)))
7284 (org-maybe-renumber-ordered-list))
7285 (goto-char pos)
7286 (error "Cannot move this item further up"))))
7288 (defun org-maybe-renumber-ordered-list ()
7289 "Renumber the ordered list at point if setup allows it.
7290 This tests the user option `org-auto-renumber-ordered-lists' before
7291 doing the renumbering."
7292 (interactive)
7293 (when (and org-auto-renumber-ordered-lists
7294 (org-at-item-p))
7295 (if (match-beginning 3)
7296 (org-renumber-ordered-list 1)
7297 (org-fix-bullet-type))))
7299 (defun org-maybe-renumber-ordered-list-safe ()
7300 (condition-case nil
7301 (save-excursion
7302 (org-maybe-renumber-ordered-list))
7303 (error nil)))
7305 (defun org-cycle-list-bullet (&optional which)
7306 "Cycle through the different itemize/enumerate bullets.
7307 This cycle the entire list level through the sequence:
7309 `-' -> `+' -> `*' -> `1.' -> `1)'
7311 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7312 0 meand `-', 1 means `+' etc."
7313 (interactive "P")
7314 (org-preserve-lc
7315 (org-beginning-of-item-list)
7316 (org-at-item-p)
7317 (beginning-of-line 1)
7318 (let ((current (match-string 0))
7319 (prevp (eq which 'previous))
7320 new)
7321 (setq new (cond
7322 ((and (numberp which)
7323 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7324 ((string-match "-" current) (if prevp "1)" "+"))
7325 ((string-match "\\+" current)
7326 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7327 ((string-match "\\*" current) (if prevp "+" "1."))
7328 ((string-match "\\." current) (if prevp "*" "1)"))
7329 ((string-match ")" current) (if prevp "1." "-"))
7330 (t (error "This should not happen"))))
7331 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7332 (org-fix-bullet-type)
7333 (org-maybe-renumber-ordered-list))))
7335 (defun org-get-string-indentation (s)
7336 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7337 (let ((n -1) (i 0) (w tab-width) c)
7338 (catch 'exit
7339 (while (< (setq n (1+ n)) (length s))
7340 (setq c (aref s n))
7341 (cond ((= c ?\ ) (setq i (1+ i)))
7342 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7343 (t (throw 'exit t)))))
7346 (defun org-renumber-ordered-list (arg)
7347 "Renumber an ordered plain list.
7348 Cursor needs to be in the first line of an item, the line that starts
7349 with something like \"1.\" or \"2)\"."
7350 (interactive "p")
7351 (unless (and (org-at-item-p)
7352 (match-beginning 3))
7353 (error "This is not an ordered list"))
7354 (let ((line (org-current-line))
7355 (col (current-column))
7356 (ind (org-get-string-indentation
7357 (buffer-substring (point-at-bol) (match-beginning 3))))
7358 ;; (term (substring (match-string 3) -1))
7359 ind1 (n (1- arg))
7360 fmt)
7361 ;; find where this list begins
7362 (org-beginning-of-item-list)
7363 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7364 (setq fmt (concat "%d" (match-string 1)))
7365 (beginning-of-line 0)
7366 ;; walk forward and replace these numbers
7367 (catch 'exit
7368 (while t
7369 (catch 'next
7370 (beginning-of-line 2)
7371 (if (eobp) (throw 'exit nil))
7372 (if (looking-at "[ \t]*$") (throw 'next nil))
7373 (skip-chars-forward " \t") (setq ind1 (current-column))
7374 (if (> ind1 ind) (throw 'next t))
7375 (if (< ind1 ind) (throw 'exit t))
7376 (if (not (org-at-item-p)) (throw 'exit nil))
7377 (delete-region (match-beginning 2) (match-end 2))
7378 (goto-char (match-beginning 2))
7379 (insert (format fmt (setq n (1+ n)))))))
7380 (goto-line line)
7381 (move-to-column col)))
7383 (defun org-fix-bullet-type ()
7384 "Make sure all items in this list have the same bullet as the firsst item."
7385 (interactive)
7386 (unless (org-at-item-p) (error "This is not a list"))
7387 (let ((line (org-current-line))
7388 (col (current-column))
7389 (ind (current-indentation))
7390 ind1 bullet)
7391 ;; find where this list begins
7392 (org-beginning-of-item-list)
7393 (beginning-of-line 1)
7394 ;; find out what the bullet type is
7395 (looking-at "[ \t]*\\(\\S-+\\)")
7396 (setq bullet (match-string 1))
7397 ;; walk forward and replace these numbers
7398 (beginning-of-line 0)
7399 (catch 'exit
7400 (while t
7401 (catch 'next
7402 (beginning-of-line 2)
7403 (if (eobp) (throw 'exit nil))
7404 (if (looking-at "[ \t]*$") (throw 'next nil))
7405 (skip-chars-forward " \t") (setq ind1 (current-column))
7406 (if (> ind1 ind) (throw 'next t))
7407 (if (< ind1 ind) (throw 'exit t))
7408 (if (not (org-at-item-p)) (throw 'exit nil))
7409 (skip-chars-forward " \t")
7410 (looking-at "\\S-+")
7411 (replace-match bullet))))
7412 (goto-line line)
7413 (move-to-column col)
7414 (if (string-match "[0-9]" bullet)
7415 (org-renumber-ordered-list 1))))
7417 (defun org-beginning-of-item-list ()
7418 "Go to the beginning of the current item list.
7419 I.e. to the first item in this list."
7420 (interactive)
7421 (org-beginning-of-item)
7422 (let ((pos (point-at-bol))
7423 (ind (org-get-indentation))
7424 ind1)
7425 ;; find where this list begins
7426 (catch 'exit
7427 (while t
7428 (catch 'next
7429 (beginning-of-line 0)
7430 (if (looking-at "[ \t]*$")
7431 (throw (if (bobp) 'exit 'next) t))
7432 (skip-chars-forward " \t") (setq ind1 (current-column))
7433 (if (or (< ind1 ind)
7434 (and (= ind1 ind)
7435 (not (org-at-item-p)))
7436 (bobp))
7437 (throw 'exit t)
7438 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7439 (goto-char pos)))
7442 (defun org-end-of-item-list ()
7443 "Go to the end of the current item list.
7444 I.e. to the text after the last item."
7445 (interactive)
7446 (org-beginning-of-item)
7447 (let ((pos (point-at-bol))
7448 (ind (org-get-indentation))
7449 ind1)
7450 ;; find where this list begins
7451 (catch 'exit
7452 (while t
7453 (catch 'next
7454 (beginning-of-line 2)
7455 (if (looking-at "[ \t]*$")
7456 (throw (if (eobp) 'exit 'next) t))
7457 (skip-chars-forward " \t") (setq ind1 (current-column))
7458 (if (or (< ind1 ind)
7459 (and (= ind1 ind)
7460 (not (org-at-item-p)))
7461 (eobp))
7462 (progn
7463 (setq pos (point-at-bol))
7464 (throw 'exit t))))))
7465 (goto-char pos)))
7468 (defvar org-last-indent-begin-marker (make-marker))
7469 (defvar org-last-indent-end-marker (make-marker))
7471 (defun org-outdent-item (arg)
7472 "Outdent a local list item."
7473 (interactive "p")
7474 (org-indent-item (- arg)))
7476 (defun org-indent-item (arg)
7477 "Indent a local list item."
7478 (interactive "p")
7479 (unless (org-at-item-p)
7480 (error "Not on an item"))
7481 (save-excursion
7482 (let (beg end ind ind1 tmp delta ind-down ind-up)
7483 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7484 (setq beg org-last-indent-begin-marker
7485 end org-last-indent-end-marker)
7486 (org-beginning-of-item)
7487 (setq beg (move-marker org-last-indent-begin-marker (point)))
7488 (org-end-of-item)
7489 (setq end (move-marker org-last-indent-end-marker (point))))
7490 (goto-char beg)
7491 (setq tmp (org-item-indent-positions)
7492 ind (car tmp)
7493 ind-down (nth 2 tmp)
7494 ind-up (nth 1 tmp)
7495 delta (if (> arg 0)
7496 (if ind-down (- ind-down ind) 2)
7497 (if ind-up (- ind-up ind) -2)))
7498 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7499 (while (< (point) end)
7500 (beginning-of-line 1)
7501 (skip-chars-forward " \t") (setq ind1 (current-column))
7502 (delete-region (point-at-bol) (point))
7503 (or (eolp) (indent-to-column (+ ind1 delta)))
7504 (beginning-of-line 2))))
7505 (org-fix-bullet-type)
7506 (org-maybe-renumber-ordered-list-safe)
7507 (save-excursion
7508 (beginning-of-line 0)
7509 (condition-case nil (org-beginning-of-item) (error nil))
7510 (org-maybe-renumber-ordered-list-safe)))
7512 (defun org-item-indent-positions ()
7513 "Return indentation for plain list items.
7514 This returns a list with three values: The current indentation, the
7515 parent indentation and the indentation a child should habe.
7516 Assumes cursor in item line."
7517 (let* ((bolpos (point-at-bol))
7518 (ind (org-get-indentation))
7519 ind-down ind-up pos)
7520 (save-excursion
7521 (org-beginning-of-item-list)
7522 (skip-chars-backward "\n\r \t")
7523 (when (org-in-item-p)
7524 (org-beginning-of-item)
7525 (setq ind-up (org-get-indentation))))
7526 (setq pos (point))
7527 (save-excursion
7528 (cond
7529 ((and (condition-case nil (progn (org-previous-item) t)
7530 (error nil))
7531 (or (forward-char 1) t)
7532 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7533 (setq ind-down (org-get-indentation)))
7534 ((and (goto-char pos)
7535 (org-at-item-p))
7536 (goto-char (match-end 0))
7537 (skip-chars-forward " \t")
7538 (setq ind-down (current-column)))))
7539 (list ind ind-up ind-down)))
7541 ;;; The orgstruct minor mode
7543 ;; Define a minor mode which can be used in other modes in order to
7544 ;; integrate the org-mode structure editing commands.
7546 ;; This is really a hack, because the org-mode structure commands use
7547 ;; keys which normally belong to the major mode. Here is how it
7548 ;; works: The minor mode defines all the keys necessary to operate the
7549 ;; structure commands, but wraps the commands into a function which
7550 ;; tests if the cursor is currently at a headline or a plain list
7551 ;; item. If that is the case, the structure command is used,
7552 ;; temporarily setting many Org-mode variables like regular
7553 ;; expressions for filling etc. However, when any of those keys is
7554 ;; used at a different location, function uses `key-binding' to look
7555 ;; up if the key has an associated command in another currently active
7556 ;; keymap (minor modes, major mode, global), and executes that
7557 ;; command. There might be problems if any of the keys is otherwise
7558 ;; used as a prefix key.
7560 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7561 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7562 ;; addresses this by checking explicitly for both bindings.
7564 (defvar orgstruct-mode-map (make-sparse-keymap)
7565 "Keymap for the minor `orgstruct-mode'.")
7567 (defvar org-local-vars nil
7568 "List of local variables, for use by `orgstruct-mode'")
7570 ;;;###autoload
7571 (define-minor-mode orgstruct-mode
7572 "Toggle the minor more `orgstruct-mode'.
7573 This mode is for using Org-mode structure commands in other modes.
7574 The following key behave as if Org-mode was active, if the cursor
7575 is on a headline, or on a plain list item (both in the definition
7576 of Org-mode).
7578 M-up Move entry/item up
7579 M-down Move entry/item down
7580 M-left Promote
7581 M-right Demote
7582 M-S-up Move entry/item up
7583 M-S-down Move entry/item down
7584 M-S-left Promote subtree
7585 M-S-right Demote subtree
7586 M-q Fill paragraph and items like in Org-mode
7587 C-c ^ Sort entries
7588 C-c - Cycle list bullet
7589 TAB Cycle item visibility
7590 M-RET Insert new heading/item
7591 S-M-RET Insert new TODO heading / Chekbox item
7592 C-c C-c Set tags / toggle checkbox"
7593 nil " OrgStruct" nil
7594 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7596 ;;;###autoload
7597 (defun turn-on-orgstruct ()
7598 "Unconditionally turn on `orgstruct-mode'."
7599 (orgstruct-mode 1))
7601 ;;;###autoload
7602 (defun turn-on-orgstruct++ ()
7603 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7604 In addition to setting orgstruct-mode, this also exports all indentation and
7605 autofilling variables from org-mode into the buffer. Note that turning
7606 off orgstruct-mode will *not* remove these additional settings."
7607 (orgstruct-mode 1)
7608 (let (var val)
7609 (mapc
7610 (lambda (x)
7611 (when (string-match
7612 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7613 (symbol-name (car x)))
7614 (setq var (car x) val (nth 1 x))
7615 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7616 org-local-vars)))
7618 (defun orgstruct-error ()
7619 "Error when there is no default binding for a structure key."
7620 (interactive)
7621 (error "This key has no function outside structure elements"))
7623 (defun orgstruct-setup ()
7624 "Setup orgstruct keymaps."
7625 (let ((nfunc 0)
7626 (bindings
7627 (list
7628 '([(meta up)] org-metaup)
7629 '([(meta down)] org-metadown)
7630 '([(meta left)] org-metaleft)
7631 '([(meta right)] org-metaright)
7632 '([(meta shift up)] org-shiftmetaup)
7633 '([(meta shift down)] org-shiftmetadown)
7634 '([(meta shift left)] org-shiftmetaleft)
7635 '([(meta shift right)] org-shiftmetaright)
7636 '([(shift up)] org-shiftup)
7637 '([(shift down)] org-shiftdown)
7638 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7639 '("\M-q" fill-paragraph)
7640 '("\C-c^" org-sort)
7641 '("\C-c-" org-cycle-list-bullet)))
7642 elt key fun cmd)
7643 (while (setq elt (pop bindings))
7644 (setq nfunc (1+ nfunc))
7645 (setq key (org-key (car elt))
7646 fun (nth 1 elt)
7647 cmd (orgstruct-make-binding fun nfunc key))
7648 (org-defkey orgstruct-mode-map key cmd))
7650 ;; Special treatment needed for TAB and RET
7651 (org-defkey orgstruct-mode-map [(tab)]
7652 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7653 (org-defkey orgstruct-mode-map "\C-i"
7654 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7656 (org-defkey orgstruct-mode-map "\M-\C-m"
7657 (orgstruct-make-binding 'org-insert-heading 105
7658 "\M-\C-m" [(meta return)]))
7659 (org-defkey orgstruct-mode-map [(meta return)]
7660 (orgstruct-make-binding 'org-insert-heading 106
7661 [(meta return)] "\M-\C-m"))
7663 (org-defkey orgstruct-mode-map [(shift meta return)]
7664 (orgstruct-make-binding 'org-insert-todo-heading 107
7665 [(meta return)] "\M-\C-m"))
7667 (unless org-local-vars
7668 (setq org-local-vars (org-get-local-variables)))
7672 (defun orgstruct-make-binding (fun n &rest keys)
7673 "Create a function for binding in the structure minor mode.
7674 FUN is the command to call inside a table. N is used to create a unique
7675 command name. KEYS are keys that should be checked in for a command
7676 to execute outside of tables."
7677 (eval
7678 (list 'defun
7679 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7680 '(arg)
7681 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7682 "Outside of structure, run the binding of `"
7683 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7684 "'.")
7685 '(interactive "p")
7686 (list 'if
7687 '(org-context-p 'headline 'item)
7688 (list 'org-run-like-in-org-mode (list 'quote fun))
7689 (list 'let '(orgstruct-mode)
7690 (list 'call-interactively
7691 (append '(or)
7692 (mapcar (lambda (k)
7693 (list 'key-binding k))
7694 keys)
7695 '('orgstruct-error))))))))
7697 (defun org-context-p (&rest contexts)
7698 "Check if local context is and of CONTEXTS.
7699 Possible values in the list of contexts are `table', `headline', and `item'."
7700 (let ((pos (point)))
7701 (goto-char (point-at-bol))
7702 (prog1 (or (and (memq 'table contexts)
7703 (looking-at "[ \t]*|"))
7704 (and (memq 'headline contexts)
7705 (looking-at "\\*+"))
7706 (and (memq 'item contexts)
7707 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
7708 (goto-char pos))))
7710 (defun org-get-local-variables ()
7711 "Return a list of all local variables in an org-mode buffer."
7712 (let (varlist)
7713 (with-current-buffer (get-buffer-create "*Org tmp*")
7714 (erase-buffer)
7715 (org-mode)
7716 (setq varlist (buffer-local-variables)))
7717 (kill-buffer "*Org tmp*")
7718 (delq nil
7719 (mapcar
7720 (lambda (x)
7721 (setq x
7722 (if (symbolp x)
7723 (list x)
7724 (list (car x) (list 'quote (cdr x)))))
7725 (if (string-match
7726 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7727 (symbol-name (car x)))
7728 x nil))
7729 varlist))))
7731 ;;;###autoload
7732 (defun org-run-like-in-org-mode (cmd)
7733 (unless org-local-vars
7734 (setq org-local-vars (org-get-local-variables)))
7735 (eval (list 'let org-local-vars
7736 (list 'call-interactively (list 'quote cmd)))))
7738 ;;;; Archiving
7740 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
7742 (defun org-archive-subtree (&optional find-done)
7743 "Move the current subtree to the archive.
7744 The archive can be a certain top-level heading in the current file, or in
7745 a different file. The tree will be moved to that location, the subtree
7746 heading be marked DONE, and the current time will be added.
7748 When called with prefix argument FIND-DONE, find whole trees without any
7749 open TODO items and archive them (after getting confirmation from the user).
7750 If the cursor is not at a headline when this comand is called, try all level
7751 1 trees. If the cursor is on a headline, only try the direct children of
7752 this heading."
7753 (interactive "P")
7754 (if find-done
7755 (org-archive-all-done)
7756 ;; Save all relevant TODO keyword-relatex variables
7758 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
7759 (tr-org-todo-keywords-1 org-todo-keywords-1)
7760 (tr-org-todo-kwd-alist org-todo-kwd-alist)
7761 (tr-org-done-keywords org-done-keywords)
7762 (tr-org-todo-regexp org-todo-regexp)
7763 (tr-org-todo-line-regexp org-todo-line-regexp)
7764 (tr-org-odd-levels-only org-odd-levels-only)
7765 (this-buffer (current-buffer))
7766 (org-archive-location org-archive-location)
7767 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
7768 ;; start of variables that will be used for saving context
7769 ;; The compiler complains about them - keep them anyway!
7770 (file (abbreviate-file-name (buffer-file-name)))
7771 (olpath (mapconcat 'identity (org-get-outline-path) "/"))
7772 (time (format-time-string
7773 (substring (cdr org-time-stamp-formats) 1 -1)
7774 (current-time)))
7775 afile heading buffer level newfile-p
7776 category todo priority
7777 ;; start of variables that will be used for savind context
7778 ltags itags prop)
7780 ;; Try to find a local archive location
7781 (save-excursion
7782 (save-restriction
7783 (widen)
7784 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
7785 (if (and prop (string-match "\\S-" prop))
7786 (setq org-archive-location prop)
7787 (if (or (re-search-backward re nil t)
7788 (re-search-forward re nil t))
7789 (setq org-archive-location (match-string 1))))))
7791 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
7792 (progn
7793 (setq afile (format (match-string 1 org-archive-location)
7794 (file-name-nondirectory buffer-file-name))
7795 heading (match-string 2 org-archive-location)))
7796 (error "Invalid `org-archive-location'"))
7797 (if (> (length afile) 0)
7798 (setq newfile-p (not (file-exists-p afile))
7799 buffer (find-file-noselect afile))
7800 (setq buffer (current-buffer)))
7801 (unless buffer
7802 (error "Cannot access file \"%s\"" afile))
7803 (if (and (> (length heading) 0)
7804 (string-match "^\\*+" heading))
7805 (setq level (match-end 0))
7806 (setq heading nil level 0))
7807 (save-excursion
7808 (org-back-to-heading t)
7809 ;; Get context information that will be lost by moving the tree
7810 (org-refresh-category-properties)
7811 (setq category (org-get-category)
7812 todo (and (looking-at org-todo-line-regexp)
7813 (match-string 2))
7814 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
7815 ltags (org-get-tags)
7816 itags (org-delete-all ltags (org-get-tags-at)))
7817 (setq ltags (mapconcat 'identity ltags " ")
7818 itags (mapconcat 'identity itags " "))
7819 ;; We first only copy, in case something goes wrong
7820 ;; we need to protect this-command, to avoid kill-region sets it,
7821 ;; which would lead to duplication of subtrees
7822 (let (this-command) (org-copy-subtree))
7823 (set-buffer buffer)
7824 ;; Enforce org-mode for the archive buffer
7825 (if (not (org-mode-p))
7826 ;; Force the mode for future visits.
7827 (let ((org-insert-mode-line-in-empty-file t)
7828 (org-inhibit-startup t))
7829 (call-interactively 'org-mode)))
7830 (when newfile-p
7831 (goto-char (point-max))
7832 (insert (format "\nArchived entries from file %s\n\n"
7833 (buffer-file-name this-buffer))))
7834 ;; Force the TODO keywords of the original buffer
7835 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
7836 (org-todo-keywords-1 tr-org-todo-keywords-1)
7837 (org-todo-kwd-alist tr-org-todo-kwd-alist)
7838 (org-done-keywords tr-org-done-keywords)
7839 (org-todo-regexp tr-org-todo-regexp)
7840 (org-todo-line-regexp tr-org-todo-line-regexp)
7841 (org-odd-levels-only
7842 (if (local-variable-p 'org-odd-levels-only (current-buffer))
7843 org-odd-levels-only
7844 tr-org-odd-levels-only)))
7845 (goto-char (point-min))
7846 (if heading
7847 (progn
7848 (if (re-search-forward
7849 (concat "^" (regexp-quote heading)
7850 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
7851 nil t)
7852 (goto-char (match-end 0))
7853 ;; Heading not found, just insert it at the end
7854 (goto-char (point-max))
7855 (or (bolp) (insert "\n"))
7856 (insert "\n" heading "\n")
7857 (end-of-line 0))
7858 ;; Make the subtree visible
7859 (show-subtree)
7860 (org-end-of-subtree t)
7861 (skip-chars-backward " \t\r\n")
7862 (and (looking-at "[ \t\r\n]*")
7863 (replace-match "\n\n")))
7864 ;; No specific heading, just go to end of file.
7865 (goto-char (point-max)) (insert "\n"))
7866 ;; Paste
7867 (org-paste-subtree (org-get-legal-level level 1))
7869 ;; Mark the entry as done
7870 (when (and org-archive-mark-done
7871 (looking-at org-todo-line-regexp)
7872 (or (not (match-end 2))
7873 (not (member (match-string 2) org-done-keywords))))
7874 (let (org-log-done)
7875 (org-todo
7876 (car (or (member org-archive-mark-done org-done-keywords)
7877 org-done-keywords)))))
7879 ;; Add the context info
7880 (when org-archive-save-context-info
7881 (let ((l org-archive-save-context-info) e n v)
7882 (while (setq e (pop l))
7883 (when (and (setq v (symbol-value e))
7884 (stringp v) (string-match "\\S-" v))
7885 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
7886 (org-entry-put (point) n v)))))
7888 ;; Save the buffer, if it is not the same buffer.
7889 (if (not (eq this-buffer buffer)) (save-buffer))))
7890 ;; Here we are back in the original buffer. Everything seems to have
7891 ;; worked. So now cut the tree and finish up.
7892 (let (this-command) (org-cut-subtree))
7893 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
7894 (message "Subtree archived %s"
7895 (if (eq this-buffer buffer)
7896 (concat "under heading: " heading)
7897 (concat "in file: " (abbreviate-file-name afile)))))))
7899 (defun org-refresh-category-properties ()
7900 "Refresh category text properties in teh buffer."
7901 (let ((def-cat (cond
7902 ((null org-category)
7903 (if buffer-file-name
7904 (file-name-sans-extension
7905 (file-name-nondirectory buffer-file-name))
7906 "???"))
7907 ((symbolp org-category) (symbol-name org-category))
7908 (t org-category)))
7909 beg end cat pos optionp)
7910 (org-unmodified
7911 (save-excursion
7912 (save-restriction
7913 (widen)
7914 (goto-char (point-min))
7915 (put-text-property (point) (point-max) 'org-category def-cat)
7916 (while (re-search-forward
7917 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7918 (setq pos (match-end 0)
7919 optionp (equal (char-after (match-beginning 0)) ?#)
7920 cat (org-trim (match-string 2)))
7921 (if optionp
7922 (setq beg (point-at-bol) end (point-max))
7923 (org-back-to-heading t)
7924 (setq beg (point) end (org-end-of-subtree t t)))
7925 (put-text-property beg end 'org-category cat)
7926 (goto-char pos)))))))
7928 (defun org-archive-all-done (&optional tag)
7929 "Archive sublevels of the current tree without open TODO items.
7930 If the cursor is not on a headline, try all level 1 trees. If
7931 it is on a headline, try all direct children.
7932 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
7933 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
7934 (rea (concat ".*:" org-archive-tag ":"))
7935 (begm (make-marker))
7936 (endm (make-marker))
7937 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
7938 "Move subtree to archive (no open TODO items)? "))
7939 beg end (cntarch 0))
7940 (if (org-on-heading-p)
7941 (progn
7942 (setq re1 (concat "^" (regexp-quote
7943 (make-string
7944 (1+ (- (match-end 0) (match-beginning 0) 1))
7945 ?*))
7946 " "))
7947 (move-marker begm (point))
7948 (move-marker endm (org-end-of-subtree t)))
7949 (setq re1 "^* ")
7950 (move-marker begm (point-min))
7951 (move-marker endm (point-max)))
7952 (save-excursion
7953 (goto-char begm)
7954 (while (re-search-forward re1 endm t)
7955 (setq beg (match-beginning 0)
7956 end (save-excursion (org-end-of-subtree t) (point)))
7957 (goto-char beg)
7958 (if (re-search-forward re end t)
7959 (goto-char end)
7960 (goto-char beg)
7961 (if (and (or (not tag) (not (looking-at rea)))
7962 (y-or-n-p question))
7963 (progn
7964 (if tag
7965 (org-toggle-tag org-archive-tag 'on)
7966 (org-archive-subtree))
7967 (setq cntarch (1+ cntarch)))
7968 (goto-char end)))))
7969 (message "%d trees archived" cntarch)))
7971 (defun org-cycle-hide-drawers (state)
7972 "Re-hide all drawers after a visibility state change."
7973 (when (and (org-mode-p)
7974 (not (memq state '(overview folded))))
7975 (save-excursion
7976 (let* ((globalp (memq state '(contents all)))
7977 (beg (if globalp (point-min) (point)))
7978 (end (if globalp (point-max) (org-end-of-subtree t))))
7979 (goto-char beg)
7980 (while (re-search-forward org-drawer-regexp end t)
7981 (org-flag-drawer t))))))
7983 (defun org-flag-drawer (flag)
7984 (save-excursion
7985 (beginning-of-line 1)
7986 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7987 (let ((b (match-end 0))
7988 (outline-regexp org-outline-regexp))
7989 (if (re-search-forward
7990 "^[ \t]*:END:"
7991 (save-excursion (outline-next-heading) (point)) t)
7992 (outline-flag-region b (point-at-eol) flag)
7993 (error ":END: line missing"))))))
7995 (defun org-cycle-hide-archived-subtrees (state)
7996 "Re-hide all archived subtrees after a visibility state change."
7997 (when (and (not org-cycle-open-archived-trees)
7998 (not (memq state '(overview folded))))
7999 (save-excursion
8000 (let* ((globalp (memq state '(contents all)))
8001 (beg (if globalp (point-min) (point)))
8002 (end (if globalp (point-max) (org-end-of-subtree t))))
8003 (org-hide-archived-subtrees beg end)
8004 (goto-char beg)
8005 (if (looking-at (concat ".*:" org-archive-tag ":"))
8006 (message "%s" (substitute-command-keys
8007 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
8009 (defun org-force-cycle-archived ()
8010 "Cycle subtree even if it is archived."
8011 (interactive)
8012 (setq this-command 'org-cycle)
8013 (let ((org-cycle-open-archived-trees t))
8014 (call-interactively 'org-cycle)))
8016 (defun org-hide-archived-subtrees (beg end)
8017 "Re-hide all archived subtrees after a visibility state change."
8018 (save-excursion
8019 (let* ((re (concat ":" org-archive-tag ":")))
8020 (goto-char beg)
8021 (while (re-search-forward re end t)
8022 (and (org-on-heading-p) (hide-subtree))
8023 (org-end-of-subtree t)))))
8025 (defun org-toggle-tag (tag &optional onoff)
8026 "Toggle the tag TAG for the current line.
8027 If ONOFF is `on' or `off', don't toggle but set to this state."
8028 (unless (org-on-heading-p t) (error "Not on headling"))
8029 (let (res current)
8030 (save-excursion
8031 (beginning-of-line)
8032 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8033 (point-at-eol) t)
8034 (progn
8035 (setq current (match-string 1))
8036 (replace-match ""))
8037 (setq current ""))
8038 (setq current (nreverse (org-split-string current ":")))
8039 (cond
8040 ((eq onoff 'on)
8041 (setq res t)
8042 (or (member tag current) (push tag current)))
8043 ((eq onoff 'off)
8044 (or (not (member tag current)) (setq current (delete tag current))))
8045 (t (if (member tag current)
8046 (setq current (delete tag current))
8047 (setq res t)
8048 (push tag current))))
8049 (end-of-line 1)
8050 (if current
8051 (progn
8052 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8053 (org-set-tags nil t))
8054 (delete-horizontal-space))
8055 (run-hooks 'org-after-tags-change-hook))
8056 res))
8058 (defun org-toggle-archive-tag (&optional arg)
8059 "Toggle the archive tag for the current headline.
8060 With prefix ARG, check all children of current headline and offer tagging
8061 the children that do not contain any open TODO items."
8062 (interactive "P")
8063 (if arg
8064 (org-archive-all-done 'tag)
8065 (let (set)
8066 (save-excursion
8067 (org-back-to-heading t)
8068 (setq set (org-toggle-tag org-archive-tag))
8069 (when set (hide-subtree)))
8070 (and set (beginning-of-line 1))
8071 (message "Subtree %s" (if set "archived" "unarchived")))))
8074 ;;;; Tables
8076 ;;; The table editor
8078 ;; Watch out: Here we are talking about two different kind of tables.
8079 ;; Most of the code is for the tables created with the Org-mode table editor.
8080 ;; Sometimes, we talk about tables created and edited with the table.el
8081 ;; Emacs package. We call the former org-type tables, and the latter
8082 ;; table.el-type tables.
8084 (defun org-before-change-function (beg end)
8085 "Every change indicates that a table might need an update."
8086 (setq org-table-may-need-update t))
8088 (defconst org-table-line-regexp "^[ \t]*|"
8089 "Detects an org-type table line.")
8090 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8091 "Detects an org-type table line.")
8092 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8093 "Detects a table line marked for automatic recalculation.")
8094 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8095 "Detects a table line marked for automatic recalculation.")
8096 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8097 "Detects a table line marked for automatic recalculation.")
8098 (defconst org-table-hline-regexp "^[ \t]*|-"
8099 "Detects an org-type table hline.")
8100 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8101 "Detects a table-type table hline.")
8102 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8103 "Detects an org-type or table-type table.")
8104 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8105 "Searching from within a table (any type) this finds the first line
8106 outside the table.")
8107 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8108 "Searching from within a table (any type) this finds the first line
8109 outside the table.")
8111 (defvar org-table-last-highlighted-reference nil)
8112 (defvar org-table-formula-history nil)
8114 (defvar org-table-column-names nil
8115 "Alist with column names, derived from the `!' line.")
8116 (defvar org-table-column-name-regexp nil
8117 "Regular expression matching the current column names.")
8118 (defvar org-table-local-parameters nil
8119 "Alist with parameter names, derived from the `$' line.")
8120 (defvar org-table-named-field-locations nil
8121 "Alist with locations of named fields.")
8123 (defvar org-table-current-line-types nil
8124 "Table row types, non-nil only for the duration of a comand.")
8125 (defvar org-table-current-begin-line nil
8126 "Table begin line, non-nil only for the duration of a comand.")
8127 (defvar org-table-current-begin-pos nil
8128 "Table begin position, non-nil only for the duration of a comand.")
8129 (defvar org-table-dlines nil
8130 "Vector of data line line numbers in the current table.")
8131 (defvar org-table-hlines nil
8132 "Vector of hline line numbers in the current table.")
8134 (defconst org-table-range-regexp
8135 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
8136 ;; 1 2 3 4 5
8137 "Regular expression for matching ranges in formulas.")
8139 (defconst org-table-range-regexp2
8140 (concat
8141 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
8142 "\\.\\."
8143 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8144 "Match a range for reference display.")
8146 (defconst org-table-translate-regexp
8147 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8148 "Match a reference that needs translation, for reference display.")
8150 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8152 (defun org-table-create-with-table.el ()
8153 "Use the table.el package to insert a new table.
8154 If there is already a table at point, convert between Org-mode tables
8155 and table.el tables."
8156 (interactive)
8157 (require 'table)
8158 (cond
8159 ((org-at-table.el-p)
8160 (if (y-or-n-p "Convert table to Org-mode table? ")
8161 (org-table-convert)))
8162 ((org-at-table-p)
8163 (if (y-or-n-p "Convert table to table.el table? ")
8164 (org-table-convert)))
8165 (t (call-interactively 'table-insert))))
8167 (defun org-table-create-or-convert-from-region (arg)
8168 "Convert region to table, or create an empty table.
8169 If there is an active region, convert it to a table, using the function
8170 `org-table-convert-region'. See the documentation of that function
8171 to learn how the prefix argument is interpreted to determine the field
8172 separator.
8173 If there is no such region, create an empty table with `org-table-create'."
8174 (interactive "P")
8175 (if (org-region-active-p)
8176 (org-table-convert-region (region-beginning) (region-end) arg)
8177 (org-table-create arg)))
8179 (defun org-table-create (&optional size)
8180 "Query for a size and insert a table skeleton.
8181 SIZE is a string Columns x Rows like for example \"3x2\"."
8182 (interactive "P")
8183 (unless size
8184 (setq size (read-string
8185 (concat "Table size Columns x Rows [e.g. "
8186 org-table-default-size "]: ")
8187 "" nil org-table-default-size)))
8189 (let* ((pos (point))
8190 (indent (make-string (current-column) ?\ ))
8191 (split (org-split-string size " *x *"))
8192 (rows (string-to-number (nth 1 split)))
8193 (columns (string-to-number (car split)))
8194 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8195 "\n")))
8196 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8197 (point-at-bol) (point)))
8198 (beginning-of-line 1)
8199 (newline))
8200 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8201 (dotimes (i rows) (insert line))
8202 (goto-char pos)
8203 (if (> rows 1)
8204 ;; Insert a hline after the first row.
8205 (progn
8206 (end-of-line 1)
8207 (insert "\n|-")
8208 (goto-char pos)))
8209 (org-table-align)))
8211 (defun org-table-convert-region (beg0 end0 &optional separator)
8212 "Convert region to a table.
8213 The region goes from BEG0 to END0, but these borders will be moved
8214 slightly, to make sure a beginning of line in the first line is included.
8216 SEPARATOR specifies the field separator in the lines. It can have the
8217 following values:
8219 '(4) Use the comma as a field separator
8220 '(16) Use a TAB as field separator
8221 integer When a number, use that many spaces as field separator
8222 nil When nil, the command tries to be smart and figure out the
8223 separator in the following way:
8224 - when each line contains a TAB, assume TAB-separated material
8225 - when each line contains a comme, assume CSV material
8226 - else, assume one or more SPACE charcters as separator."
8227 (interactive "rP")
8228 (let* ((beg (min beg0 end0))
8229 (end (max beg0 end0))
8231 (goto-char beg)
8232 (beginning-of-line 1)
8233 (setq beg (move-marker (make-marker) (point)))
8234 (goto-char end)
8235 (if (bolp) (backward-char 1) (end-of-line 1))
8236 (setq end (move-marker (make-marker) (point)))
8237 ;; Get the right field separator
8238 (unless separator
8239 (goto-char beg)
8240 (setq separator
8241 (cond
8242 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8243 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8244 (t 1))))
8245 (setq re (cond
8246 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8247 ((equal separator '(16)) "^\\|\t")
8248 ((integerp separator)
8249 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8250 (t (error "This should not happen"))))
8251 (goto-char beg)
8252 (while (re-search-forward re end t)
8253 (replace-match "| " t t))
8254 (goto-char beg)
8255 (insert " ")
8256 (org-table-align)))
8258 (defun org-table-import (file arg)
8259 "Import FILE as a table.
8260 The file is assumed to be tab-separated. Such files can be produced by most
8261 spreadsheet and database applications. If no tabs (at least one per line)
8262 are found, lines will be split on whitespace into fields."
8263 (interactive "f\nP")
8264 (or (bolp) (newline))
8265 (let ((beg (point))
8266 (pm (point-max)))
8267 (insert-file-contents file)
8268 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8270 (defun org-table-export ()
8271 "Export table as a tab-separated file.
8272 Such a file can be imported into a spreadsheet program like Excel."
8273 (interactive)
8274 (let* ((beg (org-table-begin))
8275 (end (org-table-end))
8276 (table (buffer-substring beg end))
8277 (file (read-file-name "Export table to: "))
8278 buf)
8279 (unless (or (not (file-exists-p file))
8280 (y-or-n-p (format "Overwrite file %s? " file)))
8281 (error "Abort"))
8282 (with-current-buffer (find-file-noselect file)
8283 (setq buf (current-buffer))
8284 (erase-buffer)
8285 (fundamental-mode)
8286 (insert table)
8287 (goto-char (point-min))
8288 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8289 (replace-match "" t t)
8290 (end-of-line 1))
8291 (goto-char (point-min))
8292 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8293 (replace-match "" t t)
8294 (goto-char (min (1+ (point)) (point-max))))
8295 (goto-char (point-min))
8296 (while (re-search-forward "^-[-+]*$" nil t)
8297 (replace-match "")
8298 (if (looking-at "\n")
8299 (delete-char 1)))
8300 (goto-char (point-min))
8301 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8302 (replace-match "\t" t t))
8303 (save-buffer))
8304 (kill-buffer buf)))
8306 (defvar org-table-aligned-begin-marker (make-marker)
8307 "Marker at the beginning of the table last aligned.
8308 Used to check if cursor still is in that table, to minimize realignment.")
8309 (defvar org-table-aligned-end-marker (make-marker)
8310 "Marker at the end of the table last aligned.
8311 Used to check if cursor still is in that table, to minimize realignment.")
8312 (defvar org-table-last-alignment nil
8313 "List of flags for flushright alignment, from the last re-alignment.
8314 This is being used to correctly align a single field after TAB or RET.")
8315 (defvar org-table-last-column-widths nil
8316 "List of max width of fields in each column.
8317 This is being used to correctly align a single field after TAB or RET.")
8318 (defvar org-table-overlay-coordinates nil
8319 "Overlay coordinates after each align of a table.")
8320 (make-variable-buffer-local 'org-table-overlay-coordinates)
8322 (defvar org-last-recalc-line nil)
8323 (defconst org-narrow-column-arrow "=>"
8324 "Used as display property in narrowed table columns.")
8326 (defun org-table-align ()
8327 "Align the table at point by aligning all vertical bars."
8328 (interactive)
8329 (let* (
8330 ;; Limits of table
8331 (beg (org-table-begin))
8332 (end (org-table-end))
8333 ;; Current cursor position
8334 (linepos (org-current-line))
8335 (colpos (org-table-current-column))
8336 (winstart (window-start))
8337 (winstartline (org-current-line (min winstart (1- (point-max)))))
8338 lines (new "") lengths l typenums ty fields maxfields i
8339 column
8340 (indent "") cnt frac
8341 rfmt hfmt
8342 (spaces '(1 . 1))
8343 (sp1 (car spaces))
8344 (sp2 (cdr spaces))
8345 (rfmt1 (concat
8346 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8347 (hfmt1 (concat
8348 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8349 emptystrings links dates emph narrow fmax f1 len c e)
8350 (untabify beg end)
8351 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8352 ;; Check if we have links or dates
8353 (goto-char beg)
8354 (setq links (re-search-forward org-bracket-link-regexp end t))
8355 (goto-char beg)
8356 (setq emph (and org-hide-emphasis-markers
8357 (re-search-forward org-emph-re end t)))
8358 (goto-char beg)
8359 (setq dates (and org-display-custom-times
8360 (re-search-forward org-ts-regexp-both end t)))
8361 ;; Make sure the link properties are right
8362 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8363 ;; Make sure the date properties are right
8364 (when dates (goto-char beg) (while (org-activate-dates end)))
8365 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8367 ;; Check if we are narrowing any columns
8368 (goto-char beg)
8369 (setq narrow (and org-format-transports-properties-p
8370 (re-search-forward "<[0-9]+>" end t)))
8371 ;; Get the rows
8372 (setq lines (org-split-string
8373 (buffer-substring beg end) "\n"))
8374 ;; Store the indentation of the first line
8375 (if (string-match "^ *" (car lines))
8376 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8377 ;; Mark the hlines by setting the corresponding element to nil
8378 ;; At the same time, we remove trailing space.
8379 (setq lines (mapcar (lambda (l)
8380 (if (string-match "^ *|-" l)
8382 (if (string-match "[ \t]+$" l)
8383 (substring l 0 (match-beginning 0))
8384 l)))
8385 lines))
8386 ;; Get the data fields by splitting the lines.
8387 (setq fields (mapcar
8388 (lambda (l)
8389 (org-split-string l " *| *"))
8390 (delq nil (copy-sequence lines))))
8391 ;; How many fields in the longest line?
8392 (condition-case nil
8393 (setq maxfields (apply 'max (mapcar 'length fields)))
8394 (error
8395 (kill-region beg end)
8396 (org-table-create org-table-default-size)
8397 (error "Empty table - created default table")))
8398 ;; A list of empty strings to fill any short rows on output
8399 (setq emptystrings (make-list maxfields ""))
8400 ;; Check for special formatting.
8401 (setq i -1)
8402 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8403 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8404 ;; Check if there is an explicit width specified
8405 (when narrow
8406 (setq c column fmax nil)
8407 (while c
8408 (setq e (pop c))
8409 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8410 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8411 ;; Find fields that are wider than fmax, and shorten them
8412 (when fmax
8413 (loop for xx in column do
8414 (when (and (stringp xx)
8415 (> (org-string-width xx) fmax))
8416 (org-add-props xx nil
8417 'help-echo
8418 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8419 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8420 (unless (> f1 1)
8421 (error "Cannot narrow field starting with wide link \"%s\""
8422 (match-string 0 xx)))
8423 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8424 (add-text-properties (- f1 2) f1
8425 (list 'display org-narrow-column-arrow)
8426 xx)))))
8427 ;; Get the maximum width for each column
8428 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8429 ;; Get the fraction of numbers, to decide about alignment of the column
8430 (setq cnt 0 frac 0.0)
8431 (loop for x in column do
8432 (if (equal x "")
8434 (setq frac ( / (+ (* frac cnt)
8435 (if (string-match org-table-number-regexp x) 1 0))
8436 (setq cnt (1+ cnt))))))
8437 (push (>= frac org-table-number-fraction) typenums))
8438 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8440 ;; Store the alignment of this table, for later editing of single fields
8441 (setq org-table-last-alignment typenums
8442 org-table-last-column-widths lengths)
8444 ;; With invisible characters, `format' does not get the field width right
8445 ;; So we need to make these fields wide by hand.
8446 (when (or links emph)
8447 (loop for i from 0 upto (1- maxfields) do
8448 (setq len (nth i lengths))
8449 (loop for j from 0 upto (1- (length fields)) do
8450 (setq c (nthcdr i (car (nthcdr j fields))))
8451 (if (and (stringp (car c))
8452 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8453 ; (string-match org-bracket-link-regexp (car c))
8454 (< (org-string-width (car c)) len))
8455 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8457 ;; Compute the formats needed for output of the table
8458 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8459 (while (setq l (pop lengths))
8460 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8461 (setq rfmt (concat rfmt (format rfmt1 ty l))
8462 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8463 (setq rfmt (concat rfmt "\n")
8464 hfmt (concat (substring hfmt 0 -1) "|\n"))
8466 (setq new (mapconcat
8467 (lambda (l)
8468 (if l (apply 'format rfmt
8469 (append (pop fields) emptystrings))
8470 hfmt))
8471 lines ""))
8472 ;; Replace the old one
8473 (delete-region beg end)
8474 (move-marker end nil)
8475 (move-marker org-table-aligned-begin-marker (point))
8476 (insert new)
8477 (move-marker org-table-aligned-end-marker (point))
8478 (when (and orgtbl-mode (not (org-mode-p)))
8479 (goto-char org-table-aligned-begin-marker)
8480 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8481 ;; Try to move to the old location
8482 (goto-line winstartline)
8483 (setq winstart (point-at-bol))
8484 (goto-line linepos)
8485 (set-window-start (selected-window) winstart 'noforce)
8486 (org-table-goto-column colpos)
8487 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8488 (setq org-table-may-need-update nil)
8491 (defun org-string-width (s)
8492 "Compute width of string, ignoring invisible characters.
8493 This ignores character with invisibility property `org-link', and also
8494 characters with property `org-cwidth', because these will become invisible
8495 upon the next fontification round."
8496 (let (b l)
8497 (when (or (eq t buffer-invisibility-spec)
8498 (assq 'org-link buffer-invisibility-spec))
8499 (while (setq b (text-property-any 0 (length s)
8500 'invisible 'org-link s))
8501 (setq s (concat (substring s 0 b)
8502 (substring s (or (next-single-property-change
8503 b 'invisible s) (length s)))))))
8504 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8505 (setq s (concat (substring s 0 b)
8506 (substring s (or (next-single-property-change
8507 b 'org-cwidth s) (length s))))))
8508 (setq l (string-width s) b -1)
8509 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8510 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8513 (defun org-table-begin (&optional table-type)
8514 "Find the beginning of the table and return its position.
8515 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8516 (save-excursion
8517 (if (not (re-search-backward
8518 (if table-type org-table-any-border-regexp
8519 org-table-border-regexp)
8520 nil t))
8521 (progn (goto-char (point-min)) (point))
8522 (goto-char (match-beginning 0))
8523 (beginning-of-line 2)
8524 (point))))
8526 (defun org-table-end (&optional table-type)
8527 "Find the end of the table and return its position.
8528 With argument TABLE-TYPE, go to the end of a table.el-type table."
8529 (save-excursion
8530 (if (not (re-search-forward
8531 (if table-type org-table-any-border-regexp
8532 org-table-border-regexp)
8533 nil t))
8534 (goto-char (point-max))
8535 (goto-char (match-beginning 0)))
8536 (point-marker)))
8538 (defun org-table-justify-field-maybe (&optional new)
8539 "Justify the current field, text to left, number to right.
8540 Optional argument NEW may specify text to replace the current field content."
8541 (cond
8542 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8543 ((org-at-table-hline-p))
8544 ((and (not new)
8545 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8546 (current-buffer)))
8547 (< (point) org-table-aligned-begin-marker)
8548 (>= (point) org-table-aligned-end-marker)))
8549 ;; This is not the same table, force a full re-align
8550 (setq org-table-may-need-update t))
8551 (t ;; realign the current field, based on previous full realign
8552 (let* ((pos (point)) s
8553 (col (org-table-current-column))
8554 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8555 l f n o e)
8556 (when (> col 0)
8557 (skip-chars-backward "^|\n")
8558 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8559 (progn
8560 (setq s (match-string 1)
8561 o (match-string 0)
8562 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8563 e (not (= (match-beginning 2) (match-end 2))))
8564 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8565 l (if e "|" (setq org-table-may-need-update t) ""))
8566 n (format f s))
8567 (if new
8568 (if (<= (length new) l) ;; FIXME: length -> str-width?
8569 (setq n (format f new))
8570 (setq n (concat new "|") org-table-may-need-update t)))
8571 (or (equal n o)
8572 (let (org-table-may-need-update)
8573 (replace-match n t t))))
8574 (setq org-table-may-need-update t))
8575 (goto-char pos))))))
8577 (defun org-table-next-field ()
8578 "Go to the next field in the current table, creating new lines as needed.
8579 Before doing so, re-align the table if necessary."
8580 (interactive)
8581 (org-table-maybe-eval-formula)
8582 (org-table-maybe-recalculate-line)
8583 (if (and org-table-automatic-realign
8584 org-table-may-need-update)
8585 (org-table-align))
8586 (let ((end (org-table-end)))
8587 (if (org-at-table-hline-p)
8588 (end-of-line 1))
8589 (condition-case nil
8590 (progn
8591 (re-search-forward "|" end)
8592 (if (looking-at "[ \t]*$")
8593 (re-search-forward "|" end))
8594 (if (and (looking-at "-")
8595 org-table-tab-jumps-over-hlines
8596 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8597 (goto-char (match-beginning 1)))
8598 (if (looking-at "-")
8599 (progn
8600 (beginning-of-line 0)
8601 (org-table-insert-row 'below))
8602 (if (looking-at " ") (forward-char 1))))
8603 (error
8604 (org-table-insert-row 'below)))))
8606 (defun org-table-previous-field ()
8607 "Go to the previous field in the table.
8608 Before doing so, re-align the table if necessary."
8609 (interactive)
8610 (org-table-justify-field-maybe)
8611 (org-table-maybe-recalculate-line)
8612 (if (and org-table-automatic-realign
8613 org-table-may-need-update)
8614 (org-table-align))
8615 (if (org-at-table-hline-p)
8616 (end-of-line 1))
8617 (re-search-backward "|" (org-table-begin))
8618 (re-search-backward "|" (org-table-begin))
8619 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8620 (re-search-backward "|" (org-table-begin)))
8621 (if (looking-at "| ?")
8622 (goto-char (match-end 0))))
8624 (defun org-table-next-row ()
8625 "Go to the next row (same column) in the current table.
8626 Before doing so, re-align the table if necessary."
8627 (interactive)
8628 (org-table-maybe-eval-formula)
8629 (org-table-maybe-recalculate-line)
8630 (if (or (looking-at "[ \t]*$")
8631 (save-excursion (skip-chars-backward " \t") (bolp)))
8632 (newline)
8633 (if (and org-table-automatic-realign
8634 org-table-may-need-update)
8635 (org-table-align))
8636 (let ((col (org-table-current-column)))
8637 (beginning-of-line 2)
8638 (if (or (not (org-at-table-p))
8639 (org-at-table-hline-p))
8640 (progn
8641 (beginning-of-line 0)
8642 (org-table-insert-row 'below)))
8643 (org-table-goto-column col)
8644 (skip-chars-backward "^|\n\r")
8645 (if (looking-at " ") (forward-char 1)))))
8647 (defun org-table-copy-down (n)
8648 "Copy a field down in the current column.
8649 If the field at the cursor is empty, copy into it the content of the nearest
8650 non-empty field above. With argument N, use the Nth non-empty field.
8651 If the current field is not empty, it is copied down to the next row, and
8652 the cursor is moved with it. Therefore, repeating this command causes the
8653 column to be filled row-by-row.
8654 If the variable `org-table-copy-increment' is non-nil and the field is an
8655 integer or a timestamp, it will be incremented while copying. In the case of
8656 a timestamp, if the cursor is on the year, change the year. If it is on the
8657 month or the day, change that. Point will stay on the current date field
8658 in order to easily repeat the interval."
8659 (interactive "p")
8660 (let* ((colpos (org-table-current-column))
8661 (col (current-column))
8662 (field (org-table-get-field))
8663 (non-empty (string-match "[^ \t]" field))
8664 (beg (org-table-begin))
8665 txt)
8666 (org-table-check-inside-data-field)
8667 (if non-empty
8668 (progn
8669 (setq txt (org-trim field))
8670 (org-table-next-row)
8671 (org-table-blank-field))
8672 (save-excursion
8673 (setq txt
8674 (catch 'exit
8675 (while (progn (beginning-of-line 1)
8676 (re-search-backward org-table-dataline-regexp
8677 beg t))
8678 (org-table-goto-column colpos t)
8679 (if (and (looking-at
8680 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8681 (= (setq n (1- n)) 0))
8682 (throw 'exit (match-string 1))))))))
8683 (if txt
8684 (progn
8685 (if (and org-table-copy-increment
8686 (string-match "^[0-9]+$" txt))
8687 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8688 (insert txt)
8689 (move-to-column col)
8690 (if (and org-table-copy-increment (org-at-timestamp-p t))
8691 (org-timestamp-up 1)
8692 (org-table-maybe-recalculate-line))
8693 (org-table-align)
8694 (move-to-column col))
8695 (error "No non-empty field found"))))
8697 (defun org-table-check-inside-data-field ()
8698 "Is point inside a table data field?
8699 I.e. not on a hline or before the first or after the last column?
8700 This actually throws an error, so it aborts the current command."
8701 (if (or (not (org-at-table-p))
8702 (= (org-table-current-column) 0)
8703 (org-at-table-hline-p)
8704 (looking-at "[ \t]*$"))
8705 (error "Not in table data field")))
8707 (defvar org-table-clip nil
8708 "Clipboard for table regions.")
8710 (defun org-table-blank-field ()
8711 "Blank the current table field or active region."
8712 (interactive)
8713 (org-table-check-inside-data-field)
8714 (if (and (interactive-p) (org-region-active-p))
8715 (let (org-table-clip)
8716 (org-table-cut-region (region-beginning) (region-end)))
8717 (skip-chars-backward "^|")
8718 (backward-char 1)
8719 (if (looking-at "|[^|\n]+")
8720 (let* ((pos (match-beginning 0))
8721 (match (match-string 0))
8722 (len (org-string-width match)))
8723 (replace-match (concat "|" (make-string (1- len) ?\ )))
8724 (goto-char (+ 2 pos))
8725 (substring match 1)))))
8727 (defun org-table-get-field (&optional n replace)
8728 "Return the value of the field in column N of current row.
8729 N defaults to current field.
8730 If REPLACE is a string, replace field with this value. The return value
8731 is always the old value."
8732 (and n (org-table-goto-column n))
8733 (skip-chars-backward "^|\n")
8734 (backward-char 1)
8735 (if (looking-at "|[^|\r\n]*")
8736 (let* ((pos (match-beginning 0))
8737 (val (buffer-substring (1+ pos) (match-end 0))))
8738 (if replace
8739 (replace-match (concat "|" replace) t t))
8740 (goto-char (min (point-at-eol) (+ 2 pos)))
8741 val)
8742 (forward-char 1) ""))
8744 (defun org-table-field-info (arg)
8745 "Show info about the current field, and highlight any reference at point."
8746 (interactive "P")
8747 (org-table-get-specials)
8748 (save-excursion
8749 (let* ((pos (point))
8750 (col (org-table-current-column))
8751 (cname (car (rassoc (int-to-string col) org-table-column-names)))
8752 (name (car (rassoc (list (org-current-line) col)
8753 org-table-named-field-locations)))
8754 (eql (org-table-get-stored-formulas))
8755 (dline (org-table-current-dline))
8756 (ref (format "@%d$%d" dline col))
8757 (ref1 (org-table-convert-refs-to-an ref))
8758 (fequation (or (assoc name eql) (assoc ref eql)))
8759 (cequation (assoc (int-to-string col) eql))
8760 (eqn (or fequation cequation)))
8761 (goto-char pos)
8762 (condition-case nil
8763 (org-table-show-reference 'local)
8764 (error nil))
8765 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
8766 dline col
8767 (if cname (concat " or $" cname) "")
8768 dline col ref1
8769 (if name (concat " or $" name) "")
8770 ;; FIXME: formula info not correct if special table line
8771 (if eqn
8772 (concat ", formula: "
8773 (org-table-formula-to-user
8774 (concat
8775 (if (string-match "^[$@]"(car eqn)) "" "$")
8776 (car eqn) "=" (cdr eqn))))
8777 "")))))
8779 (defun org-table-current-column ()
8780 "Find out which column we are in.
8781 When called interactively, column is also displayed in echo area."
8782 (interactive)
8783 (if (interactive-p) (org-table-check-inside-data-field))
8784 (save-excursion
8785 (let ((cnt 0) (pos (point)))
8786 (beginning-of-line 1)
8787 (while (search-forward "|" pos t)
8788 (setq cnt (1+ cnt)))
8789 (if (interactive-p) (message "This is table column %d" cnt))
8790 cnt)))
8792 (defun org-table-current-dline ()
8793 "Find out what table data line we are in.
8794 Only datalins count for this."
8795 (interactive)
8796 (if (interactive-p) (org-table-check-inside-data-field))
8797 (save-excursion
8798 (let ((cnt 0) (pos (point)))
8799 (goto-char (org-table-begin))
8800 (while (<= (point) pos)
8801 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
8802 (beginning-of-line 2))
8803 (if (interactive-p) (message "This is table line %d" cnt))
8804 cnt)))
8806 (defun org-table-goto-column (n &optional on-delim force)
8807 "Move the cursor to the Nth column in the current table line.
8808 With optional argument ON-DELIM, stop with point before the left delimiter
8809 of the field.
8810 If there are less than N fields, just go to after the last delimiter.
8811 However, when FORCE is non-nil, create new columns if necessary."
8812 (interactive "p")
8813 (let ((pos (point-at-eol)))
8814 (beginning-of-line 1)
8815 (when (> n 0)
8816 (while (and (> (setq n (1- n)) -1)
8817 (or (search-forward "|" pos t)
8818 (and force
8819 (progn (end-of-line 1)
8820 (skip-chars-backward "^|")
8821 (insert " | "))))))
8822 ; (backward-char 2) t)))))
8823 (when (and force (not (looking-at ".*|")))
8824 (save-excursion (end-of-line 1) (insert " | ")))
8825 (if on-delim
8826 (backward-char 1)
8827 (if (looking-at " ") (forward-char 1))))))
8829 (defun org-at-table-p (&optional table-type)
8830 "Return t if the cursor is inside an org-type table.
8831 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8832 (if org-enable-table-editor
8833 (save-excursion
8834 (beginning-of-line 1)
8835 (looking-at (if table-type org-table-any-line-regexp
8836 org-table-line-regexp)))
8837 nil))
8839 (defun org-at-table.el-p ()
8840 "Return t if and only if we are at a table.el table."
8841 (and (org-at-table-p 'any)
8842 (save-excursion
8843 (goto-char (org-table-begin 'any))
8844 (looking-at org-table1-hline-regexp))))
8846 (defun org-table-recognize-table.el ()
8847 "If there is a table.el table nearby, recognize it and move into it."
8848 (if org-table-tab-recognizes-table.el
8849 (if (org-at-table.el-p)
8850 (progn
8851 (beginning-of-line 1)
8852 (if (looking-at org-table-dataline-regexp)
8854 (if (looking-at org-table1-hline-regexp)
8855 (progn
8856 (beginning-of-line 2)
8857 (if (looking-at org-table-any-border-regexp)
8858 (beginning-of-line -1)))))
8859 (if (re-search-forward "|" (org-table-end t) t)
8860 (progn
8861 (require 'table)
8862 (if (table--at-cell-p (point))
8864 (message "recognizing table.el table...")
8865 (table-recognize-table)
8866 (message "recognizing table.el table...done")))
8867 (error "This should not happen..."))
8869 nil)
8870 nil))
8872 (defun org-at-table-hline-p ()
8873 "Return t if the cursor is inside a hline in a table."
8874 (if org-enable-table-editor
8875 (save-excursion
8876 (beginning-of-line 1)
8877 (looking-at org-table-hline-regexp))
8878 nil))
8880 (defun org-table-insert-column ()
8881 "Insert a new column into the table."
8882 (interactive)
8883 (if (not (org-at-table-p))
8884 (error "Not at a table"))
8885 (org-table-find-dataline)
8886 (let* ((col (max 1 (org-table-current-column)))
8887 (beg (org-table-begin))
8888 (end (org-table-end))
8889 ;; Current cursor position
8890 (linepos (org-current-line))
8891 (colpos col))
8892 (goto-char beg)
8893 (while (< (point) end)
8894 (if (org-at-table-hline-p)
8896 (org-table-goto-column col t)
8897 (insert "| "))
8898 (beginning-of-line 2))
8899 (move-marker end nil)
8900 (goto-line linepos)
8901 (org-table-goto-column colpos)
8902 (org-table-align)
8903 (org-table-fix-formulas "$" nil (1- col) 1)))
8905 (defun org-table-find-dataline ()
8906 "Find a dataline in the current table, which is needed for column commands."
8907 (if (and (org-at-table-p)
8908 (not (org-at-table-hline-p)))
8910 (let ((col (current-column))
8911 (end (org-table-end)))
8912 (move-to-column col)
8913 (while (and (< (point) end)
8914 (or (not (= (current-column) col))
8915 (org-at-table-hline-p)))
8916 (beginning-of-line 2)
8917 (move-to-column col))
8918 (if (and (org-at-table-p)
8919 (not (org-at-table-hline-p)))
8921 (error
8922 "Please position cursor in a data line for column operations")))))
8924 (defun org-table-delete-column ()
8925 "Delete a column from the table."
8926 (interactive)
8927 (if (not (org-at-table-p))
8928 (error "Not at a table"))
8929 (org-table-find-dataline)
8930 (org-table-check-inside-data-field)
8931 (let* ((col (org-table-current-column))
8932 (beg (org-table-begin))
8933 (end (org-table-end))
8934 ;; Current cursor position
8935 (linepos (org-current-line))
8936 (colpos col))
8937 (goto-char beg)
8938 (while (< (point) end)
8939 (if (org-at-table-hline-p)
8941 (org-table-goto-column col t)
8942 (and (looking-at "|[^|\n]+|")
8943 (replace-match "|")))
8944 (beginning-of-line 2))
8945 (move-marker end nil)
8946 (goto-line linepos)
8947 (org-table-goto-column colpos)
8948 (org-table-align)
8949 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
8950 col -1 col)))
8952 (defun org-table-move-column-right ()
8953 "Move column to the right."
8954 (interactive)
8955 (org-table-move-column nil))
8956 (defun org-table-move-column-left ()
8957 "Move column to the left."
8958 (interactive)
8959 (org-table-move-column 'left))
8961 (defun org-table-move-column (&optional left)
8962 "Move the current column to the right. With arg LEFT, move to the left."
8963 (interactive "P")
8964 (if (not (org-at-table-p))
8965 (error "Not at a table"))
8966 (org-table-find-dataline)
8967 (org-table-check-inside-data-field)
8968 (let* ((col (org-table-current-column))
8969 (col1 (if left (1- col) col))
8970 (beg (org-table-begin))
8971 (end (org-table-end))
8972 ;; Current cursor position
8973 (linepos (org-current-line))
8974 (colpos (if left (1- col) (1+ col))))
8975 (if (and left (= col 1))
8976 (error "Cannot move column further left"))
8977 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8978 (error "Cannot move column further right"))
8979 (goto-char beg)
8980 (while (< (point) end)
8981 (if (org-at-table-hline-p)
8983 (org-table-goto-column col1 t)
8984 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8985 (replace-match "|\\2|\\1|")))
8986 (beginning-of-line 2))
8987 (move-marker end nil)
8988 (goto-line linepos)
8989 (org-table-goto-column colpos)
8990 (org-table-align)
8991 (org-table-fix-formulas
8992 "$" (list (cons (number-to-string col) (number-to-string colpos))
8993 (cons (number-to-string colpos) (number-to-string col))))))
8995 (defun org-table-move-row-down ()
8996 "Move table row down."
8997 (interactive)
8998 (org-table-move-row nil))
8999 (defun org-table-move-row-up ()
9000 "Move table row up."
9001 (interactive)
9002 (org-table-move-row 'up))
9004 (defun org-table-move-row (&optional up)
9005 "Move the current table line down. With arg UP, move it up."
9006 (interactive "P")
9007 (let* ((col (current-column))
9008 (pos (point))
9009 (hline1p (save-excursion (beginning-of-line 1)
9010 (looking-at org-table-hline-regexp)))
9011 (dline1 (org-table-current-dline))
9012 (dline2 (+ dline1 (if up -1 1)))
9013 (tonew (if up 0 2))
9014 txt hline2p)
9015 (beginning-of-line tonew)
9016 (unless (org-at-table-p)
9017 (goto-char pos)
9018 (error "Cannot move row further"))
9019 (setq hline2p (looking-at org-table-hline-regexp))
9020 (goto-char pos)
9021 (beginning-of-line 1)
9022 (setq pos (point))
9023 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9024 (delete-region (point) (1+ (point-at-eol)))
9025 (beginning-of-line tonew)
9026 (insert txt)
9027 (beginning-of-line 0)
9028 (move-to-column col)
9029 (unless (or hline1p hline2p)
9030 (org-table-fix-formulas
9031 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
9032 (cons (number-to-string dline2) (number-to-string dline1)))))))
9034 (defun org-table-insert-row (&optional arg)
9035 "Insert a new row above the current line into the table.
9036 With prefix ARG, insert below the current line."
9037 (interactive "P")
9038 (if (not (org-at-table-p))
9039 (error "Not at a table"))
9040 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9041 (new (org-table-clean-line line)))
9042 ;; Fix the first field if necessary
9043 (if (string-match "^[ \t]*| *[#$] *|" line)
9044 (setq new (replace-match (match-string 0 line) t t new)))
9045 (beginning-of-line (if arg 2 1))
9046 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9047 (beginning-of-line 0)
9048 (re-search-forward "| ?" (point-at-eol) t)
9049 (and (or org-table-may-need-update org-table-overlay-coordinates)
9050 (org-table-align))
9051 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
9053 (defun org-table-insert-hline (&optional above)
9054 "Insert a horizontal-line below the current line into the table.
9055 With prefix ABOVE, insert above the current line."
9056 (interactive "P")
9057 (if (not (org-at-table-p))
9058 (error "Not at a table"))
9059 (let ((line (org-table-clean-line
9060 (buffer-substring (point-at-bol) (point-at-eol))))
9061 (col (current-column)))
9062 (while (string-match "|\\( +\\)|" line)
9063 (setq line (replace-match
9064 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9065 ?-) "|") t t line)))
9066 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9067 (beginning-of-line (if above 1 2))
9068 (insert line "\n")
9069 (beginning-of-line (if above 1 -1))
9070 (move-to-column col)
9071 (and org-table-overlay-coordinates (org-table-align))))
9073 (defun org-table-hline-and-move (&optional same-column)
9074 "Insert a hline and move to the row below that line."
9075 (interactive "P")
9076 (let ((col (org-table-current-column)))
9077 (org-table-maybe-eval-formula)
9078 (org-table-maybe-recalculate-line)
9079 (org-table-insert-hline)
9080 (end-of-line 2)
9081 (if (looking-at "\n[ \t]*|-")
9082 (progn (insert "\n|") (org-table-align))
9083 (org-table-next-field))
9084 (if same-column (org-table-goto-column col))))
9086 (defun org-table-clean-line (s)
9087 "Convert a table line S into a string with only \"|\" and space.
9088 In particular, this does handle wide and invisible characters."
9089 (if (string-match "^[ \t]*|-" s)
9090 ;; It's a hline, just map the characters
9091 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
9092 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9093 (setq s (replace-match
9094 (concat "|" (make-string (org-string-width (match-string 1 s))
9095 ?\ ) "|")
9096 t t s)))
9099 (defun org-table-kill-row ()
9100 "Delete the current row or horizontal line from the table."
9101 (interactive)
9102 (if (not (org-at-table-p))
9103 (error "Not at a table"))
9104 (let ((col (current-column))
9105 (dline (org-table-current-dline)))
9106 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9107 (if (not (org-at-table-p)) (beginning-of-line 0))
9108 (move-to-column col)
9109 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
9110 dline -1 dline)))
9112 (defun org-table-sort-lines (with-case &optional sorting-type)
9113 "Sort table lines according to the column at point.
9115 The position of point indicates the column to be used for
9116 sorting, and the range of lines is the range between the nearest
9117 horizontal separator lines, or the entire table of no such lines
9118 exist. If point is before the first column, you will be prompted
9119 for the sorting column. If there is an active region, the mark
9120 specifies the first line and the sorting column, while point
9121 should be in the last line to be included into the sorting.
9123 The command then prompts for the sorting type which can be
9124 alphabetically, numerically, or by time (as given in a time stamp
9125 in the field). Sorting in reverse order is also possible.
9127 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
9129 If SORTING-TYPE is specified when this function is called from a Lisp
9130 program, no prompting will take place. SORTING-TYPE must be a character,
9131 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
9132 should be done in reverse order."
9133 (interactive "P")
9134 (let* ((thisline (org-current-line))
9135 (thiscol (org-table-current-column))
9136 beg end bcol ecol tend tbeg column lns pos)
9137 (when (equal thiscol 0)
9138 (if (interactive-p)
9139 (setq thiscol
9140 (string-to-number
9141 (read-string "Use column N for sorting: ")))
9142 (setq thiscol 1))
9143 (org-table-goto-column thiscol))
9144 (org-table-check-inside-data-field)
9145 (if (org-region-active-p)
9146 (progn
9147 (setq beg (region-beginning) end (region-end))
9148 (goto-char beg)
9149 (setq column (org-table-current-column)
9150 beg (point-at-bol))
9151 (goto-char end)
9152 (setq end (point-at-bol 2)))
9153 (setq column (org-table-current-column)
9154 pos (point)
9155 tbeg (org-table-begin)
9156 tend (org-table-end))
9157 (if (re-search-backward org-table-hline-regexp tbeg t)
9158 (setq beg (point-at-bol 2))
9159 (goto-char tbeg)
9160 (setq beg (point-at-bol 1)))
9161 (goto-char pos)
9162 (if (re-search-forward org-table-hline-regexp tend t)
9163 (setq end (point-at-bol 1))
9164 (goto-char tend)
9165 (setq end (point-at-bol))))
9166 (setq beg (move-marker (make-marker) beg)
9167 end (move-marker (make-marker) end))
9168 (untabify beg end)
9169 (goto-char beg)
9170 (org-table-goto-column column)
9171 (skip-chars-backward "^|")
9172 (setq bcol (current-column))
9173 (org-table-goto-column (1+ column))
9174 (skip-chars-backward "^|")
9175 (setq ecol (1- (current-column)))
9176 (org-table-goto-column column)
9177 (setq lns (mapcar (lambda(x) (cons
9178 (org-sort-remove-invisible
9179 (nth (1- column)
9180 (org-split-string x "[ \t]*|[ \t]*")))
9182 (org-split-string (buffer-substring beg end) "\n")))
9183 (setq lns (org-do-sort lns "Table" with-case sorting-type))
9184 (delete-region beg end)
9185 (move-marker beg nil)
9186 (move-marker end nil)
9187 (insert (mapconcat 'cdr lns "\n") "\n")
9188 (goto-line thisline)
9189 (org-table-goto-column thiscol)
9190 (message "%d lines sorted, based on column %d" (length lns) column)))
9192 ;; FIXME: maybe we will not need this? Table sorting is broken....
9193 (defun org-sort-remove-invisible (s)
9194 (remove-text-properties 0 (length s) org-rm-props s)
9195 (while (string-match org-bracket-link-regexp s)
9196 (setq s (replace-match (if (match-end 2)
9197 (match-string 3 s)
9198 (match-string 1 s)) t t s)))
9201 (defun org-table-cut-region (beg end)
9202 "Copy region in table to the clipboard and blank all relevant fields."
9203 (interactive "r")
9204 (org-table-copy-region beg end 'cut))
9206 (defun org-table-copy-region (beg end &optional cut)
9207 "Copy rectangular region in table to clipboard.
9208 A special clipboard is used which can only be accessed
9209 with `org-table-paste-rectangle'."
9210 (interactive "rP")
9211 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9212 region cols
9213 (rpl (if cut " " nil)))
9214 (goto-char beg)
9215 (org-table-check-inside-data-field)
9216 (setq l01 (org-current-line)
9217 c01 (org-table-current-column))
9218 (goto-char end)
9219 (org-table-check-inside-data-field)
9220 (setq l02 (org-current-line)
9221 c02 (org-table-current-column))
9222 (setq l1 (min l01 l02) l2 (max l01 l02)
9223 c1 (min c01 c02) c2 (max c01 c02))
9224 (catch 'exit
9225 (while t
9226 (catch 'nextline
9227 (if (> l1 l2) (throw 'exit t))
9228 (goto-line l1)
9229 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9230 (setq cols nil ic1 c1 ic2 c2)
9231 (while (< ic1 (1+ ic2))
9232 (push (org-table-get-field ic1 rpl) cols)
9233 (setq ic1 (1+ ic1)))
9234 (push (nreverse cols) region)
9235 (setq l1 (1+ l1)))))
9236 (setq org-table-clip (nreverse region))
9237 (if cut (org-table-align))
9238 org-table-clip))
9240 (defun org-table-paste-rectangle ()
9241 "Paste a rectangular region into a table.
9242 The upper right corner ends up in the current field. All involved fields
9243 will be overwritten. If the rectangle does not fit into the present table,
9244 the table is enlarged as needed. The process ignores horizontal separator
9245 lines."
9246 (interactive)
9247 (unless (and org-table-clip (listp org-table-clip))
9248 (error "First cut/copy a region to paste!"))
9249 (org-table-check-inside-data-field)
9250 (let* ((clip org-table-clip)
9251 (line (org-current-line))
9252 (col (org-table-current-column))
9253 (org-enable-table-editor t)
9254 (org-table-automatic-realign nil)
9255 c cols field)
9256 (while (setq cols (pop clip))
9257 (while (org-at-table-hline-p) (beginning-of-line 2))
9258 (if (not (org-at-table-p))
9259 (progn (end-of-line 0) (org-table-next-field)))
9260 (setq c col)
9261 (while (setq field (pop cols))
9262 (org-table-goto-column c nil 'force)
9263 (org-table-get-field nil field)
9264 (setq c (1+ c)))
9265 (beginning-of-line 2))
9266 (goto-line line)
9267 (org-table-goto-column col)
9268 (org-table-align)))
9270 (defun org-table-convert ()
9271 "Convert from `org-mode' table to table.el and back.
9272 Obviously, this only works within limits. When an Org-mode table is
9273 converted to table.el, all horizontal separator lines get lost, because
9274 table.el uses these as cell boundaries and has no notion of horizontal lines.
9275 A table.el table can be converted to an Org-mode table only if it does not
9276 do row or column spanning. Multiline cells will become multiple cells.
9277 Beware, Org-mode does not test if the table can be successfully converted - it
9278 blindly applies a recipe that works for simple tables."
9279 (interactive)
9280 (require 'table)
9281 (if (org-at-table.el-p)
9282 ;; convert to Org-mode table
9283 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9284 (end (move-marker (make-marker) (org-table-end t))))
9285 (table-unrecognize-region beg end)
9286 (goto-char beg)
9287 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9288 (replace-match ""))
9289 (goto-char beg))
9290 (if (org-at-table-p)
9291 ;; convert to table.el table
9292 (let ((beg (move-marker (make-marker) (org-table-begin)))
9293 (end (move-marker (make-marker) (org-table-end))))
9294 ;; first, get rid of all horizontal lines
9295 (goto-char beg)
9296 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9297 (replace-match ""))
9298 ;; insert a hline before first
9299 (goto-char beg)
9300 (org-table-insert-hline 'above)
9301 (beginning-of-line -1)
9302 ;; insert a hline after each line
9303 (while (progn (beginning-of-line 3) (< (point) end))
9304 (org-table-insert-hline))
9305 (goto-char beg)
9306 (setq end (move-marker end (org-table-end)))
9307 ;; replace "+" at beginning and ending of hlines
9308 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9309 (replace-match "\\1+-"))
9310 (goto-char beg)
9311 (while (re-search-forward "-|[ \t]*$" end t)
9312 (replace-match "-+"))
9313 (goto-char beg)))))
9315 (defun org-table-wrap-region (arg)
9316 "Wrap several fields in a column like a paragraph.
9317 This is useful if you'd like to spread the contents of a field over several
9318 lines, in order to keep the table compact.
9320 If there is an active region, and both point and mark are in the same column,
9321 the text in the column is wrapped to minimum width for the given number of
9322 lines. Generally, this makes the table more compact. A prefix ARG may be
9323 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9324 formats the selected text to two lines. If the region was longer than two
9325 lines, the remaining lines remain empty. A negative prefix argument reduces
9326 the current number of lines by that amount. The wrapped text is pasted back
9327 into the table. If you formatted it to more lines than it was before, fields
9328 further down in the table get overwritten - so you might need to make space in
9329 the table first.
9331 If there is no region, the current field is split at the cursor position and
9332 the text fragment to the right of the cursor is prepended to the field one
9333 line down.
9335 If there is no region, but you specify a prefix ARG, the current field gets
9336 blank, and the content is appended to the field above."
9337 (interactive "P")
9338 (org-table-check-inside-data-field)
9339 (if (org-region-active-p)
9340 ;; There is a region: fill as a paragraph
9341 (let* ((beg (region-beginning))
9342 (cline (save-excursion (goto-char beg) (org-current-line)))
9343 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9344 nlines)
9345 (org-table-cut-region (region-beginning) (region-end))
9346 (if (> (length (car org-table-clip)) 1)
9347 (error "Region must be limited to single column"))
9348 (setq nlines (if arg
9349 (if (< arg 1)
9350 (+ (length org-table-clip) arg)
9351 arg)
9352 (length org-table-clip)))
9353 (setq org-table-clip
9354 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9355 nil nlines)))
9356 (goto-line cline)
9357 (org-table-goto-column ccol)
9358 (org-table-paste-rectangle))
9359 ;; No region, split the current field at point
9360 (if arg
9361 ;; combine with field above
9362 (let ((s (org-table-blank-field))
9363 (col (org-table-current-column)))
9364 (beginning-of-line 0)
9365 (while (org-at-table-hline-p) (beginning-of-line 0))
9366 (org-table-goto-column col)
9367 (skip-chars-forward "^|")
9368 (skip-chars-backward " ")
9369 (insert " " (org-trim s))
9370 (org-table-align))
9371 ;; split field
9372 (when (looking-at "\\([^|]+\\)+|")
9373 (let ((s (match-string 1)))
9374 (replace-match " |")
9375 (goto-char (match-beginning 0))
9376 (org-table-next-row)
9377 (insert (org-trim s) " ")
9378 (org-table-align))))))
9380 (defvar org-field-marker nil)
9382 (defun org-table-edit-field (arg)
9383 "Edit table field in a different window.
9384 This is mainly useful for fields that contain hidden parts.
9385 When called with a \\[universal-argument] prefix, just make the full field visible so that
9386 it can be edited in place."
9387 (interactive "P")
9388 (if arg
9389 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9390 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9391 (remove-text-properties b e '(org-cwidth t invisible t
9392 display t intangible t))
9393 (if (and (boundp 'font-lock-mode) font-lock-mode)
9394 (font-lock-fontify-block)))
9395 (let ((pos (move-marker (make-marker) (point)))
9396 (field (org-table-get-field))
9397 (cw (current-window-configuration))
9399 (org-switch-to-buffer-other-window "*Org tmp*")
9400 (erase-buffer)
9401 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9402 (let ((org-inhibit-startup t)) (org-mode))
9403 (goto-char (setq p (point-max)))
9404 (insert (org-trim field))
9405 (remove-text-properties p (point-max)
9406 '(invisible t org-cwidth t display t
9407 intangible t))
9408 (goto-char p)
9409 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9410 (org-set-local 'org-window-configuration cw)
9411 (org-set-local 'org-field-marker pos)
9412 (message "Edit and finish with C-c C-c"))))
9414 (defun org-table-finish-edit-field ()
9415 "Finish editing a table data field.
9416 Remove all newline characters, insert the result into the table, realign
9417 the table and kill the editing buffer."
9418 (let ((pos org-field-marker)
9419 (cw org-window-configuration)
9420 (cb (current-buffer))
9421 text)
9422 (goto-char (point-min))
9423 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9424 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9425 (replace-match " "))
9426 (setq text (org-trim (buffer-string)))
9427 (set-window-configuration cw)
9428 (kill-buffer cb)
9429 (select-window (get-buffer-window (marker-buffer pos)))
9430 (goto-char pos)
9431 (move-marker pos nil)
9432 (org-table-check-inside-data-field)
9433 (org-table-get-field nil text)
9434 (org-table-align)
9435 (message "New field value inserted")))
9437 (defun org-trim (s)
9438 "Remove whitespace at beginning and end of string."
9439 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9440 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9443 (defun org-wrap (string &optional width lines)
9444 "Wrap string to either a number of lines, or a width in characters.
9445 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9446 that costs. If there is a word longer than WIDTH, the text is actually
9447 wrapped to the length of that word.
9448 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9449 many lines, whatever width that takes.
9450 The return value is a list of lines, without newlines at the end."
9451 (let* ((words (org-split-string string "[ \t\n]+"))
9452 (maxword (apply 'max (mapcar 'org-string-width words)))
9453 w ll)
9454 (cond (width
9455 (org-do-wrap words (max maxword width)))
9456 (lines
9457 (setq w maxword)
9458 (setq ll (org-do-wrap words maxword))
9459 (if (<= (length ll) lines)
9461 (setq ll words)
9462 (while (> (length ll) lines)
9463 (setq w (1+ w))
9464 (setq ll (org-do-wrap words w)))
9465 ll))
9466 (t (error "Cannot wrap this")))))
9469 (defun org-do-wrap (words width)
9470 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9471 (let (lines line)
9472 (while words
9473 (setq line (pop words))
9474 (while (and words (< (+ (length line) (length (car words))) width))
9475 (setq line (concat line " " (pop words))))
9476 (setq lines (push line lines)))
9477 (nreverse lines)))
9479 (defun org-split-string (string &optional separators)
9480 "Splits STRING into substrings at SEPARATORS.
9481 No empty strings are returned if there are matches at the beginning
9482 and end of string."
9483 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9484 (start 0)
9485 notfirst
9486 (list nil))
9487 (while (and (string-match rexp string
9488 (if (and notfirst
9489 (= start (match-beginning 0))
9490 (< start (length string)))
9491 (1+ start) start))
9492 (< (match-beginning 0) (length string)))
9493 (setq notfirst t)
9494 (or (eq (match-beginning 0) 0)
9495 (and (eq (match-beginning 0) (match-end 0))
9496 (eq (match-beginning 0) start))
9497 (setq list
9498 (cons (substring string start (match-beginning 0))
9499 list)))
9500 (setq start (match-end 0)))
9501 (or (eq start (length string))
9502 (setq list
9503 (cons (substring string start)
9504 list)))
9505 (nreverse list)))
9507 (defun org-table-map-tables (function)
9508 "Apply FUNCTION to the start of all tables in the buffer."
9509 (save-excursion
9510 (save-restriction
9511 (widen)
9512 (goto-char (point-min))
9513 (while (re-search-forward org-table-any-line-regexp nil t)
9514 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9515 (beginning-of-line 1)
9516 (if (looking-at org-table-line-regexp)
9517 (save-excursion (funcall function)))
9518 (re-search-forward org-table-any-border-regexp nil 1))))
9519 (message "Mapping tables: done"))
9521 (defvar org-timecnt) ; dynamically scoped parameter
9523 (defun org-table-sum (&optional beg end nlast)
9524 "Sum numbers in region of current table column.
9525 The result will be displayed in the echo area, and will be available
9526 as kill to be inserted with \\[yank].
9528 If there is an active region, it is interpreted as a rectangle and all
9529 numbers in that rectangle will be summed. If there is no active
9530 region and point is located in a table column, sum all numbers in that
9531 column.
9533 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9534 numbers are assumed to be times as well (in decimal hours) and the
9535 numbers are added as such.
9537 If NLAST is a number, only the NLAST fields will actually be summed."
9538 (interactive)
9539 (save-excursion
9540 (let (col (org-timecnt 0) diff h m s org-table-clip)
9541 (cond
9542 ((and beg end)) ; beg and end given explicitly
9543 ((org-region-active-p)
9544 (setq beg (region-beginning) end (region-end)))
9546 (setq col (org-table-current-column))
9547 (goto-char (org-table-begin))
9548 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9549 (error "No table data"))
9550 (org-table-goto-column col)
9551 (setq beg (point))
9552 (goto-char (org-table-end))
9553 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9554 (error "No table data"))
9555 (org-table-goto-column col)
9556 (setq end (point))))
9557 (let* ((items (apply 'append (org-table-copy-region beg end)))
9558 (items1 (cond ((not nlast) items)
9559 ((>= nlast (length items)) items)
9560 (t (setq items (reverse items))
9561 (setcdr (nthcdr (1- nlast) items) nil)
9562 (nreverse items))))
9563 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9564 items1)))
9565 (res (apply '+ numbers))
9566 (sres (if (= org-timecnt 0)
9567 (format "%g" res)
9568 (setq diff (* 3600 res)
9569 h (floor (/ diff 3600)) diff (mod diff 3600)
9570 m (floor (/ diff 60)) diff (mod diff 60)
9571 s diff)
9572 (format "%d:%02d:%02d" h m s))))
9573 (kill-new sres)
9574 (if (interactive-p)
9575 (message "%s"
9576 (substitute-command-keys
9577 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9578 (length numbers) sres))))
9579 sres))))
9581 (defun org-table-get-number-for-summing (s)
9582 (let (n)
9583 (if (string-match "^ *|? *" s)
9584 (setq s (replace-match "" nil nil s)))
9585 (if (string-match " *|? *$" s)
9586 (setq s (replace-match "" nil nil s)))
9587 (setq n (string-to-number s))
9588 (cond
9589 ((and (string-match "0" s)
9590 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9591 ((string-match "\\`[ \t]+\\'" s) nil)
9592 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9593 (let ((h (string-to-number (or (match-string 1 s) "0")))
9594 (m (string-to-number (or (match-string 2 s) "0")))
9595 (s (string-to-number (or (match-string 4 s) "0"))))
9596 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9597 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9598 ((equal n 0) nil)
9599 (t n))))
9601 (defun org-table-current-field-formula (&optional key noerror)
9602 "Return the formula active for the current field.
9603 Assumes that specials are in place.
9604 If KEY is given, return the key to this formula.
9605 Otherwise return the formula preceeded with \"=\" or \":=\"."
9606 (let* ((name (car (rassoc (list (org-current-line)
9607 (org-table-current-column))
9608 org-table-named-field-locations)))
9609 (col (org-table-current-column))
9610 (scol (int-to-string col))
9611 (ref (format "@%d$%d" (org-table-current-dline) col))
9612 (stored-list (org-table-get-stored-formulas noerror))
9613 (ass (or (assoc name stored-list)
9614 (assoc ref stored-list)
9615 (assoc scol stored-list))))
9616 (if key
9617 (car ass)
9618 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9619 (cdr ass))))))
9621 (defun org-table-get-formula (&optional equation named)
9622 "Read a formula from the minibuffer, offer stored formula as default.
9623 When NAMED is non-nil, look for a named equation."
9624 (let* ((stored-list (org-table-get-stored-formulas))
9625 (name (car (rassoc (list (org-current-line)
9626 (org-table-current-column))
9627 org-table-named-field-locations)))
9628 (ref (format "@%d$%d" (org-table-current-dline)
9629 (org-table-current-column)))
9630 (refass (assoc ref stored-list))
9631 (scol (if named
9632 (if name name ref)
9633 (int-to-string (org-table-current-column))))
9634 (dummy (and (or name refass) (not named)
9635 (not (y-or-n-p "Replace field formula with column formula? " ))
9636 (error "Abort")))
9637 (name (or name ref))
9638 (org-table-may-need-update nil)
9639 (stored (cdr (assoc scol stored-list)))
9640 (eq (cond
9641 ((and stored equation (string-match "^ *=? *$" equation))
9642 stored)
9643 ((stringp equation)
9644 equation)
9645 (t (org-table-formula-from-user
9646 (read-string
9647 (org-table-formula-to-user
9648 (format "%s formula %s%s="
9649 (if named "Field" "Column")
9650 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9651 scol))
9652 (if stored (org-table-formula-to-user stored) "")
9653 'org-table-formula-history
9654 )))))
9655 mustsave)
9656 (when (not (string-match "\\S-" eq))
9657 ;; remove formula
9658 (setq stored-list (delq (assoc scol stored-list) stored-list))
9659 (org-table-store-formulas stored-list)
9660 (error "Formula removed"))
9661 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9662 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9663 (if (and name (not named))
9664 ;; We set the column equation, delete the named one.
9665 (setq stored-list (delq (assoc name stored-list) stored-list)
9666 mustsave t))
9667 (if stored
9668 (setcdr (assoc scol stored-list) eq)
9669 (setq stored-list (cons (cons scol eq) stored-list)))
9670 (if (or mustsave (not (equal stored eq)))
9671 (org-table-store-formulas stored-list))
9672 eq))
9674 (defun org-table-store-formulas (alist)
9675 "Store the list of formulas below the current table."
9676 (setq alist (sort alist 'org-table-formula-less-p))
9677 (save-excursion
9678 (goto-char (org-table-end))
9679 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9680 (progn
9681 ;; don't overwrite TBLFM, we might use text properties to store stuff
9682 (goto-char (match-beginning 2))
9683 (delete-region (match-beginning 2) (match-end 0)))
9684 (insert "#+TBLFM:"))
9685 (insert " "
9686 (mapconcat (lambda (x)
9687 (concat
9688 (if (equal (string-to-char (car x)) ?@) "" "$")
9689 (car x) "=" (cdr x)))
9690 alist "::")
9691 "\n")))
9693 (defsubst org-table-formula-make-cmp-string (a)
9694 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9695 (concat
9696 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9697 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9698 (if (match-end 5) (concat "@@" (match-string 5 a))))))
9700 (defun org-table-formula-less-p (a b)
9701 "Compare two formulas for sorting."
9702 (let ((as (org-table-formula-make-cmp-string (car a)))
9703 (bs (org-table-formula-make-cmp-string (car b))))
9704 (and as bs (string< as bs))))
9706 (defun org-table-get-stored-formulas (&optional noerror)
9707 "Return an alist with the stored formulas directly after current table."
9708 (interactive)
9709 (let (scol eq eq-alist strings string seen)
9710 (save-excursion
9711 (goto-char (org-table-end))
9712 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9713 (setq strings (org-split-string (match-string 2) " *:: *"))
9714 (while (setq string (pop strings))
9715 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
9716 (setq scol (if (match-end 2)
9717 (match-string 2 string)
9718 (match-string 1 string))
9719 eq (match-string 3 string)
9720 eq-alist (cons (cons scol eq) eq-alist))
9721 (if (member scol seen)
9722 (if noerror
9723 (progn
9724 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9725 (ding)
9726 (sit-for 2))
9727 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
9728 (push scol seen))))))
9729 (nreverse eq-alist)))
9731 (defun org-table-fix-formulas (key replace &optional limit delta remove)
9732 "Modify the equations after the table structure has been edited.
9733 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
9734 For all numbers larger than LIMIT, shift them by DELTA."
9735 (save-excursion
9736 (goto-char (org-table-end))
9737 (when (looking-at "#\\+TBLFM:")
9738 (let ((re (concat key "\\([0-9]+\\)"))
9739 (re2
9740 (when remove
9741 (if (equal key "$")
9742 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
9743 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
9744 s n a)
9745 (when remove
9746 (while (re-search-forward re2 (point-at-eol) t)
9747 (replace-match "")))
9748 (while (re-search-forward re (point-at-eol) t)
9749 (setq s (match-string 1) n (string-to-number s))
9750 (cond
9751 ((setq a (assoc s replace))
9752 (replace-match (concat key (cdr a)) t t))
9753 ((and limit (> n limit))
9754 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
9756 (defun org-table-get-specials ()
9757 "Get the column names and local parameters for this table."
9758 (save-excursion
9759 (let ((beg (org-table-begin)) (end (org-table-end))
9760 names name fields fields1 field cnt
9761 c v l line col types dlines hlines)
9762 (setq org-table-column-names nil
9763 org-table-local-parameters nil
9764 org-table-named-field-locations nil
9765 org-table-current-begin-line nil
9766 org-table-current-begin-pos nil
9767 org-table-current-line-types nil)
9768 (goto-char beg)
9769 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9770 (setq names (org-split-string (match-string 1) " *| *")
9771 cnt 1)
9772 (while (setq name (pop names))
9773 (setq cnt (1+ cnt))
9774 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9775 (push (cons name (int-to-string cnt)) org-table-column-names))))
9776 (setq org-table-column-names (nreverse org-table-column-names))
9777 (setq org-table-column-name-regexp
9778 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9779 (goto-char beg)
9780 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9781 (setq fields (org-split-string (match-string 1) " *| *"))
9782 (while (setq field (pop fields))
9783 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9784 (push (cons (match-string 1 field) (match-string 2 field))
9785 org-table-local-parameters))))
9786 (goto-char beg)
9787 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9788 (setq c (match-string 1)
9789 fields (org-split-string (match-string 2) " *| *"))
9790 (save-excursion
9791 (beginning-of-line (if (equal c "_") 2 0))
9792 (setq line (org-current-line) col 1)
9793 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9794 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9795 (while (and fields1 (setq field (pop fields)))
9796 (setq v (pop fields1) col (1+ col))
9797 (when (and (stringp field) (stringp v)
9798 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9799 (push (cons field v) org-table-local-parameters)
9800 (push (list field line col) org-table-named-field-locations))))
9801 ;; Analyse the line types
9802 (goto-char beg)
9803 (setq org-table-current-begin-line (org-current-line)
9804 org-table-current-begin-pos (point)
9805 l org-table-current-begin-line)
9806 (while (looking-at "[ \t]*|\\(-\\)?")
9807 (push (if (match-end 1) 'hline 'dline) types)
9808 (if (match-end 1) (push l hlines) (push l dlines))
9809 (beginning-of-line 2)
9810 (setq l (1+ l)))
9811 (setq org-table-current-line-types (apply 'vector (nreverse types))
9812 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
9813 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
9815 (defun org-table-maybe-eval-formula ()
9816 "Check if the current field starts with \"=\" or \":=\".
9817 If yes, store the formula and apply it."
9818 ;; We already know we are in a table. Get field will only return a formula
9819 ;; when appropriate. It might return a separator line, but no problem.
9820 (when org-table-formula-evaluate-inline
9821 (let* ((field (org-trim (or (org-table-get-field) "")))
9822 named eq)
9823 (when (string-match "^:?=\\(.*\\)" field)
9824 (setq named (equal (string-to-char field) ?:)
9825 eq (match-string 1 field))
9826 (if (or (fboundp 'calc-eval)
9827 (equal (substring eq 0 (min 2 (length eq))) "'("))
9828 (org-table-eval-formula (if named '(4) nil)
9829 (org-table-formula-from-user eq))
9830 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
9832 (defvar org-recalc-commands nil
9833 "List of commands triggering the recalculation of a line.
9834 Will be filled automatically during use.")
9836 (defvar org-recalc-marks
9837 '((" " . "Unmarked: no special line, no automatic recalculation")
9838 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9839 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9840 ("!" . "Column name definition line. Reference in formula as $name.")
9841 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9842 ("_" . "Names for values in row below this one.")
9843 ("^" . "Names for values in row above this one.")))
9845 (defun org-table-rotate-recalc-marks (&optional newchar)
9846 "Rotate the recalculation mark in the first column.
9847 If in any row, the first field is not consistent with a mark,
9848 insert a new column for the markers.
9849 When there is an active region, change all the lines in the region,
9850 after prompting for the marking character.
9851 After each change, a message will be displayed indicating the meaning
9852 of the new mark."
9853 (interactive)
9854 (unless (org-at-table-p) (error "Not at a table"))
9855 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9856 (beg (org-table-begin))
9857 (end (org-table-end))
9858 (l (org-current-line))
9859 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9860 (l2 (if (org-region-active-p) (org-current-line (region-end))))
9861 (have-col
9862 (save-excursion
9863 (goto-char beg)
9864 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
9865 (col (org-table-current-column))
9866 (forcenew (car (assoc newchar org-recalc-marks)))
9867 epos new)
9868 (when l1
9869 (message "Change region to what mark? Type # * ! $ or SPC: ")
9870 (setq newchar (char-to-string (read-char-exclusive))
9871 forcenew (car (assoc newchar org-recalc-marks))))
9872 (if (and newchar (not forcenew))
9873 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
9874 newchar))
9875 (if l1 (goto-line l1))
9876 (save-excursion
9877 (beginning-of-line 1)
9878 (unless (looking-at org-table-dataline-regexp)
9879 (error "Not at a table data line")))
9880 (unless have-col
9881 (org-table-goto-column 1)
9882 (org-table-insert-column)
9883 (org-table-goto-column (1+ col)))
9884 (setq epos (point-at-eol))
9885 (save-excursion
9886 (beginning-of-line 1)
9887 (org-table-get-field
9888 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
9889 (concat " "
9890 (setq new (or forcenew
9891 (cadr (member (match-string 1) marks))))
9892 " ")
9893 " # ")))
9894 (if (and l1 l2)
9895 (progn
9896 (goto-line l1)
9897 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
9898 (and (looking-at org-table-dataline-regexp)
9899 (org-table-get-field 1 (concat " " new " "))))
9900 (goto-line l1)))
9901 (if (not (= epos (point-at-eol))) (org-table-align))
9902 (goto-line l)
9903 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
9905 (defun org-table-maybe-recalculate-line ()
9906 "Recompute the current line if marked for it, and if we haven't just done it."
9907 (interactive)
9908 (and org-table-allow-automatic-line-recalculation
9909 (not (and (memq last-command org-recalc-commands)
9910 (equal org-last-recalc-line (org-current-line))))
9911 (save-excursion (beginning-of-line 1)
9912 (looking-at org-table-auto-recalculate-regexp))
9913 (org-table-recalculate) t))
9915 (defvar org-table-formula-debug nil
9916 "Non-nil means, debug table formulas.
9917 When nil, simply write \"#ERROR\" in corrupted fields.")
9918 (make-variable-buffer-local 'org-table-formula-debug)
9920 (defvar modes)
9921 (defsubst org-set-calc-mode (var &optional value)
9922 (if (stringp var)
9923 (setq var (assoc var '(("D" calc-angle-mode deg)
9924 ("R" calc-angle-mode rad)
9925 ("F" calc-prefer-frac t)
9926 ("S" calc-symbolic-mode t)))
9927 value (nth 2 var) var (nth 1 var)))
9928 (if (memq var modes)
9929 (setcar (cdr (memq var modes)) value)
9930 (cons var (cons value modes)))
9931 modes)
9933 (defun org-table-eval-formula (&optional arg equation
9934 suppress-align suppress-const
9935 suppress-store suppress-analysis)
9936 "Replace the table field value at the cursor by the result of a calculation.
9938 This function makes use of Dave Gillespie's Calc package, in my view the
9939 most exciting program ever written for GNU Emacs. So you need to have Calc
9940 installed in order to use this function.
9942 In a table, this command replaces the value in the current field with the
9943 result of a formula. It also installs the formula as the \"current\" column
9944 formula, by storing it in a special line below the table. When called
9945 with a `C-u' prefix, the current field must ba a named field, and the
9946 formula is installed as valid in only this specific field.
9948 When called with two `C-u' prefixes, insert the active equation
9949 for the field back into the current field, so that it can be
9950 edited there. This is useful in order to use \\[org-table-show-reference]
9951 to check the referenced fields.
9953 When called, the command first prompts for a formula, which is read in
9954 the minibuffer. Previously entered formulas are available through the
9955 history list, and the last used formula is offered as a default.
9956 These stored formulas are adapted correctly when moving, inserting, or
9957 deleting columns with the corresponding commands.
9959 The formula can be any algebraic expression understood by the Calc package.
9960 For details, see the Org-mode manual.
9962 This function can also be called from Lisp programs and offers
9963 additional arguments: EQUATION can be the formula to apply. If this
9964 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
9965 used to speed-up recursive calls by by-passing unnecessary aligns.
9966 SUPPRESS-CONST suppresses the interpretation of constants in the
9967 formula, assuming that this has been done already outside the function.
9968 SUPPRESS-STORE means the formula should not be stored, either because
9969 it is already stored, or because it is a modified equation that should
9970 not overwrite the stored one."
9971 (interactive "P")
9972 (org-table-check-inside-data-field)
9973 (or suppress-analysis (org-table-get-specials))
9974 (if (equal arg '(16))
9975 (let ((eq (org-table-current-field-formula)))
9976 (or eq (error "No equation active for current field"))
9977 (org-table-get-field nil eq)
9978 (org-table-align)
9979 (setq org-table-may-need-update t))
9980 (let* (fields
9981 (ndown (if (integerp arg) arg 1))
9982 (org-table-automatic-realign nil)
9983 (case-fold-search nil)
9984 (down (> ndown 1))
9985 (formula (if (and equation suppress-store)
9986 equation
9987 (org-table-get-formula equation (equal arg '(4)))))
9988 (n0 (org-table-current-column))
9989 (modes (copy-sequence org-calc-default-modes))
9990 (numbers nil) ; was a variable, now fixed default
9991 (keep-empty nil)
9992 n form form0 bw fmt x ev orig c lispp literal)
9993 ;; Parse the format string. Since we have a lot of modes, this is
9994 ;; a lot of work. However, I think calc still uses most of the time.
9995 (if (string-match ";" formula)
9996 (let ((tmp (org-split-string formula ";")))
9997 (setq formula (car tmp)
9998 fmt (concat (cdr (assoc "%" org-table-local-parameters))
9999 (nth 1 tmp)))
10000 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
10001 (setq c (string-to-char (match-string 1 fmt))
10002 n (string-to-number (match-string 2 fmt)))
10003 (if (= c ?p)
10004 (setq modes (org-set-calc-mode 'calc-internal-prec n))
10005 (setq modes (org-set-calc-mode
10006 'calc-float-format
10007 (list (cdr (assoc c '((?n . float) (?f . fix)
10008 (?s . sci) (?e . eng))))
10009 n))))
10010 (setq fmt (replace-match "" t t fmt)))
10011 (if (string-match "[NT]" fmt)
10012 (setq numbers (equal (match-string 0 fmt) "N")
10013 fmt (replace-match "" t t fmt)))
10014 (if (string-match "L" fmt)
10015 (setq literal t
10016 fmt (replace-match "" t t fmt)))
10017 (if (string-match "E" fmt)
10018 (setq keep-empty t
10019 fmt (replace-match "" t t fmt)))
10020 (while (string-match "[DRFS]" fmt)
10021 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10022 (setq fmt (replace-match "" t t fmt)))
10023 (unless (string-match "\\S-" fmt)
10024 (setq fmt nil))))
10025 (if (and (not suppress-const) org-table-formula-use-constants)
10026 (setq formula (org-table-formula-substitute-names formula)))
10027 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10028 (while (> ndown 0)
10029 (setq fields (org-split-string
10030 (org-no-properties
10031 (buffer-substring (point-at-bol) (point-at-eol)))
10032 " *| *"))
10033 (if (eq numbers t)
10034 (setq fields (mapcar
10035 (lambda (x) (number-to-string (string-to-number x)))
10036 fields)))
10037 (setq ndown (1- ndown))
10038 (setq form (copy-sequence formula)
10039 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
10040 (if (and lispp literal) (setq lispp 'literal))
10041 ;; Check for old vertical references
10042 (setq form (org-rewrite-old-row-references form))
10043 ;; Insert complex ranges
10044 (while (string-match org-table-range-regexp form)
10045 (setq form
10046 (replace-match
10047 (save-match-data
10048 (org-table-make-reference
10049 (org-table-get-range (match-string 0 form) nil n0)
10050 keep-empty numbers lispp))
10051 t t form)))
10052 ;; Insert simple ranges
10053 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
10054 (setq form
10055 (replace-match
10056 (save-match-data
10057 (org-table-make-reference
10058 (org-sublist
10059 fields (string-to-number (match-string 1 form))
10060 (string-to-number (match-string 2 form)))
10061 keep-empty numbers lispp))
10062 t t form)))
10063 (setq form0 form)
10064 ;; Insert the references to fields in same row
10065 (while (string-match "\\$\\([0-9]+\\)" form)
10066 (setq n (string-to-number (match-string 1 form))
10067 x (nth (1- (if (= n 0) n0 n)) fields))
10068 (unless x (error "Invalid field specifier \"%s\""
10069 (match-string 0 form)))
10070 (setq form (replace-match
10071 (save-match-data
10072 (org-table-make-reference x nil numbers lispp))
10073 t t form)))
10075 (if lispp
10076 (setq ev (condition-case nil
10077 (eval (eval (read form)))
10078 (error "#ERROR"))
10079 ev (if (numberp ev) (number-to-string ev) ev))
10080 (or (fboundp 'calc-eval)
10081 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
10082 (setq ev (calc-eval (cons form modes)
10083 (if numbers 'num))))
10085 (when org-table-formula-debug
10086 (with-output-to-temp-buffer "*Substitution History*"
10087 (princ (format "Substitution history of formula
10088 Orig: %s
10089 $xyz-> %s
10090 @r$c-> %s
10091 $1-> %s\n" orig formula form0 form))
10092 (if (listp ev)
10093 (princ (format " %s^\nError: %s"
10094 (make-string (car ev) ?\-) (nth 1 ev)))
10095 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10096 ev (or fmt "NONE")
10097 (if fmt (format fmt (string-to-number ev)) ev)))))
10098 (setq bw (get-buffer-window "*Substitution History*"))
10099 (shrink-window-if-larger-than-buffer bw)
10100 (unless (and (interactive-p) (not ndown))
10101 (unless (let (inhibit-redisplay)
10102 (y-or-n-p "Debugging Formula. Continue to next? "))
10103 (org-table-align)
10104 (error "Abort"))
10105 (delete-window bw)
10106 (message "")))
10107 (if (listp ev) (setq fmt nil ev "#ERROR"))
10108 (org-table-justify-field-maybe
10109 (if fmt (format fmt (string-to-number ev)) ev))
10110 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10111 (call-interactively 'org-return)
10112 (setq ndown 0)))
10113 (and down (org-table-maybe-recalculate-line))
10114 (or suppress-align (and org-table-may-need-update
10115 (org-table-align))))))
10117 (defun org-table-put-field-property (prop value)
10118 (save-excursion
10119 (put-text-property (progn (skip-chars-backward "^|") (point))
10120 (progn (skip-chars-forward "^|") (point))
10121 prop value)))
10123 (defun org-table-get-range (desc &optional tbeg col highlight)
10124 "Get a calc vector from a column, accorting to descriptor DESC.
10125 Optional arguments TBEG and COL can give the beginning of the table and
10126 the current column, to avoid unnecessary parsing.
10127 HIGHLIGHT means, just highlight the range."
10128 (if (not (equal (string-to-char desc) ?@))
10129 (setq desc (concat "@" desc)))
10130 (save-excursion
10131 (or tbeg (setq tbeg (org-table-begin)))
10132 (or col (setq col (org-table-current-column)))
10133 (let ((thisline (org-current-line))
10134 beg end c1 c2 r1 r2 rangep tmp)
10135 (unless (string-match org-table-range-regexp desc)
10136 (error "Invalid table range specifier `%s'" desc))
10137 (setq rangep (match-end 3)
10138 r1 (and (match-end 1) (match-string 1 desc))
10139 r2 (and (match-end 4) (match-string 4 desc))
10140 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
10141 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
10143 (and c1 (setq c1 (+ (string-to-number c1)
10144 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
10145 (and c2 (setq c2 (+ (string-to-number c2)
10146 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
10147 (if (equal r1 "") (setq r1 nil))
10148 (if (equal r2 "") (setq r2 nil))
10149 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10150 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10151 ; (setq r2 (or r2 r1) c2 (or c2 c1))
10152 (if (not r1) (setq r1 thisline))
10153 (if (not r2) (setq r2 thisline))
10154 (if (not c1) (setq c1 col))
10155 (if (not c2) (setq c2 col))
10156 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10157 ;; just one field
10158 (progn
10159 (goto-line r1)
10160 (while (not (looking-at org-table-dataline-regexp))
10161 (beginning-of-line 2))
10162 (prog1 (org-trim (org-table-get-field c1))
10163 (if highlight (org-table-highlight-rectangle (point) (point)))))
10164 ;; A range, return a vector
10165 ;; First sort the numbers to get a regular ractangle
10166 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10167 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10168 (goto-line r1)
10169 (while (not (looking-at org-table-dataline-regexp))
10170 (beginning-of-line 2))
10171 (org-table-goto-column c1)
10172 (setq beg (point))
10173 (goto-line r2)
10174 (while (not (looking-at org-table-dataline-regexp))
10175 (beginning-of-line 0))
10176 (org-table-goto-column c2)
10177 (setq end (point))
10178 (if highlight
10179 (org-table-highlight-rectangle
10180 beg (progn (skip-chars-forward "^|\n") (point))))
10181 ;; return string representation of calc vector
10182 (mapcar 'org-trim
10183 (apply 'append (org-table-copy-region beg end)))))))
10185 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10186 "Analyze descriptor DESC and retrieve the corresponding line number.
10187 The cursor is currently in line CLINE, the table begins in line BLINE,
10188 and TABLE is a vector with line types."
10189 (if (string-match "^[0-9]+$" desc)
10190 (aref org-table-dlines (string-to-number desc))
10191 (setq cline (or cline (org-current-line))
10192 bline (or bline org-table-current-begin-line)
10193 table (or table org-table-current-line-types))
10194 (if (or
10195 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10196 ;; 1 2 3 4 5 6
10197 (and (not (match-end 3)) (not (match-end 6)))
10198 (and (match-end 3) (match-end 6) (not (match-end 5))))
10199 (error "invalid row descriptor `%s'" desc))
10200 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10201 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10202 (odir (and (match-end 5) (match-string 5 desc)))
10203 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10204 (i (- cline bline))
10205 (rel (and (match-end 6)
10206 (or (and (match-end 1) (not (match-end 3)))
10207 (match-end 5)))))
10208 (if (and hn (not hdir))
10209 (progn
10210 (setq i 0 hdir "+")
10211 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10212 (if (and (not hn) on (not odir))
10213 (error "should never happen");;(aref org-table-dlines on)
10214 (if (and hn (> hn 0))
10215 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10216 (if on
10217 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10218 (+ bline i)))))
10220 (defun org-find-row-type (table i type backwards relative n)
10221 (let ((l (length table)))
10222 (while (> n 0)
10223 (while (and (setq i (+ i (if backwards -1 1)))
10224 (>= i 0) (< i l)
10225 (not (eq (aref table i) type))
10226 (if (and relative (eq (aref table i) 'hline))
10227 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10228 t)))
10229 (setq n (1- n)))
10230 (if (or (< i 0) (>= i l))
10231 (error "Row descriptior leads outside table")
10232 i)))
10234 (defun org-rewrite-old-row-references (s)
10235 (if (string-match "&[-+0-9I]" s)
10236 (error "Formula contains old &row reference, please rewrite using @-syntax")
10239 (defun org-table-make-reference (elements keep-empty numbers lispp)
10240 "Convert list ELEMENTS to something appropriate to insert into formula.
10241 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10242 NUMBERS indicates that everything should be converted to numbers.
10243 LISPP means to return something appropriate for a Lisp list."
10244 (if (stringp elements) ; just a single val
10245 (if lispp
10246 (if (eq lispp 'literal)
10247 elements
10248 (prin1-to-string (if numbers (string-to-number elements) elements)))
10249 (if (equal elements "") (setq elements "0"))
10250 (if numbers (number-to-string (string-to-number elements)) elements))
10251 (unless keep-empty
10252 (setq elements
10253 (delq nil
10254 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10255 elements))))
10256 (setq elements (or elements '("0")))
10257 (if lispp
10258 (mapconcat
10259 (lambda (x)
10260 (if (eq lispp 'literal)
10262 (prin1-to-string (if numbers (string-to-number x) x))))
10263 elements " ")
10264 (concat "[" (mapconcat
10265 (lambda (x)
10266 (if numbers (number-to-string (string-to-number x)) x))
10267 elements
10268 ",") "]"))))
10270 (defun org-table-recalculate (&optional all noalign)
10271 "Recalculate the current table line by applying all stored formulas.
10272 With prefix arg ALL, do this for all lines in the table."
10273 (interactive "P")
10274 (or (memq this-command org-recalc-commands)
10275 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10276 (unless (org-at-table-p) (error "Not at a table"))
10277 (if (equal all '(16))
10278 (org-table-iterate)
10279 (org-table-get-specials)
10280 (let* ((eqlist (sort (org-table-get-stored-formulas)
10281 (lambda (a b) (string< (car a) (car b)))))
10282 (inhibit-redisplay (not debug-on-error))
10283 (line-re org-table-dataline-regexp)
10284 (thisline (org-current-line))
10285 (thiscol (org-table-current-column))
10286 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10287 ;; Insert constants in all formulas
10288 (setq eqlist
10289 (mapcar (lambda (x)
10290 (setcdr x (org-table-formula-substitute-names (cdr x)))
10292 eqlist))
10293 ;; Split the equation list
10294 (while (setq eq (pop eqlist))
10295 (if (<= (string-to-char (car eq)) ?9)
10296 (push eq eqlnum)
10297 (push eq eqlname)))
10298 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10299 (if all
10300 (progn
10301 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10302 (goto-char (setq beg (org-table-begin)))
10303 (if (re-search-forward org-table-calculate-mark-regexp end t)
10304 ;; This is a table with marked lines, compute selected lines
10305 (setq line-re org-table-recalculate-regexp)
10306 ;; Move forward to the first non-header line
10307 (if (and (re-search-forward org-table-dataline-regexp end t)
10308 (re-search-forward org-table-hline-regexp end t)
10309 (re-search-forward org-table-dataline-regexp end t))
10310 (setq beg (match-beginning 0))
10311 nil))) ;; just leave beg where it is
10312 (setq beg (point-at-bol)
10313 end (move-marker (make-marker) (1+ (point-at-eol)))))
10314 (goto-char beg)
10315 (and all (message "Re-applying formulas to full table..."))
10317 ;; First find the named fields, and mark them untouchanble
10318 (remove-text-properties beg end '(org-untouchable t))
10319 (while (setq eq (pop eqlname))
10320 (setq name (car eq)
10321 a (assoc name org-table-named-field-locations))
10322 (and (not a)
10323 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10324 (setq a (list name
10325 (aref org-table-dlines
10326 (string-to-number (match-string 1 name)))
10327 (string-to-number (match-string 2 name)))))
10328 (when (and a (or all (equal (nth 1 a) thisline)))
10329 (message "Re-applying formula to field: %s" name)
10330 (goto-line (nth 1 a))
10331 (org-table-goto-column (nth 2 a))
10332 (push (append a (list (cdr eq))) eqlname1)
10333 (org-table-put-field-property :org-untouchable t)))
10335 ;; Now evauluate the column formulas, but skip fields covered by
10336 ;; field formulas
10337 (goto-char beg)
10338 (while (re-search-forward line-re end t)
10339 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10340 ;; Unprotected line, recalculate
10341 (and all (message "Re-applying formulas to full table...(line %d)"
10342 (setq cnt (1+ cnt))))
10343 (setq org-last-recalc-line (org-current-line))
10344 (setq eql eqlnum)
10345 (while (setq entry (pop eql))
10346 (goto-line org-last-recalc-line)
10347 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10348 (unless (get-text-property (point) :org-untouchable)
10349 (org-table-eval-formula nil (cdr entry)
10350 'noalign 'nocst 'nostore 'noanalysis)))))
10352 ;; Now evaluate the field formulas
10353 (while (setq eq (pop eqlname1))
10354 (message "Re-applying formula to field: %s" (car eq))
10355 (goto-line (nth 1 eq))
10356 (org-table-goto-column (nth 2 eq))
10357 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10358 'nostore 'noanalysis))
10360 (goto-line thisline)
10361 (org-table-goto-column thiscol)
10362 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10363 (or noalign (and org-table-may-need-update (org-table-align))
10364 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10366 ;; back to initial position
10367 (message "Re-applying formulas...done")
10368 (goto-line thisline)
10369 (org-table-goto-column thiscol)
10370 (or noalign (and org-table-may-need-update (org-table-align))
10371 (and all (message "Re-applying formulas...done"))))))
10373 (defun org-table-iterate (&optional arg)
10374 "Recalculate the table until it does not change anymore."
10375 (interactive "P")
10376 (let ((imax (if arg (prefix-numeric-value arg) 10))
10377 (i 0)
10378 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10379 thistbl)
10380 (catch 'exit
10381 (while (< i imax)
10382 (setq i (1+ i))
10383 (org-table-recalculate 'all)
10384 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10385 (if (not (string= lasttbl thistbl))
10386 (setq lasttbl thistbl)
10387 (if (> i 1)
10388 (message "Convergence after %d iterations" i)
10389 (message "Table was already stable"))
10390 (throw 'exit t)))
10391 (error "No convergence after %d iterations" i))))
10393 (defun org-table-formula-substitute-names (f)
10394 "Replace $const with values in string F."
10395 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10396 ;; First, check for column names
10397 (while (setq start (string-match org-table-column-name-regexp f start))
10398 (setq start (1+ start))
10399 (setq a (assoc (match-string 1 f) org-table-column-names))
10400 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10401 ;; Parameters and constants
10402 (setq start 0)
10403 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10404 (setq start (1+ start))
10405 (if (setq a (save-match-data
10406 (org-table-get-constant (match-string 1 f))))
10407 (setq f (replace-match
10408 (concat (if pp "(") a (if pp ")")) t t f))))
10409 (if org-table-formula-debug
10410 (put-text-property 0 (length f) :orig-formula f1 f))
10413 (defun org-table-get-constant (const)
10414 "Find the value for a parameter or constant in a formula.
10415 Parameters get priority."
10416 (or (cdr (assoc const org-table-local-parameters))
10417 (cdr (assoc const org-table-formula-constants-local))
10418 (cdr (assoc const org-table-formula-constants))
10419 (and (fboundp 'constants-get) (constants-get const))
10420 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10421 (org-entry-get nil (substring const 5) 'inherit))
10422 "#UNDEFINED_NAME"))
10424 (defvar org-table-fedit-map
10425 (let ((map (make-sparse-keymap)))
10426 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10427 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10428 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10429 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10430 (org-defkey map "\C-c?" 'org-table-show-reference)
10431 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10432 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10433 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10434 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10435 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10436 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10437 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10438 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10439 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10440 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10441 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10442 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10443 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10444 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10445 map))
10447 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10448 '("Edit-Formulas"
10449 ["Finish and Install" org-table-fedit-finish t]
10450 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10451 ["Abort" org-table-fedit-abort t]
10452 "--"
10453 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10454 ["Complete Lisp Symbol" lisp-complete-symbol t]
10455 "--"
10456 "Shift Reference at Point"
10457 ["Up" org-table-fedit-ref-up t]
10458 ["Down" org-table-fedit-ref-down t]
10459 ["Left" org-table-fedit-ref-left t]
10460 ["Right" org-table-fedit-ref-right t]
10462 "Change Test Row for Column Formulas"
10463 ["Up" org-table-fedit-line-up t]
10464 ["Down" org-table-fedit-line-down t]
10465 "--"
10466 ["Scroll Table Window" org-table-fedit-scroll t]
10467 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10468 ["Show Table Grid" org-table-fedit-toggle-coordinates
10469 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10470 org-table-overlay-coordinates)]
10471 "--"
10472 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10473 :style toggle :selected org-table-buffer-is-an]))
10475 (defvar org-pos)
10477 (defun org-table-edit-formulas ()
10478 "Edit the formulas of the current table in a separate buffer."
10479 (interactive)
10480 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10481 (beginning-of-line 0))
10482 (unless (org-at-table-p) (error "Not at a table"))
10483 (org-table-get-specials)
10484 (let ((key (org-table-current-field-formula 'key 'noerror))
10485 (eql (sort (org-table-get-stored-formulas 'noerror)
10486 'org-table-formula-less-p))
10487 (pos (move-marker (make-marker) (point)))
10488 (startline 1)
10489 (wc (current-window-configuration))
10490 (titles '((column . "# Column Formulas\n")
10491 (field . "# Field Formulas\n")
10492 (named . "# Named Field Formulas\n")))
10493 entry s type title)
10494 (org-switch-to-buffer-other-window "*Edit Formulas*")
10495 (erase-buffer)
10496 ;; Keep global-font-lock-mode from turning on font-lock-mode
10497 (let ((font-lock-global-modes '(not fundamental-mode)))
10498 (fundamental-mode))
10499 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10500 (org-set-local 'org-pos pos)
10501 (org-set-local 'org-window-configuration wc)
10502 (use-local-map org-table-fedit-map)
10503 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10504 (easy-menu-add org-table-fedit-menu)
10505 (setq startline (org-current-line))
10506 (while (setq entry (pop eql))
10507 (setq type (cond
10508 ((equal (string-to-char (car entry)) ?@) 'field)
10509 ((string-match "^[0-9]" (car entry)) 'column)
10510 (t 'named)))
10511 (when (setq title (assq type titles))
10512 (or (bobp) (insert "\n"))
10513 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10514 (setq titles (delq title titles)))
10515 (if (equal key (car entry)) (setq startline (org-current-line)))
10516 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10517 (car entry) " = " (cdr entry) "\n"))
10518 (remove-text-properties 0 (length s) '(face nil) s)
10519 (insert s))
10520 (if (eq org-table-use-standard-references t)
10521 (org-table-fedit-toggle-ref-type))
10522 (goto-line startline)
10523 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10525 (defun org-table-fedit-post-command ()
10526 (when (not (memq this-command '(lisp-complete-symbol)))
10527 (let ((win (selected-window)))
10528 (save-excursion
10529 (condition-case nil
10530 (org-table-show-reference)
10531 (error nil))
10532 (select-window win)))))
10534 (defun org-table-formula-to-user (s)
10535 "Convert a formula from internal to user representation."
10536 (if (eq org-table-use-standard-references t)
10537 (org-table-convert-refs-to-an s)
10540 (defun org-table-formula-from-user (s)
10541 "Convert a formula from user to internal representation."
10542 (if org-table-use-standard-references
10543 (org-table-convert-refs-to-rc s)
10546 (defun org-table-convert-refs-to-rc (s)
10547 "Convert spreadsheet references from AB7 to @7$28.
10548 Works for single references, but also for entire formulas and even the
10549 full TBLFM line."
10550 (let ((start 0))
10551 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10552 (cond
10553 ((match-end 3)
10554 ;; format match, just advance
10555 (setq start (match-end 0)))
10556 ((and (> (match-beginning 0) 0)
10557 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10558 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10559 ;; 3.e5 or something like this.
10560 (setq start (match-end 0)))
10562 (setq start (match-beginning 0)
10563 s (replace-match
10564 (if (equal (match-string 2 s) "&")
10565 (format "$%d" (org-letters-to-number (match-string 1 s)))
10566 (format "@%d$%d"
10567 (string-to-number (match-string 2 s))
10568 (org-letters-to-number (match-string 1 s))))
10569 t t s)))))
10572 (defun org-table-convert-refs-to-an (s)
10573 "Convert spreadsheet references from to @7$28 to AB7.
10574 Works for single references, but also for entire formulas and even the
10575 full TBLFM line."
10576 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10577 (setq s (replace-match
10578 (format "%s%d"
10579 (org-number-to-letters
10580 (string-to-number (match-string 2 s)))
10581 (string-to-number (match-string 1 s)))
10582 t t s)))
10583 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10584 (setq s (replace-match (concat "\\1"
10585 (org-number-to-letters
10586 (string-to-number (match-string 2 s))) "&")
10587 t nil s)))
10590 (defun org-letters-to-number (s)
10591 "Convert a base 26 number represented by letters into an integer.
10592 For example: AB -> 28."
10593 (let ((n 0))
10594 (setq s (upcase s))
10595 (while (> (length s) 0)
10596 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10597 s (substring s 1)))
10600 (defun org-number-to-letters (n)
10601 "Convert an integer into a base 26 number represented by letters.
10602 For example: 28 -> AB."
10603 (let ((s ""))
10604 (while (> n 0)
10605 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10606 n (/ (1- n) 26)))
10609 (defun org-table-fedit-convert-buffer (function)
10610 "Convert all references in this buffer, using FUNTION."
10611 (let ((line (org-current-line)))
10612 (goto-char (point-min))
10613 (while (not (eobp))
10614 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10615 (delete-region (point) (point-at-eol))
10616 (or (eobp) (forward-char 1)))
10617 (goto-line line)))
10619 (defun org-table-fedit-toggle-ref-type ()
10620 "Convert all references in the buffer from B3 to @3$2 and back."
10621 (interactive)
10622 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10623 (org-table-fedit-convert-buffer
10624 (if org-table-buffer-is-an
10625 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10626 (message "Reference type switched to %s"
10627 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10629 (defun org-table-fedit-ref-up ()
10630 "Shift the reference at point one row/hline up."
10631 (interactive)
10632 (org-table-fedit-shift-reference 'up))
10633 (defun org-table-fedit-ref-down ()
10634 "Shift the reference at point one row/hline down."
10635 (interactive)
10636 (org-table-fedit-shift-reference 'down))
10637 (defun org-table-fedit-ref-left ()
10638 "Shift the reference at point one field to the left."
10639 (interactive)
10640 (org-table-fedit-shift-reference 'left))
10641 (defun org-table-fedit-ref-right ()
10642 "Shift the reference at point one field to the right."
10643 (interactive)
10644 (org-table-fedit-shift-reference 'right))
10646 (defun org-table-fedit-shift-reference (dir)
10647 (cond
10648 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10649 (if (memq dir '(left right))
10650 (org-rematch-and-replace 1 (eq dir 'left))
10651 (error "Cannot shift reference in this direction")))
10652 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10653 ;; A B3-like reference
10654 (if (memq dir '(up down))
10655 (org-rematch-and-replace 2 (eq dir 'up))
10656 (org-rematch-and-replace 1 (eq dir 'left))))
10657 ((org-at-regexp-p
10658 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10659 ;; An internal reference
10660 (if (memq dir '(up down))
10661 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10662 (org-rematch-and-replace 5 (eq dir 'left))))))
10664 (defun org-rematch-and-replace (n &optional decr hline)
10665 "Re-match the group N, and replace it with the shifted refrence."
10666 (or (match-end n) (error "Cannot shift reference in this direction"))
10667 (goto-char (match-beginning n))
10668 (and (looking-at (regexp-quote (match-string n)))
10669 (replace-match (org-shift-refpart (match-string 0) decr hline)
10670 t t)))
10672 (defun org-shift-refpart (ref &optional decr hline)
10673 "Shift a refrence part REF.
10674 If DECR is set, decrease the references row/column, else increase.
10675 If HLINE is set, this may be a hline reference, it certainly is not
10676 a translation reference."
10677 (save-match-data
10678 (let* ((sign (string-match "^[-+]" ref)) n)
10680 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10681 (cond
10682 ((and hline (string-match "^I+" ref))
10683 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10684 (setq n (+ n (if decr -1 1)))
10685 (if (= n 0) (setq n (+ n (if decr -1 1))))
10686 (if sign
10687 (setq sign (if (< n 0) "-" "+") n (abs n))
10688 (setq n (max 1 n)))
10689 (concat sign (make-string n ?I)))
10691 ((string-match "^[0-9]+" ref)
10692 (setq n (string-to-number (concat sign ref)))
10693 (setq n (+ n (if decr -1 1)))
10694 (if sign
10695 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10696 (number-to-string (max 1 n))))
10698 ((string-match "^[a-zA-Z]+" ref)
10699 (org-number-to-letters
10700 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10702 (t (error "Cannot shift reference"))))))
10704 (defun org-table-fedit-toggle-coordinates ()
10705 "Toggle the display of coordinates in the refrenced table."
10706 (interactive)
10707 (let ((pos (marker-position org-pos)))
10708 (with-current-buffer (marker-buffer org-pos)
10709 (save-excursion
10710 (goto-char pos)
10711 (org-table-toggle-coordinate-overlays)))))
10713 (defun org-table-fedit-finish (&optional arg)
10714 "Parse the buffer for formula definitions and install them.
10715 With prefix ARG, apply the new formulas to the table."
10716 (interactive "P")
10717 (org-table-remove-rectangle-highlight)
10718 (if org-table-use-standard-references
10719 (progn
10720 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
10721 (setq org-table-buffer-is-an nil)))
10722 (let ((pos org-pos) eql var form)
10723 (goto-char (point-min))
10724 (while (re-search-forward
10725 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
10726 nil t)
10727 (setq var (if (match-end 2) (match-string 2) (match-string 1))
10728 form (match-string 3))
10729 (setq form (org-trim form))
10730 (when (not (equal form ""))
10731 (while (string-match "[ \t]*\n[ \t]*" form)
10732 (setq form (replace-match " " t t form)))
10733 (when (assoc var eql)
10734 (error "Double formulas for %s" var))
10735 (push (cons var form) eql)))
10736 (setq org-pos nil)
10737 (set-window-configuration org-window-configuration)
10738 (select-window (get-buffer-window (marker-buffer pos)))
10739 (goto-char pos)
10740 (unless (org-at-table-p)
10741 (error "Lost table position - cannot install formulae"))
10742 (org-table-store-formulas eql)
10743 (move-marker pos nil)
10744 (kill-buffer "*Edit Formulas*")
10745 (if arg
10746 (org-table-recalculate 'all)
10747 (message "New formulas installed - press C-u C-c C-c to apply."))))
10749 (defun org-table-fedit-abort ()
10750 "Abort editing formulas, without installing the changes."
10751 (interactive)
10752 (org-table-remove-rectangle-highlight)
10753 (let ((pos org-pos))
10754 (set-window-configuration org-window-configuration)
10755 (select-window (get-buffer-window (marker-buffer pos)))
10756 (goto-char pos)
10757 (move-marker pos nil)
10758 (message "Formula editing aborted without installing changes")))
10760 (defun org-table-fedit-lisp-indent ()
10761 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
10762 (interactive)
10763 (let ((pos (point)) beg end ind)
10764 (beginning-of-line 1)
10765 (cond
10766 ((looking-at "[ \t]")
10767 (goto-char pos)
10768 (call-interactively 'lisp-indent-line))
10769 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
10770 ((not (fboundp 'pp-buffer))
10771 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
10772 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
10773 (goto-char (- (match-end 0) 2))
10774 (setq beg (point))
10775 (setq ind (make-string (current-column) ?\ ))
10776 (condition-case nil (forward-sexp 1)
10777 (error
10778 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
10779 (setq end (point))
10780 (save-restriction
10781 (narrow-to-region beg end)
10782 (if (eq last-command this-command)
10783 (progn
10784 (goto-char (point-min))
10785 (setq this-command nil)
10786 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
10787 (replace-match " ")))
10788 (pp-buffer)
10789 (untabify (point-min) (point-max))
10790 (goto-char (1+ (point-min)))
10791 (while (re-search-forward "^." nil t)
10792 (beginning-of-line 1)
10793 (insert ind))
10794 (goto-char (point-max))
10795 (backward-delete-char 1)))
10796 (goto-char beg))
10797 (t nil))))
10799 (defvar org-show-positions nil)
10801 (defun org-table-show-reference (&optional local)
10802 "Show the location/value of the $ expression at point."
10803 (interactive)
10804 (org-table-remove-rectangle-highlight)
10805 (catch 'exit
10806 (let ((pos (if local (point) org-pos))
10807 (face2 'highlight)
10808 (org-inhibit-highlight-removal t)
10809 (win (selected-window))
10810 (org-show-positions nil)
10811 var name e what match dest)
10812 (if local (org-table-get-specials))
10813 (setq what (cond
10814 ((or (org-at-regexp-p org-table-range-regexp2)
10815 (org-at-regexp-p org-table-translate-regexp)
10816 (org-at-regexp-p org-table-range-regexp))
10817 (setq match
10818 (save-match-data
10819 (org-table-convert-refs-to-rc (match-string 0))))
10820 'range)
10821 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
10822 ((org-at-regexp-p "\\$[0-9]+") 'column)
10823 ((not local) nil)
10824 (t (error "No reference at point")))
10825 match (and what (or match (match-string 0))))
10826 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
10827 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
10828 'secondary-selection))
10829 (org-add-hook 'before-change-functions
10830 'org-table-remove-rectangle-highlight)
10831 (if (eq what 'name) (setq var (substring match 1)))
10832 (when (eq what 'range)
10833 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
10834 (setq match (org-table-formula-substitute-names match)))
10835 (unless local
10836 (save-excursion
10837 (end-of-line 1)
10838 (re-search-backward "^\\S-" nil t)
10839 (beginning-of-line 1)
10840 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
10841 (setq dest
10842 (save-match-data
10843 (org-table-convert-refs-to-rc (match-string 1))))
10844 (org-table-add-rectangle-overlay
10845 (match-beginning 1) (match-end 1) face2))))
10846 (if (and (markerp pos) (marker-buffer pos))
10847 (if (get-buffer-window (marker-buffer pos))
10848 (select-window (get-buffer-window (marker-buffer pos)))
10849 (org-switch-to-buffer-other-window (get-buffer-window
10850 (marker-buffer pos)))))
10851 (goto-char pos)
10852 (org-table-force-dataline)
10853 (when dest
10854 (setq name (substring dest 1))
10855 (cond
10856 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
10857 (setq e (assoc name org-table-named-field-locations))
10858 (goto-line (nth 1 e))
10859 (org-table-goto-column (nth 2 e)))
10860 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
10861 (let ((l (string-to-number (match-string 1 dest)))
10862 (c (string-to-number (match-string 2 dest))))
10863 (goto-line (aref org-table-dlines l))
10864 (org-table-goto-column c)))
10865 (t (org-table-goto-column (string-to-number name))))
10866 (move-marker pos (point))
10867 (org-table-highlight-rectangle nil nil face2))
10868 (cond
10869 ((equal dest match))
10870 ((not match))
10871 ((eq what 'range)
10872 (condition-case nil
10873 (save-excursion
10874 (org-table-get-range match nil nil 'highlight))
10875 (error nil)))
10876 ((setq e (assoc var org-table-named-field-locations))
10877 (goto-line (nth 1 e))
10878 (org-table-goto-column (nth 2 e))
10879 (org-table-highlight-rectangle (point) (point))
10880 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
10881 ((setq e (assoc var org-table-column-names))
10882 (org-table-goto-column (string-to-number (cdr e)))
10883 (org-table-highlight-rectangle (point) (point))
10884 (goto-char (org-table-begin))
10885 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
10886 (org-table-end) t)
10887 (progn
10888 (goto-char (match-beginning 1))
10889 (org-table-highlight-rectangle)
10890 (message "Named column (column %s)" (cdr e)))
10891 (error "Column name not found")))
10892 ((eq what 'column)
10893 ;; column number
10894 (org-table-goto-column (string-to-number (substring match 1)))
10895 (org-table-highlight-rectangle (point) (point))
10896 (message "Column %s" (substring match 1)))
10897 ((setq e (assoc var org-table-local-parameters))
10898 (goto-char (org-table-begin))
10899 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
10900 (progn
10901 (goto-char (match-beginning 1))
10902 (org-table-highlight-rectangle)
10903 (message "Local parameter."))
10904 (error "Parameter not found")))
10906 (cond
10907 ((not var) (error "No reference at point"))
10908 ((setq e (assoc var org-table-formula-constants-local))
10909 (message "Local Constant: $%s=%s in #+CONSTANTS line."
10910 var (cdr e)))
10911 ((setq e (assoc var org-table-formula-constants))
10912 (message "Constant: $%s=%s in `org-table-formula-constants'."
10913 var (cdr e)))
10914 ((setq e (and (fboundp 'constants-get) (constants-get var)))
10915 (message "Constant: $%s=%s, from `constants.el'%s."
10916 var e (format " (%s units)" constants-unit-system)))
10917 (t (error "Undefined name $%s" var)))))
10918 (goto-char pos)
10919 (when (and org-show-positions
10920 (not (memq this-command '(org-table-fedit-scroll
10921 org-table-fedit-scroll-down))))
10922 (push pos org-show-positions)
10923 (push org-table-current-begin-pos org-show-positions)
10924 (let ((min (apply 'min org-show-positions))
10925 (max (apply 'max org-show-positions)))
10926 (goto-char min) (recenter 0)
10927 (goto-char max)
10928 (or (pos-visible-in-window-p max) (recenter -1))))
10929 (select-window win))))
10931 (defun org-table-force-dataline ()
10932 "Make sure the cursor is in a dataline in a table."
10933 (unless (save-excursion
10934 (beginning-of-line 1)
10935 (looking-at org-table-dataline-regexp))
10936 (let* ((re org-table-dataline-regexp)
10937 (p1 (save-excursion (re-search-forward re nil 'move)))
10938 (p2 (save-excursion (re-search-backward re nil 'move))))
10939 (cond ((and p1 p2)
10940 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
10941 p1 p2)))
10942 ((or p1 p2) (goto-char (or p1 p2)))
10943 (t (error "No table dataline around here"))))))
10945 (defun org-table-fedit-line-up ()
10946 "Move cursor one line up in the window showing the table."
10947 (interactive)
10948 (org-table-fedit-move 'previous-line))
10950 (defun org-table-fedit-line-down ()
10951 "Move cursor one line down in the window showing the table."
10952 (interactive)
10953 (org-table-fedit-move 'next-line))
10955 (defun org-table-fedit-move (command)
10956 "Move the cursor in the window shoinw the table.
10957 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
10958 (let ((org-table-allow-automatic-line-recalculation nil)
10959 (pos org-pos) (win (selected-window)) p)
10960 (select-window (get-buffer-window (marker-buffer org-pos)))
10961 (setq p (point))
10962 (call-interactively command)
10963 (while (and (org-at-table-p)
10964 (org-at-table-hline-p))
10965 (call-interactively command))
10966 (or (org-at-table-p) (goto-char p))
10967 (move-marker pos (point))
10968 (select-window win)))
10970 (defun org-table-fedit-scroll (N)
10971 (interactive "p")
10972 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
10973 (scroll-other-window N)))
10975 (defun org-table-fedit-scroll-down (N)
10976 (interactive "p")
10977 (org-table-fedit-scroll (- N)))
10979 (defvar org-table-rectangle-overlays nil)
10981 (defun org-table-add-rectangle-overlay (beg end &optional face)
10982 "Add a new overlay."
10983 (let ((ov (org-make-overlay beg end)))
10984 (org-overlay-put ov 'face (or face 'secondary-selection))
10985 (push ov org-table-rectangle-overlays)))
10987 (defun org-table-highlight-rectangle (&optional beg end face)
10988 "Highlight rectangular region in a table."
10989 (setq beg (or beg (point)) end (or end (point)))
10990 (let ((b (min beg end))
10991 (e (max beg end))
10992 l1 c1 l2 c2 tmp)
10993 (and (boundp 'org-show-positions)
10994 (setq org-show-positions (cons b (cons e org-show-positions))))
10995 (goto-char (min beg end))
10996 (setq l1 (org-current-line)
10997 c1 (org-table-current-column))
10998 (goto-char (max beg end))
10999 (setq l2 (org-current-line)
11000 c2 (org-table-current-column))
11001 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
11002 (goto-line l1)
11003 (beginning-of-line 1)
11004 (loop for line from l1 to l2 do
11005 (when (looking-at org-table-dataline-regexp)
11006 (org-table-goto-column c1)
11007 (skip-chars-backward "^|\n") (setq beg (point))
11008 (org-table-goto-column c2)
11009 (skip-chars-forward "^|\n") (setq end (point))
11010 (org-table-add-rectangle-overlay beg end face))
11011 (beginning-of-line 2))
11012 (goto-char b))
11013 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
11015 (defun org-table-remove-rectangle-highlight (&rest ignore)
11016 "Remove the rectangle overlays."
11017 (unless org-inhibit-highlight-removal
11018 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
11019 (mapc 'org-delete-overlay org-table-rectangle-overlays)
11020 (setq org-table-rectangle-overlays nil)))
11022 (defvar org-table-coordinate-overlays nil
11023 "Collects the cooordinate grid overlays, so that they can be removed.")
11024 (make-variable-buffer-local 'org-table-coordinate-overlays)
11026 (defun org-table-overlay-coordinates ()
11027 "Add overlays to the table at point, to show row/column coordinates."
11028 (interactive)
11029 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11030 (setq org-table-coordinate-overlays nil)
11031 (save-excursion
11032 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
11033 (goto-char (org-table-begin))
11034 (while (org-at-table-p)
11035 (setq eol (point-at-eol))
11036 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
11037 (push ov org-table-coordinate-overlays)
11038 (setq hline (looking-at org-table-hline-regexp))
11039 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
11040 (format "%4d" (setq id (1+ id)))))
11041 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
11042 (when hline
11043 (setq ic 0)
11044 (while (re-search-forward "[+|]\\(-+\\)" eol t)
11045 (setq beg (1+ (match-beginning 0))
11046 ic (1+ ic)
11047 s1 (concat "$" (int-to-string ic))
11048 s2 (org-number-to-letters ic)
11049 str (if (eq org-table-use-standard-references t) s2 s1))
11050 (setq ov (org-make-overlay beg (+ beg (length str))))
11051 (push ov org-table-coordinate-overlays)
11052 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
11053 (beginning-of-line 2)))))
11055 (defun org-table-toggle-coordinate-overlays ()
11056 "Toggle the display of Row/Column numbers in tables."
11057 (interactive)
11058 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
11059 (message "Row/Column number display turned %s"
11060 (if org-table-overlay-coordinates "on" "off"))
11061 (if (and (org-at-table-p) org-table-overlay-coordinates)
11062 (org-table-align))
11063 (unless org-table-overlay-coordinates
11064 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11065 (setq org-table-coordinate-overlays nil)))
11067 (defun org-table-toggle-formula-debugger ()
11068 "Toggle the formula debugger in tables."
11069 (interactive)
11070 (setq org-table-formula-debug (not org-table-formula-debug))
11071 (message "Formula debugging has been turned %s"
11072 (if org-table-formula-debug "on" "off")))
11074 ;;; The orgtbl minor mode
11076 ;; Define a minor mode which can be used in other modes in order to
11077 ;; integrate the org-mode table editor.
11079 ;; This is really a hack, because the org-mode table editor uses several
11080 ;; keys which normally belong to the major mode, for example the TAB and
11081 ;; RET keys. Here is how it works: The minor mode defines all the keys
11082 ;; necessary to operate the table editor, but wraps the commands into a
11083 ;; function which tests if the cursor is currently inside a table. If that
11084 ;; is the case, the table editor command is executed. However, when any of
11085 ;; those keys is used outside a table, the function uses `key-binding' to
11086 ;; look up if the key has an associated command in another currently active
11087 ;; keymap (minor modes, major mode, global), and executes that command.
11088 ;; There might be problems if any of the keys used by the table editor is
11089 ;; otherwise used as a prefix key.
11091 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11092 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11093 ;; addresses this by checking explicitly for both bindings.
11095 ;; The optimized version (see variable `orgtbl-optimized') takes over
11096 ;; all keys which are bound to `self-insert-command' in the *global map*.
11097 ;; Some modes bind other commands to simple characters, for example
11098 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11099 ;; active, this binding is ignored inside tables and replaced with a
11100 ;; modified self-insert.
11102 (defvar orgtbl-mode nil
11103 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11104 table editor in arbitrary modes.")
11105 (make-variable-buffer-local 'orgtbl-mode)
11107 (defvar orgtbl-mode-map (make-keymap)
11108 "Keymap for `orgtbl-mode'.")
11110 ;;;###autoload
11111 (defun turn-on-orgtbl ()
11112 "Unconditionally turn on `orgtbl-mode'."
11113 (orgtbl-mode 1))
11115 (defvar org-old-auto-fill-inhibit-regexp nil
11116 "Local variable used by `orgtbl-mode'")
11118 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
11119 "Matches a line belonging to an orgtbl.")
11121 (defconst orgtbl-extra-font-lock-keywords
11122 (list (list (concat "^" orgtbl-line-start-regexp ".*")
11123 0 (quote 'org-table) 'prepend))
11124 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
11126 ;;;###autoload
11127 (defun orgtbl-mode (&optional arg)
11128 "The `org-mode' table editor as a minor mode for use in other modes."
11129 (interactive)
11130 (if (org-mode-p)
11131 ;; Exit without error, in case some hook functions calls this
11132 ;; by accident in org-mode.
11133 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11134 (setq orgtbl-mode
11135 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11136 (if orgtbl-mode
11137 (progn
11138 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11139 ;; Make sure we are first in minor-mode-map-alist
11140 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11141 (and c (setq minor-mode-map-alist
11142 (cons c (delq c minor-mode-map-alist)))))
11143 (org-set-local (quote org-table-may-need-update) t)
11144 (org-add-hook 'before-change-functions 'org-before-change-function
11145 nil 'local)
11146 (org-set-local 'org-old-auto-fill-inhibit-regexp
11147 auto-fill-inhibit-regexp)
11148 (org-set-local 'auto-fill-inhibit-regexp
11149 (if auto-fill-inhibit-regexp
11150 (concat orgtbl-line-start-regexp "\\|"
11151 auto-fill-inhibit-regexp)
11152 orgtbl-line-start-regexp))
11153 (org-add-to-invisibility-spec '(org-cwidth))
11154 (when (fboundp 'font-lock-add-keywords)
11155 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11156 (org-restart-font-lock))
11157 (easy-menu-add orgtbl-mode-menu)
11158 (run-hooks 'orgtbl-mode-hook))
11159 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11160 (org-cleanup-narrow-column-properties)
11161 (org-remove-from-invisibility-spec '(org-cwidth))
11162 (remove-hook 'before-change-functions 'org-before-change-function t)
11163 (when (fboundp 'font-lock-remove-keywords)
11164 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11165 (org-restart-font-lock))
11166 (easy-menu-remove orgtbl-mode-menu)
11167 (force-mode-line-update 'all))))
11169 (defun org-cleanup-narrow-column-properties ()
11170 "Remove all properties related to narrow-column invisibility."
11171 (let ((s 1))
11172 (while (setq s (text-property-any s (point-max)
11173 'display org-narrow-column-arrow))
11174 (remove-text-properties s (1+ s) '(display t)))
11175 (setq s 1)
11176 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11177 (remove-text-properties s (1+ s) '(org-cwidth t)))
11178 (setq s 1)
11179 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11180 (remove-text-properties s (1+ s) '(invisible t)))))
11182 ;; Install it as a minor mode.
11183 (put 'orgtbl-mode :included t)
11184 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11185 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11187 (defun orgtbl-make-binding (fun n &rest keys)
11188 "Create a function for binding in the table minor mode.
11189 FUN is the command to call inside a table. N is used to create a unique
11190 command name. KEYS are keys that should be checked in for a command
11191 to execute outside of tables."
11192 (eval
11193 (list 'defun
11194 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11195 '(arg)
11196 (concat "In tables, run `" (symbol-name fun) "'.\n"
11197 "Outside of tables, run the binding of `"
11198 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11199 "'.")
11200 '(interactive "p")
11201 (list 'if
11202 '(org-at-table-p)
11203 (list 'call-interactively (list 'quote fun))
11204 (list 'let '(orgtbl-mode)
11205 (list 'call-interactively
11206 (append '(or)
11207 (mapcar (lambda (k)
11208 (list 'key-binding k))
11209 keys)
11210 '('orgtbl-error))))))))
11212 (defun orgtbl-error ()
11213 "Error when there is no default binding for a table key."
11214 (interactive)
11215 (error "This key has no function outside tables"))
11217 (defun orgtbl-setup ()
11218 "Setup orgtbl keymaps."
11219 (let ((nfunc 0)
11220 (bindings
11221 (list
11222 '([(meta shift left)] org-table-delete-column)
11223 '([(meta left)] org-table-move-column-left)
11224 '([(meta right)] org-table-move-column-right)
11225 '([(meta shift right)] org-table-insert-column)
11226 '([(meta shift up)] org-table-kill-row)
11227 '([(meta shift down)] org-table-insert-row)
11228 '([(meta up)] org-table-move-row-up)
11229 '([(meta down)] org-table-move-row-down)
11230 '("\C-c\C-w" org-table-cut-region)
11231 '("\C-c\M-w" org-table-copy-region)
11232 '("\C-c\C-y" org-table-paste-rectangle)
11233 '("\C-c-" org-table-insert-hline)
11234 '("\C-c}" org-table-toggle-coordinate-overlays)
11235 '("\C-c{" org-table-toggle-formula-debugger)
11236 '("\C-m" org-table-next-row)
11237 '([(shift return)] org-table-copy-down)
11238 '("\C-c\C-q" org-table-wrap-region)
11239 '("\C-c?" org-table-field-info)
11240 '("\C-c " org-table-blank-field)
11241 '("\C-c+" org-table-sum)
11242 '("\C-c=" org-table-eval-formula)
11243 '("\C-c'" org-table-edit-formulas)
11244 '("\C-c`" org-table-edit-field)
11245 '("\C-c*" org-table-recalculate)
11246 '("\C-c|" org-table-create-or-convert-from-region)
11247 '("\C-c^" org-table-sort-lines)
11248 '([(control ?#)] org-table-rotate-recalc-marks)))
11249 elt key fun cmd)
11250 (while (setq elt (pop bindings))
11251 (setq nfunc (1+ nfunc))
11252 (setq key (org-key (car elt))
11253 fun (nth 1 elt)
11254 cmd (orgtbl-make-binding fun nfunc key))
11255 (org-defkey orgtbl-mode-map key cmd))
11257 ;; Special treatment needed for TAB and RET
11258 (org-defkey orgtbl-mode-map [(return)]
11259 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11260 (org-defkey orgtbl-mode-map "\C-m"
11261 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11263 (org-defkey orgtbl-mode-map [(tab)]
11264 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11265 (org-defkey orgtbl-mode-map "\C-i"
11266 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11268 (org-defkey orgtbl-mode-map [(shift tab)]
11269 (orgtbl-make-binding 'org-table-previous-field 104
11270 [(shift tab)] [(tab)] "\C-i"))
11272 (org-defkey orgtbl-mode-map "\M-\C-m"
11273 (orgtbl-make-binding 'org-table-wrap-region 105
11274 "\M-\C-m" [(meta return)]))
11275 (org-defkey orgtbl-mode-map [(meta return)]
11276 (orgtbl-make-binding 'org-table-wrap-region 106
11277 [(meta return)] "\M-\C-m"))
11279 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11280 (when orgtbl-optimized
11281 ;; If the user wants maximum table support, we need to hijack
11282 ;; some standard editing functions
11283 (org-remap orgtbl-mode-map
11284 'self-insert-command 'orgtbl-self-insert-command
11285 'delete-char 'org-delete-char
11286 'delete-backward-char 'org-delete-backward-char)
11287 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11288 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11289 '("OrgTbl"
11290 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11291 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11292 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11293 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11294 "--"
11295 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11296 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11297 ["Copy Field from Above"
11298 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11299 "--"
11300 ("Column"
11301 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11302 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11303 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11304 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11305 ("Row"
11306 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11307 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11308 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11309 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11310 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
11311 "--"
11312 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11313 ("Rectangle"
11314 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11315 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11316 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11317 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11318 "--"
11319 ("Radio tables"
11320 ["Insert table template" orgtbl-insert-radio-table
11321 (assq major-mode orgtbl-radio-table-templates)]
11322 ["Comment/uncomment table" orgtbl-toggle-comment t])
11323 "--"
11324 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11325 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11326 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11327 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11328 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11329 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11330 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11331 ["Sum Column/Rectangle" org-table-sum
11332 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11333 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11334 ["Debug Formulas"
11335 org-table-toggle-formula-debugger :active (org-at-table-p)
11336 :keys "C-c {"
11337 :style toggle :selected org-table-formula-debug]
11338 ["Show Col/Row Numbers"
11339 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11340 :keys "C-c }"
11341 :style toggle :selected org-table-overlay-coordinates]
11345 (defun orgtbl-ctrl-c-ctrl-c (arg)
11346 "If the cursor is inside a table, realign the table.
11347 It it is a table to be sent away to a receiver, do it.
11348 With prefix arg, also recompute table."
11349 (interactive "P")
11350 (let ((pos (point)) action)
11351 (save-excursion
11352 (beginning-of-line 1)
11353 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11354 ((looking-at "[ \t]*|") pos)
11355 ((looking-at "#\\+TBLFM:") 'recalc))))
11356 (cond
11357 ((integerp action)
11358 (goto-char action)
11359 (org-table-maybe-eval-formula)
11360 (if arg
11361 (call-interactively 'org-table-recalculate)
11362 (org-table-maybe-recalculate-line))
11363 (call-interactively 'org-table-align)
11364 (orgtbl-send-table 'maybe))
11365 ((eq action 'recalc)
11366 (save-excursion
11367 (beginning-of-line 1)
11368 (skip-chars-backward " \r\n\t")
11369 (if (org-at-table-p)
11370 (org-call-with-arg 'org-table-recalculate t))))
11371 (t (let (orgtbl-mode)
11372 (call-interactively (key-binding "\C-c\C-c")))))))
11374 (defun orgtbl-tab (arg)
11375 "Justification and field motion for `orgtbl-mode'."
11376 (interactive "P")
11377 (if arg (org-table-edit-field t)
11378 (org-table-justify-field-maybe)
11379 (org-table-next-field)))
11381 (defun orgtbl-ret ()
11382 "Justification and field motion for `orgtbl-mode'."
11383 (interactive)
11384 (org-table-justify-field-maybe)
11385 (org-table-next-row))
11387 (defun orgtbl-self-insert-command (N)
11388 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11389 If the cursor is in a table looking at whitespace, the whitespace is
11390 overwritten, and the table is not marked as requiring realignment."
11391 (interactive "p")
11392 (if (and (org-at-table-p)
11394 (and org-table-auto-blank-field
11395 (member last-command
11396 '(orgtbl-hijacker-command-100
11397 orgtbl-hijacker-command-101
11398 orgtbl-hijacker-command-102
11399 orgtbl-hijacker-command-103
11400 orgtbl-hijacker-command-104
11401 orgtbl-hijacker-command-105))
11402 (org-table-blank-field))
11404 (eq N 1)
11405 (looking-at "[^|\n]* +|"))
11406 (let (org-table-may-need-update)
11407 (goto-char (1- (match-end 0)))
11408 (delete-backward-char 1)
11409 (goto-char (match-beginning 0))
11410 (self-insert-command N))
11411 (setq org-table-may-need-update t)
11412 (let (orgtbl-mode)
11413 (call-interactively (key-binding (vector last-input-event))))))
11415 (defun org-force-self-insert (N)
11416 "Needed to enforce self-insert under remapping."
11417 (interactive "p")
11418 (self-insert-command N))
11420 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11421 "Regula expression matching exponentials as produced by calc.")
11423 (defvar org-table-clean-did-remove-column nil)
11425 (defun orgtbl-export (table target)
11426 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11427 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11428 org-table-last-alignment org-table-last-column-widths
11429 maxcol column)
11430 (if (not (fboundp func))
11431 (error "Cannot export orgtbl table to %s" target))
11432 (setq lines (org-table-clean-before-export lines))
11433 (setq table
11434 (mapcar
11435 (lambda (x)
11436 (if (string-match org-table-hline-regexp x)
11437 'hline
11438 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11439 lines))
11440 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11441 table)))
11442 (loop for i from (1- maxcol) downto 0 do
11443 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11444 (setq column (delq nil column))
11445 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11446 (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))
11447 (funcall func table nil)))
11449 (defun orgtbl-send-table (&optional maybe)
11450 "Send a tranformed version of this table to the receiver position.
11451 With argument MAYBE, fail quietly if no transformation is defined for
11452 this table."
11453 (interactive)
11454 (catch 'exit
11455 (unless (org-at-table-p) (error "Not at a table"))
11456 ;; when non-interactive, we assume align has just happened.
11457 (when (interactive-p) (org-table-align))
11458 (save-excursion
11459 (goto-char (org-table-begin))
11460 (beginning-of-line 0)
11461 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11462 (if maybe
11463 (throw 'exit nil)
11464 (error "Don't know how to transform this table."))))
11465 (let* ((name (match-string 1))
11467 (transform (intern (match-string 2)))
11468 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11469 (skip (plist-get params :skip))
11470 (skipcols (plist-get params :skipcols))
11471 (txt (buffer-substring-no-properties
11472 (org-table-begin) (org-table-end)))
11473 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11474 (lines (org-table-clean-before-export lines))
11475 (i0 (if org-table-clean-did-remove-column 2 1))
11476 (table (mapcar
11477 (lambda (x)
11478 (if (string-match org-table-hline-regexp x)
11479 'hline
11480 (org-remove-by-index
11481 (org-split-string (org-trim x) "\\s-*|\\s-*")
11482 skipcols i0)))
11483 lines))
11484 (fun (if (= i0 2) 'cdr 'identity))
11485 (org-table-last-alignment
11486 (org-remove-by-index (funcall fun org-table-last-alignment)
11487 skipcols i0))
11488 (org-table-last-column-widths
11489 (org-remove-by-index (funcall fun org-table-last-column-widths)
11490 skipcols i0)))
11492 (unless (fboundp transform)
11493 (error "No such transformation function %s" transform))
11494 (setq txt (funcall transform table params))
11495 ;; Find the insertion place
11496 (save-excursion
11497 (goto-char (point-min))
11498 (unless (re-search-forward
11499 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11500 (error "Don't know where to insert translated table"))
11501 (goto-char (match-beginning 0))
11502 (beginning-of-line 2)
11503 (setq beg (point))
11504 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11505 (error "Cannot find end of insertion region"))
11506 (beginning-of-line 1)
11507 (delete-region beg (point))
11508 (goto-char beg)
11509 (insert txt "\n"))
11510 (message "Table converted and installed at receiver location"))))
11512 (defun org-remove-by-index (list indices &optional i0)
11513 "Remove the elements in LIST with indices in INDICES.
11514 First element has index 0, or I0 if given."
11515 (if (not indices)
11516 list
11517 (if (integerp indices) (setq indices (list indices)))
11518 (setq i0 (1- (or i0 0)))
11519 (delq :rm (mapcar (lambda (x)
11520 (setq i0 (1+ i0))
11521 (if (memq i0 indices) :rm x))
11522 list))))
11524 (defun orgtbl-toggle-comment ()
11525 "Comment or uncomment the orgtbl at point."
11526 (interactive)
11527 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11528 (re2 (concat "^" orgtbl-line-start-regexp))
11529 (commented (save-excursion (beginning-of-line 1)
11530 (cond ((looking-at re1) t)
11531 ((looking-at re2) nil)
11532 (t (error "Not at an org table")))))
11533 (re (if commented re1 re2))
11534 beg end)
11535 (save-excursion
11536 (beginning-of-line 1)
11537 (while (looking-at re) (beginning-of-line 0))
11538 (beginning-of-line 2)
11539 (setq beg (point))
11540 (while (looking-at re) (beginning-of-line 2))
11541 (setq end (point)))
11542 (comment-region beg end (if commented '(4) nil))))
11544 (defun orgtbl-insert-radio-table ()
11545 "Insert a radio table template appropriate for this major mode."
11546 (interactive)
11547 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11548 (txt (nth 1 e))
11549 name pos)
11550 (unless e (error "No radio table setup defined for %s" major-mode))
11551 (setq name (read-string "Table name: "))
11552 (while (string-match "%n" txt)
11553 (setq txt (replace-match name t t txt)))
11554 (or (bolp) (insert "\n"))
11555 (setq pos (point))
11556 (insert txt)
11557 (goto-char pos)))
11559 (defun org-get-param (params header i sym &optional hsym)
11560 "Get parameter value for symbol SYM.
11561 If this is a header line, actually get the value for the symbol with an
11562 additional \"h\" inserted after the colon.
11563 If the value is a protperty list, get the element for the current column.
11564 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11565 (let ((val (plist-get params sym)))
11566 (and hsym header (setq val (or (plist-get params hsym) val)))
11567 (if (consp val) (plist-get val i) val)))
11569 (defun orgtbl-to-generic (table params)
11570 "Convert the orgtbl-mode TABLE to some other format.
11571 This generic routine can be used for many standard cases.
11572 TABLE is a list, each entry either the symbol `hline' for a horizontal
11573 separator line, or a list of fields for that line.
11574 PARAMS is a property list of parameters that can influence the conversion.
11575 For the generic converter, some parameters are obligatory: You need to
11576 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11577 :splice, you must have :tstart and :tend.
11579 Valid parameters are
11581 :tstart String to start the table. Ignored when :splice is t.
11582 :tend String to end the table. Ignored when :splice is t.
11584 :splice When set to t, return only table body lines, don't wrap
11585 them into :tstart and :tend. Default is nil.
11587 :hline String to be inserted on horizontal separation lines.
11588 May be nil to ignore hlines.
11590 :lstart String to start a new table line.
11591 :lend String to end a table line
11592 :sep Separator between two fields
11593 :lfmt Format for entire line, with enough %s to capture all fields.
11594 If this is present, :lstart, :lend, and :sep are ignored.
11595 :fmt A format to be used to wrap the field, should contain
11596 %s for the original field value. For example, to wrap
11597 everything in dollars, you could use :fmt \"$%s$\".
11598 This may also be a property list with column numbers and
11599 formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11601 :hlstart :hlend :hlsep :hlfmt :hfmt
11602 Same as above, specific for the header lines in the table.
11603 All lines before the first hline are treated as header.
11604 If any of these is not present, the data line value is used.
11606 :efmt Use this format to print numbers with exponentials.
11607 The format should have %s twice for inserting mantissa
11608 and exponent, for example \"%s\\\\times10^{%s}\". This
11609 may also be a property list with column numbers and
11610 formats. :fmt will still be applied after :efmt.
11612 In addition to this, the parameters :skip and :skipcols are always handled
11613 directly by `orgtbl-send-table'. See manual."
11614 (interactive)
11615 (let* ((p params)
11616 (splicep (plist-get p :splice))
11617 (hline (plist-get p :hline))
11618 rtn line i fm efm lfmt h)
11620 ;; Do we have a header?
11621 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11622 (setq h t))
11624 ;; Put header
11625 (unless splicep
11626 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11628 ;; Now loop over all lines
11629 (while (setq line (pop table))
11630 (if (eq line 'hline)
11631 ;; A horizontal separator line
11632 (progn (if hline (push hline rtn))
11633 (setq h nil)) ; no longer in header
11634 ;; A normal line. Convert the fields, push line onto the result list
11635 (setq i 0)
11636 (setq line
11637 (mapcar
11638 (lambda (f)
11639 (setq i (1+ i)
11640 fm (org-get-param p h i :fmt :hfmt)
11641 efm (org-get-param p h i :efmt))
11642 (if (and efm (string-match orgtbl-exp-regexp f))
11643 (setq f (format
11644 efm (match-string 1 f) (match-string 2 f))))
11645 (if fm (setq f (format fm f)))
11647 line))
11648 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11649 (push (apply 'format lfmt line) rtn)
11650 (push (concat
11651 (org-get-param p h i :lstart :hlstart)
11652 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11653 (org-get-param p h i :lend :hlend))
11654 rtn))))
11656 (unless splicep
11657 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11659 (mapconcat 'identity (nreverse rtn) "\n")))
11661 (defun orgtbl-to-latex (table params)
11662 "Convert the orgtbl-mode TABLE to LaTeX.
11663 TABLE is a list, each entry either the symbol `hline' for a horizontal
11664 separator line, or a list of fields for that line.
11665 PARAMS is a property list of parameters that can influence the conversion.
11666 Supports all parameters from `orgtbl-to-generic'. Most important for
11667 LaTeX are:
11669 :splice When set to t, return only table body lines, don't wrap
11670 them into a tabular environment. Default is nil.
11672 :fmt A format to be used to wrap the field, should contain %s for the
11673 original field value. For example, to wrap everything in dollars,
11674 use :fmt \"$%s$\". This may also be a property list with column
11675 numbers and formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11677 :efmt Format for transforming numbers with exponentials. The format
11678 should have %s twice for inserting mantissa and exponent, for
11679 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11680 This may also be a property list with column numbers and formats.
11682 The general parameters :skip and :skipcols have already been applied when
11683 this function is called."
11684 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11685 org-table-last-alignment ""))
11686 (params2
11687 (list
11688 :tstart (concat "\\begin{tabular}{" alignment "}")
11689 :tend "\\end{tabular}"
11690 :lstart "" :lend " \\\\" :sep " & "
11691 :efmt "%s\\,(%s)" :hline "\\hline")))
11692 (orgtbl-to-generic table (org-combine-plists params2 params))))
11694 (defun orgtbl-to-html (table params)
11695 "Convert the orgtbl-mode TABLE to LaTeX.
11696 TABLE is a list, each entry either the symbol `hline' for a horizontal
11697 separator line, or a list of fields for that line.
11698 PARAMS is a property list of parameters that can influence the conversion.
11699 Currently this function recognizes the following parameters:
11701 :splice When set to t, return only table body lines, don't wrap
11702 them into a <table> environment. Default is nil.
11704 The general parameters :skip and :skipcols have already been applied when
11705 this function is called. The function does *not* use `orgtbl-to-generic',
11706 so you cannot specify parameters for it."
11707 (let* ((splicep (plist-get params :splice))
11708 html)
11709 ;; Just call the formatter we already have
11710 ;; We need to make text lines for it, so put the fields back together.
11711 (setq html (org-format-org-table-html
11712 (mapcar
11713 (lambda (x)
11714 (if (eq x 'hline)
11715 "|----+----|"
11716 (concat "| " (mapconcat 'identity x " | ") " |")))
11717 table)
11718 splicep))
11719 (if (string-match "\n+\\'" html)
11720 (setq html (replace-match "" t t html)))
11721 html))
11723 (defun orgtbl-to-texinfo (table params)
11724 "Convert the orgtbl-mode TABLE to TeXInfo.
11725 TABLE is a list, each entry either the symbol `hline' for a horizontal
11726 separator line, or a list of fields for that line.
11727 PARAMS is a property list of parameters that can influence the conversion.
11728 Supports all parameters from `orgtbl-to-generic'. Most important for
11729 TeXInfo are:
11731 :splice nil/t When set to t, return only table body lines, don't wrap
11732 them into a multitable environment. Default is nil.
11734 :fmt fmt A format to be used to wrap the field, should contain
11735 %s for the original field value. For example, to wrap
11736 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
11737 This may also be a property list with column numbers and
11738 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
11740 :cf \"f1 f2..\" The column fractions for the table. By default these
11741 are computed automatically from the width of the columns
11742 under org-mode.
11744 The general parameters :skip and :skipcols have already been applied when
11745 this function is called."
11746 (let* ((total (float (apply '+ org-table-last-column-widths)))
11747 (colfrac (or (plist-get params :cf)
11748 (mapconcat
11749 (lambda (x) (format "%.3f" (/ (float x) total)))
11750 org-table-last-column-widths " ")))
11751 (params2
11752 (list
11753 :tstart (concat "@multitable @columnfractions " colfrac)
11754 :tend "@end multitable"
11755 :lstart "@item " :lend "" :sep " @tab "
11756 :hlstart "@headitem ")))
11757 (orgtbl-to-generic table (org-combine-plists params2 params))))
11759 ;;;; Link Stuff
11761 ;;; Link abbreviations
11763 (defun org-link-expand-abbrev (link)
11764 "Apply replacements as defined in `org-link-abbrev-alist."
11765 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
11766 (let* ((key (match-string 1 link))
11767 (as (or (assoc key org-link-abbrev-alist-local)
11768 (assoc key org-link-abbrev-alist)))
11769 (tag (and (match-end 2) (match-string 3 link)))
11770 rpl)
11771 (if (not as)
11772 link
11773 (setq rpl (cdr as))
11774 (cond
11775 ((symbolp rpl) (funcall rpl tag))
11776 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
11777 (t (concat rpl tag)))))
11778 link))
11780 ;;; Storing and inserting links
11782 (defvar org-insert-link-history nil
11783 "Minibuffer history for links inserted with `org-insert-link'.")
11785 (defvar org-stored-links nil
11786 "Contains the links stored with `org-store-link'.")
11788 (defvar org-store-link-plist nil
11789 "Plist with info about the most recently link created with `org-store-link'.")
11791 (defvar org-link-protocols nil
11792 "Link protocols added to Org-mode using `org-add-link-type'.")
11794 (defvar org-store-link-functions nil
11795 "List of functions that are called to create and store a link.
11796 Each function will be called in turn until one returns a non-nil
11797 value. Each function should check if it is responsible for creating
11798 this link (for example by looking at the major mode).
11799 If not, it must exit and return nil.
11800 If yes, it should return a non-nil value after a calling
11801 `org-store-link-props' with a list of properties and values.
11802 Special properties are:
11804 :type The link prefix. like \"http\". This must be given.
11805 :link The link, like \"http://www.astro.uva.nl/~dominik\".
11806 This is obligatory as well.
11807 :description Optional default description for the second pair
11808 of brackets in an Org-mode link. The user can still change
11809 this when inserting this link into an Org-mode buffer.
11811 In addition to these, any additional properties can be specified
11812 and then used in remember templates.")
11814 (defun org-add-link-type (type &optional follow publish)
11815 "Add TYPE to the list of `org-link-types'.
11816 Re-compute all regular expressions depending on `org-link-types'
11817 FOLLOW and PUBLISH are two functions. Both take the link path as
11818 an argument.
11819 FOLLOW should do whatever is necessary to follow the link, for example
11820 to find a file or display a mail message.
11822 PUBLISH takes the path and retuns the string that should be used when
11823 this document is published. FIMXE: This is actually not yet implemented."
11824 (add-to-list 'org-link-types type t)
11825 (org-make-link-regexps)
11826 (add-to-list 'org-link-protocols
11827 (list type follow publish)))
11829 (defun org-add-agenda-custom-command (entry)
11830 "Replace or add a command in `org-agenda-custom-commands'.
11831 This is mostly for hacking and trying a new command - once the command
11832 works you probably want to add it to `org-agenda-custom-commands' for good."
11833 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
11834 (if ass
11835 (setcdr ass (cdr entry))
11836 (push entry org-agenda-custom-commands))))
11838 ;;;###autoload
11839 (defun org-store-link (arg)
11840 "\\<org-mode-map>Store an org-link to the current location.
11841 This link can later be inserted into an org-buffer with
11842 \\[org-insert-link].
11843 For some link types, a prefix arg is interpreted:
11844 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
11845 For file links, arg negates `org-context-in-file-links'."
11846 (interactive "P")
11847 (setq org-store-link-plist nil) ; reset
11848 (let (link cpltxt desc description search txt)
11849 (cond
11851 ((run-hook-with-args-until-success 'org-store-link-functions)
11852 (setq link (plist-get org-store-link-plist :link)
11853 desc (or (plist-get org-store-link-plist :description) link)))
11855 ((eq major-mode 'bbdb-mode)
11856 (let ((name (bbdb-record-name (bbdb-current-record)))
11857 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
11858 (setq cpltxt (concat "bbdb:" (or name company))
11859 link (org-make-link cpltxt))
11860 (org-store-link-props :type "bbdb" :name name :company company)))
11862 ((eq major-mode 'Info-mode)
11863 (setq link (org-make-link "info:"
11864 (file-name-nondirectory Info-current-file)
11865 ":" Info-current-node))
11866 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
11867 ":" Info-current-node))
11868 (org-store-link-props :type "info" :file Info-current-file
11869 :node Info-current-node))
11871 ((eq major-mode 'calendar-mode)
11872 (let ((cd (calendar-cursor-to-date)))
11873 (setq link
11874 (format-time-string
11875 (car org-time-stamp-formats)
11876 (apply 'encode-time
11877 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
11878 nil nil nil))))
11879 (org-store-link-props :type "calendar" :date cd)))
11881 ((or (eq major-mode 'vm-summary-mode)
11882 (eq major-mode 'vm-presentation-mode))
11883 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
11884 (vm-follow-summary-cursor)
11885 (save-excursion
11886 (vm-select-folder-buffer)
11887 (let* ((message (car vm-message-pointer))
11888 (folder buffer-file-name)
11889 (subject (vm-su-subject message))
11890 (to (vm-get-header-contents message "To"))
11891 (from (vm-get-header-contents message "From"))
11892 (message-id (vm-su-message-id message)))
11893 (org-store-link-props :type "vm" :from from :to to :subject subject
11894 :message-id message-id)
11895 (setq message-id (org-remove-angle-brackets message-id))
11896 (setq folder (abbreviate-file-name folder))
11897 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
11898 folder)
11899 (setq folder (replace-match "" t t folder)))
11900 (setq cpltxt (org-email-link-description))
11901 (setq link (org-make-link "vm:" folder "#" message-id)))))
11903 ((eq major-mode 'wl-summary-mode)
11904 (let* ((msgnum (wl-summary-message-number))
11905 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
11906 msgnum 'message-id))
11907 (wl-message-entity
11908 (if (fboundp 'elmo-message-entity)
11909 (elmo-message-entity
11910 wl-summary-buffer-elmo-folder msgnum)
11911 (elmo-msgdb-overview-get-entity
11912 msgnum (wl-summary-buffer-msgdb))))
11913 (from (wl-summary-line-from))
11914 (to (car (elmo-message-entity-field wl-message-entity 'to)))
11915 (subject (let (wl-thr-indent-string wl-parent-message-entity)
11916 (wl-summary-line-subject))))
11917 (org-store-link-props :type "wl" :from from :to to
11918 :subject subject :message-id message-id)
11919 (setq message-id (org-remove-angle-brackets message-id))
11920 (setq cpltxt (org-email-link-description))
11921 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
11922 "#" message-id))))
11924 ((or (equal major-mode 'mh-folder-mode)
11925 (equal major-mode 'mh-show-mode))
11926 (let ((from (org-mhe-get-header "From:"))
11927 (to (org-mhe-get-header "To:"))
11928 (message-id (org-mhe-get-header "Message-Id:"))
11929 (subject (org-mhe-get-header "Subject:")))
11930 (org-store-link-props :type "mh" :from from :to to
11931 :subject subject :message-id message-id)
11932 (setq cpltxt (org-email-link-description))
11933 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
11934 (org-remove-angle-brackets message-id)))))
11936 ((eq major-mode 'rmail-mode)
11937 (save-excursion
11938 (save-restriction
11939 (rmail-narrow-to-non-pruned-header)
11940 (let ((folder buffer-file-name)
11941 (message-id (mail-fetch-field "message-id"))
11942 (from (mail-fetch-field "from"))
11943 (to (mail-fetch-field "to"))
11944 (subject (mail-fetch-field "subject")))
11945 (org-store-link-props
11946 :type "rmail" :from from :to to
11947 :subject subject :message-id message-id)
11948 (setq message-id (org-remove-angle-brackets message-id))
11949 (setq cpltxt (org-email-link-description))
11950 (setq link (org-make-link "rmail:" folder "#" message-id))))))
11952 ((eq major-mode 'gnus-group-mode)
11953 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
11954 (gnus-group-group-name)) ; version
11955 ((fboundp 'gnus-group-name)
11956 (gnus-group-name))
11957 (t "???"))))
11958 (unless group (error "Not on a group"))
11959 (org-store-link-props :type "gnus" :group group)
11960 (setq cpltxt (concat
11961 (if (org-xor arg org-usenet-links-prefer-google)
11962 "http://groups.google.com/groups?group="
11963 "gnus:")
11964 group)
11965 link (org-make-link cpltxt))))
11967 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
11968 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
11969 (let* ((group gnus-newsgroup-name)
11970 (article (gnus-summary-article-number))
11971 (header (gnus-summary-article-header article))
11972 (from (mail-header-from header))
11973 (message-id (mail-header-id header))
11974 (date (mail-header-date header))
11975 (subject (gnus-summary-subject-string)))
11976 (org-store-link-props :type "gnus" :from from :subject subject
11977 :message-id message-id :group group)
11978 (setq cpltxt (org-email-link-description))
11979 (if (org-xor arg org-usenet-links-prefer-google)
11980 (setq link
11981 (concat
11982 cpltxt "\n "
11983 (format "http://groups.google.com/groups?as_umsgid=%s"
11984 (org-fixup-message-id-for-http message-id))))
11985 (setq link (org-make-link "gnus:" group
11986 "#" (number-to-string article))))))
11988 ((eq major-mode 'w3-mode)
11989 (setq cpltxt (url-view-url t)
11990 link (org-make-link cpltxt))
11991 (org-store-link-props :type "w3" :url (url-view-url t)))
11993 ((eq major-mode 'w3m-mode)
11994 (setq cpltxt (or w3m-current-title w3m-current-url)
11995 link (org-make-link w3m-current-url))
11996 (org-store-link-props :type "w3m" :url (url-view-url t)))
11998 ((setq search (run-hook-with-args-until-success
11999 'org-create-file-search-functions))
12000 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
12001 "::" search))
12002 (setq cpltxt (or description link)))
12004 ((eq major-mode 'image-mode)
12005 (setq cpltxt (concat "file:"
12006 (abbreviate-file-name buffer-file-name))
12007 link (org-make-link cpltxt))
12008 (org-store-link-props :type "image" :file buffer-file-name))
12010 ((eq major-mode 'dired-mode)
12011 ;; link to the file in the current line
12012 (setq cpltxt (concat "file:"
12013 (abbreviate-file-name
12014 (expand-file-name
12015 (dired-get-filename nil t))))
12016 link (org-make-link cpltxt)))
12018 ((and buffer-file-name (org-mode-p))
12019 ;; Just link to current headline
12020 (setq cpltxt (concat "file:"
12021 (abbreviate-file-name buffer-file-name)))
12022 ;; Add a context search string
12023 (when (org-xor org-context-in-file-links arg)
12024 ;; Check if we are on a target
12025 (if (org-in-regexp "<<\\(.*?\\)>>")
12026 (setq cpltxt (concat cpltxt "::" (match-string 1)))
12027 (setq txt (cond
12028 ((org-on-heading-p) nil)
12029 ((org-region-active-p)
12030 (buffer-substring (region-beginning) (region-end)))
12031 (t (buffer-substring (point-at-bol) (point-at-eol)))))
12032 (when (or (null txt) (string-match "\\S-" txt))
12033 (setq cpltxt
12034 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12035 desc "NONE"))))
12036 (if (string-match "::\\'" cpltxt)
12037 (setq cpltxt (substring cpltxt 0 -2)))
12038 (setq link (org-make-link cpltxt)))
12040 ((buffer-file-name (buffer-base-buffer))
12041 ;; Just link to this file here.
12042 (setq cpltxt (concat "file:"
12043 (abbreviate-file-name
12044 (buffer-file-name (buffer-base-buffer)))))
12045 ;; Add a context string
12046 (when (org-xor org-context-in-file-links arg)
12047 (setq txt (if (org-region-active-p)
12048 (buffer-substring (region-beginning) (region-end))
12049 (buffer-substring (point-at-bol) (point-at-eol))))
12050 ;; Only use search option if there is some text.
12051 (when (string-match "\\S-" txt)
12052 (setq cpltxt
12053 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12054 desc "NONE")))
12055 (setq link (org-make-link cpltxt)))
12057 ((interactive-p)
12058 (error "Cannot link to a buffer which is not visiting a file"))
12060 (t (setq link nil)))
12062 (if (consp link) (setq cpltxt (car link) link (cdr link)))
12063 (setq link (or link cpltxt)
12064 desc (or desc cpltxt))
12065 (if (equal desc "NONE") (setq desc nil))
12067 (if (and (interactive-p) link)
12068 (progn
12069 (setq org-stored-links
12070 (cons (list link desc) org-stored-links))
12071 (message "Stored: %s" (or desc link)))
12072 (and link (org-make-link-string link desc)))))
12074 (defun org-store-link-props (&rest plist)
12075 "Store link properties, extract names and addresses."
12076 (let (x adr)
12077 (when (setq x (plist-get plist :from))
12078 (setq adr (mail-extract-address-components x))
12079 (plist-put plist :fromname (car adr))
12080 (plist-put plist :fromaddress (nth 1 adr)))
12081 (when (setq x (plist-get plist :to))
12082 (setq adr (mail-extract-address-components x))
12083 (plist-put plist :toname (car adr))
12084 (plist-put plist :toaddress (nth 1 adr))))
12085 (let ((from (plist-get plist :from))
12086 (to (plist-get plist :to)))
12087 (when (and from to org-from-is-user-regexp)
12088 (plist-put plist :fromto
12089 (if (string-match org-from-is-user-regexp from)
12090 (concat "to %t")
12091 (concat "from %f")))))
12092 (setq org-store-link-plist plist))
12094 (defun org-email-link-description (&optional fmt)
12095 "Return the description part of an email link.
12096 This takes information from `org-store-link-plist' and formats it
12097 according to FMT (default from `org-email-link-description-format')."
12098 (setq fmt (or fmt org-email-link-description-format))
12099 (let* ((p org-store-link-plist)
12100 (to (plist-get p :toaddress))
12101 (from (plist-get p :fromaddress))
12102 (table
12103 (list
12104 (cons "%c" (plist-get p :fromto))
12105 (cons "%F" (plist-get p :from))
12106 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12107 (cons "%T" (plist-get p :to))
12108 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12109 (cons "%s" (plist-get p :subject))
12110 (cons "%m" (plist-get p :message-id)))))
12111 (when (string-match "%c" fmt)
12112 ;; Check if the user wrote this message
12113 (if (and org-from-is-user-regexp from to
12114 (save-match-data (string-match org-from-is-user-regexp from)))
12115 (setq fmt (replace-match "to %t" t t fmt))
12116 (setq fmt (replace-match "from %f" t t fmt))))
12117 (org-replace-escapes fmt table)))
12119 (defun org-make-org-heading-search-string (&optional string heading)
12120 "Make search string for STRING or current headline."
12121 (interactive)
12122 (let ((s (or string (org-get-heading))))
12123 (unless (and string (not heading))
12124 ;; We are using a headline, clean up garbage in there.
12125 (if (string-match org-todo-regexp s)
12126 (setq s (replace-match "" t t s)))
12127 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12128 (setq s (replace-match "" t t s)))
12129 (setq s (org-trim s))
12130 (if (string-match (concat "^\\(" org-quote-string "\\|"
12131 org-comment-string "\\)") s)
12132 (setq s (replace-match "" t t s)))
12133 (while (string-match org-ts-regexp s)
12134 (setq s (replace-match "" t t s))))
12135 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12136 (setq s (replace-match " " t t s)))
12137 (or string (setq s (concat "*" s))) ; Add * for headlines
12138 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12140 (defun org-make-link (&rest strings)
12141 "Concatenate STRINGS."
12142 (apply 'concat strings))
12144 (defun org-make-link-string (link &optional description)
12145 "Make a link with brackets, consisting of LINK and DESCRIPTION."
12146 (unless (string-match "\\S-" link)
12147 (error "Empty link"))
12148 (when (stringp description)
12149 ;; Remove brackets from the description, they are fatal.
12150 (while (string-match "\\[" description)
12151 (setq description (replace-match "{" t t description)))
12152 (while (string-match "\\]" description)
12153 (setq description (replace-match "}" t t description))))
12154 (when (equal (org-link-escape link) description)
12155 ;; No description needed, it is identical
12156 (setq description nil))
12157 (when (and (not description)
12158 (not (equal link (org-link-escape link))))
12159 (setq description link))
12160 (concat "[[" (org-link-escape link) "]"
12161 (if description (concat "[" description "]") "")
12162 "]"))
12164 (defconst org-link-escape-chars
12165 '((?\ . "%20")
12166 (?\[ . "%5B")
12167 (?\] . "%5D")
12168 (?\340 . "%E0") ; `a
12169 (?\342 . "%E2") ; ^a
12170 (?\347 . "%E7") ; ,c
12171 (?\350 . "%E8") ; `e
12172 (?\351 . "%E9") ; 'e
12173 (?\352 . "%EA") ; ^e
12174 (?\356 . "%EE") ; ^i
12175 (?\364 . "%F4") ; ^o
12176 (?\371 . "%F9") ; `u
12177 (?\373 . "%FB") ; ^u
12178 (?\; . "%3B")
12179 (?? . "%3F")
12180 (?= . "%3D")
12181 (?+ . "%2B")
12183 "Association list of escapes for some characters problematic in links.
12184 This is the list that is used for internal purposes.")
12186 (defconst org-link-escape-chars-browser
12187 '((?\ . "%20")) ; 32 for the SPC char
12188 "Association list of escapes for some characters problematic in links.
12189 This is the list that is used before handing over to the browser.")
12191 (defun org-link-escape (text &optional table)
12192 "Escape charaters in TEXT that are problematic for links."
12193 (setq table (or table org-link-escape-chars))
12194 (when text
12195 (let ((re (mapconcat (lambda (x) (regexp-quote
12196 (char-to-string (car x))))
12197 table "\\|")))
12198 (while (string-match re text)
12199 (setq text
12200 (replace-match
12201 (cdr (assoc (string-to-char (match-string 0 text))
12202 table))
12203 t t text)))
12204 text)))
12206 (defun org-link-unescape (text &optional table)
12207 "Reverse the action of `org-link-escape'."
12208 (setq table (or table org-link-escape-chars))
12209 (when text
12210 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12211 table "\\|")))
12212 (while (string-match re text)
12213 (setq text
12214 (replace-match
12215 (char-to-string (car (rassoc (match-string 0 text) table)))
12216 t t text)))
12217 text)))
12219 (defun org-xor (a b)
12220 "Exclusive or."
12221 (if a (not b) b))
12223 (defun org-get-header (header)
12224 "Find a header field in the current buffer."
12225 (save-excursion
12226 (goto-char (point-min))
12227 (let ((case-fold-search t) s)
12228 (cond
12229 ((eq header 'from)
12230 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12231 (setq s (match-string 1)))
12232 (while (string-match "\"" s)
12233 (setq s (replace-match "" t t s)))
12234 (if (string-match "[<(].*" s)
12235 (setq s (replace-match "" t t s))))
12236 ((eq header 'message-id)
12237 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12238 (setq s (match-string 1))))
12239 ((eq header 'subject)
12240 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12241 (setq s (match-string 1)))))
12242 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12243 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12244 s)))
12247 (defun org-fixup-message-id-for-http (s)
12248 "Replace special characters in a message id, so it can be used in an http query."
12249 (while (string-match "<" s)
12250 (setq s (replace-match "%3C" t t s)))
12251 (while (string-match ">" s)
12252 (setq s (replace-match "%3E" t t s)))
12253 (while (string-match "@" s)
12254 (setq s (replace-match "%40" t t s)))
12257 ;;;###autoload
12258 (defun org-insert-link-global ()
12259 "Insert a link like Org-mode does.
12260 This command can be called in any mode to insert a link in Org-mode syntax."
12261 (interactive)
12262 (org-run-like-in-org-mode 'org-insert-link))
12264 (defun org-insert-link (&optional complete-file)
12265 "Insert a link. At the prompt, enter the link.
12267 Completion can be used to select a link previously stored with
12268 `org-store-link'. When the empty string is entered (i.e. if you just
12269 press RET at the prompt), the link defaults to the most recently
12270 stored link. As SPC triggers completion in the minibuffer, you need to
12271 use M-SPC or C-q SPC to force the insertion of a space character.
12273 You will also be prompted for a description, and if one is given, it will
12274 be displayed in the buffer instead of the link.
12276 If there is already a link at point, this command will allow you to edit link
12277 and description parts.
12279 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12280 selected using completion. The path to the file will be relative to
12281 the current directory if the file is in the current directory or a
12282 subdirectory. Otherwise, the link will be the absolute path as
12283 completed in the minibuffer (i.e. normally ~/path/to/file).
12285 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12286 is in the current directory or below.
12287 With three \\[universal-argument] prefixes, negate the meaning of
12288 `org-keep-stored-link-after-insertion'."
12289 (interactive "P")
12290 (let* ((wcf (current-window-configuration))
12291 (region (if (org-region-active-p)
12292 (buffer-substring (region-beginning) (region-end))))
12293 (remove (and region (list (region-beginning) (region-end))))
12294 (desc region)
12295 tmphist ; byte-compile incorrectly complains about this
12296 link entry file)
12297 (cond
12298 ((org-in-regexp org-bracket-link-regexp 1)
12299 ;; We do have a link at point, and we are going to edit it.
12300 (setq remove (list (match-beginning 0) (match-end 0)))
12301 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12302 (setq link (read-string "Link: "
12303 (org-link-unescape
12304 (org-match-string-no-properties 1)))))
12305 ((or (org-in-regexp org-angle-link-re)
12306 (org-in-regexp org-plain-link-re))
12307 ;; Convert to bracket link
12308 (setq remove (list (match-beginning 0) (match-end 0))
12309 link (read-string "Link: "
12310 (org-remove-angle-brackets (match-string 0)))))
12311 ((equal complete-file '(4))
12312 ;; Completing read for file names.
12313 (setq file (read-file-name "File: "))
12314 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12315 (pwd1 (file-name-as-directory (abbreviate-file-name
12316 (expand-file-name ".")))))
12317 (cond
12318 ((equal complete-file '(16))
12319 (setq link (org-make-link
12320 "file:"
12321 (abbreviate-file-name (expand-file-name file)))))
12322 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12323 (setq link (org-make-link "file:" (match-string 1 file))))
12324 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12325 (expand-file-name file))
12326 (setq link (org-make-link
12327 "file:" (match-string 1 (expand-file-name file)))))
12328 (t (setq link (org-make-link "file:" file))))))
12330 ;; Read link, with completion for stored links.
12331 (with-output-to-temp-buffer "*Org Links*"
12332 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12333 (when org-stored-links
12334 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12335 (princ (mapconcat
12336 (lambda (x)
12337 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12338 (reverse org-stored-links) "\n"))))
12339 (let ((cw (selected-window)))
12340 (select-window (get-buffer-window "*Org Links*"))
12341 (shrink-window-if-larger-than-buffer)
12342 (setq truncate-lines t)
12343 (select-window cw))
12344 ;; Fake a link history, containing the stored links.
12345 (setq tmphist (append (mapcar 'car org-stored-links)
12346 org-insert-link-history))
12347 (unwind-protect
12348 (setq link (org-completing-read
12349 "Link: "
12350 (append
12351 (mapcar (lambda (x) (list (concat (car x) ":")))
12352 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12353 (mapcar (lambda (x) (list (concat x ":")))
12354 org-link-types))
12355 nil nil nil
12356 'tmphist
12357 (or (car (car org-stored-links)))))
12358 (set-window-configuration wcf)
12359 (kill-buffer "*Org Links*"))
12360 (setq entry (assoc link org-stored-links))
12361 (or entry (push link org-insert-link-history))
12362 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12363 (not org-keep-stored-link-after-insertion))
12364 (setq org-stored-links (delq (assoc link org-stored-links)
12365 org-stored-links)))
12366 (setq desc (or desc (nth 1 entry)))))
12368 (if (string-match org-plain-link-re link)
12369 ;; URL-like link, normalize the use of angular brackets.
12370 (setq link (org-make-link (org-remove-angle-brackets link))))
12372 ;; Check if we are linking to the current file with a search option
12373 ;; If yes, simplify the link by using only the search option.
12374 (when (and buffer-file-name
12375 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12376 (let* ((path (match-string 1 link))
12377 (case-fold-search nil)
12378 (search (match-string 2 link)))
12379 (save-match-data
12380 (if (equal (file-truename buffer-file-name) (file-truename path))
12381 ;; We are linking to this same file, with a search option
12382 (setq link search)))))
12384 ;; Check if we can/should use a relative path. If yes, simplify the link
12385 (when (string-match "\\<file:\\(.*\\)" link)
12386 (let* ((path (match-string 1 link))
12387 (origpath path)
12388 (desc-is-link (equal link desc))
12389 (case-fold-search nil))
12390 (cond
12391 ((eq org-link-file-path-type 'absolute)
12392 (setq path (abbreviate-file-name (expand-file-name path))))
12393 ((eq org-link-file-path-type 'noabbrev)
12394 (setq path (expand-file-name path)))
12395 ((eq org-link-file-path-type 'relative)
12396 (setq path (file-relative-name path)))
12398 (save-match-data
12399 (if (string-match (concat "^" (regexp-quote
12400 (file-name-as-directory
12401 (expand-file-name "."))))
12402 (expand-file-name path))
12403 ;; We are linking a file with relative path name.
12404 (setq path (substring (expand-file-name path)
12405 (match-end 0)))))))
12406 (setq link (concat "file:" path))
12407 (if (equal desc origpath)
12408 (setq desc path))))
12410 (setq desc (read-string "Description: " desc))
12411 (unless (string-match "\\S-" desc) (setq desc nil))
12412 (if remove (apply 'delete-region remove))
12413 (insert (org-make-link-string link desc))))
12415 (defun org-completing-read (&rest args)
12416 (let ((minibuffer-local-completion-map
12417 (copy-keymap minibuffer-local-completion-map)))
12418 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12419 (apply 'completing-read args)))
12421 ;;; Opening/following a link
12422 (defvar org-link-search-failed nil)
12424 (defun org-next-link ()
12425 "Move forward to the next link.
12426 If the link is in hidden text, expose it."
12427 (interactive)
12428 (when (and org-link-search-failed (eq this-command last-command))
12429 (goto-char (point-min))
12430 (message "Link search wrapped back to beginning of buffer"))
12431 (setq org-link-search-failed nil)
12432 (let* ((pos (point))
12433 (ct (org-context))
12434 (a (assoc :link ct)))
12435 (if a (goto-char (nth 2 a)))
12436 (if (re-search-forward org-any-link-re nil t)
12437 (progn
12438 (goto-char (match-beginning 0))
12439 (if (org-invisible-p) (org-show-context)))
12440 (goto-char pos)
12441 (setq org-link-search-failed t)
12442 (error "No further link found"))))
12444 (defun org-previous-link ()
12445 "Move backward to the previous link.
12446 If the link is in hidden text, expose it."
12447 (interactive)
12448 (when (and org-link-search-failed (eq this-command last-command))
12449 (goto-char (point-max))
12450 (message "Link search wrapped back to end of buffer"))
12451 (setq org-link-search-failed nil)
12452 (let* ((pos (point))
12453 (ct (org-context))
12454 (a (assoc :link ct)))
12455 (if a (goto-char (nth 1 a)))
12456 (if (re-search-backward org-any-link-re nil t)
12457 (progn
12458 (goto-char (match-beginning 0))
12459 (if (org-invisible-p) (org-show-context)))
12460 (goto-char pos)
12461 (setq org-link-search-failed t)
12462 (error "No further link found"))))
12464 (defun org-find-file-at-mouse (ev)
12465 "Open file link or URL at mouse."
12466 (interactive "e")
12467 (mouse-set-point ev)
12468 (org-open-at-point 'in-emacs))
12470 (defun org-open-at-mouse (ev)
12471 "Open file link or URL at mouse."
12472 (interactive "e")
12473 (mouse-set-point ev)
12474 (org-open-at-point))
12476 (defvar org-window-config-before-follow-link nil
12477 "The window configuration before following a link.
12478 This is saved in case the need arises to restore it.")
12480 (defvar org-open-link-marker (make-marker)
12481 "Marker pointing to the location where `org-open-at-point; was called.")
12483 ;;;###autoload
12484 (defun org-open-at-point-global ()
12485 "Follow a link like Org-mode does.
12486 This command can be called in any mode to follow a link that has
12487 Org-mode syntax."
12488 (interactive)
12489 (org-run-like-in-org-mode 'org-open-at-point))
12491 (defun org-open-at-point (&optional in-emacs)
12492 "Open link at or after point.
12493 If there is no link at point, this function will search forward up to
12494 the end of the current subtree.
12495 Normally, files will be opened by an appropriate application. If the
12496 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12497 (interactive "P")
12498 (catch 'abort
12499 (move-marker org-open-link-marker (point))
12500 (setq org-window-config-before-follow-link (current-window-configuration))
12501 (org-remove-occur-highlights nil nil t)
12502 (if (org-at-timestamp-p t)
12503 (org-follow-timestamp-link)
12504 (let (type path link line search (pos (point)))
12505 (catch 'match
12506 (save-excursion
12507 (skip-chars-forward "^]\n\r")
12508 (when (org-in-regexp org-bracket-link-regexp)
12509 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12510 (while (string-match " *\n *" link)
12511 (setq link (replace-match " " t t link)))
12512 (setq link (org-link-expand-abbrev link))
12513 (if (string-match org-link-re-with-space2 link)
12514 (setq type (match-string 1 link) path (match-string 2 link))
12515 (setq type "thisfile" path link))
12516 (throw 'match t)))
12518 (when (get-text-property (point) 'org-linked-text)
12519 (setq type "thisfile"
12520 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12521 (1+ (point)) (point))
12522 path (buffer-substring
12523 (previous-single-property-change pos 'org-linked-text)
12524 (next-single-property-change pos 'org-linked-text)))
12525 (throw 'match t))
12527 (save-excursion
12528 (when (or (org-in-regexp org-angle-link-re)
12529 (org-in-regexp org-plain-link-re))
12530 (setq type (match-string 1) path (match-string 2))
12531 (throw 'match t)))
12532 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12533 (setq type "tree-match"
12534 path (match-string 1))
12535 (throw 'match t))
12536 (save-excursion
12537 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12538 (setq type "tags"
12539 path (match-string 1))
12540 (while (string-match ":" path)
12541 (setq path (replace-match "+" t t path)))
12542 (throw 'match t))))
12543 (unless path
12544 (error "No link found"))
12545 ;; Remove any trailing spaces in path
12546 (if (string-match " +\\'" path)
12547 (setq path (replace-match "" t t path)))
12549 (cond
12551 ((assoc type org-link-protocols)
12552 (funcall (nth 1 (assoc type org-link-protocols)) path))
12554 ((equal type "mailto")
12555 (let ((cmd (car org-link-mailto-program))
12556 (args (cdr org-link-mailto-program)) args1
12557 (address path) (subject "") a)
12558 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12559 (setq address (match-string 1 path)
12560 subject (org-link-escape (match-string 2 path))))
12561 (while args
12562 (cond
12563 ((not (stringp (car args))) (push (pop args) args1))
12564 (t (setq a (pop args))
12565 (if (string-match "%a" a)
12566 (setq a (replace-match address t t a)))
12567 (if (string-match "%s" a)
12568 (setq a (replace-match subject t t a)))
12569 (push a args1))))
12570 (apply cmd (nreverse args1))))
12572 ((member type '("http" "https" "ftp" "news"))
12573 (browse-url (concat type ":" (org-link-escape
12574 path org-link-escape-chars-browser))))
12576 ((member type '("message"))
12577 (browse-url (concat type ":" path)))
12579 ((string= type "tags")
12580 (org-tags-view in-emacs path))
12581 ((string= type "thisfile")
12582 (if in-emacs
12583 (switch-to-buffer-other-window
12584 (org-get-buffer-for-internal-link (current-buffer)))
12585 (org-mark-ring-push))
12586 (let ((cmd `(org-link-search
12587 ,path
12588 ,(cond ((equal in-emacs '(4)) 'occur)
12589 ((equal in-emacs '(16)) 'org-occur)
12590 (t nil))
12591 ,pos)))
12592 (condition-case nil (eval cmd)
12593 (error (progn (widen) (eval cmd))))))
12595 ((string= type "tree-match")
12596 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12598 ((string= type "file")
12599 (if (string-match "::\\([0-9]+\\)\\'" path)
12600 (setq line (string-to-number (match-string 1 path))
12601 path (substring path 0 (match-beginning 0)))
12602 (if (string-match "::\\(.+\\)\\'" path)
12603 (setq search (match-string 1 path)
12604 path (substring path 0 (match-beginning 0)))))
12605 (if (string-match "[*?{]" (file-name-nondirectory path))
12606 (dired path)
12607 (org-open-file path in-emacs line search)))
12609 ((string= type "news")
12610 (org-follow-gnus-link path))
12612 ((string= type "bbdb")
12613 (org-follow-bbdb-link path))
12615 ((string= type "info")
12616 (org-follow-info-link path))
12618 ((string= type "gnus")
12619 (let (group article)
12620 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12621 (error "Error in Gnus link"))
12622 (setq group (match-string 1 path)
12623 article (match-string 3 path))
12624 (org-follow-gnus-link group article)))
12626 ((string= type "vm")
12627 (let (folder article)
12628 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12629 (error "Error in VM link"))
12630 (setq folder (match-string 1 path)
12631 article (match-string 3 path))
12632 ;; in-emacs is the prefix arg, will be interpreted as read-only
12633 (org-follow-vm-link folder article in-emacs)))
12635 ((string= type "wl")
12636 (let (folder article)
12637 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12638 (error "Error in Wanderlust link"))
12639 (setq folder (match-string 1 path)
12640 article (match-string 3 path))
12641 (org-follow-wl-link folder article)))
12643 ((string= type "mhe")
12644 (let (folder article)
12645 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12646 (error "Error in MHE link"))
12647 (setq folder (match-string 1 path)
12648 article (match-string 3 path))
12649 (org-follow-mhe-link folder article)))
12651 ((string= type "rmail")
12652 (let (folder article)
12653 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12654 (error "Error in RMAIL link"))
12655 (setq folder (match-string 1 path)
12656 article (match-string 3 path))
12657 (org-follow-rmail-link folder article)))
12659 ((string= type "shell")
12660 (let ((cmd path))
12661 (if (or (not org-confirm-shell-link-function)
12662 (funcall org-confirm-shell-link-function
12663 (format "Execute \"%s\" in shell? "
12664 (org-add-props cmd nil
12665 'face 'org-warning))))
12666 (progn
12667 (message "Executing %s" cmd)
12668 (shell-command cmd))
12669 (error "Abort"))))
12671 ((string= type "elisp")
12672 (let ((cmd path))
12673 (if (or (not org-confirm-elisp-link-function)
12674 (funcall org-confirm-elisp-link-function
12675 (format "Execute \"%s\" as elisp? "
12676 (org-add-props cmd nil
12677 'face 'org-warning))))
12678 (message "%s => %s" cmd (eval (read cmd)))
12679 (error "Abort"))))
12682 (browse-url-at-point)))))
12683 (move-marker org-open-link-marker nil)))
12685 ;;; File search
12687 (defvar org-create-file-search-functions nil
12688 "List of functions to construct the right search string for a file link.
12689 These functions are called in turn with point at the location to
12690 which the link should point.
12692 A function in the hook should first test if it would like to
12693 handle this file type, for example by checking the major-mode or
12694 the file extension. If it decides not to handle this file, it
12695 should just return nil to give other functions a chance. If it
12696 does handle the file, it must return the search string to be used
12697 when following the link. The search string will be part of the
12698 file link, given after a double colon, and `org-open-at-point'
12699 will automatically search for it. If special measures must be
12700 taken to make the search successful, another function should be
12701 added to the companion hook `org-execute-file-search-functions',
12702 which see.
12704 A function in this hook may also use `setq' to set the variable
12705 `description' to provide a suggestion for the descriptive text to
12706 be used for this link when it gets inserted into an Org-mode
12707 buffer with \\[org-insert-link].")
12709 (defvar org-execute-file-search-functions nil
12710 "List of functions to execute a file search triggered by a link.
12712 Functions added to this hook must accept a single argument, the
12713 search string that was part of the file link, the part after the
12714 double colon. The function must first check if it would like to
12715 handle this search, for example by checking the major-mode or the
12716 file extension. If it decides not to handle this search, it
12717 should just return nil to give other functions a chance. If it
12718 does handle the search, it must return a non-nil value to keep
12719 other functions from trying.
12721 Each function can access the current prefix argument through the
12722 variable `current-prefix-argument'. Note that a single prefix is
12723 used to force opening a link in Emacs, so it may be good to only
12724 use a numeric or double prefix to guide the search function.
12726 In case this is needed, a function in this hook can also restore
12727 the window configuration before `org-open-at-point' was called using:
12729 (set-window-configuration org-window-config-before-follow-link)")
12731 (defun org-link-search (s &optional type avoid-pos)
12732 "Search for a link search option.
12733 If S is surrounded by forward slashes, it is interpreted as a
12734 regular expression. In org-mode files, this will create an `org-occur'
12735 sparse tree. In ordinary files, `occur' will be used to list matches.
12736 If the current buffer is in `dired-mode', grep will be used to search
12737 in all files. If AVOID-POS is given, ignore matches near that position."
12738 (let ((case-fold-search t)
12739 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12740 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12741 (append '(("") (" ") ("\t") ("\n"))
12742 org-emphasis-alist)
12743 "\\|") "\\)"))
12744 (pos (point))
12745 (pre "") (post "")
12746 words re0 re1 re2 re3 re4 re5 re2a reall)
12747 (cond
12748 ;; First check if there are any special
12749 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12750 ;; Now try the builtin stuff
12751 ((save-excursion
12752 (goto-char (point-min))
12753 (and
12754 (re-search-forward
12755 (concat "<<" (regexp-quote s0) ">>") nil t)
12756 (setq pos (match-beginning 0))))
12757 ;; There is an exact target for this
12758 (goto-char pos))
12759 ((string-match "^/\\(.*\\)/$" s)
12760 ;; A regular expression
12761 (cond
12762 ((org-mode-p)
12763 (org-occur (match-string 1 s)))
12764 ;;((eq major-mode 'dired-mode)
12765 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12766 (t (org-do-occur (match-string 1 s)))))
12768 ;; A normal search strings
12769 (when (equal (string-to-char s) ?*)
12770 ;; Anchor on headlines, post may include tags.
12771 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
12772 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
12773 s (substring s 1)))
12774 (remove-text-properties
12775 0 (length s)
12776 '(face nil mouse-face nil keymap nil fontified nil) s)
12777 ;; Make a series of regular expressions to find a match
12778 (setq words (org-split-string s "[ \n\r\t]+")
12779 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
12780 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
12781 "\\)" markers)
12782 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
12783 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
12784 re1 (concat pre re2 post)
12785 re3 (concat pre re4 post)
12786 re5 (concat pre ".*" re4)
12787 re2 (concat pre re2)
12788 re2a (concat pre re2a)
12789 re4 (concat pre re4)
12790 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
12791 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
12792 re5 "\\)"
12794 (cond
12795 ((eq type 'org-occur) (org-occur reall))
12796 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
12797 (t (goto-char (point-min))
12798 (if (or (org-search-not-self 1 re0 nil t)
12799 (org-search-not-self 1 re1 nil t)
12800 (org-search-not-self 1 re2 nil t)
12801 (org-search-not-self 1 re2a nil t)
12802 (org-search-not-self 1 re3 nil t)
12803 (org-search-not-self 1 re4 nil t)
12804 (org-search-not-self 1 re5 nil t)
12806 (goto-char (match-beginning 1))
12807 (goto-char pos)
12808 (error "No match")))))
12810 ;; Normal string-search
12811 (goto-char (point-min))
12812 (if (search-forward s nil t)
12813 (goto-char (match-beginning 0))
12814 (error "No match"))))
12815 (and (org-mode-p) (org-show-context 'link-search))))
12817 (defun org-search-not-self (group &rest args)
12818 "Execute `re-search-forward', but only accept matches that do not
12819 enclose the position of `org-open-link-marker'."
12820 (let ((m org-open-link-marker))
12821 (catch 'exit
12822 (while (apply 're-search-forward args)
12823 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
12824 (goto-char (match-end group))
12825 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
12826 (> (match-beginning 0) (marker-position m))
12827 (< (match-end 0) (marker-position m)))
12828 (save-match-data
12829 (or (not (org-in-regexp
12830 org-bracket-link-analytic-regexp 1))
12831 (not (match-end 4)) ; no description
12832 (and (<= (match-beginning 4) (point))
12833 (>= (match-end 4) (point))))))
12834 (throw 'exit (point))))))))
12836 (defun org-get-buffer-for-internal-link (buffer)
12837 "Return a buffer to be used for displaying the link target of internal links."
12838 (cond
12839 ((not org-display-internal-link-with-indirect-buffer)
12840 buffer)
12841 ((string-match "(Clone)$" (buffer-name buffer))
12842 (message "Buffer is already a clone, not making another one")
12843 ;; we also do not modify visibility in this case
12844 buffer)
12845 (t ; make a new indirect buffer for displaying the link
12846 (let* ((bn (buffer-name buffer))
12847 (ibn (concat bn "(Clone)"))
12848 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
12849 (with-current-buffer ib (org-overview))
12850 ib))))
12852 (defun org-do-occur (regexp &optional cleanup)
12853 "Call the Emacs command `occur'.
12854 If CLEANUP is non-nil, remove the printout of the regular expression
12855 in the *Occur* buffer. This is useful if the regex is long and not useful
12856 to read."
12857 (occur regexp)
12858 (when cleanup
12859 (let ((cwin (selected-window)) win beg end)
12860 (when (setq win (get-buffer-window "*Occur*"))
12861 (select-window win))
12862 (goto-char (point-min))
12863 (when (re-search-forward "match[a-z]+" nil t)
12864 (setq beg (match-end 0))
12865 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
12866 (setq end (1- (match-beginning 0)))))
12867 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
12868 (goto-char (point-min))
12869 (select-window cwin))))
12871 ;;; The mark ring for links jumps
12873 (defvar org-mark-ring nil
12874 "Mark ring for positions before jumps in Org-mode.")
12875 (defvar org-mark-ring-last-goto nil
12876 "Last position in the mark ring used to go back.")
12877 ;; Fill and close the ring
12878 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
12879 (loop for i from 1 to org-mark-ring-length do
12880 (push (make-marker) org-mark-ring))
12881 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
12882 org-mark-ring)
12884 (defun org-mark-ring-push (&optional pos buffer)
12885 "Put the current position or POS into the mark ring and rotate it."
12886 (interactive)
12887 (setq pos (or pos (point)))
12888 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
12889 (move-marker (car org-mark-ring)
12890 (or pos (point))
12891 (or buffer (current-buffer)))
12892 (message "%s"
12893 (substitute-command-keys
12894 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
12896 (defun org-mark-ring-goto (&optional n)
12897 "Jump to the previous position in the mark ring.
12898 With prefix arg N, jump back that many stored positions. When
12899 called several times in succession, walk through the entire ring.
12900 Org-mode commands jumping to a different position in the current file,
12901 or to another Org-mode file, automatically push the old position
12902 onto the ring."
12903 (interactive "p")
12904 (let (p m)
12905 (if (eq last-command this-command)
12906 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
12907 (setq p org-mark-ring))
12908 (setq org-mark-ring-last-goto p)
12909 (setq m (car p))
12910 (switch-to-buffer (marker-buffer m))
12911 (goto-char m)
12912 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
12914 (defun org-remove-angle-brackets (s)
12915 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
12916 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
12918 (defun org-add-angle-brackets (s)
12919 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
12920 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
12923 ;;; Following specific links
12925 (defun org-follow-timestamp-link ()
12926 (cond
12927 ((org-at-date-range-p t)
12928 (let ((org-agenda-start-on-weekday)
12929 (t1 (match-string 1))
12930 (t2 (match-string 2)))
12931 (setq t1 (time-to-days (org-time-string-to-time t1))
12932 t2 (time-to-days (org-time-string-to-time t2)))
12933 (org-agenda-list nil t1 (1+ (- t2 t1)))))
12934 ((org-at-timestamp-p t)
12935 (org-agenda-list nil (time-to-days (org-time-string-to-time
12936 (substring (match-string 1) 0 10)))
12938 (t (error "This should not happen"))))
12941 (defun org-follow-bbdb-link (name)
12942 "Follow a BBDB link to NAME."
12943 (require 'bbdb)
12944 (let ((inhibit-redisplay (not debug-on-error))
12945 (bbdb-electric-p nil))
12946 (catch 'exit
12947 ;; Exact match on name
12948 (bbdb-name (concat "\\`" name "\\'") nil)
12949 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12950 ;; Exact match on name
12951 (bbdb-company (concat "\\`" name "\\'") nil)
12952 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12953 ;; Partial match on name
12954 (bbdb-name name nil)
12955 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12956 ;; Partial match on company
12957 (bbdb-company name nil)
12958 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12959 ;; General match including network address and notes
12960 (bbdb name nil)
12961 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
12962 (delete-window (get-buffer-window "*BBDB*"))
12963 (error "No matching BBDB record")))))
12965 (defun org-follow-info-link (name)
12966 "Follow an info file & node link to NAME."
12967 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
12968 (string-match "\\(.*\\)" name))
12969 (progn
12970 (require 'info)
12971 (if (match-string 2 name) ; If there isn't a node, choose "Top"
12972 (Info-find-node (match-string 1 name) (match-string 2 name))
12973 (Info-find-node (match-string 1 name) "Top")))
12974 (message "Could not open: %s" name)))
12976 (defun org-follow-gnus-link (&optional group article)
12977 "Follow a Gnus link to GROUP and ARTICLE."
12978 (require 'gnus)
12979 (funcall (cdr (assq 'gnus org-link-frame-setup)))
12980 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
12981 (cond ((and group article)
12982 (gnus-group-read-group 1 nil group)
12983 (gnus-summary-goto-article (string-to-number article) nil t))
12984 (group (gnus-group-jump-to-group group))))
12986 (defun org-follow-vm-link (&optional folder article readonly)
12987 "Follow a VM link to FOLDER and ARTICLE."
12988 (require 'vm)
12989 (setq article (org-add-angle-brackets article))
12990 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
12991 ;; ange-ftp or efs or tramp access
12992 (let ((user (or (match-string 1 folder) (user-login-name)))
12993 (host (match-string 2 folder))
12994 (file (match-string 3 folder)))
12995 (cond
12996 ((featurep 'tramp)
12997 ;; use tramp to access the file
12998 (if (featurep 'xemacs)
12999 (setq folder (format "[%s@%s]%s" user host file))
13000 (setq folder (format "/%s@%s:%s" user host file))))
13002 ;; use ange-ftp or efs
13003 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
13004 (setq folder (format "/%s@%s:%s" user host file))))))
13005 (when folder
13006 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
13007 (sit-for 0.1)
13008 (when article
13009 (vm-select-folder-buffer)
13010 (widen)
13011 (let ((case-fold-search t))
13012 (goto-char (point-min))
13013 (if (not (re-search-forward
13014 (concat "^" "message-id: *" (regexp-quote article))))
13015 (error "Could not find the specified message in this folder"))
13016 (vm-isearch-update)
13017 (vm-isearch-narrow)
13018 (vm-beginning-of-message)
13019 (vm-summarize)))))
13021 (defun org-follow-wl-link (folder article)
13022 "Follow a Wanderlust link to FOLDER and ARTICLE."
13023 (if (and (string= folder "%")
13024 article
13025 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
13026 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
13027 ;; Thus, we recompose folder and article ids.
13028 (setq folder (format "%s#%s" folder (match-string 1 article))
13029 article (match-string 3 article)))
13030 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
13031 (error "No such folder: %s" folder))
13032 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
13033 (and article
13034 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
13035 (wl-summary-redisplay)))
13037 (defun org-follow-rmail-link (folder article)
13038 "Follow an RMAIL link to FOLDER and ARTICLE."
13039 (setq article (org-add-angle-brackets article))
13040 (let (message-number)
13041 (save-excursion
13042 (save-window-excursion
13043 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13044 (setq message-number
13045 (save-restriction
13046 (widen)
13047 (goto-char (point-max))
13048 (if (re-search-backward
13049 (concat "^Message-ID:\\s-+" (regexp-quote
13050 (or article "")))
13051 nil t)
13052 (rmail-what-message))))))
13053 (if message-number
13054 (progn
13055 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13056 (rmail-show-message message-number)
13057 message-number)
13058 (error "Message not found"))))
13060 ;;; mh-e integration based on planner-mode
13061 (defun org-mhe-get-message-real-folder ()
13062 "Return the name of the current message real folder, so if you use
13063 sequences, it will now work."
13064 (save-excursion
13065 (let* ((folder
13066 (if (equal major-mode 'mh-folder-mode)
13067 mh-current-folder
13068 ;; Refer to the show buffer
13069 mh-show-folder-buffer))
13070 (end-index
13071 (if (boundp 'mh-index-folder)
13072 (min (length mh-index-folder) (length folder))))
13074 ;; a simple test on mh-index-data does not work, because
13075 ;; mh-index-data is always nil in a show buffer.
13076 (if (and (boundp 'mh-index-folder)
13077 (string= mh-index-folder (substring folder 0 end-index)))
13078 (if (equal major-mode 'mh-show-mode)
13079 (save-window-excursion
13080 (let (pop-up-frames)
13081 (when (buffer-live-p (get-buffer folder))
13082 (progn
13083 (pop-to-buffer folder)
13084 (org-mhe-get-message-folder-from-index)
13087 (org-mhe-get-message-folder-from-index)
13089 folder
13093 (defun org-mhe-get-message-folder-from-index ()
13094 "Returns the name of the message folder in a index folder buffer."
13095 (save-excursion
13096 (mh-index-previous-folder)
13097 (re-search-forward "^\\(+.*\\)$" nil t)
13098 (message "%s" (match-string 1))))
13100 (defun org-mhe-get-message-folder ()
13101 "Return the name of the current message folder. Be careful if you
13102 use sequences."
13103 (save-excursion
13104 (if (equal major-mode 'mh-folder-mode)
13105 mh-current-folder
13106 ;; Refer to the show buffer
13107 mh-show-folder-buffer)))
13109 (defun org-mhe-get-message-num ()
13110 "Return the number of the current message. Be careful if you
13111 use sequences."
13112 (save-excursion
13113 (if (equal major-mode 'mh-folder-mode)
13114 (mh-get-msg-num nil)
13115 ;; Refer to the show buffer
13116 (mh-show-buffer-message-number))))
13118 (defun org-mhe-get-header (header)
13119 "Return a header of the message in folder mode. This will create a
13120 show buffer for the corresponding message. If you have a more clever
13121 idea..."
13122 (let* ((folder (org-mhe-get-message-folder))
13123 (num (org-mhe-get-message-num))
13124 (buffer (get-buffer-create (concat "show-" folder)))
13125 (header-field))
13126 (with-current-buffer buffer
13127 (mh-display-msg num folder)
13128 (if (equal major-mode 'mh-folder-mode)
13129 (mh-header-display)
13130 (mh-show-header-display))
13131 (set-buffer buffer)
13132 (setq header-field (mh-get-header-field header))
13133 (if (equal major-mode 'mh-folder-mode)
13134 (mh-show)
13135 (mh-show-show))
13136 header-field)))
13138 (defun org-follow-mhe-link (folder article)
13139 "Follow an MHE link to FOLDER and ARTICLE.
13140 If ARTICLE is nil FOLDER is shown. If the configuration variable
13141 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
13142 ARTICLE is searched in all folders. Indexed searches (swish++,
13143 namazu, and others supported by MH-E) will always search in all
13144 folders."
13145 (require 'mh-e)
13146 (require 'mh-search)
13147 (require 'mh-utils)
13148 (mh-find-path)
13149 (if (not article)
13150 (mh-visit-folder (mh-normalize-folder-name folder))
13151 (setq article (org-add-angle-brackets article))
13152 (mh-search-choose)
13153 (if (equal mh-searcher 'pick)
13154 (progn
13155 (mh-search folder (list "--message-id" article))
13156 (when (and org-mhe-search-all-folders
13157 (not (org-mhe-get-message-real-folder)))
13158 (kill-this-buffer)
13159 (mh-search "+" (list "--message-id" article))))
13160 (mh-search "+" article))
13161 (if (org-mhe-get-message-real-folder)
13162 (mh-show-msg 1)
13163 (kill-this-buffer)
13164 (error "Message not found"))))
13166 ;;; BibTeX links
13168 ;; Use the custom search meachnism to construct and use search strings for
13169 ;; file links to BibTeX database entries.
13171 (defun org-create-file-search-in-bibtex ()
13172 "Create the search string and description for a BibTeX database entry."
13173 (when (eq major-mode 'bibtex-mode)
13174 ;; yes, we want to construct this search string.
13175 ;; Make a good description for this entry, using names, year and the title
13176 ;; Put it into the `description' variable which is dynamically scoped.
13177 (let ((bibtex-autokey-names 1)
13178 (bibtex-autokey-names-stretch 1)
13179 (bibtex-autokey-name-case-convert-function 'identity)
13180 (bibtex-autokey-name-separator " & ")
13181 (bibtex-autokey-additional-names " et al.")
13182 (bibtex-autokey-year-length 4)
13183 (bibtex-autokey-name-year-separator " ")
13184 (bibtex-autokey-titlewords 3)
13185 (bibtex-autokey-titleword-separator " ")
13186 (bibtex-autokey-titleword-case-convert-function 'identity)
13187 (bibtex-autokey-titleword-length 'infty)
13188 (bibtex-autokey-year-title-separator ": "))
13189 (setq description (bibtex-generate-autokey)))
13190 ;; Now parse the entry, get the key and return it.
13191 (save-excursion
13192 (bibtex-beginning-of-entry)
13193 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13195 (defun org-execute-file-search-in-bibtex (s)
13196 "Find the link search string S as a key for a database entry."
13197 (when (eq major-mode 'bibtex-mode)
13198 ;; Yes, we want to do the search in this file.
13199 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13200 (goto-char (point-min))
13201 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13202 (regexp-quote s) "[ \t\n]*,") nil t)
13203 (goto-char (match-beginning 0)))
13204 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13205 ;; Use double prefix to indicate that any web link should be browsed
13206 (let ((b (current-buffer)) (p (point)))
13207 ;; Restore the window configuration because we just use the web link
13208 (set-window-configuration org-window-config-before-follow-link)
13209 (save-excursion (set-buffer b) (goto-char p)
13210 (bibtex-url)))
13211 (recenter 0)) ; Move entry start to beginning of window
13212 ;; return t to indicate that the search is done.
13215 ;; Finally add the functions to the right hooks.
13216 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13217 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13219 ;; end of Bibtex link setup
13221 ;;; Following file links
13223 (defun org-open-file (path &optional in-emacs line search)
13224 "Open the file at PATH.
13225 First, this expands any special file name abbreviations. Then the
13226 configuration variable `org-file-apps' is checked if it contains an
13227 entry for this file type, and if yes, the corresponding command is launched.
13228 If no application is found, Emacs simply visits the file.
13229 With optional argument IN-EMACS, Emacs will visit the file.
13230 Optional LINE specifies a line to go to, optional SEARCH a string to
13231 search for. If LINE or SEARCH is given, the file will always be
13232 opened in Emacs.
13233 If the file does not exist, an error is thrown."
13234 (setq in-emacs (or in-emacs line search))
13235 (let* ((file (if (equal path "")
13236 buffer-file-name
13237 (substitute-in-file-name (expand-file-name path))))
13238 (apps (append org-file-apps (org-default-apps)))
13239 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13240 (dirp (if remp nil (file-directory-p file)))
13241 (dfile (downcase file))
13242 (old-buffer (current-buffer))
13243 (old-pos (point))
13244 (old-mode major-mode)
13245 ext cmd)
13246 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13247 (setq ext (match-string 1 dfile))
13248 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13249 (setq ext (match-string 1 dfile))))
13250 (if in-emacs
13251 (setq cmd 'emacs)
13252 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13253 (and dirp (cdr (assoc 'directory apps)))
13254 (cdr (assoc ext apps))
13255 (cdr (assoc t apps)))))
13256 (when (eq cmd 'mailcap)
13257 (require 'mailcap)
13258 (mailcap-parse-mailcaps)
13259 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13260 (command (mailcap-mime-info mime-type)))
13261 (if (stringp command)
13262 (setq cmd command)
13263 (setq cmd 'emacs))))
13264 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13265 (not (file-exists-p file))
13266 (not org-open-non-existing-files))
13267 (error "No such file: %s" file))
13268 (cond
13269 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13270 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13271 (while (string-match "['\"]%s['\"]" cmd)
13272 (setq cmd (replace-match "%s" t t cmd)))
13273 (while (string-match "%s" cmd)
13274 (setq cmd (replace-match
13275 (save-match-data (shell-quote-argument file))
13276 t t cmd)))
13277 (save-window-excursion
13278 (start-process-shell-command cmd nil cmd)))
13279 ((or (stringp cmd)
13280 (eq cmd 'emacs))
13281 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13282 (widen)
13283 (if line (goto-line line)
13284 (if search (org-link-search search))))
13285 ((consp cmd)
13286 (eval cmd))
13287 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13288 (and (org-mode-p) (eq old-mode 'org-mode)
13289 (or (not (equal old-buffer (current-buffer)))
13290 (not (equal old-pos (point))))
13291 (org-mark-ring-push old-pos old-buffer))))
13293 (defun org-default-apps ()
13294 "Return the default applications for this operating system."
13295 (cond
13296 ((eq system-type 'darwin)
13297 org-file-apps-defaults-macosx)
13298 ((eq system-type 'windows-nt)
13299 org-file-apps-defaults-windowsnt)
13300 (t org-file-apps-defaults-gnu)))
13302 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13303 (defun org-file-remote-p (file)
13304 "Test whether FILE specifies a location on a remote system.
13305 Return non-nil if the location is indeed remote.
13307 For example, the filename \"/user@host:/foo\" specifies a location
13308 on the system \"/user@host:\"."
13309 (cond ((fboundp 'file-remote-p)
13310 (file-remote-p file))
13311 ((fboundp 'tramp-handle-file-remote-p)
13312 (tramp-handle-file-remote-p file))
13313 ((and (boundp 'ange-ftp-name-format)
13314 (string-match (car ange-ftp-name-format) file))
13316 (t nil)))
13319 ;;;; Hooks for remember.el, and refiling
13321 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13322 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13324 ;;;###autoload
13325 (defun org-remember-insinuate ()
13326 "Setup remember.el for use wiht Org-mode."
13327 (require 'remember)
13328 (setq remember-annotation-functions '(org-remember-annotation))
13329 (setq remember-handler-functions '(org-remember-handler))
13330 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13332 ;;;###autoload
13333 (defun org-remember-annotation ()
13334 "Return a link to the current location as an annotation for remember.el.
13335 If you are using Org-mode files as target for data storage with
13336 remember.el, then the annotations should include a link compatible with the
13337 conventions in Org-mode. This function returns such a link."
13338 (org-store-link nil))
13340 (defconst org-remember-help
13341 "Select a destination location for the note.
13342 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13343 RET on headline -> Store as sublevel entry to current headline
13344 RET at beg-of-buf -> Append to file as level 2 headline
13345 <left>/<right> -> before/after current headline, same headings level")
13347 (defvar org-remember-previous-location nil)
13348 (defvar org-force-remember-template-char) ;; dynamically scoped
13350 (defun org-select-remember-template (&optional use-char)
13351 (when org-remember-templates
13352 (let* ((templates (mapcar (lambda (x)
13353 (if (stringp (car x))
13354 (append (list (nth 1 x) (car x)) (cddr x))
13355 (append (list (car x) "") (cdr x))))
13356 org-remember-templates))
13357 (char (or use-char
13358 (cond
13359 ((= (length templates) 1)
13360 (caar templates))
13361 ((and (boundp 'org-force-remember-template-char)
13362 org-force-remember-template-char)
13363 (if (stringp org-force-remember-template-char)
13364 (string-to-char org-force-remember-template-char)
13365 org-force-remember-template-char))
13367 (message "Select template: %s"
13368 (mapconcat
13369 (lambda (x)
13370 (cond
13371 ((not (string-match "\\S-" (nth 1 x)))
13372 (format "[%c]" (car x)))
13373 ((equal (downcase (car x))
13374 (downcase (aref (nth 1 x) 0)))
13375 (format "[%c]%s" (car x)
13376 (substring (nth 1 x) 1)))
13377 (t (format "[%c]%s" (car x) (nth 1 x)))))
13378 templates " "))
13379 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13380 (when (equal char0 ?\C-g)
13381 (jump-to-register remember-register)
13382 (kill-buffer remember-buffer))
13383 char0))))))
13384 (cddr (assoc char templates)))))
13386 (defvar x-last-selected-text)
13387 (defvar x-last-selected-text-primary)
13389 ;;;###autoload
13390 (defun org-remember-apply-template (&optional use-char skip-interactive)
13391 "Initialize *remember* buffer with template, invoke `org-mode'.
13392 This function should be placed into `remember-mode-hook' and in fact requires
13393 to be run from that hook to function properly."
13394 (if org-remember-templates
13395 (let* ((entry (org-select-remember-template use-char))
13396 (tpl (car entry))
13397 (plist-p (if org-store-link-plist t nil))
13398 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13399 (string-match "\\S-" (nth 1 entry)))
13400 (nth 1 entry)
13401 org-default-notes-file))
13402 (headline (nth 2 entry))
13403 (v-c (or (and (eq window-system 'x)
13404 (fboundp 'x-cut-buffer-or-selection-value)
13405 (x-cut-buffer-or-selection-value))
13406 (org-bound-and-true-p x-last-selected-text)
13407 (org-bound-and-true-p x-last-selected-text-primary)
13408 (and (> (length kill-ring) 0) (current-kill 0))))
13409 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13410 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13411 (v-u (concat "[" (substring v-t 1 -1) "]"))
13412 (v-U (concat "[" (substring v-T 1 -1) "]"))
13413 ;; `initial' and `annotation' are bound in `remember'
13414 (v-i (if (boundp 'initial) initial))
13415 (v-a (if (and (boundp 'annotation) annotation)
13416 (if (equal annotation "[[]]") "" annotation)
13417 ""))
13418 (v-A (if (and v-a
13419 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13420 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13421 v-a))
13422 (v-n user-full-name)
13423 (org-startup-folded nil)
13424 org-time-was-given org-end-time-was-given x
13425 prompt completions char time pos default histvar)
13426 (setq org-store-link-plist
13427 (append (list :annotation v-a :initial v-i)
13428 org-store-link-plist))
13429 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13430 (erase-buffer)
13431 (insert (substitute-command-keys
13432 (format
13433 "## Filing location: Select interactively, default, or last used:
13434 ## %s to select file and header location interactively.
13435 ## %s \"%s\" -> \"* %s\"
13436 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13437 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13438 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13439 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13440 (abbreviate-file-name (or file org-default-notes-file))
13441 (or headline "")
13442 (or (car org-remember-previous-location) "???")
13443 (or (cdr org-remember-previous-location) "???"))))
13444 (insert tpl) (goto-char (point-min))
13445 ;; Simple %-escapes
13446 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13447 (when (and initial (equal (match-string 0) "%i"))
13448 (save-match-data
13449 (let* ((lead (buffer-substring
13450 (point-at-bol) (match-beginning 0))))
13451 (setq v-i (mapconcat 'identity
13452 (org-split-string initial "\n")
13453 (concat "\n" lead))))))
13454 (replace-match
13455 (or (eval (intern (concat "v-" (match-string 1)))) "")
13456 t t))
13458 ;; %[] Insert contents of a file.
13459 (goto-char (point-min))
13460 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13461 (let ((start (match-beginning 0))
13462 (end (match-end 0))
13463 (filename (expand-file-name (match-string 1))))
13464 (goto-char start)
13465 (delete-region start end)
13466 (condition-case error
13467 (insert-file-contents filename)
13468 (error (insert (format "%%![Couldn't insert %s: %s]"
13469 filename error))))))
13470 ;; %() embedded elisp
13471 (goto-char (point-min))
13472 (while (re-search-forward "%\\((.+)\\)" nil t)
13473 (goto-char (match-beginning 0))
13474 (let ((template-start (point)))
13475 (forward-char 1)
13476 (let ((result
13477 (condition-case error
13478 (eval (read (current-buffer)))
13479 (error (format "%%![Error: %s]" error)))))
13480 (delete-region template-start (point))
13481 (insert result))))
13483 ;; From the property list
13484 (when plist-p
13485 (goto-char (point-min))
13486 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13487 (and (setq x (or (plist-get org-store-link-plist
13488 (intern (match-string 1))) ""))
13489 (replace-match x t t))))
13491 ;; Turn on org-mode in the remember buffer, set local variables
13492 (org-mode)
13493 (org-set-local 'org-finish-function 'org-remember-finalize)
13494 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13495 (org-set-local 'org-default-notes-file file))
13496 (if (and headline (stringp headline) (string-match "\\S-" headline))
13497 (org-set-local 'org-remember-default-headline headline))
13498 ;; Interactive template entries
13499 (goto-char (point-min))
13500 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGuUtT]\\)?" nil t)
13501 (setq char (if (match-end 3) (match-string 3))
13502 prompt (if (match-end 2) (match-string 2)))
13503 (goto-char (match-beginning 0))
13504 (replace-match "")
13505 (setq completions nil default nil)
13506 (when prompt
13507 (setq completions (org-split-string prompt "|")
13508 prompt (pop completions)
13509 default (car completions)
13510 histvar (intern (concat
13511 "org-remember-template-prompt-history::"
13512 (or prompt "")))
13513 completions (mapcar 'list completions)))
13514 (cond
13515 ((member char '("G" "g"))
13516 (let* ((org-last-tags-completion-table
13517 (org-global-tags-completion-table
13518 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13519 (org-add-colon-after-tag-completion t)
13520 (ins (completing-read
13521 (if prompt (concat prompt ": ") "Tags: ")
13522 'org-tags-completion-function nil nil nil
13523 'org-tags-history)))
13524 (setq ins (mapconcat 'identity
13525 (org-split-string ins (org-re "[^[:alnum:]]+"))
13526 ":"))
13527 (when (string-match "\\S-" ins)
13528 (or (equal (char-before) ?:) (insert ":"))
13529 (insert ins)
13530 (or (equal (char-after) ?:) (insert ":")))))
13531 (char
13532 (setq org-time-was-given (equal (upcase char) char))
13533 (setq time (org-read-date (equal (upcase char) "U") t nil
13534 prompt))
13535 (org-insert-time-stamp time org-time-was-given
13536 (member char '("u" "U"))
13537 nil nil (list org-end-time-was-given)))
13539 (insert (org-completing-read
13540 (concat (if prompt prompt "Enter string")
13541 (if default (concat " [" default "]"))
13542 ": ")
13543 completions nil nil nil histvar default)))))
13544 (goto-char (point-min))
13545 (if (re-search-forward "%\\?" nil t)
13546 (replace-match "")
13547 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13548 (org-mode)
13549 (org-set-local 'org-finish-function 'org-remember-finalize))
13550 (when (save-excursion
13551 (goto-char (point-min))
13552 (re-search-forward "%!" nil t))
13553 (replace-match "")
13554 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13556 (defun org-remember-finish-immediately ()
13557 "File remember note immediately.
13558 This should be run in `post-command-hook' and will remove itself
13559 from that hook."
13560 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13561 (when org-finish-function
13562 (funcall org-finish-function)))
13564 (defun org-remember-finalize ()
13565 "Finalize the remember process."
13566 (unless (fboundp 'remember-finalize)
13567 (defalias 'remember-finalize 'remember-buffer))
13568 (when (and org-clock-marker
13569 (equal (marker-buffer org-clock-marker) (current-buffer)))
13570 ;; FIXME: test this, this is w/o notetaking!
13571 (let (org-log-done) (org-clock-out)))
13572 (when buffer-file-name
13573 (save-buffer)
13574 (setq buffer-file-name nil))
13575 (remember-finalize))
13577 ;;;###autoload
13578 (defun org-remember (&optional goto org-force-remember-template-char)
13579 "Call `remember'. If this is already a remember buffer, re-apply template.
13580 If there is an active region, make sure remember uses it as initial content
13581 of the remember buffer.
13583 When called interactively with a `C-u' prefix argument GOTO, don't remember
13584 anything, just go to the file/headline where the selected template usually
13585 stores its notes. With a double prefix arg `C-u C-u', go to the last
13586 note stored by remember.
13588 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13589 associated with a template in `org-remember-templates'."
13590 (interactive "P")
13591 (cond
13592 ((equal goto '(4)) (org-go-to-remember-target))
13593 ((equal goto '(16)) (org-remember-goto-last-stored))
13595 (if (memq org-finish-function '(remember-buffer remember-finalize))
13596 (progn
13597 (when (< (length org-remember-templates) 2)
13598 (error "No other template available"))
13599 (erase-buffer)
13600 (let ((annotation (plist-get org-store-link-plist :annotation))
13601 (initial (plist-get org-store-link-plist :initial)))
13602 (org-remember-apply-template))
13603 (message "Press C-c C-c to remember data"))
13604 (if (org-region-active-p)
13605 (remember (buffer-substring (point) (mark)))
13606 (call-interactively 'remember))))))
13608 (defun org-remember-goto-last-stored ()
13609 "Go to the location where the last remember note was stored."
13610 (interactive)
13611 (bookmark-jump "org-remember-last-stored")
13612 (message "This is the last note stored by remember"))
13614 (defun org-go-to-remember-target (&optional template-key)
13615 "Go to the target location of a remember template.
13616 The user is queried for the template."
13617 (interactive)
13618 (let* ((entry (org-select-remember-template template-key))
13619 (file (nth 1 entry))
13620 (heading (nth 2 entry))
13621 visiting)
13622 (unless (and file (stringp file) (string-match "\\S-" file))
13623 (setq file org-default-notes-file))
13624 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13625 (setq heading org-remember-default-headline))
13626 (setq visiting (org-find-base-buffer-visiting file))
13627 (if (not visiting) (find-file-noselect file))
13628 (switch-to-buffer (or visiting (get-file-buffer file)))
13629 (widen)
13630 (goto-char (point-min))
13631 (if (re-search-forward
13632 (concat "^\\*+[ \t]+" (regexp-quote heading)
13633 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13634 nil t)
13635 (goto-char (match-beginning 0))
13636 (error "Target headline not found: %s" heading))))
13638 (defvar org-note-abort nil) ; dynamically scoped
13640 ;;;###autoload
13641 (defun org-remember-handler ()
13642 "Store stuff from remember.el into an org file.
13643 First prompts for an org file. If the user just presses return, the value
13644 of `org-default-notes-file' is used.
13645 Then the command offers the headings tree of the selected file in order to
13646 file the text at a specific location.
13647 You can either immediately press RET to get the note appended to the
13648 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13649 find a better place. Then press RET or <left> or <right> in insert the note.
13651 Key Cursor position Note gets inserted
13652 -----------------------------------------------------------------------------
13653 RET buffer-start as level 1 heading at end of file
13654 RET on headline as sublevel of the heading at cursor
13655 RET no heading at cursor position, level taken from context.
13656 Or use prefix arg to specify level manually.
13657 <left> on headline as same level, before current heading
13658 <right> on headline as same level, after current heading
13660 So the fastest way to store the note is to press RET RET to append it to
13661 the default file. This way your current train of thought is not
13662 interrupted, in accordance with the principles of remember.el.
13663 You can also get the fast execution without prompting by using
13664 C-u C-c C-c to exit the remember buffer. See also the variable
13665 `org-remember-store-without-prompt'.
13667 Before being stored away, the function ensures that the text has a
13668 headline, i.e. a first line that starts with a \"*\". If not, a headline
13669 is constructed from the current date and some additional data.
13671 If the variable `org-adapt-indentation' is non-nil, the entire text is
13672 also indented so that it starts in the same column as the headline
13673 \(i.e. after the stars).
13675 See also the variable `org-reverse-note-order'."
13676 (goto-char (point-min))
13677 (while (looking-at "^[ \t]*\n\\|^##.*\n")
13678 (replace-match ""))
13679 (goto-char (point-max))
13680 (beginning-of-line 1)
13681 (while (looking-at "[ \t]*$\\|##.*")
13682 (delete-region (1- (point)) (point-max))
13683 (beginning-of-line 1))
13684 (catch 'quit
13685 (if org-note-abort (throw 'quit nil))
13686 (let* ((txt (buffer-substring (point-min) (point-max)))
13687 (fastp (org-xor (equal current-prefix-arg '(4))
13688 org-remember-store-without-prompt))
13689 (file (cond
13690 (fastp org-default-notes-file)
13691 ((and (eq org-remember-interactive-interface 'refile)
13692 org-refile-targets)
13693 org-default-notes-file)
13694 ((not (and (equal current-prefix-arg '(16))
13695 org-remember-previous-location))
13696 (org-get-org-file))))
13697 (heading org-remember-default-headline)
13698 (visiting (and file (org-find-base-buffer-visiting file)))
13699 (org-startup-folded nil)
13700 (org-startup-align-all-tables nil)
13701 (org-goto-start-pos 1)
13702 spos exitcmd level indent reversed)
13703 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
13704 (setq file (car org-remember-previous-location)
13705 heading (cdr org-remember-previous-location)
13706 fastp t))
13707 (setq current-prefix-arg nil)
13708 (if (string-match "[ \t\n]+\\'" txt)
13709 (setq txt (replace-match "" t t txt)))
13710 ;; Modify text so that it becomes a nice subtree which can be inserted
13711 ;; into an org tree.
13712 (let* ((lines (split-string txt "\n"))
13713 first)
13714 (setq first (car lines) lines (cdr lines))
13715 (if (string-match "^\\*+ " first)
13716 ;; Is already a headline
13717 (setq indent nil)
13718 ;; We need to add a headline: Use time and first buffer line
13719 (setq lines (cons first lines)
13720 first (concat "* " (current-time-string)
13721 " (" (remember-buffer-desc) ")")
13722 indent " "))
13723 (if (and org-adapt-indentation indent)
13724 (setq lines (mapcar
13725 (lambda (x)
13726 (if (string-match "\\S-" x)
13727 (concat indent x) x))
13728 lines)))
13729 (setq txt (concat first "\n"
13730 (mapconcat 'identity lines "\n"))))
13731 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
13732 (setq txt (replace-match "\n\n" t t txt))
13733 (if (string-match "[ \t\n]*\\'" txt)
13734 (setq txt (replace-match "\n" t t txt))))
13735 ;; Put the modified text back into the remember buffer, for refile.
13736 (erase-buffer)
13737 (insert txt)
13738 (goto-char (point-min))
13739 (when (and (eq org-remember-interactive-interface 'refile)
13740 (not fastp))
13741 (org-refile nil (or visiting (find-file-noselect file)))
13742 (throw 'quit t))
13743 ;; Find the file
13744 (if (not visiting) (find-file-noselect file))
13745 (with-current-buffer (or visiting (get-file-buffer file))
13746 (unless (org-mode-p)
13747 (error "Target files for remember notes must be in Org-mode"))
13748 (save-excursion
13749 (save-restriction
13750 (widen)
13751 (and (goto-char (point-min))
13752 (not (re-search-forward "^\\* " nil t))
13753 (insert "\n* " (or heading "Notes") "\n"))
13754 (setq reversed (org-notes-order-reversed-p))
13756 ;; Find the default location
13757 (when (and heading (stringp heading) (string-match "\\S-" heading))
13758 (goto-char (point-min))
13759 (if (re-search-forward
13760 (concat "^\\*+[ \t]+" (regexp-quote heading)
13761 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13762 nil t)
13763 (setq org-goto-start-pos (match-beginning 0))
13764 (when fastp
13765 (goto-char (point-max))
13766 (unless (bolp) (newline))
13767 (insert "* " heading "\n")
13768 (setq org-goto-start-pos (point-at-bol 0)))))
13770 ;; Ask the User for a location, using the appropriate interface
13771 (cond
13772 (fastp (setq spos org-goto-start-pos
13773 exitcmd 'return))
13774 ((eq org-remember-interactive-interface 'outline)
13775 (setq spos (org-get-location (current-buffer)
13776 org-remember-help)
13777 exitcmd (cdr spos)
13778 spos (car spos)))
13779 ((eq org-remember-interactive-interface 'outline-path-completion)
13780 (let ((org-refile-targets '((nil . (:maxlevel . 10))))
13781 (org-refile-use-outline-path t))
13782 (setq spos (org-refile-get-location "Heading: ")
13783 exitcmd 'return
13784 spos (nth 3 spos))))
13785 (t (error "this should not hapen")))
13786 (if (not spos) (throw 'quit nil)) ; return nil to show we did
13787 ; not handle this note
13788 (goto-char spos)
13789 (cond ((org-on-heading-p t)
13790 (org-back-to-heading t)
13791 (setq level (funcall outline-level))
13792 (cond
13793 ((eq exitcmd 'return)
13794 ;; sublevel of current
13795 (setq org-remember-previous-location
13796 (cons (abbreviate-file-name file)
13797 (org-get-heading 'notags)))
13798 (if reversed
13799 (outline-next-heading)
13800 (org-end-of-subtree t)
13801 (if (not (bolp))
13802 (if (looking-at "[ \t]*\n")
13803 (beginning-of-line 2)
13804 (end-of-line 1)
13805 (insert "\n"))))
13806 (bookmark-set "org-remember-last-stored")
13807 (org-paste-subtree (org-get-legal-level level 1) txt))
13808 ((eq exitcmd 'left)
13809 ;; before current
13810 (bookmark-set "org-remember-last-stored")
13811 (org-paste-subtree level txt))
13812 ((eq exitcmd 'right)
13813 ;; after current
13814 (org-end-of-subtree t)
13815 (bookmark-set "org-remember-last-stored")
13816 (org-paste-subtree level txt))
13817 (t (error "This should not happen"))))
13819 ((and (bobp) (not reversed))
13820 ;; Put it at the end, one level below level 1
13821 (save-restriction
13822 (widen)
13823 (goto-char (point-max))
13824 (if (not (bolp)) (newline))
13825 (bookmark-set "org-remember-last-stored")
13826 (org-paste-subtree (org-get-legal-level 1 1) txt)))
13828 ((and (bobp) reversed)
13829 ;; Put it at the start, as level 1
13830 (save-restriction
13831 (widen)
13832 (goto-char (point-min))
13833 (re-search-forward "^\\*+ " nil t)
13834 (beginning-of-line 1)
13835 (bookmark-set "org-remember-last-stored")
13836 (org-paste-subtree 1 txt)))
13838 ;; Put it right there, with automatic level determined by
13839 ;; org-paste-subtree or from prefix arg
13840 (bookmark-set "org-remember-last-stored")
13841 (org-paste-subtree
13842 (if (numberp current-prefix-arg) current-prefix-arg)
13843 txt)))
13844 (when remember-save-after-remembering
13845 (save-buffer)
13846 (if (not visiting) (kill-buffer (current-buffer)))))))))
13848 t) ;; return t to indicate that we took care of this note.
13850 (defun org-get-org-file ()
13851 "Read a filename, with default directory `org-directory'."
13852 (let ((default (or org-default-notes-file remember-data-file)))
13853 (read-file-name (format "File name [%s]: " default)
13854 (file-name-as-directory org-directory)
13855 default)))
13857 (defun org-notes-order-reversed-p ()
13858 "Check if the current file should receive notes in reversed order."
13859 (cond
13860 ((not org-reverse-note-order) nil)
13861 ((eq t org-reverse-note-order) t)
13862 ((not (listp org-reverse-note-order)) nil)
13863 (t (catch 'exit
13864 (let ((all org-reverse-note-order)
13865 entry)
13866 (while (setq entry (pop all))
13867 (if (string-match (car entry) buffer-file-name)
13868 (throw 'exit (cdr entry))))
13869 nil)))))
13871 ;;; Refiling
13873 (defvar org-refile-target-table nil
13874 "The list of refile targets, created by `org-refile'.")
13876 (defvar org-agenda-new-buffers nil
13877 "Buffers created to visit agenda files.")
13879 (defun org-get-refile-targets (&optional default-buffer)
13880 "Produce a table with refile targets."
13881 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
13882 targets txt re files f desc descre)
13883 (with-current-buffer (or default-buffer (current-buffer))
13884 (while (setq entry (pop entries))
13885 (setq files (car entry) desc (cdr entry))
13886 (cond
13887 ((null files) (setq files (list (current-buffer))))
13888 ((eq files 'org-agenda-files)
13889 (setq files (org-agenda-files 'unrestricted)))
13890 ((and (symbolp files) (fboundp files))
13891 (setq files (funcall files)))
13892 ((and (symbolp files) (boundp files))
13893 (setq files (symbol-value files))))
13894 (if (stringp files) (setq files (list files)))
13895 (cond
13896 ((eq (car desc) :tag)
13897 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
13898 ((eq (car desc) :todo)
13899 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
13900 ((eq (car desc) :regexp)
13901 (setq descre (cdr desc)))
13902 ((eq (car desc) :level)
13903 (setq descre (concat "^\\*\\{" (number-to-string
13904 (if org-odd-levels-only
13905 (1- (* 2 (cdr desc)))
13906 (cdr desc)))
13907 "\\}[ \t]")))
13908 ((eq (car desc) :maxlevel)
13909 (setq descre (concat "^\\*\\{1," (number-to-string
13910 (if org-odd-levels-only
13911 (1- (* 2 (cdr desc)))
13912 (cdr desc)))
13913 "\\}[ \t]")))
13914 (t (error "Bad refiling target description %s" desc)))
13915 (while (setq f (pop files))
13916 (save-excursion
13917 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
13918 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
13919 (save-excursion
13920 (save-restriction
13921 (widen)
13922 (goto-char (point-min))
13923 (while (re-search-forward descre nil t)
13924 (goto-char (point-at-bol))
13925 (when (looking-at org-complex-heading-regexp)
13926 (setq txt (match-string 4)
13927 re (concat "^" (regexp-quote
13928 (buffer-substring (match-beginning 1)
13929 (match-end 4)))))
13930 (if (match-end 5) (setq re (concat re "[ \t]+"
13931 (regexp-quote
13932 (match-string 5)))))
13933 (setq re (concat re "[ \t]*$"))
13934 (when org-refile-use-outline-path
13935 (setq txt (mapconcat 'identity
13936 (append
13937 (if (eq org-refile-use-outline-path 'file)
13938 (list (file-name-nondirectory
13939 (buffer-file-name (buffer-base-buffer))))
13940 (if (eq org-refile-use-outline-path 'full-file-path)
13941 (list (buffer-file-name (buffer-base-buffer)))))
13942 (org-get-outline-path)
13943 (list txt))
13944 "/")))
13945 (push (list txt f re (point)) targets))
13946 (goto-char (point-at-eol))))))))
13947 (nreverse targets))))
13949 (defun org-get-outline-path ()
13950 "Return the outline path to the current entry, as a list."
13951 (let (rtn)
13952 (save-excursion
13953 (while (org-up-heading-safe)
13954 (when (looking-at org-complex-heading-regexp)
13955 (push (org-match-string-no-properties 4) rtn)))
13956 rtn)))
13958 (defvar org-refile-history nil
13959 "History for refiling operations.")
13961 (defun org-refile (&optional goto default-buffer)
13962 "Move the entry at point to another heading.
13963 The list of target headings is compiled using the information in
13964 `org-refile-targets', which see. This list is created upon first use, and
13965 you can update it by calling this command with a double prefix (`C-u C-u').
13966 FIXME: Can we find a better way of updating?
13968 At the target location, the entry is filed as a subitem of the target heading.
13969 Depending on `org-reverse-note-order', the new subitem will either be the
13970 first of the last subitem.
13972 With prefix are GOTO, the command will only visit the target location,
13973 not actually move anything.
13974 With a double prefix `C-c C-c', go to the location where the last refiling
13975 operation has put the subtree.
13977 With a double prefix argument, the command can be used to jump to any
13978 heading in the current buffer."
13979 (interactive "P")
13980 (let* ((cbuf (current-buffer))
13981 (filename (buffer-file-name (buffer-base-buffer cbuf)))
13982 (fname (and filename (file-truename filename)))
13983 pos it nbuf file re level reversed)
13984 (if (equal goto '(16))
13985 (org-refile-goto-last-stored)
13986 (when (setq it (org-refile-get-location
13987 (if goto "Goto: " "Refile to: ") default-buffer))
13988 (setq file (nth 1 it)
13989 re (nth 2 it)
13990 pos (nth 3 it))
13991 (setq nbuf (or (find-buffer-visiting file)
13992 (find-file-noselect file)))
13993 (if goto
13994 (progn
13995 (switch-to-buffer nbuf)
13996 (goto-char pos)
13997 (org-show-context 'org-goto))
13998 (org-copy-special)
13999 (save-excursion
14000 (set-buffer (setq nbuf (or (find-buffer-visiting file)
14001 (find-file-noselect file))))
14002 (setq reversed (org-notes-order-reversed-p))
14003 (save-excursion
14004 (save-restriction
14005 (widen)
14006 (goto-char pos)
14007 (looking-at outline-regexp)
14008 (setq level (org-get-legal-level (funcall outline-level) 1))
14009 (goto-char (or (save-excursion
14010 (if reversed
14011 (outline-next-heading)
14012 (outline-get-next-sibling)))
14013 (point-max)))
14014 (bookmark-set "org-refile-last-stored")
14015 (org-paste-subtree level))))
14016 (org-cut-special)
14017 (message "Entry refiled to \"%s\"" (car it)))))))
14019 (defun org-refile-goto-last-stored ()
14020 "Go to the location where the last refile was stored."
14021 (interactive)
14022 (bookmark-jump "org-refile-last-stored")
14023 (message "This is the location of the last refile"))
14025 (defun org-refile-get-location (&optional prompt default-buffer)
14026 "Prompt the user for a refile location, using PROMPT."
14027 (let ((org-refile-targets org-refile-targets)
14028 (org-refile-use-outline-path org-refile-use-outline-path))
14029 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
14030 (unless org-refile-target-table
14031 (error "No refile targets"))
14032 (let* ((cbuf (current-buffer))
14033 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14034 (fname (and filename (file-truename filename)))
14035 (tbl (mapcar
14036 (lambda (x)
14037 (if (not (equal fname (file-truename (nth 1 x))))
14038 (cons (concat (car x) " (" (file-name-nondirectory
14039 (nth 1 x)) ")")
14040 (cdr x))
14042 org-refile-target-table))
14043 (completion-ignore-case t)
14044 pos it nbuf file re level reversed)
14045 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
14046 tbl)))
14048 ;;;; Dynamic blocks
14050 (defun org-find-dblock (name)
14051 "Find the first dynamic block with name NAME in the buffer.
14052 If not found, stay at current position and return nil."
14053 (let (pos)
14054 (save-excursion
14055 (goto-char (point-min))
14056 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
14057 nil t)
14058 (match-beginning 0))))
14059 (if pos (goto-char pos))
14060 pos))
14062 (defconst org-dblock-start-re
14063 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
14064 "Matches the startline of a dynamic block, with parameters.")
14066 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
14067 "Matches the end of a dyhamic block.")
14069 (defun org-create-dblock (plist)
14070 "Create a dynamic block section, with parameters taken from PLIST.
14071 PLIST must containe a :name entry which is used as name of the block."
14072 (unless (bolp) (newline))
14073 (let ((name (plist-get plist :name)))
14074 (insert "#+BEGIN: " name)
14075 (while plist
14076 (if (eq (car plist) :name)
14077 (setq plist (cddr plist))
14078 (insert " " (prin1-to-string (pop plist)))))
14079 (insert "\n\n#+END:\n")
14080 (beginning-of-line -2)))
14082 (defun org-prepare-dblock ()
14083 "Prepare dynamic block for refresh.
14084 This empties the block, puts the cursor at the insert position and returns
14085 the property list including an extra property :name with the block name."
14086 (unless (looking-at org-dblock-start-re)
14087 (error "Not at a dynamic block"))
14088 (let* ((begdel (1+ (match-end 0)))
14089 (name (org-no-properties (match-string 1)))
14090 (params (append (list :name name)
14091 (read (concat "(" (match-string 3) ")")))))
14092 (unless (re-search-forward org-dblock-end-re nil t)
14093 (error "Dynamic block not terminated"))
14094 (delete-region begdel (match-beginning 0))
14095 (goto-char begdel)
14096 (open-line 1)
14097 params))
14099 (defun org-map-dblocks (&optional command)
14100 "Apply COMMAND to all dynamic blocks in the current buffer.
14101 If COMMAND is not given, use `org-update-dblock'."
14102 (let ((cmd (or command 'org-update-dblock))
14103 pos)
14104 (save-excursion
14105 (goto-char (point-min))
14106 (while (re-search-forward org-dblock-start-re nil t)
14107 (goto-char (setq pos (match-beginning 0)))
14108 (condition-case nil
14109 (funcall cmd)
14110 (error (message "Error during update of dynamic block")))
14111 (goto-char pos)
14112 (unless (re-search-forward org-dblock-end-re nil t)
14113 (error "Dynamic block not terminated"))))))
14115 (defun org-dblock-update (&optional arg)
14116 "User command for updating dynamic blocks.
14117 Update the dynamic block at point. With prefix ARG, update all dynamic
14118 blocks in the buffer."
14119 (interactive "P")
14120 (if arg
14121 (org-update-all-dblocks)
14122 (or (looking-at org-dblock-start-re)
14123 (org-beginning-of-dblock))
14124 (org-update-dblock)))
14126 (defun org-update-dblock ()
14127 "Update the dynamic block at point
14128 This means to empty the block, parse for parameters and then call
14129 the correct writing function."
14130 (save-window-excursion
14131 (let* ((pos (point))
14132 (line (org-current-line))
14133 (params (org-prepare-dblock))
14134 (name (plist-get params :name))
14135 (cmd (intern (concat "org-dblock-write:" name))))
14136 (message "Updating dynamic block `%s' at line %d..." name line)
14137 (funcall cmd params)
14138 (message "Updating dynamic block `%s' at line %d...done" name line)
14139 (goto-char pos))))
14141 (defun org-beginning-of-dblock ()
14142 "Find the beginning of the dynamic block at point.
14143 Error if there is no scuh block at point."
14144 (let ((pos (point))
14145 beg)
14146 (end-of-line 1)
14147 (if (and (re-search-backward org-dblock-start-re nil t)
14148 (setq beg (match-beginning 0))
14149 (re-search-forward org-dblock-end-re nil t)
14150 (> (match-end 0) pos))
14151 (goto-char beg)
14152 (goto-char pos)
14153 (error "Not in a dynamic block"))))
14155 (defun org-update-all-dblocks ()
14156 "Update all dynamic blocks in the buffer.
14157 This function can be used in a hook."
14158 (when (org-mode-p)
14159 (org-map-dblocks 'org-update-dblock)))
14162 ;;;; Completion
14164 (defconst org-additional-option-like-keywords
14165 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14166 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
14167 "BEGIN_EXAMPLE" "END_EXAMPLE"))
14169 (defun org-complete (&optional arg)
14170 "Perform completion on word at point.
14171 At the beginning of a headline, this completes TODO keywords as given in
14172 `org-todo-keywords'.
14173 If the current word is preceded by a backslash, completes the TeX symbols
14174 that are supported for HTML support.
14175 If the current word is preceded by \"#+\", completes special words for
14176 setting file options.
14177 In the line after \"#+STARTUP:, complete valid keywords.\"
14178 At all other locations, this simply calls the value of
14179 `org-completion-fallback-command'."
14180 (interactive "P")
14181 (org-without-partial-completion
14182 (catch 'exit
14183 (let* ((end (point))
14184 (beg1 (save-excursion
14185 (skip-chars-backward (org-re "[:alnum:]_@"))
14186 (point)))
14187 (beg (save-excursion
14188 (skip-chars-backward "a-zA-Z0-9_:$")
14189 (point)))
14190 (confirm (lambda (x) (stringp (car x))))
14191 (searchhead (equal (char-before beg) ?*))
14192 (tag (and (equal (char-before beg1) ?:)
14193 (equal (char-after (point-at-bol)) ?*)))
14194 (prop (and (equal (char-before beg1) ?:)
14195 (not (equal (char-after (point-at-bol)) ?*))))
14196 (texp (equal (char-before beg) ?\\))
14197 (link (equal (char-before beg) ?\[))
14198 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14199 beg)
14200 "#+"))
14201 (startup (string-match "^#\\+STARTUP:.*"
14202 (buffer-substring (point-at-bol) (point))))
14203 (completion-ignore-case opt)
14204 (type nil)
14205 (tbl nil)
14206 (table (cond
14207 (opt
14208 (setq type :opt)
14209 (append
14210 (mapcar
14211 (lambda (x)
14212 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14213 (cons (match-string 2 x) (match-string 1 x)))
14214 (org-split-string (org-get-current-options) "\n"))
14215 (mapcar 'list org-additional-option-like-keywords)))
14216 (startup
14217 (setq type :startup)
14218 org-startup-options)
14219 (link (append org-link-abbrev-alist-local
14220 org-link-abbrev-alist))
14221 (texp
14222 (setq type :tex)
14223 org-html-entities)
14224 ((string-match "\\`\\*+[ \t]+\\'"
14225 (buffer-substring (point-at-bol) beg))
14226 (setq type :todo)
14227 (mapcar 'list org-todo-keywords-1))
14228 (searchhead
14229 (setq type :searchhead)
14230 (save-excursion
14231 (goto-char (point-min))
14232 (while (re-search-forward org-todo-line-regexp nil t)
14233 (push (list
14234 (org-make-org-heading-search-string
14235 (match-string 3) t))
14236 tbl)))
14237 tbl)
14238 (tag (setq type :tag beg beg1)
14239 (or org-tag-alist (org-get-buffer-tags)))
14240 (prop (setq type :prop beg beg1)
14241 (mapcar 'list (org-buffer-property-keys)))
14242 (t (progn
14243 (call-interactively org-completion-fallback-command)
14244 (throw 'exit nil)))))
14245 (pattern (buffer-substring-no-properties beg end))
14246 (completion (try-completion pattern table confirm)))
14247 (cond ((eq completion t)
14248 (if (not (assoc (upcase pattern) table))
14249 (message "Already complete")
14250 (if (equal type :opt)
14251 (insert (substring (cdr (assoc (upcase pattern) table))
14252 (length pattern)))
14253 (if (memq type '(:tag :prop)) (insert ":")))))
14254 ((null completion)
14255 (message "Can't find completion for \"%s\"" pattern)
14256 (ding))
14257 ((not (string= pattern completion))
14258 (delete-region beg end)
14259 (if (string-match " +$" completion)
14260 (setq completion (replace-match "" t t completion)))
14261 (insert completion)
14262 (if (get-buffer-window "*Completions*")
14263 (delete-window (get-buffer-window "*Completions*")))
14264 (if (assoc completion table)
14265 (if (eq type :todo) (insert " ")
14266 (if (memq type '(:tag :prop)) (insert ":"))))
14267 (if (and (equal type :opt) (assoc completion table))
14268 (message "%s" (substitute-command-keys
14269 "Press \\[org-complete] again to insert example settings"))))
14271 (message "Making completion list...")
14272 (let ((list (sort (all-completions pattern table confirm)
14273 'string<)))
14274 (with-output-to-temp-buffer "*Completions*"
14275 (condition-case nil
14276 ;; Protection needed for XEmacs and emacs 21
14277 (display-completion-list list pattern)
14278 (error (display-completion-list list)))))
14279 (message "Making completion list...%s" "done")))))))
14281 ;;;; TODO, DEADLINE, Comments
14283 (defun org-toggle-comment ()
14284 "Change the COMMENT state of an entry."
14285 (interactive)
14286 (save-excursion
14287 (org-back-to-heading)
14288 (let (case-fold-search)
14289 (if (looking-at (concat outline-regexp
14290 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14291 (replace-match "" t t nil 1)
14292 (if (looking-at outline-regexp)
14293 (progn
14294 (goto-char (match-end 0))
14295 (insert org-comment-string " ")))))))
14297 (defvar org-last-todo-state-is-todo nil
14298 "This is non-nil when the last TODO state change led to a TODO state.
14299 If the last change removed the TODO tag or switched to DONE, then
14300 this is nil.")
14302 (defvar org-setting-tags nil) ; dynamically skiped
14304 ;; FIXME: better place
14305 (defun org-property-or-variable-value (var &optional inherit)
14306 "Check if there is a property fixing the value of VAR.
14307 If yes, return this value. If not, return the current value of the variable."
14308 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14309 (if (and prop (stringp prop) (string-match "\\S-" prop))
14310 (read prop)
14311 (symbol-value var))))
14313 (defun org-parse-local-options (string var)
14314 "Parse STRING for startup setting relevant for variable VAR."
14315 (let ((rtn (symbol-value var))
14316 e opts)
14317 (save-match-data
14318 (if (or (not string) (not (string-match "\\S-" string)))
14320 (setq opts (delq nil (mapcar (lambda (x)
14321 (setq e (assoc x org-startup-options))
14322 (if (eq (nth 1 e) var) e nil))
14323 (org-split-string string "[ \t]+"))))
14324 (if (not opts)
14326 (setq rtn nil)
14327 (while (setq e (pop opts))
14328 (if (not (nth 3 e))
14329 (setq rtn (nth 2 e))
14330 (if (not (listp rtn)) (setq rtn nil))
14331 (push (nth 2 e) rtn)))
14332 rtn)))))
14334 (defvar org-blocker-hook nil
14335 "Hook for functions that are allowed to block a state change.
14337 Each function gets as its single argument a property list, see
14338 `org-trigger-hook' for more information about this list.
14340 If any of the functions in this hook returns nil, the state change
14341 is blocked.")
14343 (defvar org-trigger-hook nil
14344 "Hook for functions that are triggered by a state change.
14346 Each function gets as its single argument a property list with at least
14347 the following elements:
14349 (:type type-of-change :position pos-at-entry-start
14350 :from old-state :to new-state)
14352 Depending on the type, more properties may be present.
14354 This mechanism is currently implemented for:
14356 TODO state changes
14357 ------------------
14358 :type todo-state-change
14359 :from previous state (keyword as a string), or nil
14360 :to new state (keyword as a string), or nil")
14363 (defun org-todo (&optional arg)
14364 "Change the TODO state of an item.
14365 The state of an item is given by a keyword at the start of the heading,
14366 like
14367 *** TODO Write paper
14368 *** DONE Call mom
14370 The different keywords are specified in the variable `org-todo-keywords'.
14371 By default the available states are \"TODO\" and \"DONE\".
14372 So for this example: when the item starts with TODO, it is changed to DONE.
14373 When it starts with DONE, the DONE is removed. And when neither TODO nor
14374 DONE are present, add TODO at the beginning of the heading.
14376 With C-u prefix arg, use completion to determine the new state.
14377 With numeric prefix arg, switch to that state.
14379 For calling through lisp, arg is also interpreted in the following way:
14380 'none -> empty state
14381 \"\"(empty string) -> switch to empty state
14382 'done -> switch to DONE
14383 'nextset -> switch to the next set of keywords
14384 'previousset -> switch to the previous set of keywords
14385 \"WAITING\" -> switch to the specified keyword, but only if it
14386 really is a member of `org-todo-keywords'."
14387 (interactive "P")
14388 (save-excursion
14389 (catch 'exit
14390 (org-back-to-heading)
14391 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14392 (or (looking-at (concat " +" org-todo-regexp " *"))
14393 (looking-at " *"))
14394 (let* ((match-data (match-data))
14395 (startpos (point-at-bol))
14396 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14397 (org-log-done (org-parse-local-options logging 'org-log-done))
14398 (org-log-repeat (org-parse-local-options logging 'org-log-repeat))
14399 (this (match-string 1))
14400 (hl-pos (match-beginning 0))
14401 (head (org-get-todo-sequence-head this))
14402 (ass (assoc head org-todo-kwd-alist))
14403 (interpret (nth 1 ass))
14404 (done-word (nth 3 ass))
14405 (final-done-word (nth 4 ass))
14406 (last-state (or this ""))
14407 (completion-ignore-case t)
14408 (member (member this org-todo-keywords-1))
14409 (tail (cdr member))
14410 (state (cond
14411 ((and org-todo-key-trigger
14412 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14413 (and (not arg) org-use-fast-todo-selection
14414 (not (eq org-use-fast-todo-selection 'prefix)))))
14415 ;; Use fast selection
14416 (org-fast-todo-selection))
14417 ((and (equal arg '(4))
14418 (or (not org-use-fast-todo-selection)
14419 (not org-todo-key-trigger)))
14420 ;; Read a state with completion
14421 (completing-read "State: " (mapcar (lambda(x) (list x))
14422 org-todo-keywords-1)
14423 nil t))
14424 ((eq arg 'right)
14425 (if this
14426 (if tail (car tail) nil)
14427 (car org-todo-keywords-1)))
14428 ((eq arg 'left)
14429 (if (equal member org-todo-keywords-1)
14431 (if this
14432 (nth (- (length org-todo-keywords-1) (length tail) 2)
14433 org-todo-keywords-1)
14434 (org-last org-todo-keywords-1))))
14435 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14436 (setq arg nil))) ; hack to fall back to cycling
14437 (arg
14438 ;; user or caller requests a specific state
14439 (cond
14440 ((equal arg "") nil)
14441 ((eq arg 'none) nil)
14442 ((eq arg 'done) (or done-word (car org-done-keywords)))
14443 ((eq arg 'nextset)
14444 (or (car (cdr (member head org-todo-heads)))
14445 (car org-todo-heads)))
14446 ((eq arg 'previousset)
14447 (let ((org-todo-heads (reverse org-todo-heads)))
14448 (or (car (cdr (member head org-todo-heads)))
14449 (car org-todo-heads))))
14450 ((car (member arg org-todo-keywords-1)))
14451 ((nth (1- (prefix-numeric-value arg))
14452 org-todo-keywords-1))))
14453 ((null member) (or head (car org-todo-keywords-1)))
14454 ((equal this final-done-word) nil) ;; -> make empty
14455 ((null tail) nil) ;; -> first entry
14456 ((eq interpret 'sequence)
14457 (car tail))
14458 ((memq interpret '(type priority))
14459 (if (eq this-command last-command)
14460 (car tail)
14461 (if (> (length tail) 0)
14462 (or done-word (car org-done-keywords))
14463 nil)))
14464 (t nil)))
14465 (next (if state (concat " " state " ") " "))
14466 (change-plist (list :type 'todo-state-change :from this :to state
14467 :position startpos))
14468 dostates)
14469 (when org-blocker-hook
14470 (unless (save-excursion
14471 (save-match-data
14472 (run-hook-with-args-until-failure
14473 'org-blocker-hook change-plist)))
14474 (if (interactive-p)
14475 (error "TODO state change from %s to %s blocked" this state)
14476 ;; fail silently
14477 (message "TODO state change from %s to %s blocked" this state)
14478 (throw 'exit nil))))
14479 (store-match-data match-data)
14480 (replace-match next t t)
14481 (unless (pos-visible-in-window-p hl-pos)
14482 (message "TODO state changed to %s" (org-trim next)))
14483 (unless head
14484 (setq head (org-get-todo-sequence-head state)
14485 ass (assoc head org-todo-kwd-alist)
14486 interpret (nth 1 ass)
14487 done-word (nth 3 ass)
14488 final-done-word (nth 4 ass)))
14489 (when (memq arg '(nextset previousset))
14490 (message "Keyword-Set %d/%d: %s"
14491 (- (length org-todo-sets) -1
14492 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14493 (length org-todo-sets)
14494 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14495 (setq org-last-todo-state-is-todo
14496 (not (member state org-done-keywords)))
14497 (when (and org-log-done (not (memq arg '(nextset previousset))))
14498 (setq dostates (and (listp org-log-done) (memq 'state org-log-done)
14499 (or (not org-todo-log-states)
14500 (member state org-todo-log-states))))
14502 (cond
14503 ((and state (member state org-not-done-keywords)
14504 (not (member this org-not-done-keywords)))
14505 ;; This is now a todo state and was not one before
14506 ;; Remove any CLOSED timestamp, and possibly log the state change
14507 (org-add-planning-info nil nil 'closed)
14508 (and dostates (org-add-log-maybe 'state state 'findpos)))
14509 ((and state dostates)
14510 ;; This is a non-nil state, and we need to log it
14511 (org-add-log-maybe 'state state 'findpos))
14512 ((and (member state org-done-keywords)
14513 (not (member this org-done-keywords)))
14514 ;; It is now done, and it was not done before
14515 (org-add-planning-info 'closed (org-current-time))
14516 (org-add-log-maybe 'done state 'findpos))))
14517 ;; Fixup tag positioning
14518 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14519 (run-hooks 'org-after-todo-state-change-hook)
14520 (and (member state org-done-keywords) (org-auto-repeat-maybe))
14521 (if (and arg (not (member state org-done-keywords)))
14522 (setq head (org-get-todo-sequence-head state)))
14523 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14524 ;; Fixup cursor location if close to the keyword
14525 (if (and (outline-on-heading-p)
14526 (not (bolp))
14527 (save-excursion (beginning-of-line 1)
14528 (looking-at org-todo-line-regexp))
14529 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14530 (progn
14531 (goto-char (or (match-end 2) (match-end 1)))
14532 (just-one-space)))
14533 (when org-trigger-hook
14534 (save-excursion
14535 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14537 (defun org-get-todo-sequence-head (kwd)
14538 "Return the head of the TODO sequence to which KWD belongs.
14539 If KWD is not set, check if there is a text property remembering the
14540 right sequence."
14541 (let (p)
14542 (cond
14543 ((not kwd)
14544 (or (get-text-property (point-at-bol) 'org-todo-head)
14545 (progn
14546 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14547 nil (point-at-eol)))
14548 (get-text-property p 'org-todo-head))))
14549 ((not (member kwd org-todo-keywords-1))
14550 (car org-todo-keywords-1))
14551 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14553 (defun org-fast-todo-selection ()
14554 "Fast TODO keyword selection with single keys.
14555 Returns the new TODO keyword, or nil if no state change should occur."
14556 (let* ((fulltable org-todo-key-alist)
14557 (done-keywords org-done-keywords) ;; needed for the faces.
14558 (maxlen (apply 'max (mapcar
14559 (lambda (x)
14560 (if (stringp (car x)) (string-width (car x)) 0))
14561 fulltable)))
14562 (expert nil)
14563 (fwidth (+ maxlen 3 1 3))
14564 (ncol (/ (- (window-width) 4) fwidth))
14565 tg cnt e c tbl
14566 groups ingroup)
14567 (save-window-excursion
14568 (if expert
14569 (set-buffer (get-buffer-create " *Org todo*"))
14570 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14571 (erase-buffer)
14572 (org-set-local 'org-done-keywords done-keywords)
14573 (setq tbl fulltable cnt 0)
14574 (while (setq e (pop tbl))
14575 (cond
14576 ((equal e '(:startgroup))
14577 (push '() groups) (setq ingroup t)
14578 (when (not (= cnt 0))
14579 (setq cnt 0)
14580 (insert "\n"))
14581 (insert "{ "))
14582 ((equal e '(:endgroup))
14583 (setq ingroup nil cnt 0)
14584 (insert "}\n"))
14586 (setq tg (car e) c (cdr e))
14587 (if ingroup (push tg (car groups)))
14588 (setq tg (org-add-props tg nil 'face
14589 (org-get-todo-face tg)))
14590 (if (and (= cnt 0) (not ingroup)) (insert " "))
14591 (insert "[" c "] " tg (make-string
14592 (- fwidth 4 (length tg)) ?\ ))
14593 (when (= (setq cnt (1+ cnt)) ncol)
14594 (insert "\n")
14595 (if ingroup (insert " "))
14596 (setq cnt 0)))))
14597 (insert "\n")
14598 (goto-char (point-min))
14599 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14600 (fit-window-to-buffer))
14601 (message "[a-z..]:Set [SPC]:clear")
14602 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14603 (cond
14604 ((or (= c ?\C-g)
14605 (and (= c ?q) (not (rassoc c fulltable))))
14606 (setq quit-flag t))
14607 ((= c ?\ ) nil)
14608 ((setq e (rassoc c fulltable) tg (car e))
14610 (t (setq quit-flag t))))))
14612 (defun org-get-repeat ()
14613 "Check if tere is a deadline/schedule with repeater in this entry."
14614 (save-match-data
14615 (save-excursion
14616 (org-back-to-heading t)
14617 (if (re-search-forward
14618 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
14619 (match-string 1)))))
14621 (defvar org-last-changed-timestamp)
14622 (defvar org-log-post-message)
14623 (defun org-auto-repeat-maybe ()
14624 "Check if the current headline contains a repeated deadline/schedule.
14625 If yes, set TODO state back to what it was and change the base date
14626 of repeating deadline/scheduled time stamps to new date.
14627 This function should be run in the `org-after-todo-state-change-hook'."
14628 ;; last-state is dynamically scoped into this function
14629 (let* ((repeat (org-get-repeat))
14630 (aa (assoc last-state org-todo-kwd-alist))
14631 (interpret (nth 1 aa))
14632 (head (nth 2 aa))
14633 (done-word (nth 3 aa))
14634 (whata '(("d" . day) ("m" . month) ("y" . year)))
14635 (msg "Entry repeats: ")
14636 (org-log-done)
14637 re type n what ts)
14638 (when repeat
14639 (org-todo (if (eq interpret 'type) last-state head))
14640 (when (and org-log-repeat
14641 (not (memq 'org-add-log-note
14642 (default-value 'post-command-hook))))
14643 ;; Make sure a note is taken
14644 (let ((org-log-done '(done)))
14645 (org-add-log-maybe 'done (or done-word (car org-done-keywords))
14646 'findpos)))
14647 (org-back-to-heading t)
14648 (org-add-planning-info nil nil 'closed)
14649 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
14650 org-deadline-time-regexp "\\)\\|\\("
14651 org-ts-regexp "\\)"))
14652 (while (re-search-forward
14653 re (save-excursion (outline-next-heading) (point)) t)
14654 (setq type (if (match-end 1) org-scheduled-string
14655 (if (match-end 3) org-deadline-string "Plain:"))
14656 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
14657 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
14658 (setq n (string-to-number (match-string 1 ts))
14659 what (match-string 2 ts))
14660 (if (equal what "w") (setq n (* n 7) what "d"))
14661 (org-timestamp-change n (cdr (assoc what whata)))
14662 (setq msg (concat msg type org-last-changed-timestamp " "))))
14663 (setq org-log-post-message msg)
14664 (message "%s" msg))))
14666 (defun org-show-todo-tree (arg)
14667 "Make a compact tree which shows all headlines marked with TODO.
14668 The tree will show the lines where the regexp matches, and all higher
14669 headlines above the match.
14670 With \\[universal-argument] prefix, also show the DONE entries.
14671 With a numeric prefix N, construct a sparse tree for the Nth element
14672 of `org-todo-keywords-1'."
14673 (interactive "P")
14674 (let ((case-fold-search nil)
14675 (kwd-re
14676 (cond ((null arg) org-not-done-regexp)
14677 ((equal arg '(4))
14678 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
14679 (mapcar 'list org-todo-keywords-1))))
14680 (concat "\\("
14681 (mapconcat 'identity (org-split-string kwd "|") "\\|")
14682 "\\)\\>")))
14683 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
14684 (regexp-quote (nth (1- (prefix-numeric-value arg))
14685 org-todo-keywords-1)))
14686 (t (error "Invalid prefix argument: %s" arg)))))
14687 (message "%d TODO entries found"
14688 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
14690 (defun org-deadline (&optional remove)
14691 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
14692 With argument REMOVE, remove any deadline from the item."
14693 (interactive "P")
14694 (if remove
14695 (progn
14696 (org-add-planning-info nil nil 'deadline)
14697 (message "Item no longer has a deadline."))
14698 (org-add-planning-info 'deadline nil 'closed)))
14700 (defun org-schedule (&optional remove)
14701 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
14702 With argument REMOVE, remove any scheduling date from the item."
14703 (interactive "P")
14704 (if remove
14705 (progn
14706 (org-add-planning-info nil nil 'scheduled)
14707 (message "Item is no longer scheduled."))
14708 (org-add-planning-info 'scheduled nil 'closed)))
14710 (defun org-add-planning-info (what &optional time &rest remove)
14711 "Insert new timestamp with keyword in the line directly after the headline.
14712 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
14713 If non is given, the user is prompted for a date.
14714 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
14715 be removed."
14716 (interactive)
14717 (let (org-time-was-given org-end-time-was-given)
14718 (when what (setq time (or time (org-read-date nil 'to-time))))
14719 (when (and org-insert-labeled-timestamps-at-point
14720 (member what '(scheduled deadline)))
14721 (insert
14722 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
14723 (org-insert-time-stamp time org-time-was-given
14724 nil nil nil (list org-end-time-was-given))
14725 (setq what nil))
14726 (save-excursion
14727 (save-restriction
14728 (let (col list elt ts buffer-invisibility-spec)
14729 (org-back-to-heading t)
14730 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
14731 (goto-char (match-end 1))
14732 (setq col (current-column))
14733 (goto-char (match-end 0))
14734 (if (eobp) (insert "\n") (forward-char 1))
14735 (if (and (not (looking-at outline-regexp))
14736 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
14737 "[^\r\n]*"))
14738 (not (equal (match-string 1) org-clock-string)))
14739 (narrow-to-region (match-beginning 0) (match-end 0))
14740 (insert-before-markers "\n")
14741 (backward-char 1)
14742 (narrow-to-region (point) (point))
14743 (indent-to-column col))
14744 ;; Check if we have to remove something.
14745 (setq list (cons what remove))
14746 (while list
14747 (setq elt (pop list))
14748 (goto-char (point-min))
14749 (when (or (and (eq elt 'scheduled)
14750 (re-search-forward org-scheduled-time-regexp nil t))
14751 (and (eq elt 'deadline)
14752 (re-search-forward org-deadline-time-regexp nil t))
14753 (and (eq elt 'closed)
14754 (re-search-forward org-closed-time-regexp nil t)))
14755 (replace-match "")
14756 (if (looking-at "--+<[^>]+>") (replace-match ""))
14757 (if (looking-at " +") (replace-match ""))))
14758 (goto-char (point-max))
14759 (when what
14760 (insert
14761 (if (not (equal (char-before) ?\ )) " " "")
14762 (cond ((eq what 'scheduled) org-scheduled-string)
14763 ((eq what 'deadline) org-deadline-string)
14764 ((eq what 'closed) org-closed-string))
14765 " ")
14766 (setq ts (org-insert-time-stamp
14767 time
14768 (or org-time-was-given
14769 (and (eq what 'closed) org-log-done-with-time))
14770 (eq what 'closed)
14771 nil nil (list org-end-time-was-given)))
14772 (end-of-line 1))
14773 (goto-char (point-min))
14774 (widen)
14775 (if (looking-at "[ \t]+\r?\n")
14776 (replace-match ""))
14777 ts)))))
14779 (defvar org-log-note-marker (make-marker))
14780 (defvar org-log-note-purpose nil)
14781 (defvar org-log-note-state nil)
14782 (defvar org-log-note-window-configuration nil)
14783 (defvar org-log-note-return-to (make-marker))
14784 (defvar org-log-post-message nil
14785 "Message to be displayed after a log note has been stored.
14786 The auto-repeater uses this.")
14788 (defun org-add-log-maybe (&optional purpose state findpos)
14789 "Set up the post command hook to take a note."
14790 (save-excursion
14791 (when (and (listp org-log-done)
14792 (memq purpose org-log-done))
14793 (when findpos
14794 (org-back-to-heading t)
14795 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
14796 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
14797 "[^\r\n]*\\)?"))
14798 (goto-char (match-end 0))
14799 (unless org-log-states-order-reversed
14800 (and (= (char-after) ?\n) (forward-char 1))
14801 (org-skip-over-state-notes)
14802 (skip-chars-backward " \t\n\r")))
14803 (move-marker org-log-note-marker (point))
14804 (setq org-log-note-purpose purpose)
14805 (setq org-log-note-state state)
14806 (add-hook 'post-command-hook 'org-add-log-note 'append))))
14808 (defun org-skip-over-state-notes ()
14809 "Skip past the list of State notes in an entry."
14810 (if (looking-at "\n[ \t]*- State") (forward-char 1))
14811 (while (looking-at "[ \t]*- State")
14812 (condition-case nil
14813 (org-next-item)
14814 (error (org-end-of-item)))))
14816 (defun org-add-log-note (&optional purpose)
14817 "Pop up a window for taking a note, and add this note later at point."
14818 (remove-hook 'post-command-hook 'org-add-log-note)
14819 (setq org-log-note-window-configuration (current-window-configuration))
14820 (delete-other-windows)
14821 (move-marker org-log-note-return-to (point))
14822 (switch-to-buffer (marker-buffer org-log-note-marker))
14823 (goto-char org-log-note-marker)
14824 (org-switch-to-buffer-other-window "*Org Note*")
14825 (erase-buffer)
14826 (let ((org-inhibit-startup t)) (org-mode))
14827 (insert (format "# Insert note for %s.
14828 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
14829 (cond
14830 ((eq org-log-note-purpose 'clock-out) "stopped clock")
14831 ((eq org-log-note-purpose 'done) "closed todo item")
14832 ((eq org-log-note-purpose 'state)
14833 (format "state change to \"%s\"" org-log-note-state))
14834 (t (error "This should not happen")))))
14835 (org-set-local 'org-finish-function 'org-store-log-note))
14837 (defun org-store-log-note ()
14838 "Finish taking a log note, and insert it to where it belongs."
14839 (let ((txt (buffer-string))
14840 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
14841 lines ind)
14842 (kill-buffer (current-buffer))
14843 (while (string-match "\\`#.*\n[ \t\n]*" txt)
14844 (setq txt (replace-match "" t t txt)))
14845 (if (string-match "\\s-+\\'" txt)
14846 (setq txt (replace-match "" t t txt)))
14847 (setq lines (org-split-string txt "\n"))
14848 (when (and note (string-match "\\S-" note))
14849 (setq note
14850 (org-replace-escapes
14851 note
14852 (list (cons "%u" (user-login-name))
14853 (cons "%U" user-full-name)
14854 (cons "%t" (format-time-string
14855 (org-time-stamp-format 'long 'inactive)
14856 (current-time)))
14857 (cons "%s" (if org-log-note-state
14858 (concat "\"" org-log-note-state "\"")
14859 "")))))
14860 (if lines (setq note (concat note " \\\\")))
14861 (push note lines))
14862 (when (or current-prefix-arg org-note-abort) (setq lines nil))
14863 (when lines
14864 (save-excursion
14865 (set-buffer (marker-buffer org-log-note-marker))
14866 (save-excursion
14867 (goto-char org-log-note-marker)
14868 (move-marker org-log-note-marker nil)
14869 (end-of-line 1)
14870 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
14871 (indent-relative nil)
14872 (insert "- " (pop lines))
14873 (org-indent-line-function)
14874 (beginning-of-line 1)
14875 (looking-at "[ \t]*")
14876 (setq ind (concat (match-string 0) " "))
14877 (end-of-line 1)
14878 (while lines (insert "\n" ind (pop lines)))))))
14879 (set-window-configuration org-log-note-window-configuration)
14880 (with-current-buffer (marker-buffer org-log-note-return-to)
14881 (goto-char org-log-note-return-to))
14882 (move-marker org-log-note-return-to nil)
14883 (and org-log-post-message (message "%s" org-log-post-message)))
14885 ;; FIXME: what else would be useful?
14886 ;; - priority
14887 ;; - date
14889 (defun org-sparse-tree (&optional arg)
14890 "Create a sparse tree, prompt for the details.
14891 This command can create sparse trees. You first need to select the type
14892 of match used to create the tree:
14894 t Show entries with a specific TODO keyword.
14895 T Show entries selected by a tags match.
14896 p Enter a property name and its value (both with completion on existing
14897 names/values) and show entries with that property.
14898 r Show entries matching a regular expression
14899 d Show deadlines due within `org-deadline-warning-days'."
14900 (interactive "P")
14901 (let (ans kwd value)
14902 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
14903 (setq ans (read-char-exclusive))
14904 (cond
14905 ((equal ans ?d)
14906 (call-interactively 'org-check-deadlines))
14907 ((equal ans ?b)
14908 (call-interactively 'org-check-before-date))
14909 ((equal ans ?t)
14910 (org-show-todo-tree '(4)))
14911 ((equal ans ?T)
14912 (call-interactively 'org-tags-sparse-tree))
14913 ((member ans '(?p ?P))
14914 (setq kwd (completing-read "Property: "
14915 (mapcar 'list (org-buffer-property-keys))))
14916 (setq value (completing-read "Value: "
14917 (mapcar 'list (org-property-values kwd))))
14918 (unless (string-match "\\`{.*}\\'" value)
14919 (setq value (concat "\"" value "\"")))
14920 (org-tags-sparse-tree arg (concat kwd "=" value)))
14921 ((member ans '(?r ?R ?/))
14922 (call-interactively 'org-occur))
14923 (t (error "No such sparse tree command \"%c\"" ans)))))
14925 (defvar org-occur-highlights nil)
14926 (make-variable-buffer-local 'org-occur-highlights)
14928 (defun org-occur (regexp &optional keep-previous callback)
14929 "Make a compact tree which shows all matches of REGEXP.
14930 The tree will show the lines where the regexp matches, and all higher
14931 headlines above the match. It will also show the heading after the match,
14932 to make sure editing the matching entry is easy.
14933 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
14934 call to `org-occur' will be kept, to allow stacking of calls to this
14935 command.
14936 If CALLBACK is non-nil, it is a function which is called to confirm
14937 that the match should indeed be shown."
14938 (interactive "sRegexp: \nP")
14939 (or keep-previous (org-remove-occur-highlights nil nil t))
14940 (let ((cnt 0))
14941 (save-excursion
14942 (goto-char (point-min))
14943 (if (or (not keep-previous) ; do not want to keep
14944 (not org-occur-highlights)) ; no previous matches
14945 ;; hide everything
14946 (org-overview))
14947 (while (re-search-forward regexp nil t)
14948 (when (or (not callback)
14949 (save-match-data (funcall callback)))
14950 (setq cnt (1+ cnt))
14951 (when org-highlight-sparse-tree-matches
14952 (org-highlight-new-match (match-beginning 0) (match-end 0)))
14953 (org-show-context 'occur-tree))))
14954 (when org-remove-highlights-with-change
14955 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
14956 nil 'local))
14957 (unless org-sparse-tree-open-archived-trees
14958 (org-hide-archived-subtrees (point-min) (point-max)))
14959 (run-hooks 'org-occur-hook)
14960 (if (interactive-p)
14961 (message "%d match(es) for regexp %s" cnt regexp))
14962 cnt))
14964 (defun org-show-context (&optional key)
14965 "Make sure point and context and visible.
14966 How much context is shown depends upon the variables
14967 `org-show-hierarchy-above', `org-show-following-heading'. and
14968 `org-show-siblings'."
14969 (let ((heading-p (org-on-heading-p t))
14970 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
14971 (following-p (org-get-alist-option org-show-following-heading key))
14972 (entry-p (org-get-alist-option org-show-entry-below key))
14973 (siblings-p (org-get-alist-option org-show-siblings key)))
14974 (catch 'exit
14975 ;; Show heading or entry text
14976 (if (and heading-p (not entry-p))
14977 (org-flag-heading nil) ; only show the heading
14978 (and (or entry-p (org-invisible-p) (org-invisible-p2))
14979 (org-show-hidden-entry))) ; show entire entry
14980 (when following-p
14981 ;; Show next sibling, or heading below text
14982 (save-excursion
14983 (and (if heading-p (org-goto-sibling) (outline-next-heading))
14984 (org-flag-heading nil))))
14985 (when siblings-p (org-show-siblings))
14986 (when hierarchy-p
14987 ;; show all higher headings, possibly with siblings
14988 (save-excursion
14989 (while (and (condition-case nil
14990 (progn (org-up-heading-all 1) t)
14991 (error nil))
14992 (not (bobp)))
14993 (org-flag-heading nil)
14994 (when siblings-p (org-show-siblings))))))))
14996 (defun org-reveal (&optional siblings)
14997 "Show current entry, hierarchy above it, and the following headline.
14998 This can be used to show a consistent set of context around locations
14999 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
15000 not t for the search context.
15002 With optional argument SIBLINGS, on each level of the hierarchy all
15003 siblings are shown. This repairs the tree structure to what it would
15004 look like when opened with hierarchical calls to `org-cycle'."
15005 (interactive "P")
15006 (let ((org-show-hierarchy-above t)
15007 (org-show-following-heading t)
15008 (org-show-siblings (if siblings t org-show-siblings)))
15009 (org-show-context nil)))
15011 (defun org-highlight-new-match (beg end)
15012 "Highlight from BEG to END and mark the highlight is an occur headline."
15013 (let ((ov (org-make-overlay beg end)))
15014 (org-overlay-put ov 'face 'secondary-selection)
15015 (push ov org-occur-highlights)))
15017 (defun org-remove-occur-highlights (&optional beg end noremove)
15018 "Remove the occur highlights from the buffer.
15019 BEG and END are ignored. If NOREMOVE is nil, remove this function
15020 from the `before-change-functions' in the current buffer."
15021 (interactive)
15022 (unless org-inhibit-highlight-removal
15023 (mapc 'org-delete-overlay org-occur-highlights)
15024 (setq org-occur-highlights nil)
15025 (unless noremove
15026 (remove-hook 'before-change-functions
15027 'org-remove-occur-highlights 'local))))
15029 ;;;; Priorities
15031 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
15032 "Regular expression matching the priority indicator.")
15034 (defvar org-remove-priority-next-time nil)
15036 (defun org-priority-up ()
15037 "Increase the priority of the current item."
15038 (interactive)
15039 (org-priority 'up))
15041 (defun org-priority-down ()
15042 "Decrease the priority of the current item."
15043 (interactive)
15044 (org-priority 'down))
15046 (defun org-priority (&optional action)
15047 "Change the priority of an item by ARG.
15048 ACTION can be `set', `up', `down', or a character."
15049 (interactive)
15050 (setq action (or action 'set))
15051 (let (current new news have remove)
15052 (save-excursion
15053 (org-back-to-heading)
15054 (if (looking-at org-priority-regexp)
15055 (setq current (string-to-char (match-string 2))
15056 have t)
15057 (setq current org-default-priority))
15058 (cond
15059 ((or (eq action 'set) (integerp action))
15060 (if (integerp action)
15061 (setq new action)
15062 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
15063 (setq new (read-char-exclusive)))
15064 (if (and (= (upcase org-highest-priority) org-highest-priority)
15065 (= (upcase org-lowest-priority) org-lowest-priority))
15066 (setq new (upcase new)))
15067 (cond ((equal new ?\ ) (setq remove t))
15068 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
15069 (error "Priority must be between `%c' and `%c'"
15070 org-highest-priority org-lowest-priority))))
15071 ((eq action 'up)
15072 (if (and (not have) (eq last-command this-command))
15073 (setq new org-lowest-priority)
15074 (setq new (if (and org-priority-start-cycle-with-default (not have))
15075 org-default-priority (1- current)))))
15076 ((eq action 'down)
15077 (if (and (not have) (eq last-command this-command))
15078 (setq new org-highest-priority)
15079 (setq new (if (and org-priority-start-cycle-with-default (not have))
15080 org-default-priority (1+ current)))))
15081 (t (error "Invalid action")))
15082 (if (or (< (upcase new) org-highest-priority)
15083 (> (upcase new) org-lowest-priority))
15084 (setq remove t))
15085 (setq news (format "%c" new))
15086 (if have
15087 (if remove
15088 (replace-match "" t t nil 1)
15089 (replace-match news t t nil 2))
15090 (if remove
15091 (error "No priority cookie found in line")
15092 (looking-at org-todo-line-regexp)
15093 (if (match-end 2)
15094 (progn
15095 (goto-char (match-end 2))
15096 (insert " [#" news "]"))
15097 (goto-char (match-beginning 3))
15098 (insert "[#" news "] ")))))
15099 (org-preserve-lc (org-set-tags nil 'align))
15100 (if remove
15101 (message "Priority removed")
15102 (message "Priority of current item set to %s" news))))
15105 (defun org-get-priority (s)
15106 "Find priority cookie and return priority."
15107 (save-match-data
15108 (if (not (string-match org-priority-regexp s))
15109 (* 1000 (- org-lowest-priority org-default-priority))
15110 (* 1000 (- org-lowest-priority
15111 (string-to-char (match-string 2 s)))))))
15113 ;;;; Tags
15115 (defun org-scan-tags (action matcher &optional todo-only)
15116 "Scan headline tags with inheritance and produce output ACTION.
15117 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
15118 evaluated, testing if a given set of tags qualifies a headline for
15119 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
15120 are included in the output."
15121 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
15122 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
15123 (org-re
15124 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
15125 (props (list 'face nil
15126 'done-face 'org-done
15127 'undone-face nil
15128 'mouse-face 'highlight
15129 'org-not-done-regexp org-not-done-regexp
15130 'org-todo-regexp org-todo-regexp
15131 'keymap org-agenda-keymap
15132 'help-echo
15133 (format "mouse-2 or RET jump to org file %s"
15134 (abbreviate-file-name
15135 (or (buffer-file-name (buffer-base-buffer))
15136 (buffer-name (buffer-base-buffer)))))))
15137 (case-fold-search nil)
15138 lspos
15139 tags tags-list tags-alist (llast 0) rtn level category i txt
15140 todo marker entry priority)
15141 (save-excursion
15142 (goto-char (point-min))
15143 (when (eq action 'sparse-tree)
15144 (org-overview)
15145 (org-remove-occur-highlights))
15146 (while (re-search-forward re nil t)
15147 (catch :skip
15148 (setq todo (if (match-end 1) (match-string 2))
15149 tags (if (match-end 4) (match-string 4)))
15150 (goto-char (setq lspos (1+ (match-beginning 0))))
15151 (setq level (org-reduced-level (funcall outline-level))
15152 category (org-get-category))
15153 (setq i llast llast level)
15154 ;; remove tag lists from same and sublevels
15155 (while (>= i level)
15156 (when (setq entry (assoc i tags-alist))
15157 (setq tags-alist (delete entry tags-alist)))
15158 (setq i (1- i)))
15159 ;; add the nex tags
15160 (when tags
15161 (setq tags (mapcar 'downcase (org-split-string tags ":"))
15162 tags-alist
15163 (cons (cons level tags) tags-alist)))
15164 ;; compile tags for current headline
15165 (setq tags-list
15166 (if org-use-tag-inheritance
15167 (apply 'append (mapcar 'cdr tags-alist))
15168 tags))
15169 (when (and (or (not todo-only) (member todo org-not-done-keywords))
15170 (eval matcher)
15171 (or (not org-agenda-skip-archived-trees)
15172 (not (member org-archive-tag tags-list))))
15173 (and (eq action 'agenda) (org-agenda-skip))
15174 ;; list this headline
15176 (if (eq action 'sparse-tree)
15177 (progn
15178 (and org-highlight-sparse-tree-matches
15179 (org-get-heading) (match-end 0)
15180 (org-highlight-new-match
15181 (match-beginning 0) (match-beginning 1)))
15182 (org-show-context 'tags-tree))
15183 (setq txt (org-format-agenda-item
15185 (concat
15186 (if org-tags-match-list-sublevels
15187 (make-string (1- level) ?.) "")
15188 (org-get-heading))
15189 category tags-list)
15190 priority (org-get-priority txt))
15191 (goto-char lspos)
15192 (setq marker (org-agenda-new-marker))
15193 (org-add-props txt props
15194 'org-marker marker 'org-hd-marker marker 'org-category category
15195 'priority priority 'type "tagsmatch")
15196 (push txt rtn))
15197 ;; if we are to skip sublevels, jump to end of subtree
15198 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15199 (when (and (eq action 'sparse-tree)
15200 (not org-sparse-tree-open-archived-trees))
15201 (org-hide-archived-subtrees (point-min) (point-max)))
15202 (nreverse rtn)))
15204 (defvar todo-only) ;; dynamically scoped
15206 (defun org-tags-sparse-tree (&optional todo-only match)
15207 "Create a sparse tree according to tags string MATCH.
15208 MATCH can contain positive and negative selection of tags, like
15209 \"+WORK+URGENT-WITHBOSS\".
15210 If optional argument TODO_ONLY is non-nil, only select lines that are
15211 also TODO lines."
15212 (interactive "P")
15213 (org-prepare-agenda-buffers (list (current-buffer)))
15214 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15216 (defvar org-cached-props nil)
15217 (defun org-cached-entry-get (pom property)
15218 (if (or (eq t org-use-property-inheritance)
15219 (member property org-use-property-inheritance))
15220 ;; Caching is not possible, check it directly
15221 (org-entry-get pom property 'inherit)
15222 ;; Get all properties, so that we can do complicated checks easily
15223 (cdr (assoc property (or org-cached-props
15224 (setq org-cached-props
15225 (org-entry-properties pom)))))))
15227 (defun org-global-tags-completion-table (&optional files)
15228 "Return the list of all tags in all agenda buffer/files."
15229 (save-excursion
15230 (org-uniquify
15231 (delq nil
15232 (apply 'append
15233 (mapcar
15234 (lambda (file)
15235 (set-buffer (find-file-noselect file))
15236 (append (org-get-buffer-tags)
15237 (mapcar (lambda (x) (if (stringp (car-safe x))
15238 (list (car-safe x)) nil))
15239 org-tag-alist)))
15240 (if (and files (car files))
15241 files
15242 (org-agenda-files))))))))
15244 (defun org-make-tags-matcher (match)
15245 "Create the TAGS//TODO matcher form for the selection string MATCH."
15246 ;; todo-only is scoped dynamically into this function, and the function
15247 ;; may change it it the matcher asksk for it.
15248 (unless match
15249 ;; Get a new match request, with completion
15250 (let ((org-last-tags-completion-table
15251 (org-global-tags-completion-table)))
15252 (setq match (completing-read
15253 "Match: " 'org-tags-completion-function nil nil nil
15254 'org-tags-history))))
15256 ;; Parse the string and create a lisp form
15257 (let ((match0 match)
15258 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]+\"\\)\\|[[:alnum:]_@]+\\)"))
15259 minus tag mm
15260 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15261 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15262 (if (string-match "/+" match)
15263 ;; match contains also a todo-matching request
15264 (progn
15265 (setq tagsmatch (substring match 0 (match-beginning 0))
15266 todomatch (substring match (match-end 0)))
15267 (if (string-match "^!" todomatch)
15268 (setq todo-only t todomatch (substring todomatch 1)))
15269 (if (string-match "^\\s-*$" todomatch)
15270 (setq todomatch nil)))
15271 ;; only matching tags
15272 (setq tagsmatch match todomatch nil))
15274 ;; Make the tags matcher
15275 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15276 (setq tagsmatcher t)
15277 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15278 (while (setq term (pop orterms))
15279 (while (and (equal (substring term -1) "\\") orterms)
15280 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15281 (while (string-match re term)
15282 (setq minus (and (match-end 1)
15283 (equal (match-string 1 term) "-"))
15284 tag (match-string 2 term)
15285 re-p (equal (string-to-char tag) ?{)
15286 level-p (match-end 3)
15287 prop-p (match-end 4)
15288 mm (cond
15289 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15290 (level-p `(= level ,(string-to-number
15291 (match-string 3 term))))
15292 (prop-p
15293 (setq pn (match-string 4 term)
15294 pv (match-string 5 term)
15295 cat-p (equal pn "CATEGORY")
15296 re-p (equal (string-to-char pv) ?{)
15297 pv (substring pv 1 -1))
15298 (if (equal pn "CATEGORY")
15299 (setq gv '(get-text-property (point) 'org-category))
15300 (setq gv `(org-cached-entry-get nil ,pn)))
15301 (if re-p
15302 `(string-match ,pv (or ,gv ""))
15303 `(equal ,pv ,gv)))
15304 (t `(member ,(downcase tag) tags-list)))
15305 mm (if minus (list 'not mm) mm)
15306 term (substring term (match-end 0)))
15307 (push mm tagsmatcher))
15308 (push (if (> (length tagsmatcher) 1)
15309 (cons 'and tagsmatcher)
15310 (car tagsmatcher))
15311 orlist)
15312 (setq tagsmatcher nil))
15313 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15314 (setq tagsmatcher
15315 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15317 ;; Make the todo matcher
15318 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15319 (setq todomatcher t)
15320 (setq orterms (org-split-string todomatch "|") orlist nil)
15321 (while (setq term (pop orterms))
15322 (while (string-match re term)
15323 (setq minus (and (match-end 1)
15324 (equal (match-string 1 term) "-"))
15325 kwd (match-string 2 term)
15326 re-p (equal (string-to-char kwd) ?{)
15327 term (substring term (match-end 0))
15328 mm (if re-p
15329 `(string-match ,(substring kwd 1 -1) todo)
15330 (list 'equal 'todo kwd))
15331 mm (if minus (list 'not mm) mm))
15332 (push mm todomatcher))
15333 (push (if (> (length todomatcher) 1)
15334 (cons 'and todomatcher)
15335 (car todomatcher))
15336 orlist)
15337 (setq todomatcher nil))
15338 (setq todomatcher (if (> (length orlist) 1)
15339 (cons 'or orlist) (car orlist))))
15341 ;; Return the string and lisp forms of the matcher
15342 (setq matcher (if todomatcher
15343 (list 'and tagsmatcher todomatcher)
15344 tagsmatcher))
15345 (cons match0 matcher)))
15347 (defun org-match-any-p (re list)
15348 "Does re match any element of list?"
15349 (setq list (mapcar (lambda (x) (string-match re x)) list))
15350 (delq nil list))
15352 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15353 (defvar org-tags-overlay (org-make-overlay 1 1))
15354 (org-detach-overlay org-tags-overlay)
15356 (defun org-align-tags-here (to-col)
15357 ;; Assumes that this is a headline
15358 (let ((pos (point)) (col (current-column)) tags)
15359 (beginning-of-line 1)
15360 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15361 (< pos (match-beginning 2)))
15362 (progn
15363 (setq tags (match-string 2))
15364 (goto-char (match-beginning 1))
15365 (insert " ")
15366 (delete-region (point) (1+ (match-end 0)))
15367 (backward-char 1)
15368 (move-to-column
15369 (max (1+ (current-column))
15370 (1+ col)
15371 (if (> to-col 0)
15372 to-col
15373 (- (abs to-col) (length tags))))
15375 (insert tags)
15376 (move-to-column (min (current-column) col) t))
15377 (goto-char pos))))
15379 (defun org-set-tags (&optional arg just-align)
15380 "Set the tags for the current headline.
15381 With prefix ARG, realign all tags in headings in the current buffer."
15382 (interactive "P")
15383 (let* ((re (concat "^" outline-regexp))
15384 (current (org-get-tags-string))
15385 (col (current-column))
15386 (org-setting-tags t)
15387 table current-tags inherited-tags ; computed below when needed
15388 tags p0 c0 c1 rpl)
15389 (if arg
15390 (save-excursion
15391 (goto-char (point-min))
15392 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15393 (while (re-search-forward re nil t)
15394 (org-set-tags nil t)
15395 (end-of-line 1)))
15396 (message "All tags realigned to column %d" org-tags-column))
15397 (if just-align
15398 (setq tags current)
15399 ;; Get a new set of tags from the user
15400 (save-excursion
15401 (setq table (or org-tag-alist (org-get-buffer-tags))
15402 org-last-tags-completion-table table
15403 current-tags (org-split-string current ":")
15404 inherited-tags (nreverse
15405 (nthcdr (length current-tags)
15406 (nreverse (org-get-tags-at))))
15407 tags
15408 (if (or (eq t org-use-fast-tag-selection)
15409 (and org-use-fast-tag-selection
15410 (delq nil (mapcar 'cdr table))))
15411 (org-fast-tag-selection
15412 current-tags inherited-tags table
15413 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15414 (let ((org-add-colon-after-tag-completion t))
15415 (org-trim
15416 (org-without-partial-completion
15417 (completing-read "Tags: " 'org-tags-completion-function
15418 nil nil current 'org-tags-history)))))))
15419 (while (string-match "[-+&]+" tags)
15420 ;; No boolean logic, just a list
15421 (setq tags (replace-match ":" t t tags))))
15423 (if (string-match "\\`[\t ]*\\'" tags)
15424 (setq tags "")
15425 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15426 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15428 ;; Insert new tags at the correct column
15429 (beginning-of-line 1)
15430 (cond
15431 ((and (equal current "") (equal tags "")))
15432 ((re-search-forward
15433 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15434 (point-at-eol) t)
15435 (if (equal tags "")
15436 (setq rpl "")
15437 (goto-char (match-beginning 0))
15438 (setq c0 (current-column) p0 (point)
15439 c1 (max (1+ c0) (if (> org-tags-column 0)
15440 org-tags-column
15441 (- (- org-tags-column) (length tags))))
15442 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15443 (replace-match rpl t t)
15444 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
15445 tags)
15446 (t (error "Tags alignment failed")))
15447 (move-to-column col)
15448 (unless just-align
15449 (run-hooks 'org-after-tags-change-hook)))))
15451 (defun org-change-tag-in-region (beg end tag off)
15452 "Add or remove TAG for each entry in the region.
15453 This works in the agenda, and also in an org-mode buffer."
15454 (interactive
15455 (list (region-beginning) (region-end)
15456 (let ((org-last-tags-completion-table
15457 (if (org-mode-p)
15458 (org-get-buffer-tags)
15459 (org-global-tags-completion-table))))
15460 (completing-read
15461 "Tag: " 'org-tags-completion-function nil nil nil
15462 'org-tags-history))
15463 (progn
15464 (message "[s]et or [r]emove? ")
15465 (equal (read-char-exclusive) ?r))))
15466 (if (fboundp 'deactivate-mark) (deactivate-mark))
15467 (let ((agendap (equal major-mode 'org-agenda-mode))
15468 l1 l2 m buf pos newhead (cnt 0))
15469 (goto-char end)
15470 (setq l2 (1- (org-current-line)))
15471 (goto-char beg)
15472 (setq l1 (org-current-line))
15473 (loop for l from l1 to l2 do
15474 (goto-line l)
15475 (setq m (get-text-property (point) 'org-hd-marker))
15476 (when (or (and (org-mode-p) (org-on-heading-p))
15477 (and agendap m))
15478 (setq buf (if agendap (marker-buffer m) (current-buffer))
15479 pos (if agendap m (point)))
15480 (with-current-buffer buf
15481 (save-excursion
15482 (save-restriction
15483 (goto-char pos)
15484 (setq cnt (1+ cnt))
15485 (org-toggle-tag tag (if off 'off 'on))
15486 (setq newhead (org-get-heading)))))
15487 (and agendap (org-agenda-change-all-lines newhead m))))
15488 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15490 (defun org-tags-completion-function (string predicate &optional flag)
15491 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15492 (confirm (lambda (x) (stringp (car x)))))
15493 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15494 (setq s1 (match-string 1 string)
15495 s2 (match-string 2 string))
15496 (setq s1 "" s2 string))
15497 (cond
15498 ((eq flag nil)
15499 ;; try completion
15500 (setq rtn (try-completion s2 ctable confirm))
15501 (if (stringp rtn)
15502 (setq rtn
15503 (concat s1 s2 (substring rtn (length s2))
15504 (if (and org-add-colon-after-tag-completion
15505 (assoc rtn ctable))
15506 ":" ""))))
15507 rtn)
15508 ((eq flag t)
15509 ;; all-completions
15510 (all-completions s2 ctable confirm)
15512 ((eq flag 'lambda)
15513 ;; exact match?
15514 (assoc s2 ctable)))
15517 (defun org-fast-tag-insert (kwd tags face &optional end)
15518 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15519 (insert (format "%-12s" (concat kwd ":"))
15520 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15521 (or end "")))
15523 (defun org-fast-tag-show-exit (flag)
15524 (save-excursion
15525 (goto-line 3)
15526 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15527 (replace-match ""))
15528 (when flag
15529 (end-of-line 1)
15530 (move-to-column (- (window-width) 19) t)
15531 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15533 (defun org-set-current-tags-overlay (current prefix)
15534 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15535 (if (featurep 'xemacs)
15536 (org-overlay-display org-tags-overlay (concat prefix s)
15537 'secondary-selection)
15538 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15539 (org-overlay-display org-tags-overlay (concat prefix s)))))
15541 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15542 "Fast tag selection with single keys.
15543 CURRENT is the current list of tags in the headline, INHERITED is the
15544 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15545 possibly with grouping information. TODO-TABLE is a similar table with
15546 TODO keywords, should these have keys assigned to them.
15547 If the keys are nil, a-z are automatically assigned.
15548 Returns the new tags string, or nil to not change the current settings."
15549 (let* ((fulltable (append table todo-table))
15550 (maxlen (apply 'max (mapcar
15551 (lambda (x)
15552 (if (stringp (car x)) (string-width (car x)) 0))
15553 fulltable)))
15554 (buf (current-buffer))
15555 (expert (eq org-fast-tag-selection-single-key 'expert))
15556 (buffer-tags nil)
15557 (fwidth (+ maxlen 3 1 3))
15558 (ncol (/ (- (window-width) 4) fwidth))
15559 (i-face 'org-done)
15560 (c-face 'org-todo)
15561 tg cnt e c char c1 c2 ntable tbl rtn
15562 ov-start ov-end ov-prefix
15563 (exit-after-next org-fast-tag-selection-single-key)
15564 (done-keywords org-done-keywords)
15565 groups ingroup)
15566 (save-excursion
15567 (beginning-of-line 1)
15568 (if (looking-at
15569 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15570 (setq ov-start (match-beginning 1)
15571 ov-end (match-end 1)
15572 ov-prefix "")
15573 (setq ov-start (1- (point-at-eol))
15574 ov-end (1+ ov-start))
15575 (skip-chars-forward "^\n\r")
15576 (setq ov-prefix
15577 (concat
15578 (buffer-substring (1- (point)) (point))
15579 (if (> (current-column) org-tags-column)
15581 (make-string (- org-tags-column (current-column)) ?\ ))))))
15582 (org-move-overlay org-tags-overlay ov-start ov-end)
15583 (save-window-excursion
15584 (if expert
15585 (set-buffer (get-buffer-create " *Org tags*"))
15586 (delete-other-windows)
15587 (split-window-vertically)
15588 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
15589 (erase-buffer)
15590 (org-set-local 'org-done-keywords done-keywords)
15591 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15592 (org-fast-tag-insert "Current" current c-face "\n\n")
15593 (org-fast-tag-show-exit exit-after-next)
15594 (org-set-current-tags-overlay current ov-prefix)
15595 (setq tbl fulltable char ?a cnt 0)
15596 (while (setq e (pop tbl))
15597 (cond
15598 ((equal e '(:startgroup))
15599 (push '() groups) (setq ingroup t)
15600 (when (not (= cnt 0))
15601 (setq cnt 0)
15602 (insert "\n"))
15603 (insert "{ "))
15604 ((equal e '(:endgroup))
15605 (setq ingroup nil cnt 0)
15606 (insert "}\n"))
15608 (setq tg (car e) c2 nil)
15609 (if (cdr e)
15610 (setq c (cdr e))
15611 ;; automatically assign a character.
15612 (setq c1 (string-to-char
15613 (downcase (substring
15614 tg (if (= (string-to-char tg) ?@) 1 0)))))
15615 (if (or (rassoc c1 ntable) (rassoc c1 table))
15616 (while (or (rassoc char ntable) (rassoc char table))
15617 (setq char (1+ char)))
15618 (setq c2 c1))
15619 (setq c (or c2 char)))
15620 (if ingroup (push tg (car groups)))
15621 (setq tg (org-add-props tg nil 'face
15622 (cond
15623 ((not (assoc tg table))
15624 (org-get-todo-face tg))
15625 ((member tg current) c-face)
15626 ((member tg inherited) i-face)
15627 (t nil))))
15628 (if (and (= cnt 0) (not ingroup)) (insert " "))
15629 (insert "[" c "] " tg (make-string
15630 (- fwidth 4 (length tg)) ?\ ))
15631 (push (cons tg c) ntable)
15632 (when (= (setq cnt (1+ cnt)) ncol)
15633 (insert "\n")
15634 (if ingroup (insert " "))
15635 (setq cnt 0)))))
15636 (setq ntable (nreverse ntable))
15637 (insert "\n")
15638 (goto-char (point-min))
15639 (if (and (not expert) (fboundp 'fit-window-to-buffer))
15640 (fit-window-to-buffer))
15641 (setq rtn
15642 (catch 'exit
15643 (while t
15644 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
15645 (if groups " [!] no groups" " [!]groups")
15646 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15647 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15648 (cond
15649 ((= c ?\r) (throw 'exit t))
15650 ((= c ?!)
15651 (setq groups (not groups))
15652 (goto-char (point-min))
15653 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15654 ((= c ?\C-c)
15655 (if (not expert)
15656 (org-fast-tag-show-exit
15657 (setq exit-after-next (not exit-after-next)))
15658 (setq expert nil)
15659 (delete-other-windows)
15660 (split-window-vertically)
15661 (org-switch-to-buffer-other-window " *Org tags*")
15662 (and (fboundp 'fit-window-to-buffer)
15663 (fit-window-to-buffer))))
15664 ((or (= c ?\C-g)
15665 (and (= c ?q) (not (rassoc c ntable))))
15666 (org-detach-overlay org-tags-overlay)
15667 (setq quit-flag t))
15668 ((= c ?\ )
15669 (setq current nil)
15670 (if exit-after-next (setq exit-after-next 'now)))
15671 ((= c ?\t)
15672 (condition-case nil
15673 (setq tg (completing-read
15674 "Tag: "
15675 (or buffer-tags
15676 (with-current-buffer buf
15677 (org-get-buffer-tags)))))
15678 (quit (setq tg "")))
15679 (when (string-match "\\S-" tg)
15680 (add-to-list 'buffer-tags (list tg))
15681 (if (member tg current)
15682 (setq current (delete tg current))
15683 (push tg current)))
15684 (if exit-after-next (setq exit-after-next 'now)))
15685 ((setq e (rassoc c todo-table) tg (car e))
15686 (with-current-buffer buf
15687 (save-excursion (org-todo tg)))
15688 (if exit-after-next (setq exit-after-next 'now)))
15689 ((setq e (rassoc c ntable) tg (car e))
15690 (if (member tg current)
15691 (setq current (delete tg current))
15692 (loop for g in groups do
15693 (if (member tg g)
15694 (mapc (lambda (x)
15695 (setq current (delete x current)))
15696 g)))
15697 (push tg current))
15698 (if exit-after-next (setq exit-after-next 'now))))
15700 ;; Create a sorted list
15701 (setq current
15702 (sort current
15703 (lambda (a b)
15704 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15705 (if (eq exit-after-next 'now) (throw 'exit t))
15706 (goto-char (point-min))
15707 (beginning-of-line 2)
15708 (delete-region (point) (point-at-eol))
15709 (org-fast-tag-insert "Current" current c-face)
15710 (org-set-current-tags-overlay current ov-prefix)
15711 (while (re-search-forward
15712 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
15713 (setq tg (match-string 1))
15714 (add-text-properties
15715 (match-beginning 1) (match-end 1)
15716 (list 'face
15717 (cond
15718 ((member tg current) c-face)
15719 ((member tg inherited) i-face)
15720 (t (get-text-property (match-beginning 1) 'face))))))
15721 (goto-char (point-min)))))
15722 (org-detach-overlay org-tags-overlay)
15723 (if rtn
15724 (mapconcat 'identity current ":")
15725 nil))))
15727 (defun org-get-tags-string ()
15728 "Get the TAGS string in the current headline."
15729 (unless (org-on-heading-p t)
15730 (error "Not on a heading"))
15731 (save-excursion
15732 (beginning-of-line 1)
15733 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15734 (org-match-string-no-properties 1)
15735 "")))
15737 (defun org-get-tags ()
15738 "Get the list of tags specified in the current headline."
15739 (org-split-string (org-get-tags-string) ":"))
15741 (defun org-get-buffer-tags ()
15742 "Get a table of all tags used in the buffer, for completion."
15743 (let (tags)
15744 (save-excursion
15745 (goto-char (point-min))
15746 (while (re-search-forward
15747 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
15748 (when (equal (char-after (point-at-bol 0)) ?*)
15749 (mapc (lambda (x) (add-to-list 'tags x))
15750 (org-split-string (org-match-string-no-properties 1) ":")))))
15751 (mapcar 'list tags)))
15754 ;;;; Properties
15756 ;;; Setting and retrieving properties
15758 (defconst org-special-properties
15759 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
15760 "TIMESTAMP" "TIMESTAMP_IA")
15761 "The special properties valid in Org-mode.
15763 These are properties that are not defined in the property drawer,
15764 but in some other way.")
15766 (defconst org-default-properties
15767 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
15768 "LOCATION" "LOGGING" "COLUMNS")
15769 "Some properties that are used by Org-mode for various purposes.
15770 Being in this list makes sure that they are offered for completion.")
15772 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15773 "Regular expression matching the first line of a property drawer.")
15775 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15776 "Regular expression matching the first line of a property drawer.")
15778 (defun org-property-action ()
15779 "Do an action on properties."
15780 (interactive)
15781 (let (c)
15782 (org-at-property-p)
15783 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15784 (setq c (read-char-exclusive))
15785 (cond
15786 ((equal c ?s)
15787 (call-interactively 'org-set-property))
15788 ((equal c ?d)
15789 (call-interactively 'org-delete-property))
15790 ((equal c ?D)
15791 (call-interactively 'org-delete-property-globally))
15792 ((equal c ?c)
15793 (call-interactively 'org-compute-property-at-point))
15794 (t (error "No such property action %c" c)))))
15796 (defun org-at-property-p ()
15797 "Is the cursor in a property line?"
15798 ;; FIXME: Does not check if we are actually in the drawer.
15799 ;; FIXME: also returns true on any drawers.....
15800 ;; This is used by C-c C-c for property action.
15801 (save-excursion
15802 (beginning-of-line 1)
15803 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
15805 (defmacro org-with-point-at (pom &rest body)
15806 "Move to buffer and point of point-or-marker POM for the duration of BODY."
15807 (declare (indent 1) (debug t))
15808 `(save-excursion
15809 (if (markerp pom) (set-buffer (marker-buffer pom)))
15810 (save-excursion
15811 (goto-char (or pom (point)))
15812 ,@body)))
15814 (defun org-get-property-block (&optional beg end force)
15815 "Return the (beg . end) range of the body of the property drawer.
15816 BEG and END can be beginning and end of subtree, if not given
15817 they will be found.
15818 If the drawer does not exist and FORCE is non-nil, create the drawer."
15819 (catch 'exit
15820 (save-excursion
15821 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
15822 (end (or end (progn (outline-next-heading) (point)))))
15823 (goto-char beg)
15824 (if (re-search-forward org-property-start-re end t)
15825 (setq beg (1+ (match-end 0)))
15826 (if force
15827 (save-excursion
15828 (org-insert-property-drawer)
15829 (setq end (progn (outline-next-heading) (point))))
15830 (throw 'exit nil))
15831 (goto-char beg)
15832 (if (re-search-forward org-property-start-re end t)
15833 (setq beg (1+ (match-end 0)))))
15834 (if (re-search-forward org-property-end-re end t)
15835 (setq end (match-beginning 0))
15836 (or force (throw 'exit nil))
15837 (goto-char beg)
15838 (setq end beg)
15839 (org-indent-line-function)
15840 (insert ":END:\n"))
15841 (cons beg end)))))
15843 (defun org-entry-properties (&optional pom which)
15844 "Get all properties of the entry at point-or-marker POM.
15845 This includes the TODO keyword, the tags, time strings for deadline,
15846 scheduled, and clocking, and any additional properties defined in the
15847 entry. The return value is an alist, keys may occur multiple times
15848 if the property key was used several times.
15849 POM may also be nil, in which case the current entry is used.
15850 If WHICH is nil or `all', get all properties. If WHICH is
15851 `special' or `standard', only get that subclass."
15852 (setq which (or which 'all))
15853 (org-with-point-at pom
15854 (let ((clockstr (substring org-clock-string 0 -1))
15855 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
15856 beg end range props sum-props key value string clocksum)
15857 (save-excursion
15858 (when (condition-case nil (org-back-to-heading t) (error nil))
15859 (setq beg (point))
15860 (setq sum-props (get-text-property (point) 'org-summaries))
15861 (setq clocksum (get-text-property (point) :org-clock-minutes))
15862 (outline-next-heading)
15863 (setq end (point))
15864 (when (memq which '(all special))
15865 ;; Get the special properties, like TODO and tags
15866 (goto-char beg)
15867 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15868 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15869 (when (looking-at org-priority-regexp)
15870 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15871 (when (and (setq value (org-get-tags-string))
15872 (string-match "\\S-" value))
15873 (push (cons "TAGS" value) props))
15874 (when (setq value (org-get-tags-at))
15875 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
15876 props))
15877 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15878 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
15879 string (if (equal key clockstr)
15880 (org-no-properties
15881 (org-trim
15882 (buffer-substring
15883 (match-beginning 3) (goto-char (point-at-eol)))))
15884 (substring (org-match-string-no-properties 3) 1 -1)))
15885 (unless key
15886 (if (= (char-after (match-beginning 3)) ?\[)
15887 (setq key "TIMESTAMP_IA")
15888 (setq key "TIMESTAMP")))
15889 (when (or (equal key clockstr) (not (assoc key props)))
15890 (push (cons key string) props)))
15894 (when (memq which '(all standard))
15895 ;; Get the standard properties, like :PORP: ...
15896 (setq range (org-get-property-block beg end))
15897 (when range
15898 (goto-char (car range))
15899 (while (re-search-forward
15900 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15901 (cdr range) t)
15902 (setq key (org-match-string-no-properties 1)
15903 value (org-trim (or (org-match-string-no-properties 2) "")))
15904 (unless (member key excluded)
15905 (push (cons key (or value "")) props)))))
15906 (if clocksum
15907 (push (cons "CLOCKSUM"
15908 (org-column-number-to-string (/ (float clocksum) 60.)
15909 'add_times))
15910 props))
15911 (append sum-props (nreverse props)))))))
15913 (defun org-entry-get (pom property &optional inherit)
15914 "Get value of PROPERTY for entry at point-or-marker POM.
15915 If INHERIT is non-nil and the entry does not have the property,
15916 then also check higher levels of the hierarchy.
15917 If the property is present but empty, the return value is the empty string.
15918 If the property is not present at all, nil is returned."
15919 (org-with-point-at pom
15920 (if inherit
15921 (org-entry-get-with-inheritance property)
15922 (if (member property org-special-properties)
15923 ;; We need a special property. Use brute force, get all properties.
15924 (cdr (assoc property (org-entry-properties nil 'special)))
15925 (let ((range (org-get-property-block)))
15926 (if (and range
15927 (goto-char (car range))
15928 (re-search-forward
15929 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
15930 (cdr range) t))
15931 ;; Found the property, return it.
15932 (if (match-end 1)
15933 (org-match-string-no-properties 1)
15934 "")))))))
15936 (defun org-entry-delete (pom property)
15937 "Delete the property PROPERTY from entry at point-or-marker POM."
15938 (org-with-point-at pom
15939 (if (member property org-special-properties)
15940 nil ; cannot delete these properties.
15941 (let ((range (org-get-property-block)))
15942 (if (and range
15943 (goto-char (car range))
15944 (re-search-forward
15945 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
15946 (cdr range) t))
15947 (progn
15948 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15950 nil)))))
15952 ;; Multi-values properties are properties that contain multiple values
15953 ;; These values are assumed to be single words, separated by whitespace.
15954 (defun org-entry-add-to-multivalued-property (pom property value)
15955 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15956 (let* ((old (org-entry-get pom property))
15957 (values (and old (org-split-string old "[ \t]"))))
15958 (unless (member value values)
15959 (setq values (cons value values))
15960 (org-entry-put pom property
15961 (mapconcat 'identity values " ")))))
15963 (defun org-entry-remove-from-multivalued-property (pom property value)
15964 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15965 (let* ((old (org-entry-get pom property))
15966 (values (and old (org-split-string old "[ \t]"))))
15967 (when (member value values)
15968 (setq values (delete value values))
15969 (org-entry-put pom property
15970 (mapconcat 'identity values " ")))))
15972 (defun org-entry-member-in-multivalued-property (pom property value)
15973 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15974 (let* ((old (org-entry-get pom property))
15975 (values (and old (org-split-string old "[ \t]"))))
15976 (member value values)))
15978 (defvar org-entry-property-inherited-from (make-marker))
15980 (defun org-entry-get-with-inheritance (property)
15981 "Get entry property, and search higher levels if not present."
15982 (let (tmp)
15983 (save-excursion
15984 (save-restriction
15985 (widen)
15986 (catch 'ex
15987 (while t
15988 (when (setq tmp (org-entry-get nil property))
15989 (org-back-to-heading t)
15990 (move-marker org-entry-property-inherited-from (point))
15991 (throw 'ex tmp))
15992 (or (org-up-heading-safe) (throw 'ex nil)))))
15993 (or tmp (cdr (assoc property org-local-properties))
15994 (cdr (assoc property org-global-properties))))))
15996 (defun org-entry-put (pom property value)
15997 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15998 (org-with-point-at pom
15999 (org-back-to-heading t)
16000 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
16001 range)
16002 (cond
16003 ((equal property "TODO")
16004 (when (and (stringp value) (string-match "\\S-" value)
16005 (not (member value org-todo-keywords-1)))
16006 (error "\"%s\" is not a valid TODO state" value))
16007 (if (or (not value)
16008 (not (string-match "\\S-" value)))
16009 (setq value 'none))
16010 (org-todo value)
16011 (org-set-tags nil 'align))
16012 ((equal property "PRIORITY")
16013 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
16014 (string-to-char value) ?\ ))
16015 (org-set-tags nil 'align))
16016 ((equal property "SCHEDULED")
16017 (if (re-search-forward org-scheduled-time-regexp end t)
16018 (cond
16019 ((eq value 'earlier) (org-timestamp-change -1 'day))
16020 ((eq value 'later) (org-timestamp-change 1 'day))
16021 (t (call-interactively 'org-schedule)))
16022 (call-interactively 'org-schedule)))
16023 ((equal property "DEADLINE")
16024 (if (re-search-forward org-deadline-time-regexp end t)
16025 (cond
16026 ((eq value 'earlier) (org-timestamp-change -1 'day))
16027 ((eq value 'later) (org-timestamp-change 1 'day))
16028 (t (call-interactively 'org-deadline)))
16029 (call-interactively 'org-deadline)))
16030 ((member property org-special-properties)
16031 (error "The %s property can not yet be set with `org-entry-put'"
16032 property))
16033 (t ; a non-special property
16034 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
16035 (setq range (org-get-property-block beg end 'force))
16036 (goto-char (car range))
16037 (if (re-search-forward
16038 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
16039 (progn
16040 (delete-region (match-beginning 1) (match-end 1))
16041 (goto-char (match-beginning 1)))
16042 (goto-char (cdr range))
16043 (insert "\n")
16044 (backward-char 1)
16045 (org-indent-line-function)
16046 (insert ":" property ":"))
16047 (and value (insert " " value))
16048 (org-indent-line-function)))))))
16050 (defun org-buffer-property-keys (&optional include-specials include-defaults)
16051 "Get all property keys in the current buffer.
16052 With INCLUDE-SPECIALS, also list the special properties that relect things
16053 like tags and TODO state.
16054 With INCLUDE-DEFAULTS, also include properties that has special meaning
16055 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING."
16056 (let (rtn range)
16057 (save-excursion
16058 (save-restriction
16059 (widen)
16060 (goto-char (point-min))
16061 (while (re-search-forward org-property-start-re nil t)
16062 (setq range (org-get-property-block))
16063 (goto-char (car range))
16064 (while (re-search-forward
16065 (org-re "^[ \t]*:\\([[:alnum:]_-]+\\):")
16066 (cdr range) t)
16067 (add-to-list 'rtn (org-match-string-no-properties 1)))
16068 (outline-next-heading))))
16070 (when include-specials
16071 (setq rtn (append org-special-properties rtn)))
16073 (when include-defaults
16074 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
16076 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
16078 (defun org-property-values (key)
16079 "Return a list of all values of property KEY."
16080 (save-excursion
16081 (save-restriction
16082 (widen)
16083 (goto-char (point-min))
16084 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
16085 values)
16086 (while (re-search-forward re nil t)
16087 (add-to-list 'values (org-trim (match-string 1))))
16088 (delete "" values)))))
16090 (defun org-insert-property-drawer ()
16091 "Insert a property drawer into the current entry."
16092 (interactive)
16093 (org-back-to-heading t)
16094 (looking-at outline-regexp)
16095 (let ((indent (- (match-end 0)(match-beginning 0)))
16096 (beg (point))
16097 (re (concat "^[ \t]*" org-keyword-time-regexp))
16098 end hiddenp)
16099 (outline-next-heading)
16100 (setq end (point))
16101 (goto-char beg)
16102 (while (re-search-forward re end t))
16103 (setq hiddenp (org-invisible-p))
16104 (end-of-line 1)
16105 (and (equal (char-after) ?\n) (forward-char 1))
16106 (org-skip-over-state-notes)
16107 (skip-chars-backward " \t\n\r")
16108 (if (eq (char-before) ?*) (forward-char 1))
16109 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
16110 (beginning-of-line 0)
16111 (indent-to-column indent)
16112 (beginning-of-line 2)
16113 (indent-to-column indent)
16114 (beginning-of-line 0)
16115 (if hiddenp
16116 (save-excursion
16117 (org-back-to-heading t)
16118 (hide-entry))
16119 (org-flag-drawer t))))
16121 (defun org-set-property (property value)
16122 "In the current entry, set PROPERTY to VALUE.
16123 When called interactively, this will prompt for a property name, offering
16124 completion on existing and default properties. And then it will prompt
16125 for a value, offering competion either on allowed values (via an inherited
16126 xxx_ALL property) or on existing values in other instances of this property
16127 in the current file."
16128 (interactive
16129 (let* ((prop (completing-read
16130 "Property: " (mapcar 'list (org-buffer-property-keys nil t))))
16131 (cur (org-entry-get nil prop))
16132 (allowed (org-property-get-allowed-values nil prop 'table))
16133 (existing (mapcar 'list (org-property-values prop)))
16134 (val (if allowed
16135 (completing-read "Value: " allowed nil 'req-match)
16136 (completing-read
16137 (concat "Value" (if (and cur (string-match "\\S-" cur))
16138 (concat "[" cur "]") "")
16139 ": ")
16140 existing nil nil "" nil cur))))
16141 (list prop (if (equal val "") cur val))))
16142 (unless (equal (org-entry-get nil property) value)
16143 (org-entry-put nil property value)))
16145 (defun org-delete-property (property)
16146 "In the current entry, delete PROPERTY."
16147 (interactive
16148 (let* ((prop (completing-read
16149 "Property: " (org-entry-properties nil 'standard))))
16150 (list prop)))
16151 (message "Property %s %s" property
16152 (if (org-entry-delete nil property)
16153 "deleted"
16154 "was not present in the entry")))
16156 (defun org-delete-property-globally (property)
16157 "Remove PROPERTY globally, from all entries."
16158 (interactive
16159 (let* ((prop (completing-read
16160 "Globally remove property: "
16161 (mapcar 'list (org-buffer-property-keys)))))
16162 (list prop)))
16163 (save-excursion
16164 (save-restriction
16165 (widen)
16166 (goto-char (point-min))
16167 (let ((cnt 0))
16168 (while (re-search-forward
16169 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16170 nil t)
16171 (setq cnt (1+ cnt))
16172 (replace-match ""))
16173 (message "Property \"%s\" removed from %d entries" property cnt)))))
16175 (defvar org-columns-current-fmt-compiled) ; defined below
16177 (defun org-compute-property-at-point ()
16178 "Compute the property at point.
16179 This looks for an enclosing column format, extracts the operator and
16180 then applies it to the proerty in the column format's scope."
16181 (interactive)
16182 (unless (org-at-property-p)
16183 (error "Not at a property"))
16184 (let ((prop (org-match-string-no-properties 2)))
16185 (org-columns-get-format-and-top-level)
16186 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16187 (error "No operator defined for property %s" prop))
16188 (org-columns-compute prop)))
16190 (defun org-property-get-allowed-values (pom property &optional table)
16191 "Get allowed values for the property PROPERTY.
16192 When TABLE is non-nil, return an alist that can directly be used for
16193 completion."
16194 (let (vals)
16195 (cond
16196 ((equal property "TODO")
16197 (setq vals (org-with-point-at pom
16198 (append org-todo-keywords-1 '("")))))
16199 ((equal property "PRIORITY")
16200 (let ((n org-lowest-priority))
16201 (while (>= n org-highest-priority)
16202 (push (char-to-string n) vals)
16203 (setq n (1- n)))))
16204 ((member property org-special-properties))
16206 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16208 (when (and vals (string-match "\\S-" vals))
16209 (setq vals (car (read-from-string (concat "(" vals ")"))))
16210 (setq vals (mapcar (lambda (x)
16211 (cond ((stringp x) x)
16212 ((numberp x) (number-to-string x))
16213 ((symbolp x) (symbol-name x))
16214 (t "???")))
16215 vals)))))
16216 (if table (mapcar 'list vals) vals)))
16218 (defun org-property-previous-allowed-value (&optional previous)
16219 "Switch to the next allowed value for this property."
16220 (interactive)
16221 (org-property-next-allowed-value t))
16223 (defun org-property-next-allowed-value (&optional previous)
16224 "Switch to the next allowed value for this property."
16225 (interactive)
16226 (unless (org-at-property-p)
16227 (error "Not at a property"))
16228 (let* ((key (match-string 2))
16229 (value (match-string 3))
16230 (allowed (or (org-property-get-allowed-values (point) key)
16231 (and (member value '("[ ]" "[-]" "[X]"))
16232 '("[ ]" "[X]"))))
16233 nval)
16234 (unless allowed
16235 (error "Allowed values for this property have not been defined"))
16236 (if previous (setq allowed (reverse allowed)))
16237 (if (member value allowed)
16238 (setq nval (car (cdr (member value allowed)))))
16239 (setq nval (or nval (car allowed)))
16240 (if (equal nval value)
16241 (error "Only one allowed value for this property"))
16242 (org-at-property-p)
16243 (replace-match (concat " :" key ": " nval) t t)
16244 (org-indent-line-function)
16245 (beginning-of-line 1)
16246 (skip-chars-forward " \t")))
16248 (defun org-find-entry-with-id (ident)
16249 "Locate the entry that contains the ID property with exact value IDENT.
16250 IDENT can be a string, a symbol or a number, this function will search for
16251 the string representation of it.
16252 Return the position where this entry starts, or nil if there is no such entry."
16253 (let ((id (cond
16254 ((stringp ident) ident)
16255 ((symbol-name ident) (symbol-name ident))
16256 ((numberp ident) (number-to-string ident))
16257 (t (error "IDENT %s must be a string, symbol or number" ident))))
16258 (case-fold-search nil))
16259 (save-excursion
16260 (save-restriction
16261 (goto-char (point-min))
16262 (when (re-search-forward
16263 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16264 nil t)
16265 (org-back-to-heading)
16266 (point))))))
16268 ;;; Column View
16270 (defvar org-columns-overlays nil
16271 "Holds the list of current column overlays.")
16273 (defvar org-columns-current-fmt nil
16274 "Local variable, holds the currently active column format.")
16275 (defvar org-columns-current-fmt-compiled nil
16276 "Local variable, holds the currently active column format.
16277 This is the compiled version of the format.")
16278 (defvar org-columns-current-widths nil
16279 "Loval variable, holds the currently widths of fields.")
16280 (defvar org-columns-current-maxwidths nil
16281 "Loval variable, holds the currently active maximum column widths.")
16282 (defvar org-columns-begin-marker (make-marker)
16283 "Points to the position where last a column creation command was called.")
16284 (defvar org-columns-top-level-marker (make-marker)
16285 "Points to the position where current columns region starts.")
16287 (defvar org-columns-map (make-sparse-keymap)
16288 "The keymap valid in column display.")
16290 (defun org-columns-content ()
16291 "Switch to contents view while in columns view."
16292 (interactive)
16293 (org-overview)
16294 (org-content))
16296 (org-defkey org-columns-map "c" 'org-columns-content)
16297 (org-defkey org-columns-map "o" 'org-overview)
16298 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16299 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16300 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16301 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16302 (org-defkey org-columns-map "v" 'org-columns-show-value)
16303 (org-defkey org-columns-map "q" 'org-columns-quit)
16304 (org-defkey org-columns-map "r" 'org-columns-redo)
16305 (org-defkey org-columns-map "g" 'org-columns-redo)
16306 (org-defkey org-columns-map [left] 'backward-char)
16307 (org-defkey org-columns-map "\M-b" 'backward-char)
16308 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16309 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16310 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16311 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16312 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16313 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16314 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16315 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16316 (org-defkey org-columns-map "<" 'org-columns-narrow)
16317 (org-defkey org-columns-map ">" 'org-columns-widen)
16318 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16319 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16320 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16321 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16323 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16324 '("Column"
16325 ["Edit property" org-columns-edit-value t]
16326 ["Next allowed value" org-columns-next-allowed-value t]
16327 ["Previous allowed value" org-columns-previous-allowed-value t]
16328 ["Show full value" org-columns-show-value t]
16329 ["Edit allowed values" org-columns-edit-allowed t]
16330 "--"
16331 ["Edit column attributes" org-columns-edit-attributes t]
16332 ["Increase column width" org-columns-widen t]
16333 ["Decrease column width" org-columns-narrow t]
16334 "--"
16335 ["Move column right" org-columns-move-right t]
16336 ["Move column left" org-columns-move-left t]
16337 ["Add column" org-columns-new t]
16338 ["Delete column" org-columns-delete t]
16339 "--"
16340 ["CONTENTS" org-columns-content t]
16341 ["OVERVIEW" org-overview t]
16342 ["Refresh columns display" org-columns-redo t]
16343 "--"
16344 ["Open link" org-columns-open-link t]
16345 "--"
16346 ["Quit" org-columns-quit t]))
16348 (defun org-columns-new-overlay (beg end &optional string face)
16349 "Create a new column overlay and add it to the list."
16350 (let ((ov (org-make-overlay beg end)))
16351 (org-overlay-put ov 'face (or face 'secondary-selection))
16352 (org-overlay-display ov string face)
16353 (push ov org-columns-overlays)
16354 ov))
16356 (defun org-columns-display-here (&optional props)
16357 "Overlay the current line with column display."
16358 (interactive)
16359 (let* ((fmt org-columns-current-fmt-compiled)
16360 (beg (point-at-bol))
16361 (level-face (save-excursion
16362 (beginning-of-line 1)
16363 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16364 (org-get-level-face 2))))
16365 (color (list :foreground
16366 (face-attribute (or level-face 'default) :foreground)))
16367 props pom property ass width f string ov column val modval)
16368 ;; Check if the entry is in another buffer.
16369 (unless props
16370 (if (eq major-mode 'org-agenda-mode)
16371 (setq pom (or (get-text-property (point) 'org-hd-marker)
16372 (get-text-property (point) 'org-marker))
16373 props (if pom (org-entry-properties pom) nil))
16374 (setq props (org-entry-properties nil))))
16375 ;; Walk the format
16376 (while (setq column (pop fmt))
16377 (setq property (car column)
16378 ass (if (equal property "ITEM")
16379 (cons "ITEM"
16380 (save-match-data
16381 (org-no-properties
16382 (org-remove-tabs
16383 (buffer-substring-no-properties
16384 (point-at-bol) (point-at-eol))))))
16385 (assoc property props))
16386 width (or (cdr (assoc property org-columns-current-maxwidths))
16387 (nth 2 column)
16388 (length property))
16389 f (format "%%-%d.%ds | " width width)
16390 val (or (cdr ass) "")
16391 modval (if (equal property "ITEM")
16392 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16393 string (format f (or modval val)))
16394 ;; Create the overlay
16395 (org-unmodified
16396 (setq ov (org-columns-new-overlay
16397 beg (setq beg (1+ beg)) string
16398 (list color 'org-column)))
16399 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16400 (org-overlay-put ov 'keymap org-columns-map)
16401 (org-overlay-put ov 'org-columns-key property)
16402 (org-overlay-put ov 'org-columns-value (cdr ass))
16403 (org-overlay-put ov 'org-columns-value-modified modval)
16404 (org-overlay-put ov 'org-columns-pom pom)
16405 (org-overlay-put ov 'org-columns-format f))
16406 (if (or (not (char-after beg))
16407 (equal (char-after beg) ?\n))
16408 (let ((inhibit-read-only t))
16409 (save-excursion
16410 (goto-char beg)
16411 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16412 ;; Make the rest of the line disappear.
16413 (org-unmodified
16414 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16415 (org-overlay-put ov 'invisible t)
16416 (org-overlay-put ov 'keymap org-columns-map)
16417 (org-overlay-put ov 'intangible t)
16418 (push ov org-columns-overlays)
16419 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16420 (org-overlay-put ov 'keymap org-columns-map)
16421 (push ov org-columns-overlays)
16422 (let ((inhibit-read-only t))
16423 (put-text-property (max (point-min) (1- (point-at-bol)))
16424 (min (point-max) (1+ (point-at-eol)))
16425 'read-only "Type `e' to edit property")))))
16427 (defvar org-previous-header-line-format nil
16428 "The header line format before column view was turned on.")
16429 (defvar org-columns-inhibit-recalculation nil
16430 "Inhibit recomputing of columns on column view startup.")
16433 (defvar header-line-format)
16434 (defun org-columns-display-here-title ()
16435 "Overlay the newline before the current line with the table title."
16436 (interactive)
16437 (let ((fmt org-columns-current-fmt-compiled)
16438 string (title "")
16439 property width f column str widths)
16440 (while (setq column (pop fmt))
16441 (setq property (car column)
16442 str (or (nth 1 column) property)
16443 width (or (cdr (assoc property org-columns-current-maxwidths))
16444 (nth 2 column)
16445 (length str))
16446 widths (push width widths)
16447 f (format "%%-%d.%ds | " width width)
16448 string (format f str)
16449 title (concat title string)))
16450 (setq title (concat
16451 (org-add-props " " nil 'display '(space :align-to 0))
16452 (org-add-props title nil 'face '(:weight bold :underline t))))
16453 (org-set-local 'org-previous-header-line-format header-line-format)
16454 (org-set-local 'org-columns-current-widths (nreverse widths))
16455 (setq header-line-format title)))
16457 (defun org-columns-remove-overlays ()
16458 "Remove all currently active column overlays."
16459 (interactive)
16460 (when (marker-buffer org-columns-begin-marker)
16461 (with-current-buffer (marker-buffer org-columns-begin-marker)
16462 (when (local-variable-p 'org-previous-header-line-format)
16463 (setq header-line-format org-previous-header-line-format)
16464 (kill-local-variable 'org-previous-header-line-format))
16465 (move-marker org-columns-begin-marker nil)
16466 (move-marker org-columns-top-level-marker nil)
16467 (org-unmodified
16468 (mapc 'org-delete-overlay org-columns-overlays)
16469 (setq org-columns-overlays nil)
16470 (let ((inhibit-read-only t))
16471 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16473 (defun org-columns-cleanup-item (item fmt)
16474 "Remove from ITEM what is a column in the format FMT."
16475 (if (not org-complex-heading-regexp)
16476 item
16477 (when (string-match org-complex-heading-regexp item)
16478 (concat
16479 (org-add-props (concat (match-string 1 item) " ") nil
16480 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16481 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16482 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16483 " " (match-string 4 item)
16484 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16486 (defun org-columns-show-value ()
16487 "Show the full value of the property."
16488 (interactive)
16489 (let ((value (get-char-property (point) 'org-columns-value)))
16490 (message "Value is: %s" (or value ""))))
16492 (defun org-columns-quit ()
16493 "Remove the column overlays and in this way exit column editing."
16494 (interactive)
16495 (org-unmodified
16496 (org-columns-remove-overlays)
16497 (let ((inhibit-read-only t))
16498 (remove-text-properties (point-min) (point-max) '(read-only t))))
16499 (when (eq major-mode 'org-agenda-mode)
16500 (message
16501 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16503 (defun org-columns-check-computed ()
16504 "Check if this column value is computed.
16505 If yes, throw an error indicating that changing it does not make sense."
16506 (let ((val (get-char-property (point) 'org-columns-value)))
16507 (when (and (stringp val)
16508 (get-char-property 0 'org-computed val))
16509 (error "This value is computed from the entry's children"))))
16511 (defun org-columns-todo (&optional arg)
16512 "Change the TODO state during column view."
16513 (interactive "P")
16514 (org-columns-edit-value "TODO"))
16516 (defun org-columns-set-tags-or-toggle (&optional arg)
16517 "Toggle checkbox at point, or set tags for current headline."
16518 (interactive "P")
16519 (if (string-match "\\`\\[[ xX-]\\]\\'"
16520 (get-char-property (point) 'org-columns-value))
16521 (org-columns-next-allowed-value)
16522 (org-columns-edit-value "TAGS")))
16524 (defun org-columns-edit-value (&optional key)
16525 "Edit the value of the property at point in column view.
16526 Where possible, use the standard interface for changing this line."
16527 (interactive)
16528 (org-columns-check-computed)
16529 (let* ((external-key key)
16530 (col (current-column))
16531 (key (or key (get-char-property (point) 'org-columns-key)))
16532 (value (get-char-property (point) 'org-columns-value))
16533 (bol (point-at-bol)) (eol (point-at-eol))
16534 (pom (or (get-text-property bol 'org-hd-marker)
16535 (point))) ; keep despite of compiler waring
16536 (line-overlays
16537 (delq nil (mapcar (lambda (x)
16538 (and (eq (overlay-buffer x) (current-buffer))
16539 (>= (overlay-start x) bol)
16540 (<= (overlay-start x) eol)
16542 org-columns-overlays)))
16543 nval eval allowed)
16544 (cond
16545 ((equal key "CLOCKSUM")
16546 (error "This special column cannot be edited"))
16547 ((equal key "ITEM")
16548 (setq eval '(org-with-point-at pom
16549 (org-edit-headline))))
16550 ((equal key "TODO")
16551 (setq eval '(org-with-point-at pom
16552 (let ((current-prefix-arg
16553 (if external-key current-prefix-arg '(4))))
16554 (call-interactively 'org-todo)))))
16555 ((equal key "PRIORITY")
16556 (setq eval '(org-with-point-at pom
16557 (call-interactively 'org-priority))))
16558 ((equal key "TAGS")
16559 (setq eval '(org-with-point-at pom
16560 (let ((org-fast-tag-selection-single-key
16561 (if (eq org-fast-tag-selection-single-key 'expert)
16562 t org-fast-tag-selection-single-key)))
16563 (call-interactively 'org-set-tags)))))
16564 ((equal key "DEADLINE")
16565 (setq eval '(org-with-point-at pom
16566 (call-interactively 'org-deadline))))
16567 ((equal key "SCHEDULED")
16568 (setq eval '(org-with-point-at pom
16569 (call-interactively 'org-schedule))))
16571 (setq allowed (org-property-get-allowed-values pom key 'table))
16572 (if allowed
16573 (setq nval (completing-read "Value: " allowed nil t))
16574 (setq nval (read-string "Edit: " value)))
16575 (setq nval (org-trim nval))
16576 (when (not (equal nval value))
16577 (setq eval '(org-entry-put pom key nval)))))
16578 (when eval
16579 (let ((inhibit-read-only t))
16580 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
16581 (unwind-protect
16582 (progn
16583 (setq org-columns-overlays
16584 (org-delete-all line-overlays org-columns-overlays))
16585 (mapc 'org-delete-overlay line-overlays)
16586 (org-columns-eval eval))
16587 (org-columns-display-here))))
16588 (move-to-column col)
16589 (if (and (org-mode-p)
16590 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16591 (org-columns-update key))))
16593 (defun org-edit-headline () ; FIXME: this is not columns specific
16594 "Edit the current headline, the part without TODO keyword, TAGS."
16595 (org-back-to-heading)
16596 (when (looking-at org-todo-line-regexp)
16597 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
16598 (txt (match-string 3))
16599 (post "")
16600 txt2)
16601 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
16602 (setq post (match-string 0 txt)
16603 txt (substring txt 0 (match-beginning 0))))
16604 (setq txt2 (read-string "Edit: " txt))
16605 (when (not (equal txt txt2))
16606 (beginning-of-line 1)
16607 (insert pre txt2 post)
16608 (delete-region (point) (point-at-eol))
16609 (org-set-tags nil t)))))
16611 (defun org-columns-edit-allowed ()
16612 "Edit the list of allowed values for the current property."
16613 (interactive)
16614 (let* ((key (get-char-property (point) 'org-columns-key))
16615 (key1 (concat key "_ALL"))
16616 (allowed (org-entry-get (point) key1 t))
16617 nval)
16618 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
16619 (setq nval (read-string "Allowed: " allowed))
16620 (org-entry-put
16621 (cond ((marker-position org-entry-property-inherited-from)
16622 org-entry-property-inherited-from)
16623 ((marker-position org-columns-top-level-marker)
16624 org-columns-top-level-marker))
16625 key1 nval)))
16627 (defmacro org-no-warnings (&rest body)
16628 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
16630 (defun org-columns-eval (form)
16631 (let (hidep)
16632 (save-excursion
16633 (beginning-of-line 1)
16634 ;; `next-line' is needed here, because it skips invisible line.
16635 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
16636 (setq hidep (org-on-heading-p 1)))
16637 (eval form)
16638 (and hidep (hide-entry))))
16640 (defun org-columns-previous-allowed-value ()
16641 "Switch to the previous allowed value for this column."
16642 (interactive)
16643 (org-columns-next-allowed-value t))
16645 (defun org-columns-next-allowed-value (&optional previous)
16646 "Switch to the next allowed value for this column."
16647 (interactive)
16648 (org-columns-check-computed)
16649 (let* ((col (current-column))
16650 (key (get-char-property (point) 'org-columns-key))
16651 (value (get-char-property (point) 'org-columns-value))
16652 (bol (point-at-bol)) (eol (point-at-eol))
16653 (pom (or (get-text-property bol 'org-hd-marker)
16654 (point))) ; keep despite of compiler waring
16655 (line-overlays
16656 (delq nil (mapcar (lambda (x)
16657 (and (eq (overlay-buffer x) (current-buffer))
16658 (>= (overlay-start x) bol)
16659 (<= (overlay-start x) eol)
16661 org-columns-overlays)))
16662 (allowed (or (org-property-get-allowed-values pom key)
16663 (and (equal
16664 (nth 4 (assoc key org-columns-current-fmt-compiled))
16665 'checkbox) '("[ ]" "[X]"))))
16666 nval)
16667 (when (equal key "ITEM")
16668 (error "Cannot edit item headline from here"))
16669 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
16670 (error "Allowed values for this property have not been defined"))
16671 (if (member key '("SCHEDULED" "DEADLINE"))
16672 (setq nval (if previous 'earlier 'later))
16673 (if previous (setq allowed (reverse allowed)))
16674 (if (member value allowed)
16675 (setq nval (car (cdr (member value allowed)))))
16676 (setq nval (or nval (car allowed)))
16677 (if (equal nval value)
16678 (error "Only one allowed value for this property")))
16679 (let ((inhibit-read-only t))
16680 (remove-text-properties (1- bol) eol '(read-only t))
16681 (unwind-protect
16682 (progn
16683 (setq org-columns-overlays
16684 (org-delete-all line-overlays org-columns-overlays))
16685 (mapc 'org-delete-overlay line-overlays)
16686 (org-columns-eval '(org-entry-put pom key nval)))
16687 (org-columns-display-here)))
16688 (move-to-column col)
16689 (if (and (org-mode-p)
16690 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16691 (org-columns-update key))))
16693 (defun org-verify-version (task)
16694 (cond
16695 ((eq task 'columns)
16696 (if (or (featurep 'xemacs)
16697 (< emacs-major-version 22))
16698 (error "Emacs 22 is required for the columns feature")))))
16700 (defun org-columns-open-link (&optional arg)
16701 (interactive "P")
16702 (let ((key (get-char-property (point) 'org-columns-key))
16703 (value (get-char-property (point) 'org-columns-value)))
16704 (org-open-link-from-string arg)))
16706 (defun org-open-link-from-string (s &optional arg)
16707 "Open a link in the string S, as if it was in Org-mode."
16708 (interactive)
16709 (with-temp-buffer
16710 (let ((org-inhibit-startup t))
16711 (org-mode)
16712 (insert s)
16713 (goto-char (point-min))
16714 (org-open-at-point arg))))
16716 (defun org-columns-get-format-and-top-level ()
16717 (let (fmt)
16718 (when (condition-case nil (org-back-to-heading) (error nil))
16719 (move-marker org-entry-property-inherited-from nil)
16720 (setq fmt (org-entry-get nil "COLUMNS" t)))
16721 (setq fmt (or fmt org-columns-default-format))
16722 (org-set-local 'org-columns-current-fmt fmt)
16723 (org-columns-compile-format fmt)
16724 (if (marker-position org-entry-property-inherited-from)
16725 (move-marker org-columns-top-level-marker
16726 org-entry-property-inherited-from)
16727 (move-marker org-columns-top-level-marker (point)))
16728 fmt))
16730 (defun org-columns ()
16731 "Turn on column view on an org-mode file."
16732 (interactive)
16733 (org-verify-version 'columns)
16734 (org-columns-remove-overlays)
16735 (move-marker org-columns-begin-marker (point))
16736 (let (beg end fmt cache maxwidths clocksump)
16737 (setq fmt (org-columns-get-format-and-top-level))
16738 (save-excursion
16739 (goto-char org-columns-top-level-marker)
16740 (setq beg (point))
16741 (unless org-columns-inhibit-recalculation
16742 (org-columns-compute-all))
16743 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
16744 (point-max)))
16745 ;; Get and cache the properties
16746 (goto-char beg)
16747 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
16748 (setq clocksump t)
16749 (save-excursion
16750 (save-restriction
16751 (narrow-to-region beg end)
16752 (org-clock-sum))))
16753 (while (re-search-forward (concat "^" outline-regexp) end t)
16754 (push (cons (org-current-line) (org-entry-properties)) cache))
16755 (when cache
16756 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16757 (org-set-local 'org-columns-current-maxwidths maxwidths)
16758 (org-columns-display-here-title)
16759 (mapc (lambda (x)
16760 (goto-line (car x))
16761 (org-columns-display-here (cdr x)))
16762 cache)))))
16764 (defun org-columns-new (&optional prop title width op fmt &rest rest)
16765 "Insert a new column, to the leeft o the current column."
16766 (interactive)
16767 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
16768 cell)
16769 (setq prop (completing-read
16770 "Property: " (mapcar 'list (org-buffer-property-keys t))
16771 nil nil prop))
16772 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
16773 (setq width (read-string "Column width: " (if width (number-to-string width))))
16774 (if (string-match "\\S-" width)
16775 (setq width (string-to-number width))
16776 (setq width nil))
16777 (setq fmt (completing-read "Summary [none]: "
16778 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox"))
16779 nil t))
16780 (if (string-match "\\S-" fmt)
16781 (setq fmt (intern fmt))
16782 (setq fmt nil))
16783 (if (eq fmt 'none) (setq fmt nil))
16784 (if editp
16785 (progn
16786 (setcar editp prop)
16787 (setcdr editp (list title width nil fmt)))
16788 (setq cell (nthcdr (1- (current-column))
16789 org-columns-current-fmt-compiled))
16790 (setcdr cell (cons (list prop title width nil fmt)
16791 (cdr cell))))
16792 (org-columns-store-format)
16793 (org-columns-redo)))
16795 (defun org-columns-delete ()
16796 "Delete the column at point from columns view."
16797 (interactive)
16798 (let* ((n (current-column))
16799 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
16800 (when (y-or-n-p
16801 (format "Are you sure you want to remove column \"%s\"? " title))
16802 (setq org-columns-current-fmt-compiled
16803 (delq (nth n org-columns-current-fmt-compiled)
16804 org-columns-current-fmt-compiled))
16805 (org-columns-store-format)
16806 (org-columns-redo)
16807 (if (>= (current-column) (length org-columns-current-fmt-compiled))
16808 (backward-char 1)))))
16810 (defun org-columns-edit-attributes ()
16811 "Edit the attributes of the current column."
16812 (interactive)
16813 (let* ((n (current-column))
16814 (info (nth n org-columns-current-fmt-compiled)))
16815 (apply 'org-columns-new info)))
16817 (defun org-columns-widen (arg)
16818 "Make the column wider by ARG characters."
16819 (interactive "p")
16820 (let* ((n (current-column))
16821 (entry (nth n org-columns-current-fmt-compiled))
16822 (width (or (nth 2 entry)
16823 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
16824 (setq width (max 1 (+ width arg)))
16825 (setcar (nthcdr 2 entry) width)
16826 (org-columns-store-format)
16827 (org-columns-redo)))
16829 (defun org-columns-narrow (arg)
16830 "Make the column nrrower by ARG characters."
16831 (interactive "p")
16832 (org-columns-widen (- arg)))
16834 (defun org-columns-move-right ()
16835 "Swap this column with the one to the right."
16836 (interactive)
16837 (let* ((n (current-column))
16838 (cell (nthcdr n org-columns-current-fmt-compiled))
16840 (when (>= n (1- (length org-columns-current-fmt-compiled)))
16841 (error "Cannot shift this column further to the right"))
16842 (setq e (car cell))
16843 (setcar cell (car (cdr cell)))
16844 (setcdr cell (cons e (cdr (cdr cell))))
16845 (org-columns-store-format)
16846 (org-columns-redo)
16847 (forward-char 1)))
16849 (defun org-columns-move-left ()
16850 "Swap this column with the one to the left."
16851 (interactive)
16852 (let* ((n (current-column)))
16853 (when (= n 0)
16854 (error "Cannot shift this column further to the left"))
16855 (backward-char 1)
16856 (org-columns-move-right)
16857 (backward-char 1)))
16859 (defun org-columns-store-format ()
16860 "Store the text version of the current columns format in appropriate place.
16861 This is either in the COLUMNS property of the node starting the current column
16862 display, or in the #+COLUMNS line of the current buffer."
16863 (let (fmt (cnt 0))
16864 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
16865 (org-set-local 'org-columns-current-fmt fmt)
16866 (if (marker-position org-columns-top-level-marker)
16867 (save-excursion
16868 (goto-char org-columns-top-level-marker)
16869 (if (and (org-at-heading-p)
16870 (org-entry-get nil "COLUMNS"))
16871 (org-entry-put nil "COLUMNS" fmt)
16872 (goto-char (point-min))
16873 ;; Overwrite all #+COLUMNS lines....
16874 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
16875 (setq cnt (1+ cnt))
16876 (replace-match (concat "#+COLUMNS: " fmt) t t))
16877 (unless (> cnt 0)
16878 (goto-char (point-min))
16879 (or (org-on-heading-p t) (outline-next-heading))
16880 (let ((inhibit-read-only t))
16881 (insert-before-markers "#+COLUMNS: " fmt "\n")))
16882 (org-set-local 'org-columns-default-format fmt))))))
16884 (defvar org-overriding-columns-format nil
16885 "When set, overrides any other definition.")
16886 (defvar org-agenda-view-columns-initially nil
16887 "When set, switch to columns view immediately after creating the agenda.")
16889 (defun org-agenda-columns ()
16890 "Turn on column view in the agenda."
16891 (interactive)
16892 (org-verify-version 'columns)
16893 (org-columns-remove-overlays)
16894 (move-marker org-columns-begin-marker (point))
16895 (let (fmt cache maxwidths m)
16896 (cond
16897 ((and (local-variable-p 'org-overriding-columns-format)
16898 org-overriding-columns-format)
16899 (setq fmt org-overriding-columns-format))
16900 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
16901 (setq fmt (org-entry-get m "COLUMNS" t)))
16902 ((and (boundp 'org-columns-current-fmt)
16903 (local-variable-p 'org-columns-current-fmt)
16904 org-columns-current-fmt)
16905 (setq fmt org-columns-current-fmt))
16906 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
16907 (setq m (get-text-property m 'org-hd-marker))
16908 (setq fmt (org-entry-get m "COLUMNS" t))))
16909 (setq fmt (or fmt org-columns-default-format))
16910 (org-set-local 'org-columns-current-fmt fmt)
16911 (org-columns-compile-format fmt)
16912 (save-excursion
16913 ;; Get and cache the properties
16914 (goto-char (point-min))
16915 (while (not (eobp))
16916 (when (setq m (or (get-text-property (point) 'org-hd-marker)
16917 (get-text-property (point) 'org-marker)))
16918 (push (cons (org-current-line) (org-entry-properties m)) cache))
16919 (beginning-of-line 2))
16920 (when cache
16921 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16922 (org-set-local 'org-columns-current-maxwidths maxwidths)
16923 (org-columns-display-here-title)
16924 (mapc (lambda (x)
16925 (goto-line (car x))
16926 (org-columns-display-here (cdr x)))
16927 cache)))))
16929 (defun org-columns-get-autowidth-alist (s cache)
16930 "Derive the maximum column widths from the format and the cache."
16931 (let ((start 0) rtn)
16932 (while (string-match (org-re "%\\([[:alpha:]]\\S-*\\)") s start)
16933 (push (cons (match-string 1 s) 1) rtn)
16934 (setq start (match-end 0)))
16935 (mapc (lambda (x)
16936 (setcdr x (apply 'max
16937 (mapcar
16938 (lambda (y)
16939 (length (or (cdr (assoc (car x) (cdr y))) " ")))
16940 cache))))
16941 rtn)
16942 rtn))
16944 (defun org-columns-compute-all ()
16945 "Compute all columns that have operators defined."
16946 (org-unmodified
16947 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
16948 (let ((columns org-columns-current-fmt-compiled) col)
16949 (while (setq col (pop columns))
16950 (when (nth 3 col)
16951 (save-excursion
16952 (org-columns-compute (car col)))))))
16954 (defun org-columns-update (property)
16955 "Recompute PROPERTY, and update the columns display for it."
16956 (org-columns-compute property)
16957 (let (fmt val pos)
16958 (save-excursion
16959 (mapc (lambda (ov)
16960 (when (equal (org-overlay-get ov 'org-columns-key) property)
16961 (setq pos (org-overlay-start ov))
16962 (goto-char pos)
16963 (when (setq val (cdr (assoc property
16964 (get-text-property
16965 (point-at-bol) 'org-summaries))))
16966 (setq fmt (org-overlay-get ov 'org-columns-format))
16967 (org-overlay-put ov 'org-columns-value val)
16968 (org-overlay-put ov 'display (format fmt val)))))
16969 org-columns-overlays))))
16971 (defun org-columns-compute (property)
16972 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
16973 (interactive)
16974 (let* ((re (concat "^" outline-regexp))
16975 (lmax 30) ; Does anyone use deeper levels???
16976 (lsum (make-vector lmax 0))
16977 (lflag (make-vector lmax nil))
16978 (level 0)
16979 (ass (assoc property org-columns-current-fmt-compiled))
16980 (format (nth 4 ass))
16981 (printf (nth 5 ass))
16982 (beg org-columns-top-level-marker)
16983 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
16984 (save-excursion
16985 ;; Find the region to compute
16986 (goto-char beg)
16987 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
16988 (goto-char end)
16989 ;; Walk the tree from the back and do the computations
16990 (while (re-search-backward re beg t)
16991 (setq sumpos (match-beginning 0)
16992 last-level level
16993 level (org-outline-level)
16994 val (org-entry-get nil property)
16995 valflag (and val (string-match "\\S-" val)))
16996 (cond
16997 ((< level last-level)
16998 ;; put the sum of lower levels here as a property
16999 (setq sum (aref lsum last-level) ; current sum
17000 flag (aref lflag last-level) ; any valid entries from children?
17001 str (org-column-number-to-string sum format printf)
17002 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
17003 useval (if flag str1 (if valflag val ""))
17004 sum-alist (get-text-property sumpos 'org-summaries))
17005 (if (assoc property sum-alist)
17006 (setcdr (assoc property sum-alist) useval)
17007 (push (cons property useval) sum-alist)
17008 (org-unmodified
17009 (add-text-properties sumpos (1+ sumpos)
17010 (list 'org-summaries sum-alist))))
17011 (when val
17012 (org-entry-put nil property (if flag str val)))
17013 ;; add current to current level accumulator
17014 (when (or flag valflag)
17015 (aset lsum level (+ (aref lsum level)
17016 (if flag sum (org-column-string-to-number
17017 (if flag str val) format))))
17018 (aset lflag level t))
17019 ;; clear accumulators for deeper levels
17020 (loop for l from (1+ level) to (1- lmax) do
17021 (aset lsum l 0)
17022 (aset lflag l nil)))
17023 ((>= level last-level)
17024 ;; add what we have here to the accumulator for this level
17025 (aset lsum level (+ (aref lsum level)
17026 (org-column-string-to-number (or val "0") format)))
17027 (and valflag (aset lflag level t)))
17028 (t (error "This should not happen")))))))
17030 (defun org-columns-redo ()
17031 "Construct the column display again."
17032 (interactive)
17033 (message "Recomputing columns...")
17034 (save-excursion
17035 (if (marker-position org-columns-begin-marker)
17036 (goto-char org-columns-begin-marker))
17037 (org-columns-remove-overlays)
17038 (if (org-mode-p)
17039 (call-interactively 'org-columns)
17040 (call-interactively 'org-agenda-columns)))
17041 (message "Recomputing columns...done"))
17043 (defun org-columns-not-in-agenda ()
17044 (if (eq major-mode 'org-agenda-mode)
17045 (error "This command is only allowed in Org-mode buffers")))
17048 (defun org-string-to-number (s)
17049 "Convert string to number, and interpret hh:mm:ss."
17050 (if (not (string-match ":" s))
17051 (string-to-number s)
17052 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17053 (while l
17054 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17055 sum)))
17057 (defun org-column-number-to-string (n fmt &optional printf)
17058 "Convert a computed column number to a string value, according to FMT."
17059 (cond
17060 ((eq fmt 'add_times)
17061 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
17062 (format "%d:%02d" h m)))
17063 ((eq fmt 'checkbox)
17064 (cond ((= n (floor n)) "[X]")
17065 ((> n 1.) "[-]")
17066 (t "[ ]")))
17067 (printf (format printf n))
17068 ((eq fmt 'currency)
17069 (format "%.2f" n))
17070 (t (number-to-string n))))
17072 (defun org-column-string-to-number (s fmt)
17073 "Convert a column value to a number that can be used for column computing."
17074 (cond
17075 ((string-match ":" s)
17076 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17077 (while l
17078 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17079 sum))
17080 ((eq fmt 'checkbox)
17081 (if (equal s "[X]") 1. 0.000001))
17082 (t (string-to-number s))))
17084 (defun org-columns-uncompile-format (cfmt)
17085 "Turn the compiled columns format back into a string representation."
17086 (let ((rtn "") e s prop title op width fmt printf)
17087 (while (setq e (pop cfmt))
17088 (setq prop (car e)
17089 title (nth 1 e)
17090 width (nth 2 e)
17091 op (nth 3 e)
17092 fmt (nth 4 e)
17093 printf (nth 5 e))
17094 (cond
17095 ((eq fmt 'add_times) (setq op ":"))
17096 ((eq fmt 'checkbox) (setq op "X"))
17097 ((eq fmt 'add_numbers) (setq op "+"))
17098 ((eq fmt 'currency) (setq op "$")))
17099 (if (and op printf) (setq op (concat op ";" printf)))
17100 (if (equal title prop) (setq title nil))
17101 (setq s (concat "%" (if width (number-to-string width))
17102 prop
17103 (if title (concat "(" title ")"))
17104 (if op (concat "{" op "}"))))
17105 (setq rtn (concat rtn " " s)))
17106 (org-trim rtn)))
17108 (defun org-columns-compile-format (fmt)
17109 "Turn a column format string into an alist of specifications.
17110 The alist has one entry for each column in the format. The elements of
17111 that list are:
17112 property the property
17113 title the title field for the columns
17114 width the column width in characters, can be nil for automatic
17115 operator the operator if any
17116 format the output format for computed results, derived from operator
17117 printf a printf format for computed values"
17118 (let ((start 0) width prop title op f printf)
17119 (setq org-columns-current-fmt-compiled nil)
17120 (while (string-match
17121 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
17122 fmt start)
17123 (setq start (match-end 0)
17124 width (match-string 1 fmt)
17125 prop (match-string 2 fmt)
17126 title (or (match-string 3 fmt) prop)
17127 op (match-string 4 fmt)
17128 f nil
17129 printf nil)
17130 (if width (setq width (string-to-number width)))
17131 (when (and op (string-match ";" op))
17132 (setq printf (substring op (match-end 0))
17133 op (substring op 0 (match-beginning 0))))
17134 (cond
17135 ((equal op "+") (setq f 'add_numbers))
17136 ((equal op "$") (setq f 'currency))
17137 ((equal op ":") (setq f 'add_times))
17138 ((equal op "X") (setq f 'checkbox)))
17139 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
17140 (setq org-columns-current-fmt-compiled
17141 (nreverse org-columns-current-fmt-compiled))))
17144 ;;; Dynamic block for Column view
17146 (defun org-columns-capture-view ()
17147 "Get the column view of the current buffer and return it as a list.
17148 The list will contains the title row and all other rows. Each row is
17149 a list of fields."
17150 (save-excursion
17151 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
17152 (n (length title)) row tbl)
17153 (goto-char (point-min))
17154 (while (re-search-forward "^\\*+ " nil t)
17155 (when (get-char-property (match-beginning 0) 'org-columns-key)
17156 (setq row nil)
17157 (loop for i from 0 to (1- n) do
17158 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
17159 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
17161 row))
17162 (setq row (nreverse row))
17163 (push row tbl)))
17164 (append (list title 'hline) (nreverse tbl)))))
17166 (defun org-dblock-write:columnview (params)
17167 "Write the column view table.
17168 PARAMS is a property list of parameters:
17170 :width enforce same column widths with <N> specifiers.
17171 :id the :ID: property of the entry where the columns view
17172 should be built, as a string. When `local', call locally.
17173 When `global' call column view with the cursor at the beginning
17174 of the buffer (usually this means that the whole buffer switches
17175 to column view).
17176 :hlines When t, insert a hline before each item. When a number, insert
17177 a hline before each level <= that number.
17178 :vlines When t, make each column a colgroup to enforce vertical lines."
17179 (let ((pos (move-marker (make-marker) (point)))
17180 (hlines (plist-get params :hlines))
17181 (vlines (plist-get params :vlines))
17182 tbl id idpos nfields tmp)
17183 (save-excursion
17184 (save-restriction
17185 (when (setq id (plist-get params :id))
17186 (cond ((not id) nil)
17187 ((eq id 'global) (goto-char (point-min)))
17188 ((eq id 'local) nil)
17189 ((setq idpos (org-find-entry-with-id id))
17190 (goto-char idpos))
17191 (t (error "Cannot find entry with :ID: %s" id))))
17192 (org-columns)
17193 (setq tbl (org-columns-capture-view))
17194 (setq nfields (length (car tbl)))
17195 (org-columns-quit)))
17196 (goto-char pos)
17197 (move-marker pos nil)
17198 (when tbl
17199 (when (plist-get params :hlines)
17200 (setq tmp nil)
17201 (while tbl
17202 (if (eq (car tbl) 'hline)
17203 (push (pop tbl) tmp)
17204 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17205 (if (and (not (eq (car tmp) 'hline))
17206 (or (eq hlines t)
17207 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17208 (push 'hline tmp)))
17209 (push (pop tbl) tmp)))
17210 (setq tbl (nreverse tmp)))
17211 (when vlines
17212 (setq tbl (mapcar (lambda (x)
17213 (if (eq 'hline x) x (cons "" x)))
17214 tbl))
17215 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17216 (setq pos (point))
17217 (insert (org-listtable-to-string tbl))
17218 (when (plist-get params :width)
17219 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17220 org-columns-current-widths "|")))
17221 (goto-char pos)
17222 (org-table-align))))
17224 (defun org-listtable-to-string (tbl)
17225 "Convert a listtable TBL to a string that contains the Org-mode table.
17226 The table still need to be alligned. The resulting string has no leading
17227 and tailing newline characters."
17228 (mapconcat
17229 (lambda (x)
17230 (cond
17231 ((listp x)
17232 (concat "|" (mapconcat 'identity x "|") "|"))
17233 ((eq x 'hline) "|-|")
17234 (t (error "Garbage in listtable: %s" x))))
17235 tbl "\n"))
17237 (defun org-insert-columns-dblock ()
17238 "Create a dynamic block capturing a column view table."
17239 (interactive)
17240 (let ((defaults '(:name "columnview" :hlines 1))
17241 (id (completing-read
17242 "Capture columns (local, global, entry with :ID: property) [local]: "
17243 (append '(("global") ("local"))
17244 (mapcar 'list (org-property-values "ID"))))))
17245 (if (equal id "") (setq id 'local))
17246 (if (equal id "global") (setq id 'global))
17247 (setq defaults (append defaults (list :id id)))
17248 (org-create-dblock defaults)
17249 (org-update-dblock)))
17251 ;;;; Timestamps
17253 (defvar org-last-changed-timestamp nil)
17254 (defvar org-time-was-given) ; dynamically scoped parameter
17255 (defvar org-end-time-was-given) ; dynamically scoped parameter
17256 (defvar org-ts-what) ; dynamically scoped parameter
17258 (defun org-time-stamp (arg)
17259 "Prompt for a date/time and insert a time stamp.
17260 If the user specifies a time like HH:MM, or if this command is called
17261 with a prefix argument, the time stamp will contain date and time.
17262 Otherwise, only the date will be included. All parts of a date not
17263 specified by the user will be filled in from the current date/time.
17264 So if you press just return without typing anything, the time stamp
17265 will represent the current date/time. If there is already a timestamp
17266 at the cursor, it will be modified."
17267 (interactive "P")
17268 (let* ((ts nil)
17269 (default-time
17270 ;; Default time is either today, or, when entering a range,
17271 ;; the range start.
17272 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17273 (save-excursion
17274 (re-search-backward
17275 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17276 (- (point) 20) t)))
17277 (apply 'encode-time (org-parse-time-string (match-string 1)))
17278 (current-time)))
17279 (default-input (and ts (org-get-compact-tod ts)))
17280 org-time-was-given org-end-time-was-given time)
17281 (cond
17282 ((and (org-at-timestamp-p)
17283 (eq last-command 'org-time-stamp)
17284 (eq this-command 'org-time-stamp))
17285 (insert "--")
17286 (setq time (let ((this-command this-command))
17287 (org-read-date arg 'totime nil nil default-time default-input)))
17288 (org-insert-time-stamp time (or org-time-was-given arg)))
17289 ((org-at-timestamp-p)
17290 (setq time (let ((this-command this-command))
17291 (org-read-date arg 'totime nil nil default-time default-input)))
17292 (when (org-at-timestamp-p) ; just to get the match data
17293 (replace-match "")
17294 (setq org-last-changed-timestamp
17295 (org-insert-time-stamp
17296 time (or org-time-was-given arg)
17297 nil nil nil (list org-end-time-was-given))))
17298 (message "Timestamp updated"))
17300 (setq time (let ((this-command this-command))
17301 (org-read-date arg 'totime nil nil default-time default-input)))
17302 (org-insert-time-stamp time (or org-time-was-given arg)
17303 nil nil nil (list org-end-time-was-given))))))
17305 ;; FIXME: can we use this for something else????
17306 ;; like computing time differences?????
17307 (defun org-get-compact-tod (s)
17308 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17309 (let* ((t1 (match-string 1 s))
17310 (h1 (string-to-number (match-string 2 s)))
17311 (m1 (string-to-number (match-string 3 s)))
17312 (t2 (and (match-end 4) (match-string 5 s)))
17313 (h2 (and t2 (string-to-number (match-string 6 s))))
17314 (m2 (and t2 (string-to-number (match-string 7 s))))
17315 dh dm)
17316 (if (not t2)
17318 (setq dh (- h2 h1) dm (- m2 m1))
17319 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17320 (concat t1 "+" (number-to-string dh)
17321 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17323 (defun org-time-stamp-inactive (&optional arg)
17324 "Insert an inactive time stamp.
17325 An inactive time stamp is enclosed in square brackets instead of angle
17326 brackets. It is inactive in the sense that it does not trigger agenda entries,
17327 does not link to the calendar and cannot be changed with the S-cursor keys.
17328 So these are more for recording a certain time/date."
17329 (interactive "P")
17330 (let (org-time-was-given org-end-time-was-given time)
17331 (setq time (org-read-date arg 'totime))
17332 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17333 nil nil (list org-end-time-was-given))))
17335 (defvar org-date-ovl (org-make-overlay 1 1))
17336 (org-overlay-put org-date-ovl 'face 'org-warning)
17337 (org-detach-overlay org-date-ovl)
17339 (defvar org-ans1) ; dynamically scoped parameter
17340 (defvar org-ans2) ; dynamically scoped parameter
17342 (defvar org-plain-time-of-day-regexp) ; defined below
17344 (defvar org-read-date-overlay nil)
17345 (defvar org-dcst nil) ; dynamically scoped
17347 (defun org-read-date (&optional with-time to-time from-string prompt
17348 default-time default-input)
17349 "Read a date, possibly a time, and make things smooth for the user.
17350 The prompt will suggest to enter an ISO date, but you can also enter anything
17351 which will at least partially be understood by `parse-time-string'.
17352 Unrecognized parts of the date will default to the current day, month, year,
17353 hour and minute. If this command is called to replace a timestamp at point,
17354 of to enter the second timestamp of a range, the default time is taken from the
17355 existing stamp. For example,
17356 3-2-5 --> 2003-02-05
17357 feb 15 --> currentyear-02-15
17358 sep 12 9 --> 2009-09-12
17359 12:45 --> today 12:45
17360 22 sept 0:34 --> currentyear-09-22 0:34
17361 12 --> currentyear-currentmonth-12
17362 Fri --> nearest Friday (today or later)
17363 etc.
17365 Furthermore you can specify a relative date by giving, as the *first* thing
17366 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17367 change in days weeks, months, years.
17368 With a single plus or minus, the date is relative to today. With a double
17369 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17370 +4d --> four days from today
17371 +4 --> same as above
17372 +2w --> two weeks from today
17373 ++5 --> five days from default date
17375 The function understands only English month and weekday abbreviations,
17376 but this can be configured with the variables `parse-time-months' and
17377 `parse-time-weekdays'.
17379 While prompting, a calendar is popped up - you can also select the
17380 date with the mouse (button 1). The calendar shows a period of three
17381 months. To scroll it to other months, use the keys `>' and `<'.
17382 If you don't like the calendar, turn it off with
17383 \(setq org-read-date-popup-calendar nil)
17385 With optional argument TO-TIME, the date will immediately be converted
17386 to an internal time.
17387 With an optional argument WITH-TIME, the prompt will suggest to also
17388 insert a time. Note that when WITH-TIME is not set, you can still
17389 enter a time, and this function will inform the calling routine about
17390 this change. The calling routine may then choose to change the format
17391 used to insert the time stamp into the buffer to include the time.
17392 With optional argument FROM-STRING, read from this string instead from
17393 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17394 the time/date that is used for everything that is not specified by the
17395 user."
17396 (require 'parse-time)
17397 (let* ((org-time-stamp-rounding-minutes
17398 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
17399 (org-dcst org-display-custom-times)
17400 (ct (org-current-time))
17401 (def (or default-time ct))
17402 (defdecode (decode-time def))
17403 (dummy (progn
17404 (when (< (nth 2 defdecode) org-extend-today-until)
17405 (setcar (nthcdr 2 defdecode) -1)
17406 (setcar (nthcdr 1 defdecode) 59)
17407 (setq def (apply 'encode-time defdecode)
17408 defdecode (decode-time def)))))
17409 (calendar-move-hook nil)
17410 (view-diary-entries-initially nil)
17411 (view-calendar-holidays-initially nil)
17412 (timestr (format-time-string
17413 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17414 (prompt (concat (if prompt (concat prompt " ") "")
17415 (format "Date+time [%s]: " timestr)))
17416 ans (org-ans0 "") org-ans1 org-ans2 final)
17418 (cond
17419 (from-string (setq ans from-string))
17420 (org-read-date-popup-calendar
17421 (save-excursion
17422 (save-window-excursion
17423 (calendar)
17424 (calendar-forward-day (- (time-to-days def)
17425 (calendar-absolute-from-gregorian
17426 (calendar-current-date))))
17427 (org-eval-in-calendar nil t)
17428 (let* ((old-map (current-local-map))
17429 (map (copy-keymap calendar-mode-map))
17430 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17431 (org-defkey map (kbd "RET") 'org-calendar-select)
17432 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17433 'org-calendar-select-mouse)
17434 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17435 'org-calendar-select-mouse)
17436 (org-defkey minibuffer-local-map [(meta shift left)]
17437 (lambda () (interactive)
17438 (org-eval-in-calendar '(calendar-backward-month 1))))
17439 (org-defkey minibuffer-local-map [(meta shift right)]
17440 (lambda () (interactive)
17441 (org-eval-in-calendar '(calendar-forward-month 1))))
17442 (org-defkey minibuffer-local-map [(meta shift up)]
17443 (lambda () (interactive)
17444 (org-eval-in-calendar '(calendar-backward-year 1))))
17445 (org-defkey minibuffer-local-map [(meta shift down)]
17446 (lambda () (interactive)
17447 (org-eval-in-calendar '(calendar-forward-year 1))))
17448 (org-defkey minibuffer-local-map [(shift up)]
17449 (lambda () (interactive)
17450 (org-eval-in-calendar '(calendar-backward-week 1))))
17451 (org-defkey minibuffer-local-map [(shift down)]
17452 (lambda () (interactive)
17453 (org-eval-in-calendar '(calendar-forward-week 1))))
17454 (org-defkey minibuffer-local-map [(shift left)]
17455 (lambda () (interactive)
17456 (org-eval-in-calendar '(calendar-backward-day 1))))
17457 (org-defkey minibuffer-local-map [(shift right)]
17458 (lambda () (interactive)
17459 (org-eval-in-calendar '(calendar-forward-day 1))))
17460 (org-defkey minibuffer-local-map ">"
17461 (lambda () (interactive)
17462 (org-eval-in-calendar '(scroll-calendar-left 1))))
17463 (org-defkey minibuffer-local-map "<"
17464 (lambda () (interactive)
17465 (org-eval-in-calendar '(scroll-calendar-right 1))))
17466 (unwind-protect
17467 (progn
17468 (use-local-map map)
17469 (add-hook 'post-command-hook 'org-read-date-display)
17470 (setq org-ans0 (read-string prompt default-input nil nil))
17471 ;; org-ans0: from prompt
17472 ;; org-ans1: from mouse click
17473 ;; org-ans2: from calendar motion
17474 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17475 (remove-hook 'post-command-hook 'org-read-date-display)
17476 (use-local-map old-map)
17477 (when org-read-date-overlay
17478 (org-delete-overlay org-read-date-overlay)
17479 (setq org-read-date-overlay nil)))))))
17481 (t ; Naked prompt only
17482 (unwind-protect
17483 (setq ans (read-string prompt default-input nil timestr))
17484 (when org-read-date-overlay
17485 (org-delete-overlay org-read-date-overlay)
17486 (setq org-read-date-overlay nil)))))
17488 (setq final (org-read-date-analyze ans def defdecode))
17490 (if to-time
17491 (apply 'encode-time final)
17492 (if (and (boundp 'org-time-was-given) org-time-was-given)
17493 (format "%04d-%02d-%02d %02d:%02d"
17494 (nth 5 final) (nth 4 final) (nth 3 final)
17495 (nth 2 final) (nth 1 final))
17496 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17497 (defvar def)
17498 (defvar defdecode)
17499 (defvar with-time)
17500 (defun org-read-date-display ()
17501 "Display the currrent date prompt interpretation in the minibuffer."
17502 (when org-read-date-display-live
17503 (when org-read-date-overlay
17504 (org-delete-overlay org-read-date-overlay))
17505 (let ((p (point)))
17506 (end-of-line 1)
17507 (while (not (equal (buffer-substring
17508 (max (point-min) (- (point) 4)) (point))
17509 " "))
17510 (insert " "))
17511 (goto-char p))
17512 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17513 " " (or org-ans1 org-ans2)))
17514 (org-end-time-was-given nil)
17515 (f (org-read-date-analyze ans def defdecode))
17516 (fmts (if org-dcst
17517 org-time-stamp-custom-formats
17518 org-time-stamp-formats))
17519 (fmt (if (or with-time
17520 (and (boundp 'org-time-was-given) org-time-was-given))
17521 (cdr fmts)
17522 (car fmts)))
17523 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
17524 (when (and org-end-time-was-given
17525 (string-match org-plain-time-of-day-regexp txt))
17526 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17527 org-end-time-was-given
17528 (substring txt (match-end 0)))))
17529 (setq org-read-date-overlay
17530 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17531 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
17533 (defun org-read-date-analyze (ans def defdecode)
17534 "Analyze the combined answer of the date prompt."
17535 ;; FIXME: cleanup and comment
17536 (let (delta deltan deltaw deltadef year month day
17537 hour minute second wday pm h2 m2 tl wday1)
17539 (when (setq delta (org-read-date-get-relative ans (current-time) def))
17540 (setq ans (replace-match "" t t ans)
17541 deltan (car delta)
17542 deltaw (nth 1 delta)
17543 deltadef (nth 2 delta)))
17545 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
17546 (when (string-match
17547 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17548 (setq year (if (match-end 2)
17549 (string-to-number (match-string 2 ans))
17550 (string-to-number (format-time-string "%Y")))
17551 month (string-to-number (match-string 3 ans))
17552 day (string-to-number (match-string 4 ans)))
17553 (if (< year 100) (setq year (+ 2000 year)))
17554 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17555 t nil ans)))
17556 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17557 ;; If there is a time with am/pm, and *no* time without it, we convert
17558 ;; so that matching will be successful.
17559 (loop for i from 1 to 2 do ; twice, for end time as well
17560 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17561 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17562 (setq hour (string-to-number (match-string 1 ans))
17563 minute (if (match-end 3)
17564 (string-to-number (match-string 3 ans))
17566 pm (equal ?p
17567 (string-to-char (downcase (match-string 4 ans)))))
17568 (if (and (= hour 12) (not pm))
17569 (setq hour 0)
17570 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17571 (setq ans (replace-match (format "%02d:%02d" hour minute)
17572 t t ans))))
17574 ;; Check if a time range is given as a duration
17575 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17576 (setq hour (string-to-number (match-string 1 ans))
17577 h2 (+ hour (string-to-number (match-string 3 ans)))
17578 minute (string-to-number (match-string 2 ans))
17579 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
17580 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17581 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
17583 ;; Check if there is a time range
17584 (when (boundp 'org-end-time-was-given)
17585 (setq org-time-was-given nil)
17586 (when (and (string-match org-plain-time-of-day-regexp ans)
17587 (match-end 8))
17588 (setq org-end-time-was-given (match-string 8 ans))
17589 (setq ans (concat (substring ans 0 (match-beginning 7))
17590 (substring ans (match-end 7))))))
17592 (setq tl (parse-time-string ans)
17593 day (or (nth 3 tl) (nth 3 defdecode))
17594 month (or (nth 4 tl)
17595 (if (and org-read-date-prefer-future
17596 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
17597 (1+ (nth 4 defdecode))
17598 (nth 4 defdecode)))
17599 year (or (nth 5 tl)
17600 (if (and org-read-date-prefer-future
17601 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
17602 (1+ (nth 5 defdecode))
17603 (nth 5 defdecode)))
17604 hour (or (nth 2 tl) (nth 2 defdecode))
17605 minute (or (nth 1 tl) (nth 1 defdecode))
17606 second (or (nth 0 tl) 0)
17607 wday (nth 6 tl))
17608 (when deltan
17609 (unless deltadef
17610 (let ((now (decode-time (current-time))))
17611 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17612 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17613 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17614 ((equal deltaw "m") (setq month (+ month deltan)))
17615 ((equal deltaw "y") (setq year (+ year deltan)))))
17616 (when (and wday (not (nth 3 tl)))
17617 ;; Weekday was given, but no day, so pick that day in the week
17618 ;; on or after the derived date.
17619 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17620 (unless (equal wday wday1)
17621 (setq day (+ day (% (- wday wday1 -7) 7)))))
17622 (if (and (boundp 'org-time-was-given)
17623 (nth 2 tl))
17624 (setq org-time-was-given t))
17625 (if (< year 100) (setq year (+ 2000 year)))
17626 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
17627 (list second minute hour day month year)))
17629 (defvar parse-time-weekdays)
17631 (defun org-read-date-get-relative (s today default)
17632 "Check string S for special relative date string.
17633 TODAY and DEFAULT are internal times, for today and for a default.
17634 Return shift list (N what def-flag)
17635 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17636 N is the number of WHATs to shift.
17637 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17638 the DEFAULT date rather than TODAY."
17639 (when (string-match
17640 (concat
17641 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
17642 "\\([0-9]+\\)?"
17643 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17644 "\\([ \t]\\|$\\)") s)
17645 (let* ((dir (if (match-end 1)
17646 (string-to-char (substring (match-string 1 s) -1))
17647 ?+))
17648 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17649 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17650 (what (if (match-end 3) (match-string 3 s) "d"))
17651 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17652 (date (if rel default today))
17653 (wday (nth 6 (decode-time date)))
17654 delta)
17655 (if wday1
17656 (progn
17657 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17658 (if (= dir ?-) (setq delta (- delta 7)))
17659 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17660 (list delta "d" rel))
17661 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17663 (defun org-eval-in-calendar (form &optional keepdate)
17664 "Eval FORM in the calendar window and return to current window.
17665 Also, store the cursor date in variable org-ans2."
17666 (let ((sw (selected-window)))
17667 (select-window (get-buffer-window "*Calendar*"))
17668 (eval form)
17669 (when (and (not keepdate) (calendar-cursor-to-date))
17670 (let* ((date (calendar-cursor-to-date))
17671 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17672 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17673 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17674 (select-window sw)))
17676 ; ;; Update the prompt to show new default date
17677 ; (save-excursion
17678 ; (goto-char (point-min))
17679 ; (when (and org-ans2
17680 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
17681 ; (get-text-property (match-end 0) 'field))
17682 ; (let ((inhibit-read-only t))
17683 ; (replace-match (concat "[" org-ans2 "]") t t)
17684 ; (add-text-properties (point-min) (1+ (match-end 0))
17685 ; (text-properties-at (1+ (point-min)))))))))
17687 (defun org-calendar-select ()
17688 "Return to `org-read-date' with the date currently selected.
17689 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17690 (interactive)
17691 (when (calendar-cursor-to-date)
17692 (let* ((date (calendar-cursor-to-date))
17693 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17694 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17695 (if (active-minibuffer-window) (exit-minibuffer))))
17697 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17698 "Insert a date stamp for the date given by the internal TIME.
17699 WITH-HM means, use the stamp format that includes the time of the day.
17700 INACTIVE means use square brackets instead of angular ones, so that the
17701 stamp will not contribute to the agenda.
17702 PRE and POST are optional strings to be inserted before and after the
17703 stamp.
17704 The command returns the inserted time stamp."
17705 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17706 stamp)
17707 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17708 (insert-before-markers (or pre ""))
17709 (insert-before-markers (setq stamp (format-time-string fmt time)))
17710 (when (listp extra)
17711 (setq extra (car extra))
17712 (if (and (stringp extra)
17713 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17714 (setq extra (format "-%02d:%02d"
17715 (string-to-number (match-string 1 extra))
17716 (string-to-number (match-string 2 extra))))
17717 (setq extra nil)))
17718 (when extra
17719 (backward-char 1)
17720 (insert-before-markers extra)
17721 (forward-char 1))
17722 (insert-before-markers (or post ""))
17723 stamp))
17725 (defun org-toggle-time-stamp-overlays ()
17726 "Toggle the use of custom time stamp formats."
17727 (interactive)
17728 (setq org-display-custom-times (not org-display-custom-times))
17729 (unless org-display-custom-times
17730 (let ((p (point-min)) (bmp (buffer-modified-p)))
17731 (while (setq p (next-single-property-change p 'display))
17732 (if (and (get-text-property p 'display)
17733 (eq (get-text-property p 'face) 'org-date))
17734 (remove-text-properties
17735 p (setq p (next-single-property-change p 'display))
17736 '(display t))))
17737 (set-buffer-modified-p bmp)))
17738 (if (featurep 'xemacs)
17739 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17740 (org-restart-font-lock)
17741 (setq org-table-may-need-update t)
17742 (if org-display-custom-times
17743 (message "Time stamps are overlayed with custom format")
17744 (message "Time stamp overlays removed")))
17746 (defun org-display-custom-time (beg end)
17747 "Overlay modified time stamp format over timestamp between BED and END."
17748 (let* ((ts (buffer-substring beg end))
17749 t1 w1 with-hm tf time str w2 (off 0))
17750 (save-match-data
17751 (setq t1 (org-parse-time-string ts t))
17752 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
17753 (setq off (- (match-end 0) (match-beginning 0)))))
17754 (setq end (- end off))
17755 (setq w1 (- end beg)
17756 with-hm (and (nth 1 t1) (nth 2 t1))
17757 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17758 time (org-fix-decoded-time t1)
17759 str (org-add-props
17760 (format-time-string
17761 (substring tf 1 -1) (apply 'encode-time time))
17762 nil 'mouse-face 'highlight)
17763 w2 (length str))
17764 (if (not (= w2 w1))
17765 (add-text-properties (1+ beg) (+ 2 beg)
17766 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17767 (if (featurep 'xemacs)
17768 (progn
17769 (put-text-property beg end 'invisible t)
17770 (put-text-property beg end 'end-glyph (make-glyph str)))
17771 (put-text-property beg end 'display str))))
17773 (defun org-translate-time (string)
17774 "Translate all timestamps in STRING to custom format.
17775 But do this only if the variable `org-display-custom-times' is set."
17776 (when org-display-custom-times
17777 (save-match-data
17778 (let* ((start 0)
17779 (re org-ts-regexp-both)
17780 t1 with-hm inactive tf time str beg end)
17781 (while (setq start (string-match re string start))
17782 (setq beg (match-beginning 0)
17783 end (match-end 0)
17784 t1 (save-match-data
17785 (org-parse-time-string (substring string beg end) t))
17786 with-hm (and (nth 1 t1) (nth 2 t1))
17787 inactive (equal (substring string beg (1+ beg)) "[")
17788 tf (funcall (if with-hm 'cdr 'car)
17789 org-time-stamp-custom-formats)
17790 time (org-fix-decoded-time t1)
17791 str (format-time-string
17792 (concat
17793 (if inactive "[" "<") (substring tf 1 -1)
17794 (if inactive "]" ">"))
17795 (apply 'encode-time time))
17796 string (replace-match str t t string)
17797 start (+ start (length str)))))))
17798 string)
17800 (defun org-fix-decoded-time (time)
17801 "Set 0 instead of nil for the first 6 elements of time.
17802 Don't touch the rest."
17803 (let ((n 0))
17804 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17806 (defun org-days-to-time (timestamp-string)
17807 "Difference between TIMESTAMP-STRING and now in days."
17808 (- (time-to-days (org-time-string-to-time timestamp-string))
17809 (time-to-days (current-time))))
17811 (defun org-deadline-close (timestamp-string &optional ndays)
17812 "Is the time in TIMESTAMP-STRING close to the current date?"
17813 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17814 (and (< (org-days-to-time timestamp-string) ndays)
17815 (not (org-entry-is-done-p))))
17817 (defun org-get-wdays (ts)
17818 "Get the deadline lead time appropriate for timestring TS."
17819 (cond
17820 ((<= org-deadline-warning-days 0)
17821 ;; 0 or negative, enforce this value no matter what
17822 (- org-deadline-warning-days))
17823 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
17824 ;; lead time is specified.
17825 (floor (* (string-to-number (match-string 1 ts))
17826 (cdr (assoc (match-string 2 ts)
17827 '(("d" . 1) ("w" . 7)
17828 ("m" . 30.4) ("y" . 365.25)))))))
17829 ;; go for the default.
17830 (t org-deadline-warning-days)))
17832 (defun org-calendar-select-mouse (ev)
17833 "Return to `org-read-date' with the date currently selected.
17834 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17835 (interactive "e")
17836 (mouse-set-point ev)
17837 (when (calendar-cursor-to-date)
17838 (let* ((date (calendar-cursor-to-date))
17839 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17840 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17841 (if (active-minibuffer-window) (exit-minibuffer))))
17843 (defun org-check-deadlines (ndays)
17844 "Check if there are any deadlines due or past due.
17845 A deadline is considered due if it happens within `org-deadline-warning-days'
17846 days from today's date. If the deadline appears in an entry marked DONE,
17847 it is not shown. The prefix arg NDAYS can be used to test that many
17848 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17849 (interactive "P")
17850 (let* ((org-warn-days
17851 (cond
17852 ((equal ndays '(4)) 100000)
17853 (ndays (prefix-numeric-value ndays))
17854 (t (abs org-deadline-warning-days))))
17855 (case-fold-search nil)
17856 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17857 (callback
17858 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17860 (message "%d deadlines past-due or due within %d days"
17861 (org-occur regexp nil callback)
17862 org-warn-days)))
17864 (defun org-check-before-date (date)
17865 "Check if there are deadlines or scheduled entries before DATE."
17866 (interactive (list (org-read-date)))
17867 (let ((case-fold-search nil)
17868 (regexp (concat "\\<\\(" org-deadline-string
17869 "\\|" org-scheduled-string
17870 "\\) *<\\([^>]+\\)>"))
17871 (callback
17872 (lambda () (time-less-p
17873 (org-time-string-to-time (match-string 2))
17874 (org-time-string-to-time date)))))
17875 (message "%d entries before %s"
17876 (org-occur regexp nil callback) date)))
17878 (defun org-evaluate-time-range (&optional to-buffer)
17879 "Evaluate a time range by computing the difference between start and end.
17880 Normally the result is just printed in the echo area, but with prefix arg
17881 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17882 If the time range is actually in a table, the result is inserted into the
17883 next column.
17884 For time difference computation, a year is assumed to be exactly 365
17885 days in order to avoid rounding problems."
17886 (interactive "P")
17888 (org-clock-update-time-maybe)
17889 (save-excursion
17890 (unless (org-at-date-range-p t)
17891 (goto-char (point-at-bol))
17892 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17893 (if (not (org-at-date-range-p t))
17894 (error "Not at a time-stamp range, and none found in current line")))
17895 (let* ((ts1 (match-string 1))
17896 (ts2 (match-string 2))
17897 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17898 (match-end (match-end 0))
17899 (time1 (org-time-string-to-time ts1))
17900 (time2 (org-time-string-to-time ts2))
17901 (t1 (time-to-seconds time1))
17902 (t2 (time-to-seconds time2))
17903 (diff (abs (- t2 t1)))
17904 (negative (< (- t2 t1) 0))
17905 ;; (ys (floor (* 365 24 60 60)))
17906 (ds (* 24 60 60))
17907 (hs (* 60 60))
17908 (fy "%dy %dd %02d:%02d")
17909 (fy1 "%dy %dd")
17910 (fd "%dd %02d:%02d")
17911 (fd1 "%dd")
17912 (fh "%02d:%02d")
17913 y d h m align)
17914 (if havetime
17915 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17917 d (floor (/ diff ds)) diff (mod diff ds)
17918 h (floor (/ diff hs)) diff (mod diff hs)
17919 m (floor (/ diff 60)))
17920 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17922 d (floor (+ (/ diff ds) 0.5))
17923 h 0 m 0))
17924 (if (not to-buffer)
17925 (message "%s" (org-make-tdiff-string y d h m))
17926 (if (org-at-table-p)
17927 (progn
17928 (goto-char match-end)
17929 (setq align t)
17930 (and (looking-at " *|") (goto-char (match-end 0))))
17931 (goto-char match-end))
17932 (if (looking-at
17933 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17934 (replace-match ""))
17935 (if negative (insert " -"))
17936 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17937 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17938 (insert " " (format fh h m))))
17939 (if align (org-table-align))
17940 (message "Time difference inserted")))))
17942 (defun org-make-tdiff-string (y d h m)
17943 (let ((fmt "")
17944 (l nil))
17945 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17946 l (push y l)))
17947 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17948 l (push d l)))
17949 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17950 l (push h l)))
17951 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17952 l (push m l)))
17953 (apply 'format fmt (nreverse l))))
17955 (defun org-time-string-to-time (s)
17956 (apply 'encode-time (org-parse-time-string s)))
17958 (defun org-time-string-to-absolute (s &optional daynr prefer)
17959 "Convert a time stamp to an absolute day number.
17960 If there is a specifyer for a cyclic time stamp, get the closest date to
17961 DAYNR."
17962 (cond
17963 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17964 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17965 daynr
17966 (+ daynr 1000)))
17967 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
17968 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17969 (time-to-days (current-time))) (match-string 0 s)
17970 prefer))
17971 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
17973 (defun org-time-from-absolute (d)
17974 "Return the time corresponding to date D.
17975 D may be an absolute day number, or a calendar-type list (month day year)."
17976 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17977 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17979 (defun org-calendar-holiday ()
17980 "List of holidays, for Diary display in Org-mode."
17981 (require 'holidays)
17982 (let ((hl (funcall
17983 (if (fboundp 'calendar-check-holidays)
17984 'calendar-check-holidays 'check-calendar-holidays) date)))
17985 (if hl (mapconcat 'identity hl "; "))))
17987 (defun org-diary-sexp-entry (sexp entry date)
17988 "Process a SEXP diary ENTRY for DATE."
17989 (require 'diary-lib)
17990 (let ((result (if calendar-debug-sexp
17991 (let ((stack-trace-on-error t))
17992 (eval (car (read-from-string sexp))))
17993 (condition-case nil
17994 (eval (car (read-from-string sexp)))
17995 (error
17996 (beep)
17997 (message "Bad sexp at line %d in %s: %s"
17998 (org-current-line)
17999 (buffer-file-name) sexp)
18000 (sleep-for 2))))))
18001 (cond ((stringp result) result)
18002 ((and (consp result)
18003 (stringp (cdr result))) (cdr result))
18004 (result entry)
18005 (t nil))))
18007 (defun org-diary-to-ical-string (frombuf)
18008 "Get iCalendar entries from diary entries in buffer FROMBUF.
18009 This uses the icalendar.el library."
18010 (let* ((tmpdir (if (featurep 'xemacs)
18011 (temp-directory)
18012 temporary-file-directory))
18013 (tmpfile (make-temp-name
18014 (expand-file-name "orgics" tmpdir)))
18015 buf rtn b e)
18016 (save-excursion
18017 (set-buffer frombuf)
18018 (icalendar-export-region (point-min) (point-max) tmpfile)
18019 (setq buf (find-buffer-visiting tmpfile))
18020 (set-buffer buf)
18021 (goto-char (point-min))
18022 (if (re-search-forward "^BEGIN:VEVENT" nil t)
18023 (setq b (match-beginning 0)))
18024 (goto-char (point-max))
18025 (if (re-search-backward "^END:VEVENT" nil t)
18026 (setq e (match-end 0)))
18027 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
18028 (kill-buffer buf)
18029 (kill-buffer frombuf)
18030 (delete-file tmpfile)
18031 rtn))
18033 (defun org-closest-date (start current change prefer)
18034 "Find the date closest to CURRENT that is consistent with START and CHANGE.
18035 When PREFER is `past' return a date that is either CURRENT or past.
18036 When PREFER is `future', return a date that is either CURRENT or future."
18037 ;; Make the proper lists from the dates
18038 (catch 'exit
18039 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
18040 dn dw sday cday n1 n2
18041 d m y y1 y2 date1 date2 nmonths nm ny m2)
18043 (setq start (org-date-to-gregorian start)
18044 current (org-date-to-gregorian
18045 (if org-agenda-repeating-timestamp-show-all
18046 current
18047 (time-to-days (current-time))))
18048 sday (calendar-absolute-from-gregorian start)
18049 cday (calendar-absolute-from-gregorian current))
18051 (if (<= cday sday) (throw 'exit sday))
18053 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
18054 (setq dn (string-to-number (match-string 1 change))
18055 dw (cdr (assoc (match-string 2 change) a1)))
18056 (error "Invalid change specifyer: %s" change))
18057 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
18058 (cond
18059 ((eq dw 'day)
18060 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
18061 n2 (+ n1 dn)))
18062 ((eq dw 'year)
18063 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
18064 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
18065 (setq date1 (list m d y1)
18066 n1 (calendar-absolute-from-gregorian date1)
18067 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
18068 n2 (calendar-absolute-from-gregorian date2)))
18069 ((eq dw 'month)
18070 ;; approx number of month between the tow dates
18071 (setq nmonths (floor (/ (- cday sday) 30.436875)))
18072 ;; How often does dn fit in there?
18073 (setq d (nth 1 start) m (car start) y (nth 2 start)
18074 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
18075 m (+ m nm)
18076 ny (floor (/ m 12))
18077 y (+ y ny)
18078 m (- m (* ny 12)))
18079 (while (> m 12) (setq m (- m 12) y (1+ y)))
18080 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
18081 (setq m2 (+ m dn) y2 y)
18082 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18083 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
18084 (while (< n2 cday)
18085 (setq n1 n2 m m2 y y2)
18086 (setq m2 (+ m dn) y2 y)
18087 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18088 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
18090 (if org-agenda-repeating-timestamp-show-all
18091 (cond
18092 ((eq prefer 'past) n1)
18093 ((eq prefer 'future) (if (= cday n1) n1 n2))
18094 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
18095 (cond
18096 ((eq prefer 'past) n1)
18097 ((eq prefer 'future) (if (= cday n1) n1 n2))
18098 (t (if (= cday n1) n1 n2)))))))
18100 (defun org-date-to-gregorian (date)
18101 "Turn any specification of DATE into a gregorian date for the calendar."
18102 (cond ((integerp date) (calendar-gregorian-from-absolute date))
18103 ((and (listp date) (= (length date) 3)) date)
18104 ((stringp date)
18105 (setq date (org-parse-time-string date))
18106 (list (nth 4 date) (nth 3 date) (nth 5 date)))
18107 ((listp date)
18108 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
18110 (defun org-parse-time-string (s &optional nodefault)
18111 "Parse the standard Org-mode time string.
18112 This should be a lot faster than the normal `parse-time-string'.
18113 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18114 hour and minute fields will be nil if not given."
18115 (if (string-match org-ts-regexp0 s)
18116 (list 0
18117 (if (or (match-beginning 8) (not nodefault))
18118 (string-to-number (or (match-string 8 s) "0")))
18119 (if (or (match-beginning 7) (not nodefault))
18120 (string-to-number (or (match-string 7 s) "0")))
18121 (string-to-number (match-string 4 s))
18122 (string-to-number (match-string 3 s))
18123 (string-to-number (match-string 2 s))
18124 nil nil nil)
18125 (make-list 9 0)))
18127 (defun org-timestamp-up (&optional arg)
18128 "Increase the date item at the cursor by one.
18129 If the cursor is on the year, change the year. If it is on the month or
18130 the day, change that.
18131 With prefix ARG, change by that many units."
18132 (interactive "p")
18133 (org-timestamp-change (prefix-numeric-value arg)))
18135 (defun org-timestamp-down (&optional arg)
18136 "Decrease the date item at the cursor by one.
18137 If the cursor is on the year, change the year. If it is on the month or
18138 the day, change that.
18139 With prefix ARG, change by that many units."
18140 (interactive "p")
18141 (org-timestamp-change (- (prefix-numeric-value arg))))
18143 (defun org-timestamp-up-day (&optional arg)
18144 "Increase the date in the time stamp by one day.
18145 With prefix ARG, change that many days."
18146 (interactive "p")
18147 (if (and (not (org-at-timestamp-p t))
18148 (org-on-heading-p))
18149 (org-todo 'up)
18150 (org-timestamp-change (prefix-numeric-value arg) 'day)))
18152 (defun org-timestamp-down-day (&optional arg)
18153 "Decrease the date in the time stamp by one day.
18154 With prefix ARG, change that many days."
18155 (interactive "p")
18156 (if (and (not (org-at-timestamp-p t))
18157 (org-on-heading-p))
18158 (org-todo 'down)
18159 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
18161 (defsubst org-pos-in-match-range (pos n)
18162 (and (match-beginning n)
18163 (<= (match-beginning n) pos)
18164 (>= (match-end n) pos)))
18166 (defun org-at-timestamp-p (&optional inactive-ok)
18167 "Determine if the cursor is in or at a timestamp."
18168 (interactive)
18169 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18170 (pos (point))
18171 (ans (or (looking-at tsr)
18172 (save-excursion
18173 (skip-chars-backward "^[<\n\r\t")
18174 (if (> (point) (point-min)) (backward-char 1))
18175 (and (looking-at tsr)
18176 (> (- (match-end 0) pos) -1))))))
18177 (and ans
18178 (boundp 'org-ts-what)
18179 (setq org-ts-what
18180 (cond
18181 ((= pos (match-beginning 0)) 'bracket)
18182 ((= pos (1- (match-end 0))) 'bracket)
18183 ((org-pos-in-match-range pos 2) 'year)
18184 ((org-pos-in-match-range pos 3) 'month)
18185 ((org-pos-in-match-range pos 7) 'hour)
18186 ((org-pos-in-match-range pos 8) 'minute)
18187 ((or (org-pos-in-match-range pos 4)
18188 (org-pos-in-match-range pos 5)) 'day)
18189 ((and (> pos (or (match-end 8) (match-end 5)))
18190 (< pos (match-end 0)))
18191 (- pos (or (match-end 8) (match-end 5))))
18192 (t 'day))))
18193 ans))
18195 (defun org-toggle-timestamp-type ()
18197 (interactive)
18198 (when (org-at-timestamp-p t)
18199 (save-excursion
18200 (goto-char (match-beginning 0))
18201 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18202 (goto-char (1- (match-end 0)))
18203 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18204 (message "Timestamp is now %sactive"
18205 (if (equal (char-before) ?>) "in" ""))))
18207 (defun org-timestamp-change (n &optional what)
18208 "Change the date in the time stamp at point.
18209 The date will be changed by N times WHAT. WHAT can be `day', `month',
18210 `year', `minute', `second'. If WHAT is not given, the cursor position
18211 in the timestamp determines what will be changed."
18212 (let ((pos (point))
18213 with-hm inactive
18214 org-ts-what
18215 extra
18216 ts time time0)
18217 (if (not (org-at-timestamp-p t))
18218 (error "Not at a timestamp"))
18219 (if (and (not what) (eq org-ts-what 'bracket))
18220 (org-toggle-timestamp-type)
18221 (if (and (not what) (not (eq org-ts-what 'day))
18222 org-display-custom-times
18223 (get-text-property (point) 'display)
18224 (not (get-text-property (1- (point)) 'display)))
18225 (setq org-ts-what 'day))
18226 (setq org-ts-what (or what org-ts-what)
18227 inactive (= (char-after (match-beginning 0)) ?\[)
18228 ts (match-string 0))
18229 (replace-match "")
18230 (if (string-match
18231 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
18233 (setq extra (match-string 1 ts)))
18234 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18235 (setq with-hm t))
18236 (setq time0 (org-parse-time-string ts))
18237 (setq time
18238 (encode-time (or (car time0) 0)
18239 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18240 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18241 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18242 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18243 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18244 (nthcdr 6 time0)))
18245 (when (integerp org-ts-what)
18246 (setq extra (org-modify-ts-extra extra org-ts-what n)))
18247 (if (eq what 'calendar)
18248 (let ((cal-date (org-get-date-from-calendar)))
18249 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18250 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18251 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18252 (setcar time0 (or (car time0) 0))
18253 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18254 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18255 (setq time (apply 'encode-time time0))))
18256 (setq org-last-changed-timestamp
18257 (org-insert-time-stamp time with-hm inactive nil nil extra))
18258 (org-clock-update-time-maybe)
18259 (goto-char pos)
18260 ;; Try to recenter the calendar window, if any
18261 (if (and org-calendar-follow-timestamp-change
18262 (get-buffer-window "*Calendar*" t)
18263 (memq org-ts-what '(day month year)))
18264 (org-recenter-calendar (time-to-days time))))))
18266 ;; FIXME: does not yet work for lead times
18267 (defun org-modify-ts-extra (s pos n)
18268 "Change the different parts of the lead-time and repeat fields in timestamp."
18269 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18270 ng h m new)
18271 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18272 (cond
18273 ((or (org-pos-in-match-range pos 2)
18274 (org-pos-in-match-range pos 3))
18275 (setq m (string-to-number (match-string 3 s))
18276 h (string-to-number (match-string 2 s)))
18277 (if (org-pos-in-match-range pos 2)
18278 (setq h (+ h n))
18279 (setq m (+ m n)))
18280 (if (< m 0) (setq m (+ m 60) h (1- h)))
18281 (if (> m 59) (setq m (- m 60) h (1+ h)))
18282 (setq h (min 24 (max 0 h)))
18283 (setq ng 1 new (format "-%02d:%02d" h m)))
18284 ((org-pos-in-match-range pos 6)
18285 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18286 ((org-pos-in-match-range pos 5)
18287 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
18289 (when ng
18290 (setq s (concat
18291 (substring s 0 (match-beginning ng))
18293 (substring s (match-end ng))))))
18296 (defun org-recenter-calendar (date)
18297 "If the calendar is visible, recenter it to DATE."
18298 (let* ((win (selected-window))
18299 (cwin (get-buffer-window "*Calendar*" t))
18300 (calendar-move-hook nil))
18301 (when cwin
18302 (select-window cwin)
18303 (calendar-goto-date (if (listp date) date
18304 (calendar-gregorian-from-absolute date)))
18305 (select-window win))))
18307 (defun org-goto-calendar (&optional arg)
18308 "Go to the Emacs calendar at the current date.
18309 If there is a time stamp in the current line, go to that date.
18310 A prefix ARG can be used to force the current date."
18311 (interactive "P")
18312 (let ((tsr org-ts-regexp) diff
18313 (calendar-move-hook nil)
18314 (view-calendar-holidays-initially nil)
18315 (view-diary-entries-initially nil))
18316 (if (or (org-at-timestamp-p)
18317 (save-excursion
18318 (beginning-of-line 1)
18319 (looking-at (concat ".*" tsr))))
18320 (let ((d1 (time-to-days (current-time)))
18321 (d2 (time-to-days
18322 (org-time-string-to-time (match-string 1)))))
18323 (setq diff (- d2 d1))))
18324 (calendar)
18325 (calendar-goto-today)
18326 (if (and diff (not arg)) (calendar-forward-day diff))))
18328 (defun org-get-date-from-calendar ()
18329 "Return a list (month day year) of date at point in calendar."
18330 (with-current-buffer "*Calendar*"
18331 (save-match-data
18332 (calendar-cursor-to-date))))
18334 (defun org-date-from-calendar ()
18335 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18336 If there is already a time stamp at the cursor position, update it."
18337 (interactive)
18338 (if (org-at-timestamp-p t)
18339 (org-timestamp-change 0 'calendar)
18340 (let ((cal-date (org-get-date-from-calendar)))
18341 (org-insert-time-stamp
18342 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18344 ;; Make appt aware of appointments from the agenda
18345 ;;;###autoload
18346 (defun org-agenda-to-appt (&optional filter)
18347 "Activate appointments found in `org-agenda-files'.
18348 When prefixed, prompt for a regular expression and use it as a
18349 filter: only add entries if they match this regular expression.
18351 FILTER can be a string. In this case, use this string as a
18352 regular expression to filter results.
18354 FILTER can also be an alist, with the car of each cell being
18355 either 'headline or 'category. For example:
18357 '((headline \"IMPORTANT\")
18358 (category \"Work\"))
18360 will only add headlines containing IMPORTANT or headlines
18361 belonging to the category \"Work\"."
18362 (interactive "P")
18363 (require 'calendar)
18364 (if (equal filter '(4))
18365 (setq filter (read-from-minibuffer "Regexp filter: ")))
18366 (let* ((cnt 0) ; count added events
18367 (org-agenda-new-buffers nil)
18368 (today (org-date-to-gregorian
18369 (time-to-days (current-time))))
18370 (files (org-agenda-files)) entries file)
18371 ;; Get all entries which may contain an appt
18372 (while (setq file (pop files))
18373 (setq entries
18374 (append entries
18375 (org-agenda-get-day-entries
18376 file today
18377 :timestamp :scheduled :deadline))))
18378 (setq entries (delq nil entries))
18379 ;; Map thru entries and find if they pass thru the filter
18380 (mapc
18381 (lambda(x)
18382 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18383 (cat (get-text-property 1 'org-category x))
18384 (tod (get-text-property 1 'time-of-day x))
18385 (ok (or (null filter)
18386 (and (stringp filter) (string-match filter evt))
18387 (and (listp filter)
18388 (or (string-match
18389 (cadr (assoc 'category filter)) cat)
18390 (string-match
18391 (cadr (assoc 'headline filter)) evt))))))
18392 ;; FIXME: Shall we remove text-properties for the appt text?
18393 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18394 (when (and ok tod)
18395 (setq tod (number-to-string tod)
18396 tod (when (string-match
18397 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18398 (concat (match-string 1 tod) ":"
18399 (match-string 2 tod))))
18400 (appt-add tod evt)
18401 (setq cnt (1+ cnt))))) entries)
18402 (org-release-buffers org-agenda-new-buffers)
18403 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" ""))))
18405 ;;; The clock for measuring work time.
18407 (defvar org-mode-line-string "")
18408 (put 'org-mode-line-string 'risky-local-variable t)
18410 (defvar org-mode-line-timer nil)
18411 (defvar org-clock-heading "")
18412 (defvar org-clock-start-time "")
18414 (defun org-update-mode-line ()
18415 (let* ((delta (- (time-to-seconds (current-time))
18416 (time-to-seconds org-clock-start-time)))
18417 (h (floor delta 3600))
18418 (m (floor (- delta (* 3600 h)) 60)))
18419 (setq org-mode-line-string
18420 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18421 'help-echo "Org-mode clock is running"))
18422 (force-mode-line-update)))
18424 (defvar org-clock-marker (make-marker)
18425 "Marker recording the last clock-in.")
18426 (defvar org-clock-mode-line-entry nil
18427 "Information for the modeline about the running clock.")
18429 (defun org-clock-in ()
18430 "Start the clock on the current item.
18431 If necessary, clock-out of the currently active clock."
18432 (interactive)
18433 (org-clock-out t)
18434 (let (ts)
18435 (save-excursion
18436 (org-back-to-heading t)
18437 (when (and org-clock-in-switch-to-state
18438 (not (looking-at (concat outline-regexp "[ \t]*"
18439 org-clock-in-switch-to-state
18440 "\\>"))))
18441 (org-todo org-clock-in-switch-to-state))
18442 (if (and org-clock-heading-function
18443 (functionp org-clock-heading-function))
18444 (setq org-clock-heading (funcall org-clock-heading-function))
18445 (if (looking-at org-complex-heading-regexp)
18446 (setq org-clock-heading (match-string 4))
18447 (setq org-clock-heading "???")))
18448 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18449 (org-clock-find-position)
18451 (insert "\n") (backward-char 1)
18452 (indent-relative)
18453 (insert org-clock-string " ")
18454 (setq org-clock-start-time (current-time))
18455 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18456 (move-marker org-clock-marker (point) (buffer-base-buffer))
18457 (or global-mode-string (setq global-mode-string '("")))
18458 (or (memq 'org-mode-line-string global-mode-string)
18459 (setq global-mode-string
18460 (append global-mode-string '(org-mode-line-string))))
18461 (org-update-mode-line)
18462 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18463 (message "Clock started at %s" ts))))
18465 (defun org-clock-find-position ()
18466 "Find the location where the next clock line should be inserted."
18467 (org-back-to-heading t)
18468 (catch 'exit
18469 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
18470 (re (concat "^[ \t]*" org-clock-string))
18471 (cnt 0)
18472 first last)
18473 (goto-char beg)
18474 (when (eobp) (newline) (setq end (max (point) end)))
18475 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
18476 ;; we seem to have a CLOCK drawer, so go there.
18477 (beginning-of-line 2)
18478 (throw 'exit t))
18479 ;; Lets count the CLOCK lines
18480 (goto-char beg)
18481 (while (re-search-forward re end t)
18482 (setq first (or first (match-beginning 0))
18483 last (match-beginning 0)
18484 cnt (1+ cnt)))
18485 (when (and (integerp org-clock-into-drawer)
18486 (>= (1+ cnt) org-clock-into-drawer))
18487 ;; Wrap current entries into a new drawer
18488 (goto-char last)
18489 (beginning-of-line 2)
18490 (if (org-at-item-p) (org-end-of-item))
18491 (insert ":END:\n")
18492 (beginning-of-line 0)
18493 (org-indent-line-function)
18494 (goto-char first)
18495 (insert ":CLOCK:\n")
18496 (beginning-of-line 0)
18497 (org-indent-line-function)
18498 (org-flag-drawer t)
18499 (beginning-of-line 2)
18500 (throw 'exit nil))
18502 (goto-char beg)
18503 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18504 (not (equal (match-string 1) org-clock-string)))
18505 ;; Planning info, skip to after it
18506 (beginning-of-line 2)
18507 (or (bolp) (newline)))
18508 (when (eq t org-clock-into-drawer)
18509 (insert ":CLOCK:\n:END:\n")
18510 (beginning-of-line -1)
18511 (org-indent-line-function)
18512 (org-flag-drawer t)
18513 (beginning-of-line 2)
18514 (org-indent-line-function)))))
18516 (defun org-clock-out (&optional fail-quietly)
18517 "Stop the currently running clock.
18518 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
18519 (interactive)
18520 (catch 'exit
18521 (if (not (marker-buffer org-clock-marker))
18522 (if fail-quietly (throw 'exit t) (error "No active clock")))
18523 (let (ts te s h m)
18524 (save-excursion
18525 (set-buffer (marker-buffer org-clock-marker))
18526 (goto-char org-clock-marker)
18527 (beginning-of-line 1)
18528 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18529 (equal (match-string 1) org-clock-string))
18530 (setq ts (match-string 2))
18531 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
18532 (goto-char (match-end 0))
18533 (delete-region (point) (point-at-eol))
18534 (insert "--")
18535 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18536 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
18537 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
18538 h (floor (/ s 3600))
18539 s (- s (* 3600 h))
18540 m (floor (/ s 60))
18541 s (- s (* 60 s)))
18542 (insert " => " (format "%2d:%02d" h m))
18543 (move-marker org-clock-marker nil)
18544 (let* ((logging (save-match-data (org-entry-get nil "LOGGING" t)))
18545 (org-log-done (org-parse-local-options logging 'org-log-done))
18546 (org-log-repeat (org-parse-local-options logging 'org-log-repeat)))
18547 (org-add-log-maybe 'clock-out))
18548 (when org-mode-line-timer
18549 (cancel-timer org-mode-line-timer)
18550 (setq org-mode-line-timer nil))
18551 (setq global-mode-string
18552 (delq 'org-mode-line-string global-mode-string))
18553 (force-mode-line-update)
18554 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
18556 (defun org-clock-cancel ()
18557 "Cancel the running clock be removing the start timestamp."
18558 (interactive)
18559 (if (not (marker-buffer org-clock-marker))
18560 (error "No active clock"))
18561 (save-excursion
18562 (set-buffer (marker-buffer org-clock-marker))
18563 (goto-char org-clock-marker)
18564 (delete-region (1- (point-at-bol)) (point-at-eol)))
18565 (setq global-mode-string
18566 (delq 'org-mode-line-string global-mode-string))
18567 (force-mode-line-update)
18568 (message "Clock canceled"))
18570 (defun org-clock-goto (&optional delete-windows)
18571 "Go to the currently clocked-in entry."
18572 (interactive "P")
18573 (if (not (marker-buffer org-clock-marker))
18574 (error "No active clock"))
18575 (switch-to-buffer-other-window
18576 (marker-buffer org-clock-marker))
18577 (if delete-windows (delete-other-windows))
18578 (goto-char org-clock-marker)
18579 (org-show-entry)
18580 (org-back-to-heading)
18581 (recenter))
18583 (defvar org-clock-file-total-minutes nil
18584 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
18585 (make-variable-buffer-local 'org-clock-file-total-minutes)
18587 (defun org-clock-sum (&optional tstart tend)
18588 "Sum the times for each subtree.
18589 Puts the resulting times in minutes as a text property on each headline."
18590 (interactive)
18591 (let* ((bmp (buffer-modified-p))
18592 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
18593 org-clock-string
18594 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
18595 (lmax 30)
18596 (ltimes (make-vector lmax 0))
18597 (t1 0)
18598 (level 0)
18599 ts te dt
18600 time)
18601 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
18602 (save-excursion
18603 (goto-char (point-max))
18604 (while (re-search-backward re nil t)
18605 (cond
18606 ((match-end 2)
18607 ;; Two time stamps
18608 (setq ts (match-string 2)
18609 te (match-string 3)
18610 ts (time-to-seconds
18611 (apply 'encode-time (org-parse-time-string ts)))
18612 te (time-to-seconds
18613 (apply 'encode-time (org-parse-time-string te)))
18614 ts (if tstart (max ts tstart) ts)
18615 te (if tend (min te tend) te)
18616 dt (- te ts)
18617 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
18618 ((match-end 4)
18619 ;; A naket time
18620 (setq t1 (+ t1 (string-to-number (match-string 5))
18621 (* 60 (string-to-number (match-string 4))))))
18622 (t ;; A headline
18623 (setq level (- (match-end 1) (match-beginning 1)))
18624 (when (or (> t1 0) (> (aref ltimes level) 0))
18625 (loop for l from 0 to level do
18626 (aset ltimes l (+ (aref ltimes l) t1)))
18627 (setq t1 0 time (aref ltimes level))
18628 (loop for l from level to (1- lmax) do
18629 (aset ltimes l 0))
18630 (goto-char (match-beginning 0))
18631 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
18632 (setq org-clock-file-total-minutes (aref ltimes 0)))
18633 (set-buffer-modified-p bmp)))
18635 (defun org-clock-display (&optional total-only)
18636 "Show subtree times in the entire buffer.
18637 If TOTAL-ONLY is non-nil, only show the total time for the entire file
18638 in the echo area."
18639 (interactive)
18640 (org-remove-clock-overlays)
18641 (let (time h m p)
18642 (org-clock-sum)
18643 (unless total-only
18644 (save-excursion
18645 (goto-char (point-min))
18646 (while (or (and (equal (setq p (point)) (point-min))
18647 (get-text-property p :org-clock-minutes))
18648 (setq p (next-single-property-change
18649 (point) :org-clock-minutes)))
18650 (goto-char p)
18651 (when (setq time (get-text-property p :org-clock-minutes))
18652 (org-put-clock-overlay time (funcall outline-level))))
18653 (setq h (/ org-clock-file-total-minutes 60)
18654 m (- org-clock-file-total-minutes (* 60 h)))
18655 ;; Arrange to remove the overlays upon next change.
18656 (when org-remove-highlights-with-change
18657 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
18658 nil 'local))))
18659 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
18661 (defvar org-clock-overlays nil)
18662 (make-variable-buffer-local 'org-clock-overlays)
18664 (defun org-put-clock-overlay (time &optional level)
18665 "Put an overlays on the current line, displaying TIME.
18666 If LEVEL is given, prefix time with a corresponding number of stars.
18667 This creates a new overlay and stores it in `org-clock-overlays', so that it
18668 will be easy to remove."
18669 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
18670 (l (if level (org-get-legal-level level 0) 0))
18671 (off 0)
18672 ov tx)
18673 (move-to-column c)
18674 (unless (eolp) (skip-chars-backward "^ \t"))
18675 (skip-chars-backward " \t")
18676 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
18677 tx (concat (buffer-substring (1- (point)) (point))
18678 (make-string (+ off (max 0 (- c (current-column)))) ?.)
18679 (org-add-props (format "%s %2d:%02d%s"
18680 (make-string l ?*) h m
18681 (make-string (- 10 l) ?\ ))
18682 '(face secondary-selection))
18683 ""))
18684 (if (not (featurep 'xemacs))
18685 (org-overlay-put ov 'display tx)
18686 (org-overlay-put ov 'invisible t)
18687 (org-overlay-put ov 'end-glyph (make-glyph tx)))
18688 (push ov org-clock-overlays)))
18690 (defun org-remove-clock-overlays (&optional beg end noremove)
18691 "Remove the occur highlights from the buffer.
18692 BEG and END are ignored. If NOREMOVE is nil, remove this function
18693 from the `before-change-functions' in the current buffer."
18694 (interactive)
18695 (unless org-inhibit-highlight-removal
18696 (mapc 'org-delete-overlay org-clock-overlays)
18697 (setq org-clock-overlays nil)
18698 (unless noremove
18699 (remove-hook 'before-change-functions
18700 'org-remove-clock-overlays 'local))))
18702 (defun org-clock-out-if-current ()
18703 "Clock out if the current entry contains the running clock.
18704 This is used to stop the clock after a TODO entry is marked DONE,
18705 and is only done if the variable `org-clock-out-when-done' is not nil."
18706 (when (and org-clock-out-when-done
18707 (member state org-done-keywords)
18708 (equal (marker-buffer org-clock-marker) (current-buffer))
18709 (< (point) org-clock-marker)
18710 (> (save-excursion (outline-next-heading) (point))
18711 org-clock-marker))
18712 ;; Clock out, but don't accept a logging message for this.
18713 (let ((org-log-done (if (and (listp org-log-done)
18714 (member 'clock-out org-log-done))
18715 '(done)
18716 org-log-done)))
18717 (org-clock-out))))
18719 (add-hook 'org-after-todo-state-change-hook
18720 'org-clock-out-if-current)
18722 (defun org-check-running-clock ()
18723 "Check if the current buffer contains the running clock.
18724 If yes, offer to stop it and to save the buffer with the changes."
18725 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
18726 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
18727 (buffer-name))))
18728 (org-clock-out)
18729 (when (y-or-n-p "Save changed buffer?")
18730 (save-buffer))))
18732 (defun org-clock-report (&optional arg)
18733 "Create a table containing a report about clocked time.
18734 If the cursor is inside an existing clocktable block, then the table
18735 will be updated. If not, a new clocktable will be inserted.
18736 When called with a prefix argument, move to the first clock table in the
18737 buffer and update it."
18738 (interactive "P")
18739 (org-remove-clock-overlays)
18740 (when arg (org-find-dblock "clocktable"))
18741 (if (org-in-clocktable-p)
18742 (goto-char (org-in-clocktable-p))
18743 (org-create-dblock (list :name "clocktable"
18744 :maxlevel 2 :scope 'file)))
18745 (org-update-dblock))
18747 (defun org-in-clocktable-p ()
18748 "Check if the cursor is in a clocktable."
18749 (let ((pos (point)) start)
18750 (save-excursion
18751 (end-of-line 1)
18752 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
18753 (setq start (match-beginning 0))
18754 (re-search-forward "^#\\+END:.*" nil t)
18755 (>= (match-end 0) pos)
18756 start))))
18758 (defun org-clock-update-time-maybe ()
18759 "If this is a CLOCK line, update it and return t.
18760 Otherwise, return nil."
18761 (interactive)
18762 (save-excursion
18763 (beginning-of-line 1)
18764 (skip-chars-forward " \t")
18765 (when (looking-at org-clock-string)
18766 (let ((re (concat "[ \t]*" org-clock-string
18767 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
18768 "\\([ \t]*=>.*\\)?"))
18769 ts te h m s)
18770 (if (not (looking-at re))
18772 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
18773 (end-of-line 1)
18774 (setq ts (match-string 1)
18775 te (match-string 2))
18776 (setq s (- (time-to-seconds
18777 (apply 'encode-time (org-parse-time-string te)))
18778 (time-to-seconds
18779 (apply 'encode-time (org-parse-time-string ts))))
18780 h (floor (/ s 3600))
18781 s (- s (* 3600 h))
18782 m (floor (/ s 60))
18783 s (- s (* 60 s)))
18784 (insert " => " (format "%2d:%02d" h m))
18785 t)))))
18787 (defun org-clock-special-range (key &optional time as-strings)
18788 "Return two times bordering a special time range.
18789 Key is a symbol specifying the range and can be one of `today', `yesterday',
18790 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
18791 A week starts Monday 0:00 and ends Sunday 24:00.
18792 The range is determined relative to TIME. TIME defaults to the current time.
18793 The return value is a cons cell with two internal times like the ones
18794 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
18795 the returned times will be formatted strings."
18796 (let* ((tm (decode-time (or time (current-time))))
18797 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
18798 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
18799 (dow (nth 6 tm))
18800 s1 m1 h1 d1 month1 y1 diff ts te fm)
18801 (cond
18802 ((eq key 'today)
18803 (setq h 0 m 0 h1 24 m1 0))
18804 ((eq key 'yesterday)
18805 (setq d (1- d) h 0 m 0 h1 24 m1 0))
18806 ((eq key 'thisweek)
18807 (setq diff (if (= dow 0) 6 (1- dow))
18808 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18809 ((eq key 'lastweek)
18810 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
18811 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18812 ((eq key 'thismonth)
18813 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
18814 ((eq key 'lastmonth)
18815 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
18816 ((eq key 'thisyear)
18817 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
18818 ((eq key 'lastyear)
18819 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
18820 (t (error "No such time block %s" key)))
18821 (setq ts (encode-time s m h d month y)
18822 te (encode-time (or s1 s) (or m1 m) (or h1 h)
18823 (or d1 d) (or month1 month) (or y1 y)))
18824 (setq fm (cdr org-time-stamp-formats))
18825 (if as-strings
18826 (cons (format-time-string fm ts) (format-time-string fm te))
18827 (cons ts te))))
18829 (defun org-dblock-write:clocktable (params)
18830 "Write the standard clocktable."
18831 (catch 'exit
18832 (let* ((hlchars '((1 . "*") (2 . "/")))
18833 (ins (make-marker))
18834 (total-time nil)
18835 (scope (plist-get params :scope))
18836 (tostring (plist-get params :tostring))
18837 (multifile (plist-get params :multifile))
18838 (header (plist-get params :header))
18839 (maxlevel (or (plist-get params :maxlevel) 3))
18840 (step (plist-get params :step))
18841 (emph (plist-get params :emphasize))
18842 (ts (plist-get params :tstart))
18843 (te (plist-get params :tend))
18844 (block (plist-get params :block))
18845 ipos time h m p level hlc hdl
18846 cc beg end pos tbl)
18847 (when step
18848 (org-clocktable-steps params)
18849 (throw 'exit nil))
18850 (when block
18851 (setq cc (org-clock-special-range block nil t)
18852 ts (car cc) te (cdr cc)))
18853 (if ts (setq ts (time-to-seconds
18854 (apply 'encode-time (org-parse-time-string ts)))))
18855 (if te (setq te (time-to-seconds
18856 (apply 'encode-time (org-parse-time-string te)))))
18857 (move-marker ins (point))
18858 (setq ipos (point))
18860 ;; Get the right scope
18861 (setq pos (point))
18862 (save-restriction
18863 (cond
18864 ((not scope))
18865 ((eq scope 'file) (widen))
18866 ((eq scope 'subtree) (org-narrow-to-subtree))
18867 ((eq scope 'tree)
18868 (while (org-up-heading-safe))
18869 (org-narrow-to-subtree))
18870 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
18871 (symbol-name scope)))
18872 (setq level (string-to-number (match-string 1 (symbol-name scope))))
18873 (catch 'exit
18874 (while (org-up-heading-safe)
18875 (looking-at outline-regexp)
18876 (if (<= (org-reduced-level (funcall outline-level)) level)
18877 (throw 'exit nil))))
18878 (org-narrow-to-subtree))
18879 ((or (listp scope) (eq scope 'agenda))
18880 (let* ((files (if (listp scope) scope (org-agenda-files)))
18881 (scope 'agenda)
18882 (p1 (copy-sequence params))
18883 file)
18884 (plist-put p1 :tostring t)
18885 (plist-put p1 :multifile t)
18886 (plist-put p1 :scope 'file)
18887 (org-prepare-agenda-buffers files)
18888 (while (setq file (pop files))
18889 (with-current-buffer (find-buffer-visiting file)
18890 (push (org-clocktable-add-file
18891 file (org-dblock-write:clocktable p1)) tbl)
18892 (setq total-time (+ (or total-time 0)
18893 org-clock-file-total-minutes)))))))
18894 (goto-char pos)
18896 (unless (eq scope 'agenda)
18897 (org-clock-sum ts te)
18898 (goto-char (point-min))
18899 (while (setq p (next-single-property-change (point) :org-clock-minutes))
18900 (goto-char p)
18901 (when (setq time (get-text-property p :org-clock-minutes))
18902 (save-excursion
18903 (beginning-of-line 1)
18904 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
18905 (setq level (org-reduced-level
18906 (- (match-end 1) (match-beginning 1))))
18907 (<= level maxlevel))
18908 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
18909 hdl (match-string 2)
18910 h (/ time 60)
18911 m (- time (* 60 h)))
18912 (if (and (not multifile) (= level 1)) (push "|-" tbl))
18913 (push (concat
18914 "| " (int-to-string level) "|" hlc hdl hlc " |"
18915 (make-string (1- level) ?|)
18916 hlc (format "%d:%02d" h m) hlc
18917 " |") tbl))))))
18918 (setq tbl (nreverse tbl))
18919 (if tostring
18920 (if tbl (mapconcat 'identity tbl "\n") nil)
18921 (goto-char ins)
18922 (insert-before-markers
18923 (or header
18924 (concat
18925 "Clock summary at ["
18926 (substring
18927 (format-time-string (cdr org-time-stamp-formats))
18928 1 -1)
18929 "]."
18930 (if block
18931 (format " Considered range is /%s/." block)
18933 "\n\n"))
18934 (if (eq scope 'agenda) "|File" "")
18935 "|L|Headline|Time|\n")
18936 (setq total-time (or total-time org-clock-file-total-minutes)
18937 h (/ total-time 60)
18938 m (- total-time (* 60 h)))
18939 (insert-before-markers
18940 "|-\n|"
18941 (if (eq scope 'agenda) "|" "")
18943 "*Total time*| "
18944 (format "*%d:%02d*" h m)
18945 "|\n|-\n")
18946 (setq tbl (delq nil tbl))
18947 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
18948 (equal (substring (car tbl) 0 2) "|-"))
18949 (pop tbl))
18950 (insert-before-markers (mapconcat
18951 'identity (delq nil tbl)
18952 (if (eq scope 'agenda) "\n|-\n" "\n")))
18953 (backward-delete-char 1)
18954 (goto-char ipos)
18955 (skip-chars-forward "^|")
18956 (org-table-align))))))
18958 (defun org-clocktable-steps (params)
18959 (let* ((p1 (copy-sequence params))
18960 (ts (plist-get p1 :tstart))
18961 (te (plist-get p1 :tend))
18962 (step0 (plist-get p1 :step))
18963 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
18964 (block (plist-get p1 :block))
18966 (when block
18967 (setq cc (org-clock-special-range block nil t)
18968 ts (car cc) te (cdr cc)))
18969 (if ts (setq ts (time-to-seconds
18970 (apply 'encode-time (org-parse-time-string ts)))))
18971 (if te (setq te (time-to-seconds
18972 (apply 'encode-time (org-parse-time-string te)))))
18973 (plist-put p1 :header "")
18974 (plist-put p1 :step nil)
18975 (plist-put p1 :block nil)
18976 (while (< ts te)
18977 (or (bolp) (insert "\n"))
18978 (plist-put p1 :tstart (format-time-string
18979 (car org-time-stamp-formats)
18980 (seconds-to-time ts)))
18981 (plist-put p1 :tend (format-time-string
18982 (car org-time-stamp-formats)
18983 (seconds-to-time (setq ts (+ ts step)))))
18984 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
18985 (plist-get p1 :tstart) "\n")
18986 (org-dblock-write:clocktable p1)
18987 (re-search-forward "#\\+END:")
18988 (end-of-line 0))))
18991 (defun org-clocktable-add-file (file table)
18992 (if table
18993 (let ((lines (org-split-string table "\n"))
18994 (ff (file-name-nondirectory file)))
18995 (mapconcat 'identity
18996 (mapcar (lambda (x)
18997 (if (string-match org-table-dataline-regexp x)
18998 (concat "|" ff x)
19000 lines)
19001 "\n"))))
19003 ;; FIXME: I don't think anybody uses this, ask David
19004 (defun org-collect-clock-time-entries ()
19005 "Return an internal list with clocking information.
19006 This list has one entry for each CLOCK interval.
19007 FIXME: describe the elements."
19008 (interactive)
19009 (let ((re (concat "^[ \t]*" org-clock-string
19010 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
19011 rtn beg end next cont level title total closedp leafp
19012 clockpos titlepos h m donep)
19013 (save-excursion
19014 (org-clock-sum)
19015 (goto-char (point-min))
19016 (while (re-search-forward re nil t)
19017 (setq clockpos (match-beginning 0)
19018 beg (match-string 1) end (match-string 2)
19019 cont (match-end 0))
19020 (setq beg (apply 'encode-time (org-parse-time-string beg))
19021 end (apply 'encode-time (org-parse-time-string end)))
19022 (org-back-to-heading t)
19023 (setq donep (org-entry-is-done-p))
19024 (setq titlepos (point)
19025 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
19026 h (/ total 60) m (- total (* 60 h))
19027 total (cons h m))
19028 (looking-at "\\(\\*+\\) +\\(.*\\)")
19029 (setq level (- (match-end 1) (match-beginning 1))
19030 title (org-match-string-no-properties 2))
19031 (save-excursion (outline-next-heading) (setq next (point)))
19032 (setq closedp (re-search-forward org-closed-time-regexp next t))
19033 (goto-char next)
19034 (setq leafp (and (looking-at "^\\*+ ")
19035 (<= (- (match-end 0) (point)) level)))
19036 (push (list beg end clockpos closedp donep
19037 total title titlepos level leafp)
19038 rtn)
19039 (goto-char cont)))
19040 (nreverse rtn)))
19042 ;;;; Agenda, and Diary Integration
19044 ;;; Define the Org-agenda-mode
19046 (defvar org-agenda-mode-map (make-sparse-keymap)
19047 "Keymap for `org-agenda-mode'.")
19049 (defvar org-agenda-menu) ; defined later in this file.
19050 (defvar org-agenda-follow-mode nil)
19051 (defvar org-agenda-show-log nil)
19052 (defvar org-agenda-redo-command nil)
19053 (defvar org-agenda-mode-hook nil)
19054 (defvar org-agenda-type nil)
19055 (defvar org-agenda-force-single-file nil)
19057 (defun org-agenda-mode ()
19058 "Mode for time-sorted view on action items in Org-mode files.
19060 The following commands are available:
19062 \\{org-agenda-mode-map}"
19063 (interactive)
19064 (kill-all-local-variables)
19065 (setq org-agenda-undo-list nil
19066 org-agenda-pending-undo-list nil)
19067 (setq major-mode 'org-agenda-mode)
19068 ;; Keep global-font-lock-mode from turning on font-lock-mode
19069 (org-set-local 'font-lock-global-modes (list 'not major-mode))
19070 (setq mode-name "Org-Agenda")
19071 (use-local-map org-agenda-mode-map)
19072 (easy-menu-add org-agenda-menu)
19073 (if org-startup-truncated (setq truncate-lines t))
19074 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
19075 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
19076 ;; Make sure properties are removed when copying text
19077 (when (boundp 'buffer-substring-filters)
19078 (org-set-local 'buffer-substring-filters
19079 (cons (lambda (x)
19080 (set-text-properties 0 (length x) nil x) x)
19081 buffer-substring-filters)))
19082 (unless org-agenda-keep-modes
19083 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
19084 org-agenda-show-log nil))
19085 (easy-menu-change
19086 '("Agenda") "Agenda Files"
19087 (append
19088 (list
19089 (vector
19090 (if (get 'org-agenda-files 'org-restrict)
19091 "Restricted to single file"
19092 "Edit File List")
19093 '(org-edit-agenda-file-list)
19094 (not (get 'org-agenda-files 'org-restrict)))
19095 "--")
19096 (mapcar 'org-file-menu-entry (org-agenda-files))))
19097 (org-agenda-set-mode-name)
19098 (apply
19099 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
19100 (list 'org-agenda-mode-hook)))
19102 (substitute-key-definition 'undo 'org-agenda-undo
19103 org-agenda-mode-map global-map)
19104 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
19105 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
19106 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
19107 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
19108 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
19109 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
19110 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
19111 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
19112 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
19113 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
19114 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
19115 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
19116 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
19117 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
19118 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
19119 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
19120 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
19121 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
19122 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
19123 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
19124 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
19125 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
19126 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
19127 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
19128 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
19129 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
19130 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
19131 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
19132 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
19134 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
19135 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
19136 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
19137 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
19138 (while l (org-defkey org-agenda-mode-map
19139 (int-to-string (pop l)) 'digit-argument)))
19141 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
19142 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
19143 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
19144 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
19145 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
19146 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
19147 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
19148 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
19149 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
19150 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
19151 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
19152 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
19153 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
19154 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
19155 (org-defkey org-agenda-mode-map "n" 'next-line)
19156 (org-defkey org-agenda-mode-map "p" 'previous-line)
19157 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
19158 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
19159 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
19160 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
19161 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
19162 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
19163 (eval-after-load "calendar"
19164 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
19165 'org-calendar-goto-agenda))
19166 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
19167 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
19168 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
19169 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
19170 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
19171 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
19172 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
19173 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
19174 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
19175 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
19176 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
19177 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19178 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
19179 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
19180 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
19181 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
19182 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
19183 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
19184 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
19185 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
19186 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
19187 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
19189 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
19190 "Local keymap for agenda entries from Org-mode.")
19192 (org-defkey org-agenda-keymap
19193 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
19194 (org-defkey org-agenda-keymap
19195 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
19196 (when org-agenda-mouse-1-follows-link
19197 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
19198 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
19199 '("Agenda"
19200 ("Agenda Files")
19201 "--"
19202 ["Show" org-agenda-show t]
19203 ["Go To (other window)" org-agenda-goto t]
19204 ["Go To (this window)" org-agenda-switch-to t]
19205 ["Follow Mode" org-agenda-follow-mode
19206 :style toggle :selected org-agenda-follow-mode :active t]
19207 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
19208 "--"
19209 ["Cycle TODO" org-agenda-todo t]
19210 ["Archive subtree" org-agenda-archive t]
19211 ["Delete subtree" org-agenda-kill t]
19212 "--"
19213 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
19214 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
19215 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
19216 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
19217 "--"
19218 ("Tags and Properties"
19219 ["Show all Tags" org-agenda-show-tags t]
19220 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
19221 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
19222 "--"
19223 ["Column View" org-columns t])
19224 ("Date/Schedule"
19225 ["Schedule" org-agenda-schedule t]
19226 ["Set Deadline" org-agenda-deadline t]
19227 "--"
19228 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19229 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19230 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19231 ("Clock"
19232 ["Clock in" org-agenda-clock-in t]
19233 ["Clock out" org-agenda-clock-out t]
19234 ["Clock cancel" org-agenda-clock-cancel t]
19235 ["Goto running clock" org-clock-goto t])
19236 ("Priority"
19237 ["Set Priority" org-agenda-priority t]
19238 ["Increase Priority" org-agenda-priority-up t]
19239 ["Decrease Priority" org-agenda-priority-down t]
19240 ["Show Priority" org-agenda-show-priority t])
19241 ("Calendar/Diary"
19242 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19243 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19244 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19245 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19246 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19247 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19248 "--"
19249 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19250 "--"
19251 ("View"
19252 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19253 :style radio :selected (equal org-agenda-ndays 1)]
19254 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19255 :style radio :selected (equal org-agenda-ndays 7)]
19256 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19257 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19258 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19259 :style radio :selected (member org-agenda-ndays '(365 366))]
19260 "--"
19261 ["Show Logbook entries" org-agenda-log-mode
19262 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19263 ["Include Diary" org-agenda-toggle-diary
19264 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19265 ["Use Time Grid" org-agenda-toggle-time-grid
19266 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19267 ["Write view to file" org-write-agenda t]
19268 ["Rebuild buffer" org-agenda-redo t]
19269 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19270 "--"
19271 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19272 "--"
19273 ["Quit" org-agenda-quit t]
19274 ["Exit and Release Buffers" org-agenda-exit t]
19277 ;;; Agenda undo
19279 (defvar org-agenda-allow-remote-undo t
19280 "Non-nil means, allow remote undo from the agenda buffer.")
19281 (defvar org-agenda-undo-list nil
19282 "List of undoable operations in the agenda since last refresh.")
19283 (defvar org-agenda-undo-has-started-in nil
19284 "Buffers that have already seen `undo-start' in the current undo sequence.")
19285 (defvar org-agenda-pending-undo-list nil
19286 "In a series of undo commands, this is the list of remaning undo items.")
19288 (defmacro org-if-unprotected (&rest body)
19289 "Execute BODY if there is no `org-protected' text property at point."
19290 (declare (debug t))
19291 `(unless (get-text-property (point) 'org-protected)
19292 ,@body))
19294 (defmacro org-with-remote-undo (_buffer &rest _body)
19295 "Execute BODY while recording undo information in two buffers."
19296 (declare (indent 1) (debug t))
19297 `(let ((_cline (org-current-line))
19298 (_cmd this-command)
19299 (_buf1 (current-buffer))
19300 (_buf2 ,_buffer)
19301 (_undo1 buffer-undo-list)
19302 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19303 _c1 _c2)
19304 ,@_body
19305 (when org-agenda-allow-remote-undo
19306 (setq _c1 (org-verify-change-for-undo
19307 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19308 _c2 (org-verify-change-for-undo
19309 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19310 (when (or _c1 _c2)
19311 ;; make sure there are undo boundaries
19312 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19313 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19314 ;; remember which buffer to undo
19315 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19316 org-agenda-undo-list)))))
19318 (defun org-agenda-undo ()
19319 "Undo a remote editing step in the agenda.
19320 This undoes changes both in the agenda buffer and in the remote buffer
19321 that have been changed along."
19322 (interactive)
19323 (or org-agenda-allow-remote-undo
19324 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19325 (if (not (eq this-command last-command))
19326 (setq org-agenda-undo-has-started-in nil
19327 org-agenda-pending-undo-list org-agenda-undo-list))
19328 (if (not org-agenda-pending-undo-list)
19329 (error "No further undo information"))
19330 (let* ((entry (pop org-agenda-pending-undo-list))
19331 buf line cmd rembuf)
19332 (setq cmd (pop entry) line (pop entry))
19333 (setq rembuf (nth 2 entry))
19334 (org-with-remote-undo rembuf
19335 (while (bufferp (setq buf (pop entry)))
19336 (if (pop entry)
19337 (with-current-buffer buf
19338 (let ((last-undo-buffer buf)
19339 (inhibit-read-only t))
19340 (unless (memq buf org-agenda-undo-has-started-in)
19341 (push buf org-agenda-undo-has-started-in)
19342 (make-local-variable 'pending-undo-list)
19343 (undo-start))
19344 (while (and pending-undo-list
19345 (listp pending-undo-list)
19346 (not (car pending-undo-list)))
19347 (pop pending-undo-list))
19348 (undo-more 1))))))
19349 (goto-line line)
19350 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19352 (defun org-verify-change-for-undo (l1 l2)
19353 "Verify that a real change occurred between the undo lists L1 and L2."
19354 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19355 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19356 (not (eq l1 l2)))
19358 ;;; Agenda dispatch
19360 (defvar org-agenda-restrict nil)
19361 (defvar org-agenda-restrict-begin (make-marker))
19362 (defvar org-agenda-restrict-end (make-marker))
19363 (defvar org-agenda-last-dispatch-buffer nil)
19364 (defvar org-agenda-overriding-restriction nil)
19366 ;;;###autoload
19367 (defun org-agenda (arg &optional keys restriction)
19368 "Dispatch agenda commands to collect entries to the agenda buffer.
19369 Prompts for a command to execute. Any prefix arg will be passed
19370 on to the selected command. The default selections are:
19372 a Call `org-agenda-list' to display the agenda for current day or week.
19373 t Call `org-todo-list' to display the global todo list.
19374 T Call `org-todo-list' to display the global todo list, select only
19375 entries with a specific TODO keyword (the user gets a prompt).
19376 m Call `org-tags-view' to display headlines with tags matching
19377 a condition (the user is prompted for the condition).
19378 M Like `m', but select only TODO entries, no ordinary headlines.
19379 L Create a timeline for the current buffer.
19380 e Export views to associated files.
19382 More commands can be added by configuring the variable
19383 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19384 searches can be pre-defined in this way.
19386 If the current buffer is in Org-mode and visiting a file, you can also
19387 first press `<' once to indicate that the agenda should be temporarily
19388 \(until the next use of \\[org-agenda]) restricted to the current file.
19389 Pressing `<' twice means to restrict to the current subtree or region
19390 \(if active)."
19391 (interactive "P")
19392 (catch 'exit
19393 (let* ((prefix-descriptions nil)
19394 (org-agenda-custom-commands-orig org-agenda-custom-commands)
19395 (org-agenda-custom-commands
19396 ;; normalize different versions
19397 (delq nil
19398 (mapcar
19399 (lambda (x)
19400 (cond ((stringp (cdr x))
19401 (push x prefix-descriptions)
19402 nil)
19403 ((stringp (nth 1 x)) x)
19404 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19405 (t (cons (car x) (cons "" (cdr x))))))
19406 org-agenda-custom-commands)))
19407 (buf (current-buffer))
19408 (bfn (buffer-file-name (buffer-base-buffer)))
19409 entry key type match lprops ans)
19410 ;; Turn off restriction unless there is an overriding one
19411 (unless org-agenda-overriding-restriction
19412 (put 'org-agenda-files 'org-restrict nil)
19413 (setq org-agenda-restrict nil)
19414 (move-marker org-agenda-restrict-begin nil)
19415 (move-marker org-agenda-restrict-end nil))
19416 ;; Delete old local properties
19417 (put 'org-agenda-redo-command 'org-lprops nil)
19418 ;; Remember where this call originated
19419 (setq org-agenda-last-dispatch-buffer (current-buffer))
19420 (unless keys
19421 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19422 keys (car ans)
19423 restriction (cdr ans)))
19424 ;; Estabish the restriction, if any
19425 (when (and (not org-agenda-overriding-restriction) restriction)
19426 (put 'org-agenda-files 'org-restrict (list bfn))
19427 (cond
19428 ((eq restriction 'region)
19429 (setq org-agenda-restrict t)
19430 (move-marker org-agenda-restrict-begin (region-beginning))
19431 (move-marker org-agenda-restrict-end (region-end)))
19432 ((eq restriction 'subtree)
19433 (save-excursion
19434 (setq org-agenda-restrict t)
19435 (org-back-to-heading t)
19436 (move-marker org-agenda-restrict-begin (point))
19437 (move-marker org-agenda-restrict-end
19438 (progn (org-end-of-subtree t)))))))
19440 (require 'calendar) ; FIXME: can we avoid this for some commands?
19441 ;; For example the todo list should not need it (but does...)
19442 (cond
19443 ((setq entry (assoc keys org-agenda-custom-commands))
19444 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19445 (progn
19446 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19447 (put 'org-agenda-redo-command 'org-lprops lprops)
19448 (cond
19449 ((eq type 'agenda)
19450 (org-let lprops '(org-agenda-list current-prefix-arg)))
19451 ((eq type 'alltodo)
19452 (org-let lprops '(org-todo-list current-prefix-arg)))
19453 ((eq type 'stuck)
19454 (org-let lprops '(org-agenda-list-stuck-projects
19455 current-prefix-arg)))
19456 ((eq type 'tags)
19457 (org-let lprops '(org-tags-view current-prefix-arg match)))
19458 ((eq type 'tags-todo)
19459 (org-let lprops '(org-tags-view '(4) match)))
19460 ((eq type 'todo)
19461 (org-let lprops '(org-todo-list match)))
19462 ((eq type 'tags-tree)
19463 (org-check-for-org-mode)
19464 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
19465 ((eq type 'todo-tree)
19466 (org-check-for-org-mode)
19467 (org-let lprops
19468 '(org-occur (concat "^" outline-regexp "[ \t]*"
19469 (regexp-quote match) "\\>"))))
19470 ((eq type 'occur-tree)
19471 (org-check-for-org-mode)
19472 (org-let lprops '(org-occur match)))
19473 ((functionp type)
19474 (org-let lprops '(funcall type match)))
19475 ((fboundp type)
19476 (org-let lprops '(funcall type match)))
19477 (t (error "Invalid custom agenda command type %s" type))))
19478 (org-run-agenda-series (nth 1 entry) (cddr entry))))
19479 ((equal keys "C")
19480 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
19481 (customize-variable 'org-agenda-custom-commands))
19482 ((equal keys "a") (call-interactively 'org-agenda-list))
19483 ((equal keys "t") (call-interactively 'org-todo-list))
19484 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
19485 ((equal keys "m") (call-interactively 'org-tags-view))
19486 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
19487 ((equal keys "e") (call-interactively 'org-store-agenda-views))
19488 ((equal keys "L")
19489 (unless (org-mode-p)
19490 (error "This is not an Org-mode file"))
19491 (unless restriction
19492 (put 'org-agenda-files 'org-restrict (list bfn))
19493 (org-call-with-arg 'org-timeline arg)))
19494 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
19495 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
19496 ((equal keys "!") (customize-variable 'org-stuck-projects))
19497 (t (error "Invalid agenda key"))))))
19499 (defun org-agenda-normalize-custom-commands (cmds)
19500 (delq nil
19501 (mapcar
19502 (lambda (x)
19503 (cond ((stringp (cdr x)) nil)
19504 ((stringp (nth 1 x)) x)
19505 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19506 (t (cons (car x) (cons "" (cdr x))))))
19507 cmds)))
19509 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
19510 "The user interface for selecting an agenda command."
19511 (catch 'exit
19512 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
19513 (restrict-ok (and bfn (org-mode-p)))
19514 (region-p (org-region-active-p))
19515 (custom org-agenda-custom-commands)
19516 (selstring "")
19517 restriction second-time
19518 c entry key type match prefixes rmheader header-end custom1 desc)
19519 (save-window-excursion
19520 (delete-other-windows)
19521 (org-switch-to-buffer-other-window " *Agenda Commands*")
19522 (erase-buffer)
19523 (insert (eval-when-compile
19524 (let ((header
19526 Press key for an agenda command: < Buffer,subtree/region restriction
19527 -------------------------------- > Remove restriction
19528 a Agenda for current week or day e Export agenda views
19529 t List of all TODO entries T Entries with special TODO kwd
19530 m Match a TAGS query M Like m, but only TODO entries
19531 L Timeline for current buffer # List stuck projects (!=configure)
19532 / Multi-occur C Configure custom agenda commands
19534 (start 0))
19535 (while (string-match
19536 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
19537 header start)
19538 (setq start (match-end 0))
19539 (add-text-properties (match-beginning 2) (match-end 2)
19540 '(face bold) header))
19541 header)))
19542 (setq header-end (move-marker (make-marker) (point)))
19543 (while t
19544 (setq custom1 custom)
19545 (when (eq rmheader t)
19546 (goto-line 1)
19547 (re-search-forward ":" nil t)
19548 (delete-region (match-end 0) (point-at-eol))
19549 (forward-char 1)
19550 (looking-at "-+")
19551 (delete-region (match-end 0) (point-at-eol))
19552 (move-marker header-end (match-end 0)))
19553 (goto-char header-end)
19554 (delete-region (point) (point-max))
19555 (while (setq entry (pop custom1))
19556 (setq key (car entry) desc (nth 1 entry)
19557 type (nth 2 entry) match (nth 3 entry))
19558 (if (> (length key) 1)
19559 (add-to-list 'prefixes (string-to-char key))
19560 (insert
19561 (format
19562 "\n%-4s%-14s: %s"
19563 (org-add-props (copy-sequence key)
19564 '(face bold))
19565 (cond
19566 ((string-match "\\S-" desc) desc)
19567 ((eq type 'agenda) "Agenda for current week or day")
19568 ((eq type 'alltodo) "List of all TODO entries")
19569 ((eq type 'stuck) "List of stuck projects")
19570 ((eq type 'todo) "TODO keyword")
19571 ((eq type 'tags) "Tags query")
19572 ((eq type 'tags-todo) "Tags (TODO)")
19573 ((eq type 'tags-tree) "Tags tree")
19574 ((eq type 'todo-tree) "TODO kwd tree")
19575 ((eq type 'occur-tree) "Occur tree")
19576 ((functionp type) (if (symbolp type)
19577 (symbol-name type)
19578 "Lambda expression"))
19579 (t "???"))
19580 (cond
19581 ((stringp match)
19582 (org-add-props match nil 'face 'org-warning))
19583 (match
19584 (format "set of %d commands" (length match)))
19585 (t ""))))))
19586 (when prefixes
19587 (mapc (lambda (x)
19588 (insert
19589 (format "\n%s %s"
19590 (org-add-props (char-to-string x)
19591 nil 'face 'bold)
19592 (or (cdr (assoc (concat selstring (char-to-string x))
19593 prefix-descriptions))
19594 "Prefix key"))))
19595 prefixes))
19596 (goto-char (point-min))
19597 (when (fboundp 'fit-window-to-buffer)
19598 (if second-time
19599 (if (not (pos-visible-in-window-p (point-max)))
19600 (fit-window-to-buffer))
19601 (setq second-time t)
19602 (fit-window-to-buffer)))
19603 (message "Press key for agenda command%s:"
19604 (if (or restrict-ok org-agenda-overriding-restriction)
19605 (if org-agenda-overriding-restriction
19606 " (restriction lock active)"
19607 (if restriction
19608 (format " (restricted to %s)" restriction)
19609 " (unrestricted)"))
19610 ""))
19611 (setq c (read-char-exclusive))
19612 (message "")
19613 (cond
19614 ((assoc (char-to-string c) custom)
19615 (setq selstring (concat selstring (char-to-string c)))
19616 (throw 'exit (cons selstring restriction)))
19617 ((memq c prefixes)
19618 (setq selstring (concat selstring (char-to-string c))
19619 prefixes nil
19620 rmheader (or rmheader t)
19621 custom (delq nil (mapcar
19622 (lambda (x)
19623 (if (or (= (length (car x)) 1)
19624 (/= (string-to-char (car x)) c))
19626 (cons (substring (car x) 1) (cdr x))))
19627 custom))))
19628 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
19629 (message "Restriction is only possible in Org-mode buffers")
19630 (ding) (sit-for 1))
19631 ((eq c ?1)
19632 (org-agenda-remove-restriction-lock 'noupdate)
19633 (setq restriction 'buffer))
19634 ((eq c ?0)
19635 (org-agenda-remove-restriction-lock 'noupdate)
19636 (setq restriction (if region-p 'region 'subtree)))
19637 ((eq c ?<)
19638 (org-agenda-remove-restriction-lock 'noupdate)
19639 (setq restriction
19640 (cond
19641 ((eq restriction 'buffer)
19642 (if region-p 'region 'subtree))
19643 ((memq restriction '(subtree region))
19644 nil)
19645 (t 'buffer))))
19646 ((eq c ?>)
19647 (org-agenda-remove-restriction-lock 'noupdate)
19648 (setq restriction nil))
19649 ((and (equal selstring "") (memq c '(?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
19650 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
19651 ((and (> (length selstring) 0) (eq c ?\d))
19652 (delete-window)
19653 (org-agenda-get-restriction-and-command prefix-descriptions))
19655 ((equal c ?q) (error "Abort"))
19656 (t (error "Invalid key %c" c))))))))
19658 (defun org-run-agenda-series (name series)
19659 (org-prepare-agenda name)
19660 (let* ((org-agenda-multi t)
19661 (redo (list 'org-run-agenda-series name (list 'quote series)))
19662 (cmds (car series))
19663 (gprops (nth 1 series))
19664 match ;; The byte compiler incorrectly complains about this. Keep it!
19665 cmd type lprops)
19666 (while (setq cmd (pop cmds))
19667 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
19668 (cond
19669 ((eq type 'agenda)
19670 (org-let2 gprops lprops
19671 '(call-interactively 'org-agenda-list)))
19672 ((eq type 'alltodo)
19673 (org-let2 gprops lprops
19674 '(call-interactively 'org-todo-list)))
19675 ((eq type 'stuck)
19676 (org-let2 gprops lprops
19677 '(call-interactively 'org-agenda-list-stuck-projects)))
19678 ((eq type 'tags)
19679 (org-let2 gprops lprops
19680 '(org-tags-view current-prefix-arg match)))
19681 ((eq type 'tags-todo)
19682 (org-let2 gprops lprops
19683 '(org-tags-view '(4) match)))
19684 ((eq type 'todo)
19685 (org-let2 gprops lprops
19686 '(org-todo-list match)))
19687 ((fboundp type)
19688 (org-let2 gprops lprops
19689 '(funcall type match)))
19690 (t (error "Invalid type in command series"))))
19691 (widen)
19692 (setq org-agenda-redo-command redo)
19693 (goto-char (point-min)))
19694 (org-finalize-agenda))
19696 ;;;###autoload
19697 (defmacro org-batch-agenda (cmd-key &rest parameters)
19698 "Run an agenda command in batch mode and send the result to STDOUT.
19699 If CMD-KEY is a string of length 1, it is used as a key in
19700 `org-agenda-custom-commands' and triggers this command. If it is a
19701 longer string it is used as a tags/todo match string.
19702 Paramters are alternating variable names and values that will be bound
19703 before running the agenda command."
19704 (let (pars)
19705 (while parameters
19706 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19707 (if (> (length cmd-key) 2)
19708 (eval (list 'let (nreverse pars)
19709 (list 'org-tags-view nil cmd-key)))
19710 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19711 (set-buffer org-agenda-buffer-name)
19712 (princ (org-encode-for-stdout (buffer-string)))))
19714 (defun org-encode-for-stdout (string)
19715 (if (fboundp 'encode-coding-string)
19716 (encode-coding-string string buffer-file-coding-system)
19717 string))
19719 (defvar org-agenda-info nil)
19721 ;;;###autoload
19722 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
19723 "Run an agenda command in batch mode and send the result to STDOUT.
19724 If CMD-KEY is a string of length 1, it is used as a key in
19725 `org-agenda-custom-commands' and triggers this command. If it is a
19726 longer string it is used as a tags/todo match string.
19727 Paramters are alternating variable names and values that will be bound
19728 before running the agenda command.
19730 The output gives a line for each selected agenda item. Each
19731 item is a list of comma-separated values, like this:
19733 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
19735 category The category of the item
19736 head The headline, without TODO kwd, TAGS and PRIORITY
19737 type The type of the agenda entry, can be
19738 todo selected in TODO match
19739 tagsmatch selected in tags match
19740 diary imported from diary
19741 deadline a deadline on given date
19742 scheduled scheduled on given date
19743 timestamp entry has timestamp on given date
19744 closed entry was closed on given date
19745 upcoming-deadline warning about deadline
19746 past-scheduled forwarded scheduled item
19747 block entry has date block including g. date
19748 todo The todo keyword, if any
19749 tags All tags including inherited ones, separated by colons
19750 date The relevant date, like 2007-2-14
19751 time The time, like 15:00-16:50
19752 extra Sting with extra planning info
19753 priority-l The priority letter if any was given
19754 priority-n The computed numerical priority
19755 agenda-day The day in the agenda where this is listed"
19757 (let (pars)
19758 (while parameters
19759 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19760 (push (list 'org-agenda-remove-tags t) pars)
19761 (if (> (length cmd-key) 2)
19762 (eval (list 'let (nreverse pars)
19763 (list 'org-tags-view nil cmd-key)))
19764 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19765 (set-buffer org-agenda-buffer-name)
19766 (let* ((lines (org-split-string (buffer-string) "\n"))
19767 line)
19768 (while (setq line (pop lines))
19769 (catch 'next
19770 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
19771 (setq org-agenda-info
19772 (org-fix-agenda-info (text-properties-at 0 line)))
19773 (princ
19774 (org-encode-for-stdout
19775 (mapconcat 'org-agenda-export-csv-mapper
19776 '(org-category txt type todo tags date time-of-day extra
19777 priority-letter priority agenda-day)
19778 ",")))
19779 (princ "\n"))))))
19781 (defun org-fix-agenda-info (props)
19782 "Make sure all properties on an agenda item have a canonical form,
19783 so the export commands can easily use it."
19784 (let (tmp re)
19785 (when (setq tmp (plist-get props 'tags))
19786 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
19787 (when (setq tmp (plist-get props 'date))
19788 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19789 (let ((calendar-date-display-form '(year "-" month "-" day)))
19790 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
19792 (setq tmp (calendar-date-string tmp)))
19793 (setq props (plist-put props 'date tmp)))
19794 (when (setq tmp (plist-get props 'day))
19795 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19796 (let ((calendar-date-display-form '(year "-" month "-" day)))
19797 (setq tmp (calendar-date-string tmp)))
19798 (setq props (plist-put props 'day tmp))
19799 (setq props (plist-put props 'agenda-day tmp)))
19800 (when (setq tmp (plist-get props 'txt))
19801 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
19802 (plist-put props 'priority-letter (match-string 1 tmp))
19803 (setq tmp (replace-match "" t t tmp)))
19804 (when (and (setq re (plist-get props 'org-todo-regexp))
19805 (setq re (concat "\\`\\.*" re " ?"))
19806 (string-match re tmp))
19807 (plist-put props 'todo (match-string 1 tmp))
19808 (setq tmp (replace-match "" t t tmp)))
19809 (plist-put props 'txt tmp)))
19810 props)
19812 (defun org-agenda-export-csv-mapper (prop)
19813 (let ((res (plist-get org-agenda-info prop)))
19814 (setq res
19815 (cond
19816 ((not res) "")
19817 ((stringp res) res)
19818 (t (prin1-to-string res))))
19819 (while (string-match "," res)
19820 (setq res (replace-match ";" t t res)))
19821 (org-trim res)))
19824 ;;;###autoload
19825 (defun org-store-agenda-views (&rest parameters)
19826 (interactive)
19827 (eval (list 'org-batch-store-agenda-views)))
19829 ;; FIXME, why is this a macro?????
19830 ;;;###autoload
19831 (defmacro org-batch-store-agenda-views (&rest parameters)
19832 "Run all custom agenda commands that have a file argument."
19833 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
19834 (pop-up-frames nil)
19835 (dir default-directory)
19836 pars cmd thiscmdkey files opts)
19837 (while parameters
19838 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19839 (setq pars (reverse pars))
19840 (save-window-excursion
19841 (while cmds
19842 (setq cmd (pop cmds)
19843 thiscmdkey (car cmd)
19844 opts (nth 4 cmd)
19845 files (nth 5 cmd))
19846 (if (stringp files) (setq files (list files)))
19847 (when files
19848 (eval (list 'let (append org-agenda-exporter-settings opts pars)
19849 (list 'org-agenda nil thiscmdkey)))
19850 (set-buffer org-agenda-buffer-name)
19851 (while files
19852 (eval (list 'let (append org-agenda-exporter-settings opts pars)
19853 (list 'org-write-agenda
19854 (expand-file-name (pop files) dir) t))))
19855 (and (get-buffer org-agenda-buffer-name)
19856 (kill-buffer org-agenda-buffer-name)))))))
19858 (defun org-write-agenda (file &optional nosettings)
19859 "Write the current buffer (an agenda view) as a file.
19860 Depending on the extension of the file name, plain text (.txt),
19861 HTML (.html or .htm) or Postscript (.ps) is produced.
19862 If NOSETTINGS is given, do not scope the settings of
19863 `org-agenda-exporter-settings' into the export commands. This is used when
19864 the settings have already been scoped and we do not wish to overrule other,
19865 higher priority settings."
19866 (interactive "FWrite agenda to file: ")
19867 (if (not (file-writable-p file))
19868 (error "Cannot write agenda to file %s" file))
19869 (cond
19870 ((string-match "\\.html?\\'" file) (require 'htmlize))
19871 ((string-match "\\.ps\\'" file) (require 'ps-print)))
19872 (org-let (if nosettings nil org-agenda-exporter-settings)
19873 '(save-excursion
19874 (save-window-excursion
19875 (cond
19876 ((string-match "\\.html?\\'" file)
19877 (set-buffer (htmlize-buffer (current-buffer)))
19879 (when (and org-agenda-export-html-style
19880 (string-match "<style>" org-agenda-export-html-style))
19881 ;; replace <style> section with org-agenda-export-html-style
19882 (goto-char (point-min))
19883 (kill-region (- (search-forward "<style") 6)
19884 (search-forward "</style>"))
19885 (insert org-agenda-export-html-style))
19886 (write-file file)
19887 (kill-buffer (current-buffer))
19888 (message "HTML written to %s" file))
19889 ((string-match "\\.ps\\'" file)
19890 (ps-print-buffer-with-faces file)
19891 (message "Postscript written to %s" file))
19893 (let ((bs (buffer-string)))
19894 (find-file file)
19895 (insert bs)
19896 (save-buffer 0)
19897 (kill-buffer (current-buffer))
19898 (message "Plain text written to %s" file))))))
19899 (set-buffer org-agenda-buffer-name)))
19901 (defmacro org-no-read-only (&rest body)
19902 "Inhibit read-only for BODY."
19903 `(let ((inhibit-read-only t)) ,@body))
19905 (defun org-check-for-org-mode ()
19906 "Make sure current buffer is in org-mode. Error if not."
19907 (or (org-mode-p)
19908 (error "Cannot execute org-mode agenda command on buffer in %s."
19909 major-mode)))
19911 (defun org-fit-agenda-window ()
19912 "Fit the window to the buffer size."
19913 (and (memq org-agenda-window-setup '(reorganize-frame))
19914 (fboundp 'fit-window-to-buffer)
19915 (fit-window-to-buffer
19917 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
19918 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
19920 ;;; Agenda file list
19922 (defun org-agenda-files (&optional unrestricted)
19923 "Get the list of agenda files.
19924 Optional UNRESTRICTED means return the full list even if a restriction
19925 is currently in place."
19926 (let ((files
19927 (cond
19928 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
19929 ((stringp org-agenda-files) (org-read-agenda-file-list))
19930 ((listp org-agenda-files) org-agenda-files)
19931 (t (error "Invalid value of `org-agenda-files'")))))
19932 (setq files (apply 'append
19933 (mapcar (lambda (f)
19934 (if (file-directory-p f)
19935 (directory-files f t
19936 org-agenda-file-regexp)
19937 (list f)))
19938 files)))
19939 (if org-agenda-skip-unavailable-files
19940 (delq nil
19941 (mapcar (function
19942 (lambda (file)
19943 (and (file-readable-p file) file)))
19944 files))
19945 files))) ; `org-check-agenda-file' will remove them from the list
19947 (defun org-edit-agenda-file-list ()
19948 "Edit the list of agenda files.
19949 Depending on setup, this either uses customize to edit the variable
19950 `org-agenda-files', or it visits the file that is holding the list. In the
19951 latter case, the buffer is set up in a way that saving it automatically kills
19952 the buffer and restores the previous window configuration."
19953 (interactive)
19954 (if (stringp org-agenda-files)
19955 (let ((cw (current-window-configuration)))
19956 (find-file org-agenda-files)
19957 (org-set-local 'org-window-configuration cw)
19958 (org-add-hook 'after-save-hook
19959 (lambda ()
19960 (set-window-configuration
19961 (prog1 org-window-configuration
19962 (kill-buffer (current-buffer))))
19963 (org-install-agenda-files-menu)
19964 (message "New agenda file list installed"))
19965 nil 'local)
19966 (message "%s" (substitute-command-keys
19967 "Edit list and finish with \\[save-buffer]")))
19968 (customize-variable 'org-agenda-files)))
19970 (defun org-store-new-agenda-file-list (list)
19971 "Set new value for the agenda file list and save it correcly."
19972 (if (stringp org-agenda-files)
19973 (let ((f org-agenda-files) b)
19974 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
19975 (with-temp-file f
19976 (insert (mapconcat 'identity list "\n") "\n")))
19977 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
19978 (setq org-agenda-files list)
19979 (customize-save-variable 'org-agenda-files org-agenda-files))))
19981 (defun org-read-agenda-file-list ()
19982 "Read the list of agenda files from a file."
19983 (when (stringp org-agenda-files)
19984 (with-temp-buffer
19985 (insert-file-contents org-agenda-files)
19986 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
19989 ;;;###autoload
19990 (defun org-cycle-agenda-files ()
19991 "Cycle through the files in `org-agenda-files'.
19992 If the current buffer visits an agenda file, find the next one in the list.
19993 If the current buffer does not, find the first agenda file."
19994 (interactive)
19995 (let* ((fs (org-agenda-files t))
19996 (files (append fs (list (car fs))))
19997 (tcf (if buffer-file-name (file-truename buffer-file-name)))
19998 file)
19999 (unless files (error "No agenda files"))
20000 (catch 'exit
20001 (while (setq file (pop files))
20002 (if (equal (file-truename file) tcf)
20003 (when (car files)
20004 (find-file (car files))
20005 (throw 'exit t))))
20006 (find-file (car fs)))
20007 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
20009 (defun org-agenda-file-to-front (&optional to-end)
20010 "Move/add the current file to the top of the agenda file list.
20011 If the file is not present in the list, it is added to the front. If it is
20012 present, it is moved there. With optional argument TO-END, add/move to the
20013 end of the list."
20014 (interactive "P")
20015 (let ((org-agenda-skip-unavailable-files nil)
20016 (file-alist (mapcar (lambda (x)
20017 (cons (file-truename x) x))
20018 (org-agenda-files t)))
20019 (ctf (file-truename buffer-file-name))
20020 x had)
20021 (setq x (assoc ctf file-alist) had x)
20023 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
20024 (if to-end
20025 (setq file-alist (append (delq x file-alist) (list x)))
20026 (setq file-alist (cons x (delq x file-alist))))
20027 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
20028 (org-install-agenda-files-menu)
20029 (message "File %s to %s of agenda file list"
20030 (if had "moved" "added") (if to-end "end" "front"))))
20032 (defun org-remove-file (&optional file)
20033 "Remove current file from the list of files in variable `org-agenda-files'.
20034 These are the files which are being checked for agenda entries.
20035 Optional argument FILE means, use this file instead of the current."
20036 (interactive)
20037 (let* ((org-agenda-skip-unavailable-files nil)
20038 (file (or file buffer-file-name))
20039 (true-file (file-truename file))
20040 (afile (abbreviate-file-name file))
20041 (files (delq nil (mapcar
20042 (lambda (x)
20043 (if (equal true-file
20044 (file-truename x))
20045 nil x))
20046 (org-agenda-files t)))))
20047 (if (not (= (length files) (length (org-agenda-files t))))
20048 (progn
20049 (org-store-new-agenda-file-list files)
20050 (org-install-agenda-files-menu)
20051 (message "Removed file: %s" afile))
20052 (message "File was not in list: %s (not removed)" afile))))
20054 (defun org-file-menu-entry (file)
20055 (vector file (list 'find-file file) t))
20057 (defun org-check-agenda-file (file)
20058 "Make sure FILE exists. If not, ask user what to do."
20059 (when (not (file-exists-p file))
20060 (message "non-existent file %s. [R]emove from list or [A]bort?"
20061 (abbreviate-file-name file))
20062 (let ((r (downcase (read-char-exclusive))))
20063 (cond
20064 ((equal r ?r)
20065 (org-remove-file file)
20066 (throw 'nextfile t))
20067 (t (error "Abort"))))))
20069 ;;; Agenda prepare and finalize
20071 (defvar org-agenda-multi nil) ; dynammically scoped
20072 (defvar org-agenda-buffer-name "*Org Agenda*")
20073 (defvar org-pre-agenda-window-conf nil)
20074 (defvar org-agenda-name nil)
20075 (defun org-prepare-agenda (&optional name)
20076 (setq org-todo-keywords-for-agenda nil)
20077 (setq org-done-keywords-for-agenda nil)
20078 (if org-agenda-multi
20079 (progn
20080 (setq buffer-read-only nil)
20081 (goto-char (point-max))
20082 (unless (or (bobp) org-agenda-compact-blocks)
20083 (insert "\n" (make-string (window-width) ?=) "\n"))
20084 (narrow-to-region (point) (point-max)))
20085 (org-agenda-maybe-reset-markers 'force)
20086 (org-prepare-agenda-buffers (org-agenda-files))
20087 (setq org-todo-keywords-for-agenda
20088 (org-uniquify org-todo-keywords-for-agenda))
20089 (setq org-done-keywords-for-agenda
20090 (org-uniquify org-done-keywords-for-agenda))
20091 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
20092 (awin (get-buffer-window abuf)))
20093 (cond
20094 ((equal (current-buffer) abuf) nil)
20095 (awin (select-window awin))
20096 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
20097 ((equal org-agenda-window-setup 'current-window)
20098 (switch-to-buffer abuf))
20099 ((equal org-agenda-window-setup 'other-window)
20100 (org-switch-to-buffer-other-window abuf))
20101 ((equal org-agenda-window-setup 'other-frame)
20102 (switch-to-buffer-other-frame abuf))
20103 ((equal org-agenda-window-setup 'reorganize-frame)
20104 (delete-other-windows)
20105 (org-switch-to-buffer-other-window abuf))))
20106 (setq buffer-read-only nil)
20107 (erase-buffer)
20108 (org-agenda-mode)
20109 (and name (not org-agenda-name)
20110 (org-set-local 'org-agenda-name name)))
20111 (setq buffer-read-only nil))
20113 (defun org-finalize-agenda ()
20114 "Finishing touch for the agenda buffer, called just before displaying it."
20115 (unless org-agenda-multi
20116 (save-excursion
20117 (let ((inhibit-read-only t))
20118 (goto-char (point-min))
20119 (while (org-activate-bracket-links (point-max))
20120 (add-text-properties (match-beginning 0) (match-end 0)
20121 '(face org-link)))
20122 (org-agenda-align-tags)
20123 (unless org-agenda-with-colors
20124 (remove-text-properties (point-min) (point-max) '(face nil))))
20125 (if (and (boundp 'org-overriding-columns-format)
20126 org-overriding-columns-format)
20127 (org-set-local 'org-overriding-columns-format
20128 org-overriding-columns-format))
20129 (if (and (boundp 'org-agenda-view-columns-initially)
20130 org-agenda-view-columns-initially)
20131 (org-agenda-columns))
20132 (when org-agenda-fontify-priorities
20133 (org-fontify-priorities))
20134 (run-hooks 'org-finalize-agenda-hook)
20135 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20138 (defun org-fontify-priorities ()
20139 "Make highest priority lines bold, and lowest italic."
20140 (interactive)
20141 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
20142 (org-delete-overlay o)))
20143 (org-overlays-in (point-min) (point-max)))
20144 (save-excursion
20145 (let ((inhibit-read-only t)
20146 b e p ov h l)
20147 (goto-char (point-min))
20148 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
20149 (setq h (or (get-char-property (point) 'org-highest-priority)
20150 org-highest-priority)
20151 l (or (get-char-property (point) 'org-lowest-priority)
20152 org-lowest-priority)
20153 p (string-to-char (match-string 1))
20154 b (match-beginning 0) e (point-at-eol)
20155 ov (org-make-overlay b e))
20156 (org-overlay-put
20157 ov 'face
20158 (cond ((listp org-agenda-fontify-priorities)
20159 (cdr (assoc p org-agenda-fontify-priorities)))
20160 ((equal p l) 'italic)
20161 ((equal p h) 'bold)))
20162 (org-overlay-put ov 'org-type 'org-priority)))))
20164 (defun org-prepare-agenda-buffers (files)
20165 "Create buffers for all agenda files, protect archived trees and comments."
20166 (interactive)
20167 (let ((pa '(:org-archived t))
20168 (pc '(:org-comment t))
20169 (pall '(:org-archived t :org-comment t))
20170 (inhibit-read-only t)
20171 (rea (concat ":" org-archive-tag ":"))
20172 bmp file re)
20173 (save-excursion
20174 (save-restriction
20175 (while (setq file (pop files))
20176 (if (bufferp file)
20177 (set-buffer file)
20178 (org-check-agenda-file file)
20179 (set-buffer (org-get-agenda-file-buffer file)))
20180 (widen)
20181 (setq bmp (buffer-modified-p))
20182 (org-refresh-category-properties)
20183 (setq org-todo-keywords-for-agenda
20184 (append org-todo-keywords-for-agenda org-todo-keywords-1))
20185 (setq org-done-keywords-for-agenda
20186 (append org-done-keywords-for-agenda org-done-keywords))
20187 (save-excursion
20188 (remove-text-properties (point-min) (point-max) pall)
20189 (when org-agenda-skip-archived-trees
20190 (goto-char (point-min))
20191 (while (re-search-forward rea nil t)
20192 (if (org-on-heading-p t)
20193 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
20194 (goto-char (point-min))
20195 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
20196 (while (re-search-forward re nil t)
20197 (add-text-properties
20198 (match-beginning 0) (org-end-of-subtree t) pc)))
20199 (set-buffer-modified-p bmp))))))
20201 (defvar org-agenda-skip-function nil
20202 "Function to be called at each match during agenda construction.
20203 If this function returns nil, the current match should not be skipped.
20204 Otherwise, the function must return a position from where the search
20205 should be continued.
20206 This may also be a Lisp form, it will be evaluated.
20207 Never set this variable using `setq' or so, because then it will apply
20208 to all future agenda commands. Instead, bind it with `let' to scope
20209 it dynamically into the agenda-constructing command. A good way to set
20210 it is through options in org-agenda-custom-commands.")
20212 (defun org-agenda-skip ()
20213 "Throw to `:skip' in places that should be skipped.
20214 Also moves point to the end of the skipped region, so that search can
20215 continue from there."
20216 (let ((p (point-at-bol)) to fp)
20217 (and org-agenda-skip-archived-trees
20218 (get-text-property p :org-archived)
20219 (org-end-of-subtree t)
20220 (throw :skip t))
20221 (and (get-text-property p :org-comment)
20222 (org-end-of-subtree t)
20223 (throw :skip t))
20224 (if (equal (char-after p) ?#) (throw :skip t))
20225 (when (and (or (setq fp (functionp org-agenda-skip-function))
20226 (consp org-agenda-skip-function))
20227 (setq to (save-excursion
20228 (save-match-data
20229 (if fp
20230 (funcall org-agenda-skip-function)
20231 (eval org-agenda-skip-function))))))
20232 (goto-char to)
20233 (throw :skip t))))
20235 (defvar org-agenda-markers nil
20236 "List of all currently active markers created by `org-agenda'.")
20237 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20238 "Creation time of the last agenda marker.")
20240 (defun org-agenda-new-marker (&optional pos)
20241 "Return a new agenda marker.
20242 Org-mode keeps a list of these markers and resets them when they are
20243 no longer in use."
20244 (let ((m (copy-marker (or pos (point)))))
20245 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20246 (push m org-agenda-markers)
20249 (defun org-agenda-maybe-reset-markers (&optional force)
20250 "Reset markers created by `org-agenda'. But only if they are old enough."
20251 (if (or (and force (not org-agenda-multi))
20252 (> (- (time-to-seconds (current-time))
20253 org-agenda-last-marker-time)
20255 (while org-agenda-markers
20256 (move-marker (pop org-agenda-markers) nil))))
20258 (defun org-get-agenda-file-buffer (file)
20259 "Get a buffer visiting FILE. If the buffer needs to be created, add
20260 it to the list of buffers which might be released later."
20261 (let ((buf (org-find-base-buffer-visiting file)))
20262 (if buf
20263 buf ; just return it
20264 ;; Make a new buffer and remember it
20265 (setq buf (find-file-noselect file))
20266 (if buf (push buf org-agenda-new-buffers))
20267 buf)))
20269 (defun org-release-buffers (blist)
20270 "Release all buffers in list, asking the user for confirmation when needed.
20271 When a buffer is unmodified, it is just killed. When modified, it is saved
20272 \(if the user agrees) and then killed."
20273 (let (buf file)
20274 (while (setq buf (pop blist))
20275 (setq file (buffer-file-name buf))
20276 (when (and (buffer-modified-p buf)
20277 file
20278 (y-or-n-p (format "Save file %s? " file)))
20279 (with-current-buffer buf (save-buffer)))
20280 (kill-buffer buf))))
20282 (defun org-get-category (&optional pos)
20283 "Get the category applying to position POS."
20284 (get-text-property (or pos (point)) 'org-category))
20286 ;;; Agenda timeline
20288 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20290 (defun org-timeline (&optional include-all)
20291 "Show a time-sorted view of the entries in the current org file.
20292 Only entries with a time stamp of today or later will be listed. With
20293 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20294 under the current date.
20295 If the buffer contains an active region, only check the region for
20296 dates."
20297 (interactive "P")
20298 (require 'calendar)
20299 (org-compile-prefix-format 'timeline)
20300 (org-set-sorting-strategy 'timeline)
20301 (let* ((dopast t)
20302 (dotodo include-all)
20303 (doclosed org-agenda-show-log)
20304 (entry buffer-file-name)
20305 (date (calendar-current-date))
20306 (beg (if (org-region-active-p) (region-beginning) (point-min)))
20307 (end (if (org-region-active-p) (region-end) (point-max)))
20308 (day-numbers (org-get-all-dates beg end 'no-ranges
20309 t doclosed ; always include today
20310 org-timeline-show-empty-dates))
20311 (org-deadline-warning-days 0)
20312 (org-agenda-only-exact-dates t)
20313 (today (time-to-days (current-time)))
20314 (past t)
20315 args
20316 s e rtn d emptyp)
20317 (setq org-agenda-redo-command
20318 (list 'progn
20319 (list 'org-switch-to-buffer-other-window (current-buffer))
20320 (list 'org-timeline (list 'quote include-all))))
20321 (if (not dopast)
20322 ;; Remove past dates from the list of dates.
20323 (setq day-numbers (delq nil (mapcar (lambda(x)
20324 (if (>= x today) x nil))
20325 day-numbers))))
20326 (org-prepare-agenda (concat "Timeline "
20327 (file-name-nondirectory buffer-file-name)))
20328 (if doclosed (push :closed args))
20329 (push :timestamp args)
20330 (push :deadline args)
20331 (push :scheduled args)
20332 (push :sexp args)
20333 (if dotodo (push :todo args))
20334 (while (setq d (pop day-numbers))
20335 (if (and (listp d) (eq (car d) :omitted))
20336 (progn
20337 (setq s (point))
20338 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20339 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20340 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20341 (if (and (>= d today)
20342 dopast
20343 past)
20344 (progn
20345 (setq past nil)
20346 (insert (make-string 79 ?-) "\n")))
20347 (setq date (calendar-gregorian-from-absolute d))
20348 (setq s (point))
20349 (setq rtn (and (not emptyp)
20350 (apply 'org-agenda-get-day-entries entry
20351 date args)))
20352 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20353 (progn
20354 (insert
20355 (if (stringp org-agenda-format-date)
20356 (format-time-string org-agenda-format-date
20357 (org-time-from-absolute date))
20358 (funcall org-agenda-format-date date))
20359 "\n")
20360 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20361 (put-text-property s (1- (point)) 'org-date-line t)
20362 (if (equal d today)
20363 (put-text-property s (1- (point)) 'org-today t))
20364 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20365 (put-text-property s (1- (point)) 'day d)))))
20366 (goto-char (point-min))
20367 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20368 (point-min)))
20369 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20370 (org-finalize-agenda)
20371 (setq buffer-read-only t)))
20373 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty pre-re)
20374 "Return a list of all relevant day numbers from BEG to END buffer positions.
20375 If NO-RANGES is non-nil, include only the start and end dates of a range,
20376 not every single day in the range. If FORCE-TODAY is non-nil, make
20377 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20378 inactive time stamps (those in square brackets) are included.
20379 When EMPTY is non-nil, also include days without any entries."
20380 (let ((re (concat
20381 (if pre-re pre-re "")
20382 (if inactive org-ts-regexp-both org-ts-regexp)))
20383 dates dates1 date day day1 day2 ts1 ts2)
20384 (if force-today
20385 (setq dates (list (time-to-days (current-time)))))
20386 (save-excursion
20387 (goto-char beg)
20388 (while (re-search-forward re end t)
20389 (setq day (time-to-days (org-time-string-to-time
20390 (substring (match-string 1) 0 10))))
20391 (or (memq day dates) (push day dates)))
20392 (unless no-ranges
20393 (goto-char beg)
20394 (while (re-search-forward org-tr-regexp end t)
20395 (setq ts1 (substring (match-string 1) 0 10)
20396 ts2 (substring (match-string 2) 0 10)
20397 day1 (time-to-days (org-time-string-to-time ts1))
20398 day2 (time-to-days (org-time-string-to-time ts2)))
20399 (while (< (setq day1 (1+ day1)) day2)
20400 (or (memq day1 dates) (push day1 dates)))))
20401 (setq dates (sort dates '<))
20402 (when empty
20403 (while (setq day (pop dates))
20404 (setq day2 (car dates))
20405 (push day dates1)
20406 (when (and day2 empty)
20407 (if (or (eq empty t)
20408 (and (numberp empty) (<= (- day2 day) empty)))
20409 (while (< (setq day (1+ day)) day2)
20410 (push (list day) dates1))
20411 (push (cons :omitted (- day2 day)) dates1))))
20412 (setq dates (nreverse dates1)))
20413 dates)))
20415 ;;; Agenda Daily/Weekly
20417 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
20418 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
20419 (defvar org-agenda-last-arguments nil
20420 "The arguments of the previous call to org-agenda")
20421 (defvar org-starting-day nil) ; local variable in the agenda buffer
20422 (defvar org-agenda-span nil) ; local variable in the agenda buffer
20423 (defvar org-include-all-loc nil) ; local variable
20424 (defvar org-agenda-remove-date nil) ; dynamically scoped
20426 ;;;###autoload
20427 (defun org-agenda-list (&optional include-all start-day ndays)
20428 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
20429 The view will be for the current day or week, but from the overview buffer
20430 you will be able to go to other days/weeks.
20432 With one \\[universal-argument] prefix argument INCLUDE-ALL,
20433 all unfinished TODO items will also be shown, before the agenda.
20434 This feature is considered obsolete, please use the TODO list or a block
20435 agenda instead.
20437 With a numeric prefix argument in an interactive call, the agenda will
20438 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
20439 the number of days. NDAYS defaults to `org-agenda-ndays'.
20441 START-DAY defaults to TODAY, or to the most recent match for the weekday
20442 given in `org-agenda-start-on-weekday'."
20443 (interactive "P")
20444 (if (and (integerp include-all) (> include-all 0))
20445 (setq ndays include-all include-all nil))
20446 (setq ndays (or ndays org-agenda-ndays)
20447 start-day (or start-day org-agenda-start-day))
20448 (if org-agenda-overriding-arguments
20449 (setq include-all (car org-agenda-overriding-arguments)
20450 start-day (nth 1 org-agenda-overriding-arguments)
20451 ndays (nth 2 org-agenda-overriding-arguments)))
20452 (if (stringp start-day)
20453 ;; Convert to an absolute day number
20454 (setq start-day (time-to-days (org-read-date nil t start-day))))
20455 (setq org-agenda-last-arguments (list include-all start-day ndays))
20456 (org-compile-prefix-format 'agenda)
20457 (org-set-sorting-strategy 'agenda)
20458 (require 'calendar)
20459 (let* ((org-agenda-start-on-weekday
20460 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
20461 org-agenda-start-on-weekday nil))
20462 (thefiles (org-agenda-files))
20463 (files thefiles)
20464 (today (time-to-days
20465 (time-subtract (current-time)
20466 (list 0 (* 3600 org-extend-today-until) 0))))
20467 (sd (or start-day today))
20468 (start (if (or (null org-agenda-start-on-weekday)
20469 (< org-agenda-ndays 7))
20471 (let* ((nt (calendar-day-of-week
20472 (calendar-gregorian-from-absolute sd)))
20473 (n1 org-agenda-start-on-weekday)
20474 (d (- nt n1)))
20475 (- sd (+ (if (< d 0) 7 0) d)))))
20476 (day-numbers (list start))
20477 (day-cnt 0)
20478 (inhibit-redisplay (not debug-on-error))
20479 s e rtn rtnall file date d start-pos end-pos todayp nd)
20480 (setq org-agenda-redo-command
20481 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
20482 ;; Make the list of days
20483 (setq ndays (or ndays org-agenda-ndays)
20484 nd ndays)
20485 (while (> ndays 1)
20486 (push (1+ (car day-numbers)) day-numbers)
20487 (setq ndays (1- ndays)))
20488 (setq day-numbers (nreverse day-numbers))
20489 (org-prepare-agenda "Day/Week")
20490 (org-set-local 'org-starting-day (car day-numbers))
20491 (org-set-local 'org-include-all-loc include-all)
20492 (org-set-local 'org-agenda-span
20493 (org-agenda-ndays-to-span nd))
20494 (when (and (or include-all org-agenda-include-all-todo)
20495 (member today day-numbers))
20496 (setq files thefiles
20497 rtnall nil)
20498 (while (setq file (pop files))
20499 (catch 'nextfile
20500 (org-check-agenda-file file)
20501 (setq date (calendar-gregorian-from-absolute today)
20502 rtn (org-agenda-get-day-entries
20503 file date :todo))
20504 (setq rtnall (append rtnall rtn))))
20505 (when rtnall
20506 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
20507 (add-text-properties (point-min) (1- (point))
20508 (list 'face 'org-agenda-structure))
20509 (insert (org-finalize-agenda-entries rtnall) "\n")))
20510 (unless org-agenda-compact-blocks
20511 (setq s (point))
20512 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
20513 "-agenda:\n")
20514 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
20515 'org-date-line t)))
20516 (while (setq d (pop day-numbers))
20517 (setq date (calendar-gregorian-from-absolute d)
20518 s (point))
20519 (if (or (setq todayp (= d today))
20520 (and (not start-pos) (= d sd)))
20521 (setq start-pos (point))
20522 (if (and start-pos (not end-pos))
20523 (setq end-pos (point))))
20524 (setq files thefiles
20525 rtnall nil)
20526 (while (setq file (pop files))
20527 (catch 'nextfile
20528 (org-check-agenda-file file)
20529 (if org-agenda-show-log
20530 (setq rtn (org-agenda-get-day-entries
20531 file date
20532 :deadline :scheduled :timestamp :sexp :closed))
20533 (setq rtn (org-agenda-get-day-entries
20534 file date
20535 :deadline :scheduled :sexp :timestamp)))
20536 (setq rtnall (append rtnall rtn))))
20537 (if org-agenda-include-diary
20538 (progn
20539 (require 'diary-lib)
20540 (setq rtn (org-get-entries-from-diary date))
20541 (setq rtnall (append rtnall rtn))))
20542 (if (or rtnall org-agenda-show-all-dates)
20543 (progn
20544 (setq day-cnt (1+ day-cnt))
20545 (insert
20546 (if (stringp org-agenda-format-date)
20547 (format-time-string org-agenda-format-date
20548 (org-time-from-absolute date))
20549 (funcall org-agenda-format-date date))
20550 "\n")
20551 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20552 (put-text-property s (1- (point)) 'org-date-line t)
20553 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
20554 (if todayp (put-text-property s (1- (point)) 'org-today t))
20555 (if rtnall (insert
20556 (org-finalize-agenda-entries
20557 (org-agenda-add-time-grid-maybe
20558 rtnall nd todayp))
20559 "\n"))
20560 (put-text-property s (1- (point)) 'day d)
20561 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
20562 (goto-char (point-min))
20563 (org-fit-agenda-window)
20564 (unless (and (pos-visible-in-window-p (point-min))
20565 (pos-visible-in-window-p (point-max)))
20566 (goto-char (1- (point-max)))
20567 (recenter -1)
20568 (if (not (pos-visible-in-window-p (or start-pos 1)))
20569 (progn
20570 (goto-char (or start-pos 1))
20571 (recenter 1))))
20572 (goto-char (or start-pos 1))
20573 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
20574 (org-finalize-agenda)
20575 (setq buffer-read-only t)
20576 (message "")))
20578 (defun org-agenda-ndays-to-span (n)
20579 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
20581 ;;; Agenda TODO list
20583 (defvar org-select-this-todo-keyword nil)
20584 (defvar org-last-arg nil)
20586 ;;;###autoload
20587 (defun org-todo-list (arg)
20588 "Show all TODO entries from all agenda file in a single list.
20589 The prefix arg can be used to select a specific TODO keyword and limit
20590 the list to these. When using \\[universal-argument], you will be prompted
20591 for a keyword. A numeric prefix directly selects the Nth keyword in
20592 `org-todo-keywords-1'."
20593 (interactive "P")
20594 (require 'calendar)
20595 (org-compile-prefix-format 'todo)
20596 (org-set-sorting-strategy 'todo)
20597 (org-prepare-agenda "TODO")
20598 (let* ((today (time-to-days (current-time)))
20599 (date (calendar-gregorian-from-absolute today))
20600 (kwds org-todo-keywords-for-agenda)
20601 (completion-ignore-case t)
20602 (org-select-this-todo-keyword
20603 (if (stringp arg) arg
20604 (and arg (integerp arg) (> arg 0)
20605 (nth (1- arg) kwds))))
20606 rtn rtnall files file pos)
20607 (when (equal arg '(4))
20608 (setq org-select-this-todo-keyword
20609 (completing-read "Keyword (or KWD1|K2D2|...): "
20610 (mapcar 'list kwds) nil nil)))
20611 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
20612 (org-set-local 'org-last-arg arg)
20613 (setq org-agenda-redo-command
20614 '(org-todo-list (or current-prefix-arg org-last-arg)))
20615 (setq files (org-agenda-files)
20616 rtnall nil)
20617 (while (setq file (pop files))
20618 (catch 'nextfile
20619 (org-check-agenda-file file)
20620 (setq rtn (org-agenda-get-day-entries file date :todo))
20621 (setq rtnall (append rtnall rtn))))
20622 (if org-agenda-overriding-header
20623 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20624 nil 'face 'org-agenda-structure) "\n")
20625 (insert "Global list of TODO items of type: ")
20626 (add-text-properties (point-min) (1- (point))
20627 (list 'face 'org-agenda-structure))
20628 (setq pos (point))
20629 (insert (or org-select-this-todo-keyword "ALL") "\n")
20630 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20631 (setq pos (point))
20632 (unless org-agenda-multi
20633 (insert "Available with `N r': (0)ALL")
20634 (let ((n 0) s)
20635 (mapc (lambda (x)
20636 (setq s (format "(%d)%s" (setq n (1+ n)) x))
20637 (if (> (+ (current-column) (string-width s) 1) (frame-width))
20638 (insert "\n "))
20639 (insert " " s))
20640 kwds))
20641 (insert "\n"))
20642 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20643 (when rtnall
20644 (insert (org-finalize-agenda-entries rtnall) "\n"))
20645 (goto-char (point-min))
20646 (org-fit-agenda-window)
20647 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
20648 (org-finalize-agenda)
20649 (setq buffer-read-only t)))
20651 ;;; Agenda tags match
20653 ;;;###autoload
20654 (defun org-tags-view (&optional todo-only match)
20655 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
20656 The prefix arg TODO-ONLY limits the search to TODO entries."
20657 (interactive "P")
20658 (org-compile-prefix-format 'tags)
20659 (org-set-sorting-strategy 'tags)
20660 (let* ((org-tags-match-list-sublevels
20661 (if todo-only t org-tags-match-list-sublevels))
20662 (completion-ignore-case t)
20663 rtn rtnall files file pos matcher
20664 buffer)
20665 (setq matcher (org-make-tags-matcher match)
20666 match (car matcher) matcher (cdr matcher))
20667 (org-prepare-agenda (concat "TAGS " match))
20668 (setq org-agenda-redo-command
20669 (list 'org-tags-view (list 'quote todo-only)
20670 (list 'if 'current-prefix-arg nil match)))
20671 (setq files (org-agenda-files)
20672 rtnall nil)
20673 (while (setq file (pop files))
20674 (catch 'nextfile
20675 (org-check-agenda-file file)
20676 (setq buffer (if (file-exists-p file)
20677 (org-get-agenda-file-buffer file)
20678 (error "No such file %s" file)))
20679 (if (not buffer)
20680 ;; If file does not exist, merror message to agenda
20681 (setq rtn (list
20682 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
20683 rtnall (append rtnall rtn))
20684 (with-current-buffer buffer
20685 (unless (org-mode-p)
20686 (error "Agenda file %s is not in `org-mode'" file))
20687 (save-excursion
20688 (save-restriction
20689 (if org-agenda-restrict
20690 (narrow-to-region org-agenda-restrict-begin
20691 org-agenda-restrict-end)
20692 (widen))
20693 (setq rtn (org-scan-tags 'agenda matcher todo-only))
20694 (setq rtnall (append rtnall rtn))))))))
20695 (if org-agenda-overriding-header
20696 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20697 nil 'face 'org-agenda-structure) "\n")
20698 (insert "Headlines with TAGS match: ")
20699 (add-text-properties (point-min) (1- (point))
20700 (list 'face 'org-agenda-structure))
20701 (setq pos (point))
20702 (insert match "\n")
20703 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20704 (setq pos (point))
20705 (unless org-agenda-multi
20706 (insert "Press `C-u r' to search again with new search string\n"))
20707 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20708 (when rtnall
20709 (insert (org-finalize-agenda-entries rtnall) "\n"))
20710 (goto-char (point-min))
20711 (org-fit-agenda-window)
20712 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
20713 (org-finalize-agenda)
20714 (setq buffer-read-only t)))
20716 ;;; Agenda Finding stuck projects
20718 (defvar org-agenda-skip-regexp nil
20719 "Regular expression used in skipping subtrees for the agenda.
20720 This is basically a temporary global variable that can be set and then
20721 used by user-defined selections using `org-agenda-skip-function'.")
20723 (defvar org-agenda-overriding-header nil
20724 "When this is set during todo and tags searches, will replace header.")
20726 (defun org-agenda-skip-subtree-when-regexp-matches ()
20727 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
20728 If yes, it returns the end position of this tree, causing agenda commands
20729 to skip this subtree. This is a function that can be put into
20730 `org-agenda-skip-function' for the duration of a command."
20731 (let ((end (save-excursion (org-end-of-subtree t)))
20732 skip)
20733 (save-excursion
20734 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
20735 (and skip end)))
20737 (defun org-agenda-skip-entry-if (&rest conditions)
20738 "Skip entry if any of CONDITIONS is true.
20739 See `org-agenda-skip-if' for details."
20740 (org-agenda-skip-if nil conditions))
20742 (defun org-agenda-skip-subtree-if (&rest conditions)
20743 "Skip entry if any of CONDITIONS is true.
20744 See `org-agenda-skip-if' for details."
20745 (org-agenda-skip-if t conditions))
20747 (defun org-agenda-skip-if (subtree conditions)
20748 "Checks current entity for CONDITIONS.
20749 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
20750 the entry, i.e. the text before the next heading is checked.
20752 CONDITIONS is a list of symbols, boolean OR is used to combine the results
20753 from different tests. Valid conditions are:
20755 scheduled Check if there is a scheduled cookie
20756 notscheduled Check if there is no scheduled cookie
20757 deadline Check if there is a deadline
20758 notdeadline Check if there is no deadline
20759 regexp Check if regexp matches
20760 notregexp Check if regexp does not match.
20762 The regexp is taken from the conditions list, it must come right after
20763 the `regexp' or `notregexp' element.
20765 If any of these conditions is met, this function returns the end point of
20766 the entity, causing the search to continue from there. This is a function
20767 that can be put into `org-agenda-skip-function' for the duration of a command."
20768 (let (beg end m)
20769 (org-back-to-heading t)
20770 (setq beg (point)
20771 end (if subtree
20772 (progn (org-end-of-subtree t) (point))
20773 (progn (outline-next-heading) (1- (point)))))
20774 (goto-char beg)
20775 (and
20777 (and (memq 'scheduled conditions)
20778 (re-search-forward org-scheduled-time-regexp end t))
20779 (and (memq 'notscheduled conditions)
20780 (not (re-search-forward org-scheduled-time-regexp end t)))
20781 (and (memq 'deadline conditions)
20782 (re-search-forward org-deadline-time-regexp end t))
20783 (and (memq 'notdeadline conditions)
20784 (not (re-search-forward org-deadline-time-regexp end t)))
20785 (and (setq m (memq 'regexp conditions))
20786 (stringp (nth 1 m))
20787 (re-search-forward (nth 1 m) end t))
20788 (and (setq m (memq 'notregexp conditions))
20789 (stringp (nth 1 m))
20790 (not (re-search-forward (nth 1 m) end t))))
20791 end)))
20793 ;;;###autoload
20794 (defun org-agenda-list-stuck-projects (&rest ignore)
20795 "Create agenda view for projects that are stuck.
20796 Stuck projects are project that have no next actions. For the definitions
20797 of what a project is and how to check if it stuck, customize the variable
20798 `org-stuck-projects'.
20799 MATCH is being ignored."
20800 (interactive)
20801 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
20802 ;; FIXME: we could have used org-agenda-skip-if here.
20803 (org-agenda-overriding-header "List of stuck projects: ")
20804 (matcher (nth 0 org-stuck-projects))
20805 (todo (nth 1 org-stuck-projects))
20806 (todo-wds (if (member "*" todo)
20807 (progn
20808 (org-prepare-agenda-buffers (org-agenda-files))
20809 (org-delete-all
20810 org-done-keywords-for-agenda
20811 (copy-sequence org-todo-keywords-for-agenda)))
20812 todo))
20813 (todo-re (concat "^\\*+[ \t]+\\("
20814 (mapconcat 'identity todo-wds "\\|")
20815 "\\)\\>"))
20816 (tags (nth 2 org-stuck-projects))
20817 (tags-re (if (member "*" tags)
20818 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
20819 (concat "^\\*+ .*:\\("
20820 (mapconcat 'identity tags "\\|")
20821 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
20822 (gen-re (nth 3 org-stuck-projects))
20823 (re-list
20824 (delq nil
20825 (list
20826 (if todo todo-re)
20827 (if tags tags-re)
20828 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
20829 gen-re)))))
20830 (setq org-agenda-skip-regexp
20831 (if re-list
20832 (mapconcat 'identity re-list "\\|")
20833 (error "No information how to identify unstuck projects")))
20834 (org-tags-view nil matcher)
20835 (with-current-buffer org-agenda-buffer-name
20836 (setq org-agenda-redo-command
20837 '(org-agenda-list-stuck-projects
20838 (or current-prefix-arg org-last-arg))))))
20840 ;;; Diary integration
20842 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
20844 (defun org-get-entries-from-diary (date)
20845 "Get the (Emacs Calendar) diary entries for DATE."
20846 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
20847 (diary-display-hook '(fancy-diary-display))
20848 (pop-up-frames nil)
20849 (list-diary-entries-hook
20850 (cons 'org-diary-default-entry list-diary-entries-hook))
20851 (diary-file-name-prefix-function nil) ; turn this feature off
20852 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
20853 entries
20854 (org-disable-agenda-to-diary t))
20855 (save-excursion
20856 (save-window-excursion
20857 (funcall (if (fboundp 'diary-list-entries)
20858 'diary-list-entries 'list-diary-entries)
20859 date 1)))
20860 (if (not (get-buffer fancy-diary-buffer))
20861 (setq entries nil)
20862 (with-current-buffer fancy-diary-buffer
20863 (setq buffer-read-only nil)
20864 (if (zerop (buffer-size))
20865 ;; No entries
20866 (setq entries nil)
20867 ;; Omit the date and other unnecessary stuff
20868 (org-agenda-cleanup-fancy-diary)
20869 ;; Add prefix to each line and extend the text properties
20870 (if (zerop (buffer-size))
20871 (setq entries nil)
20872 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
20873 (set-buffer-modified-p nil)
20874 (kill-buffer fancy-diary-buffer)))
20875 (when entries
20876 (setq entries (org-split-string entries "\n"))
20877 (setq entries
20878 (mapcar
20879 (lambda (x)
20880 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
20881 ;; Extend the text properties to the beginning of the line
20882 (org-add-props x (text-properties-at (1- (length x)) x)
20883 'type "diary" 'date date))
20884 entries)))))
20886 (defun org-agenda-cleanup-fancy-diary ()
20887 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
20888 This gets rid of the date, the underline under the date, and
20889 the dummy entry installed by `org-mode' to ensure non-empty diary for each
20890 date. It also removes lines that contain only whitespace."
20891 (goto-char (point-min))
20892 (if (looking-at ".*?:[ \t]*")
20893 (progn
20894 (replace-match "")
20895 (re-search-forward "\n=+$" nil t)
20896 (replace-match "")
20897 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
20898 (re-search-forward "\n=+$" nil t)
20899 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
20900 (goto-char (point-min))
20901 (while (re-search-forward "^ +\n" nil t)
20902 (replace-match ""))
20903 (goto-char (point-min))
20904 (if (re-search-forward "^Org-mode dummy\n?" nil t)
20905 (replace-match "")))
20907 ;; Make sure entries from the diary have the right text properties.
20908 (eval-after-load "diary-lib"
20909 '(if (boundp 'diary-modify-entry-list-string-function)
20910 ;; We can rely on the hook, nothing to do
20912 ;; Hook not avaiable, must use advice to make this work
20913 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
20914 "Make the position visible."
20915 (if (and org-disable-agenda-to-diary ;; called from org-agenda
20916 (stringp string)
20917 buffer-file-name)
20918 (setq string (org-modify-diary-entry-string string))))))
20920 (defun org-modify-diary-entry-string (string)
20921 "Add text properties to string, allowing org-mode to act on it."
20922 (org-add-props string nil
20923 'mouse-face 'highlight
20924 'keymap org-agenda-keymap
20925 'help-echo (if buffer-file-name
20926 (format "mouse-2 or RET jump to diary file %s"
20927 (abbreviate-file-name buffer-file-name))
20929 'org-agenda-diary-link t
20930 'org-marker (org-agenda-new-marker (point-at-bol))))
20932 (defun org-diary-default-entry ()
20933 "Add a dummy entry to the diary.
20934 Needed to avoid empty dates which mess up holiday display."
20935 ;; Catch the error if dealing with the new add-to-diary-alist
20936 (when org-disable-agenda-to-diary
20937 (condition-case nil
20938 (add-to-diary-list original-date "Org-mode dummy" "")
20939 (error
20940 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
20942 ;;;###autoload
20943 (defun org-diary (&rest args)
20944 "Return diary information from org-files.
20945 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
20946 It accesses org files and extracts information from those files to be
20947 listed in the diary. The function accepts arguments specifying what
20948 items should be listed. The following arguments are allowed:
20950 :timestamp List the headlines of items containing a date stamp or
20951 date range matching the selected date. Deadlines will
20952 also be listed, on the expiration day.
20954 :sexp List entries resulting from diary-like sexps.
20956 :deadline List any deadlines past due, or due within
20957 `org-deadline-warning-days'. The listing occurs only
20958 in the diary for *today*, not at any other date. If
20959 an entry is marked DONE, it is no longer listed.
20961 :scheduled List all items which are scheduled for the given date.
20962 The diary for *today* also contains items which were
20963 scheduled earlier and are not yet marked DONE.
20965 :todo List all TODO items from the org-file. This may be a
20966 long list - so this is not turned on by default.
20967 Like deadlines, these entries only show up in the
20968 diary for *today*, not at any other date.
20970 The call in the diary file should look like this:
20972 &%%(org-diary) ~/path/to/some/orgfile.org
20974 Use a separate line for each org file to check. Or, if you omit the file name,
20975 all files listed in `org-agenda-files' will be checked automatically:
20977 &%%(org-diary)
20979 If you don't give any arguments (as in the example above), the default
20980 arguments (:deadline :scheduled :timestamp :sexp) are used.
20981 So the example above may also be written as
20983 &%%(org-diary :deadline :timestamp :sexp :scheduled)
20985 The function expects the lisp variables `entry' and `date' to be provided
20986 by the caller, because this is how the calendar works. Don't use this
20987 function from a program - use `org-agenda-get-day-entries' instead."
20988 (org-agenda-maybe-reset-markers)
20989 (org-compile-prefix-format 'agenda)
20990 (org-set-sorting-strategy 'agenda)
20991 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
20992 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
20993 (list entry)
20994 (org-agenda-files t)))
20995 file rtn results)
20996 (org-prepare-agenda-buffers files)
20997 ;; If this is called during org-agenda, don't return any entries to
20998 ;; the calendar. Org Agenda will list these entries itself.
20999 (if org-disable-agenda-to-diary (setq files nil))
21000 (while (setq file (pop files))
21001 (setq rtn (apply 'org-agenda-get-day-entries file date args))
21002 (setq results (append results rtn)))
21003 (if results
21004 (concat (org-finalize-agenda-entries results) "\n"))))
21006 ;;; Agenda entry finders
21008 (defun org-agenda-get-day-entries (file date &rest args)
21009 "Does the work for `org-diary' and `org-agenda'.
21010 FILE is the path to a file to be checked for entries. DATE is date like
21011 the one returned by `calendar-current-date'. ARGS are symbols indicating
21012 which kind of entries should be extracted. For details about these, see
21013 the documentation of `org-diary'."
21014 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21015 (let* ((org-startup-folded nil)
21016 (org-startup-align-all-tables nil)
21017 (buffer (if (file-exists-p file)
21018 (org-get-agenda-file-buffer file)
21019 (error "No such file %s" file)))
21020 arg results rtn)
21021 (if (not buffer)
21022 ;; If file does not exist, make sure an error message ends up in diary
21023 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21024 (with-current-buffer buffer
21025 (unless (org-mode-p)
21026 (error "Agenda file %s is not in `org-mode'" file))
21027 (let ((case-fold-search nil))
21028 (save-excursion
21029 (save-restriction
21030 (if org-agenda-restrict
21031 (narrow-to-region org-agenda-restrict-begin
21032 org-agenda-restrict-end)
21033 (widen))
21034 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
21035 (while (setq arg (pop args))
21036 (cond
21037 ((and (eq arg :todo)
21038 (equal date (calendar-current-date)))
21039 (setq rtn (org-agenda-get-todos))
21040 (setq results (append results rtn)))
21041 ((eq arg :timestamp)
21042 (setq rtn (org-agenda-get-blocks))
21043 (setq results (append results rtn))
21044 (setq rtn (org-agenda-get-timestamps))
21045 (setq results (append results rtn)))
21046 ((eq arg :sexp)
21047 (setq rtn (org-agenda-get-sexps))
21048 (setq results (append results rtn)))
21049 ((eq arg :scheduled)
21050 (setq rtn (org-agenda-get-scheduled))
21051 (setq results (append results rtn)))
21052 ((eq arg :closed)
21053 (setq rtn (org-agenda-get-closed))
21054 (setq results (append results rtn)))
21055 ((eq arg :deadline)
21056 (setq rtn (org-agenda-get-deadlines))
21057 (setq results (append results rtn))))))))
21058 results))))
21060 (defun org-entry-is-todo-p ()
21061 (member (org-get-todo-state) org-not-done-keywords))
21063 (defun org-entry-is-done-p ()
21064 (member (org-get-todo-state) org-done-keywords))
21066 (defun org-get-todo-state ()
21067 (save-excursion
21068 (org-back-to-heading t)
21069 (and (looking-at org-todo-line-regexp)
21070 (match-end 2)
21071 (match-string 2))))
21073 (defun org-at-date-range-p (&optional inactive-ok)
21074 "Is the cursor inside a date range?"
21075 (interactive)
21076 (save-excursion
21077 (catch 'exit
21078 (let ((pos (point)))
21079 (skip-chars-backward "^[<\r\n")
21080 (skip-chars-backward "<[")
21081 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21082 (>= (match-end 0) pos)
21083 (throw 'exit t))
21084 (skip-chars-backward "^<[\r\n")
21085 (skip-chars-backward "<[")
21086 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21087 (>= (match-end 0) pos)
21088 (throw 'exit t)))
21089 nil)))
21091 (defun org-agenda-get-todos ()
21092 "Return the TODO information for agenda display."
21093 (let* ((props (list 'face nil
21094 'done-face 'org-done
21095 'org-not-done-regexp org-not-done-regexp
21096 'org-todo-regexp org-todo-regexp
21097 'mouse-face 'highlight
21098 'keymap org-agenda-keymap
21099 'help-echo
21100 (format "mouse-2 or RET jump to org file %s"
21101 (abbreviate-file-name buffer-file-name))))
21102 ;; FIXME: get rid of the \n at some point but watch out
21103 (regexp (concat "^\\*+[ \t]+\\("
21104 (if org-select-this-todo-keyword
21105 (if (equal org-select-this-todo-keyword "*")
21106 org-todo-regexp
21107 (concat "\\<\\("
21108 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
21109 "\\)\\>"))
21110 org-not-done-regexp)
21111 "[^\n\r]*\\)"))
21112 marker priority category tags
21113 ee txt beg end)
21114 (goto-char (point-min))
21115 (while (re-search-forward regexp nil t)
21116 (catch :skip
21117 (save-match-data
21118 (beginning-of-line)
21119 (setq beg (point) end (progn (outline-next-heading) (point)))
21120 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
21121 (re-search-forward org-ts-regexp end t))
21122 (and org-agenda-todo-ignore-scheduled (goto-char beg)
21123 (re-search-forward org-scheduled-time-regexp end t))
21124 (and org-agenda-todo-ignore-deadlines (goto-char beg)
21125 (re-search-forward org-deadline-time-regexp end t)
21126 (org-deadline-close (match-string 1))))
21127 (goto-char (1+ beg))
21128 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
21129 (throw :skip nil)))
21130 (goto-char beg)
21131 (org-agenda-skip)
21132 (goto-char (match-beginning 1))
21133 (setq marker (org-agenda-new-marker (match-beginning 0))
21134 category (org-get-category)
21135 tags (org-get-tags-at (point))
21136 txt (org-format-agenda-item "" (match-string 1) category tags)
21137 priority (1+ (org-get-priority txt)))
21138 (org-add-props txt props
21139 'org-marker marker 'org-hd-marker marker
21140 'priority priority 'org-category category
21141 'type "todo")
21142 (push txt ee)
21143 (if org-agenda-todo-list-sublevels
21144 (goto-char (match-end 1))
21145 (org-end-of-subtree 'invisible))))
21146 (nreverse ee)))
21148 (defconst org-agenda-no-heading-message
21149 "No heading for this item in buffer or region.")
21151 (defun org-agenda-get-timestamps ()
21152 "Return the date stamp information for agenda display."
21153 (let* ((props (list 'face nil
21154 'org-not-done-regexp org-not-done-regexp
21155 'org-todo-regexp org-todo-regexp
21156 'mouse-face 'highlight
21157 'keymap org-agenda-keymap
21158 'help-echo
21159 (format "mouse-2 or RET jump to org file %s"
21160 (abbreviate-file-name buffer-file-name))))
21161 (d1 (calendar-absolute-from-gregorian date))
21162 (remove-re
21163 (concat
21164 (regexp-quote
21165 (format-time-string
21166 "<%Y-%m-%d"
21167 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
21168 ".*?>"))
21169 (regexp
21170 (concat
21171 (regexp-quote
21172 (substring
21173 (format-time-string
21174 (car org-time-stamp-formats)
21175 (apply 'encode-time ; DATE bound by calendar
21176 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21177 0 11))
21178 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
21179 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
21180 marker hdmarker deadlinep scheduledp donep tmp priority category
21181 ee txt timestr tags b0 b3 e3 head)
21182 (goto-char (point-min))
21183 (while (re-search-forward regexp nil t)
21184 (setq b0 (match-beginning 0)
21185 b3 (match-beginning 3) e3 (match-end 3))
21186 (catch :skip
21187 (and (org-at-date-range-p) (throw :skip nil))
21188 (org-agenda-skip)
21189 (if (and (match-end 1)
21190 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
21191 (throw :skip nil))
21192 (if (and e3
21193 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
21194 (throw :skip nil))
21195 (setq marker (org-agenda-new-marker b0)
21196 category (org-get-category b0)
21197 tmp (buffer-substring (max (point-min)
21198 (- b0 org-ds-keyword-length))
21200 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
21201 deadlinep (string-match org-deadline-regexp tmp)
21202 scheduledp (string-match org-scheduled-regexp tmp)
21203 donep (org-entry-is-done-p))
21204 (if (or scheduledp deadlinep) (throw :skip t))
21205 (if (string-match ">" timestr)
21206 ;; substring should only run to end of time stamp
21207 (setq timestr (substring timestr 0 (match-end 0))))
21208 (save-excursion
21209 (if (re-search-backward "^\\*+ " nil t)
21210 (progn
21211 (goto-char (match-beginning 0))
21212 (setq hdmarker (org-agenda-new-marker)
21213 tags (org-get-tags-at))
21214 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21215 (setq head (match-string 1))
21216 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
21217 (setq txt (org-format-agenda-item
21218 nil head category tags timestr nil
21219 remove-re)))
21220 (setq txt org-agenda-no-heading-message))
21221 (setq priority (org-get-priority txt))
21222 (org-add-props txt props
21223 'org-marker marker 'org-hd-marker hdmarker)
21224 (org-add-props txt nil 'priority priority
21225 'org-category category 'date date
21226 'type "timestamp")
21227 (push txt ee))
21228 (outline-next-heading)))
21229 (nreverse ee)))
21231 (defun org-agenda-get-sexps ()
21232 "Return the sexp information for agenda display."
21233 (require 'diary-lib)
21234 (let* ((props (list 'face nil
21235 'mouse-face 'highlight
21236 'keymap org-agenda-keymap
21237 'help-echo
21238 (format "mouse-2 or RET jump to org file %s"
21239 (abbreviate-file-name buffer-file-name))))
21240 (regexp "^&?%%(")
21241 marker category ee txt tags entry result beg b sexp sexp-entry)
21242 (goto-char (point-min))
21243 (while (re-search-forward regexp nil t)
21244 (catch :skip
21245 (org-agenda-skip)
21246 (setq beg (match-beginning 0))
21247 (goto-char (1- (match-end 0)))
21248 (setq b (point))
21249 (forward-sexp 1)
21250 (setq sexp (buffer-substring b (point)))
21251 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
21252 (org-trim (match-string 1))
21253 ""))
21254 (setq result (org-diary-sexp-entry sexp sexp-entry date))
21255 (when result
21256 (setq marker (org-agenda-new-marker beg)
21257 category (org-get-category beg))
21259 (if (string-match "\\S-" result)
21260 (setq txt result)
21261 (setq txt "SEXP entry returned empty string"))
21263 (setq txt (org-format-agenda-item
21264 "" txt category tags 'time))
21265 (org-add-props txt props 'org-marker marker)
21266 (org-add-props txt nil
21267 'org-category category 'date date
21268 'type "sexp")
21269 (push txt ee))))
21270 (nreverse ee)))
21272 (defun org-agenda-get-closed ()
21273 "Return the logged TODO entries for agenda display."
21274 (let* ((props (list 'mouse-face 'highlight
21275 'org-not-done-regexp org-not-done-regexp
21276 'org-todo-regexp org-todo-regexp
21277 'keymap org-agenda-keymap
21278 'help-echo
21279 (format "mouse-2 or RET jump to org file %s"
21280 (abbreviate-file-name buffer-file-name))))
21281 (regexp (concat
21282 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
21283 (regexp-quote
21284 (substring
21285 (format-time-string
21286 (car org-time-stamp-formats)
21287 (apply 'encode-time ; DATE bound by calendar
21288 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21289 1 11))))
21290 marker hdmarker priority category tags closedp
21291 ee txt timestr)
21292 (goto-char (point-min))
21293 (while (re-search-forward regexp nil t)
21294 (catch :skip
21295 (org-agenda-skip)
21296 (setq marker (org-agenda-new-marker (match-beginning 0))
21297 closedp (equal (match-string 1) org-closed-string)
21298 category (org-get-category (match-beginning 0))
21299 timestr (buffer-substring (match-beginning 0) (point-at-eol))
21300 ;; donep (org-entry-is-done-p)
21302 (if (string-match "\\]" timestr)
21303 ;; substring should only run to end of time stamp
21304 (setq timestr (substring timestr 0 (match-end 0))))
21305 (save-excursion
21306 (if (re-search-backward "^\\*+ " nil t)
21307 (progn
21308 (goto-char (match-beginning 0))
21309 (setq hdmarker (org-agenda-new-marker)
21310 tags (org-get-tags-at))
21311 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21312 (setq txt (org-format-agenda-item
21313 (if closedp "Closed: " "Clocked: ")
21314 (match-string 1) category tags timestr)))
21315 (setq txt org-agenda-no-heading-message))
21316 (setq priority 100000)
21317 (org-add-props txt props
21318 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
21319 'priority priority 'org-category category
21320 'type "closed" 'date date
21321 'undone-face 'org-warning 'done-face 'org-done)
21322 (push txt ee))
21323 (goto-char (point-at-eol))))
21324 ; (outline-next-heading)))
21325 (nreverse ee)))
21327 (defun org-agenda-get-deadlines ()
21328 "Return the deadline information for agenda display."
21329 (let* ((props (list 'mouse-face 'highlight
21330 'org-not-done-regexp org-not-done-regexp
21331 'org-todo-regexp org-todo-regexp
21332 'keymap org-agenda-keymap
21333 'help-echo
21334 (format "mouse-2 or RET jump to org file %s"
21335 (abbreviate-file-name buffer-file-name))))
21336 (regexp org-deadline-time-regexp)
21337 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21338 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21339 d2 diff dfrac wdays pos pos1 category tags
21340 ee txt head face s upcomingp donep timestr)
21341 (goto-char (point-min))
21342 (while (re-search-forward regexp nil t)
21343 (catch :skip
21344 (org-agenda-skip)
21345 (setq s (match-string 1)
21346 pos (1- (match-beginning 1))
21347 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21348 diff (- d2 d1)
21349 wdays (org-get-wdays s)
21350 dfrac (/ (* 1.0 (- wdays diff)) wdays)
21351 upcomingp (and todayp (> diff 0)))
21352 ;; When to show a deadline in the calendar:
21353 ;; If the expiration is within wdays warning time.
21354 ;; Past-due deadlines are only shown on the current date
21355 (if (or (and (<= diff wdays)
21356 (and todayp (not org-agenda-only-exact-dates)))
21357 (= diff 0))
21358 (save-excursion
21359 (setq category (org-get-category))
21360 (if (re-search-backward "^\\*+[ \t]+" nil t)
21361 (progn
21362 (goto-char (match-end 0))
21363 (setq pos1 (match-beginning 0))
21364 (setq tags (org-get-tags-at pos1))
21365 (setq head (buffer-substring-no-properties
21366 (point)
21367 (progn (skip-chars-forward "^\r\n")
21368 (point))))
21369 (setq donep (string-match org-looking-at-done-regexp head))
21370 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21371 (setq timestr
21372 (concat (substring s (match-beginning 1)) " "))
21373 (setq timestr 'time))
21374 (if (and donep
21375 (or org-agenda-skip-deadline-if-done
21376 (not (= diff 0))))
21377 (setq txt nil)
21378 (setq txt (org-format-agenda-item
21379 (if (= diff 0)
21380 (car org-agenda-deadline-leaders)
21381 (format (nth 1 org-agenda-deadline-leaders)
21382 diff))
21383 head category tags timestr))))
21384 (setq txt org-agenda-no-heading-message))
21385 (when txt
21386 (setq face (org-agenda-deadline-face dfrac))
21387 (org-add-props txt props
21388 'org-marker (org-agenda-new-marker pos)
21389 'org-hd-marker (org-agenda-new-marker pos1)
21390 'priority (+ (if upcomingp (floor (* dfrac 10.)) 100)
21391 (org-get-priority txt))
21392 'org-category category
21393 'type (if upcomingp "upcoming-deadline" "deadline")
21394 'date (if upcomingp date d2)
21395 'face (if donep 'org-done face)
21396 'undone-face face 'done-face 'org-done)
21397 (push txt ee))))))
21398 (nreverse ee)))
21400 (defun org-agenda-deadline-face (fraction)
21401 "Return the face to displaying a deadline item.
21402 FRACTION is what fraction of the head-warning time has passed."
21403 (let ((faces org-agenda-deadline-faces) f)
21404 (catch 'exit
21405 (while (setq f (pop faces))
21406 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
21408 (defun org-agenda-get-scheduled ()
21409 "Return the scheduled information for agenda display."
21410 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
21411 'org-todo-regexp org-todo-regexp
21412 'done-face 'org-done
21413 'mouse-face 'highlight
21414 'keymap org-agenda-keymap
21415 'help-echo
21416 (format "mouse-2 or RET jump to org file %s"
21417 (abbreviate-file-name buffer-file-name))))
21418 (regexp org-scheduled-time-regexp)
21419 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21420 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21421 d2 diff pos pos1 category tags
21422 ee txt head pastschedp donep face timestr s)
21423 (goto-char (point-min))
21424 (while (re-search-forward regexp nil t)
21425 (catch :skip
21426 (org-agenda-skip)
21427 (setq s (match-string 1)
21428 pos (1- (match-beginning 1))
21429 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21430 ;;; is this right?
21431 ;;; do we need to do this for deadleine too????
21432 ;;; d2 (org-time-string-to-absolute (match-string 1) (if todayp nil d1))
21433 diff (- d2 d1))
21434 (setq pastschedp (and todayp (< diff 0)))
21435 ;; When to show a scheduled item in the calendar:
21436 ;; If it is on or past the date.
21437 (if (or (and (< diff 0)
21438 (and todayp (not org-agenda-only-exact-dates)))
21439 (= diff 0))
21440 (save-excursion
21441 (setq category (org-get-category))
21442 (if (re-search-backward "^\\*+[ \t]+" nil t)
21443 (progn
21444 (goto-char (match-end 0))
21445 (setq pos1 (match-beginning 0))
21446 (setq tags (org-get-tags-at))
21447 (setq head (buffer-substring-no-properties
21448 (point)
21449 (progn (skip-chars-forward "^\r\n") (point))))
21450 (setq donep (string-match org-looking-at-done-regexp head))
21451 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21452 (setq timestr
21453 (concat (substring s (match-beginning 1)) " "))
21454 (setq timestr 'time))
21455 (if (and donep
21456 (or org-agenda-skip-scheduled-if-done
21457 (not (= diff 0))))
21458 (setq txt nil)
21459 (setq txt (org-format-agenda-item
21460 (if (= diff 0)
21461 (car org-agenda-scheduled-leaders)
21462 (format (nth 1 org-agenda-scheduled-leaders)
21463 (- 1 diff)))
21464 head category tags timestr))))
21465 (setq txt org-agenda-no-heading-message))
21466 (when txt
21467 (setq face (if pastschedp
21468 'org-scheduled-previously
21469 'org-scheduled-today))
21470 (org-add-props txt props
21471 'undone-face face
21472 'face (if donep 'org-done face)
21473 'org-marker (org-agenda-new-marker pos)
21474 'org-hd-marker (org-agenda-new-marker pos1)
21475 'type (if pastschedp "past-scheduled" "scheduled")
21476 'date (if pastschedp d2 date)
21477 'priority (+ 94 (- 5 diff) (org-get-priority txt))
21478 'org-category category)
21479 (push txt ee))))))
21480 (nreverse ee)))
21482 (defun org-agenda-get-blocks ()
21483 "Return the date-range information for agenda display."
21484 (let* ((props (list 'face nil
21485 'org-not-done-regexp org-not-done-regexp
21486 'org-todo-regexp org-todo-regexp
21487 'mouse-face 'highlight
21488 'keymap org-agenda-keymap
21489 'help-echo
21490 (format "mouse-2 or RET jump to org file %s"
21491 (abbreviate-file-name buffer-file-name))))
21492 (regexp org-tr-regexp)
21493 (d0 (calendar-absolute-from-gregorian date))
21494 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
21495 donep head)
21496 (goto-char (point-min))
21497 (while (re-search-forward regexp nil t)
21498 (catch :skip
21499 (org-agenda-skip)
21500 (setq pos (point))
21501 (setq timestr (match-string 0)
21502 s1 (match-string 1)
21503 s2 (match-string 2)
21504 d1 (time-to-days (org-time-string-to-time s1))
21505 d2 (time-to-days (org-time-string-to-time s2)))
21506 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
21507 ;; Only allow days between the limits, because the normal
21508 ;; date stamps will catch the limits.
21509 (save-excursion
21510 (setq marker (org-agenda-new-marker (point)))
21511 (setq category (org-get-category))
21512 (if (re-search-backward "^\\*+ " nil t)
21513 (progn
21514 (goto-char (match-beginning 0))
21515 (setq hdmarker (org-agenda-new-marker (point)))
21516 (setq tags (org-get-tags-at))
21517 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21518 (setq head (match-string 1))
21519 (and org-agenda-skip-timestamp-if-done
21520 (org-entry-is-done-p)
21521 (throw :skip t))
21522 (setq txt (org-format-agenda-item
21523 (format (if (= d1 d2) "" "(%d/%d): ")
21524 (1+ (- d0 d1)) (1+ (- d2 d1)))
21525 head category tags
21526 (if (= d0 d1) timestr))))
21527 (setq txt org-agenda-no-heading-message))
21528 (org-add-props txt props
21529 'org-marker marker 'org-hd-marker hdmarker
21530 'type "block" 'date date
21531 'priority (org-get-priority txt) 'org-category category)
21532 (push txt ee)))
21533 (goto-char pos)))
21534 ;; Sort the entries by expiration date.
21535 (nreverse ee)))
21537 ;;; Agenda presentation and sorting
21539 (defconst org-plain-time-of-day-regexp
21540 (concat
21541 "\\(\\<[012]?[0-9]"
21542 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21543 "\\(--?"
21544 "\\(\\<[012]?[0-9]"
21545 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21546 "\\)?")
21547 "Regular expression to match a plain time or time range.
21548 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
21549 groups carry important information:
21550 0 the full match
21551 1 the first time, range or not
21552 8 the second time, if it is a range.")
21554 (defconst org-plain-time-extension-regexp
21555 (concat
21556 "\\(\\<[012]?[0-9]"
21557 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21558 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
21559 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
21560 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
21561 groups carry important information:
21562 0 the full match
21563 7 hours of duration
21564 9 minutes of duration")
21566 (defconst org-stamp-time-of-day-regexp
21567 (concat
21568 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
21569 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
21570 "\\(--?"
21571 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
21572 "Regular expression to match a timestamp time or time range.
21573 After a match, the following groups carry important information:
21574 0 the full match
21575 1 date plus weekday, for backreferencing to make sure both times on same day
21576 2 the first time, range or not
21577 4 the second time, if it is a range.")
21579 (defvar org-prefix-has-time nil
21580 "A flag, set by `org-compile-prefix-format'.
21581 The flag is set if the currently compiled format contains a `%t'.")
21582 (defvar org-prefix-has-tag nil
21583 "A flag, set by `org-compile-prefix-format'.
21584 The flag is set if the currently compiled format contains a `%T'.")
21586 (defun org-format-agenda-item (extra txt &optional category tags dotime
21587 noprefix remove-re)
21588 "Format TXT to be inserted into the agenda buffer.
21589 In particular, it adds the prefix and corresponding text properties. EXTRA
21590 must be a string and replaces the `%s' specifier in the prefix format.
21591 CATEGORY (string, symbol or nil) may be used to overrule the default
21592 category taken from local variable or file name. It will replace the `%c'
21593 specifier in the format. DOTIME, when non-nil, indicates that a
21594 time-of-day should be extracted from TXT for sorting of this entry, and for
21595 the `%t' specifier in the format. When DOTIME is a string, this string is
21596 searched for a time before TXT is. NOPREFIX is a flag and indicates that
21597 only the correctly processes TXT should be returned - this is used by
21598 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
21599 Any match of REMOVE-RE will be removed from TXT."
21600 (save-match-data
21601 ;; Diary entries sometimes have extra whitespace at the beginning
21602 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
21603 (let* ((category (or category
21604 org-category
21605 (if buffer-file-name
21606 (file-name-sans-extension
21607 (file-name-nondirectory buffer-file-name))
21608 "")))
21609 (tag (if tags (nth (1- (length tags)) tags) ""))
21610 time ; time and tag are needed for the eval of the prefix format
21611 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
21612 (time-of-day (and dotime (org-get-time-of-day ts)))
21613 stamp plain s0 s1 s2 rtn srp)
21614 (when (and dotime time-of-day org-prefix-has-time)
21615 ;; Extract starting and ending time and move them to prefix
21616 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
21617 (setq plain (string-match org-plain-time-of-day-regexp ts)))
21618 (setq s0 (match-string 0 ts)
21619 srp (and stamp (match-end 3))
21620 s1 (match-string (if plain 1 2) ts)
21621 s2 (match-string (if plain 8 (if srp 4 6)) ts))
21623 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
21624 ;; them, we might want to remove them there to avoid duplication.
21625 ;; The user can turn this off with a variable.
21626 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
21627 (string-match (concat (regexp-quote s0) " *") txt)
21628 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
21629 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
21630 (= (match-beginning 0) 0)
21632 (setq txt (replace-match "" nil nil txt))))
21633 ;; Normalize the time(s) to 24 hour
21634 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
21635 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
21637 (when (and s1 (not s2) org-agenda-default-appointment-duration
21638 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
21639 (let ((m (+ (string-to-number (match-string 2 s1))
21640 (* 60 (string-to-number (match-string 1 s1)))
21641 org-agenda-default-appointment-duration))
21643 (setq h (/ m 60) m (- m (* h 60)))
21644 (setq s2 (format "%02d:%02d" h m))))
21646 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
21647 txt)
21648 ;; Tags are in the string
21649 (if (or (eq org-agenda-remove-tags t)
21650 (and org-agenda-remove-tags
21651 org-prefix-has-tag))
21652 (setq txt (replace-match "" t t txt))
21653 (setq txt (replace-match
21654 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
21655 (match-string 2 txt))
21656 t t txt))))
21658 (when remove-re
21659 (while (string-match remove-re txt)
21660 (setq txt (replace-match "" t t txt))))
21662 ;; Create the final string
21663 (if noprefix
21664 (setq rtn txt)
21665 ;; Prepare the variables needed in the eval of the compiled format
21666 (setq time (cond (s2 (concat s1 "-" s2))
21667 (s1 (concat s1 "......"))
21668 (t ""))
21669 extra (or extra "")
21670 category (if (symbolp category) (symbol-name category) category))
21671 ;; Evaluate the compiled format
21672 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
21674 ;; And finally add the text properties
21675 (org-add-props rtn nil
21676 'org-category (downcase category) 'tags tags
21677 'org-highest-priority org-highest-priority
21678 'org-lowest-priority org-lowest-priority
21679 'prefix-length (- (length rtn) (length txt))
21680 'time-of-day time-of-day
21681 'txt txt
21682 'time time
21683 'extra extra
21684 'dotime dotime))))
21686 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
21687 (defvar org-agenda-sorting-strategy-selected nil)
21689 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
21690 (catch 'exit
21691 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
21692 ((and todayp (member 'today (car org-agenda-time-grid))))
21693 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
21694 ((member 'weekly (car org-agenda-time-grid)))
21695 (t (throw 'exit list)))
21696 (let* ((have (delq nil (mapcar
21697 (lambda (x) (get-text-property 1 'time-of-day x))
21698 list)))
21699 (string (nth 1 org-agenda-time-grid))
21700 (gridtimes (nth 2 org-agenda-time-grid))
21701 (req (car org-agenda-time-grid))
21702 (remove (member 'remove-match req))
21703 new time)
21704 (if (and (member 'require-timed req) (not have))
21705 ;; don't show empty grid
21706 (throw 'exit list))
21707 (while (setq time (pop gridtimes))
21708 (unless (and remove (member time have))
21709 (setq time (int-to-string time))
21710 (push (org-format-agenda-item
21711 nil string "" nil
21712 (concat (substring time 0 -2) ":" (substring time -2)))
21713 new)
21714 (put-text-property
21715 1 (length (car new)) 'face 'org-time-grid (car new))))
21716 (if (member 'time-up org-agenda-sorting-strategy-selected)
21717 (append new list)
21718 (append list new)))))
21720 (defun org-compile-prefix-format (key)
21721 "Compile the prefix format into a Lisp form that can be evaluated.
21722 The resulting form is returned and stored in the variable
21723 `org-prefix-format-compiled'."
21724 (setq org-prefix-has-time nil org-prefix-has-tag nil)
21725 (let ((s (cond
21726 ((stringp org-agenda-prefix-format)
21727 org-agenda-prefix-format)
21728 ((assq key org-agenda-prefix-format)
21729 (cdr (assq key org-agenda-prefix-format)))
21730 (t " %-12:c%?-12t% s")))
21731 (start 0)
21732 varform vars var e c f opt)
21733 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
21734 s start)
21735 (setq var (cdr (assoc (match-string 4 s)
21736 '(("c" . category) ("t" . time) ("s" . extra)
21737 ("T" . tag))))
21738 c (or (match-string 3 s) "")
21739 opt (match-beginning 1)
21740 start (1+ (match-beginning 0)))
21741 (if (equal var 'time) (setq org-prefix-has-time t))
21742 (if (equal var 'tag) (setq org-prefix-has-tag t))
21743 (setq f (concat "%" (match-string 2 s) "s"))
21744 (if opt
21745 (setq varform
21746 `(if (equal "" ,var)
21748 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
21749 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
21750 (setq s (replace-match "%s" t nil s))
21751 (push varform vars))
21752 (setq vars (nreverse vars))
21753 (setq org-prefix-format-compiled `(format ,s ,@vars))))
21755 (defun org-set-sorting-strategy (key)
21756 (if (symbolp (car org-agenda-sorting-strategy))
21757 ;; the old format
21758 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
21759 (setq org-agenda-sorting-strategy-selected
21760 (or (cdr (assq key org-agenda-sorting-strategy))
21761 (cdr (assq 'agenda org-agenda-sorting-strategy))
21762 '(time-up category-keep priority-down)))))
21764 (defun org-get-time-of-day (s &optional string mod24)
21765 "Check string S for a time of day.
21766 If found, return it as a military time number between 0 and 2400.
21767 If not found, return nil.
21768 The optional STRING argument forces conversion into a 5 character wide string
21769 HH:MM."
21770 (save-match-data
21771 (when
21772 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
21773 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
21774 (let* ((h (string-to-number (match-string 1 s)))
21775 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
21776 (ampm (if (match-end 4) (downcase (match-string 4 s))))
21777 (am-p (equal ampm "am"))
21778 (h1 (cond ((not ampm) h)
21779 ((= h 12) (if am-p 0 12))
21780 (t (+ h (if am-p 0 12)))))
21781 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
21782 (mod h1 24) h1))
21783 (t0 (+ (* 100 h2) m))
21784 (t1 (concat (if (>= h1 24) "+" " ")
21785 (if (< t0 100) "0" "")
21786 (if (< t0 10) "0" "")
21787 (int-to-string t0))))
21788 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
21790 (defun org-finalize-agenda-entries (list &optional nosort)
21791 "Sort and concatenate the agenda items."
21792 (setq list (mapcar 'org-agenda-highlight-todo list))
21793 (if nosort
21794 list
21795 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
21797 (defun org-agenda-highlight-todo (x)
21798 (let (re pl)
21799 (if (eq x 'line)
21800 (save-excursion
21801 (beginning-of-line 1)
21802 (setq re (get-text-property (point) 'org-todo-regexp))
21803 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
21804 (when (looking-at (concat "[ \t]*\\.*" re " +"))
21805 (add-text-properties (match-beginning 0) (match-end 0)
21806 (list 'face (org-get-todo-face 0)))
21807 (let ((s (buffer-substring (match-beginning 1) (match-end 1))))
21808 (delete-region (match-beginning 1) (1- (match-end 0)))
21809 (goto-char (match-beginning 1))
21810 (insert (format org-agenda-todo-keyword-format s)))))
21811 (setq re (concat (get-text-property 0 'org-todo-regexp x))
21812 pl (get-text-property 0 'prefix-length x))
21813 ; (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
21814 ; (add-text-properties
21815 ; (or (match-end 1) (match-end 0)) (match-end 0)
21816 ; (list 'face (org-get-todo-face (match-string 2 x)))
21817 ; x))
21818 (when (and re
21819 (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)")
21820 x (or pl 0)) pl))
21821 (add-text-properties
21822 (or (match-end 1) (match-end 0)) (match-end 0)
21823 (list 'face (org-get-todo-face (match-string 2 x)))
21825 (setq x (concat (substring x 0 (match-end 1))
21826 (format org-agenda-todo-keyword-format
21827 (match-string 2 x))
21829 (substring x (match-end 3)))))
21830 x)))
21832 (defsubst org-cmp-priority (a b)
21833 "Compare the priorities of string A and B."
21834 (let ((pa (or (get-text-property 1 'priority a) 0))
21835 (pb (or (get-text-property 1 'priority b) 0)))
21836 (cond ((> pa pb) +1)
21837 ((< pa pb) -1)
21838 (t nil))))
21840 (defsubst org-cmp-category (a b)
21841 "Compare the string values of categories of strings A and B."
21842 (let ((ca (or (get-text-property 1 'org-category a) ""))
21843 (cb (or (get-text-property 1 'org-category b) "")))
21844 (cond ((string-lessp ca cb) -1)
21845 ((string-lessp cb ca) +1)
21846 (t nil))))
21848 (defsubst org-cmp-tag (a b)
21849 "Compare the string values of categories of strings A and B."
21850 (let ((ta (car (last (get-text-property 1 'tags a))))
21851 (tb (car (last (get-text-property 1 'tags b)))))
21852 (cond ((not ta) +1)
21853 ((not tb) -1)
21854 ((string-lessp ta tb) -1)
21855 ((string-lessp tb ta) +1)
21856 (t nil))))
21858 (defsubst org-cmp-time (a b)
21859 "Compare the time-of-day values of strings A and B."
21860 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
21861 (ta (or (get-text-property 1 'time-of-day a) def))
21862 (tb (or (get-text-property 1 'time-of-day b) def)))
21863 (cond ((< ta tb) -1)
21864 ((< tb ta) +1)
21865 (t nil))))
21867 (defun org-entries-lessp (a b)
21868 "Predicate for sorting agenda entries."
21869 ;; The following variables will be used when the form is evaluated.
21870 ;; So even though the compiler complains, keep them.
21871 (let* ((time-up (org-cmp-time a b))
21872 (time-down (if time-up (- time-up) nil))
21873 (priority-up (org-cmp-priority a b))
21874 (priority-down (if priority-up (- priority-up) nil))
21875 (category-up (org-cmp-category a b))
21876 (category-down (if category-up (- category-up) nil))
21877 (category-keep (if category-up +1 nil))
21878 (tag-up (org-cmp-tag a b))
21879 (tag-down (if tag-up (- tag-up) nil)))
21880 (cdr (assoc
21881 (eval (cons 'or org-agenda-sorting-strategy-selected))
21882 '((-1 . t) (1 . nil) (nil . nil))))))
21884 ;;; Agenda restriction lock
21886 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
21887 "Overlay to mark the headline to which arenda commands are restricted.")
21888 (org-overlay-put org-agenda-restriction-lock-overlay
21889 'face 'org-agenda-restriction-lock)
21890 (org-overlay-put org-agenda-restriction-lock-overlay
21891 'help-echo "Agendas are currently limited to this subtree.")
21892 (org-detach-overlay org-agenda-restriction-lock-overlay)
21893 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
21894 "Overlay marking the agenda restriction line in speedbar.")
21895 (org-overlay-put org-speedbar-restriction-lock-overlay
21896 'face 'org-agenda-restriction-lock)
21897 (org-overlay-put org-speedbar-restriction-lock-overlay
21898 'help-echo "Agendas are currently limited to this item.")
21899 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21901 (defun org-agenda-set-restriction-lock (&optional type)
21902 "Set restriction lock for agenda, to current subtree or file.
21903 Restriction will be the file if TYPE is `file', or if type is the
21904 universal prefix '(4), or if the cursor is before the first headline
21905 in the file. Otherwise, restriction will be to the current subtree."
21906 (interactive "P")
21907 (and (equal type '(4)) (setq type 'file))
21908 (setq type (cond
21909 (type type)
21910 ((org-at-heading-p) 'subtree)
21911 ((condition-case nil (org-back-to-heading t) (error nil))
21912 'subtree)
21913 (t 'file)))
21914 (if (eq type 'subtree)
21915 (progn
21916 (setq org-agenda-restrict t)
21917 (setq org-agenda-overriding-restriction 'subtree)
21918 (put 'org-agenda-files 'org-restrict
21919 (list (buffer-file-name (buffer-base-buffer))))
21920 (org-back-to-heading t)
21921 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
21922 (move-marker org-agenda-restrict-begin (point))
21923 (move-marker org-agenda-restrict-end
21924 (save-excursion (org-end-of-subtree t)))
21925 (message "Locking agenda restriction to subtree"))
21926 (put 'org-agenda-files 'org-restrict
21927 (list (buffer-file-name (buffer-base-buffer))))
21928 (setq org-agenda-restrict nil)
21929 (setq org-agenda-overriding-restriction 'file)
21930 (move-marker org-agenda-restrict-begin nil)
21931 (move-marker org-agenda-restrict-end nil)
21932 (message "Locking agenda restriction to file"))
21933 (setq current-prefix-arg nil)
21934 (org-agenda-maybe-redo))
21936 (defun org-agenda-remove-restriction-lock (&optional noupdate)
21937 "Remove the agenda restriction lock."
21938 (interactive "P")
21939 (org-detach-overlay org-agenda-restriction-lock-overlay)
21940 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21941 (setq org-agenda-overriding-restriction nil)
21942 (setq org-agenda-restrict nil)
21943 (put 'org-agenda-files 'org-restrict nil)
21944 (move-marker org-agenda-restrict-begin nil)
21945 (move-marker org-agenda-restrict-end nil)
21946 (setq current-prefix-arg nil)
21947 (message "Agenda restriction lock removed")
21948 (or noupdate (org-agenda-maybe-redo)))
21950 (defun org-agenda-maybe-redo ()
21951 "If there is any window showing the agenda view, update it."
21952 (let ((w (get-buffer-window org-agenda-buffer-name t))
21953 (w0 (selected-window)))
21954 (when w
21955 (select-window w)
21956 (org-agenda-redo)
21957 (select-window w0)
21958 (if org-agenda-overriding-restriction
21959 (message "Agenda view shifted to new %s restriction"
21960 org-agenda-overriding-restriction)
21961 (message "Agenda restriction lock removed")))))
21963 ;;; Agenda commands
21965 (defun org-agenda-check-type (error &rest types)
21966 "Check if agenda buffer is of allowed type.
21967 If ERROR is non-nil, throw an error, otherwise just return nil."
21968 (if (memq org-agenda-type types)
21970 (if error
21971 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
21972 nil)))
21974 (defun org-agenda-quit ()
21975 "Exit agenda by removing the window or the buffer."
21976 (interactive)
21977 (let ((buf (current-buffer)))
21978 (if (not (one-window-p)) (delete-window))
21979 (kill-buffer buf)
21980 (org-agenda-maybe-reset-markers 'force)
21981 (org-columns-remove-overlays))
21982 ;; Maybe restore the pre-agenda window configuration.
21983 (and org-agenda-restore-windows-after-quit
21984 (not (eq org-agenda-window-setup 'other-frame))
21985 org-pre-agenda-window-conf
21986 (set-window-configuration org-pre-agenda-window-conf)))
21988 (defun org-agenda-exit ()
21989 "Exit agenda by removing the window or the buffer.
21990 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
21991 Org-mode buffers visited directly by the user will not be touched."
21992 (interactive)
21993 (org-release-buffers org-agenda-new-buffers)
21994 (setq org-agenda-new-buffers nil)
21995 (org-agenda-quit))
21997 (defun org-agenda-execute (arg)
21998 "Execute another agenda command, keeping same window.\\<global-map>
21999 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
22000 (interactive "P")
22001 (let ((org-agenda-window-setup 'current-window))
22002 (org-agenda arg)))
22004 (defun org-save-all-org-buffers ()
22005 "Save all Org-mode buffers without user confirmation."
22006 (interactive)
22007 (message "Saving all Org-mode buffers...")
22008 (save-some-buffers t 'org-mode-p)
22009 (message "Saving all Org-mode buffers... done"))
22011 (defun org-agenda-redo ()
22012 "Rebuild Agenda.
22013 When this is the global TODO list, a prefix argument will be interpreted."
22014 (interactive)
22015 (let* ((org-agenda-keep-modes t)
22016 (line (org-current-line))
22017 (window-line (- line (org-current-line (window-start))))
22018 (lprops (get 'org-agenda-redo-command 'org-lprops)))
22019 (message "Rebuilding agenda buffer...")
22020 (org-let lprops '(eval org-agenda-redo-command))
22021 (setq org-agenda-undo-list nil
22022 org-agenda-pending-undo-list nil)
22023 (message "Rebuilding agenda buffer...done")
22024 (goto-line line)
22025 (recenter window-line)))
22027 (defun org-agenda-goto-date (date)
22028 "Jump to DATE in agenda."
22029 (interactive (list (org-read-date)))
22030 (org-agenda-list nil date))
22032 (defun org-agenda-goto-today ()
22033 "Go to today."
22034 (interactive)
22035 (org-agenda-check-type t 'timeline 'agenda)
22036 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
22037 (cond
22038 (tdpos (goto-char tdpos))
22039 ((eq org-agenda-type 'agenda)
22040 (let* ((sd (time-to-days
22041 (time-subtract (current-time)
22042 (list 0 (* 3600 org-extend-today-until) 0))))
22043 (comp (org-agenda-compute-time-span sd org-agenda-span))
22044 (org-agenda-overriding-arguments org-agenda-last-arguments))
22045 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
22046 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
22047 (org-agenda-redo)
22048 (org-agenda-find-same-or-today-or-agenda)))
22049 (t (error "Cannot find today")))))
22051 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
22052 (goto-char
22053 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
22054 (text-property-any (point-min) (point-max) 'org-today t)
22055 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
22056 (point-min))))
22058 (defun org-agenda-later (arg)
22059 "Go forward in time by thee current span.
22060 With prefix ARG, go forward that many times the current span."
22061 (interactive "p")
22062 (org-agenda-check-type t 'agenda)
22063 (let* ((span org-agenda-span)
22064 (sd org-starting-day)
22065 (greg (calendar-gregorian-from-absolute sd))
22066 (cnt (get-text-property (point) 'org-day-cnt))
22067 greg2 nd)
22068 (cond
22069 ((eq span 'day)
22070 (setq sd (+ arg sd) nd 1))
22071 ((eq span 'week)
22072 (setq sd (+ (* 7 arg) sd) nd 7))
22073 ((eq span 'month)
22074 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
22075 sd (calendar-absolute-from-gregorian greg2))
22076 (setcar greg2 (1+ (car greg2)))
22077 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
22078 ((eq span 'year)
22079 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
22080 sd (calendar-absolute-from-gregorian greg2))
22081 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
22082 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
22083 (let ((org-agenda-overriding-arguments
22084 (list (car org-agenda-last-arguments) sd nd t)))
22085 (org-agenda-redo)
22086 (org-agenda-find-same-or-today-or-agenda cnt))))
22088 (defun org-agenda-earlier (arg)
22089 "Go backward in time by the current span.
22090 With prefix ARG, go backward that many times the current span."
22091 (interactive "p")
22092 (org-agenda-later (- arg)))
22094 (defun org-agenda-day-view ()
22095 "Switch to daily view for agenda."
22096 (interactive)
22097 (setq org-agenda-ndays 1)
22098 (org-agenda-change-time-span 'day))
22099 (defun org-agenda-week-view ()
22100 "Switch to daily view for agenda."
22101 (interactive)
22102 (setq org-agenda-ndays 7)
22103 (org-agenda-change-time-span 'week))
22104 (defun org-agenda-month-view ()
22105 "Switch to daily view for agenda."
22106 (interactive)
22107 (org-agenda-change-time-span 'month))
22108 (defun org-agenda-year-view ()
22109 "Switch to daily view for agenda."
22110 (interactive)
22111 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
22112 (org-agenda-change-time-span 'year)
22113 (error "Abort")))
22115 (defun org-agenda-change-time-span (span)
22116 "Change the agenda view to SPAN.
22117 SPAN may be `day', `week', `month', `year'."
22118 (org-agenda-check-type t 'agenda)
22119 (if (equal org-agenda-span span)
22120 (error "Viewing span is already \"%s\"" span))
22121 (let* ((sd (or (get-text-property (point) 'day)
22122 org-starting-day))
22123 (computed (org-agenda-compute-time-span sd span))
22124 (org-agenda-overriding-arguments
22125 (list (car org-agenda-last-arguments)
22126 (car computed) (cdr computed) t)))
22127 (org-agenda-redo)
22128 (org-agenda-find-same-or-today-or-agenda))
22129 (org-agenda-set-mode-name)
22130 (message "Switched to %s view" span))
22132 (defun org-agenda-compute-time-span (sd span)
22133 "Compute starting date and number of days for agenda.
22134 SPAN may be `day', `week', `month', `year'. The return value
22135 is a cons cell with the starting date and the number of days,
22136 so that the date SD will be in that range."
22137 (let* ((greg (calendar-gregorian-from-absolute sd))
22139 (cond
22140 ((eq span 'day)
22141 (setq nd 1))
22142 ((eq span 'week)
22143 (let* ((nt (calendar-day-of-week
22144 (calendar-gregorian-from-absolute sd)))
22145 (d (if org-agenda-start-on-weekday
22146 (- nt org-agenda-start-on-weekday)
22147 0)))
22148 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
22149 (setq nd 7)))
22150 ((eq span 'month)
22151 (setq sd (calendar-absolute-from-gregorian
22152 (list (car greg) 1 (nth 2 greg)))
22153 nd (- (calendar-absolute-from-gregorian
22154 (list (1+ (car greg)) 1 (nth 2 greg)))
22155 sd)))
22156 ((eq span 'year)
22157 (setq sd (calendar-absolute-from-gregorian
22158 (list 1 1 (nth 2 greg)))
22159 nd (- (calendar-absolute-from-gregorian
22160 (list 1 1 (1+ (nth 2 greg))))
22161 sd))))
22162 (cons sd nd)))
22164 ;; FIXME: does not work if user makes date format that starts with a blank
22165 (defun org-agenda-next-date-line (&optional arg)
22166 "Jump to the next line indicating a date in agenda buffer."
22167 (interactive "p")
22168 (org-agenda-check-type t 'agenda 'timeline)
22169 (beginning-of-line 1)
22170 (if (looking-at "^\\S-") (forward-char 1))
22171 (if (not (re-search-forward "^\\S-" nil t arg))
22172 (progn
22173 (backward-char 1)
22174 (error "No next date after this line in this buffer")))
22175 (goto-char (match-beginning 0)))
22177 (defun org-agenda-previous-date-line (&optional arg)
22178 "Jump to the previous line indicating a date in agenda buffer."
22179 (interactive "p")
22180 (org-agenda-check-type t 'agenda 'timeline)
22181 (beginning-of-line 1)
22182 (if (not (re-search-backward "^\\S-" nil t arg))
22183 (error "No previous date before this line in this buffer")))
22185 ;; Initialize the highlight
22186 (defvar org-hl (org-make-overlay 1 1))
22187 (org-overlay-put org-hl 'face 'highlight)
22189 (defun org-highlight (begin end &optional buffer)
22190 "Highlight a region with overlay."
22191 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
22192 org-hl begin end (or buffer (current-buffer))))
22194 (defun org-unhighlight ()
22195 "Detach overlay INDEX."
22196 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
22198 ;; FIXME this is currently not used.
22199 (defun org-highlight-until-next-command (beg end &optional buffer)
22200 (org-highlight beg end buffer)
22201 (add-hook 'pre-command-hook 'org-unhighlight-once))
22202 (defun org-unhighlight-once ()
22203 (remove-hook 'pre-command-hook 'org-unhighlight-once)
22204 (org-unhighlight))
22206 (defun org-agenda-follow-mode ()
22207 "Toggle follow mode in an agenda buffer."
22208 (interactive)
22209 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
22210 (org-agenda-set-mode-name)
22211 (message "Follow mode is %s"
22212 (if org-agenda-follow-mode "on" "off")))
22214 (defun org-agenda-log-mode ()
22215 "Toggle log mode in an agenda buffer."
22216 (interactive)
22217 (org-agenda-check-type t 'agenda 'timeline)
22218 (setq org-agenda-show-log (not org-agenda-show-log))
22219 (org-agenda-set-mode-name)
22220 (org-agenda-redo)
22221 (message "Log mode is %s"
22222 (if org-agenda-show-log "on" "off")))
22224 (defun org-agenda-toggle-diary ()
22225 "Toggle diary inclusion in an agenda buffer."
22226 (interactive)
22227 (org-agenda-check-type t 'agenda)
22228 (setq org-agenda-include-diary (not org-agenda-include-diary))
22229 (org-agenda-redo)
22230 (org-agenda-set-mode-name)
22231 (message "Diary inclusion turned %s"
22232 (if org-agenda-include-diary "on" "off")))
22234 (defun org-agenda-toggle-time-grid ()
22235 "Toggle time grid in an agenda buffer."
22236 (interactive)
22237 (org-agenda-check-type t 'agenda)
22238 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
22239 (org-agenda-redo)
22240 (org-agenda-set-mode-name)
22241 (message "Time-grid turned %s"
22242 (if org-agenda-use-time-grid "on" "off")))
22244 (defun org-agenda-set-mode-name ()
22245 "Set the mode name to indicate all the small mode settings."
22246 (setq mode-name
22247 (concat "Org-Agenda"
22248 (if (equal org-agenda-ndays 1) " Day" "")
22249 (if (equal org-agenda-ndays 7) " Week" "")
22250 (if org-agenda-follow-mode " Follow" "")
22251 (if org-agenda-include-diary " Diary" "")
22252 (if org-agenda-use-time-grid " Grid" "")
22253 (if org-agenda-show-log " Log" "")))
22254 (force-mode-line-update))
22256 (defun org-agenda-post-command-hook ()
22257 (and (eolp) (not (bolp)) (backward-char 1))
22258 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
22259 (if (and org-agenda-follow-mode
22260 (get-text-property (point) 'org-marker))
22261 (org-agenda-show)))
22263 (defun org-agenda-show-priority ()
22264 "Show the priority of the current item.
22265 This priority is composed of the main priority given with the [#A] cookies,
22266 and by additional input from the age of a schedules or deadline entry."
22267 (interactive)
22268 (let* ((pri (get-text-property (point-at-bol) 'priority)))
22269 (message "Priority is %d" (if pri pri -1000))))
22271 (defun org-agenda-show-tags ()
22272 "Show the tags applicable to the current item."
22273 (interactive)
22274 (let* ((tags (get-text-property (point-at-bol) 'tags)))
22275 (if tags
22276 (message "Tags are :%s:"
22277 (org-no-properties (mapconcat 'identity tags ":")))
22278 (message "No tags associated with this line"))))
22280 (defun org-agenda-goto (&optional highlight)
22281 "Go to the Org-mode file which contains the item at point."
22282 (interactive)
22283 (let* ((marker (or (get-text-property (point) 'org-marker)
22284 (org-agenda-error)))
22285 (buffer (marker-buffer marker))
22286 (pos (marker-position marker)))
22287 (switch-to-buffer-other-window buffer)
22288 (widen)
22289 (goto-char pos)
22290 (when (org-mode-p)
22291 (org-show-context 'agenda)
22292 (save-excursion
22293 (and (outline-next-heading)
22294 (org-flag-heading nil)))) ; show the next heading
22295 (run-hooks 'org-agenda-after-show-hook)
22296 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
22298 (defvar org-agenda-after-show-hook nil
22299 "Normal hook run after an item has been shown from the agenda.
22300 Point is in the buffer where the item originated.")
22302 (defun org-agenda-kill ()
22303 "Kill the entry or subtree belonging to the current agenda entry."
22304 (interactive)
22305 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22306 (let* ((marker (or (get-text-property (point) 'org-marker)
22307 (org-agenda-error)))
22308 (buffer (marker-buffer marker))
22309 (pos (marker-position marker))
22310 (type (get-text-property (point) 'type))
22311 dbeg dend (n 0) conf)
22312 (org-with-remote-undo buffer
22313 (with-current-buffer buffer
22314 (save-excursion
22315 (goto-char pos)
22316 (if (and (org-mode-p) (not (member type '("sexp"))))
22317 (setq dbeg (progn (org-back-to-heading t) (point))
22318 dend (org-end-of-subtree t t))
22319 (setq dbeg (point-at-bol)
22320 dend (min (point-max) (1+ (point-at-eol)))))
22321 (goto-char dbeg)
22322 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
22323 (setq conf (or (eq t org-agenda-confirm-kill)
22324 (and (numberp org-agenda-confirm-kill)
22325 (> n org-agenda-confirm-kill))))
22326 (and conf
22327 (not (y-or-n-p
22328 (format "Delete entry with %d lines in buffer \"%s\"? "
22329 n (buffer-name buffer))))
22330 (error "Abort"))
22331 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
22332 (with-current-buffer buffer (delete-region dbeg dend))
22333 (message "Agenda item and source killed"))))
22335 (defun org-agenda-archive ()
22336 "Kill the entry or subtree belonging to the current agenda entry."
22337 (interactive)
22338 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22339 (let* ((marker (or (get-text-property (point) 'org-marker)
22340 (org-agenda-error)))
22341 (buffer (marker-buffer marker))
22342 (pos (marker-position marker)))
22343 (org-with-remote-undo buffer
22344 (with-current-buffer buffer
22345 (if (org-mode-p)
22346 (save-excursion
22347 (goto-char pos)
22348 (org-remove-subtree-entries-from-agenda)
22349 (org-back-to-heading t)
22350 (org-archive-subtree))
22351 (error "Archiving works only in Org-mode files"))))))
22353 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
22354 "Remove all lines in the agenda that correspond to a given subtree.
22355 The subtree is the one in buffer BUF, starting at BEG and ending at END.
22356 If this information is not given, the function uses the tree at point."
22357 (let ((buf (or buf (current-buffer))) m p)
22358 (save-excursion
22359 (unless (and beg end)
22360 (org-back-to-heading t)
22361 (setq beg (point))
22362 (org-end-of-subtree t)
22363 (setq end (point)))
22364 (set-buffer (get-buffer org-agenda-buffer-name))
22365 (save-excursion
22366 (goto-char (point-max))
22367 (beginning-of-line 1)
22368 (while (not (bobp))
22369 (when (and (setq m (get-text-property (point) 'org-marker))
22370 (equal buf (marker-buffer m))
22371 (setq p (marker-position m))
22372 (>= p beg)
22373 (<= p end))
22374 (let ((inhibit-read-only t))
22375 (delete-region (point-at-bol) (1+ (point-at-eol)))))
22376 (beginning-of-line 0))))))
22378 (defun org-agenda-open-link ()
22379 "Follow the link in the current line, if any."
22380 (interactive)
22381 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
22382 (save-excursion
22383 (save-restriction
22384 (narrow-to-region (point-at-bol) (point-at-eol))
22385 (org-open-at-point))))
22387 (defun org-agenda-copy-local-variable (var)
22388 "Get a variable from a referenced buffer and install it here."
22389 (let ((m (get-text-property (point) 'org-marker)))
22390 (when (and m (buffer-live-p (marker-buffer m)))
22391 (org-set-local var (with-current-buffer (marker-buffer m)
22392 (symbol-value var))))))
22394 (defun org-agenda-switch-to (&optional delete-other-windows)
22395 "Go to the Org-mode file which contains the item at point."
22396 (interactive)
22397 (let* ((marker (or (get-text-property (point) 'org-marker)
22398 (org-agenda-error)))
22399 (buffer (marker-buffer marker))
22400 (pos (marker-position marker)))
22401 (switch-to-buffer buffer)
22402 (and delete-other-windows (delete-other-windows))
22403 (widen)
22404 (goto-char pos)
22405 (when (org-mode-p)
22406 (org-show-context 'agenda)
22407 (save-excursion
22408 (and (outline-next-heading)
22409 (org-flag-heading nil)))))) ; show the next heading
22411 (defun org-agenda-goto-mouse (ev)
22412 "Go to the Org-mode file which contains the item at the mouse click."
22413 (interactive "e")
22414 (mouse-set-point ev)
22415 (org-agenda-goto))
22417 (defun org-agenda-show ()
22418 "Display the Org-mode file which contains the item at point."
22419 (interactive)
22420 (let ((win (selected-window)))
22421 (org-agenda-goto t)
22422 (select-window win)))
22424 (defun org-agenda-recenter (arg)
22425 "Display the Org-mode file which contains the item at point and recenter."
22426 (interactive "P")
22427 (let ((win (selected-window)))
22428 (org-agenda-goto t)
22429 (recenter arg)
22430 (select-window win)))
22432 (defun org-agenda-show-mouse (ev)
22433 "Display the Org-mode file which contains the item at the mouse click."
22434 (interactive "e")
22435 (mouse-set-point ev)
22436 (org-agenda-show))
22438 (defun org-agenda-check-no-diary ()
22439 "Check if the entry is a diary link and abort if yes."
22440 (if (get-text-property (point) 'org-agenda-diary-link)
22441 (org-agenda-error)))
22443 (defun org-agenda-error ()
22444 (error "Command not allowed in this line"))
22446 (defun org-agenda-tree-to-indirect-buffer ()
22447 "Show the subtree corresponding to the current entry in an indirect buffer.
22448 This calls the command `org-tree-to-indirect-buffer' from the original
22449 Org-mode buffer.
22450 With numerical prefix arg ARG, go up to this level and then take that tree.
22451 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
22452 dedicated frame)."
22453 (interactive)
22454 (org-agenda-check-no-diary)
22455 (let* ((marker (or (get-text-property (point) 'org-marker)
22456 (org-agenda-error)))
22457 (buffer (marker-buffer marker))
22458 (pos (marker-position marker)))
22459 (with-current-buffer buffer
22460 (save-excursion
22461 (goto-char pos)
22462 (call-interactively 'org-tree-to-indirect-buffer)))))
22464 (defvar org-last-heading-marker (make-marker)
22465 "Marker pointing to the headline that last changed its TODO state
22466 by a remote command from the agenda.")
22468 (defun org-agenda-todo-nextset ()
22469 "Switch TODO entry to next sequence."
22470 (interactive)
22471 (org-agenda-todo 'nextset))
22473 (defun org-agenda-todo-previousset ()
22474 "Switch TODO entry to previous sequence."
22475 (interactive)
22476 (org-agenda-todo 'previousset))
22478 (defun org-agenda-todo (&optional arg)
22479 "Cycle TODO state of line at point, also in Org-mode file.
22480 This changes the line at point, all other lines in the agenda referring to
22481 the same tree node, and the headline of the tree node in the Org-mode file."
22482 (interactive "P")
22483 (org-agenda-check-no-diary)
22484 (let* ((col (current-column))
22485 (marker (or (get-text-property (point) 'org-marker)
22486 (org-agenda-error)))
22487 (buffer (marker-buffer marker))
22488 (pos (marker-position marker))
22489 (hdmarker (get-text-property (point) 'org-hd-marker))
22490 (inhibit-read-only t)
22491 newhead)
22492 (org-with-remote-undo buffer
22493 (with-current-buffer buffer
22494 (widen)
22495 (goto-char pos)
22496 (org-show-context 'agenda)
22497 (save-excursion
22498 (and (outline-next-heading)
22499 (org-flag-heading nil))) ; show the next heading
22500 (org-todo arg)
22501 (and (bolp) (forward-char 1))
22502 (setq newhead (org-get-heading))
22503 (save-excursion
22504 (org-back-to-heading)
22505 (move-marker org-last-heading-marker (point))))
22506 (beginning-of-line 1)
22507 (save-excursion
22508 (org-agenda-change-all-lines newhead hdmarker 'fixface))
22509 (move-to-column col))))
22511 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
22512 "Change all lines in the agenda buffer which match HDMARKER.
22513 The new content of the line will be NEWHEAD (as modified by
22514 `org-format-agenda-item'). HDMARKER is checked with
22515 `equal' against all `org-hd-marker' text properties in the file.
22516 If FIXFACE is non-nil, the face of each item is modified acording to
22517 the new TODO state."
22518 (let* ((inhibit-read-only t)
22519 props m pl undone-face done-face finish new dotime cat tags)
22520 (save-excursion
22521 (goto-char (point-max))
22522 (beginning-of-line 1)
22523 (while (not finish)
22524 (setq finish (bobp))
22525 (when (and (setq m (get-text-property (point) 'org-hd-marker))
22526 (equal m hdmarker))
22527 (setq props (text-properties-at (point))
22528 dotime (get-text-property (point) 'dotime)
22529 cat (get-text-property (point) 'org-category)
22530 tags (get-text-property (point) 'tags)
22531 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
22532 pl (get-text-property (point) 'prefix-length)
22533 undone-face (get-text-property (point) 'undone-face)
22534 done-face (get-text-property (point) 'done-face))
22535 (move-to-column pl)
22536 (cond
22537 ((equal new "")
22538 (beginning-of-line 1)
22539 (and (looking-at ".*\n?") (replace-match "")))
22540 ((looking-at ".*")
22541 (replace-match new t t)
22542 (beginning-of-line 1)
22543 (add-text-properties (point-at-bol) (point-at-eol) props)
22544 (when fixface
22545 (add-text-properties
22546 (point-at-bol) (point-at-eol)
22547 (list 'face
22548 (if org-last-todo-state-is-todo
22549 undone-face done-face))))
22550 (org-agenda-highlight-todo 'line)
22551 (beginning-of-line 1))
22552 (t (error "Line update did not work"))))
22553 (beginning-of-line 0)))
22554 (org-finalize-agenda)))
22556 (defun org-agenda-align-tags (&optional line)
22557 "Align all tags in agenda items to `org-agenda-tags-column'."
22558 (let ((inhibit-read-only t) l c)
22559 (save-excursion
22560 (goto-char (if line (point-at-bol) (point-min)))
22561 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22562 (if line (point-at-eol) nil) t)
22563 (add-text-properties
22564 (match-beginning 2) (match-end 2)
22565 (list 'face (list 'org-tag (get-text-property
22566 (match-beginning 2) 'face))))
22567 (setq l (- (match-end 2) (match-beginning 2))
22568 c (if (< org-agenda-tags-column 0)
22569 (- (abs org-agenda-tags-column) l)
22570 org-agenda-tags-column))
22571 (delete-region (match-beginning 1) (match-end 1))
22572 (goto-char (match-beginning 1))
22573 (insert (org-add-props
22574 (make-string (max 1 (- c (current-column))) ?\ )
22575 (text-properties-at (point))))))))
22577 (defun org-agenda-priority-up ()
22578 "Increase the priority of line at point, also in Org-mode file."
22579 (interactive)
22580 (org-agenda-priority 'up))
22582 (defun org-agenda-priority-down ()
22583 "Decrease the priority of line at point, also in Org-mode file."
22584 (interactive)
22585 (org-agenda-priority 'down))
22587 (defun org-agenda-priority (&optional force-direction)
22588 "Set the priority of line at point, also in Org-mode file.
22589 This changes the line at point, all other lines in the agenda referring to
22590 the same tree node, and the headline of the tree node in the Org-mode file."
22591 (interactive)
22592 (org-agenda-check-no-diary)
22593 (let* ((marker (or (get-text-property (point) 'org-marker)
22594 (org-agenda-error)))
22595 (hdmarker (get-text-property (point) 'org-hd-marker))
22596 (buffer (marker-buffer hdmarker))
22597 (pos (marker-position hdmarker))
22598 (inhibit-read-only t)
22599 newhead)
22600 (org-with-remote-undo buffer
22601 (with-current-buffer buffer
22602 (widen)
22603 (goto-char pos)
22604 (org-show-context 'agenda)
22605 (save-excursion
22606 (and (outline-next-heading)
22607 (org-flag-heading nil))) ; show the next heading
22608 (funcall 'org-priority force-direction)
22609 (end-of-line 1)
22610 (setq newhead (org-get-heading)))
22611 (org-agenda-change-all-lines newhead hdmarker)
22612 (beginning-of-line 1))))
22614 (defun org-get-tags-at (&optional pos)
22615 "Get a list of all headline tags applicable at POS.
22616 POS defaults to point. If tags are inherited, the list contains
22617 the targets in the same sequence as the headlines appear, i.e.
22618 the tags of the current headline come last."
22619 (interactive)
22620 (let (tags lastpos)
22621 (save-excursion
22622 (save-restriction
22623 (widen)
22624 (goto-char (or pos (point)))
22625 (save-match-data
22626 (org-back-to-heading t)
22627 (condition-case nil
22628 (while (not (equal lastpos (point)))
22629 (setq lastpos (point))
22630 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
22631 (setq tags (append (org-split-string
22632 (org-match-string-no-properties 1) ":")
22633 tags)))
22634 (or org-use-tag-inheritance (error ""))
22635 (org-up-heading-all 1))
22636 (error nil))))
22637 tags)))
22639 ;; FIXME: should fix the tags property of the agenda line.
22640 (defun org-agenda-set-tags ()
22641 "Set tags for the current headline."
22642 (interactive)
22643 (org-agenda-check-no-diary)
22644 (if (and (org-region-active-p) (interactive-p))
22645 (call-interactively 'org-change-tag-in-region)
22646 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22647 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22648 (org-agenda-error)))
22649 (buffer (marker-buffer hdmarker))
22650 (pos (marker-position hdmarker))
22651 (inhibit-read-only t)
22652 newhead)
22653 (org-with-remote-undo buffer
22654 (with-current-buffer buffer
22655 (widen)
22656 (goto-char pos)
22657 (save-excursion
22658 (org-show-context 'agenda))
22659 (save-excursion
22660 (and (outline-next-heading)
22661 (org-flag-heading nil))) ; show the next heading
22662 (goto-char pos)
22663 (call-interactively 'org-set-tags)
22664 (end-of-line 1)
22665 (setq newhead (org-get-heading)))
22666 (org-agenda-change-all-lines newhead hdmarker)
22667 (beginning-of-line 1)))))
22669 (defun org-agenda-toggle-archive-tag ()
22670 "Toggle the archive tag for the current entry."
22671 (interactive)
22672 (org-agenda-check-no-diary)
22673 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22674 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22675 (org-agenda-error)))
22676 (buffer (marker-buffer hdmarker))
22677 (pos (marker-position hdmarker))
22678 (inhibit-read-only t)
22679 newhead)
22680 (org-with-remote-undo buffer
22681 (with-current-buffer buffer
22682 (widen)
22683 (goto-char pos)
22684 (org-show-context 'agenda)
22685 (save-excursion
22686 (and (outline-next-heading)
22687 (org-flag-heading nil))) ; show the next heading
22688 (call-interactively 'org-toggle-archive-tag)
22689 (end-of-line 1)
22690 (setq newhead (org-get-heading)))
22691 (org-agenda-change-all-lines newhead hdmarker)
22692 (beginning-of-line 1))))
22694 (defun org-agenda-date-later (arg &optional what)
22695 "Change the date of this item to one day later."
22696 (interactive "p")
22697 (org-agenda-check-type t 'agenda 'timeline)
22698 (org-agenda-check-no-diary)
22699 (let* ((marker (or (get-text-property (point) 'org-marker)
22700 (org-agenda-error)))
22701 (buffer (marker-buffer marker))
22702 (pos (marker-position marker)))
22703 (org-with-remote-undo buffer
22704 (with-current-buffer buffer
22705 (widen)
22706 (goto-char pos)
22707 (if (not (org-at-timestamp-p))
22708 (error "Cannot find time stamp"))
22709 (org-timestamp-change arg (or what 'day)))
22710 (org-agenda-show-new-time marker org-last-changed-timestamp))
22711 (message "Time stamp changed to %s" org-last-changed-timestamp)))
22713 (defun org-agenda-date-earlier (arg &optional what)
22714 "Change the date of this item to one day earlier."
22715 (interactive "p")
22716 (org-agenda-date-later (- arg) what))
22718 (defun org-agenda-show-new-time (marker stamp &optional prefix)
22719 "Show new date stamp via text properties."
22720 ;; We use text properties to make this undoable
22721 (let ((inhibit-read-only t))
22722 (setq stamp (concat " " prefix " => " stamp))
22723 (save-excursion
22724 (goto-char (point-max))
22725 (while (not (bobp))
22726 (when (equal marker (get-text-property (point) 'org-marker))
22727 (move-to-column (- (window-width) (length stamp)) t)
22728 (if (featurep 'xemacs)
22729 ;; Use `duplicable' property to trigger undo recording
22730 (let ((ex (make-extent nil nil))
22731 (gl (make-glyph stamp)))
22732 (set-glyph-face gl 'secondary-selection)
22733 (set-extent-properties
22734 ex (list 'invisible t 'end-glyph gl 'duplicable t))
22735 (insert-extent ex (1- (point)) (point-at-eol)))
22736 (add-text-properties
22737 (1- (point)) (point-at-eol)
22738 (list 'display (org-add-props stamp nil
22739 'face 'secondary-selection))))
22740 (beginning-of-line 1))
22741 (beginning-of-line 0)))))
22743 (defun org-agenda-date-prompt (arg)
22744 "Change the date of this item. Date is prompted for, with default today.
22745 The prefix ARG is passed to the `org-time-stamp' command and can therefore
22746 be used to request time specification in the time stamp."
22747 (interactive "P")
22748 (org-agenda-check-type t 'agenda 'timeline)
22749 (org-agenda-check-no-diary)
22750 (let* ((marker (or (get-text-property (point) 'org-marker)
22751 (org-agenda-error)))
22752 (buffer (marker-buffer marker))
22753 (pos (marker-position marker)))
22754 (org-with-remote-undo buffer
22755 (with-current-buffer buffer
22756 (widen)
22757 (goto-char pos)
22758 (if (not (org-at-timestamp-p))
22759 (error "Cannot find time stamp"))
22760 (org-time-stamp arg)
22761 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
22763 (defun org-agenda-schedule (arg)
22764 "Schedule the item at point."
22765 (interactive "P")
22766 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22767 (org-agenda-check-no-diary)
22768 (let* ((marker (or (get-text-property (point) 'org-marker)
22769 (org-agenda-error)))
22770 (buffer (marker-buffer marker))
22771 (pos (marker-position marker))
22772 (org-insert-labeled-timestamps-at-point nil)
22774 (org-with-remote-undo buffer
22775 (with-current-buffer buffer
22776 (widen)
22777 (goto-char pos)
22778 (setq ts (org-schedule arg)))
22779 (org-agenda-show-new-time marker ts "S"))
22780 (message "Item scheduled for %s" ts)))
22782 (defun org-agenda-deadline (arg)
22783 "Schedule the item at point."
22784 (interactive "P")
22785 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22786 (org-agenda-check-no-diary)
22787 (let* ((marker (or (get-text-property (point) 'org-marker)
22788 (org-agenda-error)))
22789 (buffer (marker-buffer marker))
22790 (pos (marker-position marker))
22791 (org-insert-labeled-timestamps-at-point nil)
22793 (org-with-remote-undo buffer
22794 (with-current-buffer buffer
22795 (widen)
22796 (goto-char pos)
22797 (setq ts (org-deadline arg)))
22798 (org-agenda-show-new-time marker ts "S"))
22799 (message "Deadline for this item set to %s" ts)))
22801 (defun org-get-heading (&optional no-tags)
22802 "Return the heading of the current entry, without the stars."
22803 (save-excursion
22804 (org-back-to-heading t)
22805 (if (looking-at
22806 (if no-tags
22807 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
22808 "\\*+[ \t]+\\([^\r\n]*\\)"))
22809 (match-string 1) "")))
22811 (defun org-agenda-clock-in (&optional arg)
22812 "Start the clock on the currently selected item."
22813 (interactive "P")
22814 (org-agenda-check-no-diary)
22815 (let* ((marker (or (get-text-property (point) 'org-marker)
22816 (org-agenda-error)))
22817 (pos (marker-position marker)))
22818 (org-with-remote-undo (marker-buffer marker)
22819 (with-current-buffer (marker-buffer marker)
22820 (widen)
22821 (goto-char pos)
22822 (org-clock-in)))))
22824 (defun org-agenda-clock-out (&optional arg)
22825 "Stop the currently running clock."
22826 (interactive "P")
22827 (unless (marker-buffer org-clock-marker)
22828 (error "No running clock"))
22829 (org-with-remote-undo (marker-buffer org-clock-marker)
22830 (org-clock-out)))
22832 (defun org-agenda-clock-cancel (&optional arg)
22833 "Cancel the currently running clock."
22834 (interactive "P")
22835 (unless (marker-buffer org-clock-marker)
22836 (error "No running clock"))
22837 (org-with-remote-undo (marker-buffer org-clock-marker)
22838 (org-clock-cancel)))
22840 (defun org-agenda-diary-entry ()
22841 "Make a diary entry, like the `i' command from the calendar.
22842 All the standard commands work: block, weekly etc."
22843 (interactive)
22844 (org-agenda-check-type t 'agenda 'timeline)
22845 (require 'diary-lib)
22846 (let* ((char (progn
22847 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
22848 (read-char-exclusive)))
22849 (cmd (cdr (assoc char
22850 '((?d . insert-diary-entry)
22851 (?w . insert-weekly-diary-entry)
22852 (?m . insert-monthly-diary-entry)
22853 (?y . insert-yearly-diary-entry)
22854 (?a . insert-anniversary-diary-entry)
22855 (?b . insert-block-diary-entry)
22856 (?c . insert-cyclic-diary-entry)))))
22857 (oldf (symbol-function 'calendar-cursor-to-date))
22858 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
22859 (point (point))
22860 (mark (or (mark t) (point))))
22861 (unless cmd
22862 (error "No command associated with <%c>" char))
22863 (unless (and (get-text-property point 'day)
22864 (or (not (equal ?b char))
22865 (get-text-property mark 'day)))
22866 (error "Don't know which date to use for diary entry"))
22867 ;; We implement this by hacking the `calendar-cursor-to-date' function
22868 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
22869 (let ((calendar-mark-ring
22870 (list (calendar-gregorian-from-absolute
22871 (or (get-text-property mark 'day)
22872 (get-text-property point 'day))))))
22873 (unwind-protect
22874 (progn
22875 (fset 'calendar-cursor-to-date
22876 (lambda (&optional error)
22877 (calendar-gregorian-from-absolute
22878 (get-text-property point 'day))))
22879 (call-interactively cmd))
22880 (fset 'calendar-cursor-to-date oldf)))))
22883 (defun org-agenda-execute-calendar-command (cmd)
22884 "Execute a calendar command from the agenda, with the date associated to
22885 the cursor position."
22886 (org-agenda-check-type t 'agenda 'timeline)
22887 (require 'diary-lib)
22888 (unless (get-text-property (point) 'day)
22889 (error "Don't know which date to use for calendar command"))
22890 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
22891 (point (point))
22892 (date (calendar-gregorian-from-absolute
22893 (get-text-property point 'day)))
22894 ;; the following 3 vars are needed in the calendar
22895 (displayed-day (extract-calendar-day date))
22896 (displayed-month (extract-calendar-month date))
22897 (displayed-year (extract-calendar-year date)))
22898 (unwind-protect
22899 (progn
22900 (fset 'calendar-cursor-to-date
22901 (lambda (&optional error)
22902 (calendar-gregorian-from-absolute
22903 (get-text-property point 'day))))
22904 (call-interactively cmd))
22905 (fset 'calendar-cursor-to-date oldf))))
22907 (defun org-agenda-phases-of-moon ()
22908 "Display the phases of the moon for the 3 months around the cursor date."
22909 (interactive)
22910 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
22912 (defun org-agenda-holidays ()
22913 "Display the holidays for the 3 months around the cursor date."
22914 (interactive)
22915 (org-agenda-execute-calendar-command 'list-calendar-holidays))
22917 (defun org-agenda-sunrise-sunset (arg)
22918 "Display sunrise and sunset for the cursor date.
22919 Latitude and longitude can be specified with the variables
22920 `calendar-latitude' and `calendar-longitude'. When called with prefix
22921 argument, latitude and longitude will be prompted for."
22922 (interactive "P")
22923 (let ((calendar-longitude (if arg nil calendar-longitude))
22924 (calendar-latitude (if arg nil calendar-latitude))
22925 (calendar-location-name
22926 (if arg "the given coordinates" calendar-location-name)))
22927 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
22929 (defun org-agenda-goto-calendar ()
22930 "Open the Emacs calendar with the date at the cursor."
22931 (interactive)
22932 (org-agenda-check-type t 'agenda 'timeline)
22933 (let* ((day (or (get-text-property (point) 'day)
22934 (error "Don't know which date to open in calendar")))
22935 (date (calendar-gregorian-from-absolute day))
22936 (calendar-move-hook nil)
22937 (view-calendar-holidays-initially nil)
22938 (view-diary-entries-initially nil))
22939 (calendar)
22940 (calendar-goto-date date)))
22942 (defun org-calendar-goto-agenda ()
22943 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
22944 This is a command that has to be installed in `calendar-mode-map'."
22945 (interactive)
22946 (org-agenda-list nil (calendar-absolute-from-gregorian
22947 (calendar-cursor-to-date))
22948 nil))
22950 (defun org-agenda-convert-date ()
22951 (interactive)
22952 (org-agenda-check-type t 'agenda 'timeline)
22953 (let ((day (get-text-property (point) 'day))
22954 date s)
22955 (unless day
22956 (error "Don't know which date to convert"))
22957 (setq date (calendar-gregorian-from-absolute day))
22958 (setq s (concat
22959 "Gregorian: " (calendar-date-string date) "\n"
22960 "ISO: " (calendar-iso-date-string date) "\n"
22961 "Day of Yr: " (calendar-day-of-year-string date) "\n"
22962 "Julian: " (calendar-julian-date-string date) "\n"
22963 "Astron. JD: " (calendar-astro-date-string date)
22964 " (Julian date number at noon UTC)\n"
22965 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
22966 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
22967 "French: " (calendar-french-date-string date) "\n"
22968 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
22969 "Mayan: " (calendar-mayan-date-string date) "\n"
22970 "Coptic: " (calendar-coptic-date-string date) "\n"
22971 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
22972 "Persian: " (calendar-persian-date-string date) "\n"
22973 "Chinese: " (calendar-chinese-date-string date) "\n"))
22974 (with-output-to-temp-buffer "*Dates*"
22975 (princ s))
22976 (if (fboundp 'fit-window-to-buffer)
22977 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
22980 ;;;; Embedded LaTeX
22982 (defvar org-cdlatex-mode-map (make-sparse-keymap)
22983 "Keymap for the minor `org-cdlatex-mode'.")
22985 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
22986 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
22987 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
22988 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
22989 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
22991 (defvar org-cdlatex-texmathp-advice-is-done nil
22992 "Flag remembering if we have applied the advice to texmathp already.")
22994 (define-minor-mode org-cdlatex-mode
22995 "Toggle the minor `org-cdlatex-mode'.
22996 This mode supports entering LaTeX environment and math in LaTeX fragments
22997 in Org-mode.
22998 \\{org-cdlatex-mode-map}"
22999 nil " OCDL" nil
23000 (when org-cdlatex-mode (require 'cdlatex))
23001 (unless org-cdlatex-texmathp-advice-is-done
23002 (setq org-cdlatex-texmathp-advice-is-done t)
23003 (defadvice texmathp (around org-math-always-on activate)
23004 "Always return t in org-mode buffers.
23005 This is because we want to insert math symbols without dollars even outside
23006 the LaTeX math segments. If Orgmode thinks that point is actually inside
23007 en embedded LaTeX fragement, let texmathp do its job.
23008 \\[org-cdlatex-mode-map]"
23009 (interactive)
23010 (let (p)
23011 (cond
23012 ((not (org-mode-p)) ad-do-it)
23013 ((eq this-command 'cdlatex-math-symbol)
23014 (setq ad-return-value t
23015 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
23017 (let ((p (org-inside-LaTeX-fragment-p)))
23018 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
23019 (setq ad-return-value t
23020 texmathp-why '("Org-mode embedded math" . 0))
23021 (if p ad-do-it)))))))))
23023 (defun turn-on-org-cdlatex ()
23024 "Unconditionally turn on `org-cdlatex-mode'."
23025 (org-cdlatex-mode 1))
23027 (defun org-inside-LaTeX-fragment-p ()
23028 "Test if point is inside a LaTeX fragment.
23029 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
23030 sequence appearing also before point.
23031 Even though the matchers for math are configurable, this function assumes
23032 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
23033 delimiters are skipped when they have been removed by customization.
23034 The return value is nil, or a cons cell with the delimiter and
23035 and the position of this delimiter.
23037 This function does a reasonably good job, but can locally be fooled by
23038 for example currency specifications. For example it will assume being in
23039 inline math after \"$22.34\". The LaTeX fragment formatter will only format
23040 fragments that are properly closed, but during editing, we have to live
23041 with the uncertainty caused by missing closing delimiters. This function
23042 looks only before point, not after."
23043 (catch 'exit
23044 (let ((pos (point))
23045 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
23046 (lim (progn
23047 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
23048 (point)))
23049 dd-on str (start 0) m re)
23050 (goto-char pos)
23051 (when dodollar
23052 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
23053 re (nth 1 (assoc "$" org-latex-regexps)))
23054 (while (string-match re str start)
23055 (cond
23056 ((= (match-end 0) (length str))
23057 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
23058 ((= (match-end 0) (- (length str) 5))
23059 (throw 'exit nil))
23060 (t (setq start (match-end 0))))))
23061 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
23062 (goto-char pos)
23063 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
23064 (and (match-beginning 2) (throw 'exit nil))
23065 ;; count $$
23066 (while (re-search-backward "\\$\\$" lim t)
23067 (setq dd-on (not dd-on)))
23068 (goto-char pos)
23069 (if dd-on (cons "$$" m))))))
23072 (defun org-try-cdlatex-tab ()
23073 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
23074 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
23075 - inside a LaTeX fragment, or
23076 - after the first word in a line, where an abbreviation expansion could
23077 insert a LaTeX environment."
23078 (when org-cdlatex-mode
23079 (cond
23080 ((save-excursion
23081 (skip-chars-backward "a-zA-Z0-9*")
23082 (skip-chars-backward " \t")
23083 (bolp))
23084 (cdlatex-tab) t)
23085 ((org-inside-LaTeX-fragment-p)
23086 (cdlatex-tab) t)
23087 (t nil))))
23089 (defun org-cdlatex-underscore-caret (&optional arg)
23090 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
23091 Revert to the normal definition outside of these fragments."
23092 (interactive "P")
23093 (if (org-inside-LaTeX-fragment-p)
23094 (call-interactively 'cdlatex-sub-superscript)
23095 (let (org-cdlatex-mode)
23096 (call-interactively (key-binding (vector last-input-event))))))
23098 (defun org-cdlatex-math-modify (&optional arg)
23099 "Execute `cdlatex-math-modify' in LaTeX fragments.
23100 Revert to the normal definition outside of these fragments."
23101 (interactive "P")
23102 (if (org-inside-LaTeX-fragment-p)
23103 (call-interactively 'cdlatex-math-modify)
23104 (let (org-cdlatex-mode)
23105 (call-interactively (key-binding (vector last-input-event))))))
23107 (defvar org-latex-fragment-image-overlays nil
23108 "List of overlays carrying the images of latex fragments.")
23109 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
23111 (defun org-remove-latex-fragment-image-overlays ()
23112 "Remove all overlays with LaTeX fragment images in current buffer."
23113 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
23114 (setq org-latex-fragment-image-overlays nil))
23116 (defun org-preview-latex-fragment (&optional subtree)
23117 "Preview the LaTeX fragment at point, or all locally or globally.
23118 If the cursor is in a LaTeX fragment, create the image and overlay
23119 it over the source code. If there is no fragment at point, display
23120 all fragments in the current text, from one headline to the next. With
23121 prefix SUBTREE, display all fragments in the current subtree. With a
23122 double prefix `C-u C-u', or when the cursor is before the first headline,
23123 display all fragments in the buffer.
23124 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
23125 (interactive "P")
23126 (org-remove-latex-fragment-image-overlays)
23127 (save-excursion
23128 (save-restriction
23129 (let (beg end at msg)
23130 (cond
23131 ((or (equal subtree '(16))
23132 (not (save-excursion
23133 (re-search-backward (concat "^" outline-regexp) nil t))))
23134 (setq beg (point-min) end (point-max)
23135 msg "Creating images for buffer...%s"))
23136 ((equal subtree '(4))
23137 (org-back-to-heading)
23138 (setq beg (point) end (org-end-of-subtree t)
23139 msg "Creating images for subtree...%s"))
23141 (if (setq at (org-inside-LaTeX-fragment-p))
23142 (goto-char (max (point-min) (- (cdr at) 2)))
23143 (org-back-to-heading))
23144 (setq beg (point) end (progn (outline-next-heading) (point))
23145 msg (if at "Creating image...%s"
23146 "Creating images for entry...%s"))))
23147 (message msg "")
23148 (narrow-to-region beg end)
23149 (goto-char beg)
23150 (org-format-latex
23151 (concat "ltxpng/" (file-name-sans-extension
23152 (file-name-nondirectory
23153 buffer-file-name)))
23154 default-directory 'overlays msg at 'forbuffer)
23155 (message msg "done. Use `C-c C-c' to remove images.")))))
23157 (defvar org-latex-regexps
23158 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
23159 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
23160 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
23161 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
23162 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
23163 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
23164 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
23165 "Regular expressions for matching embedded LaTeX.")
23167 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
23168 "Replace LaTeX fragments with links to an image, and produce images."
23169 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
23170 (let* ((prefixnodir (file-name-nondirectory prefix))
23171 (absprefix (expand-file-name prefix dir))
23172 (todir (file-name-directory absprefix))
23173 (opt org-format-latex-options)
23174 (matchers (plist-get opt :matchers))
23175 (re-list org-latex-regexps)
23176 (cnt 0) txt link beg end re e checkdir
23177 m n block linkfile movefile ov)
23178 ;; Check if there are old images files with this prefix, and remove them
23179 (when (file-directory-p todir)
23180 (mapc 'delete-file
23181 (directory-files
23182 todir 'full
23183 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
23184 ;; Check the different regular expressions
23185 (while (setq e (pop re-list))
23186 (setq m (car e) re (nth 1 e) n (nth 2 e)
23187 block (if (nth 3 e) "\n\n" ""))
23188 (when (member m matchers)
23189 (goto-char (point-min))
23190 (while (re-search-forward re nil t)
23191 (when (or (not at) (equal (cdr at) (match-beginning n)))
23192 (setq txt (match-string n)
23193 beg (match-beginning n) end (match-end n)
23194 cnt (1+ cnt)
23195 linkfile (format "%s_%04d.png" prefix cnt)
23196 movefile (format "%s_%04d.png" absprefix cnt)
23197 link (concat block "[[file:" linkfile "]]" block))
23198 (if msg (message msg cnt))
23199 (goto-char beg)
23200 (unless checkdir ; make sure the directory exists
23201 (setq checkdir t)
23202 (or (file-directory-p todir) (make-directory todir)))
23203 (org-create-formula-image
23204 txt movefile opt forbuffer)
23205 (if overlays
23206 (progn
23207 (setq ov (org-make-overlay beg end))
23208 (if (featurep 'xemacs)
23209 (progn
23210 (org-overlay-put ov 'invisible t)
23211 (org-overlay-put
23212 ov 'end-glyph
23213 (make-glyph (vector 'png :file movefile))))
23214 (org-overlay-put
23215 ov 'display
23216 (list 'image :type 'png :file movefile :ascent 'center)))
23217 (push ov org-latex-fragment-image-overlays)
23218 (goto-char end))
23219 (delete-region beg end)
23220 (insert link))))))))
23222 ;; This function borrows from Ganesh Swami's latex2png.el
23223 (defun org-create-formula-image (string tofile options buffer)
23224 (let* ((tmpdir (if (featurep 'xemacs)
23225 (temp-directory)
23226 temporary-file-directory))
23227 (texfilebase (make-temp-name
23228 (expand-file-name "orgtex" tmpdir)))
23229 (texfile (concat texfilebase ".tex"))
23230 (dvifile (concat texfilebase ".dvi"))
23231 (pngfile (concat texfilebase ".png"))
23232 (fnh (face-attribute 'default :height nil))
23233 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
23234 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
23235 (fg (or (plist-get options (if buffer :foreground :html-foreground))
23236 "Black"))
23237 (bg (or (plist-get options (if buffer :background :html-background))
23238 "Transparent")))
23239 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
23240 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
23241 (with-temp-file texfile
23242 (insert org-format-latex-header
23243 "\n\\begin{document}\n" string "\n\\end{document}\n"))
23244 (let ((dir default-directory))
23245 (condition-case nil
23246 (progn
23247 (cd tmpdir)
23248 (call-process "latex" nil nil nil texfile))
23249 (error nil))
23250 (cd dir))
23251 (if (not (file-exists-p dvifile))
23252 (progn (message "Failed to create dvi file from %s" texfile) nil)
23253 (call-process "dvipng" nil nil nil
23254 "-E" "-fg" fg "-bg" bg
23255 "-D" dpi
23256 ;;"-x" scale "-y" scale
23257 "-T" "tight"
23258 "-o" pngfile
23259 dvifile)
23260 (if (not (file-exists-p pngfile))
23261 (progn (message "Failed to create png file from %s" texfile) nil)
23262 ;; Use the requested file name and clean up
23263 (copy-file pngfile tofile 'replace)
23264 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
23265 (delete-file (concat texfilebase e)))
23266 pngfile))))
23268 (defun org-dvipng-color (attr)
23269 "Return an rgb color specification for dvipng."
23270 (apply 'format "rgb %s %s %s"
23271 (mapcar 'org-normalize-color
23272 (color-values (face-attribute 'default attr nil)))))
23274 (defun org-normalize-color (value)
23275 "Return string to be used as color value for an RGB component."
23276 (format "%g" (/ value 65535.0)))
23278 ;;;; Exporting
23280 ;;; Variables, constants, and parameter plists
23282 (defconst org-level-max 20)
23284 (defvar org-export-html-preamble nil
23285 "Preamble, to be inserted just after <body>. Set by publishing functions.")
23286 (defvar org-export-html-postamble nil
23287 "Preamble, to be inserted just before </body>. Set by publishing functions.")
23288 (defvar org-export-html-auto-preamble t
23289 "Should default preamble be inserted? Set by publishing functions.")
23290 (defvar org-export-html-auto-postamble t
23291 "Should default postamble be inserted? Set by publishing functions.")
23292 (defvar org-current-export-file nil) ; dynamically scoped parameter
23293 (defvar org-current-export-dir nil) ; dynamically scoped parameter
23296 (defconst org-export-plist-vars
23297 '((:language . org-export-default-language)
23298 (:customtime . org-display-custom-times)
23299 (:headline-levels . org-export-headline-levels)
23300 (:section-numbers . org-export-with-section-numbers)
23301 (:table-of-contents . org-export-with-toc)
23302 (:preserve-breaks . org-export-preserve-breaks)
23303 (:archived-trees . org-export-with-archived-trees)
23304 (:emphasize . org-export-with-emphasize)
23305 (:sub-superscript . org-export-with-sub-superscripts)
23306 (:special-strings . org-export-with-special-strings)
23307 (:footnotes . org-export-with-footnotes)
23308 (:drawers . org-export-with-drawers)
23309 (:tags . org-export-with-tags)
23310 (:TeX-macros . org-export-with-TeX-macros)
23311 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
23312 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
23313 (:fixed-width . org-export-with-fixed-width)
23314 (:timestamps . org-export-with-timestamps)
23315 (:author-info . org-export-author-info)
23316 (:time-stamp-file . org-export-time-stamp-file)
23317 (:tables . org-export-with-tables)
23318 (:table-auto-headline . org-export-highlight-first-table-line)
23319 (:style . org-export-html-style)
23320 (:agenda-style . org-agenda-export-html-style)
23321 (:convert-org-links . org-export-html-link-org-files-as-html)
23322 (:inline-images . org-export-html-inline-images)
23323 (:html-extension . org-export-html-extension)
23324 (:html-table-tag . org-export-html-table-tag)
23325 (:expand-quoted-html . org-export-html-expand)
23326 (:timestamp . org-export-html-with-timestamp)
23327 (:publishing-directory . org-export-publishing-directory)
23328 (:preamble . org-export-html-preamble)
23329 (:postamble . org-export-html-postamble)
23330 (:auto-preamble . org-export-html-auto-preamble)
23331 (:auto-postamble . org-export-html-auto-postamble)
23332 (:author . user-full-name)
23333 (:email . user-mail-address)))
23335 (defun org-default-export-plist ()
23336 "Return the property list with default settings for the export variables."
23337 (let ((l org-export-plist-vars) rtn e)
23338 (while (setq e (pop l))
23339 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
23340 rtn))
23342 (defun org-infile-export-plist ()
23343 "Return the property list with file-local settings for export."
23344 (save-excursion
23345 (save-restriction
23346 (widen)
23347 (goto-char 0)
23348 (let ((re (org-make-options-regexp
23349 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
23350 p key val text options)
23351 (while (re-search-forward re nil t)
23352 (setq key (org-match-string-no-properties 1)
23353 val (org-match-string-no-properties 2))
23354 (cond
23355 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
23356 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
23357 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
23358 ((string-equal key "DATE") (setq p (plist-put p :date val)))
23359 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
23360 ((string-equal key "TEXT")
23361 (setq text (if text (concat text "\n" val) val)))
23362 ((string-equal key "OPTIONS") (setq options val))))
23363 (setq p (plist-put p :text text))
23364 (when options
23365 (let ((op '(("H" . :headline-levels)
23366 ("num" . :section-numbers)
23367 ("toc" . :table-of-contents)
23368 ("\\n" . :preserve-breaks)
23369 ("@" . :expand-quoted-html)
23370 (":" . :fixed-width)
23371 ("|" . :tables)
23372 ("^" . :sub-superscript)
23373 ("-" . :special-strings)
23374 ("f" . :footnotes)
23375 ("d" . :drawers)
23376 ("tags" . :tags)
23377 ("*" . :emphasize)
23378 ("TeX" . :TeX-macros)
23379 ("LaTeX" . :LaTeX-fragments)
23380 ("skip" . :skip-before-1st-heading)
23381 ("author" . :author-info)
23382 ("timestamp" . :time-stamp-file)))
23384 (while (setq o (pop op))
23385 (if (string-match (concat (regexp-quote (car o))
23386 ":\\([^ \t\n\r;,.]*\\)")
23387 options)
23388 (setq p (plist-put p (cdr o)
23389 (car (read-from-string
23390 (match-string 1 options)))))))))
23391 p))))
23393 (defun org-export-directory (type plist)
23394 (let* ((val (plist-get plist :publishing-directory))
23395 (dir (if (listp val)
23396 (or (cdr (assoc type val)) ".")
23397 val)))
23398 dir))
23400 (defun org-skip-comments (lines)
23401 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
23402 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
23403 (re2 "^\\(\\*+\\)[ \t\n\r]")
23404 (case-fold-search nil)
23405 rtn line level)
23406 (while (setq line (pop lines))
23407 (cond
23408 ((and (string-match re1 line)
23409 (setq level (- (match-end 1) (match-beginning 1))))
23410 ;; Beginning of a COMMENT subtree. Skip it.
23411 (while (and (setq line (pop lines))
23412 (or (not (string-match re2 line))
23413 (> (- (match-end 1) (match-beginning 1)) level))))
23414 (setq lines (cons line lines)))
23415 ((string-match "^#" line)
23416 ;; an ordinary comment line
23418 ((and org-export-table-remove-special-lines
23419 (string-match "^[ \t]*|" line)
23420 (or (string-match "^[ \t]*| *[!_^] *|" line)
23421 (and (string-match "| *<[0-9]+> *|" line)
23422 (not (string-match "| *[^ <|]" line)))))
23423 ;; a special table line that should be removed
23425 (t (setq rtn (cons line rtn)))))
23426 (nreverse rtn)))
23428 (defun org-export (&optional arg)
23429 (interactive)
23430 (let ((help "[t] insert the export option template
23431 \[v] limit export to visible part of outline tree
23433 \[a] export as ASCII
23435 \[h] export as HTML
23436 \[H] export as HTML to temporary buffer
23437 \[R] export region as HTML
23438 \[b] export as HTML and browse immediately
23439 \[x] export as XOXO
23441 \[l] export as LaTeX
23442 \[L] export as LaTeX to temporary buffer
23444 \[i] export current file as iCalendar file
23445 \[I] export all agenda files as iCalendar files
23446 \[c] export agenda files into combined iCalendar file
23448 \[F] publish current file
23449 \[P] publish current project
23450 \[X] publish... (project will be prompted for)
23451 \[A] publish all projects")
23452 (cmds
23453 '((?t . org-insert-export-options-template)
23454 (?v . org-export-visible)
23455 (?a . org-export-as-ascii)
23456 (?h . org-export-as-html)
23457 (?b . org-export-as-html-and-open)
23458 (?H . org-export-as-html-to-buffer)
23459 (?R . org-export-region-as-html)
23460 (?x . org-export-as-xoxo)
23461 (?l . org-export-as-latex)
23462 (?L . org-export-as-latex-to-buffer)
23463 (?i . org-export-icalendar-this-file)
23464 (?I . org-export-icalendar-all-agenda-files)
23465 (?c . org-export-icalendar-combine-agenda-files)
23466 (?F . org-publish-current-file)
23467 (?P . org-publish-current-project)
23468 (?X . org-publish)
23469 (?A . org-publish-all)))
23470 r1 r2 ass)
23471 (save-window-excursion
23472 (delete-other-windows)
23473 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
23474 (princ help))
23475 (message "Select command: ")
23476 (setq r1 (read-char-exclusive)))
23477 (setq r2 (if (< r1 27) (+ r1 96) r1))
23478 (if (setq ass (assq r2 cmds))
23479 (call-interactively (cdr ass))
23480 (error "No command associated with key %c" r1))))
23482 (defconst org-html-entities
23483 '(("nbsp")
23484 ("iexcl")
23485 ("cent")
23486 ("pound")
23487 ("curren")
23488 ("yen")
23489 ("brvbar")
23490 ("vert" . "&#124;")
23491 ("sect")
23492 ("uml")
23493 ("copy")
23494 ("ordf")
23495 ("laquo")
23496 ("not")
23497 ("shy")
23498 ("reg")
23499 ("macr")
23500 ("deg")
23501 ("plusmn")
23502 ("sup2")
23503 ("sup3")
23504 ("acute")
23505 ("micro")
23506 ("para")
23507 ("middot")
23508 ("odot"."o")
23509 ("star"."*")
23510 ("cedil")
23511 ("sup1")
23512 ("ordm")
23513 ("raquo")
23514 ("frac14")
23515 ("frac12")
23516 ("frac34")
23517 ("iquest")
23518 ("Agrave")
23519 ("Aacute")
23520 ("Acirc")
23521 ("Atilde")
23522 ("Auml")
23523 ("Aring") ("AA"."&Aring;")
23524 ("AElig")
23525 ("Ccedil")
23526 ("Egrave")
23527 ("Eacute")
23528 ("Ecirc")
23529 ("Euml")
23530 ("Igrave")
23531 ("Iacute")
23532 ("Icirc")
23533 ("Iuml")
23534 ("ETH")
23535 ("Ntilde")
23536 ("Ograve")
23537 ("Oacute")
23538 ("Ocirc")
23539 ("Otilde")
23540 ("Ouml")
23541 ("times")
23542 ("Oslash")
23543 ("Ugrave")
23544 ("Uacute")
23545 ("Ucirc")
23546 ("Uuml")
23547 ("Yacute")
23548 ("THORN")
23549 ("szlig")
23550 ("agrave")
23551 ("aacute")
23552 ("acirc")
23553 ("atilde")
23554 ("auml")
23555 ("aring")
23556 ("aelig")
23557 ("ccedil")
23558 ("egrave")
23559 ("eacute")
23560 ("ecirc")
23561 ("euml")
23562 ("igrave")
23563 ("iacute")
23564 ("icirc")
23565 ("iuml")
23566 ("eth")
23567 ("ntilde")
23568 ("ograve")
23569 ("oacute")
23570 ("ocirc")
23571 ("otilde")
23572 ("ouml")
23573 ("divide")
23574 ("oslash")
23575 ("ugrave")
23576 ("uacute")
23577 ("ucirc")
23578 ("uuml")
23579 ("yacute")
23580 ("thorn")
23581 ("yuml")
23582 ("fnof")
23583 ("Alpha")
23584 ("Beta")
23585 ("Gamma")
23586 ("Delta")
23587 ("Epsilon")
23588 ("Zeta")
23589 ("Eta")
23590 ("Theta")
23591 ("Iota")
23592 ("Kappa")
23593 ("Lambda")
23594 ("Mu")
23595 ("Nu")
23596 ("Xi")
23597 ("Omicron")
23598 ("Pi")
23599 ("Rho")
23600 ("Sigma")
23601 ("Tau")
23602 ("Upsilon")
23603 ("Phi")
23604 ("Chi")
23605 ("Psi")
23606 ("Omega")
23607 ("alpha")
23608 ("beta")
23609 ("gamma")
23610 ("delta")
23611 ("epsilon")
23612 ("varepsilon"."&epsilon;")
23613 ("zeta")
23614 ("eta")
23615 ("theta")
23616 ("iota")
23617 ("kappa")
23618 ("lambda")
23619 ("mu")
23620 ("nu")
23621 ("xi")
23622 ("omicron")
23623 ("pi")
23624 ("rho")
23625 ("sigmaf") ("varsigma"."&sigmaf;")
23626 ("sigma")
23627 ("tau")
23628 ("upsilon")
23629 ("phi")
23630 ("chi")
23631 ("psi")
23632 ("omega")
23633 ("thetasym") ("vartheta"."&thetasym;")
23634 ("upsih")
23635 ("piv")
23636 ("bull") ("bullet"."&bull;")
23637 ("hellip") ("dots"."&hellip;")
23638 ("prime")
23639 ("Prime")
23640 ("oline")
23641 ("frasl")
23642 ("weierp")
23643 ("image")
23644 ("real")
23645 ("trade")
23646 ("alefsym")
23647 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
23648 ("uarr") ("uparrow"."&uarr;")
23649 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
23650 ("darr")("downarrow"."&darr;")
23651 ("harr") ("leftrightarrow"."&harr;")
23652 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
23653 ("lArr") ("Leftarrow"."&lArr;")
23654 ("uArr") ("Uparrow"."&uArr;")
23655 ("rArr") ("Rightarrow"."&rArr;")
23656 ("dArr") ("Downarrow"."&dArr;")
23657 ("hArr") ("Leftrightarrow"."&hArr;")
23658 ("forall")
23659 ("part") ("partial"."&part;")
23660 ("exist") ("exists"."&exist;")
23661 ("empty") ("emptyset"."&empty;")
23662 ("nabla")
23663 ("isin") ("in"."&isin;")
23664 ("notin")
23665 ("ni")
23666 ("prod")
23667 ("sum")
23668 ("minus")
23669 ("lowast") ("ast"."&lowast;")
23670 ("radic")
23671 ("prop") ("proptp"."&prop;")
23672 ("infin") ("infty"."&infin;")
23673 ("ang") ("angle"."&ang;")
23674 ("and") ("wedge"."&and;")
23675 ("or") ("vee"."&or;")
23676 ("cap")
23677 ("cup")
23678 ("int")
23679 ("there4")
23680 ("sim")
23681 ("cong") ("simeq"."&cong;")
23682 ("asymp")("approx"."&asymp;")
23683 ("ne") ("neq"."&ne;")
23684 ("equiv")
23685 ("le")
23686 ("ge")
23687 ("sub") ("subset"."&sub;")
23688 ("sup") ("supset"."&sup;")
23689 ("nsub")
23690 ("sube")
23691 ("supe")
23692 ("oplus")
23693 ("otimes")
23694 ("perp")
23695 ("sdot") ("cdot"."&sdot;")
23696 ("lceil")
23697 ("rceil")
23698 ("lfloor")
23699 ("rfloor")
23700 ("lang")
23701 ("rang")
23702 ("loz") ("Diamond"."&loz;")
23703 ("spades") ("spadesuit"."&spades;")
23704 ("clubs") ("clubsuit"."&clubs;")
23705 ("hearts") ("diamondsuit"."&hearts;")
23706 ("diams") ("diamondsuit"."&diams;")
23707 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
23708 ("quot")
23709 ("amp")
23710 ("lt")
23711 ("gt")
23712 ("OElig")
23713 ("oelig")
23714 ("Scaron")
23715 ("scaron")
23716 ("Yuml")
23717 ("circ")
23718 ("tilde")
23719 ("ensp")
23720 ("emsp")
23721 ("thinsp")
23722 ("zwnj")
23723 ("zwj")
23724 ("lrm")
23725 ("rlm")
23726 ("ndash")
23727 ("mdash")
23728 ("lsquo")
23729 ("rsquo")
23730 ("sbquo")
23731 ("ldquo")
23732 ("rdquo")
23733 ("bdquo")
23734 ("dagger")
23735 ("Dagger")
23736 ("permil")
23737 ("lsaquo")
23738 ("rsaquo")
23739 ("euro")
23741 ("arccos"."arccos")
23742 ("arcsin"."arcsin")
23743 ("arctan"."arctan")
23744 ("arg"."arg")
23745 ("cos"."cos")
23746 ("cosh"."cosh")
23747 ("cot"."cot")
23748 ("coth"."coth")
23749 ("csc"."csc")
23750 ("deg"."deg")
23751 ("det"."det")
23752 ("dim"."dim")
23753 ("exp"."exp")
23754 ("gcd"."gcd")
23755 ("hom"."hom")
23756 ("inf"."inf")
23757 ("ker"."ker")
23758 ("lg"."lg")
23759 ("lim"."lim")
23760 ("liminf"."liminf")
23761 ("limsup"."limsup")
23762 ("ln"."ln")
23763 ("log"."log")
23764 ("max"."max")
23765 ("min"."min")
23766 ("Pr"."Pr")
23767 ("sec"."sec")
23768 ("sin"."sin")
23769 ("sinh"."sinh")
23770 ("sup"."sup")
23771 ("tan"."tan")
23772 ("tanh"."tanh")
23774 "Entities for TeX->HTML translation.
23775 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
23776 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
23777 In that case, \"\\ent\" will be translated to \"&other;\".
23778 The list contains HTML entities for Latin-1, Greek and other symbols.
23779 It is supplemented by a number of commonly used TeX macros with appropriate
23780 translations. There is currently no way for users to extend this.")
23782 ;;; General functions for all backends
23784 (defun org-cleaned-string-for-export (string &rest parameters)
23785 "Cleanup a buffer STRING so that links can be created safely."
23786 (interactive)
23787 (let* ((re-radio (and org-target-link-regexp
23788 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
23789 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
23790 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
23791 (re-archive (concat ":" org-archive-tag ":"))
23792 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
23793 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
23794 (htmlp (plist-get parameters :for-html))
23795 (asciip (plist-get parameters :for-ascii))
23796 (latexp (plist-get parameters :for-LaTeX))
23797 (commentsp (plist-get parameters :comments))
23798 (archived-trees (plist-get parameters :archived-trees))
23799 (inhibit-read-only t)
23800 (drawers org-drawers)
23801 (exp-drawers (plist-get parameters :drawers))
23802 (outline-regexp "\\*+ ")
23803 a b xx
23804 rtn p)
23805 (with-current-buffer (get-buffer-create " org-mode-tmp")
23806 (erase-buffer)
23807 (insert string)
23808 ;; Remove license-to-kill stuff
23809 (while (setq p (text-property-any (point-min) (point-max)
23810 :org-license-to-kill t))
23811 (delete-region p (next-single-property-change p :org-license-to-kill)))
23813 (let ((org-inhibit-startup t)) (org-mode))
23814 (untabify (point-min) (point-max))
23816 ;; Get the correct stuff before the first headline
23817 (when (plist-get parameters :skip-before-1st-heading)
23818 (goto-char (point-min))
23819 (when (re-search-forward "^\\*+[ \t]" nil t)
23820 (delete-region (point-min) (match-beginning 0))
23821 (goto-char (point-min))
23822 (insert "\n")))
23823 (when (plist-get parameters :add-text)
23824 (goto-char (point-min))
23825 (insert (plist-get parameters :add-text) "\n"))
23827 ;; Get rid of archived trees
23828 (when (not (eq archived-trees t))
23829 (goto-char (point-min))
23830 (while (re-search-forward re-archive nil t)
23831 (if (not (org-on-heading-p t))
23832 (org-end-of-subtree t)
23833 (beginning-of-line 1)
23834 (setq a (if archived-trees
23835 (1+ (point-at-eol)) (point))
23836 b (org-end-of-subtree t))
23837 (if (> b a) (delete-region a b)))))
23839 ;; Get rid of drawers
23840 (unless (eq t exp-drawers)
23841 (goto-char (point-min))
23842 (let ((re (concat "^[ \t]*:\\("
23843 (mapconcat
23844 'identity
23845 (org-delete-all exp-drawers
23846 (copy-sequence drawers))
23847 "\\|")
23848 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
23849 (while (re-search-forward re nil t)
23850 (replace-match ""))))
23852 ;; Find targets in comments and move them out of comments,
23853 ;; but mark them as targets that should be invisible
23854 (goto-char (point-min))
23855 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
23856 (replace-match "\\1(INVISIBLE)"))
23858 ;; Protect backend specific stuff, throw away the others.
23859 (let ((formatters
23860 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
23861 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
23862 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
23863 fmt)
23864 (goto-char (point-min))
23865 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
23866 (goto-char (match-end 0))
23867 (while (not (looking-at "#\\+END_EXAMPLE"))
23868 (insert ": ")
23869 (beginning-of-line 2)))
23870 (goto-char (point-min))
23871 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
23872 (add-text-properties (match-beginning 0) (match-end 0)
23873 '(org-protected t)))
23874 (while formatters
23875 (setq fmt (pop formatters))
23876 (when (car fmt)
23877 (goto-char (point-min))
23878 (while (re-search-forward (concat "^#\\+" (cadr fmt)
23879 ":[ \t]*\\(.*\\)") nil t)
23880 (replace-match "\\1" t)
23881 (add-text-properties
23882 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
23883 '(org-protected t))))
23884 (goto-char (point-min))
23885 (while (re-search-forward
23886 (concat "^#\\+"
23887 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
23888 (cadddr fmt) "\\>.*\n?") nil t)
23889 (if (car fmt)
23890 (add-text-properties (match-beginning 1) (1+ (match-end 1))
23891 '(org-protected t))
23892 (delete-region (match-beginning 0) (match-end 0))))))
23894 ;; Protect quoted subtrees
23895 (goto-char (point-min))
23896 (while (re-search-forward re-quote nil t)
23897 (goto-char (match-beginning 0))
23898 (end-of-line 1)
23899 (add-text-properties (point) (org-end-of-subtree t)
23900 '(org-protected t)))
23902 ;; Protect verbatim elements
23903 (goto-char (point-min))
23904 (while (re-search-forward org-verbatim-re nil t)
23905 (add-text-properties (match-beginning 4) (match-end 4)
23906 '(org-protected t))
23907 (goto-char (1+ (match-end 4))))
23909 ;; Remove subtrees that are commented
23910 (goto-char (point-min))
23911 (while (re-search-forward re-commented nil t)
23912 (goto-char (match-beginning 0))
23913 (delete-region (point) (org-end-of-subtree t)))
23915 ;; Remove special table lines
23916 (when org-export-table-remove-special-lines
23917 (goto-char (point-min))
23918 (while (re-search-forward "^[ \t]*|" nil t)
23919 (beginning-of-line 1)
23920 (if (or (looking-at "[ \t]*| *[!_^] *|")
23921 (and (looking-at ".*?| *<[0-9]+> *|")
23922 (not (looking-at ".*?| *[^ <|]"))))
23923 (delete-region (max (point-min) (1- (point-at-bol)))
23924 (point-at-eol))
23925 (end-of-line 1))))
23927 ;; Specific LaTeX stuff
23928 (when latexp
23929 (require 'org-export-latex nil)
23930 (org-export-latex-cleaned-string))
23932 (when asciip
23933 (org-export-ascii-clean-string))
23935 ;; Specific HTML stuff
23936 (when htmlp
23937 ;; Convert LaTeX fragments to images
23938 (when (plist-get parameters :LaTeX-fragments)
23939 (org-format-latex
23940 (concat "ltxpng/" (file-name-sans-extension
23941 (file-name-nondirectory
23942 org-current-export-file)))
23943 org-current-export-dir nil "Creating LaTeX image %s"))
23944 (message "Exporting..."))
23946 ;; Remove or replace comments
23947 (goto-char (point-min))
23948 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
23949 (if commentsp
23950 (progn (add-text-properties
23951 (match-beginning 0) (match-end 0) '(org-protected t))
23952 (replace-match (format commentsp (match-string 1)) t t))
23953 (replace-match "")))
23955 ;; Find matches for radio targets and turn them into internal links
23956 (goto-char (point-min))
23957 (when re-radio
23958 (while (re-search-forward re-radio nil t)
23959 (org-if-unprotected
23960 (replace-match "\\1[[\\2]]"))))
23962 ;; Find all links that contain a newline and put them into a single line
23963 (goto-char (point-min))
23964 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
23965 (org-if-unprotected
23966 (replace-match "\\1 \\3")
23967 (goto-char (match-beginning 0))))
23970 ;; Normalize links: Convert angle and plain links into bracket links
23971 ;; Expand link abbreviations
23972 (goto-char (point-min))
23973 (while (re-search-forward re-plain-link nil t)
23974 (goto-char (1- (match-end 0)))
23975 (org-if-unprotected
23976 (let* ((s (concat (match-string 1) "[[" (match-string 2)
23977 ":" (match-string 3) "]]")))
23978 ;; added 'org-link face to links
23979 (put-text-property 0 (length s) 'face 'org-link s)
23980 (replace-match s t t))))
23981 (goto-char (point-min))
23982 (while (re-search-forward re-angle-link nil t)
23983 (goto-char (1- (match-end 0)))
23984 (org-if-unprotected
23985 (let* ((s (concat (match-string 1) "[[" (match-string 2)
23986 ":" (match-string 3) "]]")))
23987 (put-text-property 0 (length s) 'face 'org-link s)
23988 (replace-match s t t))))
23989 (goto-char (point-min))
23990 (while (re-search-forward org-bracket-link-regexp nil t)
23991 (org-if-unprotected
23992 (let* ((s (concat "[[" (setq xx (save-match-data
23993 (org-link-expand-abbrev (match-string 1))))
23995 (if (match-end 3)
23996 (match-string 2)
23997 (concat "[" xx "]"))
23998 "]")))
23999 (put-text-property 0 (length s) 'face 'org-link s)
24000 (replace-match s t t))))
24002 ;; Find multiline emphasis and put them into single line
24003 (when (plist-get parameters :emph-multiline)
24004 (goto-char (point-min))
24005 (while (re-search-forward org-emph-re nil t)
24006 (if (not (= (char-after (match-beginning 3))
24007 (char-after (match-beginning 4))))
24008 (org-if-unprotected
24009 (subst-char-in-region (match-beginning 0) (match-end 0)
24010 ?\n ?\ t)
24011 (goto-char (1- (match-end 0))))
24012 (goto-char (1+ (match-beginning 0))))))
24014 (setq rtn (buffer-string)))
24015 (kill-buffer " org-mode-tmp")
24016 rtn))
24018 (defun org-export-grab-title-from-buffer ()
24019 "Get a title for the current document, from looking at the buffer."
24020 (let ((inhibit-read-only t))
24021 (save-excursion
24022 (goto-char (point-min))
24023 (let ((end (save-excursion (outline-next-heading) (point))))
24024 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
24025 ;; Mark the line so that it will not be exported as normal text.
24026 (org-unmodified
24027 (add-text-properties (match-beginning 0) (match-end 0)
24028 (list :org-license-to-kill t)))
24029 ;; Return the title string
24030 (org-trim (match-string 0)))))))
24032 (defun org-export-get-title-from-subtree ()
24033 "Return subtree title and exclude it from export."
24034 (let (title (m (mark)))
24035 (save-excursion
24036 (goto-char (region-beginning))
24037 (when (and (org-at-heading-p)
24038 (>= (org-end-of-subtree t t) (region-end)))
24039 ;; This is a subtree, we take the title from the first heading
24040 (goto-char (region-beginning))
24041 (looking-at org-todo-line-regexp)
24042 (setq title (match-string 3))
24043 (org-unmodified
24044 (add-text-properties (point) (1+ (point-at-eol))
24045 (list :org-license-to-kill t)))))
24046 title))
24048 (defun org-solidify-link-text (s &optional alist)
24049 "Take link text and make a safe target out of it."
24050 (save-match-data
24051 (let* ((rtn
24052 (mapconcat
24053 'identity
24054 (org-split-string s "[ \t\r\n]+") "--"))
24055 (a (assoc rtn alist)))
24056 (or (cdr a) rtn))))
24058 (defun org-get-min-level (lines)
24059 "Get the minimum level in LINES."
24060 (let ((re "^\\(\\*+\\) ") l min)
24061 (catch 'exit
24062 (while (setq l (pop lines))
24063 (if (string-match re l)
24064 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24065 1)))
24067 ;; Variable holding the vector with section numbers
24068 (defvar org-section-numbers (make-vector org-level-max 0))
24070 (defun org-init-section-numbers ()
24071 "Initialize the vector for the section numbers."
24072 (let* ((level -1)
24073 (numbers (nreverse (org-split-string "" "\\.")))
24074 (depth (1- (length org-section-numbers)))
24075 (i depth) number-string)
24076 (while (>= i 0)
24077 (if (> i level)
24078 (aset org-section-numbers i 0)
24079 (setq number-string (or (car numbers) "0"))
24080 (if (string-match "\\`[A-Z]\\'" number-string)
24081 (aset org-section-numbers i
24082 (- (string-to-char number-string) ?A -1))
24083 (aset org-section-numbers i (string-to-number number-string)))
24084 (pop numbers))
24085 (setq i (1- i)))))
24087 (defun org-section-number (&optional level)
24088 "Return a string with the current section number.
24089 When LEVEL is non-nil, increase section numbers on that level."
24090 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
24091 (when level
24092 (when (> level -1)
24093 (aset org-section-numbers
24094 level (1+ (aref org-section-numbers level))))
24095 (setq idx (1+ level))
24096 (while (<= idx depth)
24097 (if (not (= idx 1))
24098 (aset org-section-numbers idx 0))
24099 (setq idx (1+ idx))))
24100 (setq idx 0)
24101 (while (<= idx depth)
24102 (setq n (aref org-section-numbers idx))
24103 (setq string (concat string (if (not (string= string "")) "." "")
24104 (int-to-string n)))
24105 (setq idx (1+ idx)))
24106 (save-match-data
24107 (if (string-match "\\`\\([@0]\\.\\)+" string)
24108 (setq string (replace-match "" t nil string)))
24109 (if (string-match "\\(\\.0\\)+\\'" string)
24110 (setq string (replace-match "" t nil string))))
24111 string))
24113 ;;; ASCII export
24115 (defvar org-last-level nil) ; dynamically scoped variable
24116 (defvar org-min-level nil) ; dynamically scoped variable
24117 (defvar org-levels-open nil) ; dynamically scoped parameter
24118 (defvar org-ascii-current-indentation nil) ; For communication
24120 (defun org-export-as-ascii (arg)
24121 "Export the outline as a pretty ASCII file.
24122 If there is an active region, export only the region.
24123 The prefix ARG specifies how many levels of the outline should become
24124 underlined headlines. The default is 3."
24125 (interactive "P")
24126 (setq-default org-todo-line-regexp org-todo-line-regexp)
24127 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24128 (org-infile-export-plist)))
24129 (region-p (org-region-active-p))
24130 (subtree-p
24131 (when region-p
24132 (save-excursion
24133 (goto-char (region-beginning))
24134 (and (org-at-heading-p)
24135 (>= (org-end-of-subtree t t) (region-end))))))
24136 (custom-times org-display-custom-times)
24137 (org-ascii-current-indentation '(0 . 0))
24138 (level 0) line txt
24139 (umax nil)
24140 (umax-toc nil)
24141 (case-fold-search nil)
24142 (filename (concat (file-name-as-directory
24143 (org-export-directory :ascii opt-plist))
24144 (file-name-sans-extension
24145 (or (and subtree-p
24146 (org-entry-get (region-beginning)
24147 "EXPORT_FILE_NAME" t))
24148 (file-name-nondirectory buffer-file-name)))
24149 ".txt"))
24150 (filename (if (equal (file-truename filename)
24151 (file-truename buffer-file-name))
24152 (concat filename ".txt")
24153 filename))
24154 (buffer (find-file-noselect filename))
24155 (org-levels-open (make-vector org-level-max nil))
24156 (odd org-odd-levels-only)
24157 (date (plist-get opt-plist :date))
24158 (author (plist-get opt-plist :author))
24159 (title (or (and subtree-p (org-export-get-title-from-subtree))
24160 (plist-get opt-plist :title)
24161 (and (not
24162 (plist-get opt-plist :skip-before-1st-heading))
24163 (org-export-grab-title-from-buffer))
24164 (file-name-sans-extension
24165 (file-name-nondirectory buffer-file-name))))
24166 (email (plist-get opt-plist :email))
24167 (language (plist-get opt-plist :language))
24168 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24169 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
24170 (todo nil)
24171 (lang-words nil)
24172 (region
24173 (buffer-substring
24174 (if (org-region-active-p) (region-beginning) (point-min))
24175 (if (org-region-active-p) (region-end) (point-max))))
24176 (lines (org-split-string
24177 (org-cleaned-string-for-export
24178 region
24179 :for-ascii t
24180 :skip-before-1st-heading
24181 (plist-get opt-plist :skip-before-1st-heading)
24182 :drawers (plist-get opt-plist :drawers)
24183 :verbatim-multiline t
24184 :archived-trees
24185 (plist-get opt-plist :archived-trees)
24186 :add-text (plist-get opt-plist :text))
24187 "\n"))
24188 thetoc have-headings first-heading-pos
24189 table-open table-buffer)
24191 (let ((inhibit-read-only t))
24192 (org-unmodified
24193 (remove-text-properties (point-min) (point-max)
24194 '(:org-license-to-kill t))))
24196 (setq org-min-level (org-get-min-level lines))
24197 (setq org-last-level org-min-level)
24198 (org-init-section-numbers)
24200 (find-file-noselect filename)
24202 (setq lang-words (or (assoc language org-export-language-setup)
24203 (assoc "en" org-export-language-setup)))
24204 (switch-to-buffer-other-window buffer)
24205 (erase-buffer)
24206 (fundamental-mode)
24207 ;; create local variables for all options, to make sure all called
24208 ;; functions get the correct information
24209 (mapc (lambda (x)
24210 (set (make-local-variable (cdr x))
24211 (plist-get opt-plist (car x))))
24212 org-export-plist-vars)
24213 (org-set-local 'org-odd-levels-only odd)
24214 (setq umax (if arg (prefix-numeric-value arg)
24215 org-export-headline-levels))
24216 (setq umax-toc (if (integerp org-export-with-toc)
24217 (min org-export-with-toc umax)
24218 umax))
24220 ;; File header
24221 (if title (org-insert-centered title ?=))
24222 (insert "\n")
24223 (if (and (or author email)
24224 org-export-author-info)
24225 (insert (concat (nth 1 lang-words) ": " (or author "")
24226 (if email (concat " <" email ">") "")
24227 "\n")))
24229 (cond
24230 ((and date (string-match "%" date))
24231 (setq date (format-time-string date (current-time))))
24232 (date)
24233 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24235 (if (and date org-export-time-stamp-file)
24236 (insert (concat (nth 2 lang-words) ": " date"\n")))
24238 (insert "\n\n")
24240 (if org-export-with-toc
24241 (progn
24242 (push (concat (nth 3 lang-words) "\n") thetoc)
24243 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
24244 (mapc '(lambda (line)
24245 (if (string-match org-todo-line-regexp
24246 line)
24247 ;; This is a headline
24248 (progn
24249 (setq have-headings t)
24250 (setq level (- (match-end 1) (match-beginning 1))
24251 level (org-tr-level level)
24252 txt (match-string 3 line)
24253 todo
24254 (or (and org-export-mark-todo-in-toc
24255 (match-beginning 2)
24256 (not (member (match-string 2 line)
24257 org-done-keywords)))
24258 ; TODO, not DONE
24259 (and org-export-mark-todo-in-toc
24260 (= level umax-toc)
24261 (org-search-todo-below
24262 line lines level))))
24263 (setq txt (org-html-expand-for-ascii txt))
24265 (while (string-match org-bracket-link-regexp txt)
24266 (setq txt
24267 (replace-match
24268 (match-string (if (match-end 2) 3 1) txt)
24269 t t txt)))
24271 (if (and (memq org-export-with-tags '(not-in-toc nil))
24272 (string-match
24273 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
24274 txt))
24275 (setq txt (replace-match "" t t txt)))
24276 (if (string-match quote-re0 txt)
24277 (setq txt (replace-match "" t t txt)))
24279 (if org-export-with-section-numbers
24280 (setq txt (concat (org-section-number level)
24281 " " txt)))
24282 (if (<= level umax-toc)
24283 (progn
24284 (push
24285 (concat
24286 (make-string
24287 (* (max 0 (- level org-min-level)) 4) ?\ )
24288 (format (if todo "%s (*)\n" "%s\n") txt))
24289 thetoc)
24290 (setq org-last-level level))
24291 ))))
24292 lines)
24293 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24295 (org-init-section-numbers)
24296 (while (setq line (pop lines))
24297 ;; Remove the quoted HTML tags.
24298 (setq line (org-html-expand-for-ascii line))
24299 ;; Remove targets
24300 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
24301 (setq line (replace-match "" t t line)))
24302 ;; Replace internal links
24303 (while (string-match org-bracket-link-regexp line)
24304 (setq line (replace-match
24305 (if (match-end 3) "[\\3]" "[\\1]")
24306 t nil line)))
24307 (when custom-times
24308 (setq line (org-translate-time line)))
24309 (cond
24310 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24311 ;; a Headline
24312 (setq first-heading-pos (or first-heading-pos (point)))
24313 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24314 txt (match-string 2 line))
24315 (org-ascii-level-start level txt umax lines))
24317 ((and org-export-with-tables
24318 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24319 (if (not table-open)
24320 ;; New table starts
24321 (setq table-open t table-buffer nil))
24322 ;; Accumulate lines
24323 (setq table-buffer (cons line table-buffer))
24324 (when (or (not lines)
24325 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24326 (car lines))))
24327 (setq table-open nil
24328 table-buffer (nreverse table-buffer))
24329 (insert (mapconcat
24330 (lambda (x)
24331 (org-fix-indentation x org-ascii-current-indentation))
24332 (org-format-table-ascii table-buffer)
24333 "\n") "\n")))
24335 (setq line (org-fix-indentation line org-ascii-current-indentation))
24336 (if (and org-export-with-fixed-width
24337 (string-match "^\\([ \t]*\\)\\(:\\)" line))
24338 (setq line (replace-match "\\1" nil nil line)))
24339 (insert line "\n"))))
24341 (normal-mode)
24343 ;; insert the table of contents
24344 (when thetoc
24345 (goto-char (point-min))
24346 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
24347 (progn
24348 (goto-char (match-beginning 0))
24349 (replace-match ""))
24350 (goto-char first-heading-pos))
24351 (mapc 'insert thetoc)
24352 (or (looking-at "[ \t]*\n[ \t]*\n")
24353 (insert "\n\n")))
24355 ;; Convert whitespace place holders
24356 (goto-char (point-min))
24357 (let (beg end)
24358 (while (setq beg (next-single-property-change (point) 'org-whitespace))
24359 (setq end (next-single-property-change beg 'org-whitespace))
24360 (goto-char beg)
24361 (delete-region beg end)
24362 (insert (make-string (- end beg) ?\ ))))
24364 (save-buffer)
24365 ;; remove display and invisible chars
24366 (let (beg end)
24367 (goto-char (point-min))
24368 (while (setq beg (next-single-property-change (point) 'display))
24369 (setq end (next-single-property-change beg 'display))
24370 (delete-region beg end)
24371 (goto-char beg)
24372 (insert "=>"))
24373 (goto-char (point-min))
24374 (while (setq beg (next-single-property-change (point) 'org-cwidth))
24375 (setq end (next-single-property-change beg 'org-cwidth))
24376 (delete-region beg end)
24377 (goto-char beg)))
24378 (goto-char (point-min))))
24380 (defun org-export-ascii-clean-string ()
24381 "Do extra work for ASCII export"
24382 (goto-char (point-min))
24383 (while (re-search-forward org-verbatim-re nil t)
24384 (goto-char (match-end 2))
24385 (backward-delete-char 1) (insert "'")
24386 (goto-char (match-beginning 2))
24387 (delete-char 1) (insert "`")
24388 (goto-char (match-end 2))))
24390 (defun org-search-todo-below (line lines level)
24391 "Search the subtree below LINE for any TODO entries."
24392 (let ((rest (cdr (memq line lines)))
24393 (re org-todo-line-regexp)
24394 line lv todo)
24395 (catch 'exit
24396 (while (setq line (pop rest))
24397 (if (string-match re line)
24398 (progn
24399 (setq lv (- (match-end 1) (match-beginning 1))
24400 todo (and (match-beginning 2)
24401 (not (member (match-string 2 line)
24402 org-done-keywords))))
24403 ; TODO, not DONE
24404 (if (<= lv level) (throw 'exit nil))
24405 (if todo (throw 'exit t))))))))
24407 (defun org-html-expand-for-ascii (line)
24408 "Handle quoted HTML for ASCII export."
24409 (if org-export-html-expand
24410 (while (string-match "@<[^<>\n]*>" line)
24411 ;; We just remove the tags for now.
24412 (setq line (replace-match "" nil nil line))))
24413 line)
24415 (defun org-insert-centered (s &optional underline)
24416 "Insert the string S centered and underline it with character UNDERLINE."
24417 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
24418 (insert (make-string ind ?\ ) s "\n")
24419 (if underline
24420 (insert (make-string ind ?\ )
24421 (make-string (string-width s) underline)
24422 "\n"))))
24424 (defun org-ascii-level-start (level title umax &optional lines)
24425 "Insert a new level in ASCII export."
24426 (let (char (n (- level umax 1)) (ind 0))
24427 (if (> level umax)
24428 (progn
24429 (insert (make-string (* 2 n) ?\ )
24430 (char-to-string (nth (% n (length org-export-ascii-bullets))
24431 org-export-ascii-bullets))
24432 " " title "\n")
24433 ;; find the indentation of the next non-empty line
24434 (catch 'stop
24435 (while lines
24436 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
24437 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
24438 (throw 'stop (setq ind (org-get-indentation (car lines)))))
24439 (pop lines)))
24440 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
24441 (if (or (not (equal (char-before) ?\n))
24442 (not (equal (char-before (1- (point))) ?\n)))
24443 (insert "\n"))
24444 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
24445 (unless org-export-with-tags
24446 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
24447 (setq title (replace-match "" t t title))))
24448 (if org-export-with-section-numbers
24449 (setq title (concat (org-section-number level) " " title)))
24450 (insert title "\n" (make-string (string-width title) char) "\n")
24451 (setq org-ascii-current-indentation '(0 . 0)))))
24453 (defun org-export-visible (type arg)
24454 "Create a copy of the visible part of the current buffer, and export it.
24455 The copy is created in a temporary buffer and removed after use.
24456 TYPE is the final key (as a string) that also select the export command in
24457 the `C-c C-e' export dispatcher.
24458 As a special case, if the you type SPC at the prompt, the temporary
24459 org-mode file will not be removed but presented to you so that you can
24460 continue to use it. The prefix arg ARG is passed through to the exporting
24461 command."
24462 (interactive
24463 (list (progn
24464 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
24465 (read-char-exclusive))
24466 current-prefix-arg))
24467 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
24468 (error "Invalid export key"))
24469 (let* ((binding (cdr (assoc type
24470 '((?a . org-export-as-ascii)
24471 (?\C-a . org-export-as-ascii)
24472 (?b . org-export-as-html-and-open)
24473 (?\C-b . org-export-as-html-and-open)
24474 (?h . org-export-as-html)
24475 (?H . org-export-as-html-to-buffer)
24476 (?R . org-export-region-as-html)
24477 (?x . org-export-as-xoxo)))))
24478 (keepp (equal type ?\ ))
24479 (file buffer-file-name)
24480 (buffer (get-buffer-create "*Org Export Visible*"))
24481 s e)
24482 ;; Need to hack the drawers here.
24483 (save-excursion
24484 (goto-char (point-min))
24485 (while (re-search-forward org-drawer-regexp nil t)
24486 (goto-char (match-beginning 1))
24487 (or (org-invisible-p) (org-flag-drawer nil))))
24488 (with-current-buffer buffer (erase-buffer))
24489 (save-excursion
24490 (setq s (goto-char (point-min)))
24491 (while (not (= (point) (point-max)))
24492 (goto-char (org-find-invisible))
24493 (append-to-buffer buffer s (point))
24494 (setq s (goto-char (org-find-visible))))
24495 (org-cycle-hide-drawers 'all)
24496 (goto-char (point-min))
24497 (unless keepp
24498 ;; Copy all comment lines to the end, to make sure #+ settings are
24499 ;; still available for the second export step. Kind of a hack, but
24500 ;; does do the trick.
24501 (if (looking-at "#[^\r\n]*")
24502 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
24503 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
24504 (append-to-buffer buffer (1+ (match-beginning 0))
24505 (min (point-max) (1+ (match-end 0))))))
24506 (set-buffer buffer)
24507 (let ((buffer-file-name file)
24508 (org-inhibit-startup t))
24509 (org-mode)
24510 (show-all)
24511 (unless keepp (funcall binding arg))))
24512 (if (not keepp)
24513 (kill-buffer buffer)
24514 (switch-to-buffer-other-window buffer)
24515 (goto-char (point-min)))))
24517 (defun org-find-visible ()
24518 (let ((s (point)))
24519 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24520 (get-char-property s 'invisible)))
24522 (defun org-find-invisible ()
24523 (let ((s (point)))
24524 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24525 (not (get-char-property s 'invisible))))
24528 ;;; HTML export
24530 (defun org-get-current-options ()
24531 "Return a string with current options as keyword options.
24532 Does include HTML export options as well as TODO and CATEGORY stuff."
24533 (format
24534 "#+TITLE: %s
24535 #+AUTHOR: %s
24536 #+EMAIL: %s
24537 #+LANGUAGE: %s
24538 #+TEXT: Some descriptive text to be emitted. Several lines OK.
24539 #+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
24540 #+CATEGORY: %s
24541 #+SEQ_TODO: %s
24542 #+TYP_TODO: %s
24543 #+PRIORITIES: %c %c %c
24544 #+DRAWERS: %s
24545 #+STARTUP: %s %s %s %s %s
24546 #+TAGS: %s
24547 #+ARCHIVE: %s
24548 #+LINK: %s
24550 (buffer-name) (user-full-name) user-mail-address org-export-default-language
24551 org-export-headline-levels
24552 org-export-with-section-numbers
24553 org-export-with-toc
24554 org-export-preserve-breaks
24555 org-export-html-expand
24556 org-export-with-fixed-width
24557 org-export-with-tables
24558 org-export-with-sub-superscripts
24559 org-export-with-special-strings
24560 org-export-with-footnotes
24561 org-export-with-emphasize
24562 org-export-with-TeX-macros
24563 org-export-with-LaTeX-fragments
24564 org-export-skip-text-before-1st-heading
24565 org-export-with-drawers
24566 org-export-with-tags
24567 (file-name-nondirectory buffer-file-name)
24568 "TODO FEEDBACK VERIFY DONE"
24569 "Me Jason Marie DONE"
24570 org-highest-priority org-lowest-priority org-default-priority
24571 (mapconcat 'identity org-drawers " ")
24572 (cdr (assoc org-startup-folded
24573 '((nil . "showall") (t . "overview") (content . "content"))))
24574 (if org-odd-levels-only "odd" "oddeven")
24575 (if org-hide-leading-stars "hidestars" "showstars")
24576 (if org-startup-align-all-tables "align" "noalign")
24577 (cond ((eq t org-log-done) "logdone")
24578 ((not org-log-done) "nologging")
24579 ((listp org-log-done)
24580 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
24581 org-log-done " ")))
24582 (or (mapconcat (lambda (x)
24583 (cond
24584 ((equal '(:startgroup) x) "{")
24585 ((equal '(:endgroup) x) "}")
24586 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
24587 (t (car x))))
24588 (or org-tag-alist (org-get-buffer-tags)) " ") "")
24589 org-archive-location
24590 "org file:~/org/%s.org"
24593 (defun org-insert-export-options-template ()
24594 "Insert into the buffer a template with information for exporting."
24595 (interactive)
24596 (if (not (bolp)) (newline))
24597 (let ((s (org-get-current-options)))
24598 (and (string-match "#\\+CATEGORY" s)
24599 (setq s (substring s 0 (match-beginning 0))))
24600 (insert s)))
24602 (defun org-toggle-fixed-width-section (arg)
24603 "Toggle the fixed-width export.
24604 If there is no active region, the QUOTE keyword at the current headline is
24605 inserted or removed. When present, it causes the text between this headline
24606 and the next to be exported as fixed-width text, and unmodified.
24607 If there is an active region, this command adds or removes a colon as the
24608 first character of this line. If the first character of a line is a colon,
24609 this line is also exported in fixed-width font."
24610 (interactive "P")
24611 (let* ((cc 0)
24612 (regionp (org-region-active-p))
24613 (beg (if regionp (region-beginning) (point)))
24614 (end (if regionp (region-end)))
24615 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
24616 (case-fold-search nil)
24617 (re "[ \t]*\\(:\\)")
24618 off)
24619 (if regionp
24620 (save-excursion
24621 (goto-char beg)
24622 (setq cc (current-column))
24623 (beginning-of-line 1)
24624 (setq off (looking-at re))
24625 (while (> nlines 0)
24626 (setq nlines (1- nlines))
24627 (beginning-of-line 1)
24628 (cond
24629 (arg
24630 (move-to-column cc t)
24631 (insert ":\n")
24632 (forward-line -1))
24633 ((and off (looking-at re))
24634 (replace-match "" t t nil 1))
24635 ((not off) (move-to-column cc t) (insert ":")))
24636 (forward-line 1)))
24637 (save-excursion
24638 (org-back-to-heading)
24639 (if (looking-at (concat outline-regexp
24640 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
24641 (replace-match "" t t nil 1)
24642 (if (looking-at outline-regexp)
24643 (progn
24644 (goto-char (match-end 0))
24645 (insert org-quote-string " "))))))))
24647 (defun org-export-as-html-and-open (arg)
24648 "Export the outline as HTML and immediately open it with a browser.
24649 If there is an active region, export only the region.
24650 The prefix ARG specifies how many levels of the outline should become
24651 headlines. The default is 3. Lower levels will become bulleted lists."
24652 (interactive "P")
24653 (org-export-as-html arg 'hidden)
24654 (org-open-file buffer-file-name))
24656 (defun org-export-as-html-batch ()
24657 "Call `org-export-as-html', may be used in batch processing as
24658 emacs --batch
24659 --load=$HOME/lib/emacs/org.el
24660 --eval \"(setq org-export-headline-levels 2)\"
24661 --visit=MyFile --funcall org-export-as-html-batch"
24662 (org-export-as-html org-export-headline-levels 'hidden))
24664 (defun org-export-as-html-to-buffer (arg)
24665 "Call `org-exort-as-html` with output to a temporary buffer.
24666 No file is created. The prefix ARG is passed through to `org-export-as-html'."
24667 (interactive "P")
24668 (org-export-as-html arg nil nil "*Org HTML Export*")
24669 (switch-to-buffer-other-window "*Org HTML Export*"))
24671 (defun org-replace-region-by-html (beg end)
24672 "Assume the current region has org-mode syntax, and convert it to HTML.
24673 This can be used in any buffer. For example, you could write an
24674 itemized list in org-mode syntax in an HTML buffer and then use this
24675 command to convert it."
24676 (interactive "r")
24677 (let (reg html buf pop-up-frames)
24678 (save-window-excursion
24679 (if (org-mode-p)
24680 (setq html (org-export-region-as-html
24681 beg end t 'string))
24682 (setq reg (buffer-substring beg end)
24683 buf (get-buffer-create "*Org tmp*"))
24684 (with-current-buffer buf
24685 (erase-buffer)
24686 (insert reg)
24687 (org-mode)
24688 (setq html (org-export-region-as-html
24689 (point-min) (point-max) t 'string)))
24690 (kill-buffer buf)))
24691 (delete-region beg end)
24692 (insert html)))
24694 (defun org-export-region-as-html (beg end &optional body-only buffer)
24695 "Convert region from BEG to END in org-mode buffer to HTML.
24696 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
24697 contents, and only produce the region of converted text, useful for
24698 cut-and-paste operations.
24699 If BUFFER is a buffer or a string, use/create that buffer as a target
24700 of the converted HTML. If BUFFER is the symbol `string', return the
24701 produced HTML as a string and leave not buffer behind. For example,
24702 a Lisp program could call this function in the following way:
24704 (setq html (org-export-region-as-html beg end t 'string))
24706 When called interactively, the output buffer is selected, and shown
24707 in a window. A non-interactive call will only retunr the buffer."
24708 (interactive "r\nP")
24709 (when (interactive-p)
24710 (setq buffer "*Org HTML Export*"))
24711 (let ((transient-mark-mode t) (zmacs-regions t)
24712 rtn)
24713 (goto-char end)
24714 (set-mark (point)) ;; to activate the region
24715 (goto-char beg)
24716 (setq rtn (org-export-as-html
24717 nil nil nil
24718 buffer body-only))
24719 (if (fboundp 'deactivate-mark) (deactivate-mark))
24720 (if (and (interactive-p) (bufferp rtn))
24721 (switch-to-buffer-other-window rtn)
24722 rtn)))
24724 (defvar html-table-tag nil) ; dynamically scoped into this.
24725 (defun org-export-as-html (arg &optional hidden ext-plist
24726 to-buffer body-only)
24727 "Export the outline as a pretty HTML file.
24728 If there is an active region, export only the region. The prefix
24729 ARG specifies how many levels of the outline should become
24730 headlines. The default is 3. Lower levels will become bulleted
24731 lists. When HIDDEN is non-nil, don't display the HTML buffer.
24732 EXT-PLIST is a property list with external parameters overriding
24733 org-mode's default settings, but still inferior to file-local
24734 settings. When TO-BUFFER is non-nil, create a buffer with that
24735 name and export to that buffer. If TO-BUFFER is the symbol `string',
24736 don't leave any buffer behind but just return the resulting HTML as
24737 a string. When BODY-ONLY is set, don't produce the file header and footer,
24738 simply return the content of <body>...</body>, without even
24739 the body tags themselves."
24740 (interactive "P")
24742 ;; Make sure we have a file name when we need it.
24743 (when (and (not (or to-buffer body-only))
24744 (not buffer-file-name))
24745 (if (buffer-base-buffer)
24746 (org-set-local 'buffer-file-name
24747 (with-current-buffer (buffer-base-buffer)
24748 buffer-file-name))
24749 (error "Need a file name to be able to export.")))
24751 (message "Exporting...")
24752 (setq-default org-todo-line-regexp org-todo-line-regexp)
24753 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
24754 (setq-default org-done-keywords org-done-keywords)
24755 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
24756 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24757 ext-plist
24758 (org-infile-export-plist)))
24760 (style (plist-get opt-plist :style))
24761 (link-validate (plist-get opt-plist :link-validation-function))
24762 valid thetoc have-headings first-heading-pos
24763 (odd org-odd-levels-only)
24764 (region-p (org-region-active-p))
24765 (subtree-p
24766 (when region-p
24767 (save-excursion
24768 (goto-char (region-beginning))
24769 (and (org-at-heading-p)
24770 (>= (org-end-of-subtree t t) (region-end))))))
24771 ;; The following two are dynamically scoped into other
24772 ;; routines below.
24773 (org-current-export-dir (org-export-directory :html opt-plist))
24774 (org-current-export-file buffer-file-name)
24775 (level 0) (line "") (origline "") txt todo
24776 (umax nil)
24777 (umax-toc nil)
24778 (filename (if to-buffer nil
24779 (expand-file-name
24780 (concat
24781 (file-name-sans-extension
24782 (or (and subtree-p
24783 (org-entry-get (region-beginning)
24784 "EXPORT_FILE_NAME" t))
24785 (file-name-nondirectory buffer-file-name)))
24786 "." org-export-html-extension)
24787 (file-name-as-directory
24788 (org-export-directory :html opt-plist)))))
24789 (current-dir (if buffer-file-name
24790 (file-name-directory buffer-file-name)
24791 default-directory))
24792 (buffer (if to-buffer
24793 (cond
24794 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
24795 (t (get-buffer-create to-buffer)))
24796 (find-file-noselect filename)))
24797 (org-levels-open (make-vector org-level-max nil))
24798 (date (plist-get opt-plist :date))
24799 (author (plist-get opt-plist :author))
24800 (title (or (and subtree-p (org-export-get-title-from-subtree))
24801 (plist-get opt-plist :title)
24802 (and (not
24803 (plist-get opt-plist :skip-before-1st-heading))
24804 (org-export-grab-title-from-buffer))
24805 (and buffer-file-name
24806 (file-name-sans-extension
24807 (file-name-nondirectory buffer-file-name)))
24808 "UNTITLED"))
24809 (html-table-tag (plist-get opt-plist :html-table-tag))
24810 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24811 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
24812 (inquote nil)
24813 (infixed nil)
24814 (in-local-list nil)
24815 (local-list-num nil)
24816 (local-list-indent nil)
24817 (llt org-plain-list-ordered-item-terminator)
24818 (email (plist-get opt-plist :email))
24819 (language (plist-get opt-plist :language))
24820 (lang-words nil)
24821 (target-alist nil) tg
24822 (head-count 0) cnt
24823 (start 0)
24824 (coding-system (and (boundp 'buffer-file-coding-system)
24825 buffer-file-coding-system))
24826 (coding-system-for-write (or org-export-html-coding-system
24827 coding-system))
24828 (save-buffer-coding-system (or org-export-html-coding-system
24829 coding-system))
24830 (charset (and coding-system-for-write
24831 (fboundp 'coding-system-get)
24832 (coding-system-get coding-system-for-write
24833 'mime-charset)))
24834 (region
24835 (buffer-substring
24836 (if region-p (region-beginning) (point-min))
24837 (if region-p (region-end) (point-max))))
24838 (lines
24839 (org-split-string
24840 (org-cleaned-string-for-export
24841 region
24842 :emph-multiline t
24843 :for-html t
24844 :skip-before-1st-heading
24845 (plist-get opt-plist :skip-before-1st-heading)
24846 :drawers (plist-get opt-plist :drawers)
24847 :archived-trees
24848 (plist-get opt-plist :archived-trees)
24849 :add-text
24850 (plist-get opt-plist :text)
24851 :LaTeX-fragments
24852 (plist-get opt-plist :LaTeX-fragments))
24853 "[\r\n]"))
24854 table-open type
24855 table-buffer table-orig-buffer
24856 ind start-is-num starter didclose
24857 rpl path desc descp desc1 desc2 link
24860 (let ((inhibit-read-only t))
24861 (org-unmodified
24862 (remove-text-properties (point-min) (point-max)
24863 '(:org-license-to-kill t))))
24865 (message "Exporting...")
24867 (setq org-min-level (org-get-min-level lines))
24868 (setq org-last-level org-min-level)
24869 (org-init-section-numbers)
24871 (cond
24872 ((and date (string-match "%" date))
24873 (setq date (format-time-string date (current-time))))
24874 (date)
24875 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24877 ;; Get the language-dependent settings
24878 (setq lang-words (or (assoc language org-export-language-setup)
24879 (assoc "en" org-export-language-setup)))
24881 ;; Switch to the output buffer
24882 (set-buffer buffer)
24883 (let ((inhibit-read-only t)) (erase-buffer))
24884 (fundamental-mode)
24886 (and (fboundp 'set-buffer-file-coding-system)
24887 (set-buffer-file-coding-system coding-system-for-write))
24889 (let ((case-fold-search nil)
24890 (org-odd-levels-only odd))
24891 ;; create local variables for all options, to make sure all called
24892 ;; functions get the correct information
24893 (mapc (lambda (x)
24894 (set (make-local-variable (cdr x))
24895 (plist-get opt-plist (car x))))
24896 org-export-plist-vars)
24897 (setq umax (if arg (prefix-numeric-value arg)
24898 org-export-headline-levels))
24899 (setq umax-toc (if (integerp org-export-with-toc)
24900 (min org-export-with-toc umax)
24901 umax))
24902 (unless body-only
24903 ;; File header
24904 (insert (format
24905 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
24906 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
24907 <html xmlns=\"http://www.w3.org/1999/xhtml\"
24908 lang=\"%s\" xml:lang=\"%s\">
24909 <head>
24910 <title>%s</title>
24911 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
24912 <meta name=\"generator\" content=\"Org-mode\"/>
24913 <meta name=\"generated\" content=\"%s\"/>
24914 <meta name=\"author\" content=\"%s\"/>
24916 </head><body>
24918 language language (org-html-expand title)
24919 (or charset "iso-8859-1") date author style))
24921 (insert (or (plist-get opt-plist :preamble) ""))
24923 (when (plist-get opt-plist :auto-preamble)
24924 (if title (insert (format org-export-html-title-format
24925 (org-html-expand title))))))
24927 (if (and org-export-with-toc (not body-only))
24928 (progn
24929 (push (format "<h%d>%s</h%d>\n"
24930 org-export-html-toplevel-hlevel
24931 (nth 3 lang-words)
24932 org-export-html-toplevel-hlevel)
24933 thetoc)
24934 (push "<ul>\n<li>" thetoc)
24935 (setq lines
24936 (mapcar '(lambda (line)
24937 (if (string-match org-todo-line-regexp line)
24938 ;; This is a headline
24939 (progn
24940 (setq have-headings t)
24941 (setq level (- (match-end 1) (match-beginning 1))
24942 level (org-tr-level level)
24943 txt (save-match-data
24944 (org-html-expand
24945 (org-export-cleanup-toc-line
24946 (match-string 3 line))))
24947 todo
24948 (or (and org-export-mark-todo-in-toc
24949 (match-beginning 2)
24950 (not (member (match-string 2 line)
24951 org-done-keywords)))
24952 ; TODO, not DONE
24953 (and org-export-mark-todo-in-toc
24954 (= level umax-toc)
24955 (org-search-todo-below
24956 line lines level))))
24957 (if (string-match
24958 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
24959 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
24960 (if (string-match quote-re0 txt)
24961 (setq txt (replace-match "" t t txt)))
24962 (if org-export-with-section-numbers
24963 (setq txt (concat (org-section-number level)
24964 " " txt)))
24965 (if (<= level (max umax umax-toc))
24966 (setq head-count (+ head-count 1)))
24967 (if (<= level umax-toc)
24968 (progn
24969 (if (> level org-last-level)
24970 (progn
24971 (setq cnt (- level org-last-level))
24972 (while (>= (setq cnt (1- cnt)) 0)
24973 (push "\n<ul>\n<li>" thetoc))
24974 (push "\n" thetoc)))
24975 (if (< level org-last-level)
24976 (progn
24977 (setq cnt (- org-last-level level))
24978 (while (>= (setq cnt (1- cnt)) 0)
24979 (push "</li>\n</ul>" thetoc))
24980 (push "\n" thetoc)))
24981 ;; Check for targets
24982 (while (string-match org-target-regexp line)
24983 (setq tg (match-string 1 line)
24984 line (replace-match
24985 (concat "@<span class=\"target\">" tg "@</span> ")
24986 t t line))
24987 (push (cons (org-solidify-link-text tg)
24988 (format "sec-%d" head-count))
24989 target-alist))
24990 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
24991 (setq txt (replace-match "" t t txt)))
24992 (push
24993 (format
24994 (if todo
24995 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
24996 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
24997 head-count txt) thetoc)
24999 (setq org-last-level level))
25001 line)
25002 lines))
25003 (while (> org-last-level (1- org-min-level))
25004 (setq org-last-level (1- org-last-level))
25005 (push "</li>\n</ul>\n" thetoc))
25006 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25008 (setq head-count 0)
25009 (org-init-section-numbers)
25011 (while (setq line (pop lines) origline line)
25012 (catch 'nextline
25014 ;; end of quote section?
25015 (when (and inquote (string-match "^\\*+ " line))
25016 (insert "</pre>\n")
25017 (setq inquote nil))
25018 ;; inside a quote section?
25019 (when inquote
25020 (insert (org-html-protect line) "\n")
25021 (throw 'nextline nil))
25023 ;; verbatim lines
25024 (when (and org-export-with-fixed-width
25025 (string-match "^[ \t]*:\\(.*\\)" line))
25026 (when (not infixed)
25027 (setq infixed t)
25028 (insert "<pre>\n"))
25029 (insert (org-html-protect (match-string 1 line)) "\n")
25030 (when (and lines
25031 (not (string-match "^[ \t]*\\(:.*\\)"
25032 (car lines))))
25033 (setq infixed nil)
25034 (insert "</pre>\n"))
25035 (throw 'nextline nil))
25037 ;; Protected HTML
25038 (when (get-text-property 0 'org-protected line)
25039 (let (par)
25040 (when (re-search-backward
25041 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
25042 (setq par (match-string 1))
25043 (replace-match "\\2\n"))
25044 (insert line "\n")
25045 (while (and lines
25046 (or (= (length (car lines)) 0)
25047 (get-text-property 0 'org-protected (car lines))))
25048 (insert (pop lines) "\n"))
25049 (and par (insert "<p>\n")))
25050 (throw 'nextline nil))
25052 ;; Horizontal line
25053 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
25054 (insert "\n<hr/>\n")
25055 (throw 'nextline nil))
25057 ;; make targets to anchors
25058 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
25059 (cond
25060 ((match-end 2)
25061 (setq line (replace-match
25062 (concat "@<a name=\""
25063 (org-solidify-link-text (match-string 1 line))
25064 "\">\\nbsp@</a>")
25065 t t line)))
25066 ((and org-export-with-toc (equal (string-to-char line) ?*))
25067 (setq line (replace-match
25068 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
25069 ; (concat "@<i>" (match-string 1 line) "@</i> ")
25070 t t line)))
25072 (setq line (replace-match
25073 (concat "@<a name=\""
25074 (org-solidify-link-text (match-string 1 line))
25075 "\" class=\"target\">" (match-string 1 line) "@</a> ")
25076 t t line)))))
25078 (setq line (org-html-handle-time-stamps line))
25080 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
25081 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
25082 ;; Also handle sub_superscripts and checkboxes
25083 (or (string-match org-table-hline-regexp line)
25084 (setq line (org-html-expand line)))
25086 ;; Format the links
25087 (setq start 0)
25088 (while (string-match org-bracket-link-analytic-regexp line start)
25089 (setq start (match-beginning 0))
25090 (setq type (if (match-end 2) (match-string 2 line) "internal"))
25091 (setq path (match-string 3 line))
25092 (setq desc1 (if (match-end 5) (match-string 5 line))
25093 desc2 (if (match-end 2) (concat type ":" path) path)
25094 descp (and desc1 (not (equal desc1 desc2)))
25095 desc (or desc1 desc2))
25096 ;; Make an image out of the description if that is so wanted
25097 (when (and descp (org-file-image-p desc))
25098 (save-match-data
25099 (if (string-match "^file:" desc)
25100 (setq desc (substring desc (match-end 0)))))
25101 (setq desc (concat "<img src=\"" desc "\"/>")))
25102 ;; FIXME: do we need to unescape here somewhere?
25103 (cond
25104 ((equal type "internal")
25105 (setq rpl
25106 (concat
25107 "<a href=\"#"
25108 (org-solidify-link-text
25109 (save-match-data (org-link-unescape path)) target-alist)
25110 "\">" desc "</a>")))
25111 ((member type '("http" "https"))
25112 ;; standard URL, just check if we need to inline an image
25113 (if (and (or (eq t org-export-html-inline-images)
25114 (and org-export-html-inline-images (not descp)))
25115 (org-file-image-p path))
25116 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
25117 (setq link (concat type ":" path))
25118 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
25119 ((member type '("ftp" "mailto" "news"))
25120 ;; standard URL
25121 (setq link (concat type ":" path))
25122 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
25123 ((string= type "file")
25124 ;; FILE link
25125 (let* ((filename path)
25126 (abs-p (file-name-absolute-p filename))
25127 thefile file-is-image-p search)
25128 (save-match-data
25129 (if (string-match "::\\(.*\\)" filename)
25130 (setq search (match-string 1 filename)
25131 filename (replace-match "" t nil filename)))
25132 (setq valid
25133 (if (functionp link-validate)
25134 (funcall link-validate filename current-dir)
25136 (setq file-is-image-p (org-file-image-p filename))
25137 (setq thefile (if abs-p (expand-file-name filename) filename))
25138 (when (and org-export-html-link-org-files-as-html
25139 (string-match "\\.org$" thefile))
25140 (setq thefile (concat (substring thefile 0
25141 (match-beginning 0))
25142 "." org-export-html-extension))
25143 (if (and search
25144 ;; make sure this is can be used as target search
25145 (not (string-match "^[0-9]*$" search))
25146 (not (string-match "^\\*" search))
25147 (not (string-match "^/.*/$" search)))
25148 (setq thefile (concat thefile "#"
25149 (org-solidify-link-text
25150 (org-link-unescape search)))))
25151 (when (string-match "^file:" desc)
25152 (setq desc (replace-match "" t t desc))
25153 (if (string-match "\\.org$" desc)
25154 (setq desc (replace-match "" t t desc))))))
25155 (setq rpl (if (and file-is-image-p
25156 (or (eq t org-export-html-inline-images)
25157 (and org-export-html-inline-images
25158 (not descp))))
25159 (concat "<img src=\"" thefile "\"/>")
25160 (concat "<a href=\"" thefile "\">" desc "</a>")))
25161 (if (not valid) (setq rpl desc))))
25162 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
25163 (setq rpl (concat "<i>&lt;" type ":"
25164 (save-match-data (org-link-unescape path))
25165 "&gt;</i>"))))
25166 (setq line (replace-match rpl t t line)
25167 start (+ start (length rpl))))
25169 ;; TODO items
25170 (if (and (string-match org-todo-line-regexp line)
25171 (match-beginning 2))
25173 (setq line
25174 (concat (substring line 0 (match-beginning 2))
25175 "<span class=\""
25176 (if (member (match-string 2 line)
25177 org-done-keywords)
25178 "done" "todo")
25179 "\">" (match-string 2 line)
25180 "</span>" (substring line (match-end 2)))))
25182 ;; Does this contain a reference to a footnote?
25183 (when org-export-with-footnotes
25184 (setq start 0)
25185 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
25186 (if (get-text-property (match-beginning 2) 'org-protected line)
25187 (setq start (match-end 2))
25188 (let ((n (match-string 2 line)))
25189 (setq line
25190 (replace-match
25191 (format
25192 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
25193 (match-string 1 line) n n n)
25194 t t line))))))
25196 (cond
25197 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25198 ;; This is a headline
25199 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25200 txt (match-string 2 line))
25201 (if (string-match quote-re0 txt)
25202 (setq txt (replace-match "" t t txt)))
25203 (if (<= level (max umax umax-toc))
25204 (setq head-count (+ head-count 1)))
25205 (when in-local-list
25206 ;; Close any local lists before inserting a new header line
25207 (while local-list-num
25208 (org-close-li)
25209 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25210 (pop local-list-num))
25211 (setq local-list-indent nil
25212 in-local-list nil))
25213 (setq first-heading-pos (or first-heading-pos (point)))
25214 (org-html-level-start level txt umax
25215 (and org-export-with-toc (<= level umax))
25216 head-count)
25217 ;; QUOTES
25218 (when (string-match quote-re line)
25219 (insert "<pre>")
25220 (setq inquote t)))
25222 ((and org-export-with-tables
25223 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25224 (if (not table-open)
25225 ;; New table starts
25226 (setq table-open t table-buffer nil table-orig-buffer nil))
25227 ;; Accumulate lines
25228 (setq table-buffer (cons line table-buffer)
25229 table-orig-buffer (cons origline table-orig-buffer))
25230 (when (or (not lines)
25231 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25232 (car lines))))
25233 (setq table-open nil
25234 table-buffer (nreverse table-buffer)
25235 table-orig-buffer (nreverse table-orig-buffer))
25236 (org-close-par-maybe)
25237 (insert (org-format-table-html table-buffer table-orig-buffer))))
25239 ;; Normal lines
25240 (when (string-match
25241 (cond
25242 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25243 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25244 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25245 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
25246 line)
25247 (setq ind (org-get-string-indentation line)
25248 start-is-num (match-beginning 4)
25249 starter (if (match-beginning 2)
25250 (substring (match-string 2 line) 0 -1))
25251 line (substring line (match-beginning 5)))
25252 (unless (string-match "[^ \t]" line)
25253 ;; empty line. Pretend indentation is large.
25254 (setq ind (if org-empty-line-terminates-plain-lists
25256 (1+ (or (car local-list-indent) 1)))))
25257 (setq didclose nil)
25258 (while (and in-local-list
25259 (or (and (= ind (car local-list-indent))
25260 (not starter))
25261 (< ind (car local-list-indent))))
25262 (setq didclose t)
25263 (org-close-li)
25264 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25265 (pop local-list-num) (pop local-list-indent)
25266 (setq in-local-list local-list-indent))
25267 (cond
25268 ((and starter
25269 (or (not in-local-list)
25270 (> ind (car local-list-indent))))
25271 ;; Start new (level of) list
25272 (org-close-par-maybe)
25273 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
25274 (push start-is-num local-list-num)
25275 (push ind local-list-indent)
25276 (setq in-local-list t))
25277 (starter
25278 ;; continue current list
25279 (org-close-li)
25280 (insert "<li>\n"))
25281 (didclose
25282 ;; we did close a list, normal text follows: need <p>
25283 (org-open-par)))
25284 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
25285 (setq line
25286 (replace-match
25287 (if (equal (match-string 1 line) "X")
25288 "<b>[X]</b>"
25289 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
25290 t t line))))
25292 ;; Empty lines start a new paragraph. If hand-formatted lists
25293 ;; are not fully interpreted, lines starting with "-", "+", "*"
25294 ;; also start a new paragraph.
25295 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
25297 ;; Is this the start of a footnote?
25298 (when org-export-with-footnotes
25299 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
25300 (org-close-par-maybe)
25301 (let ((n (match-string 1 line)))
25302 (setq line (replace-match
25303 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
25305 ;; Check if the line break needs to be conserved
25306 (cond
25307 ((string-match "\\\\\\\\[ \t]*$" line)
25308 (setq line (replace-match "<br/>" t t line)))
25309 (org-export-preserve-breaks
25310 (setq line (concat line "<br/>"))))
25312 (insert line "\n")))))
25314 ;; Properly close all local lists and other lists
25315 (when inquote (insert "</pre>\n"))
25316 (when in-local-list
25317 ;; Close any local lists before inserting a new header line
25318 (while local-list-num
25319 (org-close-li)
25320 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
25321 (pop local-list-num))
25322 (setq local-list-indent nil
25323 in-local-list nil))
25324 (org-html-level-start 1 nil umax
25325 (and org-export-with-toc (<= level umax))
25326 head-count)
25328 (unless body-only
25329 (when (plist-get opt-plist :auto-postamble)
25330 (insert "<div id=\"postamble\">")
25331 (when (and org-export-author-info author)
25332 (insert "<p class=\"author\"> "
25333 (nth 1 lang-words) ": " author "\n")
25334 (when email
25335 (if (listp (split-string email ",+ *"))
25336 (mapc (lambda(e)
25337 (insert "<a href=\"mailto:" e "\">&lt;"
25338 e "&gt;</a>\n"))
25339 (split-string email ",+ *"))
25340 (insert "<a href=\"mailto:" email "\">&lt;"
25341 email "&gt;</a>\n")))
25342 (insert "</p>\n"))
25343 (when (and date org-export-time-stamp-file)
25344 (insert "<p class=\"date\"> "
25345 (nth 2 lang-words) ": "
25346 date "</p>\n"))
25347 (insert "</div>"))
25349 (if org-export-html-with-timestamp
25350 (insert org-export-html-html-helper-timestamp))
25351 (insert (or (plist-get opt-plist :postamble) ""))
25352 (insert "</body>\n</html>\n"))
25354 (normal-mode)
25355 (if (eq major-mode default-major-mode) (html-mode))
25357 ;; insert the table of contents
25358 (goto-char (point-min))
25359 (when thetoc
25360 (if (or (re-search-forward
25361 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
25362 (re-search-forward
25363 "\\[TABLE-OF-CONTENTS\\]" nil t))
25364 (progn
25365 (goto-char (match-beginning 0))
25366 (replace-match ""))
25367 (goto-char first-heading-pos)
25368 (when (looking-at "\\s-*</p>")
25369 (goto-char (match-end 0))
25370 (insert "\n")))
25371 (insert "<div id=\"table-of-contents\">\n")
25372 (mapc 'insert thetoc)
25373 (insert "</div>\n"))
25374 ;; remove empty paragraphs and lists
25375 (goto-char (point-min))
25376 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
25377 (replace-match ""))
25378 (goto-char (point-min))
25379 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
25380 (replace-match ""))
25381 ;; Convert whitespace place holders
25382 (goto-char (point-min))
25383 (let (beg end n)
25384 (while (setq beg (next-single-property-change (point) 'org-whitespace))
25385 (setq n (get-text-property beg 'org-whitespace)
25386 end (next-single-property-change beg 'org-whitespace))
25387 (goto-char beg)
25388 (delete-region beg end)
25389 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
25390 (make-string n ?x)))))
25392 (or to-buffer (save-buffer))
25393 (goto-char (point-min))
25394 (message "Exporting... done")
25395 (if (eq to-buffer 'string)
25396 (prog1 (buffer-substring (point-min) (point-max))
25397 (kill-buffer (current-buffer)))
25398 (current-buffer)))))
25400 (defvar org-table-colgroup-info nil)
25401 (defun org-format-table-ascii (lines)
25402 "Format a table for ascii export."
25403 (if (stringp lines)
25404 (setq lines (org-split-string lines "\n")))
25405 (if (not (string-match "^[ \t]*|" (car lines)))
25406 ;; Table made by table.el - test for spanning
25407 lines
25409 ;; A normal org table
25410 ;; Get rid of hlines at beginning and end
25411 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25412 (setq lines (nreverse lines))
25413 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25414 (setq lines (nreverse lines))
25415 (when org-export-table-remove-special-lines
25416 ;; Check if the table has a marking column. If yes remove the
25417 ;; column and the special lines
25418 (setq lines (org-table-clean-before-export lines)))
25419 ;; Get rid of the vertical lines except for grouping
25420 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
25421 rtn line vl1 start)
25422 (while (setq line (pop lines))
25423 (if (string-match org-table-hline-regexp line)
25424 (and (string-match "|\\(.*\\)|" line)
25425 (setq line (replace-match " \\1" t nil line)))
25426 (setq start 0 vl1 vl)
25427 (while (string-match "|" line start)
25428 (setq start (match-end 0))
25429 (or (pop vl1) (setq line (replace-match " " t t line)))))
25430 (push line rtn))
25431 (nreverse rtn))))
25433 (defun org-colgroup-info-to-vline-list (info)
25434 (let (vl new last)
25435 (while info
25436 (setq last new new (pop info))
25437 (if (or (memq last '(:end :startend))
25438 (memq new '(:start :startend)))
25439 (push t vl)
25440 (push nil vl)))
25441 (setq vl (nreverse vl))
25442 (and vl (setcar vl nil))
25443 vl))
25445 (defun org-format-table-html (lines olines)
25446 "Find out which HTML converter to use and return the HTML code."
25447 (if (stringp lines)
25448 (setq lines (org-split-string lines "\n")))
25449 (if (string-match "^[ \t]*|" (car lines))
25450 ;; A normal org table
25451 (org-format-org-table-html lines)
25452 ;; Table made by table.el - test for spanning
25453 (let* ((hlines (delq nil (mapcar
25454 (lambda (x)
25455 (if (string-match "^[ \t]*\\+-" x) x
25456 nil))
25457 lines)))
25458 (first (car hlines))
25459 (ll (and (string-match "\\S-+" first)
25460 (match-string 0 first)))
25461 (re (concat "^[ \t]*" (regexp-quote ll)))
25462 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
25463 hlines))))
25464 (if (and (not spanning)
25465 (not org-export-prefer-native-exporter-for-tables))
25466 ;; We can use my own converter with HTML conversions
25467 (org-format-table-table-html lines)
25468 ;; Need to use the code generator in table.el, with the original text.
25469 (org-format-table-table-html-using-table-generate-source olines)))))
25471 (defun org-format-org-table-html (lines &optional splice)
25472 "Format a table into HTML."
25473 ;; Get rid of hlines at beginning and end
25474 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25475 (setq lines (nreverse lines))
25476 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25477 (setq lines (nreverse lines))
25478 (when org-export-table-remove-special-lines
25479 ;; Check if the table has a marking column. If yes remove the
25480 ;; column and the special lines
25481 (setq lines (org-table-clean-before-export lines)))
25483 (let ((head (and org-export-highlight-first-table-line
25484 (delq nil (mapcar
25485 (lambda (x) (string-match "^[ \t]*|-" x))
25486 (cdr lines)))))
25487 (nlines 0) fnum i
25488 tbopen line fields html gr colgropen)
25489 (if splice (setq head nil))
25490 (unless splice (push (if head "<thead>" "<tbody>") html))
25491 (setq tbopen t)
25492 (while (setq line (pop lines))
25493 (catch 'next-line
25494 (if (string-match "^[ \t]*|-" line)
25495 (progn
25496 (unless splice
25497 (push (if head "</thead>" "</tbody>") html)
25498 (if lines (push "<tbody>" html) (setq tbopen nil)))
25499 (setq head nil) ;; head ends here, first time around
25500 ;; ignore this line
25501 (throw 'next-line t)))
25502 ;; Break the line into fields
25503 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25504 (unless fnum (setq fnum (make-vector (length fields) 0)))
25505 (setq nlines (1+ nlines) i -1)
25506 (push (concat "<tr>"
25507 (mapconcat
25508 (lambda (x)
25509 (setq i (1+ i))
25510 (if (and (< i nlines)
25511 (string-match org-table-number-regexp x))
25512 (incf (aref fnum i)))
25513 (if head
25514 (concat (car org-export-table-header-tags) x
25515 (cdr org-export-table-header-tags))
25516 (concat (car org-export-table-data-tags) x
25517 (cdr org-export-table-data-tags))))
25518 fields "")
25519 "</tr>")
25520 html)))
25521 (unless splice (if tbopen (push "</tbody>" html)))
25522 (unless splice (push "</table>\n" html))
25523 (setq html (nreverse html))
25524 (unless splice
25525 ;; Put in col tags with the alignment (unfortuntely often ignored...)
25526 (push (mapconcat
25527 (lambda (x)
25528 (setq gr (pop org-table-colgroup-info))
25529 (format "%s<col align=\"%s\"></col>%s"
25530 (if (memq gr '(:start :startend))
25531 (prog1
25532 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
25533 (setq colgropen t))
25535 (if (> (/ (float x) nlines) org-table-number-fraction)
25536 "right" "left")
25537 (if (memq gr '(:end :startend))
25538 (progn (setq colgropen nil) "</colgroup>")
25539 "")))
25540 fnum "")
25541 html)
25542 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
25543 (push html-table-tag html))
25544 (concat (mapconcat 'identity html "\n") "\n")))
25546 (defun org-table-clean-before-export (lines)
25547 "Check if the table has a marking column.
25548 If yes remove the column and the special lines."
25549 (setq org-table-colgroup-info nil)
25550 (if (memq nil
25551 (mapcar
25552 (lambda (x) (or (string-match "^[ \t]*|-" x)
25553 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
25554 lines))
25555 (progn
25556 (setq org-table-clean-did-remove-column nil)
25557 (delq nil
25558 (mapcar
25559 (lambda (x)
25560 (cond
25561 ((string-match "^[ \t]*| */ *|" x)
25562 (setq org-table-colgroup-info
25563 (mapcar (lambda (x)
25564 (cond ((member x '("<" "&lt;")) :start)
25565 ((member x '(">" "&gt;")) :end)
25566 ((member x '("<>" "&lt;&gt;")) :startend)
25567 (t nil)))
25568 (org-split-string x "[ \t]*|[ \t]*")))
25569 nil)
25570 (t x)))
25571 lines)))
25572 (setq org-table-clean-did-remove-column t)
25573 (delq nil
25574 (mapcar
25575 (lambda (x)
25576 (cond
25577 ((string-match "^[ \t]*| */ *|" x)
25578 (setq org-table-colgroup-info
25579 (mapcar (lambda (x)
25580 (cond ((member x '("<" "&lt;")) :start)
25581 ((member x '(">" "&gt;")) :end)
25582 ((member x '("<>" "&lt;&gt;")) :startend)
25583 (t nil)))
25584 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
25585 nil)
25586 ((string-match "^[ \t]*| *[!_^/] *|" x)
25587 nil) ; ignore this line
25588 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
25589 (string-match "^\\([ \t]*\\)|[^|]*|" x))
25590 ;; remove the first column
25591 (replace-match "\\1|" t nil x))))
25592 lines))))
25594 (defun org-format-table-table-html (lines)
25595 "Format a table generated by table.el into HTML.
25596 This conversion does *not* use `table-generate-source' from table.el.
25597 This has the advantage that Org-mode's HTML conversions can be used.
25598 But it has the disadvantage, that no cell- or row-spanning is allowed."
25599 (let (line field-buffer
25600 (head org-export-highlight-first-table-line)
25601 fields html empty)
25602 (setq html (concat html-table-tag "\n"))
25603 (while (setq line (pop lines))
25604 (setq empty "&nbsp;")
25605 (catch 'next-line
25606 (if (string-match "^[ \t]*\\+-" line)
25607 (progn
25608 (if field-buffer
25609 (progn
25610 (setq
25611 html
25612 (concat
25613 html
25614 "<tr>"
25615 (mapconcat
25616 (lambda (x)
25617 (if (equal x "") (setq x empty))
25618 (if head
25619 (concat (car org-export-table-header-tags) x
25620 (cdr org-export-table-header-tags))
25621 (concat (car org-export-table-data-tags) x
25622 (cdr org-export-table-data-tags))))
25623 field-buffer "\n")
25624 "</tr>\n"))
25625 (setq head nil)
25626 (setq field-buffer nil)))
25627 ;; Ignore this line
25628 (throw 'next-line t)))
25629 ;; Break the line into fields and store the fields
25630 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25631 (if field-buffer
25632 (setq field-buffer (mapcar
25633 (lambda (x)
25634 (concat x "<br/>" (pop fields)))
25635 field-buffer))
25636 (setq field-buffer fields))))
25637 (setq html (concat html "</table>\n"))
25638 html))
25640 (defun org-format-table-table-html-using-table-generate-source (lines)
25641 "Format a table into html, using `table-generate-source' from table.el.
25642 This has the advantage that cell- or row-spanning is allowed.
25643 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
25644 (require 'table)
25645 (with-current-buffer (get-buffer-create " org-tmp1 ")
25646 (erase-buffer)
25647 (insert (mapconcat 'identity lines "\n"))
25648 (goto-char (point-min))
25649 (if (not (re-search-forward "|[^+]" nil t))
25650 (error "Error processing table"))
25651 (table-recognize-table)
25652 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
25653 (table-generate-source 'html " org-tmp2 ")
25654 (set-buffer " org-tmp2 ")
25655 (buffer-substring (point-min) (point-max))))
25657 (defun org-html-handle-time-stamps (s)
25658 "Format time stamps in string S, or remove them."
25659 (catch 'exit
25660 (let (r b)
25661 (while (string-match org-maybe-keyword-time-regexp s)
25662 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
25663 ;; never export CLOCK
25664 (throw 'exit ""))
25665 (or b (setq b (substring s 0 (match-beginning 0))))
25666 (if (not org-export-with-timestamps)
25667 (setq r (concat r (substring s 0 (match-beginning 0)))
25668 s (substring s (match-end 0)))
25669 (setq r (concat
25670 r (substring s 0 (match-beginning 0))
25671 (if (match-end 1)
25672 (format "@<span class=\"timestamp-kwd\">%s @</span>"
25673 (match-string 1 s)))
25674 (format " @<span class=\"timestamp\">%s@</span>"
25675 (substring
25676 (org-translate-time (match-string 3 s)) 1 -1)))
25677 s (substring s (match-end 0)))))
25678 ;; Line break if line started and ended with time stamp stuff
25679 (if (not r)
25681 (setq r (concat r s))
25682 (unless (string-match "\\S-" (concat b s))
25683 (setq r (concat r "@<br/>")))
25684 r))))
25686 (defun org-html-protect (s)
25687 ;; convert & to &amp;, < to &lt; and > to &gt;
25688 (let ((start 0))
25689 (while (string-match "&" s start)
25690 (setq s (replace-match "&amp;" t t s)
25691 start (1+ (match-beginning 0))))
25692 (while (string-match "<" s)
25693 (setq s (replace-match "&lt;" t t s)))
25694 (while (string-match ">" s)
25695 (setq s (replace-match "&gt;" t t s))))
25698 (defun org-export-cleanup-toc-line (s)
25699 "Remove tags and time staps from lines going into the toc."
25700 (when (memq org-export-with-tags '(not-in-toc nil))
25701 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
25702 (setq s (replace-match "" t t s))))
25703 (when org-export-remove-timestamps-from-toc
25704 (while (string-match org-maybe-keyword-time-regexp s)
25705 (setq s (replace-match "" t t s))))
25706 (while (string-match org-bracket-link-regexp s)
25707 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
25708 t t s)))
25711 (defun org-html-expand (string)
25712 "Prepare STRING for HTML export. Applies all active conversions.
25713 If there are links in the string, don't modify these."
25714 (let* ((re (concat org-bracket-link-regexp "\\|"
25715 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
25716 m s l res)
25717 (while (setq m (string-match re string))
25718 (setq s (substring string 0 m)
25719 l (match-string 0 string)
25720 string (substring string (match-end 0)))
25721 (push (org-html-do-expand s) res)
25722 (push l res))
25723 (push (org-html-do-expand string) res)
25724 (apply 'concat (nreverse res))))
25726 (defun org-html-do-expand (s)
25727 "Apply all active conversions to translate special ASCII to HTML."
25728 (setq s (org-html-protect s))
25729 (if org-export-html-expand
25730 (let ((start 0))
25731 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
25732 (setq s (replace-match "<\\1>" t nil s)))))
25733 (if org-export-with-emphasize
25734 (setq s (org-export-html-convert-emphasize s)))
25735 (if org-export-with-special-strings
25736 (setq s (org-export-html-convert-special-strings s)))
25737 (if org-export-with-sub-superscripts
25738 (setq s (org-export-html-convert-sub-super s)))
25739 (if org-export-with-TeX-macros
25740 (let ((start 0) wd ass)
25741 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
25742 (if (get-text-property (match-beginning 0) 'org-protected s)
25743 (setq start (match-end 0))
25744 (setq wd (match-string 1 s))
25745 (if (setq ass (assoc wd org-html-entities))
25746 (setq s (replace-match (or (cdr ass)
25747 (concat "&" (car ass) ";"))
25748 t t s))
25749 (setq start (+ start (length wd))))))))
25752 (defun org-create-multibrace-regexp (left right n)
25753 "Create a regular expression which will match a balanced sexp.
25754 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
25755 as single character strings.
25756 The regexp returned will match the entire expression including the
25757 delimiters. It will also define a single group which contains the
25758 match except for the outermost delimiters. The maximum depth of
25759 stacked delimiters is N. Escaping delimiters is not possible."
25760 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
25761 (or "\\|")
25762 (re nothing)
25763 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
25764 (while (> n 1)
25765 (setq n (1- n)
25766 re (concat re or next)
25767 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
25768 (concat left "\\(" re "\\)" right)))
25770 (defvar org-match-substring-regexp
25771 (concat
25772 "\\([^\\]\\)\\([_^]\\)\\("
25773 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
25774 "\\|"
25775 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
25776 "\\|"
25777 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
25778 "The regular expression matching a sub- or superscript.")
25780 (defvar org-match-substring-with-braces-regexp
25781 (concat
25782 "\\([^\\]\\)\\([_^]\\)\\("
25783 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
25784 "\\)")
25785 "The regular expression matching a sub- or superscript, forcing braces.")
25787 (defconst org-export-html-special-string-regexps
25788 '(("\\\\-" . "&shy;")
25789 ("---\\([^-]\\)" . "&mdash;\\1")
25790 ("--\\([^-]\\)" . "&ndash;\\1")
25791 ("\\.\\.\\." . "&hellip;"))
25792 "Regular expressions for special string conversion.")
25794 (defun org-export-html-convert-special-strings (string)
25795 "Convert special characters in STRING to HTML."
25796 (let ((all org-export-html-special-string-regexps)
25797 e a re rpl start)
25798 (while (setq a (pop all))
25799 (setq re (car a) rpl (cdr a) start 0)
25800 (while (string-match re string start)
25801 (if (get-text-property (match-beginning 0) 'org-protected string)
25802 (setq start (match-end 0))
25803 (setq string (replace-match rpl t nil string)))))
25804 string))
25806 (defun org-export-html-convert-sub-super (string)
25807 "Convert sub- and superscripts in STRING to HTML."
25808 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
25809 (while (string-match org-match-substring-regexp string s)
25810 (cond
25811 ((and requireb (match-end 8)) (setq s (match-end 2)))
25812 ((get-text-property (match-beginning 2) 'org-protected string)
25813 (setq s (match-end 2)))
25815 (setq s (match-end 1)
25816 key (if (string= (match-string 2 string) "_") "sub" "sup")
25817 c (or (match-string 8 string)
25818 (match-string 6 string)
25819 (match-string 5 string))
25820 string (replace-match
25821 (concat (match-string 1 string)
25822 "<" key ">" c "</" key ">")
25823 t t string)))))
25824 (while (string-match "\\\\\\([_^]\\)" string)
25825 (setq string (replace-match (match-string 1 string) t t string)))
25826 string))
25828 (defun org-export-html-convert-emphasize (string)
25829 "Apply emphasis."
25830 (let ((s 0) rpl)
25831 (while (string-match org-emph-re string s)
25832 (if (not (equal
25833 (substring string (match-beginning 3) (1+ (match-beginning 3)))
25834 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
25835 (setq s (match-beginning 0)
25837 (concat
25838 (match-string 1 string)
25839 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
25840 (match-string 4 string)
25841 (nth 3 (assoc (match-string 3 string)
25842 org-emphasis-alist))
25843 (match-string 5 string))
25844 string (replace-match rpl t t string)
25845 s (+ s (- (length rpl) 2)))
25846 (setq s (1+ s))))
25847 string))
25849 (defvar org-par-open nil)
25850 (defun org-open-par ()
25851 "Insert <p>, but first close previous paragraph if any."
25852 (org-close-par-maybe)
25853 (insert "\n<p>")
25854 (setq org-par-open t))
25855 (defun org-close-par-maybe ()
25856 "Close paragraph if there is one open."
25857 (when org-par-open
25858 (insert "</p>")
25859 (setq org-par-open nil)))
25860 (defun org-close-li ()
25861 "Close <li> if necessary."
25862 (org-close-par-maybe)
25863 (insert "</li>\n"))
25865 (defvar body-only) ; dynamically scoped into this.
25866 (defun org-html-level-start (level title umax with-toc head-count)
25867 "Insert a new level in HTML export.
25868 When TITLE is nil, just close all open levels."
25869 (org-close-par-maybe)
25870 (let ((l org-level-max))
25871 (while (>= l level)
25872 (if (aref org-levels-open (1- l))
25873 (progn
25874 (org-html-level-close l umax)
25875 (aset org-levels-open (1- l) nil)))
25876 (setq l (1- l)))
25877 (when title
25878 ;; If title is nil, this means this function is called to close
25879 ;; all levels, so the rest is done only if title is given
25880 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
25881 (setq title (replace-match
25882 (if org-export-with-tags
25883 (save-match-data
25884 (concat
25885 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
25886 (mapconcat 'identity (org-split-string
25887 (match-string 1 title) ":")
25888 "&nbsp;")
25889 "</span>"))
25891 t t title)))
25892 (if (> level umax)
25893 (progn
25894 (if (aref org-levels-open (1- level))
25895 (progn
25896 (org-close-li)
25897 (insert "<li>" title "<br/>\n"))
25898 (aset org-levels-open (1- level) t)
25899 (org-close-par-maybe)
25900 (insert "<ul>\n<li>" title "<br/>\n")))
25901 (aset org-levels-open (1- level) t)
25902 (if (and org-export-with-section-numbers (not body-only))
25903 (setq title (concat (org-section-number level) " " title)))
25904 (setq level (+ level org-export-html-toplevel-hlevel -1))
25905 (if with-toc
25906 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
25907 level level head-count title level))
25908 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
25909 (org-open-par)))))
25911 (defun org-html-level-close (level max-outline-level)
25912 "Terminate one level in HTML export."
25913 (if (<= level max-outline-level)
25914 (insert "</div>\n")
25915 (org-close-li)
25916 (insert "</ul>\n")))
25918 ;;; iCalendar export
25920 ;;;###autoload
25921 (defun org-export-icalendar-this-file ()
25922 "Export current file as an iCalendar file.
25923 The iCalendar file will be located in the same directory as the Org-mode
25924 file, but with extension `.ics'."
25925 (interactive)
25926 (org-export-icalendar nil buffer-file-name))
25928 ;;;###autoload
25929 (defun org-export-icalendar-all-agenda-files ()
25930 "Export all files in `org-agenda-files' to iCalendar .ics files.
25931 Each iCalendar file will be located in the same directory as the Org-mode
25932 file, but with extension `.ics'."
25933 (interactive)
25934 (apply 'org-export-icalendar nil (org-agenda-files t)))
25936 ;;;###autoload
25937 (defun org-export-icalendar-combine-agenda-files ()
25938 "Export all files in `org-agenda-files' to a single combined iCalendar file.
25939 The file is stored under the name `org-combined-agenda-icalendar-file'."
25940 (interactive)
25941 (apply 'org-export-icalendar t (org-agenda-files t)))
25943 (defun org-export-icalendar (combine &rest files)
25944 "Create iCalendar files for all elements of FILES.
25945 If COMBINE is non-nil, combine all calendar entries into a single large
25946 file and store it under the name `org-combined-agenda-icalendar-file'."
25947 (save-excursion
25948 (org-prepare-agenda-buffers files)
25949 (let* ((dir (org-export-directory
25950 :ical (list :publishing-directory
25951 org-export-publishing-directory)))
25952 file ical-file ical-buffer category started org-agenda-new-buffers)
25954 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
25955 (when combine
25956 (setq ical-file
25957 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
25958 org-combined-agenda-icalendar-file
25959 (expand-file-name org-combined-agenda-icalendar-file dir))
25960 ical-buffer (org-get-agenda-file-buffer ical-file))
25961 (set-buffer ical-buffer) (erase-buffer))
25962 (while (setq file (pop files))
25963 (catch 'nextfile
25964 (org-check-agenda-file file)
25965 (set-buffer (org-get-agenda-file-buffer file))
25966 (unless combine
25967 (setq ical-file (concat (file-name-as-directory dir)
25968 (file-name-sans-extension
25969 (file-name-nondirectory buffer-file-name))
25970 ".ics"))
25971 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
25972 (with-current-buffer ical-buffer (erase-buffer)))
25973 (setq category (or org-category
25974 (file-name-sans-extension
25975 (file-name-nondirectory buffer-file-name))))
25976 (if (symbolp category) (setq category (symbol-name category)))
25977 (let ((standard-output ical-buffer))
25978 (if combine
25979 (and (not started) (setq started t)
25980 (org-start-icalendar-file org-icalendar-combined-name))
25981 (org-start-icalendar-file category))
25982 (org-print-icalendar-entries combine)
25983 (when (or (and combine (not files)) (not combine))
25984 (org-finish-icalendar-file)
25985 (set-buffer ical-buffer)
25986 (save-buffer)
25987 (run-hooks 'org-after-save-iCalendar-file-hook)))))
25988 (org-release-buffers org-agenda-new-buffers))))
25990 (defvar org-after-save-iCalendar-file-hook nil
25991 "Hook run after an iCalendar file has been saved.
25992 The iCalendar buffer is still current when this hook is run.
25993 A good way to use this is to tell a desktop calenndar application to re-read
25994 the iCalendar file.")
25996 (defun org-print-icalendar-entries (&optional combine)
25997 "Print iCalendar entries for the current Org-mode file to `standard-output'.
25998 When COMBINE is non nil, add the category to each line."
25999 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
26000 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
26001 (dts (org-ical-ts-to-string
26002 (format-time-string (cdr org-time-stamp-formats) (current-time))
26003 "DTSTART"))
26004 hd ts ts2 state status (inc t) pos b sexp rrule
26005 scheduledp deadlinep tmp pri category entry location summary desc
26006 (sexp-buffer (get-buffer-create "*ical-tmp*")))
26007 (org-refresh-category-properties)
26008 (save-excursion
26009 (goto-char (point-min))
26010 (while (re-search-forward re1 nil t)
26011 (catch :skip
26012 (org-agenda-skip)
26013 (setq pos (match-beginning 0)
26014 ts (match-string 0)
26015 inc t
26016 hd (org-get-heading)
26017 summary (org-icalendar-cleanup-string
26018 (org-entry-get nil "SUMMARY"))
26019 desc (org-icalendar-cleanup-string
26020 (or (org-entry-get nil "DESCRIPTION")
26021 (and org-icalendar-include-body (org-get-entry)))
26022 t org-icalendar-include-body)
26023 location (org-icalendar-cleanup-string
26024 (org-entry-get nil "LOCATION"))
26025 category (org-get-category))
26026 (if (looking-at re2)
26027 (progn
26028 (goto-char (match-end 0))
26029 (setq ts2 (match-string 1) inc nil))
26030 (setq tmp (buffer-substring (max (point-min)
26031 (- pos org-ds-keyword-length))
26032 pos)
26033 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
26034 (progn
26035 (setq inc nil)
26036 (replace-match "\\1" t nil ts))
26038 deadlinep (string-match org-deadline-regexp tmp)
26039 scheduledp (string-match org-scheduled-regexp tmp)
26040 ;; donep (org-entry-is-done-p)
26042 (if (or (string-match org-tr-regexp hd)
26043 (string-match org-ts-regexp hd))
26044 (setq hd (replace-match "" t t hd)))
26045 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
26046 (setq rrule
26047 (concat "\nRRULE:FREQ="
26048 (cdr (assoc
26049 (match-string 2 ts)
26050 '(("d" . "DAILY")("w" . "WEEKLY")
26051 ("m" . "MONTHLY")("y" . "YEARLY"))))
26052 ";INTERVAL=" (match-string 1 ts)))
26053 (setq rrule ""))
26054 (setq summary (or summary hd))
26055 (if (string-match org-bracket-link-regexp summary)
26056 (setq summary
26057 (replace-match (if (match-end 3)
26058 (match-string 3 summary)
26059 (match-string 1 summary))
26060 t t summary)))
26061 (if deadlinep (setq summary (concat "DL: " summary)))
26062 (if scheduledp (setq summary (concat "S: " summary)))
26063 (if (string-match "\\`<%%" ts)
26064 (with-current-buffer sexp-buffer
26065 (insert (substring ts 1 -1) " " summary "\n"))
26066 (princ (format "BEGIN:VEVENT
26068 %s%s
26069 SUMMARY:%s%s%s
26070 CATEGORIES:%s
26071 END:VEVENT\n"
26072 (org-ical-ts-to-string ts "DTSTART")
26073 (org-ical-ts-to-string ts2 "DTEND" inc)
26074 rrule summary
26075 (if (and desc (string-match "\\S-" desc))
26076 (concat "\nDESCRIPTION: " desc) "")
26077 (if (and location (string-match "\\S-" location))
26078 (concat "\nLOCATION: " location) "")
26079 category)))))
26081 (when (and org-icalendar-include-sexps
26082 (condition-case nil (require 'icalendar) (error nil))
26083 (fboundp 'icalendar-export-region))
26084 ;; Get all the literal sexps
26085 (goto-char (point-min))
26086 (while (re-search-forward "^&?%%(" nil t)
26087 (catch :skip
26088 (org-agenda-skip)
26089 (setq b (match-beginning 0))
26090 (goto-char (1- (match-end 0)))
26091 (forward-sexp 1)
26092 (end-of-line 1)
26093 (setq sexp (buffer-substring b (point)))
26094 (with-current-buffer sexp-buffer
26095 (insert sexp "\n"))
26096 (princ (org-diary-to-ical-string sexp-buffer)))))
26098 (when org-icalendar-include-todo
26099 (goto-char (point-min))
26100 (while (re-search-forward org-todo-line-regexp nil t)
26101 (catch :skip
26102 (org-agenda-skip)
26103 (setq state (match-string 2))
26104 (setq status (if (member state org-done-keywords)
26105 "COMPLETED" "NEEDS-ACTION"))
26106 (when (and state
26107 (or (not (member state org-done-keywords))
26108 (eq org-icalendar-include-todo 'all))
26109 (not (member org-archive-tag (org-get-tags-at)))
26111 (setq hd (match-string 3)
26112 summary (org-icalendar-cleanup-string
26113 (org-entry-get nil "SUMMARY"))
26114 desc (org-icalendar-cleanup-string
26115 (or (org-entry-get nil "DESCRIPTION")
26116 (and org-icalendar-include-body (org-get-entry)))
26117 t org-icalendar-include-body)
26118 location (org-icalendar-cleanup-string
26119 (org-entry-get nil "LOCATION")))
26120 (if (string-match org-bracket-link-regexp hd)
26121 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
26122 (match-string 1 hd))
26123 t t hd)))
26124 (if (string-match org-priority-regexp hd)
26125 (setq pri (string-to-char (match-string 2 hd))
26126 hd (concat (substring hd 0 (match-beginning 1))
26127 (substring hd (match-end 1))))
26128 (setq pri org-default-priority))
26129 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
26130 (- org-lowest-priority org-highest-priority))))))
26132 (princ (format "BEGIN:VTODO
26134 SUMMARY:%s%s%s
26135 CATEGORIES:%s
26136 SEQUENCE:1
26137 PRIORITY:%d
26138 STATUS:%s
26139 END:VTODO\n"
26141 (or summary hd)
26142 (if (and location (string-match "\\S-" location))
26143 (concat "\nLOCATION: " location) "")
26144 (if (and desc (string-match "\\S-" desc))
26145 (concat "\nDESCRIPTION: " desc) "")
26146 category pri status)))))))))
26148 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
26149 "Take out stuff and quote what needs to be quoted.
26150 When IS-BODY is non-nil, assume that this is the body of an item, clean up
26151 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
26152 characters."
26153 (if (not s)
26155 (when is-body
26156 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
26157 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
26158 (while (string-match re s) (setq s (replace-match "" t t s)))
26159 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
26160 (let ((start 0))
26161 (while (string-match "\\([,;\\]\\)" s start)
26162 (setq start (+ (match-beginning 0) 2)
26163 s (replace-match "\\\\\\1" nil nil s))))
26164 (when is-body
26165 (while (string-match "[ \t]*\n[ \t]*" s)
26166 (setq s (replace-match "\\n" t t s))))
26167 (setq s (org-trim s))
26168 (if is-body
26169 (if maxlength
26170 (if (and (numberp maxlength)
26171 (> (length s) maxlength))
26172 (setq s (substring s 0 maxlength)))))
26175 (defun org-get-entry ()
26176 "Clean-up description string."
26177 (save-excursion
26178 (org-back-to-heading t)
26179 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
26181 (defun org-start-icalendar-file (name)
26182 "Start an iCalendar file by inserting the header."
26183 (let ((user user-full-name)
26184 (name (or name "unknown"))
26185 (timezone (cadr (current-time-zone))))
26186 (princ
26187 (format "BEGIN:VCALENDAR
26188 VERSION:2.0
26189 X-WR-CALNAME:%s
26190 PRODID:-//%s//Emacs with Org-mode//EN
26191 X-WR-TIMEZONE:%s
26192 CALSCALE:GREGORIAN\n" name user timezone))))
26194 (defun org-finish-icalendar-file ()
26195 "Finish an iCalendar file by inserting the END statement."
26196 (princ "END:VCALENDAR\n"))
26198 (defun org-ical-ts-to-string (s keyword &optional inc)
26199 "Take a time string S and convert it to iCalendar format.
26200 KEYWORD is added in front, to make a complete line like DTSTART....
26201 When INC is non-nil, increase the hour by two (if time string contains
26202 a time), or the day by one (if it does not contain a time)."
26203 (let ((t1 (org-parse-time-string s 'nodefault))
26204 t2 fmt have-time time)
26205 (if (and (car t1) (nth 1 t1) (nth 2 t1))
26206 (setq t2 t1 have-time t)
26207 (setq t2 (org-parse-time-string s)))
26208 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
26209 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
26210 (when inc
26211 (if have-time
26212 (if org-agenda-default-appointment-duration
26213 (setq mi (+ org-agenda-default-appointment-duration mi))
26214 (setq h (+ 2 h)))
26215 (setq d (1+ d))))
26216 (setq time (encode-time s mi h d m y)))
26217 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
26218 (concat keyword (format-time-string fmt time))))
26220 ;;; XOXO export
26222 (defun org-export-as-xoxo-insert-into (buffer &rest output)
26223 (with-current-buffer buffer
26224 (apply 'insert output)))
26225 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
26227 (defun org-export-as-xoxo (&optional buffer)
26228 "Export the org buffer as XOXO.
26229 The XOXO buffer is named *xoxo-<source buffer name>*"
26230 (interactive (list (current-buffer)))
26231 ;; A quickie abstraction
26233 ;; Output everything as XOXO
26234 (with-current-buffer (get-buffer buffer)
26235 (let* ((pos (point))
26236 (opt-plist (org-combine-plists (org-default-export-plist)
26237 (org-infile-export-plist)))
26238 (filename (concat (file-name-as-directory
26239 (org-export-directory :xoxo opt-plist))
26240 (file-name-sans-extension
26241 (file-name-nondirectory buffer-file-name))
26242 ".html"))
26243 (out (find-file-noselect filename))
26244 (last-level 1)
26245 (hanging-li nil))
26246 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
26247 ;; Check the output buffer is empty.
26248 (with-current-buffer out (erase-buffer))
26249 ;; Kick off the output
26250 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
26251 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
26252 (let* ((hd (match-string-no-properties 1))
26253 (level (length hd))
26254 (text (concat
26255 (match-string-no-properties 2)
26256 (save-excursion
26257 (goto-char (match-end 0))
26258 (let ((str ""))
26259 (catch 'loop
26260 (while 't
26261 (forward-line)
26262 (if (looking-at "^[ \t]\\(.*\\)")
26263 (setq str (concat str (match-string-no-properties 1)))
26264 (throw 'loop str)))))))))
26266 ;; Handle level rendering
26267 (cond
26268 ((> level last-level)
26269 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
26271 ((< level last-level)
26272 (dotimes (- (- last-level level) 1)
26273 (if hanging-li
26274 (org-export-as-xoxo-insert-into out "</li>\n"))
26275 (org-export-as-xoxo-insert-into out "</ol>\n"))
26276 (when hanging-li
26277 (org-export-as-xoxo-insert-into out "</li>\n")
26278 (setq hanging-li nil)))
26280 ((equal level last-level)
26281 (if hanging-li
26282 (org-export-as-xoxo-insert-into out "</li>\n")))
26285 (setq last-level level)
26287 ;; And output the new li
26288 (setq hanging-li 't)
26289 (if (equal ?+ (elt text 0))
26290 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
26291 (org-export-as-xoxo-insert-into out "<li>" text))))
26293 ;; Finally finish off the ol
26294 (dotimes (- last-level 1)
26295 (if hanging-li
26296 (org-export-as-xoxo-insert-into out "</li>\n"))
26297 (org-export-as-xoxo-insert-into out "</ol>\n"))
26299 (goto-char pos)
26300 ;; Finish the buffer off and clean it up.
26301 (switch-to-buffer-other-window out)
26302 (indent-region (point-min) (point-max) nil)
26303 (save-buffer)
26304 (goto-char (point-min))
26308 ;;;; Key bindings
26310 ;; Make `C-c C-x' a prefix key
26311 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
26313 ;; TAB key with modifiers
26314 (org-defkey org-mode-map "\C-i" 'org-cycle)
26315 (org-defkey org-mode-map [(tab)] 'org-cycle)
26316 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
26317 (org-defkey org-mode-map [(meta tab)] 'org-complete)
26318 (org-defkey org-mode-map "\M-\t" 'org-complete)
26319 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
26320 ;; The following line is necessary under Suse GNU/Linux
26321 (unless (featurep 'xemacs)
26322 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
26323 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
26324 (define-key org-mode-map [backtab] 'org-shifttab)
26326 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
26327 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
26328 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
26330 ;; Cursor keys with modifiers
26331 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
26332 (org-defkey org-mode-map [(meta right)] 'org-metaright)
26333 (org-defkey org-mode-map [(meta up)] 'org-metaup)
26334 (org-defkey org-mode-map [(meta down)] 'org-metadown)
26336 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
26337 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
26338 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
26339 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
26341 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
26342 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
26343 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
26344 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
26346 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
26347 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
26349 ;;; Extra keys for tty access.
26350 ;; We only set them when really needed because otherwise the
26351 ;; menus don't show the simple keys
26353 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
26354 (not window-system))
26355 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
26356 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
26357 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
26358 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
26359 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
26360 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
26361 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
26362 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
26363 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
26364 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
26365 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
26366 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
26367 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
26368 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
26369 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
26370 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
26371 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
26372 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
26373 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
26374 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
26375 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
26376 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
26378 ;; All the other keys
26380 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
26381 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
26382 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
26383 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
26384 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
26385 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
26386 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
26387 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
26388 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
26389 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
26390 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
26391 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
26392 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
26393 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
26394 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
26395 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
26396 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
26397 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
26398 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
26399 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
26400 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
26401 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
26402 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
26403 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
26404 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
26405 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
26406 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
26407 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
26408 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
26409 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
26410 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
26411 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
26412 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
26413 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
26414 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
26415 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
26416 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
26417 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
26418 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
26419 (org-defkey org-mode-map "\C-c^" 'org-sort)
26420 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
26421 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
26422 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
26423 (org-defkey org-mode-map "\C-m" 'org-return)
26424 (org-defkey org-mode-map "\C-j" 'org-return-indent)
26425 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
26426 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
26427 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
26428 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
26429 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
26430 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
26431 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
26432 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
26433 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
26434 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
26435 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
26436 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
26437 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
26438 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
26439 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
26440 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
26442 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
26443 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
26444 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
26445 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
26447 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
26448 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
26449 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
26450 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
26451 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
26452 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
26453 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
26454 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
26455 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
26456 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
26457 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
26458 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
26460 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
26462 (when (featurep 'xemacs)
26463 (org-defkey org-mode-map 'button3 'popup-mode-menu))
26465 (defsubst org-table-p () (org-at-table-p))
26467 (defun org-self-insert-command (N)
26468 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
26469 If the cursor is in a table looking at whitespace, the whitespace is
26470 overwritten, and the table is not marked as requiring realignment."
26471 (interactive "p")
26472 (if (and (org-table-p)
26473 (progn
26474 ;; check if we blank the field, and if that triggers align
26475 (and org-table-auto-blank-field
26476 (member last-command
26477 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
26478 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
26479 ;; got extra space, this field does not determine column width
26480 (let (org-table-may-need-update) (org-table-blank-field))
26481 ;; no extra space, this field may determine column width
26482 (org-table-blank-field)))
26484 (eq N 1)
26485 (looking-at "[^|\n]* |"))
26486 (let (org-table-may-need-update)
26487 (goto-char (1- (match-end 0)))
26488 (delete-backward-char 1)
26489 (goto-char (match-beginning 0))
26490 (self-insert-command N))
26491 (setq org-table-may-need-update t)
26492 (self-insert-command N)
26493 (org-fix-tags-on-the-fly)))
26495 (defun org-fix-tags-on-the-fly ()
26496 (when (and (equal (char-after (point-at-bol)) ?*)
26497 (org-on-heading-p))
26498 (org-align-tags-here org-tags-column)))
26500 (defun org-delete-backward-char (N)
26501 "Like `delete-backward-char', insert whitespace at field end in tables.
26502 When deleting backwards, in tables this function will insert whitespace in
26503 front of the next \"|\" separator, to keep the table aligned. The table will
26504 still be marked for re-alignment if the field did fill the entire column,
26505 because, in this case the deletion might narrow the column."
26506 (interactive "p")
26507 (if (and (org-table-p)
26508 (eq N 1)
26509 (string-match "|" (buffer-substring (point-at-bol) (point)))
26510 (looking-at ".*?|"))
26511 (let ((pos (point))
26512 (noalign (looking-at "[^|\n\r]* |"))
26513 (c org-table-may-need-update))
26514 (backward-delete-char N)
26515 (skip-chars-forward "^|")
26516 (insert " ")
26517 (goto-char (1- pos))
26518 ;; noalign: if there were two spaces at the end, this field
26519 ;; does not determine the width of the column.
26520 (if noalign (setq org-table-may-need-update c)))
26521 (backward-delete-char N)
26522 (org-fix-tags-on-the-fly)))
26524 (defun org-delete-char (N)
26525 "Like `delete-char', but insert whitespace at field end in tables.
26526 When deleting characters, in tables this function will insert whitespace in
26527 front of the next \"|\" separator, to keep the table aligned. The table will
26528 still be marked for re-alignment if the field did fill the entire column,
26529 because, in this case the deletion might narrow the column."
26530 (interactive "p")
26531 (if (and (org-table-p)
26532 (not (bolp))
26533 (not (= (char-after) ?|))
26534 (eq N 1))
26535 (if (looking-at ".*?|")
26536 (let ((pos (point))
26537 (noalign (looking-at "[^|\n\r]* |"))
26538 (c org-table-may-need-update))
26539 (replace-match (concat
26540 (substring (match-string 0) 1 -1)
26541 " |"))
26542 (goto-char pos)
26543 ;; noalign: if there were two spaces at the end, this field
26544 ;; does not determine the width of the column.
26545 (if noalign (setq org-table-may-need-update c)))
26546 (delete-char N))
26547 (delete-char N)
26548 (org-fix-tags-on-the-fly)))
26550 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
26551 (put 'org-self-insert-command 'delete-selection t)
26552 (put 'orgtbl-self-insert-command 'delete-selection t)
26553 (put 'org-delete-char 'delete-selection 'supersede)
26554 (put 'org-delete-backward-char 'delete-selection 'supersede)
26556 ;; Make `flyspell-mode' delay after some commands
26557 (put 'org-self-insert-command 'flyspell-delayed t)
26558 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
26559 (put 'org-delete-char 'flyspell-delayed t)
26560 (put 'org-delete-backward-char 'flyspell-delayed t)
26562 ;; Make pabbrev-mode expand after org-mode commands
26563 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
26564 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
26566 ;; How to do this: Measure non-white length of current string
26567 ;; If equal to column width, we should realign.
26569 (defun org-remap (map &rest commands)
26570 "In MAP, remap the functions given in COMMANDS.
26571 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
26572 (let (new old)
26573 (while commands
26574 (setq old (pop commands) new (pop commands))
26575 (if (fboundp 'command-remapping)
26576 (org-defkey map (vector 'remap old) new)
26577 (substitute-key-definition old new map global-map)))))
26579 (when (eq org-enable-table-editor 'optimized)
26580 ;; If the user wants maximum table support, we need to hijack
26581 ;; some standard editing functions
26582 (org-remap org-mode-map
26583 'self-insert-command 'org-self-insert-command
26584 'delete-char 'org-delete-char
26585 'delete-backward-char 'org-delete-backward-char)
26586 (org-defkey org-mode-map "|" 'org-force-self-insert))
26588 (defun org-shiftcursor-error ()
26589 "Throw an error because Shift-Cursor command was applied in wrong context."
26590 (error "This command is active in special context like tables, headlines or timestamps"))
26592 (defun org-shifttab (&optional arg)
26593 "Global visibility cycling or move to previous table field.
26594 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
26595 on context.
26596 See the individual commands for more information."
26597 (interactive "P")
26598 (cond
26599 ((org-at-table-p) (call-interactively 'org-table-previous-field))
26600 (arg (message "Content view to level: ")
26601 (org-content (prefix-numeric-value arg))
26602 (setq org-cycle-global-status 'overview))
26603 (t (call-interactively 'org-global-cycle))))
26605 (defun org-shiftmetaleft ()
26606 "Promote subtree or delete table column.
26607 Calls `org-promote-subtree', `org-outdent-item',
26608 or `org-table-delete-column', depending on context.
26609 See the individual commands for more information."
26610 (interactive)
26611 (cond
26612 ((org-at-table-p) (call-interactively 'org-table-delete-column))
26613 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
26614 ((org-at-item-p) (call-interactively 'org-outdent-item))
26615 (t (org-shiftcursor-error))))
26617 (defun org-shiftmetaright ()
26618 "Demote subtree or insert table column.
26619 Calls `org-demote-subtree', `org-indent-item',
26620 or `org-table-insert-column', depending on context.
26621 See the individual commands for more information."
26622 (interactive)
26623 (cond
26624 ((org-at-table-p) (call-interactively 'org-table-insert-column))
26625 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
26626 ((org-at-item-p) (call-interactively 'org-indent-item))
26627 (t (org-shiftcursor-error))))
26629 (defun org-shiftmetaup (&optional arg)
26630 "Move subtree up or kill table row.
26631 Calls `org-move-subtree-up' or `org-table-kill-row' or
26632 `org-move-item-up' depending on context. See the individual commands
26633 for more information."
26634 (interactive "P")
26635 (cond
26636 ((org-at-table-p) (call-interactively 'org-table-kill-row))
26637 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26638 ((org-at-item-p) (call-interactively 'org-move-item-up))
26639 (t (org-shiftcursor-error))))
26640 (defun org-shiftmetadown (&optional arg)
26641 "Move subtree down or insert table row.
26642 Calls `org-move-subtree-down' or `org-table-insert-row' or
26643 `org-move-item-down', depending on context. See the individual
26644 commands for more information."
26645 (interactive "P")
26646 (cond
26647 ((org-at-table-p) (call-interactively 'org-table-insert-row))
26648 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26649 ((org-at-item-p) (call-interactively 'org-move-item-down))
26650 (t (org-shiftcursor-error))))
26652 (defun org-metaleft (&optional arg)
26653 "Promote heading or move table column to left.
26654 Calls `org-do-promote' or `org-table-move-column', depending on context.
26655 With no specific context, calls the Emacs default `backward-word'.
26656 See the individual commands for more information."
26657 (interactive "P")
26658 (cond
26659 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
26660 ((or (org-on-heading-p) (org-region-active-p))
26661 (call-interactively 'org-do-promote))
26662 ((org-at-item-p) (call-interactively 'org-outdent-item))
26663 (t (call-interactively 'backward-word))))
26665 (defun org-metaright (&optional arg)
26666 "Demote subtree or move table column to right.
26667 Calls `org-do-demote' or `org-table-move-column', depending on context.
26668 With no specific context, calls the Emacs default `forward-word'.
26669 See the individual commands for more information."
26670 (interactive "P")
26671 (cond
26672 ((org-at-table-p) (call-interactively 'org-table-move-column))
26673 ((or (org-on-heading-p) (org-region-active-p))
26674 (call-interactively 'org-do-demote))
26675 ((org-at-item-p) (call-interactively 'org-indent-item))
26676 (t (call-interactively 'forward-word))))
26678 (defun org-metaup (&optional arg)
26679 "Move subtree up or move table row up.
26680 Calls `org-move-subtree-up' or `org-table-move-row' or
26681 `org-move-item-up', depending on context. See the individual commands
26682 for more information."
26683 (interactive "P")
26684 (cond
26685 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
26686 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26687 ((org-at-item-p) (call-interactively 'org-move-item-up))
26688 (t (transpose-lines 1) (beginning-of-line -1))))
26690 (defun org-metadown (&optional arg)
26691 "Move subtree down or move table row down.
26692 Calls `org-move-subtree-down' or `org-table-move-row' or
26693 `org-move-item-down', depending on context. See the individual
26694 commands for more information."
26695 (interactive "P")
26696 (cond
26697 ((org-at-table-p) (call-interactively 'org-table-move-row))
26698 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26699 ((org-at-item-p) (call-interactively 'org-move-item-down))
26700 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
26702 (defun org-shiftup (&optional arg)
26703 "Increase item in timestamp or increase priority of current headline.
26704 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
26705 depending on context. See the individual commands for more information."
26706 (interactive "P")
26707 (cond
26708 ((org-at-timestamp-p t)
26709 (call-interactively (if org-edit-timestamp-down-means-later
26710 'org-timestamp-down 'org-timestamp-up)))
26711 ((org-on-heading-p) (call-interactively 'org-priority-up))
26712 ((org-at-item-p) (call-interactively 'org-previous-item))
26713 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
26715 (defun org-shiftdown (&optional arg)
26716 "Decrease item in timestamp or decrease priority of current headline.
26717 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
26718 depending on context. See the individual commands for more information."
26719 (interactive "P")
26720 (cond
26721 ((org-at-timestamp-p t)
26722 (call-interactively (if org-edit-timestamp-down-means-later
26723 'org-timestamp-up 'org-timestamp-down)))
26724 ((org-on-heading-p) (call-interactively 'org-priority-down))
26725 (t (call-interactively 'org-next-item))))
26727 (defun org-shiftright ()
26728 "Next TODO keyword or timestamp one day later, depending on context."
26729 (interactive)
26730 (cond
26731 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
26732 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
26733 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
26734 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
26735 (t (org-shiftcursor-error))))
26737 (defun org-shiftleft ()
26738 "Previous TODO keyword or timestamp one day earlier, depending on context."
26739 (interactive)
26740 (cond
26741 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
26742 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
26743 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
26744 ((org-at-property-p)
26745 (call-interactively 'org-property-previous-allowed-value))
26746 (t (org-shiftcursor-error))))
26748 (defun org-shiftcontrolright ()
26749 "Switch to next TODO set."
26750 (interactive)
26751 (cond
26752 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
26753 (t (org-shiftcursor-error))))
26755 (defun org-shiftcontrolleft ()
26756 "Switch to previous TODO set."
26757 (interactive)
26758 (cond
26759 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
26760 (t (org-shiftcursor-error))))
26762 (defun org-ctrl-c-ret ()
26763 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
26764 (interactive)
26765 (cond
26766 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
26767 (t (call-interactively 'org-insert-heading))))
26769 (defun org-copy-special ()
26770 "Copy region in table or copy current subtree.
26771 Calls `org-table-copy' or `org-copy-subtree', depending on context.
26772 See the individual commands for more information."
26773 (interactive)
26774 (call-interactively
26775 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
26777 (defun org-cut-special ()
26778 "Cut region in table or cut current subtree.
26779 Calls `org-table-copy' or `org-cut-subtree', depending on context.
26780 See the individual commands for more information."
26781 (interactive)
26782 (call-interactively
26783 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
26785 (defun org-paste-special (arg)
26786 "Paste rectangular region into table, or past subtree relative to level.
26787 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
26788 See the individual commands for more information."
26789 (interactive "P")
26790 (if (org-at-table-p)
26791 (org-table-paste-rectangle)
26792 (org-paste-subtree arg)))
26794 (defun org-ctrl-c-ctrl-c (&optional arg)
26795 "Set tags in headline, or update according to changed information at point.
26797 This command does many different things, depending on context:
26799 - If the cursor is in a headline, prompt for tags and insert them
26800 into the current line, aligned to `org-tags-column'. When called
26801 with prefix arg, realign all tags in the current buffer.
26803 - If the cursor is in one of the special #+KEYWORD lines, this
26804 triggers scanning the buffer for these lines and updating the
26805 information.
26807 - If the cursor is inside a table, realign the table. This command
26808 works even if the automatic table editor has been turned off.
26810 - If the cursor is on a #+TBLFM line, re-apply the formulas to
26811 the entire table.
26813 - If the cursor is a the beginning of a dynamic block, update it.
26815 - If the cursor is inside a table created by the table.el package,
26816 activate that table.
26818 - If the current buffer is a remember buffer, close note and file it.
26819 with a prefix argument, file it without further interaction to the default
26820 location.
26822 - If the cursor is on a <<<target>>>, update radio targets and corresponding
26823 links in this buffer.
26825 - If the cursor is on a numbered item in a plain list, renumber the
26826 ordered list.
26828 - If the cursor is on a checkbox, toggle it."
26829 (interactive "P")
26830 (let ((org-enable-table-editor t))
26831 (cond
26832 ((or org-clock-overlays
26833 org-occur-highlights
26834 org-latex-fragment-image-overlays)
26835 (org-remove-clock-overlays)
26836 (org-remove-occur-highlights)
26837 (org-remove-latex-fragment-image-overlays)
26838 (message "Temporary highlights/overlays removed from current buffer"))
26839 ((and (local-variable-p 'org-finish-function (current-buffer))
26840 (fboundp org-finish-function))
26841 (funcall org-finish-function))
26842 ((org-at-property-p)
26843 (call-interactively 'org-property-action))
26844 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
26845 ((org-on-heading-p) (call-interactively 'org-set-tags))
26846 ((org-at-table.el-p)
26847 (require 'table)
26848 (beginning-of-line 1)
26849 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
26850 (call-interactively 'table-recognize-table))
26851 ((org-at-table-p)
26852 (org-table-maybe-eval-formula)
26853 (if arg
26854 (call-interactively 'org-table-recalculate)
26855 (org-table-maybe-recalculate-line))
26856 (call-interactively 'org-table-align))
26857 ((org-at-item-checkbox-p)
26858 (call-interactively 'org-toggle-checkbox))
26859 ((org-at-item-p)
26860 (call-interactively 'org-maybe-renumber-ordered-list))
26861 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
26862 ;; Dynamic block
26863 (beginning-of-line 1)
26864 (org-update-dblock))
26865 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
26866 (cond
26867 ((equal (match-string 1) "TBLFM")
26868 ;; Recalculate the table before this line
26869 (save-excursion
26870 (beginning-of-line 1)
26871 (skip-chars-backward " \r\n\t")
26872 (if (org-at-table-p)
26873 (org-call-with-arg 'org-table-recalculate t))))
26875 (call-interactively 'org-mode-restart))))
26876 (t (error "C-c C-c can do nothing useful at this location.")))))
26878 (defun org-mode-restart ()
26879 "Restart Org-mode, to scan again for special lines.
26880 Also updates the keyword regular expressions."
26881 (interactive)
26882 (let ((org-inhibit-startup t)) (org-mode))
26883 (message "Org-mode restarted to refresh keyword and special line setup"))
26885 (defun org-kill-note-or-show-branches ()
26886 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
26887 (interactive)
26888 (if (not org-finish-function)
26889 (call-interactively 'show-branches)
26890 (let ((org-note-abort t))
26891 (funcall org-finish-function))))
26893 (defun org-return (&optional indent)
26894 "Goto next table row or insert a newline.
26895 Calls `org-table-next-row' or `newline', depending on context.
26896 See the individual commands for more information."
26897 (interactive)
26898 (cond
26899 ((bobp) (if indent (newline-and-indent) (newline)))
26900 ((org-at-table-p)
26901 (org-table-justify-field-maybe)
26902 (call-interactively 'org-table-next-row))
26903 (t (if indent (newline-and-indent) (newline)))))
26905 (defun org-return-indent ()
26906 (interactive)
26907 "Goto next table row or insert a newline and indent.
26908 Calls `org-table-next-row' or `newline-and-indent', depending on
26909 context. See the individual commands for more information."
26910 (org-return t))
26912 (defun org-ctrl-c-minus ()
26913 "Insert separator line in table or modify bullet type in list.
26914 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
26915 depending on context."
26916 (interactive)
26917 (cond
26918 ((org-at-table-p)
26919 (call-interactively 'org-table-insert-hline))
26920 ((org-on-heading-p)
26921 ;; Convert to item
26922 (save-excursion
26923 (beginning-of-line 1)
26924 (if (looking-at "\\*+ ")
26925 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
26926 ((org-in-item-p)
26927 (call-interactively 'org-cycle-list-bullet))
26928 (t (error "`C-c -' does have no function here."))))
26930 (defun org-meta-return (&optional arg)
26931 "Insert a new heading or wrap a region in a table.
26932 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
26933 See the individual commands for more information."
26934 (interactive "P")
26935 (cond
26936 ((org-at-table-p)
26937 (call-interactively 'org-table-wrap-region))
26938 (t (call-interactively 'org-insert-heading))))
26940 ;;; Menu entries
26942 ;; Define the Org-mode menus
26943 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
26944 '("Tbl"
26945 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
26946 ["Next Field" org-cycle (org-at-table-p)]
26947 ["Previous Field" org-shifttab (org-at-table-p)]
26948 ["Next Row" org-return (org-at-table-p)]
26949 "--"
26950 ["Blank Field" org-table-blank-field (org-at-table-p)]
26951 ["Edit Field" org-table-edit-field (org-at-table-p)]
26952 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
26953 "--"
26954 ("Column"
26955 ["Move Column Left" org-metaleft (org-at-table-p)]
26956 ["Move Column Right" org-metaright (org-at-table-p)]
26957 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
26958 ["Insert Column" org-shiftmetaright (org-at-table-p)])
26959 ("Row"
26960 ["Move Row Up" org-metaup (org-at-table-p)]
26961 ["Move Row Down" org-metadown (org-at-table-p)]
26962 ["Delete Row" org-shiftmetaup (org-at-table-p)]
26963 ["Insert Row" org-shiftmetadown (org-at-table-p)]
26964 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
26965 "--"
26966 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
26967 ("Rectangle"
26968 ["Copy Rectangle" org-copy-special (org-at-table-p)]
26969 ["Cut Rectangle" org-cut-special (org-at-table-p)]
26970 ["Paste Rectangle" org-paste-special (org-at-table-p)]
26971 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
26972 "--"
26973 ("Calculate"
26974 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
26975 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
26976 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
26977 "--"
26978 ["Recalculate line" org-table-recalculate (org-at-table-p)]
26979 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
26980 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
26981 "--"
26982 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
26983 "--"
26984 ["Sum Column/Rectangle" org-table-sum
26985 (or (org-at-table-p) (org-region-active-p))]
26986 ["Which Column?" org-table-current-column (org-at-table-p)])
26987 ["Debug Formulas"
26988 org-table-toggle-formula-debugger
26989 :style toggle :selected org-table-formula-debug]
26990 ["Show Col/Row Numbers"
26991 org-table-toggle-coordinate-overlays
26992 :style toggle :selected org-table-overlay-coordinates]
26993 "--"
26994 ["Create" org-table-create (and (not (org-at-table-p))
26995 org-enable-table-editor)]
26996 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
26997 ["Import from File" org-table-import (not (org-at-table-p))]
26998 ["Export to File" org-table-export (org-at-table-p)]
26999 "--"
27000 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
27002 (easy-menu-define org-org-menu org-mode-map "Org menu"
27003 '("Org"
27004 ("Show/Hide"
27005 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
27006 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
27007 ["Sparse Tree" org-occur t]
27008 ["Reveal Context" org-reveal t]
27009 ["Show All" show-all t]
27010 "--"
27011 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
27012 "--"
27013 ["New Heading" org-insert-heading t]
27014 ("Navigate Headings"
27015 ["Up" outline-up-heading t]
27016 ["Next" outline-next-visible-heading t]
27017 ["Previous" outline-previous-visible-heading t]
27018 ["Next Same Level" outline-forward-same-level t]
27019 ["Previous Same Level" outline-backward-same-level t]
27020 "--"
27021 ["Jump" org-goto t])
27022 ("Edit Structure"
27023 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
27024 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
27025 "--"
27026 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
27027 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
27028 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
27029 "--"
27030 ["Promote Heading" org-metaleft (not (org-at-table-p))]
27031 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
27032 ["Demote Heading" org-metaright (not (org-at-table-p))]
27033 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
27034 "--"
27035 ["Sort Region/Children" org-sort (not (org-at-table-p))]
27036 "--"
27037 ["Convert to odd levels" org-convert-to-odd-levels t]
27038 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
27039 ("Editing"
27040 ["Emphasis..." org-emphasize t])
27041 ("Archive"
27042 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
27043 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
27044 ; :active t :keys "C-u C-c C-x C-a"]
27045 ["Sparse trees open ARCHIVE trees"
27046 (setq org-sparse-tree-open-archived-trees
27047 (not org-sparse-tree-open-archived-trees))
27048 :style toggle :selected org-sparse-tree-open-archived-trees]
27049 ["Cycling opens ARCHIVE trees"
27050 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
27051 :style toggle :selected org-cycle-open-archived-trees]
27052 ["Agenda includes ARCHIVE trees"
27053 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
27054 :style toggle :selected (not org-agenda-skip-archived-trees)]
27055 "--"
27056 ["Move Subtree to Archive" org-advertized-archive-subtree t]
27057 ; ["Check and Move Children" (org-archive-subtree '(4))
27058 ; :active t :keys "C-u C-c C-x C-s"]
27060 "--"
27061 ("TODO Lists"
27062 ["TODO/DONE/-" org-todo t]
27063 ("Select keyword"
27064 ["Next keyword" org-shiftright (org-on-heading-p)]
27065 ["Previous keyword" org-shiftleft (org-on-heading-p)]
27066 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
27067 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
27068 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
27069 ["Show TODO Tree" org-show-todo-tree t]
27070 ["Global TODO list" org-todo-list t]
27071 "--"
27072 ["Set Priority" org-priority t]
27073 ["Priority Up" org-shiftup t]
27074 ["Priority Down" org-shiftdown t])
27075 ("TAGS and Properties"
27076 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
27077 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
27078 "--"
27079 ["Set property" 'org-set-property t]
27080 ["Column view of properties" org-columns t]
27081 ["Insert Column View DBlock" org-insert-columns-dblock t])
27082 ("Dates and Scheduling"
27083 ["Timestamp" org-time-stamp t]
27084 ["Timestamp (inactive)" org-time-stamp-inactive t]
27085 ("Change Date"
27086 ["1 Day Later" org-shiftright t]
27087 ["1 Day Earlier" org-shiftleft t]
27088 ["1 ... Later" org-shiftup t]
27089 ["1 ... Earlier" org-shiftdown t])
27090 ["Compute Time Range" org-evaluate-time-range t]
27091 ["Schedule Item" org-schedule t]
27092 ["Deadline" org-deadline t]
27093 "--"
27094 ["Custom time format" org-toggle-time-stamp-overlays
27095 :style radio :selected org-display-custom-times]
27096 "--"
27097 ["Goto Calendar" org-goto-calendar t]
27098 ["Date from Calendar" org-date-from-calendar t])
27099 ("Logging work"
27100 ["Clock in" org-clock-in t]
27101 ["Clock out" org-clock-out t]
27102 ["Clock cancel" org-clock-cancel t]
27103 ["Goto running clock" org-clock-goto t]
27104 ["Display times" org-clock-display t]
27105 ["Create clock table" org-clock-report t]
27106 "--"
27107 ["Record DONE time"
27108 (progn (setq org-log-done (not org-log-done))
27109 (message "Switching to %s will %s record a timestamp"
27110 (car org-done-keywords)
27111 (if org-log-done "automatically" "not")))
27112 :style toggle :selected org-log-done])
27113 "--"
27114 ["Agenda Command..." org-agenda t]
27115 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
27116 ("File List for Agenda")
27117 ("Special views current file"
27118 ["TODO Tree" org-show-todo-tree t]
27119 ["Check Deadlines" org-check-deadlines t]
27120 ["Timeline" org-timeline t]
27121 ["Tags Tree" org-tags-sparse-tree t])
27122 "--"
27123 ("Hyperlinks"
27124 ["Store Link (Global)" org-store-link t]
27125 ["Insert Link" org-insert-link t]
27126 ["Follow Link" org-open-at-point t]
27127 "--"
27128 ["Next link" org-next-link t]
27129 ["Previous link" org-previous-link t]
27130 "--"
27131 ["Descriptive Links"
27132 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
27133 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
27134 ["Literal Links"
27135 (progn
27136 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
27137 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
27138 "--"
27139 ["Export/Publish..." org-export t]
27140 ("LaTeX"
27141 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
27142 :selected org-cdlatex-mode]
27143 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
27144 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
27145 ["Modify math symbol" org-cdlatex-math-modify
27146 (org-inside-LaTeX-fragment-p)]
27147 ["Export LaTeX fragments as images"
27148 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
27149 :style toggle :selected org-export-with-LaTeX-fragments])
27150 "--"
27151 ("Documentation"
27152 ["Show Version" org-version t]
27153 ["Info Documentation" org-info t])
27154 ("Customize"
27155 ["Browse Org Group" org-customize t]
27156 "--"
27157 ["Expand This Menu" org-create-customize-menu
27158 (fboundp 'customize-menu-create)])
27159 "--"
27160 ["Refresh setup" org-mode-restart t]
27163 (defun org-info (&optional node)
27164 "Read documentation for Org-mode in the info system.
27165 With optional NODE, go directly to that node."
27166 (interactive)
27167 (require 'info)
27168 (Info-goto-node (format "(org)%s" (or node ""))))
27170 (defun org-install-agenda-files-menu ()
27171 (let ((bl (buffer-list)))
27172 (save-excursion
27173 (while bl
27174 (set-buffer (pop bl))
27175 (if (org-mode-p) (setq bl nil)))
27176 (when (org-mode-p)
27177 (easy-menu-change
27178 '("Org") "File List for Agenda"
27179 (append
27180 (list
27181 ["Edit File List" (org-edit-agenda-file-list) t]
27182 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
27183 ["Remove Current File from List" org-remove-file t]
27184 ["Cycle through agenda files" org-cycle-agenda-files t]
27185 ["Occur in all agenda files" org-occur-in-agenda-files t]
27186 "--")
27187 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
27189 ;;;; Documentation
27191 (defun org-customize ()
27192 "Call the customize function with org as argument."
27193 (interactive)
27194 (customize-browse 'org))
27196 (defun org-create-customize-menu ()
27197 "Create a full customization menu for Org-mode, insert it into the menu."
27198 (interactive)
27199 (if (fboundp 'customize-menu-create)
27200 (progn
27201 (easy-menu-change
27202 '("Org") "Customize"
27203 `(["Browse Org group" org-customize t]
27204 "--"
27205 ,(customize-menu-create 'org)
27206 ["Set" Custom-set t]
27207 ["Save" Custom-save t]
27208 ["Reset to Current" Custom-reset-current t]
27209 ["Reset to Saved" Custom-reset-saved t]
27210 ["Reset to Standard Settings" Custom-reset-standard t]))
27211 (message "\"Org\"-menu now contains full customization menu"))
27212 (error "Cannot expand menu (outdated version of cus-edit.el)")))
27214 ;;;; Miscellaneous stuff
27217 ;;; Generally useful functions
27219 (defun org-context ()
27220 "Return a list of contexts of the current cursor position.
27221 If several contexts apply, all are returned.
27222 Each context entry is a list with a symbol naming the context, and
27223 two positions indicating start and end of the context. Possible
27224 contexts are:
27226 :headline anywhere in a headline
27227 :headline-stars on the leading stars in a headline
27228 :todo-keyword on a TODO keyword (including DONE) in a headline
27229 :tags on the TAGS in a headline
27230 :priority on the priority cookie in a headline
27231 :item on the first line of a plain list item
27232 :item-bullet on the bullet/number of a plain list item
27233 :checkbox on the checkbox in a plain list item
27234 :table in an org-mode table
27235 :table-special on a special filed in a table
27236 :table-table in a table.el table
27237 :link on a hyperlink
27238 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
27239 :target on a <<target>>
27240 :radio-target on a <<<radio-target>>>
27241 :latex-fragment on a LaTeX fragment
27242 :latex-preview on a LaTeX fragment with overlayed preview image
27244 This function expects the position to be visible because it uses font-lock
27245 faces as a help to recognize the following contexts: :table-special, :link,
27246 and :keyword."
27247 (let* ((f (get-text-property (point) 'face))
27248 (faces (if (listp f) f (list f)))
27249 (p (point)) clist o)
27250 ;; First the large context
27251 (cond
27252 ((org-on-heading-p t)
27253 (push (list :headline (point-at-bol) (point-at-eol)) clist)
27254 (when (progn
27255 (beginning-of-line 1)
27256 (looking-at org-todo-line-tags-regexp))
27257 (push (org-point-in-group p 1 :headline-stars) clist)
27258 (push (org-point-in-group p 2 :todo-keyword) clist)
27259 (push (org-point-in-group p 4 :tags) clist))
27260 (goto-char p)
27261 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
27262 (if (looking-at "\\[#[A-Z0-9]\\]")
27263 (push (org-point-in-group p 0 :priority) clist)))
27265 ((org-at-item-p)
27266 (push (org-point-in-group p 2 :item-bullet) clist)
27267 (push (list :item (point-at-bol)
27268 (save-excursion (org-end-of-item) (point)))
27269 clist)
27270 (and (org-at-item-checkbox-p)
27271 (push (org-point-in-group p 0 :checkbox) clist)))
27273 ((org-at-table-p)
27274 (push (list :table (org-table-begin) (org-table-end)) clist)
27275 (if (memq 'org-formula faces)
27276 (push (list :table-special
27277 (previous-single-property-change p 'face)
27278 (next-single-property-change p 'face)) clist)))
27279 ((org-at-table-p 'any)
27280 (push (list :table-table) clist)))
27281 (goto-char p)
27283 ;; Now the small context
27284 (cond
27285 ((org-at-timestamp-p)
27286 (push (org-point-in-group p 0 :timestamp) clist))
27287 ((memq 'org-link faces)
27288 (push (list :link
27289 (previous-single-property-change p 'face)
27290 (next-single-property-change p 'face)) clist))
27291 ((memq 'org-special-keyword faces)
27292 (push (list :keyword
27293 (previous-single-property-change p 'face)
27294 (next-single-property-change p 'face)) clist))
27295 ((org-on-target-p)
27296 (push (org-point-in-group p 0 :target) clist)
27297 (goto-char (1- (match-beginning 0)))
27298 (if (looking-at org-radio-target-regexp)
27299 (push (org-point-in-group p 0 :radio-target) clist))
27300 (goto-char p))
27301 ((setq o (car (delq nil
27302 (mapcar
27303 (lambda (x)
27304 (if (memq x org-latex-fragment-image-overlays) x))
27305 (org-overlays-at (point))))))
27306 (push (list :latex-fragment
27307 (org-overlay-start o) (org-overlay-end o)) clist)
27308 (push (list :latex-preview
27309 (org-overlay-start o) (org-overlay-end o)) clist))
27310 ((org-inside-LaTeX-fragment-p)
27311 ;; FIXME: positions wrong.
27312 (push (list :latex-fragment (point) (point)) clist)))
27314 (setq clist (nreverse (delq nil clist)))
27315 clist))
27317 ;; FIXME: Compare with at-regexp-p Do we need both?
27318 (defun org-in-regexp (re &optional nlines visually)
27319 "Check if point is inside a match of regexp.
27320 Normally only the current line is checked, but you can include NLINES extra
27321 lines both before and after point into the search.
27322 If VISUALLY is set, require that the cursor is not after the match but
27323 really on, so that the block visually is on the match."
27324 (catch 'exit
27325 (let ((pos (point))
27326 (eol (point-at-eol (+ 1 (or nlines 0))))
27327 (inc (if visually 1 0)))
27328 (save-excursion
27329 (beginning-of-line (- 1 (or nlines 0)))
27330 (while (re-search-forward re eol t)
27331 (if (and (<= (match-beginning 0) pos)
27332 (>= (+ inc (match-end 0)) pos))
27333 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
27335 (defun org-at-regexp-p (regexp)
27336 "Is point inside a match of REGEXP in the current line?"
27337 (catch 'exit
27338 (save-excursion
27339 (let ((pos (point)) (end (point-at-eol)))
27340 (beginning-of-line 1)
27341 (while (re-search-forward regexp end t)
27342 (if (and (<= (match-beginning 0) pos)
27343 (>= (match-end 0) pos))
27344 (throw 'exit t)))
27345 nil))))
27347 (defun org-occur-in-agenda-files (regexp &optional nlines)
27348 "Call `multi-occur' with buffers for all agenda files."
27349 (interactive "sOrg-files matching: \np")
27350 (let* ((files (org-agenda-files))
27351 (tnames (mapcar 'file-truename files))
27352 (extra org-agenda-multi-occur-extra-files)
27354 (while (setq f (pop extra))
27355 (unless (member (file-truename f) tnames)
27356 (add-to-list 'files f 'append)
27357 (add-to-list 'tnames (file-truename f) 'append)))
27358 (multi-occur
27359 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
27360 regexp)))
27362 (if (boundp 'occur-mode-find-occurrence-hook)
27363 ;; Emacs 23
27364 (add-hook 'occur-mode-find-occurrence-hook
27365 (lambda ()
27366 (when (org-mode-p)
27367 (org-reveal))))
27368 ;; Emacs 22
27369 (defadvice occur-mode-goto-occurrence
27370 (after org-occur-reveal activate)
27371 (and (org-mode-p) (org-reveal)))
27372 (defadvice occur-mode-goto-occurrence-other-window
27373 (after org-occur-reveal activate)
27374 (and (org-mode-p) (org-reveal)))
27375 (defadvice occur-mode-display-occurrence
27376 (after org-occur-reveal activate)
27377 (when (org-mode-p)
27378 (let ((pos (occur-mode-find-occurrence)))
27379 (with-current-buffer (marker-buffer pos)
27380 (save-excursion
27381 (goto-char pos)
27382 (org-reveal)))))))
27384 (defun org-uniquify (list)
27385 "Remove duplicate elements from LIST."
27386 (let (res)
27387 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
27388 res))
27390 (defun org-delete-all (elts list)
27391 "Remove all elements in ELTS from LIST."
27392 (while elts
27393 (setq list (delete (pop elts) list)))
27394 list)
27396 (defun org-back-over-empty-lines ()
27397 "Move backwards over witespace, to the beginning of the first empty line.
27398 Returns the number o empty lines passed."
27399 (let ((pos (point)))
27400 (skip-chars-backward " \t\n\r")
27401 (beginning-of-line 2)
27402 (goto-char (min (point) pos))
27403 (count-lines (point) pos)))
27405 (defun org-skip-whitespace ()
27406 (skip-chars-forward " \t\n\r"))
27408 (defun org-point-in-group (point group &optional context)
27409 "Check if POINT is in match-group GROUP.
27410 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
27411 match. If the match group does ot exist or point is not inside it,
27412 return nil."
27413 (and (match-beginning group)
27414 (>= point (match-beginning group))
27415 (<= point (match-end group))
27416 (if context
27417 (list context (match-beginning group) (match-end group))
27418 t)))
27420 (defun org-switch-to-buffer-other-window (&rest args)
27421 "Switch to buffer in a second window on the current frame.
27422 In particular, do not allow pop-up frames."
27423 (let (pop-up-frames special-display-buffer-names special-display-regexps
27424 special-display-function)
27425 (apply 'switch-to-buffer-other-window args)))
27427 (defun org-combine-plists (&rest plists)
27428 "Create a single property list from all plists in PLISTS.
27429 The process starts by copying the first list, and then setting properties
27430 from the other lists. Settings in the last list are the most significant
27431 ones and overrule settings in the other lists."
27432 (let ((rtn (copy-sequence (pop plists)))
27433 p v ls)
27434 (while plists
27435 (setq ls (pop plists))
27436 (while ls
27437 (setq p (pop ls) v (pop ls))
27438 (setq rtn (plist-put rtn p v))))
27439 rtn))
27441 (defun org-move-line-down (arg)
27442 "Move the current line down. With prefix argument, move it past ARG lines."
27443 (interactive "p")
27444 (let ((col (current-column))
27445 beg end pos)
27446 (beginning-of-line 1) (setq beg (point))
27447 (beginning-of-line 2) (setq end (point))
27448 (beginning-of-line (+ 1 arg))
27449 (setq pos (move-marker (make-marker) (point)))
27450 (insert (delete-and-extract-region beg end))
27451 (goto-char pos)
27452 (move-to-column col)))
27454 (defun org-move-line-up (arg)
27455 "Move the current line up. With prefix argument, move it past ARG lines."
27456 (interactive "p")
27457 (let ((col (current-column))
27458 beg end pos)
27459 (beginning-of-line 1) (setq beg (point))
27460 (beginning-of-line 2) (setq end (point))
27461 (beginning-of-line (- arg))
27462 (setq pos (move-marker (make-marker) (point)))
27463 (insert (delete-and-extract-region beg end))
27464 (goto-char pos)
27465 (move-to-column col)))
27467 (defun org-replace-escapes (string table)
27468 "Replace %-escapes in STRING with values in TABLE.
27469 TABLE is an association list with keys like \"%a\" and string values.
27470 The sequences in STRING may contain normal field width and padding information,
27471 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
27472 so values can contain further %-escapes if they are define later in TABLE."
27473 (let ((case-fold-search nil)
27474 e re rpl)
27475 (while (setq e (pop table))
27476 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
27477 (while (string-match re string)
27478 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
27479 (cdr e)))
27480 (setq string (replace-match rpl t t string))))
27481 string))
27484 (defun org-sublist (list start end)
27485 "Return a section of LIST, from START to END.
27486 Counting starts at 1."
27487 (let (rtn (c start))
27488 (setq list (nthcdr (1- start) list))
27489 (while (and list (<= c end))
27490 (push (pop list) rtn)
27491 (setq c (1+ c)))
27492 (nreverse rtn)))
27494 (defun org-find-base-buffer-visiting (file)
27495 "Like `find-buffer-visiting' but alway return the base buffer and
27496 not an indirect buffer"
27497 (let ((buf (find-buffer-visiting file)))
27498 (if buf
27499 (or (buffer-base-buffer buf) buf)
27500 nil)))
27502 (defun org-image-file-name-regexp ()
27503 "Return regexp matching the file names of images."
27504 (if (fboundp 'image-file-name-regexp)
27505 (image-file-name-regexp)
27506 (let ((image-file-name-extensions
27507 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
27508 "xbm" "xpm" "pbm" "pgm" "ppm")))
27509 (concat "\\."
27510 (regexp-opt (nconc (mapcar 'upcase
27511 image-file-name-extensions)
27512 image-file-name-extensions)
27514 "\\'"))))
27516 (defun org-file-image-p (file)
27517 "Return non-nil if FILE is an image."
27518 (save-match-data
27519 (string-match (org-image-file-name-regexp) file)))
27521 ;;; Paragraph filling stuff.
27522 ;; We want this to be just right, so use the full arsenal.
27524 (defun org-indent-line-function ()
27525 "Indent line like previous, but further if previous was headline or item."
27526 (interactive)
27527 (let* ((pos (point))
27528 (itemp (org-at-item-p))
27529 column bpos bcol tpos tcol bullet btype bullet-type)
27530 ;; Find the previous relevant line
27531 (beginning-of-line 1)
27532 (cond
27533 ((looking-at "#") (setq column 0))
27534 ((looking-at "\\*+ ") (setq column 0))
27536 (beginning-of-line 0)
27537 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
27538 (beginning-of-line 0))
27539 (cond
27540 ((looking-at "\\*+[ \t]+")
27541 (goto-char (match-end 0))
27542 (setq column (current-column)))
27543 ((org-in-item-p)
27544 (org-beginning-of-item)
27545 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
27546 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
27547 (setq bpos (match-beginning 1) tpos (match-end 0)
27548 bcol (progn (goto-char bpos) (current-column))
27549 tcol (progn (goto-char tpos) (current-column))
27550 bullet (match-string 1)
27551 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
27552 (if (not itemp)
27553 (setq column tcol)
27554 (goto-char pos)
27555 (beginning-of-line 1)
27556 (if (looking-at "\\S-")
27557 (progn
27558 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
27559 (setq bullet (match-string 1)
27560 btype (if (string-match "[0-9]" bullet) "n" bullet))
27561 (setq column (if (equal btype bullet-type) bcol tcol)))
27562 (setq column (org-get-indentation)))))
27563 (t (setq column (org-get-indentation))))))
27564 (goto-char pos)
27565 (if (<= (current-column) (current-indentation))
27566 (indent-line-to column)
27567 (save-excursion (indent-line-to column)))
27568 (setq column (current-column))
27569 (beginning-of-line 1)
27570 (if (looking-at
27571 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
27572 (replace-match (concat "\\1" (format org-property-format
27573 (match-string 2) (match-string 3)))
27574 t nil))
27575 (move-to-column column)))
27577 (defun org-set-autofill-regexps ()
27578 (interactive)
27579 ;; In the paragraph separator we include headlines, because filling
27580 ;; text in a line directly attached to a headline would otherwise
27581 ;; fill the headline as well.
27582 (org-set-local 'comment-start-skip "^#+[ \t]*")
27583 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
27584 ;; The paragraph starter includes hand-formatted lists.
27585 (org-set-local 'paragraph-start
27586 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
27587 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
27588 ;; But only if the user has not turned off tables or fixed-width regions
27589 (org-set-local
27590 'auto-fill-inhibit-regexp
27591 (concat "\\*+ \\|#\\+"
27592 "\\|[ \t]*" org-keyword-time-regexp
27593 (if (or org-enable-table-editor org-enable-fixed-width-editor)
27594 (concat
27595 "\\|[ \t]*["
27596 (if org-enable-table-editor "|" "")
27597 (if org-enable-fixed-width-editor ":" "")
27598 "]"))))
27599 ;; We use our own fill-paragraph function, to make sure that tables
27600 ;; and fixed-width regions are not wrapped. That function will pass
27601 ;; through to `fill-paragraph' when appropriate.
27602 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
27603 ; Adaptive filling: To get full control, first make sure that
27604 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
27605 (org-set-local 'adaptive-fill-regexp "\000")
27606 (org-set-local 'adaptive-fill-function
27607 'org-adaptive-fill-function)
27608 (org-set-local
27609 'align-mode-rules-list
27610 '((org-in-buffer-settings
27611 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
27612 (modes . '(org-mode))))))
27614 (defun org-fill-paragraph (&optional justify)
27615 "Re-align a table, pass through to fill-paragraph if no table."
27616 (let ((table-p (org-at-table-p))
27617 (table.el-p (org-at-table.el-p)))
27618 (cond ((and (equal (char-after (point-at-bol)) ?*)
27619 (save-excursion (goto-char (point-at-bol))
27620 (looking-at outline-regexp)))
27621 t) ; skip headlines
27622 (table.el-p t) ; skip table.el tables
27623 (table-p (org-table-align) t) ; align org-mode tables
27624 (t nil)))) ; call paragraph-fill
27626 ;; For reference, this is the default value of adaptive-fill-regexp
27627 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
27629 (defun org-adaptive-fill-function ()
27630 "Return a fill prefix for org-mode files.
27631 In particular, this makes sure hanging paragraphs for hand-formatted lists
27632 work correctly."
27633 (cond ((looking-at "#[ \t]+")
27634 (match-string 0))
27635 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
27636 (save-excursion
27637 (goto-char (match-end 0))
27638 (make-string (current-column) ?\ )))
27639 (t nil)))
27641 ;;;; Functions extending outline functionality
27644 (defun org-beginning-of-line (&optional arg)
27645 "Go to the beginning of the current line. If that is invisible, continue
27646 to a visible line beginning. This makes the function of C-a more intuitive.
27647 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27648 first attempt, and only move to after the tags when the cursor is already
27649 beyond the end of the headline."
27650 (interactive "P")
27651 (let ((pos (point)))
27652 (beginning-of-line 1)
27653 (if (bobp)
27655 (backward-char 1)
27656 (if (org-invisible-p)
27657 (while (and (not (bobp)) (org-invisible-p))
27658 (backward-char 1)
27659 (beginning-of-line 1))
27660 (forward-char 1)))
27661 (when org-special-ctrl-a/e
27662 (cond
27663 ((and (looking-at org-todo-line-regexp)
27664 (= (char-after (match-end 1)) ?\ ))
27665 (goto-char
27666 (if (eq org-special-ctrl-a/e t)
27667 (cond ((> pos (match-beginning 3)) (match-beginning 3))
27668 ((= pos (point)) (match-beginning 3))
27669 (t (point)))
27670 (cond ((> pos (point)) (point))
27671 ((not (eq last-command this-command)) (point))
27672 (t (match-beginning 3))))))
27673 ((org-at-item-p)
27674 (goto-char
27675 (if (eq org-special-ctrl-a/e t)
27676 (cond ((> pos (match-end 4)) (match-end 4))
27677 ((= pos (point)) (match-end 4))
27678 (t (point)))
27679 (cond ((> pos (point)) (point))
27680 ((not (eq last-command this-command)) (point))
27681 (t (match-end 4))))))))))
27683 (defun org-end-of-line (&optional arg)
27684 "Go to the end of the line.
27685 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27686 first attempt, and only move to after the tags when the cursor is already
27687 beyond the end of the headline."
27688 (interactive "P")
27689 (if (or (not org-special-ctrl-a/e)
27690 (not (org-on-heading-p)))
27691 (end-of-line arg)
27692 (let ((pos (point)))
27693 (beginning-of-line 1)
27694 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
27695 (if (eq org-special-ctrl-a/e t)
27696 (if (or (< pos (match-beginning 1))
27697 (= pos (match-end 0)))
27698 (goto-char (match-beginning 1))
27699 (goto-char (match-end 0)))
27700 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
27701 (goto-char (match-end 0))
27702 (goto-char (match-beginning 1))))
27703 (end-of-line arg)))))
27705 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
27706 (define-key org-mode-map "\C-e" 'org-end-of-line)
27708 (defun org-kill-line (&optional arg)
27709 "Kill line, to tags or end of line."
27710 (interactive "P")
27711 (cond
27712 ((or (not org-special-ctrl-k)
27713 (bolp)
27714 (not (org-on-heading-p)))
27715 (call-interactively 'kill-line))
27716 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
27717 (kill-region (point) (match-beginning 1))
27718 (org-set-tags nil t))
27719 (t (kill-region (point) (point-at-eol)))))
27721 (define-key org-mode-map "\C-k" 'org-kill-line)
27723 (defun org-invisible-p ()
27724 "Check if point is at a character currently not visible."
27725 ;; Early versions of noutline don't have `outline-invisible-p'.
27726 (if (fboundp 'outline-invisible-p)
27727 (outline-invisible-p)
27728 (get-char-property (point) 'invisible)))
27730 (defun org-invisible-p2 ()
27731 "Check if point is at a character currently not visible."
27732 (save-excursion
27733 (if (and (eolp) (not (bobp))) (backward-char 1))
27734 ;; Early versions of noutline don't have `outline-invisible-p'.
27735 (if (fboundp 'outline-invisible-p)
27736 (outline-invisible-p)
27737 (get-char-property (point) 'invisible))))
27739 (defalias 'org-back-to-heading 'outline-back-to-heading)
27740 (defalias 'org-on-heading-p 'outline-on-heading-p)
27741 (defalias 'org-at-heading-p 'outline-on-heading-p)
27742 (defun org-at-heading-or-item-p ()
27743 (or (org-on-heading-p) (org-at-item-p)))
27745 (defun org-on-target-p ()
27746 (or (org-in-regexp org-radio-target-regexp)
27747 (org-in-regexp org-target-regexp)))
27749 (defun org-up-heading-all (arg)
27750 "Move to the heading line of which the present line is a subheading.
27751 This function considers both visible and invisible heading lines.
27752 With argument, move up ARG levels."
27753 (if (fboundp 'outline-up-heading-all)
27754 (outline-up-heading-all arg) ; emacs 21 version of outline.el
27755 (outline-up-heading arg t))) ; emacs 22 version of outline.el
27757 (defun org-up-heading-safe ()
27758 "Move to the heading line of which the present line is a subheading.
27759 This version will not throw an error. It will return the level of the
27760 headline found, or nil if no higher level is found."
27761 (let ((pos (point)) start-level level
27762 (re (concat "^" outline-regexp)))
27763 (catch 'exit
27764 (outline-back-to-heading t)
27765 (setq start-level (funcall outline-level))
27766 (if (equal start-level 1) (throw 'exit nil))
27767 (while (re-search-backward re nil t)
27768 (setq level (funcall outline-level))
27769 (if (< level start-level) (throw 'exit level)))
27770 nil)))
27772 (defun org-first-sibling-p ()
27773 "Is this heading the first child of its parents?"
27774 (interactive)
27775 (let ((re (concat "^" outline-regexp))
27776 level l)
27777 (unless (org-at-heading-p t)
27778 (error "Not at a heading"))
27779 (setq level (funcall outline-level))
27780 (save-excursion
27781 (if (not (re-search-backward re nil t))
27783 (setq l (funcall outline-level))
27784 (< l level)))))
27786 (defun org-goto-sibling (&optional previous)
27787 "Goto the next sibling, even if it is invisible.
27788 When PREVIOUS is set, go to the previous sibling instead. Returns t
27789 when a sibling was found. When none is found, return nil and don't
27790 move point."
27791 (let ((fun (if previous 're-search-backward 're-search-forward))
27792 (pos (point))
27793 (re (concat "^" outline-regexp))
27794 level l)
27795 (when (condition-case nil (org-back-to-heading t) (error nil))
27796 (setq level (funcall outline-level))
27797 (catch 'exit
27798 (or previous (forward-char 1))
27799 (while (funcall fun re nil t)
27800 (setq l (funcall outline-level))
27801 (when (< l level) (goto-char pos) (throw 'exit nil))
27802 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
27803 (goto-char pos)
27804 nil))))
27806 (defun org-show-siblings ()
27807 "Show all siblings of the current headline."
27808 (save-excursion
27809 (while (org-goto-sibling) (org-flag-heading nil)))
27810 (save-excursion
27811 (while (org-goto-sibling 'previous)
27812 (org-flag-heading nil))))
27814 (defun org-show-hidden-entry ()
27815 "Show an entry where even the heading is hidden."
27816 (save-excursion
27817 (org-show-entry)))
27819 (defun org-flag-heading (flag &optional entry)
27820 "Flag the current heading. FLAG non-nil means make invisible.
27821 When ENTRY is non-nil, show the entire entry."
27822 (save-excursion
27823 (org-back-to-heading t)
27824 ;; Check if we should show the entire entry
27825 (if entry
27826 (progn
27827 (org-show-entry)
27828 (save-excursion
27829 (and (outline-next-heading)
27830 (org-flag-heading nil))))
27831 (outline-flag-region (max (point-min) (1- (point)))
27832 (save-excursion (outline-end-of-heading) (point))
27833 flag))))
27835 (defun org-end-of-subtree (&optional invisible-OK to-heading)
27836 ;; This is an exact copy of the original function, but it uses
27837 ;; `org-back-to-heading', to make it work also in invisible
27838 ;; trees. And is uses an invisible-OK argument.
27839 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
27840 (org-back-to-heading invisible-OK)
27841 (let ((first t)
27842 (level (funcall outline-level)))
27843 (while (and (not (eobp))
27844 (or first (> (funcall outline-level) level)))
27845 (setq first nil)
27846 (outline-next-heading))
27847 (unless to-heading
27848 (if (memq (preceding-char) '(?\n ?\^M))
27849 (progn
27850 ;; Go to end of line before heading
27851 (forward-char -1)
27852 (if (memq (preceding-char) '(?\n ?\^M))
27853 ;; leave blank line before heading
27854 (forward-char -1))))))
27855 (point))
27857 (defun org-show-subtree ()
27858 "Show everything after this heading at deeper levels."
27859 (outline-flag-region
27860 (point)
27861 (save-excursion
27862 (outline-end-of-subtree) (outline-next-heading) (point))
27863 nil))
27865 (defun org-show-entry ()
27866 "Show the body directly following this heading.
27867 Show the heading too, if it is currently invisible."
27868 (interactive)
27869 (save-excursion
27870 (condition-case nil
27871 (progn
27872 (org-back-to-heading t)
27873 (outline-flag-region
27874 (max (point-min) (1- (point)))
27875 (save-excursion
27876 (re-search-forward
27877 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
27878 (or (match-beginning 1) (point-max)))
27879 nil))
27880 (error nil))))
27882 (defun org-make-options-regexp (kwds)
27883 "Make a regular expression for keyword lines."
27884 (concat
27886 "#?[ \t]*\\+\\("
27887 (mapconcat 'regexp-quote kwds "\\|")
27888 "\\):[ \t]*"
27889 "\\(.+\\)"))
27891 ;; Make isearch reveal the necessary context
27892 (defun org-isearch-end ()
27893 "Reveal context after isearch exits."
27894 (when isearch-success ; only if search was successful
27895 (if (featurep 'xemacs)
27896 ;; Under XEmacs, the hook is run in the correct place,
27897 ;; we directly show the context.
27898 (org-show-context 'isearch)
27899 ;; In Emacs the hook runs *before* restoring the overlays.
27900 ;; So we have to use a one-time post-command-hook to do this.
27901 ;; (Emacs 22 has a special variable, see function `org-mode')
27902 (unless (and (boundp 'isearch-mode-end-hook-quit)
27903 isearch-mode-end-hook-quit)
27904 ;; Only when the isearch was not quitted.
27905 (org-add-hook 'post-command-hook 'org-isearch-post-command
27906 'append 'local)))))
27908 (defun org-isearch-post-command ()
27909 "Remove self from hook, and show context."
27910 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
27911 (org-show-context 'isearch))
27914 ;;;; Integration with and fixes for other packages
27916 ;;; Imenu support
27918 (defvar org-imenu-markers nil
27919 "All markers currently used by Imenu.")
27920 (make-variable-buffer-local 'org-imenu-markers)
27922 (defun org-imenu-new-marker (&optional pos)
27923 "Return a new marker for use by Imenu, and remember the marker."
27924 (let ((m (make-marker)))
27925 (move-marker m (or pos (point)))
27926 (push m org-imenu-markers)
27929 (defun org-imenu-get-tree ()
27930 "Produce the index for Imenu."
27931 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
27932 (setq org-imenu-markers nil)
27933 (let* ((n org-imenu-depth)
27934 (re (concat "^" outline-regexp))
27935 (subs (make-vector (1+ n) nil))
27936 (last-level 0)
27937 m tree level head)
27938 (save-excursion
27939 (save-restriction
27940 (widen)
27941 (goto-char (point-max))
27942 (while (re-search-backward re nil t)
27943 (setq level (org-reduced-level (funcall outline-level)))
27944 (when (<= level n)
27945 (looking-at org-complex-heading-regexp)
27946 (setq head (org-match-string-no-properties 4)
27947 m (org-imenu-new-marker))
27948 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
27949 (if (>= level last-level)
27950 (push (cons head m) (aref subs level))
27951 (push (cons head (aref subs (1+ level))) (aref subs level))
27952 (loop for i from (1+ level) to n do (aset subs i nil)))
27953 (setq last-level level)))))
27954 (aref subs 1)))
27956 (eval-after-load "imenu"
27957 '(progn
27958 (add-hook 'imenu-after-jump-hook
27959 (lambda () (org-show-context 'org-goto)))))
27961 ;; Speedbar support
27963 (defun org-speedbar-set-agenda-restriction ()
27964 "Restrict future agenda commands to the location at point in speedbar.
27965 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
27966 (interactive)
27967 (let (p m tp np dir txt w)
27968 (cond
27969 ((setq p (text-property-any (point-at-bol) (point-at-eol)
27970 'org-imenu t))
27971 (setq m (get-text-property p 'org-imenu-marker))
27972 (save-excursion
27973 (save-restriction
27974 (set-buffer (marker-buffer m))
27975 (goto-char m)
27976 (org-agenda-set-restriction-lock 'subtree))))
27977 ((setq p (text-property-any (point-at-bol) (point-at-eol)
27978 'speedbar-function 'speedbar-find-file))
27979 (setq tp (previous-single-property-change
27980 (1+ p) 'speedbar-function)
27981 np (next-single-property-change
27982 tp 'speedbar-function)
27983 dir (speedbar-line-directory)
27984 txt (buffer-substring-no-properties (or tp (point-min))
27985 (or np (point-max))))
27986 (save-excursion
27987 (save-restriction
27988 (set-buffer (find-file-noselect
27989 (let ((default-directory dir))
27990 (expand-file-name txt))))
27991 (unless (org-mode-p)
27992 (error "Cannot restrict to non-Org-mode file"))
27993 (org-agenda-set-restriction-lock 'file))))
27994 (t (error "Don't know how to restrict Org-mode's agenda")))
27995 (org-move-overlay org-speedbar-restriction-lock-overlay
27996 (point-at-bol) (point-at-eol))
27997 (setq current-prefix-arg nil)
27998 (org-agenda-maybe-redo)))
28000 (eval-after-load "speedbar"
28001 '(progn
28002 (speedbar-add-supported-extension ".org")
28003 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
28004 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
28005 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
28006 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
28007 (add-hook 'speedbar-visiting-tag-hook
28008 (lambda () (org-show-context 'org-goto)))))
28011 ;;; Fixes and Hacks
28013 ;; Make flyspell not check words in links, to not mess up our keymap
28014 (defun org-mode-flyspell-verify ()
28015 "Don't let flyspell put overlays at active buttons."
28016 (not (get-text-property (point) 'keymap)))
28018 ;; Make `bookmark-jump' show the jump location if it was hidden.
28019 (eval-after-load "bookmark"
28020 '(if (boundp 'bookmark-after-jump-hook)
28021 ;; We can use the hook
28022 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
28023 ;; Hook not available, use advice
28024 (defadvice bookmark-jump (after org-make-visible activate)
28025 "Make the position visible."
28026 (org-bookmark-jump-unhide))))
28028 (defun org-bookmark-jump-unhide ()
28029 "Unhide the current position, to show the bookmark location."
28030 (and (org-mode-p)
28031 (or (org-invisible-p)
28032 (save-excursion (goto-char (max (point-min) (1- (point))))
28033 (org-invisible-p)))
28034 (org-show-context 'bookmark-jump)))
28036 ;; Fix a bug in htmlize where there are text properties (face nil)
28037 (eval-after-load "htmlize"
28038 '(progn
28039 (defadvice htmlize-faces-in-buffer (after org-no-nil-faces activate)
28040 "Make sure there are no nil faces"
28041 (setq ad-return-value (delq nil ad-return-value)))))
28043 ;; Make session.el ignore our circular variable
28044 (eval-after-load "session"
28045 '(add-to-list 'session-globals-exclude 'org-mark-ring))
28047 ;;;; Experimental code
28049 (defun org-closed-in-range ()
28050 "Sparse tree of items closed in a certain time range.
28051 Still experimental, may disappear in the future."
28052 (interactive)
28053 ;; Get the time interval from the user.
28054 (let* ((time1 (time-to-seconds
28055 (org-read-date nil 'to-time nil "Starting date: ")))
28056 (time2 (time-to-seconds
28057 (org-read-date nil 'to-time nil "End date:")))
28058 ;; callback function
28059 (callback (lambda ()
28060 (let ((time
28061 (time-to-seconds
28062 (apply 'encode-time
28063 (org-parse-time-string
28064 (match-string 1))))))
28065 ;; check if time in interval
28066 (and (>= time time1) (<= time time2))))))
28067 ;; make tree, check each match with the callback
28068 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
28072 ;(let ((org-refile-targets org-refile-targets)
28073 ; (org-refile-use-outline-path org-refile-use-outline-path))
28074 ; (when (equal just-goto '(16))
28075 ; (setq org-refile-targets '((nil . (:maxlevel . 10))))
28076 ; (setq org-refile-use-outline-path t))
28077 ; (setq org-refile-target-table (org-get-refile-targets default-buffer)))
28079 ;;;; Finish up
28081 (provide 'org)
28083 (run-hooks 'org-load-hook)
28085 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
28086 ;;; org.el ends here