Release 5.21.
[org-mode/org-tableheadings.git] / org.el
blobd5a994a30756f56a325fd4b145b528922f985187
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.21
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.21"
88 "The version number of the file org.el.")
90 (defun org-version (&optional here)
91 "Show the org-mode version in the echo area.
92 With prefix arg HERE, insert it at point."
93 (interactive "P")
94 (let ((version (format "Org-mode version %s" org-version)))
95 (message version)
96 (if here
97 (insert version))))
99 ;;; Compatibility constants
100 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
101 (defconst org-format-transports-properties-p
102 (let ((x "a"))
103 (add-text-properties 0 1 '(test t) x)
104 (get-text-property 0 'test (format "%s" x)))
105 "Does format transport text properties?")
107 (defmacro org-bound-and-true-p (var)
108 "Return the value of symbol VAR if it is bound, else nil."
109 `(and (boundp (quote ,var)) ,var))
111 (defmacro org-unmodified (&rest body)
112 "Execute body without changing `buffer-modified-p'."
113 `(set-buffer-modified-p
114 (prog1 (buffer-modified-p) ,@body)))
116 (defmacro org-re (s)
117 "Replace posix classes in regular expression."
118 (if (featurep 'xemacs)
119 (let ((ss s))
120 (save-match-data
121 (while (string-match "\\[:alnum:\\]" ss)
122 (setq ss (replace-match "a-zA-Z0-9" t t ss)))
123 (while (string-match "\\[:alpha:\\]" ss)
124 (setq ss (replace-match "a-zA-Z" t t ss)))
125 ss))
128 (defmacro org-preserve-lc (&rest body)
129 `(let ((_line (org-current-line))
130 (_col (current-column)))
131 (unwind-protect
132 (progn ,@body)
133 (goto-line _line)
134 (move-to-column _col))))
136 (defmacro org-without-partial-completion (&rest body)
137 `(let ((pc-mode (and (boundp 'partial-completion-mode)
138 partial-completion-mode)))
139 (unwind-protect
140 (progn
141 (if pc-mode (partial-completion-mode -1))
142 ,@body)
143 (if pc-mode (partial-completion-mode 1)))))
145 ;;; The custom variables
147 (defgroup org nil
148 "Outline-based notes management and organizer."
149 :tag "Org"
150 :group 'outlines
151 :group 'hypermedia
152 :group 'calendar)
154 ;; FIXME: Needs a separate group...
155 (defcustom org-completion-fallback-command 'hippie-expand
156 "The expansion command called by \\[org-complete] in normal context.
157 Normal means, no org-mode-specific context."
158 :group 'org
159 :type 'function)
161 (defgroup org-startup nil
162 "Options concerning startup of Org-mode."
163 :tag "Org Startup"
164 :group 'org)
166 (defcustom org-startup-folded t
167 "Non-nil means, entering Org-mode will switch to OVERVIEW.
168 This can also be configured on a per-file basis by adding one of
169 the following lines anywhere in the buffer:
171 #+STARTUP: fold
172 #+STARTUP: nofold
173 #+STARTUP: content"
174 :group 'org-startup
175 :type '(choice
176 (const :tag "nofold: show all" nil)
177 (const :tag "fold: overview" t)
178 (const :tag "content: all headlines" content)))
180 (defcustom org-startup-truncated t
181 "Non-nil means, entering Org-mode will set `truncate-lines'.
182 This is useful since some lines containing links can be very long and
183 uninteresting. Also tables look terrible when wrapped."
184 :group 'org-startup
185 :type 'boolean)
187 (defcustom org-startup-align-all-tables nil
188 "Non-nil means, align all tables when visiting a file.
189 This is useful when the column width in tables is forced with <N> cookies
190 in table fields. Such tables will look correct only after the first re-align.
191 This can also be configured on a per-file basis by adding one of
192 the following lines anywhere in the buffer:
193 #+STARTUP: align
194 #+STARTUP: noalign"
195 :group 'org-startup
196 :type 'boolean)
198 (defcustom org-insert-mode-line-in-empty-file nil
199 "Non-nil means insert the first line setting Org-mode in empty files.
200 When the function `org-mode' is called interactively in an empty file, this
201 normally means that the file name does not automatically trigger Org-mode.
202 To ensure that the file will always be in Org-mode in the future, a
203 line enforcing Org-mode will be inserted into the buffer, if this option
204 has been set."
205 :group 'org-startup
206 :type 'boolean)
208 (defcustom org-replace-disputed-keys nil
209 "Non-nil means use alternative key bindings for some keys.
210 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
211 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
212 If you want to use Org-mode together with one of these other modes,
213 or more generally if you would like to move some Org-mode commands to
214 other keys, set this variable and configure the keys with the variable
215 `org-disputed-keys'.
217 This option is only relevant at load-time of Org-mode, and must be set
218 *before* org.el is loaded. Changing it requires a restart of Emacs to
219 become effective."
220 :group 'org-startup
221 :type 'boolean)
223 (if (fboundp 'defvaralias)
224 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
226 (defcustom org-disputed-keys
227 '(([(shift up)] . [(meta p)])
228 ([(shift down)] . [(meta n)])
229 ([(shift left)] . [(meta -)])
230 ([(shift right)] . [(meta +)])
231 ([(control shift right)] . [(meta shift +)])
232 ([(control shift left)] . [(meta shift -)]))
233 "Keys for which Org-mode and other modes compete.
234 This is an alist, cars are the default keys, second element specifies
235 the alternative to use when `org-replace-disputed-keys' is t.
237 Keys can be specified in any syntax supported by `define-key'.
238 The value of this option takes effect only at Org-mode's startup,
239 therefore you'll have to restart Emacs to apply it after changing."
240 :group 'org-startup
241 :type 'alist)
243 (defun org-key (key)
244 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
245 Or return the original if not disputed."
246 (if org-replace-disputed-keys
247 (let* ((nkey (key-description key))
248 (x (org-find-if (lambda (x)
249 (equal (key-description (car x)) nkey))
250 org-disputed-keys)))
251 (if x (cdr x) key))
252 key))
254 (defun org-find-if (predicate seq)
255 (catch 'exit
256 (while seq
257 (if (funcall predicate (car seq))
258 (throw 'exit (car seq))
259 (pop seq)))))
261 (defun org-defkey (keymap key def)
262 "Define a key, possibly translated, as returned by `org-key'."
263 (define-key keymap (org-key key) def))
265 (defcustom org-ellipsis nil
266 "The ellipsis to use in the Org-mode outline.
267 When nil, just use the standard three dots. When a string, use that instead,
268 When a face, use the standart 3 dots, but with the specified face.
269 The change affects only Org-mode (which will then use its own display table).
270 Changing this requires executing `M-x org-mode' in a buffer to become
271 effective."
272 :group 'org-startup
273 :type '(choice (const :tag "Default" nil)
274 (face :tag "Face" :value org-warning)
275 (string :tag "String" :value "...#")))
277 (defvar org-display-table nil
278 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
280 (defgroup org-keywords nil
281 "Keywords in Org-mode."
282 :tag "Org Keywords"
283 :group 'org)
285 (defcustom org-deadline-string "DEADLINE:"
286 "String to mark deadline entries.
287 A deadline is this string, followed by a time stamp. Should be a word,
288 terminated by a colon. You can insert a schedule keyword and
289 a timestamp with \\[org-deadline].
290 Changes become only effective after restarting Emacs."
291 :group 'org-keywords
292 :type 'string)
294 (defcustom org-scheduled-string "SCHEDULED:"
295 "String to mark scheduled TODO entries.
296 A schedule is this string, followed by a time stamp. Should be a word,
297 terminated by a colon. You can insert a schedule keyword and
298 a timestamp with \\[org-schedule].
299 Changes become only effective after restarting Emacs."
300 :group 'org-keywords
301 :type 'string)
303 (defcustom org-closed-string "CLOSED:"
304 "String used as the prefix for timestamps logging closing a TODO entry."
305 :group 'org-keywords
306 :type 'string)
308 (defcustom org-clock-string "CLOCK:"
309 "String used as prefix for timestamps clocking work hours on an item."
310 :group 'org-keywords
311 :type 'string)
313 (defcustom org-comment-string "COMMENT"
314 "Entries starting with this keyword will never be exported.
315 An entry can be toggled between COMMENT and normal with
316 \\[org-toggle-comment].
317 Changes become only effective after restarting Emacs."
318 :group 'org-keywords
319 :type 'string)
321 (defcustom org-quote-string "QUOTE"
322 "Entries starting with this keyword will be exported in fixed-width font.
323 Quoting applies only to the text in the entry following the headline, and does
324 not extend beyond the next headline, even if that is lower level.
325 An entry can be toggled between QUOTE and normal with
326 \\[org-toggle-fixed-width-section]."
327 :group 'org-keywords
328 :type 'string)
330 (defconst org-repeat-re
331 ; (concat "\\(?:\\<\\(?:" org-scheduled-string "\\|" org-deadline-string "\\)"
332 ; " +<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\)\\(\\+[0-9]+[dwmy]\\)")
333 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\(\\+[0-9]+[dwmy]\\)"
334 "Regular expression for specifying repeated events.
335 After a match, group 1 contains the repeat expression.")
337 (defgroup org-structure nil
338 "Options concerning the general structure of Org-mode files."
339 :tag "Org Structure"
340 :group 'org)
342 (defgroup org-reveal-location nil
343 "Options about how to make context of a location visible."
344 :tag "Org Reveal Location"
345 :group 'org-structure)
347 (defconst org-context-choice
348 '(choice
349 (const :tag "Always" t)
350 (const :tag "Never" nil)
351 (repeat :greedy t :tag "Individual contexts"
352 (cons
353 (choice :tag "Context"
354 (const agenda)
355 (const org-goto)
356 (const occur-tree)
357 (const tags-tree)
358 (const link-search)
359 (const mark-goto)
360 (const bookmark-jump)
361 (const isearch)
362 (const default))
363 (boolean))))
364 "Contexts for the reveal options.")
366 (defcustom org-show-hierarchy-above '((default . t))
367 "Non-nil means, show full hierarchy when revealing a location.
368 Org-mode often shows locations in an org-mode file which might have
369 been invisible before. When this is set, the hierarchy of headings
370 above the exposed location is shown.
371 Turning this off for example for sparse trees makes them very compact.
372 Instead of t, this can also be an alist specifying this option for different
373 contexts. Valid contexts are
374 agenda when exposing an entry from the agenda
375 org-goto when using the command `org-goto' on key C-c C-j
376 occur-tree when using the command `org-occur' on key C-c /
377 tags-tree when constructing a sparse tree based on tags matches
378 link-search when exposing search matches associated with a link
379 mark-goto when exposing the jump goal of a mark
380 bookmark-jump when exposing a bookmark location
381 isearch when exiting from an incremental search
382 default default for all contexts not set explicitly"
383 :group 'org-reveal-location
384 :type org-context-choice)
386 (defcustom org-show-following-heading '((default . nil))
387 "Non-nil means, show following heading when revealing a location.
388 Org-mode often shows locations in an org-mode file which might have
389 been invisible before. When this is set, the heading following the
390 match is shown.
391 Turning this off for example for sparse trees makes them very compact,
392 but makes it harder to edit the location of the match. In such a case,
393 use the command \\[org-reveal] to show more context.
394 Instead of t, this can also be an alist specifying this option for different
395 contexts. See `org-show-hierarchy-above' for valid contexts."
396 :group 'org-reveal-location
397 :type org-context-choice)
399 (defcustom org-show-siblings '((default . nil) (isearch t))
400 "Non-nil means, show all sibling heading when revealing a location.
401 Org-mode often shows locations in an org-mode file which might have
402 been invisible before. When this is set, the sibling of the current entry
403 heading are all made visible. If `org-show-hierarchy-above' is t,
404 the same happens on each level of the hierarchy above the current entry.
406 By default this is on for the isearch context, off for all other contexts.
407 Turning this off for example for sparse trees makes them very compact,
408 but makes it harder to edit the location of the match. In such a case,
409 use the command \\[org-reveal] to show more context.
410 Instead of t, this can also be an alist specifying this option for different
411 contexts. See `org-show-hierarchy-above' for valid contexts."
412 :group 'org-reveal-location
413 :type org-context-choice)
415 (defcustom org-show-entry-below '((default . nil))
416 "Non-nil means, show the entry below a headline when revealing a location.
417 Org-mode often shows locations in an org-mode file which might have
418 been invisible before. When this is set, the text below the headline that is
419 exposed is also shown.
421 By default this is off for all contexts.
422 Instead of t, this can also be an alist specifying this option for different
423 contexts. See `org-show-hierarchy-above' for valid contexts."
424 :group 'org-reveal-location
425 :type org-context-choice)
427 (defgroup org-cycle nil
428 "Options concerning visibility cycling in Org-mode."
429 :tag "Org Cycle"
430 :group 'org-structure)
432 (defcustom org-drawers '("PROPERTIES" "CLOCK")
433 "Names of drawers. Drawers are not opened by cycling on the headline above.
434 Drawers only open with a TAB on the drawer line itself. A drawer looks like
435 this:
436 :DRAWERNAME:
437 .....
438 :END:
439 The drawer \"PROPERTIES\" is special for capturing properties through
440 the property API.
442 Drawers can be defined on the per-file basis with a line like:
444 #+DRAWERS: HIDDEN STATE PROPERTIES"
445 :group 'org-structure
446 :type '(repeat (string :tag "Drawer Name")))
448 (defcustom org-cycle-global-at-bob nil
449 "Cycle globally if cursor is at beginning of buffer and not at a headline.
450 This makes it possible to do global cycling without having to use S-TAB or
451 C-u TAB. For this special case to work, the first line of the buffer
452 must not be a headline - it may be empty ot some other text. When used in
453 this way, `org-cycle-hook' is disables temporarily, to make sure the
454 cursor stays at the beginning of the buffer.
455 When this option is nil, don't do anything special at the beginning
456 of the buffer."
457 :group 'org-cycle
458 :type 'boolean)
460 (defcustom org-cycle-emulate-tab t
461 "Where should `org-cycle' emulate TAB.
462 nil Never
463 white Only in completely white lines
464 whitestart Only at the beginning of lines, before the first non-white char
465 t Everywhere except in headlines
466 exc-hl-bol Everywhere except at the start of a headline
467 If TAB is used in a place where it does not emulate TAB, the current subtree
468 visibility is cycled."
469 :group 'org-cycle
470 :type '(choice (const :tag "Never" nil)
471 (const :tag "Only in completely white lines" white)
472 (const :tag "Before first char in a line" whitestart)
473 (const :tag "Everywhere except in headlines" t)
474 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
477 (defcustom org-cycle-separator-lines 2
478 "Number of empty lines needed to keep an empty line between collapsed trees.
479 If you leave an empty line between the end of a subtree and the following
480 headline, this empty line is hidden when the subtree is folded.
481 Org-mode will leave (exactly) one empty line visible if the number of
482 empty lines is equal or larger to the number given in this variable.
483 So the default 2 means, at least 2 empty lines after the end of a subtree
484 are needed to produce free space between a collapsed subtree and the
485 following headline.
487 Special case: when 0, never leave empty lines in collapsed view."
488 :group 'org-cycle
489 :type 'integer)
491 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
492 org-cycle-hide-drawers
493 org-cycle-show-empty-lines
494 org-optimize-window-after-visibility-change)
495 "Hook that is run after `org-cycle' has changed the buffer visibility.
496 The function(s) in this hook must accept a single argument which indicates
497 the new state that was set by the most recent `org-cycle' command. The
498 argument is a symbol. After a global state change, it can have the values
499 `overview', `content', or `all'. After a local state change, it can have
500 the values `folded', `children', or `subtree'."
501 :group 'org-cycle
502 :type 'hook)
504 (defgroup org-edit-structure nil
505 "Options concerning structure editing in Org-mode."
506 :tag "Org Edit Structure"
507 :group 'org-structure)
509 (defcustom org-special-ctrl-a/e nil
510 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
511 When t, `C-a' will bring back the cursor to the beginning of the
512 headline text, i.e. after the stars and after a possible TODO keyword.
513 In an item, this will be the position after the bullet.
514 When the cursor is already at that position, another `C-a' will bring
515 it to the beginning of the line.
516 `C-e' will jump to the end of the headline, ignoring the presence of tags
517 in the headline. A second `C-e' will then jump to the true end of the
518 line, after any tags.
519 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
520 and only a directly following, identical keypress will bring the cursor
521 to the special positions."
522 :group 'org-edit-structure
523 :type '(choice
524 (const :tag "off" nil)
525 (const :tag "after bullet first" t)
526 (const :tag "border first" reversed)))
528 (if (fboundp 'defvaralias)
529 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
531 (defcustom org-special-ctrl-k nil
532 "Non-nil means `C-k' will behave specially in headlines.
533 When nil, `C-k' will call the default `kill-line' command.
534 When t, the following will happen while the cursor is in the headline:
536 - When the cursor is at the beginning of a headline, kill the entire
537 line and possible the folded subtree below the line.
538 - When in the middle of the headline text, kill the headline up to the tags.
539 - When after the headline text, kill the tags."
540 :group 'org-edit-structure
541 :type 'boolean)
543 (defcustom org-odd-levels-only nil
544 "Non-nil means, skip even levels and only use odd levels for the outline.
545 This has the effect that two stars are being added/taken away in
546 promotion/demotion commands. It also influences how levels are
547 handled by the exporters.
548 Changing it requires restart of `font-lock-mode' to become effective
549 for fontification also in regions already fontified.
550 You may also set this on a per-file basis by adding one of the following
551 lines to the buffer:
553 #+STARTUP: odd
554 #+STARTUP: oddeven"
555 :group 'org-edit-structure
556 :group 'org-font-lock
557 :type 'boolean)
559 (defcustom org-adapt-indentation t
560 "Non-nil means, adapt indentation when promoting and demoting.
561 When this is set and the *entire* text in an entry is indented, the
562 indentation is increased by one space in a demotion command, and
563 decreased by one in a promotion command. If any line in the entry
564 body starts at column 0, indentation is not changed at all."
565 :group 'org-edit-structure
566 :type 'boolean)
568 (defcustom org-blank-before-new-entry '((heading . nil)
569 (plain-list-item . nil))
570 "Should `org-insert-heading' leave a blank line before new heading/item?
571 The value is an alist, with `heading' and `plain-list-item' as car,
572 and a boolean flag as cdr."
573 :group 'org-edit-structure
574 :type '(list
575 (cons (const heading) (boolean))
576 (cons (const plain-list-item) (boolean))))
578 (defcustom org-insert-heading-hook nil
579 "Hook being run after inserting a new heading."
580 :group 'org-edit-structure
581 :type 'hook)
583 (defcustom org-enable-fixed-width-editor t
584 "Non-nil means, lines starting with \":\" are treated as fixed-width.
585 This currently only means, they are never auto-wrapped.
586 When nil, such lines will be treated like ordinary lines.
587 See also the QUOTE keyword."
588 :group 'org-edit-structure
589 :type 'boolean)
591 (defcustom org-goto-auto-isearch t
592 "Non-nil means, typing characters in org-goto starts incremental search."
593 :group 'org-edit-structure
594 :type 'boolean)
596 (defgroup org-sparse-trees nil
597 "Options concerning sparse trees in Org-mode."
598 :tag "Org Sparse Trees"
599 :group 'org-structure)
601 (defcustom org-highlight-sparse-tree-matches t
602 "Non-nil means, highlight all matches that define a sparse tree.
603 The highlights will automatically disappear the next time the buffer is
604 changed by an edit command."
605 :group 'org-sparse-trees
606 :type 'boolean)
608 (defcustom org-remove-highlights-with-change t
609 "Non-nil means, any change to the buffer will remove temporary highlights.
610 Such highlights are created by `org-occur' and `org-clock-display'.
611 When nil, `C-c C-c needs to be used to get rid of the highlights.
612 The highlights created by `org-preview-latex-fragment' always need
613 `C-c C-c' to be removed."
614 :group 'org-sparse-trees
615 :group 'org-time
616 :type 'boolean)
619 (defcustom org-occur-hook '(org-first-headline-recenter)
620 "Hook that is run after `org-occur' has constructed a sparse tree.
621 This can be used to recenter the window to show as much of the structure
622 as possible."
623 :group 'org-sparse-trees
624 :type 'hook)
626 (defgroup org-plain-lists nil
627 "Options concerning plain lists in Org-mode."
628 :tag "Org Plain lists"
629 :group 'org-structure)
631 (defcustom org-cycle-include-plain-lists nil
632 "Non-nil means, include plain lists into visibility cycling.
633 This means that during cycling, plain list items will *temporarily* be
634 interpreted as outline headlines with a level given by 1000+i where i is the
635 indentation of the bullet. In all other operations, plain list items are
636 not seen as headlines. For example, you cannot assign a TODO keyword to
637 such an item."
638 :group 'org-plain-lists
639 :type 'boolean)
641 (defcustom org-plain-list-ordered-item-terminator t
642 "The character that makes a line with leading number an ordered list item.
643 Valid values are ?. and ?\). To get both terminators, use t. While
644 ?. may look nicer, it creates the danger that a line with leading
645 number may be incorrectly interpreted as an item. ?\) therefore is
646 the safe choice."
647 :group 'org-plain-lists
648 :type '(choice (const :tag "dot like in \"2.\"" ?.)
649 (const :tag "paren like in \"2)\"" ?\))
650 (const :tab "both" t)))
652 (defcustom org-auto-renumber-ordered-lists t
653 "Non-nil means, automatically renumber ordered plain lists.
654 Renumbering happens when the sequence have been changed with
655 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
656 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
657 :group 'org-plain-lists
658 :type 'boolean)
660 (defcustom org-provide-checkbox-statistics t
661 "Non-nil means, update checkbox statistics after insert and toggle.
662 When this is set, checkbox statistics is updated each time you either insert
663 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
664 with \\[org-ctrl-c-ctrl-c\\]."
665 :group 'org-plain-lists
666 :type 'boolean)
668 (defgroup org-archive nil
669 "Options concerning archiving in Org-mode."
670 :tag "Org Archive"
671 :group 'org-structure)
673 (defcustom org-archive-tag "ARCHIVE"
674 "The tag that marks a subtree as archived.
675 An archived subtree does not open during visibility cycling, and does
676 not contribute to the agenda listings.
677 After changing this, font-lock must be restarted in the relevant buffers to
678 get the proper fontification."
679 :group 'org-archive
680 :group 'org-keywords
681 :type 'string)
683 (defcustom org-agenda-skip-archived-trees t
684 "Non-nil means, the agenda will skip any items located in archived trees.
685 An archived tree is a tree marked with the tag ARCHIVE."
686 :group 'org-archive
687 :group 'org-agenda-skip
688 :type 'boolean)
690 (defcustom org-cycle-open-archived-trees nil
691 "Non-nil means, `org-cycle' will open archived trees.
692 An archived tree is a tree marked with the tag ARCHIVE.
693 When nil, archived trees will stay folded. You can still open them with
694 normal outline commands like `show-all', but not with the cycling commands."
695 :group 'org-archive
696 :group 'org-cycle
697 :type 'boolean)
699 (defcustom org-sparse-tree-open-archived-trees nil
700 "Non-nil means sparse tree construction shows matches in archived trees.
701 When nil, matches in these trees are highlighted, but the trees are kept in
702 collapsed state."
703 :group 'org-archive
704 :group 'org-sparse-trees
705 :type 'boolean)
707 (defcustom org-archive-location "%s_archive::"
708 "The location where subtrees should be archived.
709 This string consists of two parts, separated by a double-colon.
711 The first part is a file name - when omitted, archiving happens in the same
712 file. %s will be replaced by the current file name (without directory part).
713 Archiving to a different file is useful to keep archived entries from
714 contributing to the Org-mode Agenda.
716 The part after the double colon is a headline. The archived entries will be
717 filed under that headline. When omitted, the subtrees are simply filed away
718 at the end of the file, as top-level entries.
720 Here are a few examples:
721 \"%s_archive::\"
722 If the current file is Projects.org, archive in file
723 Projects.org_archive, as top-level trees. This is the default.
725 \"::* Archived Tasks\"
726 Archive in the current file, under the top-level headline
727 \"* Archived Tasks\".
729 \"~/org/archive.org::\"
730 Archive in file ~/org/archive.org (absolute path), as top-level trees.
732 \"basement::** Finished Tasks\"
733 Archive in file ./basement (relative path), as level 3 trees
734 below the level 2 heading \"** Finished Tasks\".
736 You may set this option on a per-file basis by adding to the buffer a
737 line like
739 #+ARCHIVE: basement::** Finished Tasks"
740 :group 'org-archive
741 :type 'string)
743 (defcustom org-archive-mark-done t
744 "Non-nil means, mark entries as DONE when they are moved to the archive file.
745 This can be a string to set the keyword to use. When t, Org-mode will
746 use the first keyword in its list that means done."
747 :group 'org-archive
748 :type '(choice
749 (const :tag "No" nil)
750 (const :tag "Yes" t)
751 (string :tag "Use this keyword")))
753 (defcustom org-archive-stamp-time t
754 "Non-nil means, add a time stamp to entries moved to an archive file.
755 This variable is obsolete and has no effect anymore, instead add ot remove
756 `time' from the variablle `org-archive-save-context-info'."
757 :group 'org-archive
758 :type 'boolean)
760 (defcustom org-archive-save-context-info '(time file olpath category todo itags)
761 "Parts of context info that should be stored as properties when archiving.
762 When a subtree is moved to an archive file, it looses information given by
763 context, like inherited tags, the category, and possibly also the TODO
764 state (depending on the variable `org-archive-mark-done').
765 This variable can be a list of any of the following symbols:
767 time The time of archiving.
768 file The file where the entry originates.
769 itags The local tags, in the headline of the subtree.
770 ltags The tags the subtree inherits from further up the hierarchy.
771 todo The pre-archive TODO state.
772 category The category, taken from file name or #+CATEGORY lines.
773 olpath The outline path to the item. These are all headlines above
774 the current item, separated by /, like a file path.
776 For each symbol present in the list, a property will be created in
777 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
778 information."
779 :group 'org-archive
780 :type '(set :greedy t
781 (const :tag "Time" time)
782 (const :tag "File" file)
783 (const :tag "Category" category)
784 (const :tag "TODO state" todo)
785 (const :tag "TODO state" priority)
786 (const :tag "Inherited tags" itags)
787 (const :tag "Outline path" olpath)
788 (const :tag "Local tags" ltags)))
790 (defgroup org-imenu-and-speedbar nil
791 "Options concerning imenu and speedbar in Org-mode."
792 :tag "Org Imenu and Speedbar"
793 :group 'org-structure)
795 (defcustom org-imenu-depth 2
796 "The maximum level for Imenu access to Org-mode headlines.
797 This also applied for speedbar access."
798 :group 'org-imenu-and-speedbar
799 :type 'number)
801 (defgroup org-table nil
802 "Options concerning tables in Org-mode."
803 :tag "Org Table"
804 :group 'org)
806 (defcustom org-enable-table-editor 'optimized
807 "Non-nil means, lines starting with \"|\" are handled by the table editor.
808 When nil, such lines will be treated like ordinary lines.
810 When equal to the symbol `optimized', the table editor will be optimized to
811 do the following:
812 - Automatic overwrite mode in front of whitespace in table fields.
813 This makes the structure of the table stay in tact as long as the edited
814 field does not exceed the column width.
815 - Minimize the number of realigns. Normally, the table is aligned each time
816 TAB or RET are pressed to move to another field. With optimization this
817 happens only if changes to a field might have changed the column width.
818 Optimization requires replacing the functions `self-insert-command',
819 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
820 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
821 very good at guessing when a re-align will be necessary, but you can always
822 force one with \\[org-ctrl-c-ctrl-c].
824 If you would like to use the optimized version in Org-mode, but the
825 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
827 This variable can be used to turn on and off the table editor during a session,
828 but in order to toggle optimization, a restart is required.
830 See also the variable `org-table-auto-blank-field'."
831 :group 'org-table
832 :type '(choice
833 (const :tag "off" nil)
834 (const :tag "on" t)
835 (const :tag "on, optimized" optimized)))
837 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
838 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
839 In the optimized version, the table editor takes over all simple keys that
840 normally just insert a character. In tables, the characters are inserted
841 in a way to minimize disturbing the table structure (i.e. in overwrite mode
842 for empty fields). Outside tables, the correct binding of the keys is
843 restored.
845 The default for this option is t if the optimized version is also used in
846 Org-mode. See the variable `org-enable-table-editor' for details. Changing
847 this variable requires a restart of Emacs to become effective."
848 :group 'org-table
849 :type 'boolean)
851 (defcustom orgtbl-radio-table-templates
852 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
853 % END RECEIVE ORGTBL %n
854 \\begin{comment}
855 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
856 | | |
857 \\end{comment}\n")
858 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
859 @c END RECEIVE ORGTBL %n
860 @ignore
861 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
862 | | |
863 @end ignore\n")
864 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
865 <!-- END RECEIVE ORGTBL %n -->
866 <!--
867 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
868 | | |
869 -->\n"))
870 "Templates for radio tables in different major modes.
871 All occurrences of %n in a template will be replaced with the name of the
872 table, obtained by prompting the user."
873 :group 'org-table
874 :type '(repeat
875 (list (symbol :tag "Major mode")
876 (string :tag "Format"))))
878 (defgroup org-table-settings nil
879 "Settings for tables in Org-mode."
880 :tag "Org Table Settings"
881 :group 'org-table)
883 (defcustom org-table-default-size "5x2"
884 "The default size for newly created tables, Columns x Rows."
885 :group 'org-table-settings
886 :type 'string)
888 (defcustom org-table-number-regexp
889 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
890 "Regular expression for recognizing numbers in table columns.
891 If a table column contains mostly numbers, it will be aligned to the
892 right. If not, it will be aligned to the left.
894 The default value of this option is a regular expression which allows
895 anything which looks remotely like a number as used in scientific
896 context. For example, all of the following will be considered a
897 number:
898 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
900 Other options offered by the customize interface are more restrictive."
901 :group 'org-table-settings
902 :type '(choice
903 (const :tag "Positive Integers"
904 "^[0-9]+$")
905 (const :tag "Integers"
906 "^[-+]?[0-9]+$")
907 (const :tag "Floating Point Numbers"
908 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
909 (const :tag "Floating Point Number or Integer"
910 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
911 (const :tag "Exponential, Floating point, Integer"
912 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
913 (const :tag "Very General Number-Like, including hex"
914 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
915 (string :tag "Regexp:")))
917 (defcustom org-table-number-fraction 0.5
918 "Fraction of numbers in a column required to make the column align right.
919 In a column all non-white fields are considered. If at least this
920 fraction of fields is matched by `org-table-number-fraction',
921 alignment to the right border applies."
922 :group 'org-table-settings
923 :type 'number)
925 (defgroup org-table-editing nil
926 "Behavior of tables during editing in Org-mode."
927 :tag "Org Table Editing"
928 :group 'org-table)
930 (defcustom org-table-automatic-realign t
931 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
932 When nil, aligning is only done with \\[org-table-align], or after column
933 removal/insertion."
934 :group 'org-table-editing
935 :type 'boolean)
937 (defcustom org-table-auto-blank-field t
938 "Non-nil means, automatically blank table field when starting to type into it.
939 This only happens when typing immediately after a field motion
940 command (TAB, S-TAB or RET).
941 Only relevant when `org-enable-table-editor' is equal to `optimized'."
942 :group 'org-table-editing
943 :type 'boolean)
945 (defcustom org-table-tab-jumps-over-hlines t
946 "Non-nil means, tab in the last column of a table with jump over a hline.
947 If a horizontal separator line is following the current line,
948 `org-table-next-field' can either create a new row before that line, or jump
949 over the line. When this option is nil, a new line will be created before
950 this line."
951 :group 'org-table-editing
952 :type 'boolean)
954 (defcustom org-table-tab-recognizes-table.el t
955 "Non-nil means, TAB will automatically notice a table.el table.
956 When it sees such a table, it moves point into it and - if necessary -
957 calls `table-recognize-table'."
958 :group 'org-table-editing
959 :type 'boolean)
961 (defgroup org-table-calculation nil
962 "Options concerning tables in Org-mode."
963 :tag "Org Table Calculation"
964 :group 'org-table)
966 (defcustom org-table-use-standard-references t
967 "Should org-mode work with table refrences like B3 instead of @3$2?
968 Possible values are:
969 nil never use them
970 from accept as input, do not present for editing
971 t: accept as input and present for editing"
972 :group 'org-table-calculation
973 :type '(choice
974 (const :tag "Never, don't even check unser input for them" nil)
975 (const :tag "Always, both as user input, and when editing" t)
976 (const :tag "Convert user input, don't offer during editing" 'from)))
978 (defcustom org-table-copy-increment t
979 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
980 :group 'org-table-calculation
981 :type 'boolean)
983 (defcustom org-calc-default-modes
984 '(calc-internal-prec 12
985 calc-float-format (float 5)
986 calc-angle-mode deg
987 calc-prefer-frac nil
988 calc-symbolic-mode nil
989 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
990 calc-display-working-message t
992 "List with Calc mode settings for use in calc-eval for table formulas.
993 The list must contain alternating symbols (Calc modes variables and values).
994 Don't remove any of the default settings, just change the values. Org-mode
995 relies on the variables to be present in the list."
996 :group 'org-table-calculation
997 :type 'plist)
999 (defcustom org-table-formula-evaluate-inline t
1000 "Non-nil means, TAB and RET evaluate a formula in current table field.
1001 If the current field starts with an equal sign, it is assumed to be a formula
1002 which should be evaluated as described in the manual and in the documentation
1003 string of the command `org-table-eval-formula'. This feature requires the
1004 Emacs calc package.
1005 When this variable is nil, formula calculation is only available through
1006 the command \\[org-table-eval-formula]."
1007 :group 'org-table-calculation
1008 :type 'boolean)
1010 (defcustom org-table-formula-use-constants t
1011 "Non-nil means, interpret constants in formulas in tables.
1012 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1013 by the value given in `org-table-formula-constants', or by a value obtained
1014 from the `constants.el' package."
1015 :group 'org-table-calculation
1016 :type 'boolean)
1018 (defcustom org-table-formula-constants nil
1019 "Alist with constant names and values, for use in table formulas.
1020 The car of each element is a name of a constant, without the `$' before it.
1021 The cdr is the value as a string. For example, if you'd like to use the
1022 speed of light in a formula, you would configure
1024 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1026 and then use it in an equation like `$1*$c'.
1028 Constants can also be defined on a per-file basis using a line like
1030 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
1031 :group 'org-table-calculation
1032 :type '(repeat
1033 (cons (string :tag "name")
1034 (string :tag "value"))))
1036 (defvar org-table-formula-constants-local nil
1037 "Local version of `org-table-formula-constants'.")
1038 (make-variable-buffer-local 'org-table-formula-constants-local)
1040 (defcustom org-table-allow-automatic-line-recalculation t
1041 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1042 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1043 :group 'org-table-calculation
1044 :type 'boolean)
1046 (defgroup org-link nil
1047 "Options concerning links in Org-mode."
1048 :tag "Org Link"
1049 :group 'org)
1051 (defvar org-link-abbrev-alist-local nil
1052 "Buffer-local version of `org-link-abbrev-alist', which see.
1053 The value of this is taken from the #+LINK lines.")
1054 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1056 (defcustom org-link-abbrev-alist nil
1057 "Alist of link abbreviations.
1058 The car of each element is a string, to be replaced at the start of a link.
1059 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1060 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1062 [[linkkey:tag][description]]
1064 If REPLACE is a string, the tag will simply be appended to create the link.
1065 If the string contains \"%s\", the tag will be inserted there.
1067 REPLACE may also be a function that will be called with the tag as the
1068 only argument to create the link, which should be returned as a string.
1070 See the manual for examples."
1071 :group 'org-link
1072 :type 'alist)
1074 (defcustom org-descriptive-links t
1075 "Non-nil means, hide link part and only show description of bracket links.
1076 Bracket links are like [[link][descritpion]]. This variable sets the initial
1077 state in new org-mode buffers. The setting can then be toggled on a
1078 per-buffer basis from the Org->Hyperlinks menu."
1079 :group 'org-link
1080 :type 'boolean)
1082 (defcustom org-link-file-path-type 'adaptive
1083 "How the path name in file links should be stored.
1084 Valid values are:
1086 relative Relative to the current directory, i.e. the directory of the file
1087 into which the link is being inserted.
1088 absolute Absolute path, if possible with ~ for home directory.
1089 noabbrev Absolute path, no abbreviation of home directory.
1090 adaptive Use relative path for files in the current directory and sub-
1091 directories of it. For other files, use an absolute path."
1092 :group 'org-link
1093 :type '(choice
1094 (const relative)
1095 (const absolute)
1096 (const noabbrev)
1097 (const adaptive)))
1099 (defcustom org-activate-links '(bracket angle plain radio tag date)
1100 "Types of links that should be activated in Org-mode files.
1101 This is a list of symbols, each leading to the activation of a certain link
1102 type. In principle, it does not hurt to turn on most link types - there may
1103 be a small gain when turning off unused link types. The types are:
1105 bracket The recommended [[link][description]] or [[link]] links with hiding.
1106 angular Links in angular brackes that may contain whitespace like
1107 <bbdb:Carsten Dominik>.
1108 plain Plain links in normal text, no whitespace, like http://google.com.
1109 radio Text that is matched by a radio target, see manual for details.
1110 tag Tag settings in a headline (link to tag search).
1111 date Time stamps (link to calendar).
1113 Changing this variable requires a restart of Emacs to become effective."
1114 :group 'org-link
1115 :type '(set (const :tag "Double bracket links (new style)" bracket)
1116 (const :tag "Angular bracket links (old style)" angular)
1117 (const :tag "plain text links" plain)
1118 (const :tag "Radio target matches" radio)
1119 (const :tag "Tags" tag)
1120 (const :tag "Tags" target)
1121 (const :tag "Timestamps" date)))
1123 (defgroup org-link-store nil
1124 "Options concerning storing links in Org-mode"
1125 :tag "Org Store Link"
1126 :group 'org-link)
1128 (defcustom org-email-link-description-format "Email %c: %.30s"
1129 "Format of the description part of a link to an email or usenet message.
1130 The following %-excapes will be replaced by corresponding information:
1132 %F full \"From\" field
1133 %f name, taken from \"From\" field, address if no name
1134 %T full \"To\" field
1135 %t first name in \"To\" field, address if no name
1136 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1137 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1138 %s subject
1139 %m message-id.
1141 You may use normal field width specification between the % and the letter.
1142 This is for example useful to limit the length of the subject.
1144 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1145 :group 'org-link-store
1146 :type 'string)
1148 (defcustom org-from-is-user-regexp
1149 (let (r1 r2)
1150 (when (and user-mail-address (not (string= user-mail-address "")))
1151 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1152 (when (and user-full-name (not (string= user-full-name "")))
1153 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1154 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1155 "Regexp mached against the \"From:\" header of an email or usenet message.
1156 It should match if the message is from the user him/herself."
1157 :group 'org-link-store
1158 :type 'regexp)
1160 (defcustom org-context-in-file-links t
1161 "Non-nil means, file links from `org-store-link' contain context.
1162 A search string will be added to the file name with :: as separator and
1163 used to find the context when the link is activated by the command
1164 `org-open-at-point'.
1165 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1166 negates this setting for the duration of the command."
1167 :group 'org-link-store
1168 :type 'boolean)
1170 (defcustom org-keep-stored-link-after-insertion nil
1171 "Non-nil means, keep link in list for entire session.
1173 The command `org-store-link' adds a link pointing to the current
1174 location to an internal list. These links accumulate during a session.
1175 The command `org-insert-link' can be used to insert links into any
1176 Org-mode file (offering completion for all stored links). When this
1177 option is nil, every link which has been inserted once using \\[org-insert-link]
1178 will be removed from the list, to make completing the unused links
1179 more efficient."
1180 :group 'org-link-store
1181 :type 'boolean)
1183 (defcustom org-usenet-links-prefer-google nil
1184 "Non-nil means, `org-store-link' will create web links to Google groups.
1185 When nil, Gnus will be used for such links.
1186 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1187 negates this setting for the duration of the command."
1188 :group 'org-link-store
1189 :type 'boolean)
1191 (defgroup org-link-follow nil
1192 "Options concerning following links in Org-mode"
1193 :tag "Org Follow Link"
1194 :group 'org-link)
1196 (defcustom org-tab-follows-link nil
1197 "Non-nil means, on links TAB 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-return-follows-link nil
1203 "Non-nil means, on links RET will follow the link.
1204 Needs to be set before org.el is loaded."
1205 :group 'org-link-follow
1206 :type 'boolean)
1208 (defcustom org-mouse-1-follows-link t
1209 "Non-nil means, mouse-1 on a link will follow the link.
1210 A longer mouse click will still set point. Does not wortk on XEmacs.
1211 Needs to be set before org.el is loaded."
1212 :group 'org-link-follow
1213 :type 'boolean)
1215 (defcustom org-mark-ring-length 4
1216 "Number of different positions to be recorded in the ring
1217 Changing this requires a restart of Emacs to work correctly."
1218 :group 'org-link-follow
1219 :type 'interger)
1221 (defcustom org-link-frame-setup
1222 '((vm . vm-visit-folder-other-frame)
1223 (gnus . gnus-other-frame)
1224 (file . find-file-other-window))
1225 "Setup the frame configuration for following links.
1226 When following a link with Emacs, it may often be useful to display
1227 this link in another window or frame. This variable can be used to
1228 set this up for the different types of links.
1229 For VM, use any of
1230 `vm-visit-folder'
1231 `vm-visit-folder-other-frame'
1232 For Gnus, use any of
1233 `gnus'
1234 `gnus-other-frame'
1235 For FILE, use any of
1236 `find-file'
1237 `find-file-other-window'
1238 `find-file-other-frame'
1239 For the calendar, use the variable `calendar-setup'.
1240 For BBDB, it is currently only possible to display the matches in
1241 another window."
1242 :group 'org-link-follow
1243 :type '(list
1244 (cons (const vm)
1245 (choice
1246 (const vm-visit-folder)
1247 (const vm-visit-folder-other-window)
1248 (const vm-visit-folder-other-frame)))
1249 (cons (const gnus)
1250 (choice
1251 (const gnus)
1252 (const gnus-other-frame)))
1253 (cons (const file)
1254 (choice
1255 (const find-file)
1256 (const find-file-other-window)
1257 (const find-file-other-frame)))))
1259 (defcustom org-display-internal-link-with-indirect-buffer nil
1260 "Non-nil means, use indirect buffer to display infile links.
1261 Activating internal links (from one location in a file to another location
1262 in the same file) normally just jumps to the location. When the link is
1263 activated with a C-u prefix (or with mouse-3), the link is displayed in
1264 another window. When this option is set, the other window actually displays
1265 an indirect buffer clone of the current buffer, to avoid any visibility
1266 changes to the current buffer."
1267 :group 'org-link-follow
1268 :type 'boolean)
1270 (defcustom org-open-non-existing-files nil
1271 "Non-nil means, `org-open-file' will open non-existing files.
1272 When nil, an error will be generated."
1273 :group 'org-link-follow
1274 :type 'boolean)
1276 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1277 "Function and arguments to call for following mailto links.
1278 This is a list with the first element being a lisp function, and the
1279 remaining elements being arguments to the function. In string arguments,
1280 %a will be replaced by the address, and %s will be replaced by the subject
1281 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1282 :group 'org-link-follow
1283 :type '(choice
1284 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1285 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1286 (const :tag "message-mail" (message-mail "%a" "%s"))
1287 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1289 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1290 "Non-nil means, ask for confirmation before executing shell links.
1291 Shell links can be dangerous: just think about a link
1293 [[shell:rm -rf ~/*][Google Search]]
1295 This link would show up in your Org-mode document as \"Google Search\",
1296 but really it would remove your entire home directory.
1297 Therefore we advise against setting this variable to nil.
1298 Just change it to `y-or-n-p' of you want to confirm with a
1299 single keystroke rather than having to type \"yes\"."
1300 :group 'org-link-follow
1301 :type '(choice
1302 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1303 (const :tag "with y-or-n (faster)" y-or-n-p)
1304 (const :tag "no confirmation (dangerous)" nil)))
1306 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1307 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1308 Elisp links can be dangerous: just think about a link
1310 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1312 This link would show up in your Org-mode document as \"Google Search\",
1313 but really it would remove your entire home directory.
1314 Therefore we advise against setting this variable to nil.
1315 Just change it to `y-or-n-p' of you want to confirm with a
1316 single keystroke rather than having to type \"yes\"."
1317 :group 'org-link-follow
1318 :type '(choice
1319 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1320 (const :tag "with y-or-n (faster)" y-or-n-p)
1321 (const :tag "no confirmation (dangerous)" nil)))
1323 (defconst org-file-apps-defaults-gnu
1324 '((remote . emacs)
1325 (t . mailcap))
1326 "Default file applications on a UNIX or GNU/Linux system.
1327 See `org-file-apps'.")
1329 (defconst org-file-apps-defaults-macosx
1330 '((remote . emacs)
1331 (t . "open %s")
1332 ("ps" . "gv %s")
1333 ("ps.gz" . "gv %s")
1334 ("eps" . "gv %s")
1335 ("eps.gz" . "gv %s")
1336 ("dvi" . "xdvi %s")
1337 ("fig" . "xfig %s"))
1338 "Default file applications on a MacOS X system.
1339 The system \"open\" is known as a default, but we use X11 applications
1340 for some files for which the OS does not have a good default.
1341 See `org-file-apps'.")
1343 (defconst org-file-apps-defaults-windowsnt
1344 (list
1345 '(remote . emacs)
1346 (cons t
1347 (list (if (featurep 'xemacs)
1348 'mswindows-shell-execute
1349 'w32-shell-execute)
1350 "open" 'file)))
1351 "Default file applications on a Windows NT system.
1352 The system \"open\" is used for most files.
1353 See `org-file-apps'.")
1355 (defcustom org-file-apps
1357 ("txt" . emacs)
1358 ("tex" . emacs)
1359 ("ltx" . emacs)
1360 ("org" . emacs)
1361 ("el" . emacs)
1362 ("bib" . emacs)
1364 "External applications for opening `file:path' items in a document.
1365 Org-mode uses system defaults for different file types, but
1366 you can use this variable to set the application for a given file
1367 extension. The entries in this list are cons cells where the car identifies
1368 files and the cdr the corresponding command. Possible values for the
1369 file identifier are
1370 \"ext\" A string identifying an extension
1371 `directory' Matches a directory
1372 `remote' Matches a remote file, accessible through tramp or efs.
1373 Remote files most likely should be visited through Emacs
1374 because external applications cannot handle such paths.
1375 t Default for all remaining files
1377 Possible values for the command are:
1378 `emacs' The file will be visited by the current Emacs process.
1379 `default' Use the default application for this file type.
1380 string A command to be executed by a shell; %s will be replaced
1381 by the path to the file.
1382 sexp A Lisp form which will be evaluated. The file path will
1383 be available in the Lisp variable `file'.
1384 For more examples, see the system specific constants
1385 `org-file-apps-defaults-macosx'
1386 `org-file-apps-defaults-windowsnt'
1387 `org-file-apps-defaults-gnu'."
1388 :group 'org-link-follow
1389 :type '(repeat
1390 (cons (choice :value ""
1391 (string :tag "Extension")
1392 (const :tag "Default for unrecognized files" t)
1393 (const :tag "Remote file" remote)
1394 (const :tag "Links to a directory" directory))
1395 (choice :value ""
1396 (const :tag "Visit with Emacs" emacs)
1397 (const :tag "Use system default" default)
1398 (string :tag "Command")
1399 (sexp :tag "Lisp form")))))
1401 (defcustom org-mhe-search-all-folders nil
1402 "Non-nil means, that the search for the mh-message will be extended to
1403 all folders if the message cannot be found in the folder given in the link.
1404 Searching all folders is very efficient with one of the search engines
1405 supported by MH-E, but will be slow with pick."
1406 :group 'org-link-follow
1407 :type 'boolean)
1409 (defgroup org-remember nil
1410 "Options concerning interaction with remember.el."
1411 :tag "Org Remember"
1412 :group 'org)
1414 (defcustom org-directory "~/org"
1415 "Directory with org files.
1416 This directory will be used as default to prompt for org files.
1417 Used by the hooks for remember.el."
1418 :group 'org-remember
1419 :type 'directory)
1421 (defcustom org-default-notes-file "~/.notes"
1422 "Default target for storing notes.
1423 Used by the hooks for remember.el. This can be a string, or nil to mean
1424 the value of `remember-data-file'.
1425 You can set this on a per-template basis with the variable
1426 `org-remember-templates'."
1427 :group 'org-remember
1428 :type '(choice
1429 (const :tag "Default from remember-data-file" nil)
1430 file))
1432 (defcustom org-remember-store-without-prompt t
1433 "Non-nil means, `C-c C-c' stores remember note without further promts.
1434 In this case, you need `C-u C-c C-c' to get the prompts for
1435 note file and headline.
1436 When this variable is nil, `C-c C-c' give you the prompts, and
1437 `C-u C-c C-c' trigger the fasttrack."
1438 :group 'org-remember
1439 :type 'boolean)
1441 (defcustom org-remember-interactive-interface 'refile
1442 "The interface to be used for interactive filing of remember notes.
1443 This is only used when the interactive mode for selecting a filing
1444 location is used (see the variable `org-remember-store-without-prompt').
1445 Allowed vaues are:
1446 outline The interface shows an outline of the relevant file
1447 and the correct heading is found by moving through
1448 the outline or by searching with incremental search.
1449 outline-path-completion Headlines in the current buffer are offered via
1450 completion.
1451 refile Use the refile interface, and offer headlines,
1452 possibly from different buffers."
1453 :group 'org-remember
1454 :type '(choice
1455 (const :tag "Refile" refile)
1456 (const :tag "Outline" outline)
1457 (const :tag "Outline-path-completion" outline-path-completion)))
1459 (defcustom org-goto-interface 'outline
1460 "The default interface to be used for `org-goto'.
1461 Allowed vaues are:
1462 outline The interface shows an outline of the relevant file
1463 and the correct heading is found by moving through
1464 the outline or by searching with incremental search.
1465 outline-path-completion Headlines in the current buffer are offered via
1466 completion."
1467 :group 'org-remember ; FIXME: different group for org-goto and org-refile
1468 :type '(choice
1469 (const :tag "Outline" outline)
1470 (const :tag "Outline-path-completion" outline-path-completion)))
1472 (defcustom org-remember-default-headline ""
1473 "The headline that should be the default location in the notes file.
1474 When filing remember notes, the cursor will start at that position.
1475 You can set this on a per-template basis with the variable
1476 `org-remember-templates'."
1477 :group 'org-remember
1478 :type 'string)
1480 (defcustom org-remember-templates nil
1481 "Templates for the creation of remember buffers.
1482 When nil, just let remember make the buffer.
1483 When not nil, this is a list of 5-element lists. In each entry, the first
1484 element is the name of the template, which should be a single short word.
1485 The second element is a character, a unique key to select this template.
1486 The third element is the template. The fourth element is optional and can
1487 specify a destination file for remember items created with this template.
1488 The default file is given by `org-default-notes-file'. An optional fifth
1489 element can specify the headline in that file that should be offered
1490 first when the user is asked to file the entry. The default headline is
1491 given in the variable `org-remember-default-headline'.
1493 The template specifies the structure of the remember buffer. It should have
1494 a first line starting with a star, to act as the org-mode headline.
1495 Furthermore, the following %-escapes will be replaced with content:
1497 %^{prompt} Prompt the user for a string and replace this sequence with it.
1498 A default value and a completion table ca be specified like this:
1499 %^{prompt|default|completion2|completion3|...}
1500 %t time stamp, date only
1501 %T time stamp with date and time
1502 %u, %U like the above, but inactive time stamps
1503 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1504 You may define a prompt like %^{Please specify birthday}t
1505 %n user name (taken from `user-full-name')
1506 %a annotation, normally the link created with org-store-link
1507 %i initial content, the region when remember is called with C-u.
1508 If %i is indented, the entire inserted text will be indented
1509 as well.
1510 %c content of the clipboard, or current kill ring head
1511 %^g prompt for tags, with completion on tags in target file
1512 %^G prompt for tags, with completion all tags in all agenda files
1513 %:keyword specific information for certain link types, see below
1514 %[pathname] insert the contents of the file given by `pathname'
1515 %(sexp) evaluate elisp `(sexp)' and replace with the result
1516 %! Store this note immediately after filling the template
1518 %? After completing the template, position cursor here.
1520 Apart from these general escapes, you can access information specific to the
1521 link type that is created. For example, calling `remember' in emails or gnus
1522 will record the author and the subject of the message, which you can access
1523 with %:author and %:subject, respectively. Here is a complete list of what
1524 is recorded for each link type.
1526 Link type | Available information
1527 -------------------+------------------------------------------------------
1528 bbdb | %:type %:name %:company
1529 vm, wl, mh, rmail | %:type %:subject %:message-id
1530 | %:from %:fromname %:fromaddress
1531 | %:to %:toname %:toaddress
1532 | %:fromto (either \"to NAME\" or \"from NAME\")
1533 gnus | %:group, for messages also all email fields
1534 w3, w3m | %:type %:url
1535 info | %:type %:file %:node
1536 calendar | %:type %:date"
1537 :group 'org-remember
1538 :get (lambda (var) ; Make sure all entries have 5 elements
1539 (mapcar (lambda (x)
1540 (if (not (stringp (car x))) (setq x (cons "" x)))
1541 (cond ((= (length x) 4) (append x '("")))
1542 ((= (length x) 3) (append x '("" "")))
1543 (t x)))
1544 (default-value var)))
1545 :type '(repeat
1546 :tag "enabled"
1547 (list :value ("" ?a "\n" nil nil)
1548 (string :tag "Name")
1549 (character :tag "Selection Key")
1550 (string :tag "Template")
1551 (choice
1552 (file :tag "Destination file")
1553 (const :tag "Prompt for file" nil))
1554 (choice
1555 (string :tag "Destination headline")
1556 (const :tag "Selection interface for heading")))))
1558 (defcustom org-reverse-note-order nil
1559 "Non-nil means, store new notes at the beginning of a file or entry.
1560 When nil, new notes will be filed to the end of a file or entry.
1561 This can also be a list with cons cells of regular expressions that
1562 are matched against file names, and values."
1563 :group 'org-remember
1564 :type '(choice
1565 (const :tag "Reverse always" t)
1566 (const :tag "Reverse never" nil)
1567 (repeat :tag "By file name regexp"
1568 (cons regexp boolean))))
1570 (defcustom org-refile-targets nil
1571 "Targets for refiling entries with \\[org-refile].
1572 This is list of cons cells. Each cell contains:
1573 - a specification of the files to be considered, either a list of files,
1574 or a symbol whose function or value fields will be used to retrieve
1575 a file name or a list of file names. Nil means, refile to a different
1576 heading in the current buffer.
1577 - A specification of how to find candidate refile targets. This may be
1578 any of
1579 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1580 This tag has to be present in all target headlines, inheritance will
1581 not be considered.
1582 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1583 todo keyword.
1584 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1585 headlines that are refiling targets.
1586 - a cons cell (:level . N). Any headline of level N is considered a target.
1587 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1588 ;; FIXME: what if there are a var and func with same name???
1589 :group 'org-remember
1590 :type '(repeat
1591 (cons
1592 (choice :value org-agenda-files
1593 (const :tag "All agenda files" org-agenda-files)
1594 (const :tag "Current buffer" nil)
1595 (function) (variable) (file))
1596 (choice :tag "Identify target headline by"
1597 (cons :tag "Specific tag" (const :tag) (string))
1598 (cons :tag "TODO keyword" (const :todo) (string))
1599 (cons :tag "Regular expression" (const :regexp) (regexp))
1600 (cons :tag "Level number" (const :level) (integer))
1601 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1603 (defcustom org-refile-use-outline-path nil
1604 "Non-nil means, provide refile targets as paths.
1605 So a level 3 headline will be available as level1/level2/level3.
1606 When the value is `file', also include the file name (without directory)
1607 into the path. When `full-file-path', include the full file path."
1608 :group 'org-remember
1609 :type '(choice
1610 (const :tag "Not" nil)
1611 (const :tag "Yes" t)
1612 (const :tag "Start with file name" file)
1613 (const :tag "Start with full file path" full-file-path)))
1615 (defgroup org-todo nil
1616 "Options concerning TODO items in Org-mode."
1617 :tag "Org TODO"
1618 :group 'org)
1620 (defgroup org-progress nil
1621 "Options concerning Progress logging in Org-mode."
1622 :tag "Org Progress"
1623 :group 'org-time)
1625 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1626 "List of TODO entry keyword sequences and their interpretation.
1627 \\<org-mode-map>This is a list of sequences.
1629 Each sequence starts with a symbol, either `sequence' or `type',
1630 indicating if the keywords should be interpreted as a sequence of
1631 action steps, or as different types of TODO items. The first
1632 keywords are states requiring action - these states will select a headline
1633 for inclusion into the global TODO list Org-mode produces. If one of
1634 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1635 signify that no further action is necessary. If \"|\" is not found,
1636 the last keyword is treated as the only DONE state of the sequence.
1638 The command \\[org-todo] cycles an entry through these states, and one
1639 additional state where no keyword is present. For details about this
1640 cycling, see the manual.
1642 TODO keywords and interpretation can also be set on a per-file basis with
1643 the special #+SEQ_TODO and #+TYP_TODO lines.
1645 For backward compatibility, this variable may also be just a list
1646 of keywords - in this case the interptetation (sequence or type) will be
1647 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1648 :group 'org-todo
1649 :group 'org-keywords
1650 :type '(choice
1651 (repeat :tag "Old syntax, just keywords"
1652 (string :tag "Keyword"))
1653 (repeat :tag "New syntax"
1654 (cons
1655 (choice
1656 :tag "Interpretation"
1657 (const :tag "Sequence (cycling hits every state)" sequence)
1658 (const :tag "Type (cycling directly to DONE)" type))
1659 (repeat
1660 (string :tag "Keyword"))))))
1662 (defvar org-todo-keywords-1 nil)
1663 (make-variable-buffer-local 'org-todo-keywords-1)
1664 (defvar org-todo-keywords-for-agenda nil)
1665 (defvar org-done-keywords-for-agenda nil)
1666 (defvar org-not-done-keywords nil)
1667 (make-variable-buffer-local 'org-not-done-keywords)
1668 (defvar org-done-keywords nil)
1669 (make-variable-buffer-local 'org-done-keywords)
1670 (defvar org-todo-heads nil)
1671 (make-variable-buffer-local 'org-todo-heads)
1672 (defvar org-todo-sets nil)
1673 (make-variable-buffer-local 'org-todo-sets)
1674 (defvar org-todo-log-states nil)
1675 (make-variable-buffer-local 'org-todo-log-states)
1676 (defvar org-todo-kwd-alist nil)
1677 (make-variable-buffer-local 'org-todo-kwd-alist)
1678 (defvar org-todo-key-alist nil)
1679 (make-variable-buffer-local 'org-todo-key-alist)
1680 (defvar org-todo-key-trigger nil)
1681 (make-variable-buffer-local 'org-todo-key-trigger)
1683 (defcustom org-todo-interpretation 'sequence
1684 "Controls how TODO keywords are interpreted.
1685 This variable is in principle obsolete and is only used for
1686 backward compatibility, if the interpretation of todo keywords is
1687 not given already in `org-todo-keywords'. See that variable for
1688 more information."
1689 :group 'org-todo
1690 :group 'org-keywords
1691 :type '(choice (const sequence)
1692 (const type)))
1694 (defcustom org-use-fast-todo-selection 'prefix
1695 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1696 This variable describes if and under what circumstances the cycling
1697 mechanism for TODO keywords will be replaced by a single-key, direct
1698 selection scheme.
1700 When nil, fast selection is never used.
1702 When the symbol `prefix', it will be used when `org-todo' is called with
1703 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1704 in an agenda buffer.
1706 When t, fast selection is used by default. In this case, the prefix
1707 argument forces cycling instead.
1709 In all cases, the special interface is only used if access keys have actually
1710 been assigned by the user, i.e. if keywords in the configuration are followed
1711 by a letter in parenthesis, like TODO(t)."
1712 :group 'org-todo
1713 :type '(choice
1714 (const :tag "Never" nil)
1715 (const :tag "By default" t)
1716 (const :tag "Only with C-u C-c C-t" prefix)))
1718 (defcustom org-after-todo-state-change-hook nil
1719 "Hook which is run after the state of a TODO item was changed.
1720 The new state (a string with a TODO keyword, or nil) is available in the
1721 Lisp variable `state'."
1722 :group 'org-todo
1723 :type 'hook)
1725 (defcustom org-log-done nil
1726 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1727 When the state of an entry is changed from nothing or a DONE state to
1728 a not-done TODO state, remove a previous closing date.
1730 This can also be a list of symbols indicating under which conditions
1731 the time stamp recording the action should be annotated with a short note.
1732 Valid members of this list are
1734 done Offer to record a note when marking entries done
1735 state Offer to record a note whenever changing the TODO state
1736 of an item. This is only relevant if TODO keywords are
1737 interpreted as sequence, see variable `org-todo-interpretation'.
1738 When `state' is set, this includes tracking `done'.
1739 clock-out Offer to record a note when clocking out of an item.
1741 A separate window will then pop up and allow you to type a note.
1742 After finishing with C-c C-c, the note will be added directly after the
1743 timestamp, as a plain list item. See also the variable
1744 `org-log-note-headings'.
1746 Logging can also be configured on a per-file basis by adding one of
1747 the following lines anywhere in the buffer:
1749 #+STARTUP: logdone
1750 #+STARTUP: nologging
1751 #+STARTUP: lognotedone
1752 #+STARTUP: lognotestate
1753 #+STARTUP: lognoteclock-out
1755 You can have local logging settings for a subtree by setting the LOGGING
1756 property to one or more of these keywords."
1757 :group 'org-todo
1758 :group 'org-progress
1759 :type '(choice
1760 (const :tag "off" nil)
1761 (const :tag "on" t)
1762 (set :tag "on, with notes, detailed control" :greedy t :value (done)
1763 (const :tag "when item is marked DONE" done)
1764 (const :tag "when TODO state changes" state)
1765 (const :tag "when clocking out" clock-out))))
1767 (defcustom org-log-done-with-time t
1768 "Non-nil means, the CLOSED time stamp will contain date and time.
1769 When nil, only the date will be recorded."
1770 :group 'org-progress
1771 :type 'boolean)
1773 (defcustom org-log-note-headings
1774 '((done . "CLOSING NOTE %t")
1775 (state . "State %-12s %t")
1776 (clock-out . ""))
1777 "Headings for notes added when clocking out or closing TODO items.
1778 The value is an alist, with the car being a symbol indicating the note
1779 context, and the cdr is the heading to be used. The heading may also be the
1780 empty string.
1781 %t in the heading will be replaced by a time stamp.
1782 %s will be replaced by the new TODO state, in double quotes.
1783 %u will be replaced by the user name.
1784 %U will be replaced by the full user name."
1785 :group 'org-todo
1786 :group 'org-progress
1787 :type '(list :greedy t
1788 (cons (const :tag "Heading when closing an item" done) string)
1789 (cons (const :tag
1790 "Heading when changing todo state (todo sequence only)"
1791 state) string)
1792 (cons (const :tag "Heading when clocking out" clock-out) string)))
1794 (defcustom org-log-states-order-reversed t
1795 "Non-nil means, the latest state change note will be directly after heading.
1796 When nil, the notes will be orderer according to time."
1797 :group 'org-todo
1798 :group 'org-progress
1799 :type 'boolean)
1801 (defcustom org-log-repeat t
1802 "Non-nil means, prompt for a note when REPEAT is resetting a TODO entry.
1803 When nil, no note will be taken.
1804 This option can also be set with on a per-file-basis with
1806 #+STARTUP: logrepeat
1807 #+STARTUP: nologrepeat
1809 You can have local logging settings for a subtree by setting the LOGGING
1810 property to one or more of these keywords."
1811 :group 'org-todo
1812 :group 'org-progress
1813 :type 'boolean)
1815 (defcustom org-clock-into-drawer 2
1816 "Should clocking info be wrapped into a drawer?
1817 When t, clocking info will always be inserted into a :CLOCK: drawer.
1818 If necessary, the drawer will be created.
1819 When nil, the drawer will not be created, but used when present.
1820 When an integer and the number of clocking entries in an item
1821 reaches or exceeds this number, a drawer will be created."
1822 :group 'org-todo
1823 :group 'org-progress
1824 :type '(choice
1825 (const :tag "Always" t)
1826 (const :tag "Only when drawer exists" nil)
1827 (integer :tag "When at least N clock entries")))
1829 (defcustom org-clock-out-when-done t
1830 "When t, the clock will be stopped when the relevant entry is marked DONE.
1831 Nil means, clock will keep running until stopped explicitly with
1832 `C-c C-x C-o', or until the clock is started in a different item."
1833 :group 'org-progress
1834 :type 'boolean)
1836 (defcustom org-clock-in-switch-to-state nil
1837 "Set task to a special todo state while clocking it.
1838 The value should be the state to which the entry should be switched."
1839 :group 'org-progress
1840 :group 'org-todo
1841 :type '(choice
1842 (const :tag "Don't force a state" nil)
1843 (string :tag "State")))
1845 (defgroup org-priorities nil
1846 "Priorities in Org-mode."
1847 :tag "Org Priorities"
1848 :group 'org-todo)
1850 (defcustom org-highest-priority ?A
1851 "The highest priority of TODO items. A character like ?A, ?B etc.
1852 Must have a smaller ASCII number than `org-lowest-priority'."
1853 :group 'org-priorities
1854 :type 'character)
1856 (defcustom org-lowest-priority ?C
1857 "The lowest priority of TODO items. A character like ?A, ?B etc.
1858 Must have a larger ASCII number than `org-highest-priority'."
1859 :group 'org-priorities
1860 :type 'character)
1862 (defcustom org-default-priority ?B
1863 "The default priority of TODO items.
1864 This is the priority an item get if no explicit priority is given."
1865 :group 'org-priorities
1866 :type 'character)
1868 (defcustom org-priority-start-cycle-with-default t
1869 "Non-nil means, start with default priority when starting to cycle.
1870 When this is nil, the first step in the cycle will be (depending on the
1871 command used) one higher or lower that the default priority."
1872 :group 'org-priorities
1873 :type 'boolean)
1875 (defgroup org-time nil
1876 "Options concerning time stamps and deadlines in Org-mode."
1877 :tag "Org Time"
1878 :group 'org)
1880 (defcustom org-insert-labeled-timestamps-at-point nil
1881 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1882 When nil, these labeled time stamps are forces into the second line of an
1883 entry, just after the headline. When scheduling from the global TODO list,
1884 the time stamp will always be forced into the second line."
1885 :group 'org-time
1886 :type 'boolean)
1888 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1889 "Formats for `format-time-string' which are used for time stamps.
1890 It is not recommended to change this constant.")
1892 (defcustom org-time-stamp-rounding-minutes 0
1893 "Number of minutes to round time stamps to upon insertion.
1894 When zero, insert the time unmodified. Useful rounding numbers
1895 should be factors of 60, so for example 5, 10, 15.
1896 When this is not zero, you can still force an exact time-stamp by using
1897 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1898 :group 'org-time
1899 :type 'integer)
1901 (defcustom org-display-custom-times nil
1902 "Non-nil means, overlay custom formats over all time stamps.
1903 The formats are defined through the variable `org-time-stamp-custom-formats'.
1904 To turn this on on a per-file basis, insert anywhere in the file:
1905 #+STARTUP: customtime"
1906 :group 'org-time
1907 :set 'set-default
1908 :type 'sexp)
1909 (make-variable-buffer-local 'org-display-custom-times)
1911 (defcustom org-time-stamp-custom-formats
1912 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1913 "Custom formats for time stamps. See `format-time-string' for the syntax.
1914 These are overlayed over the default ISO format if the variable
1915 `org-display-custom-times' is set. Time like %H:%M should be at the
1916 end of the second format."
1917 :group 'org-time
1918 :type 'sexp)
1920 (defun org-time-stamp-format (&optional long inactive)
1921 "Get the right format for a time string."
1922 (let ((f (if long (cdr org-time-stamp-formats)
1923 (car org-time-stamp-formats))))
1924 (if inactive
1925 (concat "[" (substring f 1 -1) "]")
1926 f)))
1928 (defcustom org-read-date-prefer-future t
1929 "Non-nil means, assume future for incomplete date input from user.
1930 This affects the following situations:
1931 1. The user gives a day, but no month.
1932 For example, if today is the 15th, and you enter \"3\", Org-mode will
1933 read this as the third of *next* month. However, if you enter \"17\",
1934 it will be considered as *this* month.
1935 2. The user gives a month but not a year.
1936 For example, if it is april and you enter \"feb 2\", this will be read
1937 as feb 2, *next* year. \"May 5\", however, will be this year.
1939 When this option is nil, the current month and year will always be used
1940 as defaults."
1941 :group 'org-time
1942 :type 'boolean)
1944 (defcustom org-read-date-display-live t
1945 "Non-nil means, display current interpretation of date prompt live.
1946 This display will be in an overlay, in the minibuffer."
1947 :group 'org-time
1948 :type 'boolean)
1950 (defcustom org-read-date-popup-calendar t
1951 "Non-nil means, pop up a calendar when prompting for a date.
1952 In the calendar, the date can be selected with mouse-1. However, the
1953 minibuffer will also be active, and you can simply enter the date as well.
1954 When nil, only the minibuffer will be available."
1955 :group 'org-time
1956 :type 'boolean)
1957 (if (fboundp 'defvaralias)
1958 (defvaralias 'org-popup-calendar-for-date-prompt
1959 'org-read-date-popup-calendar))
1961 (defcustom org-extend-today-until 0
1962 "The hour when your day really ends.
1963 This has influence for the following applications:
1964 - When switching the agenda to \"today\". It it is still earlier than
1965 the time given here, the day recognized as TODAY is actually yesterday.
1966 - When a date is read from the user and it is still before the time given
1967 here, the current date and time will be assumed to be yesterday, 23:59.
1969 FIXME:
1970 IMPORTANT: This is still a very experimental feature, it may disappear
1971 again or it may be extended to mean more things."
1972 :group 'org-time
1973 :type 'number)
1975 (defcustom org-edit-timestamp-down-means-later nil
1976 "Non-nil means, S-down will increase the time in a time stamp.
1977 When nil, S-up will increase."
1978 :group 'org-time
1979 :type 'boolean)
1981 (defcustom org-calendar-follow-timestamp-change t
1982 "Non-nil means, make the calendar window follow timestamp changes.
1983 When a timestamp is modified and the calendar window is visible, it will be
1984 moved to the new date."
1985 :group 'org-time
1986 :type 'boolean)
1988 (defcustom org-clock-heading-function nil
1989 "When non-nil, should be a function to create `org-clock-heading'.
1990 This is the string shown in the mode line when a clock is running.
1991 The function is called with point at the beginning of the headline."
1992 :group 'org-time ; FIXME: Should we have a separate group????
1993 :type 'function)
1995 (defgroup org-tags nil
1996 "Options concerning tags in Org-mode."
1997 :tag "Org Tags"
1998 :group 'org)
2000 (defcustom org-tag-alist nil
2001 "List of tags allowed in Org-mode files.
2002 When this list is nil, Org-mode will base TAG input on what is already in the
2003 buffer.
2004 The value of this variable is an alist, the car of each entry must be a
2005 keyword as a string, the cdr may be a character that is used to select
2006 that tag through the fast-tag-selection interface.
2007 See the manual for details."
2008 :group 'org-tags
2009 :type '(repeat
2010 (choice
2011 (cons (string :tag "Tag name")
2012 (character :tag "Access char"))
2013 (const :tag "Start radio group" (:startgroup))
2014 (const :tag "End radio group" (:endgroup)))))
2016 (defcustom org-use-fast-tag-selection 'auto
2017 "Non-nil means, use fast tag selection scheme.
2018 This is a special interface to select and deselect tags with single keys.
2019 When nil, fast selection is never used.
2020 When the symbol `auto', fast selection is used if and only if selection
2021 characters for tags have been configured, either through the variable
2022 `org-tag-alist' or through a #+TAGS line in the buffer.
2023 When t, fast selection is always used and selection keys are assigned
2024 automatically if necessary."
2025 :group 'org-tags
2026 :type '(choice
2027 (const :tag "Always" t)
2028 (const :tag "Never" nil)
2029 (const :tag "When selection characters are configured" 'auto)))
2031 (defcustom org-fast-tag-selection-single-key nil
2032 "Non-nil means, fast tag selection exits after first change.
2033 When nil, you have to press RET to exit it.
2034 During fast tag selection, you can toggle this flag with `C-c'.
2035 This variable can also have the value `expert'. In this case, the window
2036 displaying the tags menu is not even shown, until you press C-c again."
2037 :group 'org-tags
2038 :type '(choice
2039 (const :tag "No" nil)
2040 (const :tag "Yes" t)
2041 (const :tag "Expert" expert)))
2043 (defvar org-fast-tag-selection-include-todo nil
2044 "Non-nil means, fast tags selection interface will also offer TODO states.
2045 This is an undocumented feature, you should not rely on it.")
2047 (defcustom org-tags-column -80
2048 "The column to which tags should be indented in a headline.
2049 If this number is positive, it specifies the column. If it is negative,
2050 it means that the tags should be flushright to that column. For example,
2051 -80 works well for a normal 80 character screen."
2052 :group 'org-tags
2053 :type 'integer)
2055 (defcustom org-auto-align-tags t
2056 "Non-nil means, realign tags after pro/demotion of TODO state change.
2057 These operations change the length of a headline and therefore shift
2058 the tags around. With this options turned on, after each such operation
2059 the tags are again aligned to `org-tags-column'."
2060 :group 'org-tags
2061 :type 'boolean)
2063 (defcustom org-use-tag-inheritance t
2064 "Non-nil means, tags in levels apply also for sublevels.
2065 When nil, only the tags directly given in a specific line apply there.
2066 If you turn off this option, you very likely want to turn on the
2067 companion option `org-tags-match-list-sublevels'."
2068 :group 'org-tags
2069 :type 'boolean)
2071 (defcustom org-tags-match-list-sublevels nil
2072 "Non-nil means list also sublevels of headlines matching tag search.
2073 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2074 the sublevels of a headline matching a tag search often also match
2075 the same search. Listing all of them can create very long lists.
2076 Setting this variable to nil causes subtrees of a match to be skipped.
2077 This option is off by default, because inheritance in on. If you turn
2078 inheritance off, you very likely want to turn this option on.
2080 As a special case, if the tag search is restricted to TODO items, the
2081 value of this variable is ignored and sublevels are always checked, to
2082 make sure all corresponding TODO items find their way into the list."
2083 :group 'org-tags
2084 :type 'boolean)
2086 (defvar org-tags-history nil
2087 "History of minibuffer reads for tags.")
2088 (defvar org-last-tags-completion-table nil
2089 "The last used completion table for tags.")
2090 (defvar org-after-tags-change-hook nil
2091 "Hook that is run after the tags in a line have changed.")
2093 (defgroup org-properties nil
2094 "Options concerning properties in Org-mode."
2095 :tag "Org Properties"
2096 :group 'org)
2098 (defcustom org-property-format "%-10s %s"
2099 "How property key/value pairs should be formatted by `indent-line'.
2100 When `indent-line' hits a property definition, it will format the line
2101 according to this format, mainly to make sure that the values are
2102 lined-up with respect to each other."
2103 :group 'org-properties
2104 :type 'string)
2106 (defcustom org-use-property-inheritance nil
2107 "Non-nil means, properties apply also for sublevels.
2108 This setting is only relevant during property searches, not when querying
2109 an entry with `org-entry-get'. To retrieve a property with inheritance,
2110 you need to call `org-entry-get' with the inheritance flag.
2111 Turning this on can cause significant overhead when doing a search, so
2112 this is turned off by default.
2113 When nil, only the properties directly given in the current entry count.
2114 The value may also be a list of properties that shouldhave inheritance.
2116 However, note that some special properties use inheritance under special
2117 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2118 and the properties ending in \"_ALL\" when they are used as descriptor
2119 for valid values of a property."
2120 :group 'org-properties
2121 :type '(choice
2122 (const :tag "Not" nil)
2123 (const :tag "Always" nil)
2124 (repeat :tag "Specific properties" (string :tag "Property"))))
2126 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2127 "The default column format, if no other format has been defined.
2128 This variable can be set on the per-file basis by inserting a line
2130 #+COLUMNS: %25ITEM ....."
2131 :group 'org-properties
2132 :type 'string)
2134 (defcustom org-global-properties nil
2135 "List of property/value pairs that can be inherited by any entry.
2136 You can set buffer-local values for this by adding lines like
2138 #+PROPERTY: NAME VALUE"
2139 :group 'org-properties
2140 :type '(repeat
2141 (cons (string :tag "Property")
2142 (string :tag "Value"))))
2144 (defvar org-local-properties nil
2145 "List of property/value pairs that can be inherited by any entry.
2146 Valid for the current buffer.
2147 This variable is populated from #+PROPERTY lines.")
2149 (defgroup org-agenda nil
2150 "Options concerning agenda views in Org-mode."
2151 :tag "Org Agenda"
2152 :group 'org)
2154 (defvar org-category nil
2155 "Variable used by org files to set a category for agenda display.
2156 Such files should use a file variable to set it, for example
2158 # -*- mode: org; org-category: \"ELisp\"
2160 or contain a special line
2162 #+CATEGORY: ELisp
2164 If the file does not specify a category, then file's base name
2165 is used instead.")
2166 (make-variable-buffer-local 'org-category)
2168 (defcustom org-agenda-files nil
2169 "The files to be used for agenda display.
2170 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2171 \\[org-remove-file]. You can also use customize to edit the list.
2173 If an entry is a directory, all files in that directory that are matched by
2174 `org-agenda-file-regexp' will be part of the file list.
2176 If the value of the variable is not a list but a single file name, then
2177 the list of agenda files is actually stored and maintained in that file, one
2178 agenda file per line."
2179 :group 'org-agenda
2180 :type '(choice
2181 (repeat :tag "List of files and directories" file)
2182 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2184 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2185 "Regular expression to match files for `org-agenda-files'.
2186 If any element in the list in that variable contains a directory instead
2187 of a normal file, all files in that directory that are matched by this
2188 regular expression will be included."
2189 :group 'org-agenda
2190 :type 'regexp)
2192 (defcustom org-agenda-skip-unavailable-files nil
2193 "t means to just skip non-reachable files in `org-agenda-files'.
2194 Nil means to remove them, after a query, from the list."
2195 :group 'org-agenda
2196 :type 'boolean)
2198 (defcustom org-agenda-multi-occur-extra-files nil
2199 "List of extra files to be searched by `org-occur-in-agenda-files'.
2200 The files in `org-agenda-files' are always searched."
2201 :group 'org-agenda
2202 :type '(repeat file))
2204 (defcustom org-agenda-confirm-kill 1
2205 "When set, remote killing from the agenda buffer needs confirmation.
2206 When t, a confirmation is always needed. When a number N, confirmation is
2207 only needed when the text to be killed contains more than N non-white lines."
2208 :group 'org-agenda
2209 :type '(choice
2210 (const :tag "Never" nil)
2211 (const :tag "Always" t)
2212 (number :tag "When more than N lines")))
2214 (defcustom org-calendar-to-agenda-key [?c]
2215 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2216 The command `org-calendar-goto-agenda' will be bound to this key. The
2217 default is the character `c' because then `c' can be used to switch back and
2218 forth between agenda and calendar."
2219 :group 'org-agenda
2220 :type 'sexp)
2222 (defcustom org-agenda-compact-blocks nil
2223 "Non-nil means, make the block agenda more compact.
2224 This is done by leaving out unnecessary lines."
2225 :group 'org-agenda
2226 :type nil)
2228 (defgroup org-agenda-export nil
2229 "Options concerning exporting agenda views in Org-mode."
2230 :tag "Org Agenda Export"
2231 :group 'org-agenda)
2233 (defcustom org-agenda-with-colors t
2234 "Non-nil means, use colors in agenda views."
2235 :group 'org-agenda-export
2236 :type 'boolean)
2238 (defcustom org-agenda-exporter-settings nil
2239 "Alist of variable/value pairs that should be active during agenda export.
2240 This is a good place to set uptions for ps-print and for htmlize."
2241 :group 'org-agenda-export
2242 :type '(repeat
2243 (list
2244 (variable)
2245 (sexp :tag "Value"))))
2247 (defcustom org-agenda-export-html-style ""
2248 "The style specification for exported HTML Agenda files.
2249 If this variable contains a string, it will replace the default <style>
2250 section as produced by `htmlize'.
2251 Since there are different ways of setting style information, this variable
2252 needs to contain the full HTML structure to provide a style, including the
2253 surrounding HTML tags. The style specifications should include definitions
2254 the fonts used by the agenda, here is an example:
2256 <style type=\"text/css\">
2257 p { font-weight: normal; color: gray; }
2258 .org-agenda-structure {
2259 font-size: 110%;
2260 color: #003399;
2261 font-weight: 600;
2263 .org-todo {
2264 color: #cc6666;Week-agenda:
2265 font-weight: bold;
2267 .org-done {
2268 color: #339933;
2270 .title { text-align: center; }
2271 .todo, .deadline { color: red; }
2272 .done { color: green; }
2273 </style>
2275 or, if you want to keep the style in a file,
2277 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2279 As the value of this option simply gets inserted into the HTML <head> header,
2280 you can \"misuse\" it to also add other text to the header. However,
2281 <style>...</style> is required, if not present the variable will be ignored."
2282 :group 'org-agenda-export
2283 :group 'org-export-html
2284 :type 'string)
2286 (defgroup org-agenda-custom-commands nil
2287 "Options concerning agenda views in Org-mode."
2288 :tag "Org Agenda Custom Commands"
2289 :group 'org-agenda)
2291 (defcustom org-agenda-custom-commands nil
2292 "Custom commands for the agenda.
2293 These commands will be offered on the splash screen displayed by the
2294 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2296 (key desc type match options files)
2298 key The key (one or more characters as a string) to be associated
2299 with the command.
2300 desc A description of the commend, when omitted or nil, a default
2301 description is built using MATCH.
2302 type The command type, any of the following symbols:
2303 todo Entries with a specific TODO keyword, in all agenda files.
2304 tags Tags match in all agenda files.
2305 tags-todo Tags match in all agenda files, TODO entries only.
2306 todo-tree Sparse tree of specific TODO keyword in *current* file.
2307 tags-tree Sparse tree with all tags matches in *current* file.
2308 occur-tree Occur sparse tree for *current* file.
2309 ... A user-defined function.
2310 match What to search for:
2311 - a single keyword for TODO keyword searches
2312 - a tags match expression for tags searches
2313 - a regular expression for occur searches
2314 options A list of option settings, similar to that in a let form, so like
2315 this: ((opt1 val1) (opt2 val2) ...)
2316 files A list of files file to write the produced agenda buffer to
2317 with the command `org-store-agenda-views'.
2318 If a file name ends in \".html\", an HTML version of the buffer
2319 is written out. If it ends in \".ps\", a postscript version is
2320 produced. Otherwide, only the plain text is written to the file.
2322 You can also define a set of commands, to create a composite agenda buffer.
2323 In this case, an entry looks like this:
2325 (key desc (cmd1 cmd2 ...) general-options file)
2327 where
2329 desc A description string to be displayed in the dispatcher menu.
2330 cmd An agenda command, similar to the above. However, tree commands
2331 are no allowed, but instead you can get agenda and global todo list.
2332 So valid commands for a set are:
2333 (agenda)
2334 (alltodo)
2335 (stuck)
2336 (todo \"match\" options files)
2337 (tags \"match\" options files)
2338 (tags-todo \"match\" options files)
2340 Each command can carry a list of options, and another set of options can be
2341 given for the whole set of commands. Individual command options take
2342 precedence over the general options.
2344 When using several characters as key to a command, the first characters
2345 are prefix commands. For the dispatcher to display useful information, you
2346 should provide a description for the prefix, like
2348 (setq org-agenda-custom-commands
2349 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2350 (\"hl\" tags \"+HOME+Lisa\")
2351 (\"hp\" tags \"+HOME+Peter\")
2352 (\"hk\" tags \"+HOME+Kim\")))"
2353 :group 'org-agenda-custom-commands
2354 :type '(repeat
2355 (choice :value ("a" "" tags "" nil)
2356 (list :tag "Single command"
2357 (string :tag "Access Key(s) ")
2358 (option (string :tag "Description"))
2359 (choice
2360 (const :tag "Agenda" agenda)
2361 (const :tag "TODO list" alltodo)
2362 (const :tag "Stuck projects" stuck)
2363 (const :tag "Tags search (all agenda files)" tags)
2364 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2365 (const :tag "TODO keyword search (all agenda files)" todo)
2366 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2367 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2368 (const :tag "Occur tree (current buffer)" occur-tree)
2369 (sexp :tag "Other, user-defined function"))
2370 (string :tag "Match")
2371 (repeat :tag "Local options"
2372 (list (variable :tag "Option") (sexp :tag "Value")))
2373 (option (repeat :tag "Export" (file :tag "Export to"))))
2374 (list :tag "Command series, all agenda files"
2375 (string :tag "Access Key(s)")
2376 (string :tag "Description ")
2377 (repeat
2378 (choice
2379 (const :tag "Agenda" (agenda))
2380 (const :tag "TODO list" (alltodo))
2381 (const :tag "Stuck projects" (stuck))
2382 (list :tag "Tags search"
2383 (const :format "" tags)
2384 (string :tag "Match")
2385 (repeat :tag "Local options"
2386 (list (variable :tag "Option")
2387 (sexp :tag "Value"))))
2389 (list :tag "Tags search, TODO entries only"
2390 (const :format "" tags-todo)
2391 (string :tag "Match")
2392 (repeat :tag "Local options"
2393 (list (variable :tag "Option")
2394 (sexp :tag "Value"))))
2396 (list :tag "TODO keyword search"
2397 (const :format "" todo)
2398 (string :tag "Match")
2399 (repeat :tag "Local options"
2400 (list (variable :tag "Option")
2401 (sexp :tag "Value"))))
2403 (list :tag "Other, user-defined function"
2404 (symbol :tag "function")
2405 (string :tag "Match")
2406 (repeat :tag "Local options"
2407 (list (variable :tag "Option")
2408 (sexp :tag "Value"))))))
2410 (repeat :tag "General options"
2411 (list (variable :tag "Option")
2412 (sexp :tag "Value")))
2413 (option (repeat :tag "Export" (file :tag "Export to"))))
2414 (cons :tag "Prefix key documentation"
2415 (string :tag "Access Key(s)")
2416 (string :tag "Description ")))))
2418 (defcustom org-stuck-projects
2419 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2420 "How to identify stuck projects.
2421 This is a list of four items:
2422 1. A tags/todo matcher string that is used to identify a project.
2423 The entire tree below a headline matched by this is considered one project.
2424 2. A list of TODO keywords identifying non-stuck projects.
2425 If the project subtree contains any headline with one of these todo
2426 keywords, the project is considered to be not stuck. If you specify
2427 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2428 3. A list of tags identifying non-stuck projects.
2429 If the project subtree contains any headline with one of these tags,
2430 the project is considered to be not stuck. If you specify \"*\" as
2431 a tag, any tag will mark the project unstuck.
2432 4. An arbitrary regular expression matching non-stuck projects.
2434 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2435 or `C-c a #' to produce the list."
2436 :group 'org-agenda-custom-commands
2437 :type '(list
2438 (string :tag "Tags/TODO match to identify a project")
2439 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2440 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2441 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2444 (defgroup org-agenda-skip nil
2445 "Options concerning skipping parts of agenda files."
2446 :tag "Org Agenda Skip"
2447 :group 'org-agenda)
2449 (defcustom org-agenda-todo-list-sublevels t
2450 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2451 When nil, the sublevels of a TODO entry are not checked, resulting in
2452 potentially much shorter TODO lists."
2453 :group 'org-agenda-skip
2454 :group 'org-todo
2455 :type 'boolean)
2457 (defcustom org-agenda-todo-ignore-with-date nil
2458 "Non-nil means, don't show entries with a date in the global todo list.
2459 You can use this if you prefer to mark mere appointments with a TODO keyword,
2460 but don't want them to show up in the TODO list.
2461 When this is set, it also covers deadlines and scheduled items, the settings
2462 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2463 will be ignored."
2464 :group 'org-agenda-skip
2465 :group 'org-todo
2466 :type 'boolean)
2468 (defcustom org-agenda-todo-ignore-scheduled nil
2469 "Non-nil means, don't show scheduled entries in the global todo list.
2470 The idea behind this is that by scheduling it, you have already taken care
2471 of this item.
2472 See also `org-agenda-todo-ignore-with-date'."
2473 :group 'org-agenda-skip
2474 :group 'org-todo
2475 :type 'boolean)
2477 (defcustom org-agenda-todo-ignore-deadlines nil
2478 "Non-nil means, don't show near deadline entries in the global todo list.
2479 Near means closer than `org-deadline-warning-days' days.
2480 The idea behind this is that such items will appear in the agenda anyway.
2481 See also `org-agenda-todo-ignore-with-date'."
2482 :group 'org-agenda-skip
2483 :group 'org-todo
2484 :type 'boolean)
2486 (defcustom org-agenda-skip-scheduled-if-done nil
2487 "Non-nil means don't show scheduled items in agenda when they are done.
2488 This is relevant for the daily/weekly agenda, not for the TODO list. And
2489 it applies only to the actual date of the scheduling. Warnings about
2490 an item with a past scheduling dates are always turned off when the item
2491 is DONE."
2492 :group 'org-agenda-skip
2493 :type 'boolean)
2495 (defcustom org-agenda-skip-deadline-if-done nil
2496 "Non-nil means don't show deadines when the corresponding item is done.
2497 When nil, the deadline is still shown and should give you a happy feeling.
2498 This is relevant for the daily/weekly agenda. And it applied only to the
2499 actualy date of the deadline. Warnings about approching and past-due
2500 deadlines are always turned off when the item is DONE."
2501 :group 'org-agenda-skip
2502 :type 'boolean)
2504 (defcustom org-agenda-skip-timestamp-if-done nil
2505 "Non-nil means don't select item by timestamp or -range if it is DONE."
2506 :group 'org-agenda-skip
2507 :type 'boolean)
2509 (defcustom org-timeline-show-empty-dates 3
2510 "Non-nil means, `org-timeline' also shows dates without an entry.
2511 When nil, only the days which actually have entries are shown.
2512 When t, all days between the first and the last date are shown.
2513 When an integer, show also empty dates, but if there is a gap of more than
2514 N days, just insert a special line indicating the size of the gap."
2515 :group 'org-agenda-skip
2516 :type '(choice
2517 (const :tag "None" nil)
2518 (const :tag "All" t)
2519 (number :tag "at most")))
2522 (defgroup org-agenda-startup nil
2523 "Options concerning initial settings in the Agenda in Org Mode."
2524 :tag "Org Agenda Startup"
2525 :group 'org-agenda)
2527 (defcustom org-finalize-agenda-hook nil
2528 "Hook run just before displaying an agenda buffer."
2529 :group 'org-agenda-startup
2530 :type 'hook)
2532 (defcustom org-agenda-mouse-1-follows-link nil
2533 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2534 A longer mouse click will still set point. Does not wortk on XEmacs.
2535 Needs to be set before org.el is loaded."
2536 :group 'org-agenda-startup
2537 :type 'boolean)
2539 (defcustom org-agenda-start-with-follow-mode nil
2540 "The initial value of follow-mode in a newly created agenda window."
2541 :group 'org-agenda-startup
2542 :type 'boolean)
2544 (defgroup org-agenda-windows nil
2545 "Options concerning the windows used by the Agenda in Org Mode."
2546 :tag "Org Agenda Windows"
2547 :group 'org-agenda)
2549 (defcustom org-agenda-window-setup 'reorganize-frame
2550 "How the agenda buffer should be displayed.
2551 Possible values for this option are:
2553 current-window Show agenda in the current window, keeping all other windows.
2554 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2555 other-window Use `switch-to-buffer-other-window' to display agenda.
2556 reorganize-frame Show only two windows on the current frame, the current
2557 window and the agenda.
2558 See also the variable `org-agenda-restore-windows-after-quit'."
2559 :group 'org-agenda-windows
2560 :type '(choice
2561 (const current-window)
2562 (const other-frame)
2563 (const other-window)
2564 (const reorganize-frame)))
2566 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2567 "The min and max height of the agenda window as a fraction of frame height.
2568 The value of the variable is a cons cell with two numbers between 0 and 1.
2569 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2570 :group 'org-agenda-windows
2571 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2573 (defcustom org-agenda-restore-windows-after-quit nil
2574 "Non-nil means, restore window configuration open exiting agenda.
2575 Before the window configuration is changed for displaying the agenda,
2576 the current status is recorded. When the agenda is exited with
2577 `q' or `x' and this option is set, the old state is restored. If
2578 `org-agenda-window-setup' is `other-frame', the value of this
2579 option will be ignored.."
2580 :group 'org-agenda-windows
2581 :type 'boolean)
2583 (defcustom org-indirect-buffer-display 'other-window
2584 "How should indirect tree buffers be displayed?
2585 This applies to indirect buffers created with the commands
2586 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2587 Valid values are:
2588 current-window Display in the current window
2589 other-window Just display in another window.
2590 dedicated-frame Create one new frame, and re-use it each time.
2591 new-frame Make a new frame each time. Note that in this case
2592 previously-made indirect buffers are kept, and you need to
2593 kill these buffers yourself."
2594 :group 'org-structure
2595 :group 'org-agenda-windows
2596 :type '(choice
2597 (const :tag "In current window" current-window)
2598 (const :tag "In current frame, other window" other-window)
2599 (const :tag "Each time a new frame" new-frame)
2600 (const :tag "One dedicated frame" dedicated-frame)))
2602 (defgroup org-agenda-daily/weekly nil
2603 "Options concerning the daily/weekly agenda."
2604 :tag "Org Agenda Daily/Weekly"
2605 :group 'org-agenda)
2607 (defcustom org-agenda-ndays 7
2608 "Number of days to include in overview display.
2609 Should be 1 or 7."
2610 :group 'org-agenda-daily/weekly
2611 :type 'number)
2613 (defcustom org-agenda-start-on-weekday 1
2614 "Non-nil means, start the overview always on the specified weekday.
2615 0 denotes Sunday, 1 denotes Monday etc.
2616 When nil, always start on the current day."
2617 :group 'org-agenda-daily/weekly
2618 :type '(choice (const :tag "Today" nil)
2619 (number :tag "Weekday No.")))
2621 (defcustom org-agenda-show-all-dates t
2622 "Non-nil means, `org-agenda' shows every day in the selected range.
2623 When nil, only the days which actually have entries are shown."
2624 :group 'org-agenda-daily/weekly
2625 :type 'boolean)
2627 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2628 "Format string for displaying dates in the agenda.
2629 Used by the daily/weekly agenda and by the timeline. This should be
2630 a format string understood by `format-time-string', or a function returning
2631 the formatted date as a string. The function must take a single argument,
2632 a calendar-style date list like (month day year)."
2633 :group 'org-agenda-daily/weekly
2634 :type '(choice
2635 (string :tag "Format string")
2636 (function :tag "Function")))
2638 (defun org-agenda-format-date-aligned (date)
2639 "Format a date string for display in the daily/weekly agenda, or timeline.
2640 This function makes sure that dates are aligned for easy reading."
2641 (format "%-9s %2d %s %4d"
2642 (calendar-day-name date)
2643 (extract-calendar-day date)
2644 (calendar-month-name (extract-calendar-month date))
2645 (extract-calendar-year date)))
2647 (defcustom org-agenda-include-diary nil
2648 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2649 :group 'org-agenda-daily/weekly
2650 :type 'boolean)
2652 (defcustom org-agenda-include-all-todo nil
2653 "Set means weekly/daily agenda will always contain all TODO entries.
2654 The TODO entries will be listed at the top of the agenda, before
2655 the entries for specific days."
2656 :group 'org-agenda-daily/weekly
2657 :type 'boolean)
2659 (defcustom org-agenda-repeating-timestamp-show-all t
2660 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2661 When nil, only one occurence is shown, either today or the
2662 nearest into the future."
2663 :group 'org-agenda-daily/weekly
2664 :type 'boolean)
2666 (defcustom org-deadline-warning-days 14
2667 "No. of days before expiration during which a deadline becomes active.
2668 This variable governs the display in sparse trees and in the agenda.
2669 When negative, it means use this number (the absolute value of it)
2670 even if a deadline has a different individual lead time specified."
2671 :group 'org-time
2672 :group 'org-agenda-daily/weekly
2673 :type 'number)
2675 (defcustom org-scheduled-past-days 10000
2676 "No. of days to continue listing scheduled items that are not marked DONE.
2677 When an item is scheduled on a date, it shows up in the agenda on this
2678 day and will be listed until it is marked done for the number of days
2679 given here."
2680 :group 'org-agenda-daily/weekly
2681 :type 'number)
2683 (defgroup org-agenda-time-grid nil
2684 "Options concerning the time grid in the Org-mode Agenda."
2685 :tag "Org Agenda Time Grid"
2686 :group 'org-agenda)
2688 (defcustom org-agenda-use-time-grid t
2689 "Non-nil means, show a time grid in the agenda schedule.
2690 A time grid is a set of lines for specific times (like every two hours between
2691 8:00 and 20:00). The items scheduled for a day at specific times are
2692 sorted in between these lines.
2693 For details about when the grid will be shown, and what it will look like, see
2694 the variable `org-agenda-time-grid'."
2695 :group 'org-agenda-time-grid
2696 :type 'boolean)
2698 (defcustom org-agenda-time-grid
2699 '((daily today require-timed)
2700 "----------------"
2701 (800 1000 1200 1400 1600 1800 2000))
2703 "The settings for time grid for agenda display.
2704 This is a list of three items. The first item is again a list. It contains
2705 symbols specifying conditions when the grid should be displayed:
2707 daily if the agenda shows a single day
2708 weekly if the agenda shows an entire week
2709 today show grid on current date, independent of daily/weekly display
2710 require-timed show grid only if at least one item has a time specification
2712 The second item is a string which will be places behing the grid time.
2714 The third item is a list of integers, indicating the times that should have
2715 a grid line."
2716 :group 'org-agenda-time-grid
2717 :type
2718 '(list
2719 (set :greedy t :tag "Grid Display Options"
2720 (const :tag "Show grid in single day agenda display" daily)
2721 (const :tag "Show grid in weekly agenda display" weekly)
2722 (const :tag "Always show grid for today" today)
2723 (const :tag "Show grid only if any timed entries are present"
2724 require-timed)
2725 (const :tag "Skip grid times already present in an entry"
2726 remove-match))
2727 (string :tag "Grid String")
2728 (repeat :tag "Grid Times" (integer :tag "Time"))))
2730 (defgroup org-agenda-sorting nil
2731 "Options concerning sorting in the Org-mode Agenda."
2732 :tag "Org Agenda Sorting"
2733 :group 'org-agenda)
2735 (defconst org-sorting-choice
2736 '(choice
2737 (const time-up) (const time-down)
2738 (const category-keep) (const category-up) (const category-down)
2739 (const tag-down) (const tag-up)
2740 (const priority-up) (const priority-down))
2741 "Sorting choices.")
2743 (defcustom org-agenda-sorting-strategy
2744 '((agenda time-up category-keep priority-down)
2745 (todo category-keep priority-down)
2746 (tags category-keep priority-down))
2747 "Sorting structure for the agenda items of a single day.
2748 This is a list of symbols which will be used in sequence to determine
2749 if an entry should be listed before another entry. The following
2750 symbols are recognized:
2752 time-up Put entries with time-of-day indications first, early first
2753 time-down Put entries with time-of-day indications first, late first
2754 category-keep Keep the default order of categories, corresponding to the
2755 sequence in `org-agenda-files'.
2756 category-up Sort alphabetically by category, A-Z.
2757 category-down Sort alphabetically by category, Z-A.
2758 tag-up Sort alphabetically by last tag, A-Z.
2759 tag-down Sort alphabetically by last tag, Z-A.
2760 priority-up Sort numerically by priority, high priority last.
2761 priority-down Sort numerically by priority, high priority first.
2763 The different possibilities will be tried in sequence, and testing stops
2764 if one comparison returns a \"not-equal\". For example, the default
2765 '(time-up category-keep priority-down)
2766 means: Pull out all entries having a specified time of day and sort them,
2767 in order to make a time schedule for the current day the first thing in the
2768 agenda listing for the day. Of the entries without a time indication, keep
2769 the grouped in categories, don't sort the categories, but keep them in
2770 the sequence given in `org-agenda-files'. Within each category sort by
2771 priority.
2773 Leaving out `category-keep' would mean that items will be sorted across
2774 categories by priority.
2776 Instead of a single list, this can also be a set of list for specific
2777 contents, with a context symbol in the car of the list, any of
2778 `agenda', `todo', `tags' for the corresponding agenda views."
2779 :group 'org-agenda-sorting
2780 :type `(choice
2781 (repeat :tag "General" ,org-sorting-choice)
2782 (list :tag "Individually"
2783 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2784 (repeat ,org-sorting-choice))
2785 (cons (const :tag "Strategy for TODO lists" todo)
2786 (repeat ,org-sorting-choice))
2787 (cons (const :tag "Strategy for Tags matches" tags)
2788 (repeat ,org-sorting-choice)))))
2790 (defcustom org-sort-agenda-notime-is-late t
2791 "Non-nil means, items without time are considered late.
2792 This is only relevant for sorting. When t, items which have no explicit
2793 time like 15:30 will be considered as 99:01, i.e. later than any items which
2794 do have a time. When nil, the default time is before 0:00. You can use this
2795 option to decide if the schedule for today should come before or after timeless
2796 agenda entries."
2797 :group 'org-agenda-sorting
2798 :type 'boolean)
2800 (defgroup org-agenda-line-format nil
2801 "Options concerning the entry prefix in the Org-mode agenda display."
2802 :tag "Org Agenda Line Format"
2803 :group 'org-agenda)
2805 (defcustom org-agenda-prefix-format
2806 '((agenda . " %-12:c%?-12t% s")
2807 (timeline . " % s")
2808 (todo . " %-12:c")
2809 (tags . " %-12:c"))
2810 "Format specifications for the prefix of items in the agenda views.
2811 An alist with four entries, for the different agenda types. The keys to the
2812 sublists are `agenda', `timeline', `todo', and `tags'. The values
2813 are format strings.
2814 This format works similar to a printf format, with the following meaning:
2816 %c the category of the item, \"Diary\" for entries from the diary, or
2817 as given by the CATEGORY keyword or derived from the file name.
2818 %T the *last* tag of the item. Last because inherited tags come
2819 first in the list.
2820 %t the time-of-day specification if one applies to the entry, in the
2821 format HH:MM
2822 %s Scheduling/Deadline information, a short string
2824 All specifiers work basically like the standard `%s' of printf, but may
2825 contain two additional characters: A question mark just after the `%' and
2826 a whitespace/punctuation character just before the final letter.
2828 If the first character after `%' is a question mark, the entire field
2829 will only be included if the corresponding value applies to the
2830 current entry. This is useful for fields which should have fixed
2831 width when present, but zero width when absent. For example,
2832 \"%?-12t\" will result in a 12 character time field if a time of the
2833 day is specified, but will completely disappear in entries which do
2834 not contain a time.
2836 If there is punctuation or whitespace character just before the final
2837 format letter, this character will be appended to the field value if
2838 the value is not empty. For example, the format \"%-12:c\" leads to
2839 \"Diary: \" if the category is \"Diary\". If the category were be
2840 empty, no additional colon would be interted.
2842 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2843 - Indent the line with two space characters
2844 - Give the category in a 12 chars wide field, padded with whitespace on
2845 the right (because of `-'). Append a colon if there is a category
2846 (because of `:').
2847 - If there is a time-of-day, put it into a 12 chars wide field. If no
2848 time, don't put in an empty field, just skip it (because of '?').
2849 - Finally, put the scheduling information and append a whitespace.
2851 As another example, if you don't want the time-of-day of entries in
2852 the prefix, you could use:
2854 (setq org-agenda-prefix-format \" %-11:c% s\")
2856 See also the variables `org-agenda-remove-times-when-in-prefix' and
2857 `org-agenda-remove-tags'."
2858 :type '(choice
2859 (string :tag "General format")
2860 (list :greedy t :tag "View dependent"
2861 (cons (const agenda) (string :tag "Format"))
2862 (cons (const timeline) (string :tag "Format"))
2863 (cons (const todo) (string :tag "Format"))
2864 (cons (const tags) (string :tag "Format"))))
2865 :group 'org-agenda-line-format)
2867 (defvar org-prefix-format-compiled nil
2868 "The compiled version of the most recently used prefix format.
2869 See the variable `org-agenda-prefix-format'.")
2871 (defcustom org-agenda-todo-keyword-format "%-1s"
2872 "Format for the TODO keyword in agenda lines.
2873 Set this to something like \"%-12s\" if you want all TODO keywords
2874 to occupy a fixed space in the agenda display."
2875 :group 'org-agenda-line-format
2876 :type 'string)
2878 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
2879 "Text preceeding scheduled items in the agenda view.
2880 This is a list with two strings. The first applies when the item is
2881 scheduled on the current day. The second applies when it has been scheduled
2882 previously, it may contain a %d to capture how many days ago the item was
2883 scheduled."
2884 :group 'org-agenda-line-format
2885 :type '(list
2886 (string :tag "Scheduled today ")
2887 (string :tag "Scheduled previously")))
2889 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
2890 "Text preceeding deadline items in the agenda view.
2891 This is a list with two strings. The first applies when the item has its
2892 deadline on the current day. The second applies when it is in the past or
2893 in the future, it may contain %d to capture how many days away the deadline
2894 is (was)."
2895 :group 'org-agenda-line-format
2896 :type '(list
2897 (string :tag "Deadline today ")
2898 (string :tag "Deadline relative")))
2900 (defcustom org-agenda-remove-times-when-in-prefix t
2901 "Non-nil means, remove duplicate time specifications in agenda items.
2902 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2903 time-of-day specification in a headline or diary entry is extracted and
2904 placed into the prefix. If this option is non-nil, the original specification
2905 \(a timestamp or -range, or just a plain time(range) specification like
2906 11:30-4pm) will be removed for agenda display. This makes the agenda less
2907 cluttered.
2908 The option can be t or nil. It may also be the symbol `beg', indicating
2909 that the time should only be removed what it is located at the beginning of
2910 the headline/diary entry."
2911 :group 'org-agenda-line-format
2912 :type '(choice
2913 (const :tag "Always" t)
2914 (const :tag "Never" nil)
2915 (const :tag "When at beginning of entry" beg)))
2918 (defcustom org-agenda-default-appointment-duration nil
2919 "Default duration for appointments that only have a starting time.
2920 When nil, no duration is specified in such cases.
2921 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
2922 :group 'org-agenda-line-format
2923 :type '(choice
2924 (integer :tag "Minutes")
2925 (const :tag "No default duration")))
2928 (defcustom org-agenda-remove-tags nil
2929 "Non-nil means, remove the tags from the headline copy in the agenda.
2930 When this is the symbol `prefix', only remove tags when
2931 `org-agenda-prefix-format' contains a `%T' specifier."
2932 :group 'org-agenda-line-format
2933 :type '(choice
2934 (const :tag "Always" t)
2935 (const :tag "Never" nil)
2936 (const :tag "When prefix format contains %T" prefix)))
2938 (if (fboundp 'defvaralias)
2939 (defvaralias 'org-agenda-remove-tags-when-in-prefix
2940 'org-agenda-remove-tags))
2942 (defcustom org-agenda-tags-column -80
2943 "Shift tags in agenda items to this column.
2944 If this number is positive, it specifies the column. If it is negative,
2945 it means that the tags should be flushright to that column. For example,
2946 -80 works well for a normal 80 character screen."
2947 :group 'org-agenda-line-format
2948 :type 'integer)
2950 (if (fboundp 'defvaralias)
2951 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
2953 (defcustom org-agenda-fontify-priorities t
2954 "Non-nil means, highlight low and high priorities in agenda.
2955 When t, the highest priority entries are bold, lowest priority italic.
2956 This may also be an association list of priority faces. The face may be
2957 a names face, or a list like `(:background \"Red\")'."
2958 :group 'org-agenda-line-format
2959 :type '(choice
2960 (const :tag "Never" nil)
2961 (const :tag "Defaults" t)
2962 (repeat :tag "Specify"
2963 (list (character :tag "Priority" :value ?A)
2964 (sexp :tag "face")))))
2966 (defgroup org-latex nil
2967 "Options for embedding LaTeX code into Org-mode"
2968 :tag "Org LaTeX"
2969 :group 'org)
2971 (defcustom org-format-latex-options
2972 '(:foreground default :background default :scale 1.0
2973 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2974 :matchers ("begin" "$" "$$" "\\(" "\\["))
2975 "Options for creating images from LaTeX fragments.
2976 This is a property list with the following properties:
2977 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
2978 `default' means use the forground of the default face.
2979 :background the background color, or \"Transparent\".
2980 `default' means use the background of the default face.
2981 :scale a scaling factor for the size of the images
2982 :html-foreground, :html-background, :html-scale
2983 The same numbers for HTML export.
2984 :matchers a list indicating which matchers should be used to
2985 find LaTeX fragments. Valid members of this list are:
2986 \"begin\" find environments
2987 \"$\" find math expressions surrounded by $...$
2988 \"$$\" find math expressions surrounded by $$....$$
2989 \"\\(\" find math expressions surrounded by \\(...\\)
2990 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2991 :group 'org-latex
2992 :type 'plist)
2994 (defcustom org-format-latex-header "\\documentclass{article}
2995 \\usepackage{fullpage} % do not remove
2996 \\usepackage{amssymb}
2997 \\usepackage[usenames]{color}
2998 \\usepackage{amsmath}
2999 \\usepackage{latexsym}
3000 \\usepackage[mathscr]{eucal}
3001 \\pagestyle{empty} % do not remove"
3002 "The document header used for processing LaTeX fragments."
3003 :group 'org-latex
3004 :type 'string)
3006 (defgroup org-export nil
3007 "Options for exporting org-listings."
3008 :tag "Org Export"
3009 :group 'org)
3011 (defgroup org-export-general nil
3012 "General options for exporting Org-mode files."
3013 :tag "Org Export General"
3014 :group 'org-export)
3016 ;; FIXME
3017 (defvar org-export-publishing-directory nil)
3019 (defcustom org-export-with-special-strings t
3020 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3021 When this option is turned on, these strings will be exported as:
3023 Org HTML LaTeX
3024 -----+----------+--------
3025 \\- &shy; \\-
3026 -- &ndash; --
3027 --- &mdash; ---
3028 ... &hellip; \ldots
3030 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3031 :group 'org-export-translation
3032 :type 'boolean)
3034 (defcustom org-export-language-setup
3035 '(("en" "Author" "Date" "Table of Contents")
3036 ("cs" "Autor" "Datum" "Obsah")
3037 ("da" "Ophavsmand" "Dato" "Indhold")
3038 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
3039 ("es" "Autor" "Fecha" "\xcdndice")
3040 ("fr" "Auteur" "Date" "Table des mati\xe8res")
3041 ("it" "Autore" "Data" "Indice")
3042 ("nl" "Auteur" "Datum" "Inhoudsopgave")
3043 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
3044 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
3045 "Terms used in export text, translated to different languages.
3046 Use the variable `org-export-default-language' to set the language,
3047 or use the +OPTION lines for a per-file setting."
3048 :group 'org-export-general
3049 :type '(repeat
3050 (list
3051 (string :tag "HTML language tag")
3052 (string :tag "Author")
3053 (string :tag "Date")
3054 (string :tag "Table of Contents"))))
3056 (defcustom org-export-default-language "en"
3057 "The default language of HTML export, as a string.
3058 This should have an association in `org-export-language-setup'."
3059 :group 'org-export-general
3060 :type 'string)
3062 (defcustom org-export-skip-text-before-1st-heading t
3063 "Non-nil means, skip all text before the first headline when exporting.
3064 When nil, that text is exported as well."
3065 :group 'org-export-general
3066 :type 'boolean)
3068 (defcustom org-export-headline-levels 3
3069 "The last level which is still exported as a headline.
3070 Inferior levels will produce itemize lists when exported.
3071 Note that a numeric prefix argument to an exporter function overrides
3072 this setting.
3074 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
3075 :group 'org-export-general
3076 :type 'number)
3078 (defcustom org-export-with-section-numbers t
3079 "Non-nil means, add section numbers to headlines when exporting.
3081 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
3082 :group 'org-export-general
3083 :type 'boolean)
3085 (defcustom org-export-with-toc t
3086 "Non-nil means, create a table of contents in exported files.
3087 The TOC contains headlines with levels up to`org-export-headline-levels'.
3088 When an integer, include levels up to N in the toc, this may then be
3089 different from `org-export-headline-levels', but it will not be allowed
3090 to be larger than the number of headline levels.
3091 When nil, no table of contents is made.
3093 Headlines which contain any TODO items will be marked with \"(*)\" in
3094 ASCII export, and with red color in HTML output, if the option
3095 `org-export-mark-todo-in-toc' is set.
3097 In HTML output, the TOC will be clickable.
3099 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
3100 or \"toc:3\"."
3101 :group 'org-export-general
3102 :type '(choice
3103 (const :tag "No Table of Contents" nil)
3104 (const :tag "Full Table of Contents" t)
3105 (integer :tag "TOC to level")))
3107 (defcustom org-export-mark-todo-in-toc nil
3108 "Non-nil means, mark TOC lines that contain any open TODO items."
3109 :group 'org-export-general
3110 :type 'boolean)
3112 (defcustom org-export-preserve-breaks nil
3113 "Non-nil means, preserve all line breaks when exporting.
3114 Normally, in HTML output paragraphs will be reformatted. In ASCII
3115 export, line breaks will always be preserved, regardless of this variable.
3117 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3118 :group 'org-export-general
3119 :type 'boolean)
3121 (defcustom org-export-with-archived-trees 'headline
3122 "Whether subtrees with the ARCHIVE tag should be exported.
3123 This can have three different values
3124 nil Do not export, pretend this tree is not present
3125 t Do export the entire tree
3126 headline Only export the headline, but skip the tree below it."
3127 :group 'org-export-general
3128 :group 'org-archive
3129 :type '(choice
3130 (const :tag "not at all" nil)
3131 (const :tag "headline only" 'headline)
3132 (const :tag "entirely" t)))
3134 (defcustom org-export-author-info t
3135 "Non-nil means, insert author name and email into the exported file.
3137 This option can also be set with the +OPTIONS line,
3138 e.g. \"author-info:nil\"."
3139 :group 'org-export-general
3140 :type 'boolean)
3142 (defcustom org-export-time-stamp-file t
3143 "Non-nil means, insert a time stamp into the exported file.
3144 The time stamp shows when the file was created.
3146 This option can also be set with the +OPTIONS line,
3147 e.g. \"timestamp:nil\"."
3148 :group 'org-export-general
3149 :type 'boolean)
3151 (defcustom org-export-with-timestamps t
3152 "If nil, do not export time stamps and associated keywords."
3153 :group 'org-export-general
3154 :type 'boolean)
3156 (defcustom org-export-remove-timestamps-from-toc t
3157 "If nil, remove timestamps from the table of contents entries."
3158 :group 'org-export-general
3159 :type 'boolean)
3161 (defcustom org-export-with-tags 'not-in-toc
3162 "If nil, do not export tags, just remove them from headlines.
3163 If this is the symbol `not-in-toc', tags will be removed from table of
3164 contents entries, but still be shown in the headlines of the document.
3166 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3167 :group 'org-export-general
3168 :type '(choice
3169 (const :tag "Off" nil)
3170 (const :tag "Not in TOC" not-in-toc)
3171 (const :tag "On" t)))
3173 (defcustom org-export-with-drawers nil
3174 "Non-nil means, export with drawers like the property drawer.
3175 When t, all drawers are exported. This may also be a list of
3176 drawer names to export."
3177 :group 'org-export-general
3178 :type '(choice
3179 (const :tag "All drawers" t)
3180 (const :tag "None" nil)
3181 (repeat :tag "Selected drawers"
3182 (string :tag "Drawer name"))))
3184 (defgroup org-export-translation nil
3185 "Options for translating special ascii sequences for the export backends."
3186 :tag "Org Export Translation"
3187 :group 'org-export)
3189 (defcustom org-export-with-emphasize t
3190 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3191 If the export target supports emphasizing text, the word will be
3192 typeset in bold, italic, or underlined, respectively. Works only for
3193 single words, but you can say: I *really* *mean* *this*.
3194 Not all export backends support this.
3196 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3197 :group 'org-export-translation
3198 :type 'boolean)
3200 (defcustom org-export-with-footnotes t
3201 "If nil, export [1] as a footnote marker.
3202 Lines starting with [1] will be formatted as footnotes.
3204 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3205 :group 'org-export-translation
3206 :type 'boolean)
3208 (defcustom org-export-with-sub-superscripts t
3209 "Non-nil means, interpret \"_\" and \"^\" for export.
3210 When this option is turned on, you can use TeX-like syntax for sub- and
3211 superscripts. Several characters after \"_\" or \"^\" will be
3212 considered as a single item - so grouping with {} is normally not
3213 needed. For example, the following things will be parsed as single
3214 sub- or superscripts.
3216 10^24 or 10^tau several digits will be considered 1 item.
3217 10^-12 or 10^-tau a leading sign with digits or a word
3218 x^2-y^3 will be read as x^2 - y^3, because items are
3219 terminated by almost any nonword/nondigit char.
3220 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3222 Still, ambiguity is possible - so when in doubt use {} to enclose the
3223 sub/superscript. If you set this variable to the symbol `{}',
3224 the braces are *required* in order to trigger interpretations as
3225 sub/superscript. This can be helpful in documents that need \"_\"
3226 frequently in plain text.
3228 Not all export backends support this, but HTML does.
3230 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3231 :group 'org-export-translation
3232 :type '(choice
3233 (const :tag "Always interpret" t)
3234 (const :tag "Only with braces" {})
3235 (const :tag "Never interpret" nil)))
3237 (defcustom org-export-with-special-strings t
3238 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3239 When this option is turned on, these strings will be exported as:
3241 \\- : &shy;
3242 -- : &ndash;
3243 --- : &mdash;
3245 Not all export backends support this, but HTML does.
3247 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3248 :group 'org-export-translation
3249 :type 'boolean)
3251 (defcustom org-export-with-TeX-macros t
3252 "Non-nil means, interpret simple TeX-like macros when exporting.
3253 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3254 No only real TeX macros will work here, but the standard HTML entities
3255 for math can be used as macro names as well. For a list of supported
3256 names in HTML export, see the constant `org-html-entities'.
3257 Not all export backends support this.
3259 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3260 :group 'org-export-translation
3261 :group 'org-export-latex
3262 :type 'boolean)
3264 (defcustom org-export-with-LaTeX-fragments nil
3265 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3266 When set, the exporter will find LaTeX environments if the \\begin line is
3267 the first non-white thing on a line. It will also find the math delimiters
3268 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3269 display math.
3271 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3272 :group 'org-export-translation
3273 :group 'org-export-latex
3274 :type 'boolean)
3276 (defcustom org-export-with-fixed-width t
3277 "Non-nil means, lines starting with \":\" will be in fixed width font.
3278 This can be used to have pre-formatted text, fragments of code etc. For
3279 example:
3280 : ;; Some Lisp examples
3281 : (while (defc cnt)
3282 : (ding))
3283 will be looking just like this in also HTML. See also the QUOTE keyword.
3284 Not all export backends support this.
3286 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3287 :group 'org-export-translation
3288 :type 'boolean)
3290 (defcustom org-match-sexp-depth 3
3291 "Number of stacked braces for sub/superscript matching.
3292 This has to be set before loading org.el to be effective."
3293 :group 'org-export-translation
3294 :type 'integer)
3296 (defgroup org-export-tables nil
3297 "Options for exporting tables in Org-mode."
3298 :tag "Org Export Tables"
3299 :group 'org-export)
3301 (defcustom org-export-with-tables t
3302 "If non-nil, lines starting with \"|\" define a table.
3303 For example:
3305 | Name | Address | Birthday |
3306 |-------------+----------+-----------|
3307 | Arthur Dent | England | 29.2.2100 |
3309 Not all export backends support this.
3311 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3312 :group 'org-export-tables
3313 :type 'boolean)
3315 (defcustom org-export-highlight-first-table-line t
3316 "Non-nil means, highlight the first table line.
3317 In HTML export, this means use <th> instead of <td>.
3318 In tables created with table.el, this applies to the first table line.
3319 In Org-mode tables, all lines before the first horizontal separator
3320 line will be formatted with <th> tags."
3321 :group 'org-export-tables
3322 :type 'boolean)
3324 (defcustom org-export-table-remove-special-lines t
3325 "Remove special lines and marking characters in calculating tables.
3326 This removes the special marking character column from tables that are set
3327 up for spreadsheet calculations. It also removes the entire lines
3328 marked with `!', `_', or `^'. The lines with `$' are kept, because
3329 the values of constants may be useful to have."
3330 :group 'org-export-tables
3331 :type 'boolean)
3333 (defcustom org-export-prefer-native-exporter-for-tables nil
3334 "Non-nil means, always export tables created with table.el natively.
3335 Natively means, use the HTML code generator in table.el.
3336 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3337 the table does not use row- or column-spanning). This has the
3338 advantage, that the automatic HTML conversions for math symbols and
3339 sub/superscripts can be applied. Org-mode's HTML generator is also
3340 much faster."
3341 :group 'org-export-tables
3342 :type 'boolean)
3344 (defgroup org-export-ascii nil
3345 "Options specific for ASCII export of Org-mode files."
3346 :tag "Org Export ASCII"
3347 :group 'org-export)
3349 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3350 "Characters for underlining headings in ASCII export.
3351 In the given sequence, these characters will be used for level 1, 2, ..."
3352 :group 'org-export-ascii
3353 :type '(repeat character))
3355 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3356 "Bullet characters for headlines converted to lists in ASCII export.
3357 The first character is used for the first lest level generated in this
3358 way, and so on. If there are more levels than characters given here,
3359 the list will be repeated.
3360 Note that plain lists will keep the same bullets as the have in the
3361 Org-mode file."
3362 :group 'org-export-ascii
3363 :type '(repeat character))
3365 (defgroup org-export-xml nil
3366 "Options specific for XML export of Org-mode files."
3367 :tag "Org Export XML"
3368 :group 'org-export)
3370 (defgroup org-export-html nil
3371 "Options specific for HTML export of Org-mode files."
3372 :tag "Org Export HTML"
3373 :group 'org-export)
3375 (defcustom org-export-html-coding-system nil
3377 :group 'org-export-html
3378 :type 'coding-system)
3380 (defcustom org-export-html-extension "html"
3381 "The extension for exported HTML files."
3382 :group 'org-export-html
3383 :type 'string)
3385 (defcustom org-export-html-style
3386 "<style type=\"text/css\">
3387 html {
3388 font-family: Times, serif;
3389 font-size: 12pt;
3391 .title { text-align: center; }
3392 .todo { color: red; }
3393 .done { color: green; }
3394 .timestamp { color: grey }
3395 .timestamp-kwd { color: CadetBlue }
3396 .tag { background-color:lightblue; font-weight:normal }
3397 .target { background-color: lavender; }
3398 pre {
3399 border: 1pt solid #AEBDCC;
3400 background-color: #F3F5F7;
3401 padding: 5pt;
3402 font-family: courier, monospace;
3404 table { border-collapse: collapse; }
3405 td, th {
3406 vertical-align: top;
3407 <!--border: 1pt solid #ADB9CC;-->
3409 </style>"
3410 "The default style specification for exported HTML files.
3411 Since there are different ways of setting style information, this variable
3412 needs to contain the full HTML structure to provide a style, including the
3413 surrounding HTML tags. The style specifications should include definitions
3414 for new classes todo, done, title, and deadline. For example, legal values
3415 would be:
3417 <style type=\"text/css\">
3418 p { font-weight: normal; color: gray; }
3419 h1 { color: black; }
3420 .title { text-align: center; }
3421 .todo, .deadline { color: red; }
3422 .done { color: green; }
3423 </style>
3425 or, if you want to keep the style in a file,
3427 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3429 As the value of this option simply gets inserted into the HTML <head> header,
3430 you can \"misuse\" it to add arbitrary text to the header."
3431 :group 'org-export-html
3432 :type 'string)
3435 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3436 "Format for typesetting the document title in HTML export."
3437 :group 'org-export-html
3438 :type 'string)
3440 (defcustom org-export-html-toplevel-hlevel 2
3441 "The <H> level for level 1 headings in HTML export."
3442 :group 'org-export-html
3443 :type 'string)
3445 (defcustom org-export-html-link-org-files-as-html t
3446 "Non-nil means, make file links to `file.org' point to `file.html'.
3447 When org-mode is exporting an org-mode file to HTML, links to
3448 non-html files are directly put into a href tag in HTML.
3449 However, links to other Org-mode files (recognized by the
3450 extension `.org.) should become links to the corresponding html
3451 file, assuming that the linked org-mode file will also be
3452 converted to HTML.
3453 When nil, the links still point to the plain `.org' file."
3454 :group 'org-export-html
3455 :type 'boolean)
3457 (defcustom org-export-html-inline-images 'maybe
3458 "Non-nil means, inline images into exported HTML pages.
3459 This is done using an <img> tag. When nil, an anchor with href is used to
3460 link to the image. If this option is `maybe', then images in links with
3461 an empty description will be inlined, while images with a description will
3462 be linked only."
3463 :group 'org-export-html
3464 :type '(choice (const :tag "Never" nil)
3465 (const :tag "Always" t)
3466 (const :tag "When there is no description" maybe)))
3468 ;; FIXME: rename
3469 (defcustom org-export-html-expand t
3470 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3471 When nil, these tags will be exported as plain text and therefore
3472 not be interpreted by a browser.
3474 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3475 :group 'org-export-html
3476 :type 'boolean)
3478 (defcustom org-export-html-table-tag
3479 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3480 "The HTML tag that is used to start a table.
3481 This must be a <table> tag, but you may change the options like
3482 borders and spacing."
3483 :group 'org-export-html
3484 :type 'string)
3486 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3487 "The opening tag for table header 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-table-data-tags '("<td>" . "</td>")
3493 "The opening tag for table data fields.
3494 This is customizable so that alignment options can be specified."
3495 :group 'org-export-tables
3496 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3498 (defcustom org-export-html-with-timestamp nil
3499 "If non-nil, write `org-export-html-html-helper-timestamp'
3500 into the exported HTML text. Otherwise, the buffer will just be saved
3501 to a file."
3502 :group 'org-export-html
3503 :type 'boolean)
3505 (defcustom org-export-html-html-helper-timestamp
3506 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3507 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3508 :group 'org-export-html
3509 :type 'string)
3511 (defgroup org-export-icalendar nil
3512 "Options specific for iCalendar export of Org-mode files."
3513 :tag "Org Export iCalendar"
3514 :group 'org-export)
3516 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3517 "The file name for the iCalendar file covering all agenda files.
3518 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3519 The file name should be absolute, the file will be overwritten without warning."
3520 :group 'org-export-icalendar
3521 :type 'file)
3523 (defcustom org-icalendar-include-todo nil
3524 "Non-nil means, export to iCalendar files should also cover TODO items."
3525 :group 'org-export-icalendar
3526 :type '(choice
3527 (const :tag "None" nil)
3528 (const :tag "Unfinished" t)
3529 (const :tag "All" all)))
3531 (defcustom org-icalendar-include-sexps t
3532 "Non-nil means, export to iCalendar files should also cover sexp entries.
3533 These are entries like in the diary, but directly in an Org-mode file."
3534 :group 'org-export-icalendar
3535 :type 'boolean)
3537 (defcustom org-icalendar-include-body 100
3538 "Amount of text below headline to be included in iCalendar export.
3539 This is a number of characters that should maximally be included.
3540 Properties, scheduling and clocking lines will always be removed.
3541 The text will be inserted into the DESCRIPTION field."
3542 :group 'org-export-icalendar
3543 :type '(choice
3544 (const :tag "Nothing" nil)
3545 (const :tag "Everything" t)
3546 (integer :tag "Max characters")))
3548 (defcustom org-icalendar-combined-name "OrgMode"
3549 "Calendar name for the combined iCalendar representing all agenda files."
3550 :group 'org-export-icalendar
3551 :type 'string)
3553 (defgroup org-font-lock nil
3554 "Font-lock settings for highlighting in Org-mode."
3555 :tag "Org Font Lock"
3556 :group 'org)
3558 (defcustom org-level-color-stars-only nil
3559 "Non-nil means fontify only the stars in each headline.
3560 When nil, the entire headline is fontified.
3561 Changing it requires restart of `font-lock-mode' to become effective
3562 also in regions already fontified."
3563 :group 'org-font-lock
3564 :type 'boolean)
3566 (defcustom org-hide-leading-stars nil
3567 "Non-nil means, hide the first N-1 stars in a headline.
3568 This works by using the face `org-hide' for these stars. This
3569 face is white for a light background, and black for a dark
3570 background. You may have to customize the face `org-hide' to
3571 make this work.
3572 Changing it requires restart of `font-lock-mode' to become effective
3573 also in regions already fontified.
3574 You may also set this on a per-file basis by adding one of the following
3575 lines to the buffer:
3577 #+STARTUP: hidestars
3578 #+STARTUP: showstars"
3579 :group 'org-font-lock
3580 :type 'boolean)
3582 (defcustom org-fontify-done-headline nil
3583 "Non-nil means, change the face of a headline if it is marked DONE.
3584 Normally, only the TODO/DONE keyword indicates the state of a headline.
3585 When this is non-nil, the headline after the keyword is set to the
3586 `org-headline-done' as an additional indication."
3587 :group 'org-font-lock
3588 :type 'boolean)
3590 (defcustom org-fontify-emphasized-text t
3591 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3592 Changing this variable requires a restart of Emacs to take effect."
3593 :group 'org-font-lock
3594 :type 'boolean)
3596 (defcustom org-highlight-latex-fragments-and-specials nil
3597 "Non-nil means, fontify what is treated specially by the exporters."
3598 :group 'org-font-lock
3599 :type 'boolean)
3601 (defcustom org-hide-emphasis-markers nil
3602 "Non-nil mean font-lock should hide the emphasis marker characters."
3603 :group 'org-font-lock
3604 :type 'boolean)
3606 (defvar org-emph-re nil
3607 "Regular expression for matching emphasis.")
3608 (defvar org-verbatim-re nil
3609 "Regular expression for matching verbatim text.")
3610 (defvar org-emphasis-regexp-components) ; defined just below
3611 (defvar org-emphasis-alist) ; defined just below
3612 (defun org-set-emph-re (var val)
3613 "Set variable and compute the emphasis regular expression."
3614 (set var val)
3615 (when (and (boundp 'org-emphasis-alist)
3616 (boundp 'org-emphasis-regexp-components)
3617 org-emphasis-alist org-emphasis-regexp-components)
3618 (let* ((e org-emphasis-regexp-components)
3619 (pre (car e))
3620 (post (nth 1 e))
3621 (border (nth 2 e))
3622 (body (nth 3 e))
3623 (nl (nth 4 e))
3624 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3625 (body1 (concat body "*?"))
3626 (markers (mapconcat 'car org-emphasis-alist ""))
3627 (vmarkers (mapconcat
3628 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3629 org-emphasis-alist "")))
3630 ;; make sure special characters appear at the right position in the class
3631 (if (string-match "\\^" markers)
3632 (setq markers (concat (replace-match "" t t markers) "^")))
3633 (if (string-match "-" markers)
3634 (setq markers (concat (replace-match "" t t markers) "-")))
3635 (if (string-match "\\^" vmarkers)
3636 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3637 (if (string-match "-" vmarkers)
3638 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3639 (if (> nl 0)
3640 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3641 (int-to-string nl) "\\}")))
3642 ;; Make the regexp
3643 (setq org-emph-re
3644 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3645 "\\("
3646 "\\([" markers "]\\)"
3647 "\\("
3648 "[^" border "]\\|"
3649 "[^" border (if (and nil stacked) markers) "]"
3650 body1
3651 "[^" border (if (and nil stacked) markers) "]"
3652 "\\)"
3653 "\\3\\)"
3654 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3655 (setq org-verbatim-re
3656 (concat "\\([" pre "]\\|^\\)"
3657 "\\("
3658 "\\([" vmarkers "]\\)"
3659 "\\("
3660 "[^" border "]\\|"
3661 "[^" border "]"
3662 body1
3663 "[^" border "]"
3664 "\\)"
3665 "\\3\\)"
3666 "\\([" post "]\\|$\\)")))))
3668 (defcustom org-emphasis-regexp-components
3669 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3670 "Components used to build the regular expression for emphasis.
3671 This is a list with 6 entries. Terminology: In an emphasis string
3672 like \" *strong word* \", we call the initial space PREMATCH, the final
3673 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3674 and \"trong wor\" is the body. The different components in this variable
3675 specify what is allowed/forbidden in each part:
3677 pre Chars allowed as prematch. Beginning of line will be allowed too.
3678 post Chars allowed as postmatch. End of line will be allowed too.
3679 border The chars *forbidden* as border characters.
3680 body-regexp A regexp like \".\" to match a body character. Don't use
3681 non-shy groups here, and don't allow newline here.
3682 newline The maximum number of newlines allowed in an emphasis exp.
3684 Use customize to modify this, or restart Emacs after changing it."
3685 :group 'org-font-lock
3686 :set 'org-set-emph-re
3687 :type '(list
3688 (sexp :tag "Allowed chars in pre ")
3689 (sexp :tag "Allowed chars in post ")
3690 (sexp :tag "Forbidden chars in border ")
3691 (sexp :tag "Regexp for body ")
3692 (integer :tag "number of newlines allowed")
3693 (option (boolean :tag "Stacking (DISABLED) "))))
3695 (defcustom org-emphasis-alist
3696 '(("*" bold "<b>" "</b>")
3697 ("/" italic "<i>" "</i>")
3698 ("_" underline "<u>" "</u>")
3699 ("=" org-code "<code>" "</code>" verbatim)
3700 ("~" org-verbatim "" "" verbatim)
3701 ("+" (:strike-through t) "<del>" "</del>")
3703 "Special syntax for emphasized text.
3704 Text starting and ending with a special character will be emphasized, for
3705 example *bold*, _underlined_ and /italic/. This variable sets the marker
3706 characters, the face to be used by font-lock for highlighting in Org-mode
3707 Emacs buffers, and the HTML tags to be used for this.
3708 Use customize to modify this, or restart Emacs after changing it."
3709 :group 'org-font-lock
3710 :set 'org-set-emph-re
3711 :type '(repeat
3712 (list
3713 (string :tag "Marker character")
3714 (choice
3715 (face :tag "Font-lock-face")
3716 (plist :tag "Face property list"))
3717 (string :tag "HTML start tag")
3718 (string :tag "HTML end tag")
3719 (option (const verbatim)))))
3721 ;;; The faces
3723 (defgroup org-faces nil
3724 "Faces in Org-mode."
3725 :tag "Org Faces"
3726 :group 'org-font-lock)
3728 (defun org-compatible-face (inherits specs)
3729 "Make a compatible face specification.
3730 If INHERITS is an existing face and if the Emacs version supports it,
3731 just inherit the face. If not, use SPECS to define the face.
3732 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3733 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3734 to the top of the list. The `min-colors' attribute will be removed from
3735 any other entries, and any resulting duplicates will be removed entirely."
3736 (cond
3737 ((and inherits (facep inherits)
3738 (not (featurep 'xemacs)) (> emacs-major-version 22))
3739 ;; In Emacs 23, we use inheritance where possible.
3740 ;; We only do this in Emacs 23, because only there the outline
3741 ;; faces have been changed to the original org-mode-level-faces.
3742 (list (list t :inherit inherits)))
3743 ((or (featurep 'xemacs) (< emacs-major-version 22))
3744 ;; These do not understand the `min-colors' attribute.
3745 (let (r e a)
3746 (while (setq e (pop specs))
3747 (cond
3748 ((memq (car e) '(t default)) (push e r))
3749 ((setq a (member '(min-colors 8) (car e)))
3750 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3751 (cdr e)))))
3752 ((setq a (assq 'min-colors (car e)))
3753 (setq e (cons (delq a (car e)) (cdr e)))
3754 (or (assoc (car e) r) (push e r)))
3755 (t (or (assoc (car e) r) (push e r)))))
3756 (nreverse r)))
3757 (t specs)))
3758 (put 'org-compatible-face 'lisp-indent-function 1)
3760 (defface org-hide
3761 '((((background light)) (:foreground "white"))
3762 (((background dark)) (:foreground "black")))
3763 "Face used to hide leading stars in headlines.
3764 The forground color of this face should be equal to the background
3765 color of the frame."
3766 :group 'org-faces)
3768 (defface org-level-1 ;; font-lock-function-name-face
3769 (org-compatible-face 'outline-1
3770 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3771 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3772 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3773 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3774 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3775 (t (:bold t))))
3776 "Face used for level 1 headlines."
3777 :group 'org-faces)
3779 (defface org-level-2 ;; font-lock-variable-name-face
3780 (org-compatible-face 'outline-2
3781 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3782 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3783 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3784 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3785 (t (:bold t))))
3786 "Face used for level 2 headlines."
3787 :group 'org-faces)
3789 (defface org-level-3 ;; font-lock-keyword-face
3790 (org-compatible-face 'outline-3
3791 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3792 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3793 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3794 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3795 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3796 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3797 (t (:bold t))))
3798 "Face used for level 3 headlines."
3799 :group 'org-faces)
3801 (defface org-level-4 ;; font-lock-comment-face
3802 (org-compatible-face 'outline-4
3803 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3804 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3805 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3806 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3807 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3808 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3809 (t (:bold t))))
3810 "Face used for level 4 headlines."
3811 :group 'org-faces)
3813 (defface org-level-5 ;; font-lock-type-face
3814 (org-compatible-face 'outline-5
3815 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3816 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3817 (((class color) (min-colors 8)) (:foreground "green"))))
3818 "Face used for level 5 headlines."
3819 :group 'org-faces)
3821 (defface org-level-6 ;; font-lock-constant-face
3822 (org-compatible-face 'outline-6
3823 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3824 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3825 (((class color) (min-colors 8)) (:foreground "magenta"))))
3826 "Face used for level 6 headlines."
3827 :group 'org-faces)
3829 (defface org-level-7 ;; font-lock-builtin-face
3830 (org-compatible-face 'outline-7
3831 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3832 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3833 (((class color) (min-colors 8)) (:foreground "blue"))))
3834 "Face used for level 7 headlines."
3835 :group 'org-faces)
3837 (defface org-level-8 ;; font-lock-string-face
3838 (org-compatible-face 'outline-8
3839 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3840 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3841 (((class color) (min-colors 8)) (:foreground "green"))))
3842 "Face used for level 8 headlines."
3843 :group 'org-faces)
3845 (defface org-special-keyword ;; font-lock-string-face
3846 (org-compatible-face nil
3847 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3848 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3849 (t (:italic t))))
3850 "Face used for special keywords."
3851 :group 'org-faces)
3853 (defface org-drawer ;; font-lock-function-name-face
3854 (org-compatible-face nil
3855 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3856 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3857 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3858 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3859 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3860 (t (:bold t))))
3861 "Face used for drawers."
3862 :group 'org-faces)
3864 (defface org-property-value nil
3865 "Face used for the value of a property."
3866 :group 'org-faces)
3868 (defface org-column
3869 (org-compatible-face nil
3870 '((((class color) (min-colors 16) (background light))
3871 (:background "grey90"))
3872 (((class color) (min-colors 16) (background dark))
3873 (:background "grey30"))
3874 (((class color) (min-colors 8))
3875 (:background "cyan" :foreground "black"))
3876 (t (:inverse-video t))))
3877 "Face for column display of entry properties."
3878 :group 'org-faces)
3880 (when (fboundp 'set-face-attribute)
3881 ;; Make sure that a fixed-width face is used when we have a column table.
3882 (set-face-attribute 'org-column nil
3883 :height (face-attribute 'default :height)
3884 :family (face-attribute 'default :family)))
3886 (defface org-warning
3887 (org-compatible-face 'font-lock-warning-face
3888 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3889 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3890 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3891 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3892 (t (:bold t))))
3893 "Face for deadlines and TODO keywords."
3894 :group 'org-faces)
3896 (defface org-archived ; similar to shadow
3897 (org-compatible-face 'shadow
3898 '((((class color grayscale) (min-colors 88) (background light))
3899 (:foreground "grey50"))
3900 (((class color grayscale) (min-colors 88) (background dark))
3901 (:foreground "grey70"))
3902 (((class color) (min-colors 8) (background light))
3903 (:foreground "green"))
3904 (((class color) (min-colors 8) (background dark))
3905 (:foreground "yellow"))))
3906 "Face for headline with the ARCHIVE tag."
3907 :group 'org-faces)
3909 (defface org-link
3910 '((((class color) (background light)) (:foreground "Purple" :underline t))
3911 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3912 (t (:underline t)))
3913 "Face for links."
3914 :group 'org-faces)
3916 (defface org-ellipsis
3917 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
3918 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
3919 (t (:strike-through t)))
3920 "Face for the ellipsis in folded text."
3921 :group 'org-faces)
3923 (defface org-target
3924 '((((class color) (background light)) (:underline t))
3925 (((class color) (background dark)) (:underline t))
3926 (t (:underline t)))
3927 "Face for links."
3928 :group 'org-faces)
3930 (defface org-date
3931 '((((class color) (background light)) (:foreground "Purple" :underline t))
3932 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3933 (t (:underline t)))
3934 "Face for links."
3935 :group 'org-faces)
3937 (defface org-sexp-date
3938 '((((class color) (background light)) (:foreground "Purple"))
3939 (((class color) (background dark)) (:foreground "Cyan"))
3940 (t (:underline t)))
3941 "Face for links."
3942 :group 'org-faces)
3944 (defface org-tag
3945 '((t (:bold t)))
3946 "Face for tags."
3947 :group 'org-faces)
3949 (defface org-todo ; font-lock-warning-face
3950 (org-compatible-face nil
3951 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3952 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3953 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3954 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3955 (t (:inverse-video t :bold t))))
3956 "Face for TODO keywords."
3957 :group 'org-faces)
3959 (defface org-done ;; font-lock-type-face
3960 (org-compatible-face nil
3961 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
3962 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
3963 (((class color) (min-colors 8)) (:foreground "green"))
3964 (t (:bold t))))
3965 "Face used for todo keywords that indicate DONE items."
3966 :group 'org-faces)
3968 (defface org-headline-done ;; font-lock-string-face
3969 (org-compatible-face nil
3970 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3971 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3972 (((class color) (min-colors 8) (background light)) (:bold nil))))
3973 "Face used to indicate that a headline is DONE.
3974 This face is only used if `org-fontify-done-headline' is set. If applies
3975 to the part of the headline after the DONE keyword."
3976 :group 'org-faces)
3978 (defcustom org-todo-keyword-faces nil
3979 "Faces for specific TODO keywords.
3980 This is a list of cons cells, with TODO keywords in the car
3981 and faces in the cdr. The face can be a symbol, or a property
3982 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
3983 :group 'org-faces
3984 :group 'org-todo
3985 :type '(repeat
3986 (cons
3987 (string :tag "keyword")
3988 (sexp :tag "face"))))
3990 (defface org-table ;; font-lock-function-name-face
3991 (org-compatible-face nil
3992 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3993 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3994 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3995 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3996 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
3997 (((class color) (min-colors 8) (background dark)))))
3998 "Face used for tables."
3999 :group 'org-faces)
4001 (defface org-formula
4002 (org-compatible-face nil
4003 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4004 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4005 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4006 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
4007 (t (:bold t :italic t))))
4008 "Face for formulas."
4009 :group 'org-faces)
4011 (defface org-code
4012 (org-compatible-face nil
4013 '((((class color grayscale) (min-colors 88) (background light))
4014 (:foreground "grey50"))
4015 (((class color grayscale) (min-colors 88) (background dark))
4016 (:foreground "grey70"))
4017 (((class color) (min-colors 8) (background light))
4018 (:foreground "green"))
4019 (((class color) (min-colors 8) (background dark))
4020 (:foreground "yellow"))))
4021 "Face for fixed-with text like code snippets."
4022 :group 'org-faces
4023 :version "22.1")
4025 (defface org-verbatim
4026 (org-compatible-face nil
4027 '((((class color grayscale) (min-colors 88) (background light))
4028 (:foreground "grey50" :underline t))
4029 (((class color grayscale) (min-colors 88) (background dark))
4030 (:foreground "grey70" :underline t))
4031 (((class color) (min-colors 8) (background light))
4032 (:foreground "green" :underline t))
4033 (((class color) (min-colors 8) (background dark))
4034 (:foreground "yellow" :underline t))))
4035 "Face for fixed-with text like code snippets."
4036 :group 'org-faces
4037 :version "22.1")
4039 (defface org-agenda-structure ;; font-lock-function-name-face
4040 (org-compatible-face nil
4041 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4042 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4043 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4044 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4045 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4046 (t (:bold t))))
4047 "Face used in agenda for captions and dates."
4048 :group 'org-faces)
4050 (defface org-scheduled-today
4051 (org-compatible-face nil
4052 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
4053 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
4054 (((class color) (min-colors 8)) (:foreground "green"))
4055 (t (:bold t :italic t))))
4056 "Face for items scheduled for a certain day."
4057 :group 'org-faces)
4059 (defface org-scheduled-previously
4060 (org-compatible-face nil
4061 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4062 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4063 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4064 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4065 (t (:bold t))))
4066 "Face for items scheduled previously, and not yet done."
4067 :group 'org-faces)
4069 (defface org-upcoming-deadline
4070 (org-compatible-face nil
4071 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4072 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4073 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4074 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4075 (t (:bold t))))
4076 "Face for items scheduled previously, and not yet done."
4077 :group 'org-faces)
4079 (defcustom org-agenda-deadline-faces
4080 '((1.0 . org-warning)
4081 (0.5 . org-upcoming-deadline)
4082 (0.0 . default))
4083 "Faces for showing deadlines in the agenda.
4084 This is a list of cons cells. The cdr of each cell is a face to be used,
4085 and it can also just be like '(:foreground \"yellow\").
4086 Each car is a fraction of the head-warning time that must have passed for
4087 this the face in the cdr to be used for display. The numbers must be
4088 given in descending order. The head-warning time is normally taken
4089 from `org-deadline-warning-days', but can also be specified in the deadline
4090 timestamp itself, like this:
4092 DEADLINE: <2007-08-13 Mon -8d>
4094 You may use d for days, w for weeks, m for months and y for years. Months
4095 and years will only be treated in an approximate fashion (30.4 days for a
4096 month and 365.24 days for a year)."
4097 :group 'org-faces
4098 :group 'org-agenda-daily/weekly
4099 :type '(repeat
4100 (cons
4101 (number :tag "Fraction of head-warning time passed")
4102 (sexp :tag "Face"))))
4104 ;; FIXME: this is not a good face yet.
4105 (defface org-agenda-restriction-lock
4106 (org-compatible-face nil
4107 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
4108 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
4109 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
4110 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
4111 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
4112 (t (:inverse-video t))))
4113 "Face for showing the agenda restriction lock."
4114 :group 'org-faces)
4116 (defface org-time-grid ;; font-lock-variable-name-face
4117 (org-compatible-face nil
4118 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4119 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4120 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4121 "Face used for time grids."
4122 :group 'org-faces)
4124 (defconst org-level-faces
4125 '(org-level-1 org-level-2 org-level-3 org-level-4
4126 org-level-5 org-level-6 org-level-7 org-level-8
4129 (defcustom org-n-level-faces (length org-level-faces)
4130 "The number different faces to be used for headlines.
4131 Org-mode defines 8 different headline faces, so this can be at most 8.
4132 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4133 :type 'number
4134 :group 'org-faces)
4136 ;;; Functions and variables from ther packages
4137 ;; Declared here to avoid compiler warnings
4139 (eval-and-compile
4140 (unless (fboundp 'declare-function)
4141 (defmacro declare-function (fn file &optional arglist fileonly))))
4143 ;; XEmacs only
4144 (defvar outline-mode-menu-heading)
4145 (defvar outline-mode-menu-show)
4146 (defvar outline-mode-menu-hide)
4147 (defvar zmacs-regions) ; XEmacs regions
4149 ;; Emacs only
4150 (defvar mark-active)
4152 ;; Various packages
4153 ;; FIXME: get the argument lists for the UNKNOWN stuff
4154 (declare-function add-to-diary-list "diary-lib"
4155 (date string specifier &optional marker globcolor literal))
4156 (declare-function table--at-cell-p "table" (position &optional object at-column))
4157 (declare-function Info-find-node "info" (filename nodename &optional no-going-back))
4158 (declare-function Info-goto-node "info" (nodename &optional fork))
4159 (declare-function bbdb "ext:bbdb-com" (string elidep))
4160 (declare-function bbdb-company "ext:bbdb-com" (string elidep))
4161 (declare-function bbdb-current-record "ext:bbdb-com" (&optional planning-on-modifying))
4162 (declare-function bbdb-name "ext:bbdb-com" (string elidep))
4163 (declare-function bbdb-record-getprop "ext:bbdb" (record property))
4164 (declare-function bbdb-record-name "ext:bbdb" (record))
4165 (declare-function bibtex-beginning-of-entry "bibtex" ())
4166 (declare-function bibtex-generate-autokey "bibtex" ())
4167 (declare-function bibtex-parse-entry "bibtex" (&optional content))
4168 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
4169 (defvar calc-embedded-close-formula)
4170 (defvar calc-embedded-open-formula)
4171 (declare-function calendar-astro-date-string "cal-julian" (&optional date))
4172 (declare-function calendar-bahai-date-string "cal-bahai" (&optional date))
4173 (declare-function calendar-check-holidays "holidays" (date))
4174 (declare-function calendar-chinese-date-string "cal-china" (&optional date))
4175 (declare-function calendar-coptic-date-string "cal-coptic" (&optional date))
4176 (declare-function calendar-ethiopic-date-string "cal-coptic" (&optional date))
4177 (declare-function calendar-forward-day "cal-move" (arg))
4178 (declare-function calendar-french-date-string "cal-french" (&optional date))
4179 (declare-function calendar-goto-date "cal-move" (date))
4180 (declare-function calendar-goto-today "cal-move" ())
4181 (declare-function calendar-hebrew-date-string "cal-hebrew" (&optional date))
4182 (declare-function calendar-islamic-date-string "cal-islam" (&optional date))
4183 (declare-function calendar-iso-date-string "cal-iso" (&optional date))
4184 (declare-function calendar-julian-date-string "cal-julian" (&optional date))
4185 (declare-function calendar-mayan-date-string "cal-mayan" (&optional date))
4186 (declare-function calendar-persian-date-string "cal-persia" (&optional date))
4187 (defvar calendar-mode-map)
4188 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4189 (declare-function cdlatex-tab "ext:cdlatex" ())
4190 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4191 (declare-function elmo-folder-exists-p "ext:elmo" (folder) t)
4192 (declare-function elmo-message-entity-field "ext:elmo-msgdb" (entity field &optional type))
4193 (declare-function elmo-message-field "ext:elmo" (folder number field &optional type) t)
4194 (declare-function elmo-msgdb-overview-get-entity "ext:elmo" (&rest unknown) t)
4195 (defvar font-lock-unfontify-region-function)
4196 (declare-function gnus-article-show-summary "gnus-art" ())
4197 (declare-function gnus-summary-last-subject "gnus-sum" ())
4198 (defvar gnus-other-frame-object)
4199 (defvar gnus-group-name)
4200 (defvar gnus-article-current)
4201 (defvar Info-current-file)
4202 (defvar Info-current-node)
4203 (declare-function mh-display-msg "mh-show" (msg-num folder-name))
4204 (declare-function mh-find-path "mh-utils" ())
4205 (declare-function mh-get-header-field "mh-utils" (field))
4206 (declare-function mh-get-msg-num "mh-utils" (error-if-no-message))
4207 (declare-function mh-header-display "mh-show" ())
4208 (declare-function mh-index-previous-folder "mh-search" ())
4209 (declare-function mh-normalize-folder-name "mh-utils" (folder &optional empty-string-okay dont-remove-trailing-slash return-nil-if-folder-empty))
4210 (declare-function mh-search "mh-search" (folder search-regexp &optional redo-search-flag window-config))
4211 (declare-function mh-search-choose "mh-search" (&optional searcher))
4212 (declare-function mh-show "mh-show" (&optional message redisplay-flag))
4213 (declare-function mh-show-buffer-message-number "mh-comp" (&optional buffer))
4214 (declare-function mh-show-header-display "mh-show" t t)
4215 (declare-function mh-show-msg "mh-show" (msg))
4216 (declare-function mh-show-show "mh-show" t t)
4217 (declare-function mh-visit-folder "mh-folder" (folder &optional range index-data))
4218 (defvar mh-progs)
4219 (defvar mh-current-folder)
4220 (defvar mh-show-folder-buffer)
4221 (defvar mh-index-folder)
4222 (defvar mh-searcher)
4223 (declare-function org-export-latex-cleaned-string "org-export-latex" ())
4224 (declare-function parse-time-string "parse-time" (string))
4225 (declare-function remember "remember" (&optional initial))
4226 (declare-function remember-buffer-desc "remember" ())
4227 (declare-function remember-finalize "remember" ())
4228 (defvar remember-save-after-remembering)
4229 (defvar remember-data-file)
4230 (defvar remember-register)
4231 (defvar remember-buffer)
4232 (defvar remember-handler-functions)
4233 (defvar remember-annotation-functions)
4234 (declare-function rmail-narrow-to-non-pruned-header "rmail" ())
4235 (declare-function rmail-show-message "rmail" (&optional n no-summary))
4236 (declare-function rmail-what-message "rmail" ())
4237 (defvar texmathp-why)
4238 (declare-function vm-beginning-of-message "ext:vm-page" ())
4239 (declare-function vm-follow-summary-cursor "ext:vm-motion" ())
4240 (declare-function vm-get-header-contents "ext:vm-summary" (message header-name-regexp &optional clump-sep))
4241 (declare-function vm-isearch-narrow "ext:vm-search" ())
4242 (declare-function vm-isearch-update "ext:vm-search" ())
4243 (declare-function vm-select-folder-buffer "ext:vm-macro" ())
4244 (declare-function vm-su-message-id "ext:vm-summary" (m))
4245 (declare-function vm-su-subject "ext:vm-summary" (m))
4246 (declare-function vm-summarize "ext:vm-summary" (&optional display raise))
4247 (defvar vm-message-pointer)
4248 (defvar vm-folder-directory)
4249 (defvar w3m-current-url)
4250 (defvar w3m-current-title)
4251 ;; backward compatibility to old version of wl
4252 (declare-function wl-summary-buffer-msgdb "ext:wl-folder" (&rest unknown) t)
4253 (declare-function wl-folder-get-elmo-folder "ext:wl-folder" (entity &optional no-cache))
4254 (declare-function wl-summary-goto-folder-subr "ext:wl-summary" (&optional name scan-type other-window sticky interactive scoring force-exit))
4255 (declare-function wl-summary-jump-to-msg-by-message-id "ext:wl-summary" (&optional id))
4256 (declare-function wl-summary-line-from "ext:wl-summary" ())
4257 (declare-function wl-summary-line-subject "ext:wl-summary" ())
4258 (declare-function wl-summary-message-number "ext:wl-summary" ())
4259 (declare-function wl-summary-redisplay "ext:wl-summary" (&optional arg))
4260 (defvar wl-summary-buffer-elmo-folder)
4261 (defvar wl-summary-buffer-folder-name)
4262 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4264 (defvar org-latex-regexps)
4265 (defvar constants-unit-system)
4267 ;;; Variables for pre-computed regular expressions, all buffer local
4269 (defvar org-drawer-regexp nil
4270 "Matches first line of a hidden block.")
4271 (make-variable-buffer-local 'org-drawer-regexp)
4272 (defvar org-todo-regexp nil
4273 "Matches any of the TODO state keywords.")
4274 (make-variable-buffer-local 'org-todo-regexp)
4275 (defvar org-not-done-regexp nil
4276 "Matches any of the TODO state keywords except the last one.")
4277 (make-variable-buffer-local 'org-not-done-regexp)
4278 (defvar org-todo-line-regexp nil
4279 "Matches a headline and puts TODO state into group 2 if present.")
4280 (make-variable-buffer-local 'org-todo-line-regexp)
4281 (defvar org-complex-heading-regexp nil
4282 "Matches a headline and puts everything into groups:
4283 group 1: the stars
4284 group 2: The todo keyword, maybe
4285 group 3: Priority cookie
4286 group 4: True headline
4287 group 5: Tags")
4288 (make-variable-buffer-local 'org-complex-heading-regexp)
4289 (defvar org-todo-line-tags-regexp nil
4290 "Matches a headline and puts TODO state into group 2 if present.
4291 Also put tags into group 4 if tags are present.")
4292 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4293 (defvar org-nl-done-regexp nil
4294 "Matches newline followed by a headline with the DONE keyword.")
4295 (make-variable-buffer-local 'org-nl-done-regexp)
4296 (defvar org-looking-at-done-regexp nil
4297 "Matches the DONE keyword a point.")
4298 (make-variable-buffer-local 'org-looking-at-done-regexp)
4299 (defvar org-ds-keyword-length 12
4300 "Maximum length of the Deadline and SCHEDULED keywords.")
4301 (make-variable-buffer-local 'org-ds-keyword-length)
4302 (defvar org-deadline-regexp nil
4303 "Matches the DEADLINE keyword.")
4304 (make-variable-buffer-local 'org-deadline-regexp)
4305 (defvar org-deadline-time-regexp nil
4306 "Matches the DEADLINE keyword together with a time stamp.")
4307 (make-variable-buffer-local 'org-deadline-time-regexp)
4308 (defvar org-deadline-line-regexp nil
4309 "Matches the DEADLINE keyword and the rest of the line.")
4310 (make-variable-buffer-local 'org-deadline-line-regexp)
4311 (defvar org-scheduled-regexp nil
4312 "Matches the SCHEDULED keyword.")
4313 (make-variable-buffer-local 'org-scheduled-regexp)
4314 (defvar org-scheduled-time-regexp nil
4315 "Matches the SCHEDULED keyword together with a time stamp.")
4316 (make-variable-buffer-local 'org-scheduled-time-regexp)
4317 (defvar org-closed-time-regexp nil
4318 "Matches the CLOSED keyword together with a time stamp.")
4319 (make-variable-buffer-local 'org-closed-time-regexp)
4321 (defvar org-keyword-time-regexp nil
4322 "Matches any of the 4 keywords, together with the time stamp.")
4323 (make-variable-buffer-local 'org-keyword-time-regexp)
4324 (defvar org-keyword-time-not-clock-regexp nil
4325 "Matches any of the 3 keywords, together with the time stamp.")
4326 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4327 (defvar org-maybe-keyword-time-regexp nil
4328 "Matches a timestamp, possibly preceeded by a keyword.")
4329 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4330 (defvar org-planning-or-clock-line-re nil
4331 "Matches a line with planning or clock info.")
4332 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4334 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4335 rear-nonsticky t mouse-map t fontified t)
4336 "Properties to remove when a string without properties is wanted.")
4338 (defsubst org-match-string-no-properties (num &optional string)
4339 (if (featurep 'xemacs)
4340 (let ((s (match-string num string)))
4341 (remove-text-properties 0 (length s) org-rm-props s)
4343 (match-string-no-properties num string)))
4345 (defsubst org-no-properties (s)
4346 (if (fboundp 'set-text-properties)
4347 (set-text-properties 0 (length s) nil s)
4348 (remove-text-properties 0 (length s) org-rm-props s))
4351 (defsubst org-get-alist-option (option key)
4352 (cond ((eq key t) t)
4353 ((eq option t) t)
4354 ((assoc key option) (cdr (assoc key option)))
4355 (t (cdr (assq 'default option)))))
4357 (defsubst org-inhibit-invisibility ()
4358 "Modified `buffer-invisibility-spec' for Emacs 21.
4359 Some ops with invisible text do not work correctly on Emacs 21. For these
4360 we turn off invisibility temporarily. Use this in a `let' form."
4361 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4363 (defsubst org-set-local (var value)
4364 "Make VAR local in current buffer and set it to VALUE."
4365 (set (make-variable-buffer-local var) value))
4367 (defsubst org-mode-p ()
4368 "Check if the current buffer is in Org-mode."
4369 (eq major-mode 'org-mode))
4371 (defsubst org-last (list)
4372 "Return the last element of LIST."
4373 (car (last list)))
4375 (defun org-let (list &rest body)
4376 (eval (cons 'let (cons list body))))
4377 (put 'org-let 'lisp-indent-function 1)
4379 (defun org-let2 (list1 list2 &rest body)
4380 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4381 (put 'org-let2 'lisp-indent-function 2)
4382 (defconst org-startup-options
4383 '(("fold" org-startup-folded t)
4384 ("overview" org-startup-folded t)
4385 ("nofold" org-startup-folded nil)
4386 ("showall" org-startup-folded nil)
4387 ("content" org-startup-folded content)
4388 ("hidestars" org-hide-leading-stars t)
4389 ("showstars" org-hide-leading-stars nil)
4390 ("odd" org-odd-levels-only t)
4391 ("oddeven" org-odd-levels-only nil)
4392 ("align" org-startup-align-all-tables t)
4393 ("noalign" org-startup-align-all-tables nil)
4394 ("customtime" org-display-custom-times t)
4395 ("logging" org-log-done t)
4396 ("logdone" org-log-done t)
4397 ("nologging" org-log-done nil)
4398 ("lognotedone" org-log-done done push)
4399 ("lognotestate" org-log-done state push)
4400 ("lognoteclock-out" org-log-done clock-out push)
4401 ("logrepeat" org-log-repeat t)
4402 ("nologrepeat" org-log-repeat nil)
4403 ("constcgs" constants-unit-system cgs)
4404 ("constSI" constants-unit-system SI))
4405 "Variable associated with STARTUP options for org-mode.
4406 Each element is a list of three items: The startup options as written
4407 in the #+STARTUP line, the corresponding variable, and the value to
4408 set this variable to if the option is found. An optional forth element PUSH
4409 means to push this value onto the list in the variable.")
4411 (defun org-set-regexps-and-options ()
4412 "Precompute regular expressions for current buffer."
4413 (when (org-mode-p)
4414 (org-set-local 'org-todo-kwd-alist nil)
4415 (org-set-local 'org-todo-key-alist nil)
4416 (org-set-local 'org-todo-key-trigger nil)
4417 (org-set-local 'org-todo-keywords-1 nil)
4418 (org-set-local 'org-done-keywords nil)
4419 (org-set-local 'org-todo-heads nil)
4420 (org-set-local 'org-todo-sets nil)
4421 (org-set-local 'org-todo-log-states nil)
4422 (let ((re (org-make-options-regexp
4423 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4424 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4425 "CONSTANTS" "PROPERTY" "DRAWERS")))
4426 (splitre "[ \t]+")
4427 kwds kws0 kwsa key value cat arch tags const links hw dws
4428 tail sep kws1 prio props drawers
4429 ex log)
4430 (save-excursion
4431 (save-restriction
4432 (widen)
4433 (goto-char (point-min))
4434 (while (re-search-forward re nil t)
4435 (setq key (match-string 1) value (org-match-string-no-properties 2))
4436 (cond
4437 ((equal key "CATEGORY")
4438 (if (string-match "[ \t]+$" value)
4439 (setq value (replace-match "" t t value)))
4440 (setq cat value))
4441 ((member key '("SEQ_TODO" "TODO"))
4442 (push (cons 'sequence (org-split-string value splitre)) kwds))
4443 ((equal key "TYP_TODO")
4444 (push (cons 'type (org-split-string value splitre)) kwds))
4445 ((equal key "TAGS")
4446 (setq tags (append tags (org-split-string value splitre))))
4447 ((equal key "COLUMNS")
4448 (org-set-local 'org-columns-default-format value))
4449 ((equal key "LINK")
4450 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4451 (push (cons (match-string 1 value)
4452 (org-trim (match-string 2 value)))
4453 links)))
4454 ((equal key "PRIORITIES")
4455 (setq prio (org-split-string value " +")))
4456 ((equal key "PROPERTY")
4457 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4458 (push (cons (match-string 1 value) (match-string 2 value))
4459 props)))
4460 ((equal key "DRAWERS")
4461 (setq drawers (org-split-string value splitre)))
4462 ((equal key "CONSTANTS")
4463 (setq const (append const (org-split-string value splitre))))
4464 ((equal key "STARTUP")
4465 (let ((opts (org-split-string value splitre))
4466 l var val)
4467 (while (setq l (pop opts))
4468 (when (setq l (assoc l org-startup-options))
4469 (setq var (nth 1 l) val (nth 2 l))
4470 (if (not (nth 3 l))
4471 (set (make-local-variable var) val)
4472 (if (not (listp (symbol-value var)))
4473 (set (make-local-variable var) nil))
4474 (set (make-local-variable var) (symbol-value var))
4475 (add-to-list var val))))))
4476 ((equal key "ARCHIVE")
4477 (string-match " *$" value)
4478 (setq arch (replace-match "" t t value))
4479 (remove-text-properties 0 (length arch)
4480 '(face t fontified t) arch)))
4482 (when cat
4483 (org-set-local 'org-category (intern cat))
4484 (push (cons "CATEGORY" cat) props))
4485 (when prio
4486 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4487 (setq prio (mapcar 'string-to-char prio))
4488 (org-set-local 'org-highest-priority (nth 0 prio))
4489 (org-set-local 'org-lowest-priority (nth 1 prio))
4490 (org-set-local 'org-default-priority (nth 2 prio)))
4491 (and props (org-set-local 'org-local-properties (nreverse props)))
4492 (and drawers (org-set-local 'org-drawers drawers))
4493 (and arch (org-set-local 'org-archive-location arch))
4494 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4495 ;; Process the TODO keywords
4496 (unless kwds
4497 ;; Use the global values as if they had been given locally.
4498 (setq kwds (default-value 'org-todo-keywords))
4499 (if (stringp (car kwds))
4500 (setq kwds (list (cons org-todo-interpretation
4501 (default-value 'org-todo-keywords)))))
4502 (setq kwds (reverse kwds)))
4503 (setq kwds (nreverse kwds))
4504 (let (inter kws kw)
4505 (while (setq kws (pop kwds))
4506 (setq inter (pop kws) sep (member "|" kws)
4507 kws0 (delete "|" (copy-sequence kws))
4508 kwsa nil
4509 kws1 (mapcar
4510 (lambda (x)
4511 (if (string-match "^\\(.*?\\)\\(?:(\\(..?\\))\\)?$" x)
4512 (progn
4513 (setq kw (match-string 1 x)
4514 ex (and (match-end 2) (match-string 2 x))
4515 log (and ex (string-match "@" ex))
4516 key (and ex (substring ex 0 1)))
4517 (if (equal key "@") (setq key nil))
4518 (push (cons kw (and key (string-to-char key))) kwsa)
4519 (and log (push kw org-todo-log-states))
4521 (error "Invalid TODO keyword %s" x)))
4522 kws0)
4523 kwsa (if kwsa (append '((:startgroup))
4524 (nreverse kwsa)
4525 '((:endgroup))))
4526 hw (car kws1)
4527 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4528 tail (list inter hw (car dws) (org-last dws)))
4529 (add-to-list 'org-todo-heads hw 'append)
4530 (push kws1 org-todo-sets)
4531 (setq org-done-keywords (append org-done-keywords dws nil))
4532 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4533 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4534 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4535 (setq org-todo-sets (nreverse org-todo-sets)
4536 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4537 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4538 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4539 ;; Process the constants
4540 (when const
4541 (let (e cst)
4542 (while (setq e (pop const))
4543 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4544 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4545 (setq org-table-formula-constants-local cst)))
4547 ;; Process the tags.
4548 (when tags
4549 (let (e tgs)
4550 (while (setq e (pop tags))
4551 (cond
4552 ((equal e "{") (push '(:startgroup) tgs))
4553 ((equal e "}") (push '(:endgroup) tgs))
4554 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4555 (push (cons (match-string 1 e)
4556 (string-to-char (match-string 2 e)))
4557 tgs))
4558 (t (push (list e) tgs))))
4559 (org-set-local 'org-tag-alist nil)
4560 (while (setq e (pop tgs))
4561 (or (and (stringp (car e))
4562 (assoc (car e) org-tag-alist))
4563 (push e org-tag-alist))))))
4565 ;; Compute the regular expressions and other local variables
4566 (if (not org-done-keywords)
4567 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4568 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4569 (length org-scheduled-string)))
4570 org-drawer-regexp
4571 (concat "^[ \t]*:\\("
4572 (mapconcat 'regexp-quote org-drawers "\\|")
4573 "\\):[ \t]*$")
4574 org-not-done-keywords
4575 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4576 org-todo-regexp
4577 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4578 "\\|") "\\)\\>")
4579 org-not-done-regexp
4580 (concat "\\<\\("
4581 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4582 "\\)\\>")
4583 org-todo-line-regexp
4584 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4585 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4586 "\\)\\>\\)?[ \t]*\\(.*\\)")
4587 org-complex-heading-regexp
4588 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4589 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4590 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4591 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4592 org-nl-done-regexp
4593 (concat "\n\\*+[ \t]+"
4594 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4595 "\\)" "\\>")
4596 org-todo-line-tags-regexp
4597 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4598 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4599 (org-re
4600 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4601 org-looking-at-done-regexp
4602 (concat "^" "\\(?:"
4603 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4604 "\\>")
4605 org-deadline-regexp (concat "\\<" org-deadline-string)
4606 org-deadline-time-regexp
4607 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4608 org-deadline-line-regexp
4609 (concat "\\<\\(" org-deadline-string "\\).*")
4610 org-scheduled-regexp
4611 (concat "\\<" org-scheduled-string)
4612 org-scheduled-time-regexp
4613 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4614 org-closed-time-regexp
4615 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4616 org-keyword-time-regexp
4617 (concat "\\<\\(" org-scheduled-string
4618 "\\|" org-deadline-string
4619 "\\|" org-closed-string
4620 "\\|" org-clock-string "\\)"
4621 " *[[<]\\([^]>]+\\)[]>]")
4622 org-keyword-time-not-clock-regexp
4623 (concat "\\<\\(" org-scheduled-string
4624 "\\|" org-deadline-string
4625 "\\|" org-closed-string
4626 "\\)"
4627 " *[[<]\\([^]>]+\\)[]>]")
4628 org-maybe-keyword-time-regexp
4629 (concat "\\(\\<\\(" org-scheduled-string
4630 "\\|" org-deadline-string
4631 "\\|" org-closed-string
4632 "\\|" org-clock-string "\\)\\)?"
4633 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4634 org-planning-or-clock-line-re
4635 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4636 "\\|" org-deadline-string
4637 "\\|" org-closed-string "\\|" org-clock-string
4638 "\\)\\>\\)")
4640 (org-compute-latex-and-specials-regexp)
4641 (org-set-font-lock-defaults)))
4643 (defun org-remove-keyword-keys (list)
4644 (mapcar (lambda (x)
4645 (if (string-match "(..?)$" x)
4646 (substring x 0 (match-beginning 0))
4648 list))
4650 ;; FIXME: this could be done much better, using second characters etc.
4651 (defun org-assign-fast-keys (alist)
4652 "Assign fast keys to a keyword-key alist.
4653 Respect keys that are already there."
4654 (let (new e k c c1 c2 (char ?a))
4655 (while (setq e (pop alist))
4656 (cond
4657 ((equal e '(:startgroup)) (push e new))
4658 ((equal e '(:endgroup)) (push e new))
4660 (setq k (car e) c2 nil)
4661 (if (cdr e)
4662 (setq c (cdr e))
4663 ;; automatically assign a character.
4664 (setq c1 (string-to-char
4665 (downcase (substring
4666 k (if (= (string-to-char k) ?@) 1 0)))))
4667 (if (or (rassoc c1 new) (rassoc c1 alist))
4668 (while (or (rassoc char new) (rassoc char alist))
4669 (setq char (1+ char)))
4670 (setq c2 c1))
4671 (setq c (or c2 char)))
4672 (push (cons k c) new))))
4673 (nreverse new)))
4675 ;;; Some variables ujsed in various places
4677 (defvar org-window-configuration nil
4678 "Used in various places to store a window configuration.")
4679 (defvar org-finish-function nil
4680 "Function to be called when `C-c C-c' is used.
4681 This is for getting out of special buffers like remember.")
4684 ;; FIXME: Occasionally check by commenting these, to make sure
4685 ;; no other functions uses these, forgetting to let-bind them.
4686 (defvar entry)
4687 (defvar state)
4688 (defvar last-state)
4689 (defvar date)
4690 (defvar description)
4692 ;; Defined somewhere in this file, but used before definition.
4693 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4694 (defvar org-agenda-buffer-name)
4695 (defvar org-agenda-undo-list)
4696 (defvar org-agenda-pending-undo-list)
4697 (defvar org-agenda-overriding-header)
4698 (defvar orgtbl-mode)
4699 (defvar org-html-entities)
4700 (defvar org-struct-menu)
4701 (defvar org-org-menu)
4702 (defvar org-tbl-menu)
4703 (defvar org-agenda-keymap)
4705 ;;;; Emacs/XEmacs compatibility
4707 ;; Overlay compatibility functions
4708 (defun org-make-overlay (beg end &optional buffer)
4709 (if (featurep 'xemacs)
4710 (make-extent beg end buffer)
4711 (make-overlay beg end buffer)))
4712 (defun org-delete-overlay (ovl)
4713 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4714 (defun org-detach-overlay (ovl)
4715 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4716 (defun org-move-overlay (ovl beg end &optional buffer)
4717 (if (featurep 'xemacs)
4718 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4719 (move-overlay ovl beg end buffer)))
4720 (defun org-overlay-put (ovl prop value)
4721 (if (featurep 'xemacs)
4722 (set-extent-property ovl prop value)
4723 (overlay-put ovl prop value)))
4724 (defun org-overlay-display (ovl text &optional face evap)
4725 "Make overlay OVL display TEXT with face FACE."
4726 (if (featurep 'xemacs)
4727 (let ((gl (make-glyph text)))
4728 (and face (set-glyph-face gl face))
4729 (set-extent-property ovl 'invisible t)
4730 (set-extent-property ovl 'end-glyph gl))
4731 (overlay-put ovl 'display text)
4732 (if face (overlay-put ovl 'face face))
4733 (if evap (overlay-put ovl 'evaporate t))))
4734 (defun org-overlay-before-string (ovl text &optional face evap)
4735 "Make overlay OVL display TEXT with face FACE."
4736 (if (featurep 'xemacs)
4737 (let ((gl (make-glyph text)))
4738 (and face (set-glyph-face gl face))
4739 (set-extent-property ovl 'begin-glyph gl))
4740 (if face (org-add-props text nil 'face face))
4741 (overlay-put ovl 'before-string text)
4742 (if evap (overlay-put ovl 'evaporate t))))
4743 (defun org-overlay-get (ovl prop)
4744 (if (featurep 'xemacs)
4745 (extent-property ovl prop)
4746 (overlay-get ovl prop)))
4747 (defun org-overlays-at (pos)
4748 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4749 (defun org-overlays-in (&optional start end)
4750 (if (featurep 'xemacs)
4751 (extent-list nil start end)
4752 (overlays-in start end)))
4753 (defun org-overlay-start (o)
4754 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4755 (defun org-overlay-end (o)
4756 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4757 (defun org-find-overlays (prop &optional pos delete)
4758 "Find all overlays specifying PROP at POS or point.
4759 If DELETE is non-nil, delete all those overlays."
4760 (let ((overlays (org-overlays-at (or pos (point))))
4761 ov found)
4762 (while (setq ov (pop overlays))
4763 (if (org-overlay-get ov prop)
4764 (if delete (org-delete-overlay ov) (push ov found))))
4765 found))
4767 ;; Region compatibility
4769 (defun org-add-hook (hook function &optional append local)
4770 "Add-hook, compatible with both Emacsen."
4771 (if (and local (featurep 'xemacs))
4772 (add-local-hook hook function append)
4773 (add-hook hook function append local)))
4775 (defvar org-ignore-region nil
4776 "To temporarily disable the active region.")
4778 (defun org-region-active-p ()
4779 "Is `transient-mark-mode' on and the region active?
4780 Works on both Emacs and XEmacs."
4781 (if org-ignore-region
4783 (if (featurep 'xemacs)
4784 (and zmacs-regions (region-active-p))
4785 (if (fboundp 'use-region-p)
4786 (use-region-p)
4787 (and transient-mark-mode mark-active))))) ; Emacs 22 and before
4789 ;; Invisibility compatibility
4791 (defun org-add-to-invisibility-spec (arg)
4792 "Add elements to `buffer-invisibility-spec'.
4793 See documentation for `buffer-invisibility-spec' for the kind of elements
4794 that can be added."
4795 (cond
4796 ((fboundp 'add-to-invisibility-spec)
4797 (add-to-invisibility-spec arg))
4798 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4799 (setq buffer-invisibility-spec (list arg)))
4801 (setq buffer-invisibility-spec
4802 (cons arg buffer-invisibility-spec)))))
4804 (defun org-remove-from-invisibility-spec (arg)
4805 "Remove elements from `buffer-invisibility-spec'."
4806 (if (fboundp 'remove-from-invisibility-spec)
4807 (remove-from-invisibility-spec arg)
4808 (if (consp buffer-invisibility-spec)
4809 (setq buffer-invisibility-spec
4810 (delete arg buffer-invisibility-spec)))))
4812 (defun org-in-invisibility-spec-p (arg)
4813 "Is ARG a member of `buffer-invisibility-spec'?"
4814 (if (consp buffer-invisibility-spec)
4815 (member arg buffer-invisibility-spec)
4816 nil))
4818 ;;;; Define the Org-mode
4820 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4821 (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."))
4824 ;; We use a before-change function to check if a table might need
4825 ;; an update.
4826 (defvar org-table-may-need-update t
4827 "Indicates that a table might need an update.
4828 This variable is set by `org-before-change-function'.
4829 `org-table-align' sets it back to nil.")
4830 (defvar org-mode-map)
4831 (defvar org-mode-hook nil)
4832 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4833 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4834 (defvar org-table-buffer-is-an nil)
4835 (defconst org-outline-regexp "\\*+ ")
4837 ;;;###autoload
4838 (define-derived-mode org-mode outline-mode "Org"
4839 "Outline-based notes management and organizer, alias
4840 \"Carsten's outline-mode for keeping track of everything.\"
4842 Org-mode develops organizational tasks around a NOTES file which
4843 contains information about projects as plain text. Org-mode is
4844 implemented on top of outline-mode, which is ideal to keep the content
4845 of large files well structured. It supports ToDo items, deadlines and
4846 time stamps, which magically appear in the diary listing of the Emacs
4847 calendar. Tables are easily created with a built-in table editor.
4848 Plain text URL-like links connect to websites, emails (VM), Usenet
4849 messages (Gnus), BBDB entries, and any files related to the project.
4850 For printing and sharing of notes, an Org-mode file (or a part of it)
4851 can be exported as a structured ASCII or HTML file.
4853 The following commands are available:
4855 \\{org-mode-map}"
4857 ;; Get rid of Outline menus, they are not needed
4858 ;; Need to do this here because define-derived-mode sets up
4859 ;; the keymap so late. Still, it is a waste to call this each time
4860 ;; we switch another buffer into org-mode.
4861 (if (featurep 'xemacs)
4862 (when (boundp 'outline-mode-menu-heading)
4863 ;; Assume this is Greg's port, it used easymenu
4864 (easy-menu-remove outline-mode-menu-heading)
4865 (easy-menu-remove outline-mode-menu-show)
4866 (easy-menu-remove outline-mode-menu-hide))
4867 (define-key org-mode-map [menu-bar headings] 'undefined)
4868 (define-key org-mode-map [menu-bar hide] 'undefined)
4869 (define-key org-mode-map [menu-bar show] 'undefined))
4871 (easy-menu-add org-org-menu)
4872 (easy-menu-add org-tbl-menu)
4873 (org-install-agenda-files-menu)
4874 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4875 (org-add-to-invisibility-spec '(org-cwidth))
4876 (when (featurep 'xemacs)
4877 (org-set-local 'line-move-ignore-invisible t))
4878 (org-set-local 'outline-regexp org-outline-regexp)
4879 (org-set-local 'outline-level 'org-outline-level)
4880 (when (and org-ellipsis
4881 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4882 (fboundp 'make-glyph-code))
4883 (unless org-display-table
4884 (setq org-display-table (make-display-table)))
4885 (set-display-table-slot
4886 org-display-table 4
4887 (vconcat (mapcar
4888 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4889 org-ellipsis)))
4890 (if (stringp org-ellipsis) org-ellipsis "..."))))
4891 (setq buffer-display-table org-display-table))
4892 (org-set-regexps-and-options)
4893 ;; Calc embedded
4894 (org-set-local 'calc-embedded-open-mode "# ")
4895 (modify-syntax-entry ?# "<")
4896 (modify-syntax-entry ?@ "w")
4897 (if org-startup-truncated (setq truncate-lines t))
4898 (org-set-local 'font-lock-unfontify-region-function
4899 'org-unfontify-region)
4900 ;; Activate before-change-function
4901 (org-set-local 'org-table-may-need-update t)
4902 (org-add-hook 'before-change-functions 'org-before-change-function nil
4903 'local)
4904 ;; Check for running clock before killing a buffer
4905 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4906 ;; Paragraphs and auto-filling
4907 (org-set-autofill-regexps)
4908 (setq indent-line-function 'org-indent-line-function)
4909 (org-update-radio-target-regexp)
4911 ;; Comment characters
4912 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4913 (org-set-local 'comment-padding " ")
4915 ;; Align options lines
4916 (org-set-local
4917 'align-mode-rules-list
4918 '((org-in-buffer-settings
4919 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4920 (modes . '(org-mode)))))
4922 ;; Imenu
4923 (org-set-local 'imenu-create-index-function
4924 'org-imenu-get-tree)
4926 ;; Make isearch reveal context
4927 (if (or (featurep 'xemacs)
4928 (not (boundp 'outline-isearch-open-invisible-function)))
4929 ;; Emacs 21 and XEmacs make use of the hook
4930 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4931 ;; Emacs 22 deals with this through a special variable
4932 (org-set-local 'outline-isearch-open-invisible-function
4933 (lambda (&rest ignore) (org-show-context 'isearch))))
4935 ;; If empty file that did not turn on org-mode automatically, make it to.
4936 (if (and org-insert-mode-line-in-empty-file
4937 (interactive-p)
4938 (= (point-min) (point-max)))
4939 (insert "# -*- mode: org -*-\n\n"))
4941 (unless org-inhibit-startup
4942 (when org-startup-align-all-tables
4943 (let ((bmp (buffer-modified-p)))
4944 (org-table-map-tables 'org-table-align)
4945 (set-buffer-modified-p bmp)))
4946 (org-cycle-hide-drawers 'all)
4947 (cond
4948 ((eq org-startup-folded t)
4949 (org-cycle '(4)))
4950 ((eq org-startup-folded 'content)
4951 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4952 (org-cycle '(4)) (org-cycle '(4)))))))
4954 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4956 (defsubst org-call-with-arg (command arg)
4957 "Call COMMAND interactively, but pretend prefix are was ARG."
4958 (let ((current-prefix-arg arg)) (call-interactively command)))
4960 (defsubst org-current-line (&optional pos)
4961 (save-excursion
4962 (and pos (goto-char pos))
4963 ;; works also in narrowed buffer, because we start at 1, not point-min
4964 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
4966 (defun org-current-time ()
4967 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4968 (if (> org-time-stamp-rounding-minutes 0)
4969 (let ((r org-time-stamp-rounding-minutes)
4970 (time (decode-time)))
4971 (apply 'encode-time
4972 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4973 (nthcdr 2 time))))
4974 (current-time)))
4976 (defun org-add-props (string plist &rest props)
4977 "Add text properties to entire string, from beginning to end.
4978 PLIST may be a list of properties, PROPS are individual properties and values
4979 that will be added to PLIST. Returns the string that was modified."
4980 (add-text-properties
4981 0 (length string) (if props (append plist props) plist) string)
4982 string)
4983 (put 'org-add-props 'lisp-indent-function 2)
4986 ;;;; Font-Lock stuff, including the activators
4988 (defvar org-mouse-map (make-sparse-keymap))
4989 (org-defkey org-mouse-map
4990 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4991 (org-defkey org-mouse-map
4992 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4993 (when org-mouse-1-follows-link
4994 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4995 (when org-tab-follows-link
4996 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4997 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4998 (when org-return-follows-link
4999 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
5000 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
5002 (require 'font-lock)
5004 (defconst org-non-link-chars "]\t\n\r<>")
5005 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
5006 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp" "message"))
5007 (defvar org-link-re-with-space nil
5008 "Matches a link with spaces, optional angular brackets around it.")
5009 (defvar org-link-re-with-space2 nil
5010 "Matches a link with spaces, optional angular brackets around it.")
5011 (defvar org-angle-link-re nil
5012 "Matches link with angular brackets, spaces are allowed.")
5013 (defvar org-plain-link-re nil
5014 "Matches plain link, without spaces.")
5015 (defvar org-bracket-link-regexp nil
5016 "Matches a link in double brackets.")
5017 (defvar org-bracket-link-analytic-regexp nil
5018 "Regular expression used to analyze links.
5019 Here is what the match groups contain after a match:
5020 1: http:
5021 2: http
5022 3: path
5023 4: [desc]
5024 5: desc")
5025 (defvar org-any-link-re nil
5026 "Regular expression matching any link.")
5028 (defun org-make-link-regexps ()
5029 "Update the link regular expressions.
5030 This should be called after the variable `org-link-types' has changed."
5031 (setq org-link-re-with-space
5032 (concat
5033 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5034 "\\([^" org-non-link-chars " ]"
5035 "[^" org-non-link-chars "]*"
5036 "[^" org-non-link-chars " ]\\)>?")
5037 org-link-re-with-space2
5038 (concat
5039 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5040 "\\([^" org-non-link-chars " ]"
5041 "[^]\t\n\r]*"
5042 "[^" org-non-link-chars " ]\\)>?")
5043 org-angle-link-re
5044 (concat
5045 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5046 "\\([^" org-non-link-chars " ]"
5047 "[^" org-non-link-chars "]*"
5048 "\\)>")
5049 org-plain-link-re
5050 (concat
5051 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5052 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5053 org-bracket-link-regexp
5054 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5055 org-bracket-link-analytic-regexp
5056 (concat
5057 "\\[\\["
5058 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
5059 "\\([^]]+\\)"
5060 "\\]"
5061 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5062 "\\]")
5063 org-any-link-re
5064 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5065 org-angle-link-re "\\)\\|\\("
5066 org-plain-link-re "\\)")))
5068 (org-make-link-regexps)
5070 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5071 "Regular expression for fast time stamp matching.")
5072 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
5073 "Regular expression for fast time stamp matching.")
5074 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5075 "Regular expression matching time strings for analysis.
5076 This one does not require the space after the date.")
5077 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5078 "Regular expression matching time strings for analysis.")
5079 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5080 "Regular expression matching time stamps, with groups.")
5081 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5082 "Regular expression matching time stamps (also [..]), with groups.")
5083 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5084 "Regular expression matching a time stamp range.")
5085 (defconst org-tr-regexp-both
5086 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5087 "Regular expression matching a time stamp range.")
5088 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5089 org-ts-regexp "\\)?")
5090 "Regular expression matching a time stamp or time stamp range.")
5091 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5092 org-ts-regexp-both "\\)?")
5093 "Regular expression matching a time stamp or time stamp range.
5094 The time stamps may be either active or inactive.")
5096 (defvar org-emph-face nil)
5098 (defun org-do-emphasis-faces (limit)
5099 "Run through the buffer and add overlays to links."
5100 (let (rtn)
5101 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5102 (if (not (= (char-after (match-beginning 3))
5103 (char-after (match-beginning 4))))
5104 (progn
5105 (setq rtn t)
5106 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5107 'face
5108 (nth 1 (assoc (match-string 3)
5109 org-emphasis-alist)))
5110 (add-text-properties (match-beginning 2) (match-end 2)
5111 '(font-lock-multiline t))
5112 (when org-hide-emphasis-markers
5113 (add-text-properties (match-end 4) (match-beginning 5)
5114 '(invisible org-link))
5115 (add-text-properties (match-beginning 3) (match-end 3)
5116 '(invisible org-link)))))
5117 (backward-char 1))
5118 rtn))
5120 (defun org-emphasize (&optional char)
5121 "Insert or change an emphasis, i.e. a font like bold or italic.
5122 If there is an active region, change that region to a new emphasis.
5123 If there is no region, just insert the marker characters and position
5124 the cursor between them.
5125 CHAR should be either the marker character, or the first character of the
5126 HTML tag associated with that emphasis. If CHAR is a space, the means
5127 to remove the emphasis of the selected region.
5128 If char is not given (for example in an interactive call) it
5129 will be prompted for."
5130 (interactive)
5131 (let ((eal org-emphasis-alist) e det
5132 (erc org-emphasis-regexp-components)
5133 (prompt "")
5134 (string "") beg end move tag c s)
5135 (if (org-region-active-p)
5136 (setq beg (region-beginning) end (region-end)
5137 string (buffer-substring beg end))
5138 (setq move t))
5140 (while (setq e (pop eal))
5141 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5142 c (aref tag 0))
5143 (push (cons c (string-to-char (car e))) det)
5144 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5145 (substring tag 1)))))
5146 (unless char
5147 (message "%s" (concat "Emphasis marker or tag:" prompt))
5148 (setq char (read-char-exclusive)))
5149 (setq char (or (cdr (assoc char det)) char))
5150 (if (equal char ?\ )
5151 (setq s "" move nil)
5152 (unless (assoc (char-to-string char) org-emphasis-alist)
5153 (error "No such emphasis marker: \"%c\"" char))
5154 (setq s (char-to-string char)))
5155 (while (and (> (length string) 1)
5156 (equal (substring string 0 1) (substring string -1))
5157 (assoc (substring string 0 1) org-emphasis-alist))
5158 (setq string (substring string 1 -1)))
5159 (setq string (concat s string s))
5160 (if beg (delete-region beg end))
5161 (unless (or (bolp)
5162 (string-match (concat "[" (nth 0 erc) "\n]")
5163 (char-to-string (char-before (point)))))
5164 (insert " "))
5165 (unless (string-match (concat "[" (nth 1 erc) "\n]")
5166 (char-to-string (char-after (point))))
5167 (insert " ") (backward-char 1))
5168 (insert string)
5169 (and move (backward-char 1))))
5171 (defconst org-nonsticky-props
5172 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5175 (defun org-activate-plain-links (limit)
5176 "Run through the buffer and add overlays to links."
5177 (catch 'exit
5178 (let (f)
5179 (while (re-search-forward org-plain-link-re limit t)
5180 (setq f (get-text-property (match-beginning 0) 'face))
5181 (if (or (eq f 'org-tag)
5182 (and (listp f) (memq 'org-tag f)))
5184 (add-text-properties (match-beginning 0) (match-end 0)
5185 (list 'mouse-face 'highlight
5186 'rear-nonsticky org-nonsticky-props
5187 'keymap org-mouse-map
5189 (throw 'exit t))))))
5191 (defun org-activate-code (limit)
5192 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
5193 (unless (get-text-property (match-beginning 1) 'face)
5194 (remove-text-properties (match-beginning 0) (match-end 0)
5195 '(display t invisible t intangible t))
5196 t)))
5198 (defun org-activate-angle-links (limit)
5199 "Run through the buffer and add overlays to links."
5200 (if (re-search-forward org-angle-link-re limit t)
5201 (progn
5202 (add-text-properties (match-beginning 0) (match-end 0)
5203 (list 'mouse-face 'highlight
5204 'rear-nonsticky org-nonsticky-props
5205 'keymap org-mouse-map
5207 t)))
5209 (defmacro org-maybe-intangible (props)
5210 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
5211 In emacs 21, invisible text is not avoided by the command loop, so the
5212 intangible property is needed to make sure point skips this text.
5213 In Emacs 22, this is not necessary. The intangible text property has
5214 led to problems with flyspell. These problems are fixed in flyspell.el,
5215 but we still avoid setting the property in Emacs 22 and later.
5216 We use a macro so that the test can happen at compilation time."
5217 (if (< emacs-major-version 22)
5218 `(append '(intangible t) ,props)
5219 props))
5221 (defun org-activate-bracket-links (limit)
5222 "Run through the buffer and add overlays to bracketed links."
5223 (if (re-search-forward org-bracket-link-regexp limit t)
5224 (let* ((help (concat "LINK: "
5225 (org-match-string-no-properties 1)))
5226 ;; FIXME: above we should remove the escapes.
5227 ;; but that requires another match, protecting match data,
5228 ;; a lot of overhead for font-lock.
5229 (ip (org-maybe-intangible
5230 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5231 'keymap org-mouse-map 'mouse-face 'highlight
5232 'font-lock-multiline t 'help-echo help)))
5233 (vp (list 'rear-nonsticky org-nonsticky-props
5234 'keymap org-mouse-map 'mouse-face 'highlight
5235 ' font-lock-multiline t 'help-echo help)))
5236 ;; We need to remove the invisible property here. Table narrowing
5237 ;; may have made some of this invisible.
5238 (remove-text-properties (match-beginning 0) (match-end 0)
5239 '(invisible nil))
5240 (if (match-end 3)
5241 (progn
5242 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5243 (add-text-properties (match-beginning 3) (match-end 3) vp)
5244 (add-text-properties (match-end 3) (match-end 0) ip))
5245 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5246 (add-text-properties (match-beginning 1) (match-end 1) vp)
5247 (add-text-properties (match-end 1) (match-end 0) ip))
5248 t)))
5250 (defun org-activate-dates (limit)
5251 "Run through the buffer and add overlays to dates."
5252 (if (re-search-forward org-tsr-regexp-both limit t)
5253 (progn
5254 (add-text-properties (match-beginning 0) (match-end 0)
5255 (list 'mouse-face 'highlight
5256 'rear-nonsticky org-nonsticky-props
5257 'keymap org-mouse-map))
5258 (when org-display-custom-times
5259 (if (match-end 3)
5260 (org-display-custom-time (match-beginning 3) (match-end 3)))
5261 (org-display-custom-time (match-beginning 1) (match-end 1)))
5262 t)))
5264 (defvar org-target-link-regexp nil
5265 "Regular expression matching radio targets in plain text.")
5266 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5267 "Regular expression matching a link target.")
5268 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5269 "Regular expression matching a radio target.")
5270 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5271 "Regular expression matching any target.")
5273 (defun org-activate-target-links (limit)
5274 "Run through the buffer and add overlays to target matches."
5275 (when org-target-link-regexp
5276 (let ((case-fold-search t))
5277 (if (re-search-forward org-target-link-regexp limit t)
5278 (progn
5279 (add-text-properties (match-beginning 0) (match-end 0)
5280 (list 'mouse-face 'highlight
5281 'rear-nonsticky org-nonsticky-props
5282 'keymap org-mouse-map
5283 'help-echo "Radio target link"
5284 'org-linked-text t))
5285 t)))))
5287 (defun org-update-radio-target-regexp ()
5288 "Find all radio targets in this file and update the regular expression."
5289 (interactive)
5290 (when (memq 'radio org-activate-links)
5291 (setq org-target-link-regexp
5292 (org-make-target-link-regexp (org-all-targets 'radio)))
5293 (org-restart-font-lock)))
5295 (defun org-hide-wide-columns (limit)
5296 (let (s e)
5297 (setq s (text-property-any (point) (or limit (point-max))
5298 'org-cwidth t))
5299 (when s
5300 (setq e (next-single-property-change s 'org-cwidth))
5301 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5302 (goto-char e)
5303 t)))
5305 (defvar org-latex-and-specials-regexp nil
5306 "Regular expression for highlighting export special stuff.")
5307 (defvar org-match-substring-regexp)
5308 (defvar org-match-substring-with-braces-regexp)
5309 (defvar org-export-html-special-string-regexps)
5311 (defun org-compute-latex-and-specials-regexp ()
5312 "Compute regular expression for stuff treated specially by exporters."
5313 (if (not org-highlight-latex-fragments-and-specials)
5314 (org-set-local 'org-latex-and-specials-regexp nil)
5315 (let*
5316 ((matchers (plist-get org-format-latex-options :matchers))
5317 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5318 org-latex-regexps)))
5319 (options (org-combine-plists (org-default-export-plist)
5320 (org-infile-export-plist)))
5321 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5322 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5323 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5324 (org-export-html-expand (plist-get options :expand-quoted-html))
5325 (org-export-with-special-strings (plist-get options :special-strings))
5326 (re-sub
5327 (cond
5328 ((equal org-export-with-sub-superscripts '{})
5329 (list org-match-substring-with-braces-regexp))
5330 (org-export-with-sub-superscripts
5331 (list org-match-substring-regexp))
5332 (t nil)))
5333 (re-latex
5334 (if org-export-with-LaTeX-fragments
5335 (mapcar (lambda (x) (nth 1 x)) latexs)))
5336 (re-macros
5337 (if org-export-with-TeX-macros
5338 (list (concat "\\\\"
5339 (regexp-opt
5340 (append (mapcar 'car org-html-entities)
5341 (if (boundp 'org-latex-entities)
5342 org-latex-entities nil))
5343 'words))) ; FIXME
5345 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5346 (re-special (if org-export-with-special-strings
5347 (mapcar (lambda (x) (car x))
5348 org-export-html-special-string-regexps)))
5349 (re-rest
5350 (delq nil
5351 (list
5352 (if org-export-html-expand "@<[^>\n]+>")
5353 ))))
5354 (org-set-local
5355 'org-latex-and-specials-regexp
5356 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5357 re-rest) "\\|")))))
5359 (defface org-latex-and-export-specials
5360 (let ((font (cond ((assq :inherit custom-face-attributes)
5361 '(:inherit underline))
5362 (t '(:underline t)))))
5363 `((((class grayscale) (background light))
5364 (:foreground "DimGray" ,@font))
5365 (((class grayscale) (background dark))
5366 (:foreground "LightGray" ,@font))
5367 (((class color) (background light))
5368 (:foreground "SaddleBrown"))
5369 (((class color) (background dark))
5370 (:foreground "burlywood"))
5371 (t (,@font))))
5372 "Face used to highlight math latex and other special exporter stuff."
5373 :group 'org-faces)
5375 (defun org-do-latex-and-special-faces (limit)
5376 "Run through the buffer and add overlays to links."
5377 (when org-latex-and-specials-regexp
5378 (let (rtn d)
5379 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5380 limit t))
5381 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5382 'face))
5383 '(org-code org-verbatim underline)))
5384 (progn
5385 (setq rtn t
5386 d (cond ((member (char-after (1+ (match-beginning 0)))
5387 '(?_ ?^)) 1)
5388 (t 0)))
5389 (font-lock-prepend-text-property
5390 (+ d (match-beginning 0)) (match-end 0)
5391 'face 'org-latex-and-export-specials)
5392 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5393 '(font-lock-multiline t)))))
5394 rtn)))
5396 (defun org-restart-font-lock ()
5397 "Restart font-lock-mode, to force refontification."
5398 (when (and (boundp 'font-lock-mode) font-lock-mode)
5399 (font-lock-mode -1)
5400 (font-lock-mode 1)))
5402 (defun org-all-targets (&optional radio)
5403 "Return a list of all targets in this file.
5404 With optional argument RADIO, only find radio targets."
5405 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5406 rtn)
5407 (save-excursion
5408 (goto-char (point-min))
5409 (while (re-search-forward re nil t)
5410 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5411 rtn)))
5413 (defun org-make-target-link-regexp (targets)
5414 "Make regular expression matching all strings in TARGETS.
5415 The regular expression finds the targets also if there is a line break
5416 between words."
5417 (and targets
5418 (concat
5419 "\\<\\("
5420 (mapconcat
5421 (lambda (x)
5422 (while (string-match " +" x)
5423 (setq x (replace-match "\\s-+" t t x)))
5425 targets
5426 "\\|")
5427 "\\)\\>")))
5429 (defun org-activate-tags (limit)
5430 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5431 (progn
5432 (add-text-properties (match-beginning 1) (match-end 1)
5433 (list 'mouse-face 'highlight
5434 'rear-nonsticky org-nonsticky-props
5435 'keymap org-mouse-map))
5436 t)))
5438 (defun org-outline-level ()
5439 (save-excursion
5440 (looking-at outline-regexp)
5441 (if (match-beginning 1)
5442 (+ (org-get-string-indentation (match-string 1)) 1000)
5443 (1- (- (match-end 0) (match-beginning 0))))))
5445 (defvar org-font-lock-keywords nil)
5447 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5448 "Regular expression matching a property line.")
5450 (defun org-set-font-lock-defaults ()
5451 (let* ((em org-fontify-emphasized-text)
5452 (lk org-activate-links)
5453 (org-font-lock-extra-keywords
5454 (list
5455 ;; Headlines
5456 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5457 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5458 ;; Table lines
5459 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5460 (1 'org-table t))
5461 ;; Table internals
5462 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5463 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5464 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5465 ;; Drawers
5466 (list org-drawer-regexp '(0 'org-special-keyword t))
5467 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5468 ;; Properties
5469 (list org-property-re
5470 '(1 'org-special-keyword t)
5471 '(3 'org-property-value t))
5472 (if org-format-transports-properties-p
5473 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5474 ;; Links
5475 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5476 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5477 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5478 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5479 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5480 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5481 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5482 '(org-hide-wide-columns (0 nil append))
5483 ;; TODO lines
5484 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5485 '(1 (org-get-todo-face 1) t))
5486 ;; DONE
5487 (if org-fontify-done-headline
5488 (list (concat "^[*]+ +\\<\\("
5489 (mapconcat 'regexp-quote org-done-keywords "\\|")
5490 "\\)\\(.*\\)")
5491 '(2 'org-headline-done t))
5492 nil)
5493 ;; Priorities
5494 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5495 ;; Special keywords
5496 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5497 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5498 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5499 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5500 ;; Emphasis
5501 (if em
5502 (if (featurep 'xemacs)
5503 '(org-do-emphasis-faces (0 nil append))
5504 '(org-do-emphasis-faces)))
5505 ;; Checkboxes
5506 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5507 2 'bold prepend)
5508 (if org-provide-checkbox-statistics
5509 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5510 (0 (org-get-checkbox-statistics-face) t)))
5511 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5512 '(1 'org-archived prepend))
5513 ;; Specials
5514 '(org-do-latex-and-special-faces)
5515 ;; Code
5516 '(org-activate-code (1 'org-code t))
5517 ;; COMMENT
5518 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5519 "\\|" org-quote-string "\\)\\>")
5520 '(1 'org-special-keyword t))
5521 '("^#.*" (0 'font-lock-comment-face t))
5523 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5524 ;; Now set the full font-lock-keywords
5525 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5526 (org-set-local 'font-lock-defaults
5527 '(org-font-lock-keywords t nil nil backward-paragraph))
5528 (kill-local-variable 'font-lock-keywords) nil))
5530 (defvar org-m nil)
5531 (defvar org-l nil)
5532 (defvar org-f nil)
5533 (defun org-get-level-face (n)
5534 "Get the right face for match N in font-lock matching of healdines."
5535 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5536 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5537 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5538 (cond
5539 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5540 ((eq n 2) org-f)
5541 (t (if org-level-color-stars-only nil org-f))))
5543 (defun org-get-todo-face (kwd)
5544 "Get the right face for a TODO keyword KWD.
5545 If KWD is a number, get the corresponding match group."
5546 (if (numberp kwd) (setq kwd (match-string kwd)))
5547 (or (cdr (assoc kwd org-todo-keyword-faces))
5548 (and (member kwd org-done-keywords) 'org-done)
5549 'org-todo))
5551 (defun org-unfontify-region (beg end &optional maybe_loudly)
5552 "Remove fontification and activation overlays from links."
5553 (font-lock-default-unfontify-region beg end)
5554 (let* ((buffer-undo-list t)
5555 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5556 (inhibit-modification-hooks t)
5557 deactivate-mark buffer-file-name buffer-file-truename)
5558 (remove-text-properties beg end
5559 '(mouse-face t keymap t org-linked-text t
5560 invisible t intangible t))))
5562 ;;;; Visibility cycling, including org-goto and indirect buffer
5564 ;;; Cycling
5566 (defvar org-cycle-global-status nil)
5567 (make-variable-buffer-local 'org-cycle-global-status)
5568 (defvar org-cycle-subtree-status nil)
5569 (make-variable-buffer-local 'org-cycle-subtree-status)
5571 ;;;###autoload
5572 (defun org-cycle (&optional arg)
5573 "Visibility cycling for Org-mode.
5575 - When this function is called with a prefix argument, rotate the entire
5576 buffer through 3 states (global cycling)
5577 1. OVERVIEW: Show only top-level headlines.
5578 2. CONTENTS: Show all headlines of all levels, but no body text.
5579 3. SHOW ALL: Show everything.
5581 - When point is at the beginning of a headline, rotate the subtree started
5582 by this line through 3 different states (local cycling)
5583 1. FOLDED: Only the main headline is shown.
5584 2. CHILDREN: The main headline and the direct children are shown.
5585 From this state, you can move to one of the children
5586 and zoom in further.
5587 3. SUBTREE: Show the entire subtree, including body text.
5589 - When there is a numeric prefix, go up to a heading with level ARG, do
5590 a `show-subtree' and return to the previous cursor position. If ARG
5591 is negative, go up that many levels.
5593 - When point is not at the beginning of a headline, execute
5594 `indent-relative', like TAB normally does. See the option
5595 `org-cycle-emulate-tab' for details.
5597 - Special case: if point is at the beginning of the buffer and there is
5598 no headline in line 1, this function will act as if called with prefix arg.
5599 But only if also the variable `org-cycle-global-at-bob' is t."
5600 (interactive "P")
5601 (let* ((outline-regexp
5602 (if (and (org-mode-p) org-cycle-include-plain-lists)
5603 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5604 outline-regexp))
5605 (bob-special (and org-cycle-global-at-bob (bobp)
5606 (not (looking-at outline-regexp))))
5607 (org-cycle-hook
5608 (if bob-special
5609 (delq 'org-optimize-window-after-visibility-change
5610 (copy-sequence org-cycle-hook))
5611 org-cycle-hook))
5612 (pos (point)))
5614 (if (or bob-special (equal arg '(4)))
5615 ;; special case: use global cycling
5616 (setq arg t))
5618 (cond
5620 ((org-at-table-p 'any)
5621 ;; Enter the table or move to the next field in the table
5622 (or (org-table-recognize-table.el)
5623 (progn
5624 (if arg (org-table-edit-field t)
5625 (org-table-justify-field-maybe)
5626 (call-interactively 'org-table-next-field)))))
5628 ((eq arg t) ;; Global cycling
5630 (cond
5631 ((and (eq last-command this-command)
5632 (eq org-cycle-global-status 'overview))
5633 ;; We just created the overview - now do table of contents
5634 ;; This can be slow in very large buffers, so indicate action
5635 (message "CONTENTS...")
5636 (org-content)
5637 (message "CONTENTS...done")
5638 (setq org-cycle-global-status 'contents)
5639 (run-hook-with-args 'org-cycle-hook 'contents))
5641 ((and (eq last-command this-command)
5642 (eq org-cycle-global-status 'contents))
5643 ;; We just showed the table of contents - now show everything
5644 (show-all)
5645 (message "SHOW ALL")
5646 (setq org-cycle-global-status 'all)
5647 (run-hook-with-args 'org-cycle-hook 'all))
5650 ;; Default action: go to overview
5651 (org-overview)
5652 (message "OVERVIEW")
5653 (setq org-cycle-global-status 'overview)
5654 (run-hook-with-args 'org-cycle-hook 'overview))))
5656 ((and org-drawers org-drawer-regexp
5657 (save-excursion
5658 (beginning-of-line 1)
5659 (looking-at org-drawer-regexp)))
5660 ;; Toggle block visibility
5661 (org-flag-drawer
5662 (not (get-char-property (match-end 0) 'invisible))))
5664 ((integerp arg)
5665 ;; Show-subtree, ARG levels up from here.
5666 (save-excursion
5667 (org-back-to-heading)
5668 (outline-up-heading (if (< arg 0) (- arg)
5669 (- (funcall outline-level) arg)))
5670 (org-show-subtree)))
5672 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5673 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5674 ;; At a heading: rotate between three different views
5675 (org-back-to-heading)
5676 (let ((goal-column 0) eoh eol eos)
5677 ;; First, some boundaries
5678 (save-excursion
5679 (org-back-to-heading)
5680 (save-excursion
5681 (beginning-of-line 2)
5682 (while (and (not (eobp)) ;; this is like `next-line'
5683 (get-char-property (1- (point)) 'invisible))
5684 (beginning-of-line 2)) (setq eol (point)))
5685 (outline-end-of-heading) (setq eoh (point))
5686 (org-end-of-subtree t)
5687 (unless (eobp)
5688 (skip-chars-forward " \t\n")
5689 (beginning-of-line 1) ; in case this is an item
5691 (setq eos (1- (point))))
5692 ;; Find out what to do next and set `this-command'
5693 (cond
5694 ((= eos eoh)
5695 ;; Nothing is hidden behind this heading
5696 (message "EMPTY ENTRY")
5697 (setq org-cycle-subtree-status nil)
5698 (save-excursion
5699 (goto-char eos)
5700 (outline-next-heading)
5701 (if (org-invisible-p) (org-flag-heading nil))))
5702 ((or (>= eol eos)
5703 (not (string-match "\\S-" (buffer-substring eol eos))))
5704 ;; Entire subtree is hidden in one line: open it
5705 (org-show-entry)
5706 (show-children)
5707 (message "CHILDREN")
5708 (save-excursion
5709 (goto-char eos)
5710 (outline-next-heading)
5711 (if (org-invisible-p) (org-flag-heading nil)))
5712 (setq org-cycle-subtree-status 'children)
5713 (run-hook-with-args 'org-cycle-hook 'children))
5714 ((and (eq last-command this-command)
5715 (eq org-cycle-subtree-status 'children))
5716 ;; We just showed the children, now show everything.
5717 (org-show-subtree)
5718 (message "SUBTREE")
5719 (setq org-cycle-subtree-status 'subtree)
5720 (run-hook-with-args 'org-cycle-hook 'subtree))
5722 ;; Default action: hide the subtree.
5723 (hide-subtree)
5724 (message "FOLDED")
5725 (setq org-cycle-subtree-status 'folded)
5726 (run-hook-with-args 'org-cycle-hook 'folded)))))
5728 ;; TAB emulation
5729 (buffer-read-only (org-back-to-heading))
5731 ((org-try-cdlatex-tab))
5733 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5734 (or (not (bolp))
5735 (not (looking-at outline-regexp))))
5736 (call-interactively (global-key-binding "\t")))
5738 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5739 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5740 (or (and (eq org-cycle-emulate-tab 'white)
5741 (= (match-end 0) (point-at-eol)))
5742 (and (eq org-cycle-emulate-tab 'whitestart)
5743 (>= (match-end 0) pos))))
5745 (eq org-cycle-emulate-tab t))
5746 ; (if (and (looking-at "[ \n\r\t]")
5747 ; (string-match "^[ \t]*$" (buffer-substring
5748 ; (point-at-bol) (point))))
5749 ; (progn
5750 ; (beginning-of-line 1)
5751 ; (and (looking-at "[ \t]+") (replace-match ""))))
5752 (call-interactively (global-key-binding "\t")))
5754 (t (save-excursion
5755 (org-back-to-heading)
5756 (org-cycle))))))
5758 ;;;###autoload
5759 (defun org-global-cycle (&optional arg)
5760 "Cycle the global visibility. For details see `org-cycle'."
5761 (interactive "P")
5762 (let ((org-cycle-include-plain-lists
5763 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5764 (if (integerp arg)
5765 (progn
5766 (show-all)
5767 (hide-sublevels arg)
5768 (setq org-cycle-global-status 'contents))
5769 (org-cycle '(4)))))
5771 (defun org-overview ()
5772 "Switch to overview mode, shoing only top-level headlines.
5773 Really, this shows all headlines with level equal or greater than the level
5774 of the first headline in the buffer. This is important, because if the
5775 first headline is not level one, then (hide-sublevels 1) gives confusing
5776 results."
5777 (interactive)
5778 (let ((level (save-excursion
5779 (goto-char (point-min))
5780 (if (re-search-forward (concat "^" outline-regexp) nil t)
5781 (progn
5782 (goto-char (match-beginning 0))
5783 (funcall outline-level))))))
5784 (and level (hide-sublevels level))))
5786 (defun org-content (&optional arg)
5787 "Show all headlines in the buffer, like a table of contents.
5788 With numerical argument N, show content up to level N."
5789 (interactive "P")
5790 (save-excursion
5791 ;; Visit all headings and show their offspring
5792 (and (integerp arg) (org-overview))
5793 (goto-char (point-max))
5794 (catch 'exit
5795 (while (and (progn (condition-case nil
5796 (outline-previous-visible-heading 1)
5797 (error (goto-char (point-min))))
5799 (looking-at outline-regexp))
5800 (if (integerp arg)
5801 (show-children (1- arg))
5802 (show-branches))
5803 (if (bobp) (throw 'exit nil))))))
5806 (defun org-optimize-window-after-visibility-change (state)
5807 "Adjust the window after a change in outline visibility.
5808 This function is the default value of the hook `org-cycle-hook'."
5809 (when (get-buffer-window (current-buffer))
5810 (cond
5811 ; ((eq state 'overview) (org-first-headline-recenter 1))
5812 ; ((eq state 'overview) (org-beginning-of-line))
5813 ((eq state 'content) nil)
5814 ((eq state 'all) nil)
5815 ((eq state 'folded) nil)
5816 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5817 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5819 (defun org-compact-display-after-subtree-move ()
5820 (let (beg end)
5821 (save-excursion
5822 (if (org-up-heading-safe)
5823 (progn
5824 (hide-subtree)
5825 (show-entry)
5826 (show-children)
5827 (org-cycle-show-empty-lines 'children)
5828 (org-cycle-hide-drawers 'children))
5829 (org-overview)))))
5831 (defun org-cycle-show-empty-lines (state)
5832 "Show empty lines above all visible headlines.
5833 The region to be covered depends on STATE when called through
5834 `org-cycle-hook'. Lisp program can use t for STATE to get the
5835 entire buffer covered. Note that an empty line is only shown if there
5836 are at least `org-cycle-separator-lines' empty lines before the headeline."
5837 (when (> org-cycle-separator-lines 0)
5838 (save-excursion
5839 (let* ((n org-cycle-separator-lines)
5840 (re (cond
5841 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5842 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5843 (t (let ((ns (number-to-string (- n 2))))
5844 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5845 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5846 beg end)
5847 (cond
5848 ((memq state '(overview contents t))
5849 (setq beg (point-min) end (point-max)))
5850 ((memq state '(children folded))
5851 (setq beg (point) end (progn (org-end-of-subtree t t)
5852 (beginning-of-line 2)
5853 (point)))))
5854 (when beg
5855 (goto-char beg)
5856 (while (re-search-forward re end t)
5857 (if (not (get-char-property (match-end 1) 'invisible))
5858 (outline-flag-region
5859 (match-beginning 1) (match-end 1) nil)))))))
5860 ;; Never hide empty lines at the end of the file.
5861 (save-excursion
5862 (goto-char (point-max))
5863 (outline-previous-heading)
5864 (outline-end-of-heading)
5865 (if (and (looking-at "[ \t\n]+")
5866 (= (match-end 0) (point-max)))
5867 (outline-flag-region (point) (match-end 0) nil))))
5869 (defun org-subtree-end-visible-p ()
5870 "Is the end of the current subtree visible?"
5871 (pos-visible-in-window-p
5872 (save-excursion (org-end-of-subtree t) (point))))
5874 (defun org-first-headline-recenter (&optional N)
5875 "Move cursor to the first headline and recenter the headline.
5876 Optional argument N means, put the headline into the Nth line of the window."
5877 (goto-char (point-min))
5878 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5879 (beginning-of-line)
5880 (recenter (prefix-numeric-value N))))
5882 ;;; Org-goto
5884 (defvar org-goto-window-configuration nil)
5885 (defvar org-goto-marker nil)
5886 (defvar org-goto-map
5887 (let ((map (make-sparse-keymap)))
5888 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5889 (while (setq cmd (pop cmds))
5890 (substitute-key-definition cmd cmd map global-map)))
5891 (suppress-keymap map)
5892 (org-defkey map "\C-m" 'org-goto-ret)
5893 (org-defkey map [(return)] 'org-goto-ret)
5894 (org-defkey map [(left)] 'org-goto-left)
5895 (org-defkey map [(right)] 'org-goto-right)
5896 (org-defkey map [(control ?g)] 'org-goto-quit)
5897 (org-defkey map "\C-i" 'org-cycle)
5898 (org-defkey map [(tab)] 'org-cycle)
5899 (org-defkey map [(down)] 'outline-next-visible-heading)
5900 (org-defkey map [(up)] 'outline-previous-visible-heading)
5901 (if org-goto-auto-isearch
5902 (if (fboundp 'define-key-after)
5903 (define-key-after map [t] 'org-goto-local-auto-isearch)
5904 nil)
5905 (org-defkey map "q" 'org-goto-quit)
5906 (org-defkey map "n" 'outline-next-visible-heading)
5907 (org-defkey map "p" 'outline-previous-visible-heading)
5908 (org-defkey map "f" 'outline-forward-same-level)
5909 (org-defkey map "b" 'outline-backward-same-level)
5910 (org-defkey map "u" 'outline-up-heading))
5911 (org-defkey map "/" 'org-occur)
5912 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5913 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5914 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5915 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5916 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5917 map))
5919 (defconst org-goto-help
5920 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5921 RET=jump to location [Q]uit and return to previous location
5922 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5924 (defvar org-goto-start-pos) ; dynamically scoped parameter
5926 (defun org-goto (&optional alternative-interface)
5927 "Look up a different location in the current file, keeping current visibility.
5929 When you want look-up or go to a different location in a document, the
5930 fastest way is often to fold the entire buffer and then dive into the tree.
5931 This method has the disadvantage, that the previous location will be folded,
5932 which may not be what you want.
5934 This command works around this by showing a copy of the current buffer
5935 in an indirect buffer, in overview mode. You can dive into the tree in
5936 that copy, use org-occur and incremental search to find a location.
5937 When pressing RET or `Q', the command returns to the original buffer in
5938 which the visibility is still unchanged. After RET is will also jump to
5939 the location selected in the indirect buffer and expose the
5940 the headline hierarchy above."
5941 (interactive "P")
5942 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
5943 (org-refile-use-outline-path t)
5944 (interface
5945 (if (not alternative-interface)
5946 org-goto-interface
5947 (if (eq org-goto-interface 'outline)
5948 'outline-path-completion
5949 'outline)))
5950 (org-goto-start-pos (point))
5951 (selected-point
5952 (if (eq interface 'outline)
5953 (car (org-get-location (current-buffer) org-goto-help))
5954 (nth 3 (org-refile-get-location "Goto: ")))))
5955 (if selected-point
5956 (progn
5957 (org-mark-ring-push org-goto-start-pos)
5958 (goto-char selected-point)
5959 (if (or (org-invisible-p) (org-invisible-p2))
5960 (org-show-context 'org-goto)))
5961 (message "Quit"))))
5963 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5964 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5965 (defvar org-goto-local-auto-isearch-map) ; defined below
5967 (defun org-get-location (buf help)
5968 "Let the user select a location in the Org-mode buffer BUF.
5969 This function uses a recursive edit. It returns the selected position
5970 or nil."
5971 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5972 (isearch-hide-immediately nil)
5973 (isearch-search-fun-function
5974 (lambda () 'org-goto-local-search-forward-headings))
5975 (org-goto-selected-point org-goto-exit-command))
5976 (save-excursion
5977 (save-window-excursion
5978 (delete-other-windows)
5979 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5980 (switch-to-buffer
5981 (condition-case nil
5982 (make-indirect-buffer (current-buffer) "*org-goto*")
5983 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5984 (with-output-to-temp-buffer "*Help*"
5985 (princ help))
5986 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
5987 (setq buffer-read-only nil)
5988 (let ((org-startup-truncated t)
5989 (org-startup-folded nil)
5990 (org-startup-align-all-tables nil))
5991 (org-mode)
5992 (org-overview))
5993 (setq buffer-read-only t)
5994 (if (and (boundp 'org-goto-start-pos)
5995 (integer-or-marker-p org-goto-start-pos))
5996 (let ((org-show-hierarchy-above t)
5997 (org-show-siblings t)
5998 (org-show-following-heading t))
5999 (goto-char org-goto-start-pos)
6000 (and (org-invisible-p) (org-show-context)))
6001 (goto-char (point-min)))
6002 (org-beginning-of-line)
6003 (message "Select location and press RET")
6004 (use-local-map org-goto-map)
6005 (recursive-edit)
6007 (kill-buffer "*org-goto*")
6008 (cons org-goto-selected-point org-goto-exit-command)))
6010 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6011 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6012 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6013 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6015 (defun org-goto-local-search-forward-headings (string bound noerror)
6016 "Search and make sure that anu matches are in headlines."
6017 (catch 'return
6018 (while (search-forward string bound noerror)
6019 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6020 (and (member :headline context)
6021 (not (member :tags context))))
6022 (throw 'return (point))))))
6024 (defun org-goto-local-auto-isearch ()
6025 "Start isearch."
6026 (interactive)
6027 (goto-char (point-min))
6028 (let ((keys (this-command-keys)))
6029 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6030 (isearch-mode t)
6031 (isearch-process-search-char (string-to-char keys)))))
6033 (defun org-goto-ret (&optional arg)
6034 "Finish `org-goto' by going to the new location."
6035 (interactive "P")
6036 (setq org-goto-selected-point (point)
6037 org-goto-exit-command 'return)
6038 (throw 'exit nil))
6040 (defun org-goto-left ()
6041 "Finish `org-goto' by going to the new location."
6042 (interactive)
6043 (if (org-on-heading-p)
6044 (progn
6045 (beginning-of-line 1)
6046 (setq org-goto-selected-point (point)
6047 org-goto-exit-command 'left)
6048 (throw 'exit nil))
6049 (error "Not on a heading")))
6051 (defun org-goto-right ()
6052 "Finish `org-goto' by going to the new location."
6053 (interactive)
6054 (if (org-on-heading-p)
6055 (progn
6056 (setq org-goto-selected-point (point)
6057 org-goto-exit-command 'right)
6058 (throw 'exit nil))
6059 (error "Not on a heading")))
6061 (defun org-goto-quit ()
6062 "Finish `org-goto' without cursor motion."
6063 (interactive)
6064 (setq org-goto-selected-point nil)
6065 (setq org-goto-exit-command 'quit)
6066 (throw 'exit nil))
6068 ;;; Indirect buffer display of subtrees
6070 (defvar org-indirect-dedicated-frame nil
6071 "This is the frame being used for indirect tree display.")
6072 (defvar org-last-indirect-buffer nil)
6074 (defun org-tree-to-indirect-buffer (&optional arg)
6075 "Create indirect buffer and narrow it to current subtree.
6076 With numerical prefix ARG, go up to this level and then take that tree.
6077 If ARG is negative, go up that many levels.
6078 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6079 indirect buffer previously made with this command, to avoid proliferation of
6080 indirect buffers. However, when you call the command with a `C-u' prefix, or
6081 when `org-indirect-buffer-display' is `new-frame', the last buffer
6082 is kept so that you can work with several indirect buffers at the same time.
6083 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6084 requests that a new frame be made for the new buffer, so that the dedicated
6085 frame is not changed."
6086 (interactive "P")
6087 (let ((cbuf (current-buffer))
6088 (cwin (selected-window))
6089 (pos (point))
6090 beg end level heading ibuf)
6091 (save-excursion
6092 (org-back-to-heading t)
6093 (when (numberp arg)
6094 (setq level (org-outline-level))
6095 (if (< arg 0) (setq arg (+ level arg)))
6096 (while (> (setq level (org-outline-level)) arg)
6097 (outline-up-heading 1 t)))
6098 (setq beg (point)
6099 heading (org-get-heading))
6100 (org-end-of-subtree t) (setq end (point)))
6101 (if (and (buffer-live-p org-last-indirect-buffer)
6102 (not (eq org-indirect-buffer-display 'new-frame))
6103 (not arg))
6104 (kill-buffer org-last-indirect-buffer))
6105 (setq ibuf (org-get-indirect-buffer cbuf)
6106 org-last-indirect-buffer ibuf)
6107 (cond
6108 ((or (eq org-indirect-buffer-display 'new-frame)
6109 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6110 (select-frame (make-frame))
6111 (delete-other-windows)
6112 (switch-to-buffer ibuf)
6113 (org-set-frame-title heading))
6114 ((eq org-indirect-buffer-display 'dedicated-frame)
6115 (raise-frame
6116 (select-frame (or (and org-indirect-dedicated-frame
6117 (frame-live-p org-indirect-dedicated-frame)
6118 org-indirect-dedicated-frame)
6119 (setq org-indirect-dedicated-frame (make-frame)))))
6120 (delete-other-windows)
6121 (switch-to-buffer ibuf)
6122 (org-set-frame-title (concat "Indirect: " heading)))
6123 ((eq org-indirect-buffer-display 'current-window)
6124 (switch-to-buffer ibuf))
6125 ((eq org-indirect-buffer-display 'other-window)
6126 (pop-to-buffer ibuf))
6127 (t (error "Invalid value.")))
6128 (if (featurep 'xemacs)
6129 (save-excursion (org-mode) (turn-on-font-lock)))
6130 (narrow-to-region beg end)
6131 (show-all)
6132 (goto-char pos)
6133 (and (window-live-p cwin) (select-window cwin))))
6135 (defun org-get-indirect-buffer (&optional buffer)
6136 (setq buffer (or buffer (current-buffer)))
6137 (let ((n 1) (base (buffer-name buffer)) bname)
6138 (while (buffer-live-p
6139 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6140 (setq n (1+ n)))
6141 (condition-case nil
6142 (make-indirect-buffer buffer bname 'clone)
6143 (error (make-indirect-buffer buffer bname)))))
6145 (defun org-set-frame-title (title)
6146 "Set the title of the current frame to the string TITLE."
6147 ;; FIXME: how to name a single frame in XEmacs???
6148 (unless (featurep 'xemacs)
6149 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6151 ;;;; Structure editing
6153 ;;; Inserting headlines
6155 (defun org-insert-heading (&optional force-heading)
6156 "Insert a new heading or item with same depth at point.
6157 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6158 If point is at the beginning of a headline, insert a sibling before the
6159 current headline. If point is in the middle of a headline, split the headline
6160 at that position and make the rest of the headline part of the sibling below
6161 the current headline."
6162 (interactive "P")
6163 (if (= (buffer-size) 0)
6164 (insert "\n* ")
6165 (when (or force-heading (not (org-insert-item)))
6166 (let* ((head (save-excursion
6167 (condition-case nil
6168 (progn
6169 (org-back-to-heading)
6170 (match-string 0))
6171 (error "*"))))
6172 (blank (cdr (assq 'heading org-blank-before-new-entry)))
6173 pos)
6174 (cond
6175 ((and (org-on-heading-p) (bolp)
6176 (or (bobp)
6177 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6178 (open-line (if blank 2 1)))
6179 ((and (bolp)
6180 (or (bobp)
6181 (save-excursion
6182 (backward-char 1) (not (org-invisible-p)))))
6183 nil)
6184 (t (newline (if blank 2 1))))
6185 (insert head) (just-one-space)
6186 (setq pos (point))
6187 (end-of-line 1)
6188 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6189 (run-hooks 'org-insert-heading-hook)))))
6191 (defun org-insert-heading-after-current ()
6192 "Insert a new heading with same level as current, after current subtree."
6193 (interactive)
6194 (org-back-to-heading)
6195 (org-insert-heading)
6196 (org-move-subtree-down)
6197 (end-of-line 1))
6199 (defun org-insert-todo-heading (arg)
6200 "Insert a new heading with the same level and TODO state as current heading.
6201 If the heading has no TODO state, or if the state is DONE, use the first
6202 state (TODO by default). Also with prefix arg, force first state."
6203 (interactive "P")
6204 (when (not (org-insert-item 'checkbox))
6205 (org-insert-heading)
6206 (save-excursion
6207 (org-back-to-heading)
6208 (outline-previous-heading)
6209 (looking-at org-todo-line-regexp))
6210 (if (or arg
6211 (not (match-beginning 2))
6212 (member (match-string 2) org-done-keywords))
6213 (insert (car org-todo-keywords-1) " ")
6214 (insert (match-string 2) " "))))
6216 (defun org-insert-subheading (arg)
6217 "Insert a new subheading and demote it.
6218 Works for outline headings and for plain lists alike."
6219 (interactive "P")
6220 (org-insert-heading arg)
6221 (cond
6222 ((org-on-heading-p) (org-do-demote))
6223 ((org-at-item-p) (org-indent-item 1))))
6225 (defun org-insert-todo-subheading (arg)
6226 "Insert a new subheading with TODO keyword or checkbox and demote it.
6227 Works for outline headings and for plain lists alike."
6228 (interactive "P")
6229 (org-insert-todo-heading arg)
6230 (cond
6231 ((org-on-heading-p) (org-do-demote))
6232 ((org-at-item-p) (org-indent-item 1))))
6234 ;;; Promotion and Demotion
6236 (defun org-promote-subtree ()
6237 "Promote the entire subtree.
6238 See also `org-promote'."
6239 (interactive)
6240 (save-excursion
6241 (org-map-tree 'org-promote))
6242 (org-fix-position-after-promote))
6244 (defun org-demote-subtree ()
6245 "Demote the entire subtree. See `org-demote'.
6246 See also `org-promote'."
6247 (interactive)
6248 (save-excursion
6249 (org-map-tree 'org-demote))
6250 (org-fix-position-after-promote))
6253 (defun org-do-promote ()
6254 "Promote the current heading higher up the tree.
6255 If the region is active in `transient-mark-mode', promote all headings
6256 in the region."
6257 (interactive)
6258 (save-excursion
6259 (if (org-region-active-p)
6260 (org-map-region 'org-promote (region-beginning) (region-end))
6261 (org-promote)))
6262 (org-fix-position-after-promote))
6264 (defun org-do-demote ()
6265 "Demote the current heading lower down the tree.
6266 If the region is active in `transient-mark-mode', demote all headings
6267 in the region."
6268 (interactive)
6269 (save-excursion
6270 (if (org-region-active-p)
6271 (org-map-region 'org-demote (region-beginning) (region-end))
6272 (org-demote)))
6273 (org-fix-position-after-promote))
6275 (defun org-fix-position-after-promote ()
6276 "Make sure that after pro/demotion cursor position is right."
6277 (let ((pos (point)))
6278 (when (save-excursion
6279 (beginning-of-line 1)
6280 (looking-at org-todo-line-regexp)
6281 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6282 (cond ((eobp) (insert " "))
6283 ((eolp) (insert " "))
6284 ((equal (char-after) ?\ ) (forward-char 1))))))
6286 (defun org-reduced-level (l)
6287 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6289 (defun org-get-legal-level (level &optional change)
6290 "Rectify a level change under the influence of `org-odd-levels-only'
6291 LEVEL is a current level, CHANGE is by how much the level should be
6292 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6293 even level numbers will become the next higher odd number."
6294 (if org-odd-levels-only
6295 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6296 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6297 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6298 (max 1 (+ level change))))
6300 (defun org-promote ()
6301 "Promote the current heading higher up the tree.
6302 If the region is active in `transient-mark-mode', promote all headings
6303 in the region."
6304 (org-back-to-heading t)
6305 (let* ((level (save-match-data (funcall outline-level)))
6306 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
6307 (diff (abs (- level (length up-head) -1))))
6308 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6309 (replace-match up-head nil t)
6310 ;; Fixup tag positioning
6311 (and org-auto-align-tags (org-set-tags nil t))
6312 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
6314 (defun org-demote ()
6315 "Demote the current heading lower down the tree.
6316 If the region is active in `transient-mark-mode', demote all headings
6317 in the region."
6318 (org-back-to-heading t)
6319 (let* ((level (save-match-data (funcall outline-level)))
6320 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
6321 (diff (abs (- level (length down-head) -1))))
6322 (replace-match down-head nil t)
6323 ;; Fixup tag positioning
6324 (and org-auto-align-tags (org-set-tags nil t))
6325 (if org-adapt-indentation (org-fixup-indentation diff))))
6327 (defun org-map-tree (fun)
6328 "Call FUN for every heading underneath the current one."
6329 (org-back-to-heading)
6330 (let ((level (funcall outline-level)))
6331 (save-excursion
6332 (funcall fun)
6333 (while (and (progn
6334 (outline-next-heading)
6335 (> (funcall outline-level) level))
6336 (not (eobp)))
6337 (funcall fun)))))
6339 (defun org-map-region (fun beg end)
6340 "Call FUN for every heading between BEG and END."
6341 (let ((org-ignore-region t))
6342 (save-excursion
6343 (setq end (copy-marker end))
6344 (goto-char beg)
6345 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6346 (< (point) end))
6347 (funcall fun))
6348 (while (and (progn
6349 (outline-next-heading)
6350 (< (point) end))
6351 (not (eobp)))
6352 (funcall fun)))))
6354 (defun org-fixup-indentation (diff)
6355 "Change the indentation in the current entry by DIFF
6356 However, if any line in the current entry has no indentation, or if it
6357 would end up with no indentation after the change, nothing at all is done."
6358 (save-excursion
6359 (let ((end (save-excursion (outline-next-heading)
6360 (point-marker)))
6361 (prohibit (if (> diff 0)
6362 "^\\S-"
6363 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6364 col)
6365 (unless (save-excursion (end-of-line 1)
6366 (re-search-forward prohibit end t))
6367 (while (and (< (point) end)
6368 (re-search-forward "^[ \t]+" end t))
6369 (goto-char (match-end 0))
6370 (setq col (current-column))
6371 (if (< diff 0) (replace-match ""))
6372 (indent-to (+ diff col))))
6373 (move-marker end nil))))
6375 (defun org-convert-to-odd-levels ()
6376 "Convert an org-mode file with all levels allowed to one with odd levels.
6377 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6378 level 5 etc."
6379 (interactive)
6380 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6381 (let ((org-odd-levels-only nil) n)
6382 (save-excursion
6383 (goto-char (point-min))
6384 (while (re-search-forward "^\\*\\*+ " nil t)
6385 (setq n (- (length (match-string 0)) 2))
6386 (while (>= (setq n (1- n)) 0)
6387 (org-demote))
6388 (end-of-line 1))))))
6391 (defun org-convert-to-oddeven-levels ()
6392 "Convert an org-mode file with only odd levels to one with odd and even levels.
6393 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6394 section with an even level, conversion would destroy the structure of the file. An error
6395 is signaled in this case."
6396 (interactive)
6397 (goto-char (point-min))
6398 ;; First check if there are no even levels
6399 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6400 (org-show-context t)
6401 (error "Not all levels are odd in this file. Conversion not possible."))
6402 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6403 (let ((org-odd-levels-only nil) n)
6404 (save-excursion
6405 (goto-char (point-min))
6406 (while (re-search-forward "^\\*\\*+ " nil t)
6407 (setq n (/ (1- (length (match-string 0))) 2))
6408 (while (>= (setq n (1- n)) 0)
6409 (org-promote))
6410 (end-of-line 1))))))
6412 (defun org-tr-level (n)
6413 "Make N odd if required."
6414 (if org-odd-levels-only (1+ (/ n 2)) n))
6416 ;;; Vertical tree motion, cutting and pasting of subtrees
6418 (defun org-move-subtree-up (&optional arg)
6419 "Move the current subtree up past ARG headlines of the same level."
6420 (interactive "p")
6421 (org-move-subtree-down (- (prefix-numeric-value arg))))
6423 (defun org-move-subtree-down (&optional arg)
6424 "Move the current subtree down past ARG headlines of the same level."
6425 (interactive "p")
6426 (setq arg (prefix-numeric-value arg))
6427 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6428 'outline-get-last-sibling))
6429 (ins-point (make-marker))
6430 (cnt (abs arg))
6431 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6432 ;; Select the tree
6433 (org-back-to-heading)
6434 (setq beg0 (point))
6435 (save-excursion
6436 (setq ne-beg (org-back-over-empty-lines))
6437 (setq beg (point)))
6438 (save-match-data
6439 (save-excursion (outline-end-of-heading)
6440 (setq folded (org-invisible-p)))
6441 (outline-end-of-subtree))
6442 (outline-next-heading)
6443 (setq ne-end (org-back-over-empty-lines))
6444 (setq end (point))
6445 (goto-char beg0)
6446 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6447 ;; include less whitespace
6448 (save-excursion
6449 (goto-char beg)
6450 (forward-line (- ne-beg ne-end))
6451 (setq beg (point))))
6452 ;; Find insertion point, with error handling
6453 (while (> cnt 0)
6454 (or (and (funcall movfunc) (looking-at outline-regexp))
6455 (progn (goto-char beg0)
6456 (error "Cannot move past superior level or buffer limit")))
6457 (setq cnt (1- cnt)))
6458 (if (> arg 0)
6459 ;; Moving forward - still need to move over subtree
6460 (progn (org-end-of-subtree t t)
6461 (save-excursion
6462 (org-back-over-empty-lines)
6463 (or (bolp) (newline)))))
6464 (setq ne-ins (org-back-over-empty-lines))
6465 (move-marker ins-point (point))
6466 (setq txt (buffer-substring beg end))
6467 (delete-region beg end)
6468 (outline-flag-region (1- beg) beg nil)
6469 (outline-flag-region (1- (point)) (point) nil)
6470 (insert txt)
6471 (or (bolp) (insert "\n"))
6472 (setq ins-end (point))
6473 (goto-char ins-point)
6474 (org-skip-whitespace)
6475 (when (and (< arg 0)
6476 (org-first-sibling-p)
6477 (> ne-ins ne-beg))
6478 ;; Move whitespace back to beginning
6479 (save-excursion
6480 (goto-char ins-end)
6481 (let ((kill-whole-line t))
6482 (kill-line (- ne-ins ne-beg)) (point)))
6483 (insert (make-string (- ne-ins ne-beg) ?\n)))
6484 (move-marker ins-point nil)
6485 (org-compact-display-after-subtree-move)
6486 (unless folded
6487 (org-show-entry)
6488 (show-children)
6489 (org-cycle-hide-drawers 'children))))
6491 (defvar org-subtree-clip ""
6492 "Clipboard for cut and paste of subtrees.
6493 This is actually only a copy of the kill, because we use the normal kill
6494 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6496 (defvar org-subtree-clip-folded nil
6497 "Was the last copied subtree folded?
6498 This is used to fold the tree back after pasting.")
6500 (defun org-cut-subtree (&optional n)
6501 "Cut the current subtree into the clipboard.
6502 With prefix arg N, cut this many sequential subtrees.
6503 This is a short-hand for marking the subtree and then cutting it."
6504 (interactive "p")
6505 (org-copy-subtree n 'cut))
6507 (defun org-copy-subtree (&optional n cut)
6508 "Cut the current subtree into the clipboard.
6509 With prefix arg N, cut this many sequential subtrees.
6510 This is a short-hand for marking the subtree and then copying it.
6511 If CUT is non-nil, actually cut the subtree."
6512 (interactive "p")
6513 (let (beg end folded (beg0 (point)))
6514 (if (interactive-p)
6515 (org-back-to-heading nil) ; take what looks like a subtree
6516 (org-back-to-heading t)) ; take what is really there
6517 (org-back-over-empty-lines)
6518 (setq beg (point))
6519 (skip-chars-forward " \t\r\n")
6520 (save-match-data
6521 (save-excursion (outline-end-of-heading)
6522 (setq folded (org-invisible-p)))
6523 (condition-case nil
6524 (outline-forward-same-level (1- n))
6525 (error nil))
6526 (org-end-of-subtree t t))
6527 (org-back-over-empty-lines)
6528 (setq end (point))
6529 (goto-char beg0)
6530 (when (> end beg)
6531 (setq org-subtree-clip-folded folded)
6532 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6533 (setq org-subtree-clip (current-kill 0))
6534 (message "%s: Subtree(s) with %d characters"
6535 (if cut "Cut" "Copied")
6536 (length org-subtree-clip)))))
6538 (defun org-paste-subtree (&optional level tree)
6539 "Paste the clipboard as a subtree, with modification of headline level.
6540 The entire subtree is promoted or demoted in order to match a new headline
6541 level. By default, the new level is derived from the visible headings
6542 before and after the insertion point, and taken to be the inferior headline
6543 level of the two. So if the previous visible heading is level 3 and the
6544 next is level 4 (or vice versa), level 4 will be used for insertion.
6545 This makes sure that the subtree remains an independent subtree and does
6546 not swallow low level entries.
6548 You can also force a different level, either by using a numeric prefix
6549 argument, or by inserting the heading marker by hand. For example, if the
6550 cursor is after \"*****\", then the tree will be shifted to level 5.
6552 If you want to insert the tree as is, just use \\[yank].
6554 If optional TREE is given, use this text instead of the kill ring."
6555 (interactive "P")
6556 (unless (org-kill-is-subtree-p tree)
6557 (error "%s"
6558 (substitute-command-keys
6559 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6560 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6561 (^re (concat "^\\(" outline-regexp "\\)"))
6562 (re (concat "\\(" outline-regexp "\\)"))
6563 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6565 (old-level (if (string-match ^re txt)
6566 (- (match-end 0) (match-beginning 0) 1)
6567 -1))
6568 (force-level (cond (level (prefix-numeric-value level))
6569 ((string-match
6570 ^re_ (buffer-substring (point-at-bol) (point)))
6571 (- (match-end 1) (match-beginning 1)))
6572 (t nil)))
6573 (previous-level (save-excursion
6574 (condition-case nil
6575 (progn
6576 (outline-previous-visible-heading 1)
6577 (if (looking-at re)
6578 (- (match-end 0) (match-beginning 0) 1)
6580 (error 1))))
6581 (next-level (save-excursion
6582 (condition-case nil
6583 (progn
6584 (or (looking-at outline-regexp)
6585 (outline-next-visible-heading 1))
6586 (if (looking-at re)
6587 (- (match-end 0) (match-beginning 0) 1)
6589 (error 1))))
6590 (new-level (or force-level (max previous-level next-level)))
6591 (shift (if (or (= old-level -1)
6592 (= new-level -1)
6593 (= old-level new-level))
6595 (- new-level old-level)))
6596 (delta (if (> shift 0) -1 1))
6597 (func (if (> shift 0) 'org-demote 'org-promote))
6598 (org-odd-levels-only nil)
6599 beg end)
6600 ;; Remove the forced level indicator
6601 (if force-level
6602 (delete-region (point-at-bol) (point)))
6603 ;; Paste
6604 (beginning-of-line 1)
6605 (org-back-over-empty-lines) ;; FIXME: correct fix????
6606 (setq beg (point))
6607 (insert-before-markers txt) ;; FIXME: correct fix????
6608 (unless (string-match "\n\\'" txt) (insert "\n"))
6609 (setq end (point))
6610 (goto-char beg)
6611 (skip-chars-forward " \t\n\r")
6612 (setq beg (point))
6613 ;; Shift if necessary
6614 (unless (= shift 0)
6615 (save-restriction
6616 (narrow-to-region beg end)
6617 (while (not (= shift 0))
6618 (org-map-region func (point-min) (point-max))
6619 (setq shift (+ delta shift)))
6620 (goto-char (point-min))))
6621 (when (interactive-p)
6622 (message "Clipboard pasted as level %d subtree" new-level))
6623 (if (and kill-ring
6624 (eq org-subtree-clip (current-kill 0))
6625 org-subtree-clip-folded)
6626 ;; The tree was folded before it was killed/copied
6627 (hide-subtree))))
6629 (defun org-kill-is-subtree-p (&optional txt)
6630 "Check if the current kill is an outline subtree, or a set of trees.
6631 Returns nil if kill does not start with a headline, or if the first
6632 headline level is not the largest headline level in the tree.
6633 So this will actually accept several entries of equal levels as well,
6634 which is OK for `org-paste-subtree'.
6635 If optional TXT is given, check this string instead of the current kill."
6636 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6637 (start-level (and kill
6638 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6639 org-outline-regexp "\\)")
6640 kill)
6641 (- (match-end 2) (match-beginning 2) 1)))
6642 (re (concat "^" org-outline-regexp))
6643 (start (1+ (match-beginning 2))))
6644 (if (not start-level)
6645 (progn
6646 nil) ;; does not even start with a heading
6647 (catch 'exit
6648 (while (setq start (string-match re kill (1+ start)))
6649 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6650 (throw 'exit nil)))
6651 t))))
6653 (defun org-narrow-to-subtree ()
6654 "Narrow buffer to the current subtree."
6655 (interactive)
6656 (save-excursion
6657 (narrow-to-region
6658 (progn (org-back-to-heading) (point))
6659 (progn (org-end-of-subtree t t) (point)))))
6662 ;;; Outline Sorting
6664 (defun org-sort (with-case)
6665 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6666 Optional argument WITH-CASE means sort case-sensitively."
6667 (interactive "P")
6668 (if (org-at-table-p)
6669 (org-call-with-arg 'org-table-sort-lines with-case)
6670 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6672 (defvar org-priority-regexp) ; defined later in the file
6674 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6675 "Sort entries on a certain level of an outline tree.
6676 If there is an active region, the entries in the region are sorted.
6677 Else, if the cursor is before the first entry, sort the top-level items.
6678 Else, the children of the entry at point are sorted.
6680 Sorting can be alphabetically, numerically, and by date/time as given by
6681 the first time stamp in the entry. The command prompts for the sorting
6682 type unless it has been given to the function through the SORTING-TYPE
6683 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6684 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6685 called with point at the beginning of the record. It must return either
6686 a string or a number that should serve as the sorting key for that record.
6688 Comparing entries ignores case by default. However, with an optional argument
6689 WITH-CASE, the sorting considers case as well."
6690 (interactive "P")
6691 (let ((case-func (if with-case 'identity 'downcase))
6692 start beg end stars re re2
6693 txt what tmp plain-list-p)
6694 ;; Find beginning and end of region to sort
6695 (cond
6696 ((org-region-active-p)
6697 ;; we will sort the region
6698 (setq end (region-end)
6699 what "region")
6700 (goto-char (region-beginning))
6701 (if (not (org-on-heading-p)) (outline-next-heading))
6702 (setq start (point)))
6703 ((org-at-item-p)
6704 ;; we will sort this plain list
6705 (org-beginning-of-item-list) (setq start (point))
6706 (org-end-of-item-list) (setq end (point))
6707 (goto-char start)
6708 (setq plain-list-p t
6709 what "plain list"))
6710 ((or (org-on-heading-p)
6711 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6712 ;; we will sort the children of the current headline
6713 (org-back-to-heading)
6714 (setq start (point)
6715 end (progn (org-end-of-subtree t t)
6716 (org-back-over-empty-lines)
6717 (point))
6718 what "children")
6719 (goto-char start)
6720 (show-subtree)
6721 (outline-next-heading))
6723 ;; we will sort the top-level entries in this file
6724 (goto-char (point-min))
6725 (or (org-on-heading-p) (outline-next-heading))
6726 (setq start (point) end (point-max) what "top-level")
6727 (goto-char start)
6728 (show-all)))
6730 (setq beg (point))
6731 (if (>= beg end) (error "Nothing to sort"))
6733 (unless plain-list-p
6734 (looking-at "\\(\\*+\\)")
6735 (setq stars (match-string 1)
6736 re (concat "^" (regexp-quote stars) " +")
6737 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6738 txt (buffer-substring beg end))
6739 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6740 (if (and (not (equal stars "*")) (string-match re2 txt))
6741 (error "Region to sort contains a level above the first entry")))
6743 (unless sorting-type
6744 (message
6745 (if plain-list-p
6746 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6747 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
6748 what)
6749 (setq sorting-type (read-char-exclusive))
6751 (and (= (downcase sorting-type) ?f)
6752 (setq getkey-func
6753 (completing-read "Sort using function: "
6754 obarray 'fboundp t nil nil))
6755 (setq getkey-func (intern getkey-func)))
6757 (and (= (downcase sorting-type) ?r)
6758 (setq property
6759 (completing-read "Property: "
6760 (mapcar 'list (org-buffer-property-keys t))
6761 nil t))))
6763 (message "Sorting entries...")
6765 (save-restriction
6766 (narrow-to-region start end)
6768 (let ((dcst (downcase sorting-type))
6769 (now (current-time)))
6770 (sort-subr
6771 (/= dcst sorting-type)
6772 ;; This function moves to the beginning character of the "record" to
6773 ;; be sorted.
6774 (if plain-list-p
6775 (lambda nil
6776 (if (org-at-item-p) t (goto-char (point-max))))
6777 (lambda nil
6778 (if (re-search-forward re nil t)
6779 (goto-char (match-beginning 0))
6780 (goto-char (point-max)))))
6781 ;; This function moves to the last character of the "record" being
6782 ;; sorted.
6783 (if plain-list-p
6784 'org-end-of-item
6785 (lambda nil
6786 (save-match-data
6787 (condition-case nil
6788 (outline-forward-same-level 1)
6789 (error
6790 (goto-char (point-max)))))))
6792 ;; This function returns the value that gets sorted against.
6793 (if plain-list-p
6794 (lambda nil
6795 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6796 (cond
6797 ((= dcst ?n)
6798 (string-to-number (buffer-substring (match-end 0)
6799 (point-at-eol))))
6800 ((= dcst ?a)
6801 (buffer-substring (match-end 0) (point-at-eol)))
6802 ((= dcst ?t)
6803 (if (re-search-forward org-ts-regexp
6804 (point-at-eol) t)
6805 (org-time-string-to-time (match-string 0))
6806 now))
6807 ((= dcst ?f)
6808 (if getkey-func
6809 (progn
6810 (setq tmp (funcall getkey-func))
6811 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6812 tmp)
6813 (error "Invalid key function `%s'" getkey-func)))
6814 (t (error "Invalid sorting type `%c'" sorting-type)))))
6815 (lambda nil
6816 (cond
6817 ((= dcst ?n)
6818 (if (looking-at outline-regexp)
6819 (string-to-number (buffer-substring (match-end 0)
6820 (point-at-eol)))
6821 nil))
6822 ((= dcst ?a)
6823 (funcall case-func (buffer-substring (point-at-bol)
6824 (point-at-eol))))
6825 ((= dcst ?t)
6826 (if (re-search-forward org-ts-regexp
6827 (save-excursion
6828 (forward-line 2)
6829 (point)) t)
6830 (org-time-string-to-time (match-string 0))
6831 now))
6832 ((= dcst ?p)
6833 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6834 (string-to-char (match-string 2))
6835 org-default-priority))
6836 ((= dcst ?r)
6837 (or (org-entry-get nil property) ""))
6838 ((= dcst ?f)
6839 (if getkey-func
6840 (progn
6841 (setq tmp (funcall getkey-func))
6842 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6843 tmp)
6844 (error "Invalid key function `%s'" getkey-func)))
6845 (t (error "Invalid sorting type `%c'" sorting-type)))))
6847 (cond
6848 ((= dcst ?a) 'string<)
6849 ((= dcst ?t) 'time-less-p)
6850 (t nil)))))
6851 (message "Sorting entries...done")))
6853 (defun org-do-sort (table what &optional with-case sorting-type)
6854 "Sort TABLE of WHAT according to SORTING-TYPE.
6855 The user will be prompted for the SORTING-TYPE if the call to this
6856 function does not specify it. WHAT is only for the prompt, to indicate
6857 what is being sorted. The sorting key will be extracted from
6858 the car of the elements of the table.
6859 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6860 (unless sorting-type
6861 (message
6862 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6863 what)
6864 (setq sorting-type (read-char-exclusive)))
6865 (let ((dcst (downcase sorting-type))
6866 extractfun comparefun)
6867 ;; Define the appropriate functions
6868 (cond
6869 ((= dcst ?n)
6870 (setq extractfun 'string-to-number
6871 comparefun (if (= dcst sorting-type) '< '>)))
6872 ((= dcst ?a)
6873 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6874 (lambda(x) (downcase (org-sort-remove-invisible x))))
6875 comparefun (if (= dcst sorting-type)
6876 'string<
6877 (lambda (a b) (and (not (string< a b))
6878 (not (string= a b)))))))
6879 ((= dcst ?t)
6880 (setq extractfun
6881 (lambda (x)
6882 (if (string-match org-ts-regexp x)
6883 (time-to-seconds
6884 (org-time-string-to-time (match-string 0 x)))
6886 comparefun (if (= dcst sorting-type) '< '>)))
6887 (t (error "Invalid sorting type `%c'" sorting-type)))
6889 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6890 table)
6891 (lambda (a b) (funcall comparefun (car a) (car b))))))
6893 ;;;; Plain list items, including checkboxes
6895 ;;; Plain list items
6897 (defun org-at-item-p ()
6898 "Is point in a line starting a hand-formatted item?"
6899 (let ((llt org-plain-list-ordered-item-terminator))
6900 (save-excursion
6901 (goto-char (point-at-bol))
6902 (looking-at
6903 (cond
6904 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6905 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6906 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6907 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
6909 (defun org-in-item-p ()
6910 "It the cursor inside a plain list item.
6911 Does not have to be the first line."
6912 (save-excursion
6913 (condition-case nil
6914 (progn
6915 (org-beginning-of-item)
6916 (org-at-item-p)
6918 (error nil))))
6920 (defun org-insert-item (&optional checkbox)
6921 "Insert a new item at the current level.
6922 Return t when things worked, nil when we are not in an item."
6923 (when (save-excursion
6924 (condition-case nil
6925 (progn
6926 (org-beginning-of-item)
6927 (org-at-item-p)
6928 (if (org-invisible-p) (error "Invisible item"))
6930 (error nil)))
6931 (let* ((bul (match-string 0))
6932 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
6933 (match-end 0)))
6934 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
6935 pos)
6936 (cond
6937 ((and (org-at-item-p) (<= (point) eow))
6938 ;; before the bullet
6939 (beginning-of-line 1)
6940 (open-line (if blank 2 1)))
6941 ((<= (point) eow)
6942 (beginning-of-line 1))
6943 (t (newline (if blank 2 1))))
6944 (insert bul (if checkbox "[ ]" ""))
6945 (just-one-space)
6946 (setq pos (point))
6947 (end-of-line 1)
6948 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
6949 (org-maybe-renumber-ordered-list)
6950 (and checkbox (org-update-checkbox-count-maybe))
6953 ;;; Checkboxes
6955 (defun org-at-item-checkbox-p ()
6956 "Is point at a line starting a plain-list item with a checklet?"
6957 (and (org-at-item-p)
6958 (save-excursion
6959 (goto-char (match-end 0))
6960 (skip-chars-forward " \t")
6961 (looking-at "\\[[- X]\\]"))))
6963 (defun org-toggle-checkbox (&optional arg)
6964 "Toggle the checkbox in the current line."
6965 (interactive "P")
6966 (catch 'exit
6967 (let (beg end status (firstnew 'unknown))
6968 (cond
6969 ((org-region-active-p)
6970 (setq beg (region-beginning) end (region-end)))
6971 ((org-on-heading-p)
6972 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
6973 ((org-at-item-checkbox-p)
6974 (let ((pos (point)))
6975 (replace-match
6976 (cond (arg "[-]")
6977 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
6978 (t "[ ]"))
6979 t t)
6980 (goto-char pos))
6981 (throw 'exit t))
6982 (t (error "Not at a checkbox or heading, and no active region")))
6983 (save-excursion
6984 (goto-char beg)
6985 (while (< (point) end)
6986 (when (org-at-item-checkbox-p)
6987 (setq status (equal (match-string 0) "[X]"))
6988 (when (eq firstnew 'unknown)
6989 (setq firstnew (not status)))
6990 (replace-match
6991 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
6992 (beginning-of-line 2)))))
6993 (org-update-checkbox-count-maybe))
6995 (defun org-update-checkbox-count-maybe ()
6996 "Update checkbox statistics unless turned off by user."
6997 (when org-provide-checkbox-statistics
6998 (org-update-checkbox-count)))
7000 (defun org-update-checkbox-count (&optional all)
7001 "Update the checkbox statistics in the current section.
7002 This will find all statistic cookies like [57%] and [6/12] and update them
7003 with the current numbers. With optional prefix argument ALL, do this for
7004 the whole buffer."
7005 (interactive "P")
7006 (save-excursion
7007 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
7008 (beg (condition-case nil
7009 (progn (outline-back-to-heading) (point))
7010 (error (point-min))))
7011 (end (move-marker (make-marker)
7012 (progn (outline-next-heading) (point))))
7013 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
7014 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
7015 (re-find (concat re "\\|" re-box))
7016 beg-cookie end-cookie is-percent c-on c-off lim
7017 eline curr-ind next-ind continue-from startsearch
7018 (cstat 0)
7020 (when all
7021 (goto-char (point-min))
7022 (outline-next-heading)
7023 (setq beg (point) end (point-max)))
7024 (goto-char end)
7025 ;; find each statistic cookie
7026 (while (re-search-backward re-find beg t)
7027 (setq beg-cookie (match-beginning 1)
7028 end-cookie (match-end 1)
7029 cstat (+ cstat (if end-cookie 1 0))
7030 startsearch (point-at-eol)
7031 continue-from (point-at-bol)
7032 is-percent (match-beginning 2)
7033 lim (cond
7034 ((org-on-heading-p) (outline-next-heading) (point))
7035 ((org-at-item-p) (org-end-of-item) (point))
7036 (t nil))
7037 c-on 0
7038 c-off 0)
7039 (when lim
7040 ;; find first checkbox for this cookie and gather
7041 ;; statistics from all that are at this indentation level
7042 (goto-char startsearch)
7043 (if (re-search-forward re-box lim t)
7044 (progn
7045 (org-beginning-of-item)
7046 (setq curr-ind (org-get-indentation))
7047 (setq next-ind curr-ind)
7048 (while (= curr-ind next-ind)
7049 (save-excursion (end-of-line) (setq eline (point)))
7050 (if (re-search-forward re-box eline t)
7051 (if (member (match-string 2) '("[ ]" "[-]"))
7052 (setq c-off (1+ c-off))
7053 (setq c-on (1+ c-on))
7056 (org-end-of-item)
7057 (setq next-ind (org-get-indentation))
7059 (goto-char continue-from)
7060 ;; update cookie
7061 (when end-cookie
7062 (delete-region beg-cookie end-cookie)
7063 (goto-char beg-cookie)
7064 (insert
7065 (if is-percent
7066 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
7067 (format "[%d/%d]" c-on (+ c-on c-off)))))
7068 ;; update items checkbox if it has one
7069 (when (org-at-item-p)
7070 (org-beginning-of-item)
7071 (when (and (> (+ c-on c-off) 0)
7072 (re-search-forward re-box (point-at-eol) t))
7073 (setq beg-cookie (match-beginning 2)
7074 end-cookie (match-end 2))
7075 (delete-region beg-cookie end-cookie)
7076 (goto-char beg-cookie)
7077 (cond ((= c-off 0) (insert "[X]"))
7078 ((= c-on 0) (insert "[ ]"))
7079 (t (insert "[-]")))
7081 (goto-char continue-from))
7082 (when (interactive-p)
7083 (message "Checkbox satistics updated %s (%d places)"
7084 (if all "in entire file" "in current outline entry") cstat)))))
7086 (defun org-get-checkbox-statistics-face ()
7087 "Select the face for checkbox statistics.
7088 The face will be `org-done' when all relevant boxes are checked. Otherwise
7089 it will be `org-todo'."
7090 (if (match-end 1)
7091 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
7092 (if (and (> (match-end 2) (match-beginning 2))
7093 (equal (match-string 2) (match-string 3)))
7094 'org-done
7095 'org-todo)))
7097 (defun org-get-indentation (&optional line)
7098 "Get the indentation of the current line, interpreting tabs.
7099 When LINE is given, assume it represents a line and compute its indentation."
7100 (if line
7101 (if (string-match "^ *" (org-remove-tabs line))
7102 (match-end 0))
7103 (save-excursion
7104 (beginning-of-line 1)
7105 (skip-chars-forward " \t")
7106 (current-column))))
7108 (defun org-remove-tabs (s &optional width)
7109 "Replace tabulators in S with spaces.
7110 Assumes that s is a single line, starting in column 0."
7111 (setq width (or width tab-width))
7112 (while (string-match "\t" s)
7113 (setq s (replace-match
7114 (make-string
7115 (- (* width (/ (+ (match-beginning 0) width) width))
7116 (match-beginning 0)) ?\ )
7117 t t s)))
7120 (defun org-fix-indentation (line ind)
7121 "Fix indentation in LINE.
7122 IND is a cons cell with target and minimum indentation.
7123 If the current indenation in LINE is smaller than the minimum,
7124 leave it alone. If it is larger than ind, set it to the target."
7125 (let* ((l (org-remove-tabs line))
7126 (i (org-get-indentation l))
7127 (i1 (car ind)) (i2 (cdr ind)))
7128 (if (>= i i2) (setq l (substring line i2)))
7129 (if (> i1 0)
7130 (concat (make-string i1 ?\ ) l)
7131 l)))
7133 (defcustom org-empty-line-terminates-plain-lists nil
7134 "Non-nil means, an empty line ends all plain list levels.
7135 When nil, empty lines are part of the preceeding item."
7136 :group 'org-plain-lists
7137 :type 'boolean)
7139 (defun org-beginning-of-item ()
7140 "Go to the beginning of the current hand-formatted item.
7141 If the cursor is not in an item, throw an error."
7142 (interactive)
7143 (let ((pos (point))
7144 (limit (save-excursion
7145 (condition-case nil
7146 (progn
7147 (org-back-to-heading)
7148 (beginning-of-line 2) (point))
7149 (error (point-min)))))
7150 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7151 ind ind1)
7152 (if (org-at-item-p)
7153 (beginning-of-line 1)
7154 (beginning-of-line 1)
7155 (skip-chars-forward " \t")
7156 (setq ind (current-column))
7157 (if (catch 'exit
7158 (while t
7159 (beginning-of-line 0)
7160 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
7162 (if (looking-at "[ \t]*$")
7163 (setq ind1 ind-empty)
7164 (skip-chars-forward " \t")
7165 (setq ind1 (current-column)))
7166 (if (< ind1 ind)
7167 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
7169 (goto-char pos)
7170 (error "Not in an item")))))
7172 (defun org-end-of-item ()
7173 "Go to the end of the current hand-formatted item.
7174 If the cursor is not in an item, throw an error."
7175 (interactive)
7176 (let* ((pos (point))
7177 ind1
7178 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7179 (limit (save-excursion (outline-next-heading) (point)))
7180 (ind (save-excursion
7181 (org-beginning-of-item)
7182 (skip-chars-forward " \t")
7183 (current-column)))
7184 (end (catch 'exit
7185 (while t
7186 (beginning-of-line 2)
7187 (if (eobp) (throw 'exit (point)))
7188 (if (>= (point) limit) (throw 'exit (point-at-bol)))
7189 (if (looking-at "[ \t]*$")
7190 (setq ind1 ind-empty)
7191 (skip-chars-forward " \t")
7192 (setq ind1 (current-column)))
7193 (if (<= ind1 ind)
7194 (throw 'exit (point-at-bol)))))))
7195 (if end
7196 (goto-char end)
7197 (goto-char pos)
7198 (error "Not in an item"))))
7200 (defun org-next-item ()
7201 "Move to the beginning of the next item in the current plain list.
7202 Error if not at a plain list, or if this is the last item in the list."
7203 (interactive)
7204 (let (ind ind1 (pos (point)))
7205 (org-beginning-of-item)
7206 (setq ind (org-get-indentation))
7207 (org-end-of-item)
7208 (setq ind1 (org-get-indentation))
7209 (unless (and (org-at-item-p) (= ind ind1))
7210 (goto-char pos)
7211 (error "On last item"))))
7213 (defun org-previous-item ()
7214 "Move to the beginning of the previous item in the current plain list.
7215 Error if not at a plain list, or if this is the first item in the list."
7216 (interactive)
7217 (let (beg ind ind1 (pos (point)))
7218 (org-beginning-of-item)
7219 (setq beg (point))
7220 (setq ind (org-get-indentation))
7221 (goto-char beg)
7222 (catch 'exit
7223 (while t
7224 (beginning-of-line 0)
7225 (if (looking-at "[ \t]*$")
7227 (if (<= (setq ind1 (org-get-indentation)) ind)
7228 (throw 'exit t)))))
7229 (condition-case nil
7230 (if (or (not (org-at-item-p))
7231 (< ind1 (1- ind)))
7232 (error "")
7233 (org-beginning-of-item))
7234 (error (goto-char pos)
7235 (error "On first item")))))
7237 (defun org-first-list-item-p ()
7238 "Is this heading the item in a plain list?"
7239 (unless (org-at-item-p)
7240 (error "Not at a plain list item"))
7241 (org-beginning-of-item)
7242 (= (point) (save-excursion (org-beginning-of-item-list))))
7244 (defun org-move-item-down ()
7245 "Move the plain list item at point down, i.e. swap with following item.
7246 Subitems (items with larger indentation) are considered part of the item,
7247 so this really moves item trees."
7248 (interactive)
7249 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
7250 (org-beginning-of-item)
7251 (setq beg0 (point))
7252 (save-excursion
7253 (setq ne-beg (org-back-over-empty-lines))
7254 (setq beg (point)))
7255 (goto-char beg0)
7256 (setq ind (org-get-indentation))
7257 (org-end-of-item)
7258 (setq end0 (point))
7259 (setq ind1 (org-get-indentation))
7260 (setq ne-end (org-back-over-empty-lines))
7261 (setq end (point))
7262 (goto-char beg0)
7263 (when (and (org-first-list-item-p) (< ne-end ne-beg))
7264 ;; include less whitespace
7265 (save-excursion
7266 (goto-char beg)
7267 (forward-line (- ne-beg ne-end))
7268 (setq beg (point))))
7269 (goto-char end0)
7270 (if (and (org-at-item-p) (= ind ind1))
7271 (progn
7272 (org-end-of-item)
7273 (org-back-over-empty-lines)
7274 (setq txt (buffer-substring beg end))
7275 (save-excursion
7276 (delete-region beg end))
7277 (setq pos (point))
7278 (insert txt)
7279 (goto-char pos) (org-skip-whitespace)
7280 (org-maybe-renumber-ordered-list))
7281 (goto-char pos)
7282 (error "Cannot move this item further down"))))
7284 (defun org-move-item-up (arg)
7285 "Move the plain list item at point up, i.e. swap with previous item.
7286 Subitems (items with larger indentation) are considered part of the item,
7287 so this really moves item trees."
7288 (interactive "p")
7289 (let (beg beg0 end end0 ind ind1 (pos (point)) txt
7290 ne-beg ne-end ne-ins ins-end)
7291 (org-beginning-of-item)
7292 (setq beg0 (point))
7293 (setq ind (org-get-indentation))
7294 (save-excursion
7295 (setq ne-beg (org-back-over-empty-lines))
7296 (setq beg (point)))
7297 (goto-char beg0)
7298 (org-end-of-item)
7299 (setq ne-end (org-back-over-empty-lines))
7300 (setq end (point))
7301 (goto-char beg0)
7302 (catch 'exit
7303 (while t
7304 (beginning-of-line 0)
7305 (if (looking-at "[ \t]*$")
7306 (if org-empty-line-terminates-plain-lists
7307 (progn
7308 (goto-char pos)
7309 (error "Cannot move this item further up"))
7310 nil)
7311 (if (<= (setq ind1 (org-get-indentation)) ind)
7312 (throw 'exit t)))))
7313 (condition-case nil
7314 (org-beginning-of-item)
7315 (error (goto-char beg)
7316 (error "Cannot move this item further up")))
7317 (setq ind1 (org-get-indentation))
7318 (if (and (org-at-item-p) (= ind ind1))
7319 (progn
7320 (setq ne-ins (org-back-over-empty-lines))
7321 (setq txt (buffer-substring beg end))
7322 (save-excursion
7323 (delete-region beg end))
7324 (setq pos (point))
7325 (insert txt)
7326 (setq ins-end (point))
7327 (goto-char pos) (org-skip-whitespace)
7329 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
7330 ;; Move whitespace back to beginning
7331 (save-excursion
7332 (goto-char ins-end)
7333 (let ((kill-whole-line t))
7334 (kill-line (- ne-ins ne-beg)) (point)))
7335 (insert (make-string (- ne-ins ne-beg) ?\n)))
7337 (org-maybe-renumber-ordered-list))
7338 (goto-char pos)
7339 (error "Cannot move this item further up"))))
7341 (defun org-maybe-renumber-ordered-list ()
7342 "Renumber the ordered list at point if setup allows it.
7343 This tests the user option `org-auto-renumber-ordered-lists' before
7344 doing the renumbering."
7345 (interactive)
7346 (when (and org-auto-renumber-ordered-lists
7347 (org-at-item-p))
7348 (if (match-beginning 3)
7349 (org-renumber-ordered-list 1)
7350 (org-fix-bullet-type))))
7352 (defun org-maybe-renumber-ordered-list-safe ()
7353 (condition-case nil
7354 (save-excursion
7355 (org-maybe-renumber-ordered-list))
7356 (error nil)))
7358 (defun org-cycle-list-bullet (&optional which)
7359 "Cycle through the different itemize/enumerate bullets.
7360 This cycle the entire list level through the sequence:
7362 `-' -> `+' -> `*' -> `1.' -> `1)'
7364 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7365 0 meand `-', 1 means `+' etc."
7366 (interactive "P")
7367 (org-preserve-lc
7368 (org-beginning-of-item-list)
7369 (org-at-item-p)
7370 (beginning-of-line 1)
7371 (let ((current (match-string 0))
7372 (prevp (eq which 'previous))
7373 new)
7374 (setq new (cond
7375 ((and (numberp which)
7376 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7377 ((string-match "-" current) (if prevp "1)" "+"))
7378 ((string-match "\\+" current)
7379 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7380 ((string-match "\\*" current) (if prevp "+" "1."))
7381 ((string-match "\\." current) (if prevp "*" "1)"))
7382 ((string-match ")" current) (if prevp "1." "-"))
7383 (t (error "This should not happen"))))
7384 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7385 (org-fix-bullet-type)
7386 (org-maybe-renumber-ordered-list))))
7388 (defun org-get-string-indentation (s)
7389 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7390 (let ((n -1) (i 0) (w tab-width) c)
7391 (catch 'exit
7392 (while (< (setq n (1+ n)) (length s))
7393 (setq c (aref s n))
7394 (cond ((= c ?\ ) (setq i (1+ i)))
7395 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7396 (t (throw 'exit t)))))
7399 (defun org-renumber-ordered-list (arg)
7400 "Renumber an ordered plain list.
7401 Cursor needs to be in the first line of an item, the line that starts
7402 with something like \"1.\" or \"2)\"."
7403 (interactive "p")
7404 (unless (and (org-at-item-p)
7405 (match-beginning 3))
7406 (error "This is not an ordered list"))
7407 (let ((line (org-current-line))
7408 (col (current-column))
7409 (ind (org-get-string-indentation
7410 (buffer-substring (point-at-bol) (match-beginning 3))))
7411 ;; (term (substring (match-string 3) -1))
7412 ind1 (n (1- arg))
7413 fmt)
7414 ;; find where this list begins
7415 (org-beginning-of-item-list)
7416 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7417 (setq fmt (concat "%d" (match-string 1)))
7418 (beginning-of-line 0)
7419 ;; walk forward and replace these numbers
7420 (catch 'exit
7421 (while t
7422 (catch 'next
7423 (beginning-of-line 2)
7424 (if (eobp) (throw 'exit nil))
7425 (if (looking-at "[ \t]*$") (throw 'next nil))
7426 (skip-chars-forward " \t") (setq ind1 (current-column))
7427 (if (> ind1 ind) (throw 'next t))
7428 (if (< ind1 ind) (throw 'exit t))
7429 (if (not (org-at-item-p)) (throw 'exit nil))
7430 (delete-region (match-beginning 2) (match-end 2))
7431 (goto-char (match-beginning 2))
7432 (insert (format fmt (setq n (1+ n)))))))
7433 (goto-line line)
7434 (move-to-column col)))
7436 (defun org-fix-bullet-type ()
7437 "Make sure all items in this list have the same bullet as the firsst item."
7438 (interactive)
7439 (unless (org-at-item-p) (error "This is not a list"))
7440 (let ((line (org-current-line))
7441 (col (current-column))
7442 (ind (current-indentation))
7443 ind1 bullet)
7444 ;; find where this list begins
7445 (org-beginning-of-item-list)
7446 (beginning-of-line 1)
7447 ;; find out what the bullet type is
7448 (looking-at "[ \t]*\\(\\S-+\\)")
7449 (setq bullet (match-string 1))
7450 ;; walk forward and replace these numbers
7451 (beginning-of-line 0)
7452 (catch 'exit
7453 (while t
7454 (catch 'next
7455 (beginning-of-line 2)
7456 (if (eobp) (throw 'exit nil))
7457 (if (looking-at "[ \t]*$") (throw 'next nil))
7458 (skip-chars-forward " \t") (setq ind1 (current-column))
7459 (if (> ind1 ind) (throw 'next t))
7460 (if (< ind1 ind) (throw 'exit t))
7461 (if (not (org-at-item-p)) (throw 'exit nil))
7462 (skip-chars-forward " \t")
7463 (looking-at "\\S-+")
7464 (replace-match bullet))))
7465 (goto-line line)
7466 (move-to-column col)
7467 (if (string-match "[0-9]" bullet)
7468 (org-renumber-ordered-list 1))))
7470 (defun org-beginning-of-item-list ()
7471 "Go to the beginning of the current item list.
7472 I.e. to the first item in this list."
7473 (interactive)
7474 (org-beginning-of-item)
7475 (let ((pos (point-at-bol))
7476 (ind (org-get-indentation))
7477 ind1)
7478 ;; find where this list begins
7479 (catch 'exit
7480 (while t
7481 (catch 'next
7482 (beginning-of-line 0)
7483 (if (looking-at "[ \t]*$")
7484 (throw (if (bobp) 'exit 'next) t))
7485 (skip-chars-forward " \t") (setq ind1 (current-column))
7486 (if (or (< ind1 ind)
7487 (and (= ind1 ind)
7488 (not (org-at-item-p)))
7489 (bobp))
7490 (throw 'exit t)
7491 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7492 (goto-char pos)))
7495 (defun org-end-of-item-list ()
7496 "Go to the end of the current item list.
7497 I.e. to the text after the last item."
7498 (interactive)
7499 (org-beginning-of-item)
7500 (let ((pos (point-at-bol))
7501 (ind (org-get-indentation))
7502 ind1)
7503 ;; find where this list begins
7504 (catch 'exit
7505 (while t
7506 (catch 'next
7507 (beginning-of-line 2)
7508 (if (looking-at "[ \t]*$")
7509 (throw (if (eobp) 'exit 'next) t))
7510 (skip-chars-forward " \t") (setq ind1 (current-column))
7511 (if (or (< ind1 ind)
7512 (and (= ind1 ind)
7513 (not (org-at-item-p)))
7514 (eobp))
7515 (progn
7516 (setq pos (point-at-bol))
7517 (throw 'exit t))))))
7518 (goto-char pos)))
7521 (defvar org-last-indent-begin-marker (make-marker))
7522 (defvar org-last-indent-end-marker (make-marker))
7524 (defun org-outdent-item (arg)
7525 "Outdent a local list item."
7526 (interactive "p")
7527 (org-indent-item (- arg)))
7529 (defun org-indent-item (arg)
7530 "Indent a local list item."
7531 (interactive "p")
7532 (unless (org-at-item-p)
7533 (error "Not on an item"))
7534 (save-excursion
7535 (let (beg end ind ind1 tmp delta ind-down ind-up)
7536 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7537 (setq beg org-last-indent-begin-marker
7538 end org-last-indent-end-marker)
7539 (org-beginning-of-item)
7540 (setq beg (move-marker org-last-indent-begin-marker (point)))
7541 (org-end-of-item)
7542 (setq end (move-marker org-last-indent-end-marker (point))))
7543 (goto-char beg)
7544 (setq tmp (org-item-indent-positions)
7545 ind (car tmp)
7546 ind-down (nth 2 tmp)
7547 ind-up (nth 1 tmp)
7548 delta (if (> arg 0)
7549 (if ind-down (- ind-down ind) 2)
7550 (if ind-up (- ind-up ind) -2)))
7551 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7552 (while (< (point) end)
7553 (beginning-of-line 1)
7554 (skip-chars-forward " \t") (setq ind1 (current-column))
7555 (delete-region (point-at-bol) (point))
7556 (or (eolp) (indent-to-column (+ ind1 delta)))
7557 (beginning-of-line 2))))
7558 (org-fix-bullet-type)
7559 (org-maybe-renumber-ordered-list-safe)
7560 (save-excursion
7561 (beginning-of-line 0)
7562 (condition-case nil (org-beginning-of-item) (error nil))
7563 (org-maybe-renumber-ordered-list-safe)))
7565 (defun org-item-indent-positions ()
7566 "Return indentation for plain list items.
7567 This returns a list with three values: The current indentation, the
7568 parent indentation and the indentation a child should habe.
7569 Assumes cursor in item line."
7570 (let* ((bolpos (point-at-bol))
7571 (ind (org-get-indentation))
7572 ind-down ind-up pos)
7573 (save-excursion
7574 (org-beginning-of-item-list)
7575 (skip-chars-backward "\n\r \t")
7576 (when (org-in-item-p)
7577 (org-beginning-of-item)
7578 (setq ind-up (org-get-indentation))))
7579 (setq pos (point))
7580 (save-excursion
7581 (cond
7582 ((and (condition-case nil (progn (org-previous-item) t)
7583 (error nil))
7584 (or (forward-char 1) t)
7585 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7586 (setq ind-down (org-get-indentation)))
7587 ((and (goto-char pos)
7588 (org-at-item-p))
7589 (goto-char (match-end 0))
7590 (skip-chars-forward " \t")
7591 (setq ind-down (current-column)))))
7592 (list ind ind-up ind-down)))
7594 ;;; The orgstruct minor mode
7596 ;; Define a minor mode which can be used in other modes in order to
7597 ;; integrate the org-mode structure editing commands.
7599 ;; This is really a hack, because the org-mode structure commands use
7600 ;; keys which normally belong to the major mode. Here is how it
7601 ;; works: The minor mode defines all the keys necessary to operate the
7602 ;; structure commands, but wraps the commands into a function which
7603 ;; tests if the cursor is currently at a headline or a plain list
7604 ;; item. If that is the case, the structure command is used,
7605 ;; temporarily setting many Org-mode variables like regular
7606 ;; expressions for filling etc. However, when any of those keys is
7607 ;; used at a different location, function uses `key-binding' to look
7608 ;; up if the key has an associated command in another currently active
7609 ;; keymap (minor modes, major mode, global), and executes that
7610 ;; command. There might be problems if any of the keys is otherwise
7611 ;; used as a prefix key.
7613 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7614 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7615 ;; addresses this by checking explicitly for both bindings.
7617 (defvar orgstruct-mode-map (make-sparse-keymap)
7618 "Keymap for the minor `orgstruct-mode'.")
7620 (defvar org-local-vars nil
7621 "List of local variables, for use by `orgstruct-mode'")
7623 ;;;###autoload
7624 (define-minor-mode orgstruct-mode
7625 "Toggle the minor more `orgstruct-mode'.
7626 This mode is for using Org-mode structure commands in other modes.
7627 The following key behave as if Org-mode was active, if the cursor
7628 is on a headline, or on a plain list item (both in the definition
7629 of Org-mode).
7631 M-up Move entry/item up
7632 M-down Move entry/item down
7633 M-left Promote
7634 M-right Demote
7635 M-S-up Move entry/item up
7636 M-S-down Move entry/item down
7637 M-S-left Promote subtree
7638 M-S-right Demote subtree
7639 M-q Fill paragraph and items like in Org-mode
7640 C-c ^ Sort entries
7641 C-c - Cycle list bullet
7642 TAB Cycle item visibility
7643 M-RET Insert new heading/item
7644 S-M-RET Insert new TODO heading / Chekbox item
7645 C-c C-c Set tags / toggle checkbox"
7646 nil " OrgStruct" nil
7647 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7649 ;;;###autoload
7650 (defun turn-on-orgstruct ()
7651 "Unconditionally turn on `orgstruct-mode'."
7652 (orgstruct-mode 1))
7654 ;;;###autoload
7655 (defun turn-on-orgstruct++ ()
7656 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7657 In addition to setting orgstruct-mode, this also exports all indentation and
7658 autofilling variables from org-mode into the buffer. Note that turning
7659 off orgstruct-mode will *not* remove these additional settings."
7660 (orgstruct-mode 1)
7661 (let (var val)
7662 (mapc
7663 (lambda (x)
7664 (when (string-match
7665 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7666 (symbol-name (car x)))
7667 (setq var (car x) val (nth 1 x))
7668 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7669 org-local-vars)))
7671 (defun orgstruct-error ()
7672 "Error when there is no default binding for a structure key."
7673 (interactive)
7674 (error "This key has no function outside structure elements"))
7676 (defun orgstruct-setup ()
7677 "Setup orgstruct keymaps."
7678 (let ((nfunc 0)
7679 (bindings
7680 (list
7681 '([(meta up)] org-metaup)
7682 '([(meta down)] org-metadown)
7683 '([(meta left)] org-metaleft)
7684 '([(meta right)] org-metaright)
7685 '([(meta shift up)] org-shiftmetaup)
7686 '([(meta shift down)] org-shiftmetadown)
7687 '([(meta shift left)] org-shiftmetaleft)
7688 '([(meta shift right)] org-shiftmetaright)
7689 '([(shift up)] org-shiftup)
7690 '([(shift down)] org-shiftdown)
7691 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7692 '("\M-q" fill-paragraph)
7693 '("\C-c^" org-sort)
7694 '("\C-c-" org-cycle-list-bullet)))
7695 elt key fun cmd)
7696 (while (setq elt (pop bindings))
7697 (setq nfunc (1+ nfunc))
7698 (setq key (org-key (car elt))
7699 fun (nth 1 elt)
7700 cmd (orgstruct-make-binding fun nfunc key))
7701 (org-defkey orgstruct-mode-map key cmd))
7703 ;; Special treatment needed for TAB and RET
7704 (org-defkey orgstruct-mode-map [(tab)]
7705 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7706 (org-defkey orgstruct-mode-map "\C-i"
7707 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7709 (org-defkey orgstruct-mode-map "\M-\C-m"
7710 (orgstruct-make-binding 'org-insert-heading 105
7711 "\M-\C-m" [(meta return)]))
7712 (org-defkey orgstruct-mode-map [(meta return)]
7713 (orgstruct-make-binding 'org-insert-heading 106
7714 [(meta return)] "\M-\C-m"))
7716 (org-defkey orgstruct-mode-map [(shift meta return)]
7717 (orgstruct-make-binding 'org-insert-todo-heading 107
7718 [(meta return)] "\M-\C-m"))
7720 (unless org-local-vars
7721 (setq org-local-vars (org-get-local-variables)))
7725 (defun orgstruct-make-binding (fun n &rest keys)
7726 "Create a function for binding in the structure minor mode.
7727 FUN is the command to call inside a table. N is used to create a unique
7728 command name. KEYS are keys that should be checked in for a command
7729 to execute outside of tables."
7730 (eval
7731 (list 'defun
7732 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7733 '(arg)
7734 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7735 "Outside of structure, run the binding of `"
7736 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7737 "'.")
7738 '(interactive "p")
7739 (list 'if
7740 '(org-context-p 'headline 'item)
7741 (list 'org-run-like-in-org-mode (list 'quote fun))
7742 (list 'let '(orgstruct-mode)
7743 (list 'call-interactively
7744 (append '(or)
7745 (mapcar (lambda (k)
7746 (list 'key-binding k))
7747 keys)
7748 '('orgstruct-error))))))))
7750 (defun org-context-p (&rest contexts)
7751 "Check if local context is and of CONTEXTS.
7752 Possible values in the list of contexts are `table', `headline', and `item'."
7753 (let ((pos (point)))
7754 (goto-char (point-at-bol))
7755 (prog1 (or (and (memq 'table contexts)
7756 (looking-at "[ \t]*|"))
7757 (and (memq 'headline contexts)
7758 (looking-at "\\*+"))
7759 (and (memq 'item contexts)
7760 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
7761 (goto-char pos))))
7763 (defun org-get-local-variables ()
7764 "Return a list of all local variables in an org-mode buffer."
7765 (let (varlist)
7766 (with-current-buffer (get-buffer-create "*Org tmp*")
7767 (erase-buffer)
7768 (org-mode)
7769 (setq varlist (buffer-local-variables)))
7770 (kill-buffer "*Org tmp*")
7771 (delq nil
7772 (mapcar
7773 (lambda (x)
7774 (setq x
7775 (if (symbolp x)
7776 (list x)
7777 (list (car x) (list 'quote (cdr x)))))
7778 (if (string-match
7779 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7780 (symbol-name (car x)))
7781 x nil))
7782 varlist))))
7784 ;;;###autoload
7785 (defun org-run-like-in-org-mode (cmd)
7786 (unless org-local-vars
7787 (setq org-local-vars (org-get-local-variables)))
7788 (eval (list 'let org-local-vars
7789 (list 'call-interactively (list 'quote cmd)))))
7791 ;;;; Archiving
7793 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
7795 (defun org-archive-subtree (&optional find-done)
7796 "Move the current subtree to the archive.
7797 The archive can be a certain top-level heading in the current file, or in
7798 a different file. The tree will be moved to that location, the subtree
7799 heading be marked DONE, and the current time will be added.
7801 When called with prefix argument FIND-DONE, find whole trees without any
7802 open TODO items and archive them (after getting confirmation from the user).
7803 If the cursor is not at a headline when this comand is called, try all level
7804 1 trees. If the cursor is on a headline, only try the direct children of
7805 this heading."
7806 (interactive "P")
7807 (if find-done
7808 (org-archive-all-done)
7809 ;; Save all relevant TODO keyword-relatex variables
7811 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
7812 (tr-org-todo-keywords-1 org-todo-keywords-1)
7813 (tr-org-todo-kwd-alist org-todo-kwd-alist)
7814 (tr-org-done-keywords org-done-keywords)
7815 (tr-org-todo-regexp org-todo-regexp)
7816 (tr-org-todo-line-regexp org-todo-line-regexp)
7817 (tr-org-odd-levels-only org-odd-levels-only)
7818 (this-buffer (current-buffer))
7819 (org-archive-location org-archive-location)
7820 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
7821 ;; start of variables that will be used for saving context
7822 ;; The compiler complains about them - keep them anyway!
7823 (file (abbreviate-file-name (buffer-file-name)))
7824 (olpath (mapconcat 'identity (org-get-outline-path) "/"))
7825 (time (format-time-string
7826 (substring (cdr org-time-stamp-formats) 1 -1)
7827 (current-time)))
7828 afile heading buffer level newfile-p
7829 category todo priority
7830 ;; start of variables that will be used for savind context
7831 ltags itags prop)
7833 ;; Try to find a local archive location
7834 (save-excursion
7835 (save-restriction
7836 (widen)
7837 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
7838 (if (and prop (string-match "\\S-" prop))
7839 (setq org-archive-location prop)
7840 (if (or (re-search-backward re nil t)
7841 (re-search-forward re nil t))
7842 (setq org-archive-location (match-string 1))))))
7844 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
7845 (progn
7846 (setq afile (format (match-string 1 org-archive-location)
7847 (file-name-nondirectory buffer-file-name))
7848 heading (match-string 2 org-archive-location)))
7849 (error "Invalid `org-archive-location'"))
7850 (if (> (length afile) 0)
7851 (setq newfile-p (not (file-exists-p afile))
7852 buffer (find-file-noselect afile))
7853 (setq buffer (current-buffer)))
7854 (unless buffer
7855 (error "Cannot access file \"%s\"" afile))
7856 (if (and (> (length heading) 0)
7857 (string-match "^\\*+" heading))
7858 (setq level (match-end 0))
7859 (setq heading nil level 0))
7860 (save-excursion
7861 (org-back-to-heading t)
7862 ;; Get context information that will be lost by moving the tree
7863 (org-refresh-category-properties)
7864 (setq category (org-get-category)
7865 todo (and (looking-at org-todo-line-regexp)
7866 (match-string 2))
7867 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
7868 ltags (org-get-tags)
7869 itags (org-delete-all ltags (org-get-tags-at)))
7870 (setq ltags (mapconcat 'identity ltags " ")
7871 itags (mapconcat 'identity itags " "))
7872 ;; We first only copy, in case something goes wrong
7873 ;; we need to protect this-command, to avoid kill-region sets it,
7874 ;; which would lead to duplication of subtrees
7875 (let (this-command) (org-copy-subtree))
7876 (set-buffer buffer)
7877 ;; Enforce org-mode for the archive buffer
7878 (if (not (org-mode-p))
7879 ;; Force the mode for future visits.
7880 (let ((org-insert-mode-line-in-empty-file t)
7881 (org-inhibit-startup t))
7882 (call-interactively 'org-mode)))
7883 (when newfile-p
7884 (goto-char (point-max))
7885 (insert (format "\nArchived entries from file %s\n\n"
7886 (buffer-file-name this-buffer))))
7887 ;; Force the TODO keywords of the original buffer
7888 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
7889 (org-todo-keywords-1 tr-org-todo-keywords-1)
7890 (org-todo-kwd-alist tr-org-todo-kwd-alist)
7891 (org-done-keywords tr-org-done-keywords)
7892 (org-todo-regexp tr-org-todo-regexp)
7893 (org-todo-line-regexp tr-org-todo-line-regexp)
7894 (org-odd-levels-only
7895 (if (local-variable-p 'org-odd-levels-only (current-buffer))
7896 org-odd-levels-only
7897 tr-org-odd-levels-only)))
7898 (goto-char (point-min))
7899 (if heading
7900 (progn
7901 (if (re-search-forward
7902 (concat "^" (regexp-quote heading)
7903 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
7904 nil t)
7905 (goto-char (match-end 0))
7906 ;; Heading not found, just insert it at the end
7907 (goto-char (point-max))
7908 (or (bolp) (insert "\n"))
7909 (insert "\n" heading "\n")
7910 (end-of-line 0))
7911 ;; Make the subtree visible
7912 (show-subtree)
7913 (org-end-of-subtree t)
7914 (skip-chars-backward " \t\r\n")
7915 (and (looking-at "[ \t\r\n]*")
7916 (replace-match "\n\n")))
7917 ;; No specific heading, just go to end of file.
7918 (goto-char (point-max)) (insert "\n"))
7919 ;; Paste
7920 (org-paste-subtree (org-get-legal-level level 1))
7922 ;; Mark the entry as done
7923 (when (and org-archive-mark-done
7924 (looking-at org-todo-line-regexp)
7925 (or (not (match-end 2))
7926 (not (member (match-string 2) org-done-keywords))))
7927 (let (org-log-done)
7928 (org-todo
7929 (car (or (member org-archive-mark-done org-done-keywords)
7930 org-done-keywords)))))
7932 ;; Add the context info
7933 (when org-archive-save-context-info
7934 (let ((l org-archive-save-context-info) e n v)
7935 (while (setq e (pop l))
7936 (when (and (setq v (symbol-value e))
7937 (stringp v) (string-match "\\S-" v))
7938 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
7939 (org-entry-put (point) n v)))))
7941 ;; Save the buffer, if it is not the same buffer.
7942 (if (not (eq this-buffer buffer)) (save-buffer))))
7943 ;; Here we are back in the original buffer. Everything seems to have
7944 ;; worked. So now cut the tree and finish up.
7945 (let (this-command) (org-cut-subtree))
7946 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
7947 (message "Subtree archived %s"
7948 (if (eq this-buffer buffer)
7949 (concat "under heading: " heading)
7950 (concat "in file: " (abbreviate-file-name afile)))))))
7952 (defun org-refresh-category-properties ()
7953 "Refresh category text properties in teh buffer."
7954 (let ((def-cat (cond
7955 ((null org-category)
7956 (if buffer-file-name
7957 (file-name-sans-extension
7958 (file-name-nondirectory buffer-file-name))
7959 "???"))
7960 ((symbolp org-category) (symbol-name org-category))
7961 (t org-category)))
7962 beg end cat pos optionp)
7963 (org-unmodified
7964 (save-excursion
7965 (save-restriction
7966 (widen)
7967 (goto-char (point-min))
7968 (put-text-property (point) (point-max) 'org-category def-cat)
7969 (while (re-search-forward
7970 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7971 (setq pos (match-end 0)
7972 optionp (equal (char-after (match-beginning 0)) ?#)
7973 cat (org-trim (match-string 2)))
7974 (if optionp
7975 (setq beg (point-at-bol) end (point-max))
7976 (org-back-to-heading t)
7977 (setq beg (point) end (org-end-of-subtree t t)))
7978 (put-text-property beg end 'org-category cat)
7979 (goto-char pos)))))))
7981 (defun org-archive-all-done (&optional tag)
7982 "Archive sublevels of the current tree without open TODO items.
7983 If the cursor is not on a headline, try all level 1 trees. If
7984 it is on a headline, try all direct children.
7985 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
7986 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
7987 (rea (concat ".*:" org-archive-tag ":"))
7988 (begm (make-marker))
7989 (endm (make-marker))
7990 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
7991 "Move subtree to archive (no open TODO items)? "))
7992 beg end (cntarch 0))
7993 (if (org-on-heading-p)
7994 (progn
7995 (setq re1 (concat "^" (regexp-quote
7996 (make-string
7997 (1+ (- (match-end 0) (match-beginning 0) 1))
7998 ?*))
7999 " "))
8000 (move-marker begm (point))
8001 (move-marker endm (org-end-of-subtree t)))
8002 (setq re1 "^* ")
8003 (move-marker begm (point-min))
8004 (move-marker endm (point-max)))
8005 (save-excursion
8006 (goto-char begm)
8007 (while (re-search-forward re1 endm t)
8008 (setq beg (match-beginning 0)
8009 end (save-excursion (org-end-of-subtree t) (point)))
8010 (goto-char beg)
8011 (if (re-search-forward re end t)
8012 (goto-char end)
8013 (goto-char beg)
8014 (if (and (or (not tag) (not (looking-at rea)))
8015 (y-or-n-p question))
8016 (progn
8017 (if tag
8018 (org-toggle-tag org-archive-tag 'on)
8019 (org-archive-subtree))
8020 (setq cntarch (1+ cntarch)))
8021 (goto-char end)))))
8022 (message "%d trees archived" cntarch)))
8024 (defun org-cycle-hide-drawers (state)
8025 "Re-hide all drawers after a visibility state change."
8026 (when (and (org-mode-p)
8027 (not (memq state '(overview folded))))
8028 (save-excursion
8029 (let* ((globalp (memq state '(contents all)))
8030 (beg (if globalp (point-min) (point)))
8031 (end (if globalp (point-max) (org-end-of-subtree t))))
8032 (goto-char beg)
8033 (while (re-search-forward org-drawer-regexp end t)
8034 (org-flag-drawer t))))))
8036 (defun org-flag-drawer (flag)
8037 (save-excursion
8038 (beginning-of-line 1)
8039 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
8040 (let ((b (match-end 0))
8041 (outline-regexp org-outline-regexp))
8042 (if (re-search-forward
8043 "^[ \t]*:END:"
8044 (save-excursion (outline-next-heading) (point)) t)
8045 (outline-flag-region b (point-at-eol) flag)
8046 (error ":END: line missing"))))))
8048 (defun org-cycle-hide-archived-subtrees (state)
8049 "Re-hide all archived subtrees after a visibility state change."
8050 (when (and (not org-cycle-open-archived-trees)
8051 (not (memq state '(overview folded))))
8052 (save-excursion
8053 (let* ((globalp (memq state '(contents all)))
8054 (beg (if globalp (point-min) (point)))
8055 (end (if globalp (point-max) (org-end-of-subtree t))))
8056 (org-hide-archived-subtrees beg end)
8057 (goto-char beg)
8058 (if (looking-at (concat ".*:" org-archive-tag ":"))
8059 (message "%s" (substitute-command-keys
8060 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
8062 (defun org-force-cycle-archived ()
8063 "Cycle subtree even if it is archived."
8064 (interactive)
8065 (setq this-command 'org-cycle)
8066 (let ((org-cycle-open-archived-trees t))
8067 (call-interactively 'org-cycle)))
8069 (defun org-hide-archived-subtrees (beg end)
8070 "Re-hide all archived subtrees after a visibility state change."
8071 (save-excursion
8072 (let* ((re (concat ":" org-archive-tag ":")))
8073 (goto-char beg)
8074 (while (re-search-forward re end t)
8075 (and (org-on-heading-p) (hide-subtree))
8076 (org-end-of-subtree t)))))
8078 (defun org-toggle-tag (tag &optional onoff)
8079 "Toggle the tag TAG for the current line.
8080 If ONOFF is `on' or `off', don't toggle but set to this state."
8081 (unless (org-on-heading-p t) (error "Not on headling"))
8082 (let (res current)
8083 (save-excursion
8084 (beginning-of-line)
8085 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8086 (point-at-eol) t)
8087 (progn
8088 (setq current (match-string 1))
8089 (replace-match ""))
8090 (setq current ""))
8091 (setq current (nreverse (org-split-string current ":")))
8092 (cond
8093 ((eq onoff 'on)
8094 (setq res t)
8095 (or (member tag current) (push tag current)))
8096 ((eq onoff 'off)
8097 (or (not (member tag current)) (setq current (delete tag current))))
8098 (t (if (member tag current)
8099 (setq current (delete tag current))
8100 (setq res t)
8101 (push tag current))))
8102 (end-of-line 1)
8103 (if current
8104 (progn
8105 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8106 (org-set-tags nil t))
8107 (delete-horizontal-space))
8108 (run-hooks 'org-after-tags-change-hook))
8109 res))
8111 (defun org-toggle-archive-tag (&optional arg)
8112 "Toggle the archive tag for the current headline.
8113 With prefix ARG, check all children of current headline and offer tagging
8114 the children that do not contain any open TODO items."
8115 (interactive "P")
8116 (if arg
8117 (org-archive-all-done 'tag)
8118 (let (set)
8119 (save-excursion
8120 (org-back-to-heading t)
8121 (setq set (org-toggle-tag org-archive-tag))
8122 (when set (hide-subtree)))
8123 (and set (beginning-of-line 1))
8124 (message "Subtree %s" (if set "archived" "unarchived")))))
8127 ;;;; Tables
8129 ;;; The table editor
8131 ;; Watch out: Here we are talking about two different kind of tables.
8132 ;; Most of the code is for the tables created with the Org-mode table editor.
8133 ;; Sometimes, we talk about tables created and edited with the table.el
8134 ;; Emacs package. We call the former org-type tables, and the latter
8135 ;; table.el-type tables.
8137 (defun org-before-change-function (beg end)
8138 "Every change indicates that a table might need an update."
8139 (setq org-table-may-need-update t))
8141 (defconst org-table-line-regexp "^[ \t]*|"
8142 "Detects an org-type table line.")
8143 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8144 "Detects an org-type table line.")
8145 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8146 "Detects a table line marked for automatic recalculation.")
8147 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8148 "Detects a table line marked for automatic recalculation.")
8149 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8150 "Detects a table line marked for automatic recalculation.")
8151 (defconst org-table-hline-regexp "^[ \t]*|-"
8152 "Detects an org-type table hline.")
8153 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8154 "Detects a table-type table hline.")
8155 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8156 "Detects an org-type or table-type table.")
8157 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8158 "Searching from within a table (any type) this finds the first line
8159 outside the table.")
8160 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8161 "Searching from within a table (any type) this finds the first line
8162 outside the table.")
8164 (defvar org-table-last-highlighted-reference nil)
8165 (defvar org-table-formula-history nil)
8167 (defvar org-table-column-names nil
8168 "Alist with column names, derived from the `!' line.")
8169 (defvar org-table-column-name-regexp nil
8170 "Regular expression matching the current column names.")
8171 (defvar org-table-local-parameters nil
8172 "Alist with parameter names, derived from the `$' line.")
8173 (defvar org-table-named-field-locations nil
8174 "Alist with locations of named fields.")
8176 (defvar org-table-current-line-types nil
8177 "Table row types, non-nil only for the duration of a comand.")
8178 (defvar org-table-current-begin-line nil
8179 "Table begin line, non-nil only for the duration of a comand.")
8180 (defvar org-table-current-begin-pos nil
8181 "Table begin position, non-nil only for the duration of a comand.")
8182 (defvar org-table-dlines nil
8183 "Vector of data line line numbers in the current table.")
8184 (defvar org-table-hlines nil
8185 "Vector of hline line numbers in the current table.")
8187 (defconst org-table-range-regexp
8188 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
8189 ;; 1 2 3 4 5
8190 "Regular expression for matching ranges in formulas.")
8192 (defconst org-table-range-regexp2
8193 (concat
8194 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
8195 "\\.\\."
8196 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8197 "Match a range for reference display.")
8199 (defconst org-table-translate-regexp
8200 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8201 "Match a reference that needs translation, for reference display.")
8203 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8205 (defun org-table-create-with-table.el ()
8206 "Use the table.el package to insert a new table.
8207 If there is already a table at point, convert between Org-mode tables
8208 and table.el tables."
8209 (interactive)
8210 (require 'table)
8211 (cond
8212 ((org-at-table.el-p)
8213 (if (y-or-n-p "Convert table to Org-mode table? ")
8214 (org-table-convert)))
8215 ((org-at-table-p)
8216 (if (y-or-n-p "Convert table to table.el table? ")
8217 (org-table-convert)))
8218 (t (call-interactively 'table-insert))))
8220 (defun org-table-create-or-convert-from-region (arg)
8221 "Convert region to table, or create an empty table.
8222 If there is an active region, convert it to a table, using the function
8223 `org-table-convert-region'. See the documentation of that function
8224 to learn how the prefix argument is interpreted to determine the field
8225 separator.
8226 If there is no such region, create an empty table with `org-table-create'."
8227 (interactive "P")
8228 (if (org-region-active-p)
8229 (org-table-convert-region (region-beginning) (region-end) arg)
8230 (org-table-create arg)))
8232 (defun org-table-create (&optional size)
8233 "Query for a size and insert a table skeleton.
8234 SIZE is a string Columns x Rows like for example \"3x2\"."
8235 (interactive "P")
8236 (unless size
8237 (setq size (read-string
8238 (concat "Table size Columns x Rows [e.g. "
8239 org-table-default-size "]: ")
8240 "" nil org-table-default-size)))
8242 (let* ((pos (point))
8243 (indent (make-string (current-column) ?\ ))
8244 (split (org-split-string size " *x *"))
8245 (rows (string-to-number (nth 1 split)))
8246 (columns (string-to-number (car split)))
8247 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8248 "\n")))
8249 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8250 (point-at-bol) (point)))
8251 (beginning-of-line 1)
8252 (newline))
8253 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8254 (dotimes (i rows) (insert line))
8255 (goto-char pos)
8256 (if (> rows 1)
8257 ;; Insert a hline after the first row.
8258 (progn
8259 (end-of-line 1)
8260 (insert "\n|-")
8261 (goto-char pos)))
8262 (org-table-align)))
8264 (defun org-table-convert-region (beg0 end0 &optional separator)
8265 "Convert region to a table.
8266 The region goes from BEG0 to END0, but these borders will be moved
8267 slightly, to make sure a beginning of line in the first line is included.
8269 SEPARATOR specifies the field separator in the lines. It can have the
8270 following values:
8272 '(4) Use the comma as a field separator
8273 '(16) Use a TAB as field separator
8274 integer When a number, use that many spaces as field separator
8275 nil When nil, the command tries to be smart and figure out the
8276 separator in the following way:
8277 - when each line contains a TAB, assume TAB-separated material
8278 - when each line contains a comme, assume CSV material
8279 - else, assume one or more SPACE charcters as separator."
8280 (interactive "rP")
8281 (let* ((beg (min beg0 end0))
8282 (end (max beg0 end0))
8284 (goto-char beg)
8285 (beginning-of-line 1)
8286 (setq beg (move-marker (make-marker) (point)))
8287 (goto-char end)
8288 (if (bolp) (backward-char 1) (end-of-line 1))
8289 (setq end (move-marker (make-marker) (point)))
8290 ;; Get the right field separator
8291 (unless separator
8292 (goto-char beg)
8293 (setq separator
8294 (cond
8295 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8296 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8297 (t 1))))
8298 (setq re (cond
8299 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8300 ((equal separator '(16)) "^\\|\t")
8301 ((integerp separator)
8302 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8303 (t (error "This should not happen"))))
8304 (goto-char beg)
8305 (while (re-search-forward re end t)
8306 (replace-match "| " t t))
8307 (goto-char beg)
8308 (insert " ")
8309 (org-table-align)))
8311 (defun org-table-import (file arg)
8312 "Import FILE as a table.
8313 The file is assumed to be tab-separated. Such files can be produced by most
8314 spreadsheet and database applications. If no tabs (at least one per line)
8315 are found, lines will be split on whitespace into fields."
8316 (interactive "f\nP")
8317 (or (bolp) (newline))
8318 (let ((beg (point))
8319 (pm (point-max)))
8320 (insert-file-contents file)
8321 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8323 (defun org-table-export ()
8324 "Export table as a tab-separated file.
8325 Such a file can be imported into a spreadsheet program like Excel."
8326 (interactive)
8327 (let* ((beg (org-table-begin))
8328 (end (org-table-end))
8329 (table (buffer-substring beg end))
8330 (file (read-file-name "Export table to: "))
8331 buf)
8332 (unless (or (not (file-exists-p file))
8333 (y-or-n-p (format "Overwrite file %s? " file)))
8334 (error "Abort"))
8335 (with-current-buffer (find-file-noselect file)
8336 (setq buf (current-buffer))
8337 (erase-buffer)
8338 (fundamental-mode)
8339 (insert table)
8340 (goto-char (point-min))
8341 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8342 (replace-match "" t t)
8343 (end-of-line 1))
8344 (goto-char (point-min))
8345 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8346 (replace-match "" t t)
8347 (goto-char (min (1+ (point)) (point-max))))
8348 (goto-char (point-min))
8349 (while (re-search-forward "^-[-+]*$" nil t)
8350 (replace-match "")
8351 (if (looking-at "\n")
8352 (delete-char 1)))
8353 (goto-char (point-min))
8354 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8355 (replace-match "\t" t t))
8356 (save-buffer))
8357 (kill-buffer buf)))
8359 (defvar org-table-aligned-begin-marker (make-marker)
8360 "Marker at the beginning of the table last aligned.
8361 Used to check if cursor still is in that table, to minimize realignment.")
8362 (defvar org-table-aligned-end-marker (make-marker)
8363 "Marker at the end of the table last aligned.
8364 Used to check if cursor still is in that table, to minimize realignment.")
8365 (defvar org-table-last-alignment nil
8366 "List of flags for flushright alignment, from the last re-alignment.
8367 This is being used to correctly align a single field after TAB or RET.")
8368 (defvar org-table-last-column-widths nil
8369 "List of max width of fields in each column.
8370 This is being used to correctly align a single field after TAB or RET.")
8371 (defvar org-table-overlay-coordinates nil
8372 "Overlay coordinates after each align of a table.")
8373 (make-variable-buffer-local 'org-table-overlay-coordinates)
8375 (defvar org-last-recalc-line nil)
8376 (defconst org-narrow-column-arrow "=>"
8377 "Used as display property in narrowed table columns.")
8379 (defun org-table-align ()
8380 "Align the table at point by aligning all vertical bars."
8381 (interactive)
8382 (let* (
8383 ;; Limits of table
8384 (beg (org-table-begin))
8385 (end (org-table-end))
8386 ;; Current cursor position
8387 (linepos (org-current-line))
8388 (colpos (org-table-current-column))
8389 (winstart (window-start))
8390 (winstartline (org-current-line (min winstart (1- (point-max)))))
8391 lines (new "") lengths l typenums ty fields maxfields i
8392 column
8393 (indent "") cnt frac
8394 rfmt hfmt
8395 (spaces '(1 . 1))
8396 (sp1 (car spaces))
8397 (sp2 (cdr spaces))
8398 (rfmt1 (concat
8399 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8400 (hfmt1 (concat
8401 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8402 emptystrings links dates emph narrow fmax f1 len c e)
8403 (untabify beg end)
8404 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8405 ;; Check if we have links or dates
8406 (goto-char beg)
8407 (setq links (re-search-forward org-bracket-link-regexp end t))
8408 (goto-char beg)
8409 (setq emph (and org-hide-emphasis-markers
8410 (re-search-forward org-emph-re end t)))
8411 (goto-char beg)
8412 (setq dates (and org-display-custom-times
8413 (re-search-forward org-ts-regexp-both end t)))
8414 ;; Make sure the link properties are right
8415 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8416 ;; Make sure the date properties are right
8417 (when dates (goto-char beg) (while (org-activate-dates end)))
8418 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8420 ;; Check if we are narrowing any columns
8421 (goto-char beg)
8422 (setq narrow (and org-format-transports-properties-p
8423 (re-search-forward "<[0-9]+>" end t)))
8424 ;; Get the rows
8425 (setq lines (org-split-string
8426 (buffer-substring beg end) "\n"))
8427 ;; Store the indentation of the first line
8428 (if (string-match "^ *" (car lines))
8429 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8430 ;; Mark the hlines by setting the corresponding element to nil
8431 ;; At the same time, we remove trailing space.
8432 (setq lines (mapcar (lambda (l)
8433 (if (string-match "^ *|-" l)
8435 (if (string-match "[ \t]+$" l)
8436 (substring l 0 (match-beginning 0))
8437 l)))
8438 lines))
8439 ;; Get the data fields by splitting the lines.
8440 (setq fields (mapcar
8441 (lambda (l)
8442 (org-split-string l " *| *"))
8443 (delq nil (copy-sequence lines))))
8444 ;; How many fields in the longest line?
8445 (condition-case nil
8446 (setq maxfields (apply 'max (mapcar 'length fields)))
8447 (error
8448 (kill-region beg end)
8449 (org-table-create org-table-default-size)
8450 (error "Empty table - created default table")))
8451 ;; A list of empty strings to fill any short rows on output
8452 (setq emptystrings (make-list maxfields ""))
8453 ;; Check for special formatting.
8454 (setq i -1)
8455 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8456 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8457 ;; Check if there is an explicit width specified
8458 (when narrow
8459 (setq c column fmax nil)
8460 (while c
8461 (setq e (pop c))
8462 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8463 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8464 ;; Find fields that are wider than fmax, and shorten them
8465 (when fmax
8466 (loop for xx in column do
8467 (when (and (stringp xx)
8468 (> (org-string-width xx) fmax))
8469 (org-add-props xx nil
8470 'help-echo
8471 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8472 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8473 (unless (> f1 1)
8474 (error "Cannot narrow field starting with wide link \"%s\""
8475 (match-string 0 xx)))
8476 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8477 (add-text-properties (- f1 2) f1
8478 (list 'display org-narrow-column-arrow)
8479 xx)))))
8480 ;; Get the maximum width for each column
8481 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8482 ;; Get the fraction of numbers, to decide about alignment of the column
8483 (setq cnt 0 frac 0.0)
8484 (loop for x in column do
8485 (if (equal x "")
8487 (setq frac ( / (+ (* frac cnt)
8488 (if (string-match org-table-number-regexp x) 1 0))
8489 (setq cnt (1+ cnt))))))
8490 (push (>= frac org-table-number-fraction) typenums))
8491 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8493 ;; Store the alignment of this table, for later editing of single fields
8494 (setq org-table-last-alignment typenums
8495 org-table-last-column-widths lengths)
8497 ;; With invisible characters, `format' does not get the field width right
8498 ;; So we need to make these fields wide by hand.
8499 (when (or links emph)
8500 (loop for i from 0 upto (1- maxfields) do
8501 (setq len (nth i lengths))
8502 (loop for j from 0 upto (1- (length fields)) do
8503 (setq c (nthcdr i (car (nthcdr j fields))))
8504 (if (and (stringp (car c))
8505 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8506 ; (string-match org-bracket-link-regexp (car c))
8507 (< (org-string-width (car c)) len))
8508 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8510 ;; Compute the formats needed for output of the table
8511 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8512 (while (setq l (pop lengths))
8513 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8514 (setq rfmt (concat rfmt (format rfmt1 ty l))
8515 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8516 (setq rfmt (concat rfmt "\n")
8517 hfmt (concat (substring hfmt 0 -1) "|\n"))
8519 (setq new (mapconcat
8520 (lambda (l)
8521 (if l (apply 'format rfmt
8522 (append (pop fields) emptystrings))
8523 hfmt))
8524 lines ""))
8525 ;; Replace the old one
8526 (delete-region beg end)
8527 (move-marker end nil)
8528 (move-marker org-table-aligned-begin-marker (point))
8529 (insert new)
8530 (move-marker org-table-aligned-end-marker (point))
8531 (when (and orgtbl-mode (not (org-mode-p)))
8532 (goto-char org-table-aligned-begin-marker)
8533 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8534 ;; Try to move to the old location
8535 (goto-line winstartline)
8536 (setq winstart (point-at-bol))
8537 (goto-line linepos)
8538 (set-window-start (selected-window) winstart 'noforce)
8539 (org-table-goto-column colpos)
8540 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8541 (setq org-table-may-need-update nil)
8544 (defun org-string-width (s)
8545 "Compute width of string, ignoring invisible characters.
8546 This ignores character with invisibility property `org-link', and also
8547 characters with property `org-cwidth', because these will become invisible
8548 upon the next fontification round."
8549 (let (b l)
8550 (when (or (eq t buffer-invisibility-spec)
8551 (assq 'org-link buffer-invisibility-spec))
8552 (while (setq b (text-property-any 0 (length s)
8553 'invisible 'org-link s))
8554 (setq s (concat (substring s 0 b)
8555 (substring s (or (next-single-property-change
8556 b 'invisible s) (length s)))))))
8557 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8558 (setq s (concat (substring s 0 b)
8559 (substring s (or (next-single-property-change
8560 b 'org-cwidth s) (length s))))))
8561 (setq l (string-width s) b -1)
8562 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8563 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8566 (defun org-table-begin (&optional table-type)
8567 "Find the beginning of the table and return its position.
8568 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8569 (save-excursion
8570 (if (not (re-search-backward
8571 (if table-type org-table-any-border-regexp
8572 org-table-border-regexp)
8573 nil t))
8574 (progn (goto-char (point-min)) (point))
8575 (goto-char (match-beginning 0))
8576 (beginning-of-line 2)
8577 (point))))
8579 (defun org-table-end (&optional table-type)
8580 "Find the end of the table and return its position.
8581 With argument TABLE-TYPE, go to the end of a table.el-type table."
8582 (save-excursion
8583 (if (not (re-search-forward
8584 (if table-type org-table-any-border-regexp
8585 org-table-border-regexp)
8586 nil t))
8587 (goto-char (point-max))
8588 (goto-char (match-beginning 0)))
8589 (point-marker)))
8591 (defun org-table-justify-field-maybe (&optional new)
8592 "Justify the current field, text to left, number to right.
8593 Optional argument NEW may specify text to replace the current field content."
8594 (cond
8595 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8596 ((org-at-table-hline-p))
8597 ((and (not new)
8598 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8599 (current-buffer)))
8600 (< (point) org-table-aligned-begin-marker)
8601 (>= (point) org-table-aligned-end-marker)))
8602 ;; This is not the same table, force a full re-align
8603 (setq org-table-may-need-update t))
8604 (t ;; realign the current field, based on previous full realign
8605 (let* ((pos (point)) s
8606 (col (org-table-current-column))
8607 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8608 l f n o e)
8609 (when (> col 0)
8610 (skip-chars-backward "^|\n")
8611 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8612 (progn
8613 (setq s (match-string 1)
8614 o (match-string 0)
8615 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8616 e (not (= (match-beginning 2) (match-end 2))))
8617 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8618 l (if e "|" (setq org-table-may-need-update t) ""))
8619 n (format f s))
8620 (if new
8621 (if (<= (length new) l) ;; FIXME: length -> str-width?
8622 (setq n (format f new))
8623 (setq n (concat new "|") org-table-may-need-update t)))
8624 (or (equal n o)
8625 (let (org-table-may-need-update)
8626 (replace-match n t t))))
8627 (setq org-table-may-need-update t))
8628 (goto-char pos))))))
8630 (defun org-table-next-field ()
8631 "Go to the next field in the current table, creating new lines as needed.
8632 Before doing so, re-align the table if necessary."
8633 (interactive)
8634 (org-table-maybe-eval-formula)
8635 (org-table-maybe-recalculate-line)
8636 (if (and org-table-automatic-realign
8637 org-table-may-need-update)
8638 (org-table-align))
8639 (let ((end (org-table-end)))
8640 (if (org-at-table-hline-p)
8641 (end-of-line 1))
8642 (condition-case nil
8643 (progn
8644 (re-search-forward "|" end)
8645 (if (looking-at "[ \t]*$")
8646 (re-search-forward "|" end))
8647 (if (and (looking-at "-")
8648 org-table-tab-jumps-over-hlines
8649 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8650 (goto-char (match-beginning 1)))
8651 (if (looking-at "-")
8652 (progn
8653 (beginning-of-line 0)
8654 (org-table-insert-row 'below))
8655 (if (looking-at " ") (forward-char 1))))
8656 (error
8657 (org-table-insert-row 'below)))))
8659 (defun org-table-previous-field ()
8660 "Go to the previous field in the table.
8661 Before doing so, re-align the table if necessary."
8662 (interactive)
8663 (org-table-justify-field-maybe)
8664 (org-table-maybe-recalculate-line)
8665 (if (and org-table-automatic-realign
8666 org-table-may-need-update)
8667 (org-table-align))
8668 (if (org-at-table-hline-p)
8669 (end-of-line 1))
8670 (re-search-backward "|" (org-table-begin))
8671 (re-search-backward "|" (org-table-begin))
8672 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8673 (re-search-backward "|" (org-table-begin)))
8674 (if (looking-at "| ?")
8675 (goto-char (match-end 0))))
8677 (defun org-table-next-row ()
8678 "Go to the next row (same column) in the current table.
8679 Before doing so, re-align the table if necessary."
8680 (interactive)
8681 (org-table-maybe-eval-formula)
8682 (org-table-maybe-recalculate-line)
8683 (if (or (looking-at "[ \t]*$")
8684 (save-excursion (skip-chars-backward " \t") (bolp)))
8685 (newline)
8686 (if (and org-table-automatic-realign
8687 org-table-may-need-update)
8688 (org-table-align))
8689 (let ((col (org-table-current-column)))
8690 (beginning-of-line 2)
8691 (if (or (not (org-at-table-p))
8692 (org-at-table-hline-p))
8693 (progn
8694 (beginning-of-line 0)
8695 (org-table-insert-row 'below)))
8696 (org-table-goto-column col)
8697 (skip-chars-backward "^|\n\r")
8698 (if (looking-at " ") (forward-char 1)))))
8700 (defun org-table-copy-down (n)
8701 "Copy a field down in the current column.
8702 If the field at the cursor is empty, copy into it the content of the nearest
8703 non-empty field above. With argument N, use the Nth non-empty field.
8704 If the current field is not empty, it is copied down to the next row, and
8705 the cursor is moved with it. Therefore, repeating this command causes the
8706 column to be filled row-by-row.
8707 If the variable `org-table-copy-increment' is non-nil and the field is an
8708 integer or a timestamp, it will be incremented while copying. In the case of
8709 a timestamp, if the cursor is on the year, change the year. If it is on the
8710 month or the day, change that. Point will stay on the current date field
8711 in order to easily repeat the interval."
8712 (interactive "p")
8713 (let* ((colpos (org-table-current-column))
8714 (col (current-column))
8715 (field (org-table-get-field))
8716 (non-empty (string-match "[^ \t]" field))
8717 (beg (org-table-begin))
8718 txt)
8719 (org-table-check-inside-data-field)
8720 (if non-empty
8721 (progn
8722 (setq txt (org-trim field))
8723 (org-table-next-row)
8724 (org-table-blank-field))
8725 (save-excursion
8726 (setq txt
8727 (catch 'exit
8728 (while (progn (beginning-of-line 1)
8729 (re-search-backward org-table-dataline-regexp
8730 beg t))
8731 (org-table-goto-column colpos t)
8732 (if (and (looking-at
8733 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8734 (= (setq n (1- n)) 0))
8735 (throw 'exit (match-string 1))))))))
8736 (if txt
8737 (progn
8738 (if (and org-table-copy-increment
8739 (string-match "^[0-9]+$" txt))
8740 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8741 (insert txt)
8742 (move-to-column col)
8743 (if (and org-table-copy-increment (org-at-timestamp-p t))
8744 (org-timestamp-up 1)
8745 (org-table-maybe-recalculate-line))
8746 (org-table-align)
8747 (move-to-column col))
8748 (error "No non-empty field found"))))
8750 (defun org-table-check-inside-data-field ()
8751 "Is point inside a table data field?
8752 I.e. not on a hline or before the first or after the last column?
8753 This actually throws an error, so it aborts the current command."
8754 (if (or (not (org-at-table-p))
8755 (= (org-table-current-column) 0)
8756 (org-at-table-hline-p)
8757 (looking-at "[ \t]*$"))
8758 (error "Not in table data field")))
8760 (defvar org-table-clip nil
8761 "Clipboard for table regions.")
8763 (defun org-table-blank-field ()
8764 "Blank the current table field or active region."
8765 (interactive)
8766 (org-table-check-inside-data-field)
8767 (if (and (interactive-p) (org-region-active-p))
8768 (let (org-table-clip)
8769 (org-table-cut-region (region-beginning) (region-end)))
8770 (skip-chars-backward "^|")
8771 (backward-char 1)
8772 (if (looking-at "|[^|\n]+")
8773 (let* ((pos (match-beginning 0))
8774 (match (match-string 0))
8775 (len (org-string-width match)))
8776 (replace-match (concat "|" (make-string (1- len) ?\ )))
8777 (goto-char (+ 2 pos))
8778 (substring match 1)))))
8780 (defun org-table-get-field (&optional n replace)
8781 "Return the value of the field in column N of current row.
8782 N defaults to current field.
8783 If REPLACE is a string, replace field with this value. The return value
8784 is always the old value."
8785 (and n (org-table-goto-column n))
8786 (skip-chars-backward "^|\n")
8787 (backward-char 1)
8788 (if (looking-at "|[^|\r\n]*")
8789 (let* ((pos (match-beginning 0))
8790 (val (buffer-substring (1+ pos) (match-end 0))))
8791 (if replace
8792 (replace-match (concat "|" replace) t t))
8793 (goto-char (min (point-at-eol) (+ 2 pos)))
8794 val)
8795 (forward-char 1) ""))
8797 (defun org-table-field-info (arg)
8798 "Show info about the current field, and highlight any reference at point."
8799 (interactive "P")
8800 (org-table-get-specials)
8801 (save-excursion
8802 (let* ((pos (point))
8803 (col (org-table-current-column))
8804 (cname (car (rassoc (int-to-string col) org-table-column-names)))
8805 (name (car (rassoc (list (org-current-line) col)
8806 org-table-named-field-locations)))
8807 (eql (org-table-get-stored-formulas))
8808 (dline (org-table-current-dline))
8809 (ref (format "@%d$%d" dline col))
8810 (ref1 (org-table-convert-refs-to-an ref))
8811 (fequation (or (assoc name eql) (assoc ref eql)))
8812 (cequation (assoc (int-to-string col) eql))
8813 (eqn (or fequation cequation)))
8814 (goto-char pos)
8815 (condition-case nil
8816 (org-table-show-reference 'local)
8817 (error nil))
8818 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
8819 dline col
8820 (if cname (concat " or $" cname) "")
8821 dline col ref1
8822 (if name (concat " or $" name) "")
8823 ;; FIXME: formula info not correct if special table line
8824 (if eqn
8825 (concat ", formula: "
8826 (org-table-formula-to-user
8827 (concat
8828 (if (string-match "^[$@]"(car eqn)) "" "$")
8829 (car eqn) "=" (cdr eqn))))
8830 "")))))
8832 (defun org-table-current-column ()
8833 "Find out which column we are in.
8834 When called interactively, column is also displayed in echo area."
8835 (interactive)
8836 (if (interactive-p) (org-table-check-inside-data-field))
8837 (save-excursion
8838 (let ((cnt 0) (pos (point)))
8839 (beginning-of-line 1)
8840 (while (search-forward "|" pos t)
8841 (setq cnt (1+ cnt)))
8842 (if (interactive-p) (message "This is table column %d" cnt))
8843 cnt)))
8845 (defun org-table-current-dline ()
8846 "Find out what table data line we are in.
8847 Only datalins count for this."
8848 (interactive)
8849 (if (interactive-p) (org-table-check-inside-data-field))
8850 (save-excursion
8851 (let ((cnt 0) (pos (point)))
8852 (goto-char (org-table-begin))
8853 (while (<= (point) pos)
8854 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
8855 (beginning-of-line 2))
8856 (if (interactive-p) (message "This is table line %d" cnt))
8857 cnt)))
8859 (defun org-table-goto-column (n &optional on-delim force)
8860 "Move the cursor to the Nth column in the current table line.
8861 With optional argument ON-DELIM, stop with point before the left delimiter
8862 of the field.
8863 If there are less than N fields, just go to after the last delimiter.
8864 However, when FORCE is non-nil, create new columns if necessary."
8865 (interactive "p")
8866 (let ((pos (point-at-eol)))
8867 (beginning-of-line 1)
8868 (when (> n 0)
8869 (while (and (> (setq n (1- n)) -1)
8870 (or (search-forward "|" pos t)
8871 (and force
8872 (progn (end-of-line 1)
8873 (skip-chars-backward "^|")
8874 (insert " | "))))))
8875 ; (backward-char 2) t)))))
8876 (when (and force (not (looking-at ".*|")))
8877 (save-excursion (end-of-line 1) (insert " | ")))
8878 (if on-delim
8879 (backward-char 1)
8880 (if (looking-at " ") (forward-char 1))))))
8882 (defun org-at-table-p (&optional table-type)
8883 "Return t if the cursor is inside an org-type table.
8884 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8885 (if org-enable-table-editor
8886 (save-excursion
8887 (beginning-of-line 1)
8888 (looking-at (if table-type org-table-any-line-regexp
8889 org-table-line-regexp)))
8890 nil))
8892 (defun org-at-table.el-p ()
8893 "Return t if and only if we are at a table.el table."
8894 (and (org-at-table-p 'any)
8895 (save-excursion
8896 (goto-char (org-table-begin 'any))
8897 (looking-at org-table1-hline-regexp))))
8899 (defun org-table-recognize-table.el ()
8900 "If there is a table.el table nearby, recognize it and move into it."
8901 (if org-table-tab-recognizes-table.el
8902 (if (org-at-table.el-p)
8903 (progn
8904 (beginning-of-line 1)
8905 (if (looking-at org-table-dataline-regexp)
8907 (if (looking-at org-table1-hline-regexp)
8908 (progn
8909 (beginning-of-line 2)
8910 (if (looking-at org-table-any-border-regexp)
8911 (beginning-of-line -1)))))
8912 (if (re-search-forward "|" (org-table-end t) t)
8913 (progn
8914 (require 'table)
8915 (if (table--at-cell-p (point))
8917 (message "recognizing table.el table...")
8918 (table-recognize-table)
8919 (message "recognizing table.el table...done")))
8920 (error "This should not happen..."))
8922 nil)
8923 nil))
8925 (defun org-at-table-hline-p ()
8926 "Return t if the cursor is inside a hline in a table."
8927 (if org-enable-table-editor
8928 (save-excursion
8929 (beginning-of-line 1)
8930 (looking-at org-table-hline-regexp))
8931 nil))
8933 (defun org-table-insert-column ()
8934 "Insert a new column into the table."
8935 (interactive)
8936 (if (not (org-at-table-p))
8937 (error "Not at a table"))
8938 (org-table-find-dataline)
8939 (let* ((col (max 1 (org-table-current-column)))
8940 (beg (org-table-begin))
8941 (end (org-table-end))
8942 ;; Current cursor position
8943 (linepos (org-current-line))
8944 (colpos col))
8945 (goto-char beg)
8946 (while (< (point) end)
8947 (if (org-at-table-hline-p)
8949 (org-table-goto-column col t)
8950 (insert "| "))
8951 (beginning-of-line 2))
8952 (move-marker end nil)
8953 (goto-line linepos)
8954 (org-table-goto-column colpos)
8955 (org-table-align)
8956 (org-table-fix-formulas "$" nil (1- col) 1)))
8958 (defun org-table-find-dataline ()
8959 "Find a dataline in the current table, which is needed for column commands."
8960 (if (and (org-at-table-p)
8961 (not (org-at-table-hline-p)))
8963 (let ((col (current-column))
8964 (end (org-table-end)))
8965 (move-to-column col)
8966 (while (and (< (point) end)
8967 (or (not (= (current-column) col))
8968 (org-at-table-hline-p)))
8969 (beginning-of-line 2)
8970 (move-to-column col))
8971 (if (and (org-at-table-p)
8972 (not (org-at-table-hline-p)))
8974 (error
8975 "Please position cursor in a data line for column operations")))))
8977 (defun org-table-delete-column ()
8978 "Delete a column from the table."
8979 (interactive)
8980 (if (not (org-at-table-p))
8981 (error "Not at a table"))
8982 (org-table-find-dataline)
8983 (org-table-check-inside-data-field)
8984 (let* ((col (org-table-current-column))
8985 (beg (org-table-begin))
8986 (end (org-table-end))
8987 ;; Current cursor position
8988 (linepos (org-current-line))
8989 (colpos col))
8990 (goto-char beg)
8991 (while (< (point) end)
8992 (if (org-at-table-hline-p)
8994 (org-table-goto-column col t)
8995 (and (looking-at "|[^|\n]+|")
8996 (replace-match "|")))
8997 (beginning-of-line 2))
8998 (move-marker end nil)
8999 (goto-line linepos)
9000 (org-table-goto-column colpos)
9001 (org-table-align)
9002 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
9003 col -1 col)))
9005 (defun org-table-move-column-right ()
9006 "Move column to the right."
9007 (interactive)
9008 (org-table-move-column nil))
9009 (defun org-table-move-column-left ()
9010 "Move column to the left."
9011 (interactive)
9012 (org-table-move-column 'left))
9014 (defun org-table-move-column (&optional left)
9015 "Move the current column to the right. With arg LEFT, move to the left."
9016 (interactive "P")
9017 (if (not (org-at-table-p))
9018 (error "Not at a table"))
9019 (org-table-find-dataline)
9020 (org-table-check-inside-data-field)
9021 (let* ((col (org-table-current-column))
9022 (col1 (if left (1- col) col))
9023 (beg (org-table-begin))
9024 (end (org-table-end))
9025 ;; Current cursor position
9026 (linepos (org-current-line))
9027 (colpos (if left (1- col) (1+ col))))
9028 (if (and left (= col 1))
9029 (error "Cannot move column further left"))
9030 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9031 (error "Cannot move column further right"))
9032 (goto-char beg)
9033 (while (< (point) end)
9034 (if (org-at-table-hline-p)
9036 (org-table-goto-column col1 t)
9037 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9038 (replace-match "|\\2|\\1|")))
9039 (beginning-of-line 2))
9040 (move-marker end nil)
9041 (goto-line linepos)
9042 (org-table-goto-column colpos)
9043 (org-table-align)
9044 (org-table-fix-formulas
9045 "$" (list (cons (number-to-string col) (number-to-string colpos))
9046 (cons (number-to-string colpos) (number-to-string col))))))
9048 (defun org-table-move-row-down ()
9049 "Move table row down."
9050 (interactive)
9051 (org-table-move-row nil))
9052 (defun org-table-move-row-up ()
9053 "Move table row up."
9054 (interactive)
9055 (org-table-move-row 'up))
9057 (defun org-table-move-row (&optional up)
9058 "Move the current table line down. With arg UP, move it up."
9059 (interactive "P")
9060 (let* ((col (current-column))
9061 (pos (point))
9062 (hline1p (save-excursion (beginning-of-line 1)
9063 (looking-at org-table-hline-regexp)))
9064 (dline1 (org-table-current-dline))
9065 (dline2 (+ dline1 (if up -1 1)))
9066 (tonew (if up 0 2))
9067 txt hline2p)
9068 (beginning-of-line tonew)
9069 (unless (org-at-table-p)
9070 (goto-char pos)
9071 (error "Cannot move row further"))
9072 (setq hline2p (looking-at org-table-hline-regexp))
9073 (goto-char pos)
9074 (beginning-of-line 1)
9075 (setq pos (point))
9076 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9077 (delete-region (point) (1+ (point-at-eol)))
9078 (beginning-of-line tonew)
9079 (insert txt)
9080 (beginning-of-line 0)
9081 (move-to-column col)
9082 (unless (or hline1p hline2p)
9083 (org-table-fix-formulas
9084 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
9085 (cons (number-to-string dline2) (number-to-string dline1)))))))
9087 (defun org-table-insert-row (&optional arg)
9088 "Insert a new row above the current line into the table.
9089 With prefix ARG, insert below the current line."
9090 (interactive "P")
9091 (if (not (org-at-table-p))
9092 (error "Not at a table"))
9093 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9094 (new (org-table-clean-line line)))
9095 ;; Fix the first field if necessary
9096 (if (string-match "^[ \t]*| *[#$] *|" line)
9097 (setq new (replace-match (match-string 0 line) t t new)))
9098 (beginning-of-line (if arg 2 1))
9099 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9100 (beginning-of-line 0)
9101 (re-search-forward "| ?" (point-at-eol) t)
9102 (and (or org-table-may-need-update org-table-overlay-coordinates)
9103 (org-table-align))
9104 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
9106 (defun org-table-insert-hline (&optional above)
9107 "Insert a horizontal-line below the current line into the table.
9108 With prefix ABOVE, insert above the current line."
9109 (interactive "P")
9110 (if (not (org-at-table-p))
9111 (error "Not at a table"))
9112 (let ((line (org-table-clean-line
9113 (buffer-substring (point-at-bol) (point-at-eol))))
9114 (col (current-column)))
9115 (while (string-match "|\\( +\\)|" line)
9116 (setq line (replace-match
9117 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9118 ?-) "|") t t line)))
9119 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9120 (beginning-of-line (if above 1 2))
9121 (insert line "\n")
9122 (beginning-of-line (if above 1 -1))
9123 (move-to-column col)
9124 (and org-table-overlay-coordinates (org-table-align))))
9126 (defun org-table-hline-and-move (&optional same-column)
9127 "Insert a hline and move to the row below that line."
9128 (interactive "P")
9129 (let ((col (org-table-current-column)))
9130 (org-table-maybe-eval-formula)
9131 (org-table-maybe-recalculate-line)
9132 (org-table-insert-hline)
9133 (end-of-line 2)
9134 (if (looking-at "\n[ \t]*|-")
9135 (progn (insert "\n|") (org-table-align))
9136 (org-table-next-field))
9137 (if same-column (org-table-goto-column col))))
9139 (defun org-table-clean-line (s)
9140 "Convert a table line S into a string with only \"|\" and space.
9141 In particular, this does handle wide and invisible characters."
9142 (if (string-match "^[ \t]*|-" s)
9143 ;; It's a hline, just map the characters
9144 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
9145 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9146 (setq s (replace-match
9147 (concat "|" (make-string (org-string-width (match-string 1 s))
9148 ?\ ) "|")
9149 t t s)))
9152 (defun org-table-kill-row ()
9153 "Delete the current row or horizontal line from the table."
9154 (interactive)
9155 (if (not (org-at-table-p))
9156 (error "Not at a table"))
9157 (let ((col (current-column))
9158 (dline (org-table-current-dline)))
9159 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9160 (if (not (org-at-table-p)) (beginning-of-line 0))
9161 (move-to-column col)
9162 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
9163 dline -1 dline)))
9165 (defun org-table-sort-lines (with-case &optional sorting-type)
9166 "Sort table lines according to the column at point.
9168 The position of point indicates the column to be used for
9169 sorting, and the range of lines is the range between the nearest
9170 horizontal separator lines, or the entire table of no such lines
9171 exist. If point is before the first column, you will be prompted
9172 for the sorting column. If there is an active region, the mark
9173 specifies the first line and the sorting column, while point
9174 should be in the last line to be included into the sorting.
9176 The command then prompts for the sorting type which can be
9177 alphabetically, numerically, or by time (as given in a time stamp
9178 in the field). Sorting in reverse order is also possible.
9180 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
9182 If SORTING-TYPE is specified when this function is called from a Lisp
9183 program, no prompting will take place. SORTING-TYPE must be a character,
9184 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
9185 should be done in reverse order."
9186 (interactive "P")
9187 (let* ((thisline (org-current-line))
9188 (thiscol (org-table-current-column))
9189 beg end bcol ecol tend tbeg column lns pos)
9190 (when (equal thiscol 0)
9191 (if (interactive-p)
9192 (setq thiscol
9193 (string-to-number
9194 (read-string "Use column N for sorting: ")))
9195 (setq thiscol 1))
9196 (org-table-goto-column thiscol))
9197 (org-table-check-inside-data-field)
9198 (if (org-region-active-p)
9199 (progn
9200 (setq beg (region-beginning) end (region-end))
9201 (goto-char beg)
9202 (setq column (org-table-current-column)
9203 beg (point-at-bol))
9204 (goto-char end)
9205 (setq end (point-at-bol 2)))
9206 (setq column (org-table-current-column)
9207 pos (point)
9208 tbeg (org-table-begin)
9209 tend (org-table-end))
9210 (if (re-search-backward org-table-hline-regexp tbeg t)
9211 (setq beg (point-at-bol 2))
9212 (goto-char tbeg)
9213 (setq beg (point-at-bol 1)))
9214 (goto-char pos)
9215 (if (re-search-forward org-table-hline-regexp tend t)
9216 (setq end (point-at-bol 1))
9217 (goto-char tend)
9218 (setq end (point-at-bol))))
9219 (setq beg (move-marker (make-marker) beg)
9220 end (move-marker (make-marker) end))
9221 (untabify beg end)
9222 (goto-char beg)
9223 (org-table-goto-column column)
9224 (skip-chars-backward "^|")
9225 (setq bcol (current-column))
9226 (org-table-goto-column (1+ column))
9227 (skip-chars-backward "^|")
9228 (setq ecol (1- (current-column)))
9229 (org-table-goto-column column)
9230 (setq lns (mapcar (lambda(x) (cons
9231 (org-sort-remove-invisible
9232 (nth (1- column)
9233 (org-split-string x "[ \t]*|[ \t]*")))
9235 (org-split-string (buffer-substring beg end) "\n")))
9236 (setq lns (org-do-sort lns "Table" with-case sorting-type))
9237 (delete-region beg end)
9238 (move-marker beg nil)
9239 (move-marker end nil)
9240 (insert (mapconcat 'cdr lns "\n") "\n")
9241 (goto-line thisline)
9242 (org-table-goto-column thiscol)
9243 (message "%d lines sorted, based on column %d" (length lns) column)))
9245 ;; FIXME: maybe we will not need this? Table sorting is broken....
9246 (defun org-sort-remove-invisible (s)
9247 (remove-text-properties 0 (length s) org-rm-props s)
9248 (while (string-match org-bracket-link-regexp s)
9249 (setq s (replace-match (if (match-end 2)
9250 (match-string 3 s)
9251 (match-string 1 s)) t t s)))
9254 (defun org-table-cut-region (beg end)
9255 "Copy region in table to the clipboard and blank all relevant fields."
9256 (interactive "r")
9257 (org-table-copy-region beg end 'cut))
9259 (defun org-table-copy-region (beg end &optional cut)
9260 "Copy rectangular region in table to clipboard.
9261 A special clipboard is used which can only be accessed
9262 with `org-table-paste-rectangle'."
9263 (interactive "rP")
9264 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9265 region cols
9266 (rpl (if cut " " nil)))
9267 (goto-char beg)
9268 (org-table-check-inside-data-field)
9269 (setq l01 (org-current-line)
9270 c01 (org-table-current-column))
9271 (goto-char end)
9272 (org-table-check-inside-data-field)
9273 (setq l02 (org-current-line)
9274 c02 (org-table-current-column))
9275 (setq l1 (min l01 l02) l2 (max l01 l02)
9276 c1 (min c01 c02) c2 (max c01 c02))
9277 (catch 'exit
9278 (while t
9279 (catch 'nextline
9280 (if (> l1 l2) (throw 'exit t))
9281 (goto-line l1)
9282 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9283 (setq cols nil ic1 c1 ic2 c2)
9284 (while (< ic1 (1+ ic2))
9285 (push (org-table-get-field ic1 rpl) cols)
9286 (setq ic1 (1+ ic1)))
9287 (push (nreverse cols) region)
9288 (setq l1 (1+ l1)))))
9289 (setq org-table-clip (nreverse region))
9290 (if cut (org-table-align))
9291 org-table-clip))
9293 (defun org-table-paste-rectangle ()
9294 "Paste a rectangular region into a table.
9295 The upper right corner ends up in the current field. All involved fields
9296 will be overwritten. If the rectangle does not fit into the present table,
9297 the table is enlarged as needed. The process ignores horizontal separator
9298 lines."
9299 (interactive)
9300 (unless (and org-table-clip (listp org-table-clip))
9301 (error "First cut/copy a region to paste!"))
9302 (org-table-check-inside-data-field)
9303 (let* ((clip org-table-clip)
9304 (line (org-current-line))
9305 (col (org-table-current-column))
9306 (org-enable-table-editor t)
9307 (org-table-automatic-realign nil)
9308 c cols field)
9309 (while (setq cols (pop clip))
9310 (while (org-at-table-hline-p) (beginning-of-line 2))
9311 (if (not (org-at-table-p))
9312 (progn (end-of-line 0) (org-table-next-field)))
9313 (setq c col)
9314 (while (setq field (pop cols))
9315 (org-table-goto-column c nil 'force)
9316 (org-table-get-field nil field)
9317 (setq c (1+ c)))
9318 (beginning-of-line 2))
9319 (goto-line line)
9320 (org-table-goto-column col)
9321 (org-table-align)))
9323 (defun org-table-convert ()
9324 "Convert from `org-mode' table to table.el and back.
9325 Obviously, this only works within limits. When an Org-mode table is
9326 converted to table.el, all horizontal separator lines get lost, because
9327 table.el uses these as cell boundaries and has no notion of horizontal lines.
9328 A table.el table can be converted to an Org-mode table only if it does not
9329 do row or column spanning. Multiline cells will become multiple cells.
9330 Beware, Org-mode does not test if the table can be successfully converted - it
9331 blindly applies a recipe that works for simple tables."
9332 (interactive)
9333 (require 'table)
9334 (if (org-at-table.el-p)
9335 ;; convert to Org-mode table
9336 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9337 (end (move-marker (make-marker) (org-table-end t))))
9338 (table-unrecognize-region beg end)
9339 (goto-char beg)
9340 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9341 (replace-match ""))
9342 (goto-char beg))
9343 (if (org-at-table-p)
9344 ;; convert to table.el table
9345 (let ((beg (move-marker (make-marker) (org-table-begin)))
9346 (end (move-marker (make-marker) (org-table-end))))
9347 ;; first, get rid of all horizontal lines
9348 (goto-char beg)
9349 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9350 (replace-match ""))
9351 ;; insert a hline before first
9352 (goto-char beg)
9353 (org-table-insert-hline 'above)
9354 (beginning-of-line -1)
9355 ;; insert a hline after each line
9356 (while (progn (beginning-of-line 3) (< (point) end))
9357 (org-table-insert-hline))
9358 (goto-char beg)
9359 (setq end (move-marker end (org-table-end)))
9360 ;; replace "+" at beginning and ending of hlines
9361 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9362 (replace-match "\\1+-"))
9363 (goto-char beg)
9364 (while (re-search-forward "-|[ \t]*$" end t)
9365 (replace-match "-+"))
9366 (goto-char beg)))))
9368 (defun org-table-wrap-region (arg)
9369 "Wrap several fields in a column like a paragraph.
9370 This is useful if you'd like to spread the contents of a field over several
9371 lines, in order to keep the table compact.
9373 If there is an active region, and both point and mark are in the same column,
9374 the text in the column is wrapped to minimum width for the given number of
9375 lines. Generally, this makes the table more compact. A prefix ARG may be
9376 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9377 formats the selected text to two lines. If the region was longer than two
9378 lines, the remaining lines remain empty. A negative prefix argument reduces
9379 the current number of lines by that amount. The wrapped text is pasted back
9380 into the table. If you formatted it to more lines than it was before, fields
9381 further down in the table get overwritten - so you might need to make space in
9382 the table first.
9384 If there is no region, the current field is split at the cursor position and
9385 the text fragment to the right of the cursor is prepended to the field one
9386 line down.
9388 If there is no region, but you specify a prefix ARG, the current field gets
9389 blank, and the content is appended to the field above."
9390 (interactive "P")
9391 (org-table-check-inside-data-field)
9392 (if (org-region-active-p)
9393 ;; There is a region: fill as a paragraph
9394 (let* ((beg (region-beginning))
9395 (cline (save-excursion (goto-char beg) (org-current-line)))
9396 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9397 nlines)
9398 (org-table-cut-region (region-beginning) (region-end))
9399 (if (> (length (car org-table-clip)) 1)
9400 (error "Region must be limited to single column"))
9401 (setq nlines (if arg
9402 (if (< arg 1)
9403 (+ (length org-table-clip) arg)
9404 arg)
9405 (length org-table-clip)))
9406 (setq org-table-clip
9407 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9408 nil nlines)))
9409 (goto-line cline)
9410 (org-table-goto-column ccol)
9411 (org-table-paste-rectangle))
9412 ;; No region, split the current field at point
9413 (if arg
9414 ;; combine with field above
9415 (let ((s (org-table-blank-field))
9416 (col (org-table-current-column)))
9417 (beginning-of-line 0)
9418 (while (org-at-table-hline-p) (beginning-of-line 0))
9419 (org-table-goto-column col)
9420 (skip-chars-forward "^|")
9421 (skip-chars-backward " ")
9422 (insert " " (org-trim s))
9423 (org-table-align))
9424 ;; split field
9425 (when (looking-at "\\([^|]+\\)+|")
9426 (let ((s (match-string 1)))
9427 (replace-match " |")
9428 (goto-char (match-beginning 0))
9429 (org-table-next-row)
9430 (insert (org-trim s) " ")
9431 (org-table-align))))))
9433 (defvar org-field-marker nil)
9435 (defun org-table-edit-field (arg)
9436 "Edit table field in a different window.
9437 This is mainly useful for fields that contain hidden parts.
9438 When called with a \\[universal-argument] prefix, just make the full field visible so that
9439 it can be edited in place."
9440 (interactive "P")
9441 (if arg
9442 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9443 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9444 (remove-text-properties b e '(org-cwidth t invisible t
9445 display t intangible t))
9446 (if (and (boundp 'font-lock-mode) font-lock-mode)
9447 (font-lock-fontify-block)))
9448 (let ((pos (move-marker (make-marker) (point)))
9449 (field (org-table-get-field))
9450 (cw (current-window-configuration))
9452 (org-switch-to-buffer-other-window "*Org tmp*")
9453 (erase-buffer)
9454 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9455 (let ((org-inhibit-startup t)) (org-mode))
9456 (goto-char (setq p (point-max)))
9457 (insert (org-trim field))
9458 (remove-text-properties p (point-max)
9459 '(invisible t org-cwidth t display t
9460 intangible t))
9461 (goto-char p)
9462 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9463 (org-set-local 'org-window-configuration cw)
9464 (org-set-local 'org-field-marker pos)
9465 (message "Edit and finish with C-c C-c"))))
9467 (defun org-table-finish-edit-field ()
9468 "Finish editing a table data field.
9469 Remove all newline characters, insert the result into the table, realign
9470 the table and kill the editing buffer."
9471 (let ((pos org-field-marker)
9472 (cw org-window-configuration)
9473 (cb (current-buffer))
9474 text)
9475 (goto-char (point-min))
9476 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9477 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9478 (replace-match " "))
9479 (setq text (org-trim (buffer-string)))
9480 (set-window-configuration cw)
9481 (kill-buffer cb)
9482 (select-window (get-buffer-window (marker-buffer pos)))
9483 (goto-char pos)
9484 (move-marker pos nil)
9485 (org-table-check-inside-data-field)
9486 (org-table-get-field nil text)
9487 (org-table-align)
9488 (message "New field value inserted")))
9490 (defun org-trim (s)
9491 "Remove whitespace at beginning and end of string."
9492 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9493 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9496 (defun org-wrap (string &optional width lines)
9497 "Wrap string to either a number of lines, or a width in characters.
9498 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9499 that costs. If there is a word longer than WIDTH, the text is actually
9500 wrapped to the length of that word.
9501 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9502 many lines, whatever width that takes.
9503 The return value is a list of lines, without newlines at the end."
9504 (let* ((words (org-split-string string "[ \t\n]+"))
9505 (maxword (apply 'max (mapcar 'org-string-width words)))
9506 w ll)
9507 (cond (width
9508 (org-do-wrap words (max maxword width)))
9509 (lines
9510 (setq w maxword)
9511 (setq ll (org-do-wrap words maxword))
9512 (if (<= (length ll) lines)
9514 (setq ll words)
9515 (while (> (length ll) lines)
9516 (setq w (1+ w))
9517 (setq ll (org-do-wrap words w)))
9518 ll))
9519 (t (error "Cannot wrap this")))))
9522 (defun org-do-wrap (words width)
9523 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9524 (let (lines line)
9525 (while words
9526 (setq line (pop words))
9527 (while (and words (< (+ (length line) (length (car words))) width))
9528 (setq line (concat line " " (pop words))))
9529 (setq lines (push line lines)))
9530 (nreverse lines)))
9532 (defun org-split-string (string &optional separators)
9533 "Splits STRING into substrings at SEPARATORS.
9534 No empty strings are returned if there are matches at the beginning
9535 and end of string."
9536 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9537 (start 0)
9538 notfirst
9539 (list nil))
9540 (while (and (string-match rexp string
9541 (if (and notfirst
9542 (= start (match-beginning 0))
9543 (< start (length string)))
9544 (1+ start) start))
9545 (< (match-beginning 0) (length string)))
9546 (setq notfirst t)
9547 (or (eq (match-beginning 0) 0)
9548 (and (eq (match-beginning 0) (match-end 0))
9549 (eq (match-beginning 0) start))
9550 (setq list
9551 (cons (substring string start (match-beginning 0))
9552 list)))
9553 (setq start (match-end 0)))
9554 (or (eq start (length string))
9555 (setq list
9556 (cons (substring string start)
9557 list)))
9558 (nreverse list)))
9560 (defun org-table-map-tables (function)
9561 "Apply FUNCTION to the start of all tables in the buffer."
9562 (save-excursion
9563 (save-restriction
9564 (widen)
9565 (goto-char (point-min))
9566 (while (re-search-forward org-table-any-line-regexp nil t)
9567 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9568 (beginning-of-line 1)
9569 (if (looking-at org-table-line-regexp)
9570 (save-excursion (funcall function)))
9571 (re-search-forward org-table-any-border-regexp nil 1))))
9572 (message "Mapping tables: done"))
9574 (defvar org-timecnt) ; dynamically scoped parameter
9576 (defun org-table-sum (&optional beg end nlast)
9577 "Sum numbers in region of current table column.
9578 The result will be displayed in the echo area, and will be available
9579 as kill to be inserted with \\[yank].
9581 If there is an active region, it is interpreted as a rectangle and all
9582 numbers in that rectangle will be summed. If there is no active
9583 region and point is located in a table column, sum all numbers in that
9584 column.
9586 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9587 numbers are assumed to be times as well (in decimal hours) and the
9588 numbers are added as such.
9590 If NLAST is a number, only the NLAST fields will actually be summed."
9591 (interactive)
9592 (save-excursion
9593 (let (col (org-timecnt 0) diff h m s org-table-clip)
9594 (cond
9595 ((and beg end)) ; beg and end given explicitly
9596 ((org-region-active-p)
9597 (setq beg (region-beginning) end (region-end)))
9599 (setq col (org-table-current-column))
9600 (goto-char (org-table-begin))
9601 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9602 (error "No table data"))
9603 (org-table-goto-column col)
9604 (setq beg (point))
9605 (goto-char (org-table-end))
9606 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9607 (error "No table data"))
9608 (org-table-goto-column col)
9609 (setq end (point))))
9610 (let* ((items (apply 'append (org-table-copy-region beg end)))
9611 (items1 (cond ((not nlast) items)
9612 ((>= nlast (length items)) items)
9613 (t (setq items (reverse items))
9614 (setcdr (nthcdr (1- nlast) items) nil)
9615 (nreverse items))))
9616 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9617 items1)))
9618 (res (apply '+ numbers))
9619 (sres (if (= org-timecnt 0)
9620 (format "%g" res)
9621 (setq diff (* 3600 res)
9622 h (floor (/ diff 3600)) diff (mod diff 3600)
9623 m (floor (/ diff 60)) diff (mod diff 60)
9624 s diff)
9625 (format "%d:%02d:%02d" h m s))))
9626 (kill-new sres)
9627 (if (interactive-p)
9628 (message "%s"
9629 (substitute-command-keys
9630 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9631 (length numbers) sres))))
9632 sres))))
9634 (defun org-table-get-number-for-summing (s)
9635 (let (n)
9636 (if (string-match "^ *|? *" s)
9637 (setq s (replace-match "" nil nil s)))
9638 (if (string-match " *|? *$" s)
9639 (setq s (replace-match "" nil nil s)))
9640 (setq n (string-to-number s))
9641 (cond
9642 ((and (string-match "0" s)
9643 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9644 ((string-match "\\`[ \t]+\\'" s) nil)
9645 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9646 (let ((h (string-to-number (or (match-string 1 s) "0")))
9647 (m (string-to-number (or (match-string 2 s) "0")))
9648 (s (string-to-number (or (match-string 4 s) "0"))))
9649 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9650 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9651 ((equal n 0) nil)
9652 (t n))))
9654 (defun org-table-current-field-formula (&optional key noerror)
9655 "Return the formula active for the current field.
9656 Assumes that specials are in place.
9657 If KEY is given, return the key to this formula.
9658 Otherwise return the formula preceeded with \"=\" or \":=\"."
9659 (let* ((name (car (rassoc (list (org-current-line)
9660 (org-table-current-column))
9661 org-table-named-field-locations)))
9662 (col (org-table-current-column))
9663 (scol (int-to-string col))
9664 (ref (format "@%d$%d" (org-table-current-dline) col))
9665 (stored-list (org-table-get-stored-formulas noerror))
9666 (ass (or (assoc name stored-list)
9667 (assoc ref stored-list)
9668 (assoc scol stored-list))))
9669 (if key
9670 (car ass)
9671 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9672 (cdr ass))))))
9674 (defun org-table-get-formula (&optional equation named)
9675 "Read a formula from the minibuffer, offer stored formula as default.
9676 When NAMED is non-nil, look for a named equation."
9677 (let* ((stored-list (org-table-get-stored-formulas))
9678 (name (car (rassoc (list (org-current-line)
9679 (org-table-current-column))
9680 org-table-named-field-locations)))
9681 (ref (format "@%d$%d" (org-table-current-dline)
9682 (org-table-current-column)))
9683 (refass (assoc ref stored-list))
9684 (scol (if named
9685 (if name name ref)
9686 (int-to-string (org-table-current-column))))
9687 (dummy (and (or name refass) (not named)
9688 (not (y-or-n-p "Replace field formula with column formula? " ))
9689 (error "Abort")))
9690 (name (or name ref))
9691 (org-table-may-need-update nil)
9692 (stored (cdr (assoc scol stored-list)))
9693 (eq (cond
9694 ((and stored equation (string-match "^ *=? *$" equation))
9695 stored)
9696 ((stringp equation)
9697 equation)
9698 (t (org-table-formula-from-user
9699 (read-string
9700 (org-table-formula-to-user
9701 (format "%s formula %s%s="
9702 (if named "Field" "Column")
9703 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9704 scol))
9705 (if stored (org-table-formula-to-user stored) "")
9706 'org-table-formula-history
9707 )))))
9708 mustsave)
9709 (when (not (string-match "\\S-" eq))
9710 ;; remove formula
9711 (setq stored-list (delq (assoc scol stored-list) stored-list))
9712 (org-table-store-formulas stored-list)
9713 (error "Formula removed"))
9714 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9715 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9716 (if (and name (not named))
9717 ;; We set the column equation, delete the named one.
9718 (setq stored-list (delq (assoc name stored-list) stored-list)
9719 mustsave t))
9720 (if stored
9721 (setcdr (assoc scol stored-list) eq)
9722 (setq stored-list (cons (cons scol eq) stored-list)))
9723 (if (or mustsave (not (equal stored eq)))
9724 (org-table-store-formulas stored-list))
9725 eq))
9727 (defun org-table-store-formulas (alist)
9728 "Store the list of formulas below the current table."
9729 (setq alist (sort alist 'org-table-formula-less-p))
9730 (save-excursion
9731 (goto-char (org-table-end))
9732 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9733 (progn
9734 ;; don't overwrite TBLFM, we might use text properties to store stuff
9735 (goto-char (match-beginning 2))
9736 (delete-region (match-beginning 2) (match-end 0)))
9737 (insert "#+TBLFM:"))
9738 (insert " "
9739 (mapconcat (lambda (x)
9740 (concat
9741 (if (equal (string-to-char (car x)) ?@) "" "$")
9742 (car x) "=" (cdr x)))
9743 alist "::")
9744 "\n")))
9746 (defsubst org-table-formula-make-cmp-string (a)
9747 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9748 (concat
9749 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9750 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9751 (if (match-end 5) (concat "@@" (match-string 5 a))))))
9753 (defun org-table-formula-less-p (a b)
9754 "Compare two formulas for sorting."
9755 (let ((as (org-table-formula-make-cmp-string (car a)))
9756 (bs (org-table-formula-make-cmp-string (car b))))
9757 (and as bs (string< as bs))))
9759 (defun org-table-get-stored-formulas (&optional noerror)
9760 "Return an alist with the stored formulas directly after current table."
9761 (interactive)
9762 (let (scol eq eq-alist strings string seen)
9763 (save-excursion
9764 (goto-char (org-table-end))
9765 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9766 (setq strings (org-split-string (match-string 2) " *:: *"))
9767 (while (setq string (pop strings))
9768 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
9769 (setq scol (if (match-end 2)
9770 (match-string 2 string)
9771 (match-string 1 string))
9772 eq (match-string 3 string)
9773 eq-alist (cons (cons scol eq) eq-alist))
9774 (if (member scol seen)
9775 (if noerror
9776 (progn
9777 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9778 (ding)
9779 (sit-for 2))
9780 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
9781 (push scol seen))))))
9782 (nreverse eq-alist)))
9784 (defun org-table-fix-formulas (key replace &optional limit delta remove)
9785 "Modify the equations after the table structure has been edited.
9786 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
9787 For all numbers larger than LIMIT, shift them by DELTA."
9788 (save-excursion
9789 (goto-char (org-table-end))
9790 (when (looking-at "#\\+TBLFM:")
9791 (let ((re (concat key "\\([0-9]+\\)"))
9792 (re2
9793 (when remove
9794 (if (equal key "$")
9795 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
9796 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
9797 s n a)
9798 (when remove
9799 (while (re-search-forward re2 (point-at-eol) t)
9800 (replace-match "")))
9801 (while (re-search-forward re (point-at-eol) t)
9802 (setq s (match-string 1) n (string-to-number s))
9803 (cond
9804 ((setq a (assoc s replace))
9805 (replace-match (concat key (cdr a)) t t))
9806 ((and limit (> n limit))
9807 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
9809 (defun org-table-get-specials ()
9810 "Get the column names and local parameters for this table."
9811 (save-excursion
9812 (let ((beg (org-table-begin)) (end (org-table-end))
9813 names name fields fields1 field cnt
9814 c v l line col types dlines hlines)
9815 (setq org-table-column-names nil
9816 org-table-local-parameters nil
9817 org-table-named-field-locations nil
9818 org-table-current-begin-line nil
9819 org-table-current-begin-pos nil
9820 org-table-current-line-types nil)
9821 (goto-char beg)
9822 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9823 (setq names (org-split-string (match-string 1) " *| *")
9824 cnt 1)
9825 (while (setq name (pop names))
9826 (setq cnt (1+ cnt))
9827 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9828 (push (cons name (int-to-string cnt)) org-table-column-names))))
9829 (setq org-table-column-names (nreverse org-table-column-names))
9830 (setq org-table-column-name-regexp
9831 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9832 (goto-char beg)
9833 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9834 (setq fields (org-split-string (match-string 1) " *| *"))
9835 (while (setq field (pop fields))
9836 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9837 (push (cons (match-string 1 field) (match-string 2 field))
9838 org-table-local-parameters))))
9839 (goto-char beg)
9840 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9841 (setq c (match-string 1)
9842 fields (org-split-string (match-string 2) " *| *"))
9843 (save-excursion
9844 (beginning-of-line (if (equal c "_") 2 0))
9845 (setq line (org-current-line) col 1)
9846 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9847 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9848 (while (and fields1 (setq field (pop fields)))
9849 (setq v (pop fields1) col (1+ col))
9850 (when (and (stringp field) (stringp v)
9851 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9852 (push (cons field v) org-table-local-parameters)
9853 (push (list field line col) org-table-named-field-locations))))
9854 ;; Analyse the line types
9855 (goto-char beg)
9856 (setq org-table-current-begin-line (org-current-line)
9857 org-table-current-begin-pos (point)
9858 l org-table-current-begin-line)
9859 (while (looking-at "[ \t]*|\\(-\\)?")
9860 (push (if (match-end 1) 'hline 'dline) types)
9861 (if (match-end 1) (push l hlines) (push l dlines))
9862 (beginning-of-line 2)
9863 (setq l (1+ l)))
9864 (setq org-table-current-line-types (apply 'vector (nreverse types))
9865 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
9866 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
9868 (defun org-table-maybe-eval-formula ()
9869 "Check if the current field starts with \"=\" or \":=\".
9870 If yes, store the formula and apply it."
9871 ;; We already know we are in a table. Get field will only return a formula
9872 ;; when appropriate. It might return a separator line, but no problem.
9873 (when org-table-formula-evaluate-inline
9874 (let* ((field (org-trim (or (org-table-get-field) "")))
9875 named eq)
9876 (when (string-match "^:?=\\(.*\\)" field)
9877 (setq named (equal (string-to-char field) ?:)
9878 eq (match-string 1 field))
9879 (if (or (fboundp 'calc-eval)
9880 (equal (substring eq 0 (min 2 (length eq))) "'("))
9881 (org-table-eval-formula (if named '(4) nil)
9882 (org-table-formula-from-user eq))
9883 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
9885 (defvar org-recalc-commands nil
9886 "List of commands triggering the recalculation of a line.
9887 Will be filled automatically during use.")
9889 (defvar org-recalc-marks
9890 '((" " . "Unmarked: no special line, no automatic recalculation")
9891 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9892 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9893 ("!" . "Column name definition line. Reference in formula as $name.")
9894 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9895 ("_" . "Names for values in row below this one.")
9896 ("^" . "Names for values in row above this one.")))
9898 (defun org-table-rotate-recalc-marks (&optional newchar)
9899 "Rotate the recalculation mark in the first column.
9900 If in any row, the first field is not consistent with a mark,
9901 insert a new column for the markers.
9902 When there is an active region, change all the lines in the region,
9903 after prompting for the marking character.
9904 After each change, a message will be displayed indicating the meaning
9905 of the new mark."
9906 (interactive)
9907 (unless (org-at-table-p) (error "Not at a table"))
9908 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9909 (beg (org-table-begin))
9910 (end (org-table-end))
9911 (l (org-current-line))
9912 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9913 (l2 (if (org-region-active-p) (org-current-line (region-end))))
9914 (have-col
9915 (save-excursion
9916 (goto-char beg)
9917 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
9918 (col (org-table-current-column))
9919 (forcenew (car (assoc newchar org-recalc-marks)))
9920 epos new)
9921 (when l1
9922 (message "Change region to what mark? Type # * ! $ or SPC: ")
9923 (setq newchar (char-to-string (read-char-exclusive))
9924 forcenew (car (assoc newchar org-recalc-marks))))
9925 (if (and newchar (not forcenew))
9926 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
9927 newchar))
9928 (if l1 (goto-line l1))
9929 (save-excursion
9930 (beginning-of-line 1)
9931 (unless (looking-at org-table-dataline-regexp)
9932 (error "Not at a table data line")))
9933 (unless have-col
9934 (org-table-goto-column 1)
9935 (org-table-insert-column)
9936 (org-table-goto-column (1+ col)))
9937 (setq epos (point-at-eol))
9938 (save-excursion
9939 (beginning-of-line 1)
9940 (org-table-get-field
9941 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
9942 (concat " "
9943 (setq new (or forcenew
9944 (cadr (member (match-string 1) marks))))
9945 " ")
9946 " # ")))
9947 (if (and l1 l2)
9948 (progn
9949 (goto-line l1)
9950 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
9951 (and (looking-at org-table-dataline-regexp)
9952 (org-table-get-field 1 (concat " " new " "))))
9953 (goto-line l1)))
9954 (if (not (= epos (point-at-eol))) (org-table-align))
9955 (goto-line l)
9956 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
9958 (defun org-table-maybe-recalculate-line ()
9959 "Recompute the current line if marked for it, and if we haven't just done it."
9960 (interactive)
9961 (and org-table-allow-automatic-line-recalculation
9962 (not (and (memq last-command org-recalc-commands)
9963 (equal org-last-recalc-line (org-current-line))))
9964 (save-excursion (beginning-of-line 1)
9965 (looking-at org-table-auto-recalculate-regexp))
9966 (org-table-recalculate) t))
9968 (defvar org-table-formula-debug nil
9969 "Non-nil means, debug table formulas.
9970 When nil, simply write \"#ERROR\" in corrupted fields.")
9971 (make-variable-buffer-local 'org-table-formula-debug)
9973 (defvar modes)
9974 (defsubst org-set-calc-mode (var &optional value)
9975 (if (stringp var)
9976 (setq var (assoc var '(("D" calc-angle-mode deg)
9977 ("R" calc-angle-mode rad)
9978 ("F" calc-prefer-frac t)
9979 ("S" calc-symbolic-mode t)))
9980 value (nth 2 var) var (nth 1 var)))
9981 (if (memq var modes)
9982 (setcar (cdr (memq var modes)) value)
9983 (cons var (cons value modes)))
9984 modes)
9986 (defun org-table-eval-formula (&optional arg equation
9987 suppress-align suppress-const
9988 suppress-store suppress-analysis)
9989 "Replace the table field value at the cursor by the result of a calculation.
9991 This function makes use of Dave Gillespie's Calc package, in my view the
9992 most exciting program ever written for GNU Emacs. So you need to have Calc
9993 installed in order to use this function.
9995 In a table, this command replaces the value in the current field with the
9996 result of a formula. It also installs the formula as the \"current\" column
9997 formula, by storing it in a special line below the table. When called
9998 with a `C-u' prefix, the current field must ba a named field, and the
9999 formula is installed as valid in only this specific field.
10001 When called with two `C-u' prefixes, insert the active equation
10002 for the field back into the current field, so that it can be
10003 edited there. This is useful in order to use \\[org-table-show-reference]
10004 to check the referenced fields.
10006 When called, the command first prompts for a formula, which is read in
10007 the minibuffer. Previously entered formulas are available through the
10008 history list, and the last used formula is offered as a default.
10009 These stored formulas are adapted correctly when moving, inserting, or
10010 deleting columns with the corresponding commands.
10012 The formula can be any algebraic expression understood by the Calc package.
10013 For details, see the Org-mode manual.
10015 This function can also be called from Lisp programs and offers
10016 additional arguments: EQUATION can be the formula to apply. If this
10017 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10018 used to speed-up recursive calls by by-passing unnecessary aligns.
10019 SUPPRESS-CONST suppresses the interpretation of constants in the
10020 formula, assuming that this has been done already outside the function.
10021 SUPPRESS-STORE means the formula should not be stored, either because
10022 it is already stored, or because it is a modified equation that should
10023 not overwrite the stored one."
10024 (interactive "P")
10025 (org-table-check-inside-data-field)
10026 (or suppress-analysis (org-table-get-specials))
10027 (if (equal arg '(16))
10028 (let ((eq (org-table-current-field-formula)))
10029 (or eq (error "No equation active for current field"))
10030 (org-table-get-field nil eq)
10031 (org-table-align)
10032 (setq org-table-may-need-update t))
10033 (let* (fields
10034 (ndown (if (integerp arg) arg 1))
10035 (org-table-automatic-realign nil)
10036 (case-fold-search nil)
10037 (down (> ndown 1))
10038 (formula (if (and equation suppress-store)
10039 equation
10040 (org-table-get-formula equation (equal arg '(4)))))
10041 (n0 (org-table-current-column))
10042 (modes (copy-sequence org-calc-default-modes))
10043 (numbers nil) ; was a variable, now fixed default
10044 (keep-empty nil)
10045 n form form0 bw fmt x ev orig c lispp literal)
10046 ;; Parse the format string. Since we have a lot of modes, this is
10047 ;; a lot of work. However, I think calc still uses most of the time.
10048 (if (string-match ";" formula)
10049 (let ((tmp (org-split-string formula ";")))
10050 (setq formula (car tmp)
10051 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10052 (nth 1 tmp)))
10053 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
10054 (setq c (string-to-char (match-string 1 fmt))
10055 n (string-to-number (match-string 2 fmt)))
10056 (if (= c ?p)
10057 (setq modes (org-set-calc-mode 'calc-internal-prec n))
10058 (setq modes (org-set-calc-mode
10059 'calc-float-format
10060 (list (cdr (assoc c '((?n . float) (?f . fix)
10061 (?s . sci) (?e . eng))))
10062 n))))
10063 (setq fmt (replace-match "" t t fmt)))
10064 (if (string-match "[NT]" fmt)
10065 (setq numbers (equal (match-string 0 fmt) "N")
10066 fmt (replace-match "" t t fmt)))
10067 (if (string-match "L" fmt)
10068 (setq literal t
10069 fmt (replace-match "" t t fmt)))
10070 (if (string-match "E" fmt)
10071 (setq keep-empty t
10072 fmt (replace-match "" t t fmt)))
10073 (while (string-match "[DRFS]" fmt)
10074 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10075 (setq fmt (replace-match "" t t fmt)))
10076 (unless (string-match "\\S-" fmt)
10077 (setq fmt nil))))
10078 (if (and (not suppress-const) org-table-formula-use-constants)
10079 (setq formula (org-table-formula-substitute-names formula)))
10080 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10081 (while (> ndown 0)
10082 (setq fields (org-split-string
10083 (org-no-properties
10084 (buffer-substring (point-at-bol) (point-at-eol)))
10085 " *| *"))
10086 (if (eq numbers t)
10087 (setq fields (mapcar
10088 (lambda (x) (number-to-string (string-to-number x)))
10089 fields)))
10090 (setq ndown (1- ndown))
10091 (setq form (copy-sequence formula)
10092 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
10093 (if (and lispp literal) (setq lispp 'literal))
10094 ;; Check for old vertical references
10095 (setq form (org-rewrite-old-row-references form))
10096 ;; Insert complex ranges
10097 (while (string-match org-table-range-regexp form)
10098 (setq form
10099 (replace-match
10100 (save-match-data
10101 (org-table-make-reference
10102 (org-table-get-range (match-string 0 form) nil n0)
10103 keep-empty numbers lispp))
10104 t t form)))
10105 ;; Insert simple ranges
10106 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
10107 (setq form
10108 (replace-match
10109 (save-match-data
10110 (org-table-make-reference
10111 (org-sublist
10112 fields (string-to-number (match-string 1 form))
10113 (string-to-number (match-string 2 form)))
10114 keep-empty numbers lispp))
10115 t t form)))
10116 (setq form0 form)
10117 ;; Insert the references to fields in same row
10118 (while (string-match "\\$\\([0-9]+\\)" form)
10119 (setq n (string-to-number (match-string 1 form))
10120 x (nth (1- (if (= n 0) n0 n)) fields))
10121 (unless x (error "Invalid field specifier \"%s\""
10122 (match-string 0 form)))
10123 (setq form (replace-match
10124 (save-match-data
10125 (org-table-make-reference x nil numbers lispp))
10126 t t form)))
10128 (if lispp
10129 (setq ev (condition-case nil
10130 (eval (eval (read form)))
10131 (error "#ERROR"))
10132 ev (if (numberp ev) (number-to-string ev) ev))
10133 (or (fboundp 'calc-eval)
10134 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
10135 (setq ev (calc-eval (cons form modes)
10136 (if numbers 'num))))
10138 (when org-table-formula-debug
10139 (with-output-to-temp-buffer "*Substitution History*"
10140 (princ (format "Substitution history of formula
10141 Orig: %s
10142 $xyz-> %s
10143 @r$c-> %s
10144 $1-> %s\n" orig formula form0 form))
10145 (if (listp ev)
10146 (princ (format " %s^\nError: %s"
10147 (make-string (car ev) ?\-) (nth 1 ev)))
10148 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10149 ev (or fmt "NONE")
10150 (if fmt (format fmt (string-to-number ev)) ev)))))
10151 (setq bw (get-buffer-window "*Substitution History*"))
10152 (shrink-window-if-larger-than-buffer bw)
10153 (unless (and (interactive-p) (not ndown))
10154 (unless (let (inhibit-redisplay)
10155 (y-or-n-p "Debugging Formula. Continue to next? "))
10156 (org-table-align)
10157 (error "Abort"))
10158 (delete-window bw)
10159 (message "")))
10160 (if (listp ev) (setq fmt nil ev "#ERROR"))
10161 (org-table-justify-field-maybe
10162 (if fmt (format fmt (string-to-number ev)) ev))
10163 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10164 (call-interactively 'org-return)
10165 (setq ndown 0)))
10166 (and down (org-table-maybe-recalculate-line))
10167 (or suppress-align (and org-table-may-need-update
10168 (org-table-align))))))
10170 (defun org-table-put-field-property (prop value)
10171 (save-excursion
10172 (put-text-property (progn (skip-chars-backward "^|") (point))
10173 (progn (skip-chars-forward "^|") (point))
10174 prop value)))
10176 (defun org-table-get-range (desc &optional tbeg col highlight)
10177 "Get a calc vector from a column, accorting to descriptor DESC.
10178 Optional arguments TBEG and COL can give the beginning of the table and
10179 the current column, to avoid unnecessary parsing.
10180 HIGHLIGHT means, just highlight the range."
10181 (if (not (equal (string-to-char desc) ?@))
10182 (setq desc (concat "@" desc)))
10183 (save-excursion
10184 (or tbeg (setq tbeg (org-table-begin)))
10185 (or col (setq col (org-table-current-column)))
10186 (let ((thisline (org-current-line))
10187 beg end c1 c2 r1 r2 rangep tmp)
10188 (unless (string-match org-table-range-regexp desc)
10189 (error "Invalid table range specifier `%s'" desc))
10190 (setq rangep (match-end 3)
10191 r1 (and (match-end 1) (match-string 1 desc))
10192 r2 (and (match-end 4) (match-string 4 desc))
10193 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
10194 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
10196 (and c1 (setq c1 (+ (string-to-number c1)
10197 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
10198 (and c2 (setq c2 (+ (string-to-number c2)
10199 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
10200 (if (equal r1 "") (setq r1 nil))
10201 (if (equal r2 "") (setq r2 nil))
10202 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10203 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10204 ; (setq r2 (or r2 r1) c2 (or c2 c1))
10205 (if (not r1) (setq r1 thisline))
10206 (if (not r2) (setq r2 thisline))
10207 (if (not c1) (setq c1 col))
10208 (if (not c2) (setq c2 col))
10209 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10210 ;; just one field
10211 (progn
10212 (goto-line r1)
10213 (while (not (looking-at org-table-dataline-regexp))
10214 (beginning-of-line 2))
10215 (prog1 (org-trim (org-table-get-field c1))
10216 (if highlight (org-table-highlight-rectangle (point) (point)))))
10217 ;; A range, return a vector
10218 ;; First sort the numbers to get a regular ractangle
10219 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10220 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10221 (goto-line r1)
10222 (while (not (looking-at org-table-dataline-regexp))
10223 (beginning-of-line 2))
10224 (org-table-goto-column c1)
10225 (setq beg (point))
10226 (goto-line r2)
10227 (while (not (looking-at org-table-dataline-regexp))
10228 (beginning-of-line 0))
10229 (org-table-goto-column c2)
10230 (setq end (point))
10231 (if highlight
10232 (org-table-highlight-rectangle
10233 beg (progn (skip-chars-forward "^|\n") (point))))
10234 ;; return string representation of calc vector
10235 (mapcar 'org-trim
10236 (apply 'append (org-table-copy-region beg end)))))))
10238 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10239 "Analyze descriptor DESC and retrieve the corresponding line number.
10240 The cursor is currently in line CLINE, the table begins in line BLINE,
10241 and TABLE is a vector with line types."
10242 (if (string-match "^[0-9]+$" desc)
10243 (aref org-table-dlines (string-to-number desc))
10244 (setq cline (or cline (org-current-line))
10245 bline (or bline org-table-current-begin-line)
10246 table (or table org-table-current-line-types))
10247 (if (or
10248 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10249 ;; 1 2 3 4 5 6
10250 (and (not (match-end 3)) (not (match-end 6)))
10251 (and (match-end 3) (match-end 6) (not (match-end 5))))
10252 (error "invalid row descriptor `%s'" desc))
10253 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10254 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10255 (odir (and (match-end 5) (match-string 5 desc)))
10256 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10257 (i (- cline bline))
10258 (rel (and (match-end 6)
10259 (or (and (match-end 1) (not (match-end 3)))
10260 (match-end 5)))))
10261 (if (and hn (not hdir))
10262 (progn
10263 (setq i 0 hdir "+")
10264 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10265 (if (and (not hn) on (not odir))
10266 (error "should never happen");;(aref org-table-dlines on)
10267 (if (and hn (> hn 0))
10268 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10269 (if on
10270 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10271 (+ bline i)))))
10273 (defun org-find-row-type (table i type backwards relative n)
10274 (let ((l (length table)))
10275 (while (> n 0)
10276 (while (and (setq i (+ i (if backwards -1 1)))
10277 (>= i 0) (< i l)
10278 (not (eq (aref table i) type))
10279 (if (and relative (eq (aref table i) 'hline))
10280 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10281 t)))
10282 (setq n (1- n)))
10283 (if (or (< i 0) (>= i l))
10284 (error "Row descriptior leads outside table")
10285 i)))
10287 (defun org-rewrite-old-row-references (s)
10288 (if (string-match "&[-+0-9I]" s)
10289 (error "Formula contains old &row reference, please rewrite using @-syntax")
10292 (defun org-table-make-reference (elements keep-empty numbers lispp)
10293 "Convert list ELEMENTS to something appropriate to insert into formula.
10294 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10295 NUMBERS indicates that everything should be converted to numbers.
10296 LISPP means to return something appropriate for a Lisp list."
10297 (if (stringp elements) ; just a single val
10298 (if lispp
10299 (if (eq lispp 'literal)
10300 elements
10301 (prin1-to-string (if numbers (string-to-number elements) elements)))
10302 (if (equal elements "") (setq elements "0"))
10303 (if numbers (number-to-string (string-to-number elements)) elements))
10304 (unless keep-empty
10305 (setq elements
10306 (delq nil
10307 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10308 elements))))
10309 (setq elements (or elements '("0")))
10310 (if lispp
10311 (mapconcat
10312 (lambda (x)
10313 (if (eq lispp 'literal)
10315 (prin1-to-string (if numbers (string-to-number x) x))))
10316 elements " ")
10317 (concat "[" (mapconcat
10318 (lambda (x)
10319 (if numbers (number-to-string (string-to-number x)) x))
10320 elements
10321 ",") "]"))))
10323 (defun org-table-recalculate (&optional all noalign)
10324 "Recalculate the current table line by applying all stored formulas.
10325 With prefix arg ALL, do this for all lines in the table."
10326 (interactive "P")
10327 (or (memq this-command org-recalc-commands)
10328 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10329 (unless (org-at-table-p) (error "Not at a table"))
10330 (if (equal all '(16))
10331 (org-table-iterate)
10332 (org-table-get-specials)
10333 (let* ((eqlist (sort (org-table-get-stored-formulas)
10334 (lambda (a b) (string< (car a) (car b)))))
10335 (inhibit-redisplay (not debug-on-error))
10336 (line-re org-table-dataline-regexp)
10337 (thisline (org-current-line))
10338 (thiscol (org-table-current-column))
10339 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10340 ;; Insert constants in all formulas
10341 (setq eqlist
10342 (mapcar (lambda (x)
10343 (setcdr x (org-table-formula-substitute-names (cdr x)))
10345 eqlist))
10346 ;; Split the equation list
10347 (while (setq eq (pop eqlist))
10348 (if (<= (string-to-char (car eq)) ?9)
10349 (push eq eqlnum)
10350 (push eq eqlname)))
10351 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10352 (if all
10353 (progn
10354 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10355 (goto-char (setq beg (org-table-begin)))
10356 (if (re-search-forward org-table-calculate-mark-regexp end t)
10357 ;; This is a table with marked lines, compute selected lines
10358 (setq line-re org-table-recalculate-regexp)
10359 ;; Move forward to the first non-header line
10360 (if (and (re-search-forward org-table-dataline-regexp end t)
10361 (re-search-forward org-table-hline-regexp end t)
10362 (re-search-forward org-table-dataline-regexp end t))
10363 (setq beg (match-beginning 0))
10364 nil))) ;; just leave beg where it is
10365 (setq beg (point-at-bol)
10366 end (move-marker (make-marker) (1+ (point-at-eol)))))
10367 (goto-char beg)
10368 (and all (message "Re-applying formulas to full table..."))
10370 ;; First find the named fields, and mark them untouchanble
10371 (remove-text-properties beg end '(org-untouchable t))
10372 (while (setq eq (pop eqlname))
10373 (setq name (car eq)
10374 a (assoc name org-table-named-field-locations))
10375 (and (not a)
10376 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10377 (setq a (list name
10378 (aref org-table-dlines
10379 (string-to-number (match-string 1 name)))
10380 (string-to-number (match-string 2 name)))))
10381 (when (and a (or all (equal (nth 1 a) thisline)))
10382 (message "Re-applying formula to field: %s" name)
10383 (goto-line (nth 1 a))
10384 (org-table-goto-column (nth 2 a))
10385 (push (append a (list (cdr eq))) eqlname1)
10386 (org-table-put-field-property :org-untouchable t)))
10388 ;; Now evauluate the column formulas, but skip fields covered by
10389 ;; field formulas
10390 (goto-char beg)
10391 (while (re-search-forward line-re end t)
10392 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10393 ;; Unprotected line, recalculate
10394 (and all (message "Re-applying formulas to full table...(line %d)"
10395 (setq cnt (1+ cnt))))
10396 (setq org-last-recalc-line (org-current-line))
10397 (setq eql eqlnum)
10398 (while (setq entry (pop eql))
10399 (goto-line org-last-recalc-line)
10400 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10401 (unless (get-text-property (point) :org-untouchable)
10402 (org-table-eval-formula nil (cdr entry)
10403 'noalign 'nocst 'nostore 'noanalysis)))))
10405 ;; Now evaluate the field formulas
10406 (while (setq eq (pop eqlname1))
10407 (message "Re-applying formula to field: %s" (car eq))
10408 (goto-line (nth 1 eq))
10409 (org-table-goto-column (nth 2 eq))
10410 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10411 'nostore 'noanalysis))
10413 (goto-line thisline)
10414 (org-table-goto-column thiscol)
10415 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10416 (or noalign (and org-table-may-need-update (org-table-align))
10417 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10419 ;; back to initial position
10420 (message "Re-applying formulas...done")
10421 (goto-line thisline)
10422 (org-table-goto-column thiscol)
10423 (or noalign (and org-table-may-need-update (org-table-align))
10424 (and all (message "Re-applying formulas...done"))))))
10426 (defun org-table-iterate (&optional arg)
10427 "Recalculate the table until it does not change anymore."
10428 (interactive "P")
10429 (let ((imax (if arg (prefix-numeric-value arg) 10))
10430 (i 0)
10431 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10432 thistbl)
10433 (catch 'exit
10434 (while (< i imax)
10435 (setq i (1+ i))
10436 (org-table-recalculate 'all)
10437 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10438 (if (not (string= lasttbl thistbl))
10439 (setq lasttbl thistbl)
10440 (if (> i 1)
10441 (message "Convergence after %d iterations" i)
10442 (message "Table was already stable"))
10443 (throw 'exit t)))
10444 (error "No convergence after %d iterations" i))))
10446 (defun org-table-formula-substitute-names (f)
10447 "Replace $const with values in string F."
10448 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10449 ;; First, check for column names
10450 (while (setq start (string-match org-table-column-name-regexp f start))
10451 (setq start (1+ start))
10452 (setq a (assoc (match-string 1 f) org-table-column-names))
10453 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10454 ;; Parameters and constants
10455 (setq start 0)
10456 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10457 (setq start (1+ start))
10458 (if (setq a (save-match-data
10459 (org-table-get-constant (match-string 1 f))))
10460 (setq f (replace-match
10461 (concat (if pp "(") a (if pp ")")) t t f))))
10462 (if org-table-formula-debug
10463 (put-text-property 0 (length f) :orig-formula f1 f))
10466 (defun org-table-get-constant (const)
10467 "Find the value for a parameter or constant in a formula.
10468 Parameters get priority."
10469 (or (cdr (assoc const org-table-local-parameters))
10470 (cdr (assoc const org-table-formula-constants-local))
10471 (cdr (assoc const org-table-formula-constants))
10472 (and (fboundp 'constants-get) (constants-get const))
10473 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10474 (org-entry-get nil (substring const 5) 'inherit))
10475 "#UNDEFINED_NAME"))
10477 (defvar org-table-fedit-map
10478 (let ((map (make-sparse-keymap)))
10479 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10480 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10481 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10482 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10483 (org-defkey map "\C-c?" 'org-table-show-reference)
10484 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10485 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10486 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10487 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10488 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10489 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10490 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10491 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10492 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10493 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10494 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10495 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10496 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10497 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10498 map))
10500 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10501 '("Edit-Formulas"
10502 ["Finish and Install" org-table-fedit-finish t]
10503 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10504 ["Abort" org-table-fedit-abort t]
10505 "--"
10506 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10507 ["Complete Lisp Symbol" lisp-complete-symbol t]
10508 "--"
10509 "Shift Reference at Point"
10510 ["Up" org-table-fedit-ref-up t]
10511 ["Down" org-table-fedit-ref-down t]
10512 ["Left" org-table-fedit-ref-left t]
10513 ["Right" org-table-fedit-ref-right t]
10515 "Change Test Row for Column Formulas"
10516 ["Up" org-table-fedit-line-up t]
10517 ["Down" org-table-fedit-line-down t]
10518 "--"
10519 ["Scroll Table Window" org-table-fedit-scroll t]
10520 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10521 ["Show Table Grid" org-table-fedit-toggle-coordinates
10522 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10523 org-table-overlay-coordinates)]
10524 "--"
10525 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10526 :style toggle :selected org-table-buffer-is-an]))
10528 (defvar org-pos)
10530 (defun org-table-edit-formulas ()
10531 "Edit the formulas of the current table in a separate buffer."
10532 (interactive)
10533 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10534 (beginning-of-line 0))
10535 (unless (org-at-table-p) (error "Not at a table"))
10536 (org-table-get-specials)
10537 (let ((key (org-table-current-field-formula 'key 'noerror))
10538 (eql (sort (org-table-get-stored-formulas 'noerror)
10539 'org-table-formula-less-p))
10540 (pos (move-marker (make-marker) (point)))
10541 (startline 1)
10542 (wc (current-window-configuration))
10543 (titles '((column . "# Column Formulas\n")
10544 (field . "# Field Formulas\n")
10545 (named . "# Named Field Formulas\n")))
10546 entry s type title)
10547 (org-switch-to-buffer-other-window "*Edit Formulas*")
10548 (erase-buffer)
10549 ;; Keep global-font-lock-mode from turning on font-lock-mode
10550 (let ((font-lock-global-modes '(not fundamental-mode)))
10551 (fundamental-mode))
10552 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10553 (org-set-local 'org-pos pos)
10554 (org-set-local 'org-window-configuration wc)
10555 (use-local-map org-table-fedit-map)
10556 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10557 (easy-menu-add org-table-fedit-menu)
10558 (setq startline (org-current-line))
10559 (while (setq entry (pop eql))
10560 (setq type (cond
10561 ((equal (string-to-char (car entry)) ?@) 'field)
10562 ((string-match "^[0-9]" (car entry)) 'column)
10563 (t 'named)))
10564 (when (setq title (assq type titles))
10565 (or (bobp) (insert "\n"))
10566 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10567 (setq titles (delq title titles)))
10568 (if (equal key (car entry)) (setq startline (org-current-line)))
10569 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10570 (car entry) " = " (cdr entry) "\n"))
10571 (remove-text-properties 0 (length s) '(face nil) s)
10572 (insert s))
10573 (if (eq org-table-use-standard-references t)
10574 (org-table-fedit-toggle-ref-type))
10575 (goto-line startline)
10576 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10578 (defun org-table-fedit-post-command ()
10579 (when (not (memq this-command '(lisp-complete-symbol)))
10580 (let ((win (selected-window)))
10581 (save-excursion
10582 (condition-case nil
10583 (org-table-show-reference)
10584 (error nil))
10585 (select-window win)))))
10587 (defun org-table-formula-to-user (s)
10588 "Convert a formula from internal to user representation."
10589 (if (eq org-table-use-standard-references t)
10590 (org-table-convert-refs-to-an s)
10593 (defun org-table-formula-from-user (s)
10594 "Convert a formula from user to internal representation."
10595 (if org-table-use-standard-references
10596 (org-table-convert-refs-to-rc s)
10599 (defun org-table-convert-refs-to-rc (s)
10600 "Convert spreadsheet references from AB7 to @7$28.
10601 Works for single references, but also for entire formulas and even the
10602 full TBLFM line."
10603 (let ((start 0))
10604 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10605 (cond
10606 ((match-end 3)
10607 ;; format match, just advance
10608 (setq start (match-end 0)))
10609 ((and (> (match-beginning 0) 0)
10610 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10611 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10612 ;; 3.e5 or something like this.
10613 (setq start (match-end 0)))
10615 (setq start (match-beginning 0)
10616 s (replace-match
10617 (if (equal (match-string 2 s) "&")
10618 (format "$%d" (org-letters-to-number (match-string 1 s)))
10619 (format "@%d$%d"
10620 (string-to-number (match-string 2 s))
10621 (org-letters-to-number (match-string 1 s))))
10622 t t s)))))
10625 (defun org-table-convert-refs-to-an (s)
10626 "Convert spreadsheet references from to @7$28 to AB7.
10627 Works for single references, but also for entire formulas and even the
10628 full TBLFM line."
10629 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10630 (setq s (replace-match
10631 (format "%s%d"
10632 (org-number-to-letters
10633 (string-to-number (match-string 2 s)))
10634 (string-to-number (match-string 1 s)))
10635 t t s)))
10636 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10637 (setq s (replace-match (concat "\\1"
10638 (org-number-to-letters
10639 (string-to-number (match-string 2 s))) "&")
10640 t nil s)))
10643 (defun org-letters-to-number (s)
10644 "Convert a base 26 number represented by letters into an integer.
10645 For example: AB -> 28."
10646 (let ((n 0))
10647 (setq s (upcase s))
10648 (while (> (length s) 0)
10649 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10650 s (substring s 1)))
10653 (defun org-number-to-letters (n)
10654 "Convert an integer into a base 26 number represented by letters.
10655 For example: 28 -> AB."
10656 (let ((s ""))
10657 (while (> n 0)
10658 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10659 n (/ (1- n) 26)))
10662 (defun org-table-fedit-convert-buffer (function)
10663 "Convert all references in this buffer, using FUNTION."
10664 (let ((line (org-current-line)))
10665 (goto-char (point-min))
10666 (while (not (eobp))
10667 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10668 (delete-region (point) (point-at-eol))
10669 (or (eobp) (forward-char 1)))
10670 (goto-line line)))
10672 (defun org-table-fedit-toggle-ref-type ()
10673 "Convert all references in the buffer from B3 to @3$2 and back."
10674 (interactive)
10675 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10676 (org-table-fedit-convert-buffer
10677 (if org-table-buffer-is-an
10678 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10679 (message "Reference type switched to %s"
10680 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10682 (defun org-table-fedit-ref-up ()
10683 "Shift the reference at point one row/hline up."
10684 (interactive)
10685 (org-table-fedit-shift-reference 'up))
10686 (defun org-table-fedit-ref-down ()
10687 "Shift the reference at point one row/hline down."
10688 (interactive)
10689 (org-table-fedit-shift-reference 'down))
10690 (defun org-table-fedit-ref-left ()
10691 "Shift the reference at point one field to the left."
10692 (interactive)
10693 (org-table-fedit-shift-reference 'left))
10694 (defun org-table-fedit-ref-right ()
10695 "Shift the reference at point one field to the right."
10696 (interactive)
10697 (org-table-fedit-shift-reference 'right))
10699 (defun org-table-fedit-shift-reference (dir)
10700 (cond
10701 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10702 (if (memq dir '(left right))
10703 (org-rematch-and-replace 1 (eq dir 'left))
10704 (error "Cannot shift reference in this direction")))
10705 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10706 ;; A B3-like reference
10707 (if (memq dir '(up down))
10708 (org-rematch-and-replace 2 (eq dir 'up))
10709 (org-rematch-and-replace 1 (eq dir 'left))))
10710 ((org-at-regexp-p
10711 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10712 ;; An internal reference
10713 (if (memq dir '(up down))
10714 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10715 (org-rematch-and-replace 5 (eq dir 'left))))))
10717 (defun org-rematch-and-replace (n &optional decr hline)
10718 "Re-match the group N, and replace it with the shifted refrence."
10719 (or (match-end n) (error "Cannot shift reference in this direction"))
10720 (goto-char (match-beginning n))
10721 (and (looking-at (regexp-quote (match-string n)))
10722 (replace-match (org-shift-refpart (match-string 0) decr hline)
10723 t t)))
10725 (defun org-shift-refpart (ref &optional decr hline)
10726 "Shift a refrence part REF.
10727 If DECR is set, decrease the references row/column, else increase.
10728 If HLINE is set, this may be a hline reference, it certainly is not
10729 a translation reference."
10730 (save-match-data
10731 (let* ((sign (string-match "^[-+]" ref)) n)
10733 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10734 (cond
10735 ((and hline (string-match "^I+" ref))
10736 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10737 (setq n (+ n (if decr -1 1)))
10738 (if (= n 0) (setq n (+ n (if decr -1 1))))
10739 (if sign
10740 (setq sign (if (< n 0) "-" "+") n (abs n))
10741 (setq n (max 1 n)))
10742 (concat sign (make-string n ?I)))
10744 ((string-match "^[0-9]+" ref)
10745 (setq n (string-to-number (concat sign ref)))
10746 (setq n (+ n (if decr -1 1)))
10747 (if sign
10748 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10749 (number-to-string (max 1 n))))
10751 ((string-match "^[a-zA-Z]+" ref)
10752 (org-number-to-letters
10753 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10755 (t (error "Cannot shift reference"))))))
10757 (defun org-table-fedit-toggle-coordinates ()
10758 "Toggle the display of coordinates in the refrenced table."
10759 (interactive)
10760 (let ((pos (marker-position org-pos)))
10761 (with-current-buffer (marker-buffer org-pos)
10762 (save-excursion
10763 (goto-char pos)
10764 (org-table-toggle-coordinate-overlays)))))
10766 (defun org-table-fedit-finish (&optional arg)
10767 "Parse the buffer for formula definitions and install them.
10768 With prefix ARG, apply the new formulas to the table."
10769 (interactive "P")
10770 (org-table-remove-rectangle-highlight)
10771 (if org-table-use-standard-references
10772 (progn
10773 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
10774 (setq org-table-buffer-is-an nil)))
10775 (let ((pos org-pos) eql var form)
10776 (goto-char (point-min))
10777 (while (re-search-forward
10778 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
10779 nil t)
10780 (setq var (if (match-end 2) (match-string 2) (match-string 1))
10781 form (match-string 3))
10782 (setq form (org-trim form))
10783 (when (not (equal form ""))
10784 (while (string-match "[ \t]*\n[ \t]*" form)
10785 (setq form (replace-match " " t t form)))
10786 (when (assoc var eql)
10787 (error "Double formulas for %s" var))
10788 (push (cons var form) eql)))
10789 (setq org-pos nil)
10790 (set-window-configuration org-window-configuration)
10791 (select-window (get-buffer-window (marker-buffer pos)))
10792 (goto-char pos)
10793 (unless (org-at-table-p)
10794 (error "Lost table position - cannot install formulae"))
10795 (org-table-store-formulas eql)
10796 (move-marker pos nil)
10797 (kill-buffer "*Edit Formulas*")
10798 (if arg
10799 (org-table-recalculate 'all)
10800 (message "New formulas installed - press C-u C-c C-c to apply."))))
10802 (defun org-table-fedit-abort ()
10803 "Abort editing formulas, without installing the changes."
10804 (interactive)
10805 (org-table-remove-rectangle-highlight)
10806 (let ((pos org-pos))
10807 (set-window-configuration org-window-configuration)
10808 (select-window (get-buffer-window (marker-buffer pos)))
10809 (goto-char pos)
10810 (move-marker pos nil)
10811 (message "Formula editing aborted without installing changes")))
10813 (defun org-table-fedit-lisp-indent ()
10814 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
10815 (interactive)
10816 (let ((pos (point)) beg end ind)
10817 (beginning-of-line 1)
10818 (cond
10819 ((looking-at "[ \t]")
10820 (goto-char pos)
10821 (call-interactively 'lisp-indent-line))
10822 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
10823 ((not (fboundp 'pp-buffer))
10824 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
10825 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
10826 (goto-char (- (match-end 0) 2))
10827 (setq beg (point))
10828 (setq ind (make-string (current-column) ?\ ))
10829 (condition-case nil (forward-sexp 1)
10830 (error
10831 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
10832 (setq end (point))
10833 (save-restriction
10834 (narrow-to-region beg end)
10835 (if (eq last-command this-command)
10836 (progn
10837 (goto-char (point-min))
10838 (setq this-command nil)
10839 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
10840 (replace-match " ")))
10841 (pp-buffer)
10842 (untabify (point-min) (point-max))
10843 (goto-char (1+ (point-min)))
10844 (while (re-search-forward "^." nil t)
10845 (beginning-of-line 1)
10846 (insert ind))
10847 (goto-char (point-max))
10848 (backward-delete-char 1)))
10849 (goto-char beg))
10850 (t nil))))
10852 (defvar org-show-positions nil)
10854 (defun org-table-show-reference (&optional local)
10855 "Show the location/value of the $ expression at point."
10856 (interactive)
10857 (org-table-remove-rectangle-highlight)
10858 (catch 'exit
10859 (let ((pos (if local (point) org-pos))
10860 (face2 'highlight)
10861 (org-inhibit-highlight-removal t)
10862 (win (selected-window))
10863 (org-show-positions nil)
10864 var name e what match dest)
10865 (if local (org-table-get-specials))
10866 (setq what (cond
10867 ((or (org-at-regexp-p org-table-range-regexp2)
10868 (org-at-regexp-p org-table-translate-regexp)
10869 (org-at-regexp-p org-table-range-regexp))
10870 (setq match
10871 (save-match-data
10872 (org-table-convert-refs-to-rc (match-string 0))))
10873 'range)
10874 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
10875 ((org-at-regexp-p "\\$[0-9]+") 'column)
10876 ((not local) nil)
10877 (t (error "No reference at point")))
10878 match (and what (or match (match-string 0))))
10879 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
10880 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
10881 'secondary-selection))
10882 (org-add-hook 'before-change-functions
10883 'org-table-remove-rectangle-highlight)
10884 (if (eq what 'name) (setq var (substring match 1)))
10885 (when (eq what 'range)
10886 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
10887 (setq match (org-table-formula-substitute-names match)))
10888 (unless local
10889 (save-excursion
10890 (end-of-line 1)
10891 (re-search-backward "^\\S-" nil t)
10892 (beginning-of-line 1)
10893 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
10894 (setq dest
10895 (save-match-data
10896 (org-table-convert-refs-to-rc (match-string 1))))
10897 (org-table-add-rectangle-overlay
10898 (match-beginning 1) (match-end 1) face2))))
10899 (if (and (markerp pos) (marker-buffer pos))
10900 (if (get-buffer-window (marker-buffer pos))
10901 (select-window (get-buffer-window (marker-buffer pos)))
10902 (org-switch-to-buffer-other-window (get-buffer-window
10903 (marker-buffer pos)))))
10904 (goto-char pos)
10905 (org-table-force-dataline)
10906 (when dest
10907 (setq name (substring dest 1))
10908 (cond
10909 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
10910 (setq e (assoc name org-table-named-field-locations))
10911 (goto-line (nth 1 e))
10912 (org-table-goto-column (nth 2 e)))
10913 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
10914 (let ((l (string-to-number (match-string 1 dest)))
10915 (c (string-to-number (match-string 2 dest))))
10916 (goto-line (aref org-table-dlines l))
10917 (org-table-goto-column c)))
10918 (t (org-table-goto-column (string-to-number name))))
10919 (move-marker pos (point))
10920 (org-table-highlight-rectangle nil nil face2))
10921 (cond
10922 ((equal dest match))
10923 ((not match))
10924 ((eq what 'range)
10925 (condition-case nil
10926 (save-excursion
10927 (org-table-get-range match nil nil 'highlight))
10928 (error nil)))
10929 ((setq e (assoc var org-table-named-field-locations))
10930 (goto-line (nth 1 e))
10931 (org-table-goto-column (nth 2 e))
10932 (org-table-highlight-rectangle (point) (point))
10933 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
10934 ((setq e (assoc var org-table-column-names))
10935 (org-table-goto-column (string-to-number (cdr e)))
10936 (org-table-highlight-rectangle (point) (point))
10937 (goto-char (org-table-begin))
10938 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
10939 (org-table-end) t)
10940 (progn
10941 (goto-char (match-beginning 1))
10942 (org-table-highlight-rectangle)
10943 (message "Named column (column %s)" (cdr e)))
10944 (error "Column name not found")))
10945 ((eq what 'column)
10946 ;; column number
10947 (org-table-goto-column (string-to-number (substring match 1)))
10948 (org-table-highlight-rectangle (point) (point))
10949 (message "Column %s" (substring match 1)))
10950 ((setq e (assoc var org-table-local-parameters))
10951 (goto-char (org-table-begin))
10952 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
10953 (progn
10954 (goto-char (match-beginning 1))
10955 (org-table-highlight-rectangle)
10956 (message "Local parameter."))
10957 (error "Parameter not found")))
10959 (cond
10960 ((not var) (error "No reference at point"))
10961 ((setq e (assoc var org-table-formula-constants-local))
10962 (message "Local Constant: $%s=%s in #+CONSTANTS line."
10963 var (cdr e)))
10964 ((setq e (assoc var org-table-formula-constants))
10965 (message "Constant: $%s=%s in `org-table-formula-constants'."
10966 var (cdr e)))
10967 ((setq e (and (fboundp 'constants-get) (constants-get var)))
10968 (message "Constant: $%s=%s, from `constants.el'%s."
10969 var e (format " (%s units)" constants-unit-system)))
10970 (t (error "Undefined name $%s" var)))))
10971 (goto-char pos)
10972 (when (and org-show-positions
10973 (not (memq this-command '(org-table-fedit-scroll
10974 org-table-fedit-scroll-down))))
10975 (push pos org-show-positions)
10976 (push org-table-current-begin-pos org-show-positions)
10977 (let ((min (apply 'min org-show-positions))
10978 (max (apply 'max org-show-positions)))
10979 (goto-char min) (recenter 0)
10980 (goto-char max)
10981 (or (pos-visible-in-window-p max) (recenter -1))))
10982 (select-window win))))
10984 (defun org-table-force-dataline ()
10985 "Make sure the cursor is in a dataline in a table."
10986 (unless (save-excursion
10987 (beginning-of-line 1)
10988 (looking-at org-table-dataline-regexp))
10989 (let* ((re org-table-dataline-regexp)
10990 (p1 (save-excursion (re-search-forward re nil 'move)))
10991 (p2 (save-excursion (re-search-backward re nil 'move))))
10992 (cond ((and p1 p2)
10993 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
10994 p1 p2)))
10995 ((or p1 p2) (goto-char (or p1 p2)))
10996 (t (error "No table dataline around here"))))))
10998 (defun org-table-fedit-line-up ()
10999 "Move cursor one line up in the window showing the table."
11000 (interactive)
11001 (org-table-fedit-move 'previous-line))
11003 (defun org-table-fedit-line-down ()
11004 "Move cursor one line down in the window showing the table."
11005 (interactive)
11006 (org-table-fedit-move 'next-line))
11008 (defun org-table-fedit-move (command)
11009 "Move the cursor in the window shoinw the table.
11010 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
11011 (let ((org-table-allow-automatic-line-recalculation nil)
11012 (pos org-pos) (win (selected-window)) p)
11013 (select-window (get-buffer-window (marker-buffer org-pos)))
11014 (setq p (point))
11015 (call-interactively command)
11016 (while (and (org-at-table-p)
11017 (org-at-table-hline-p))
11018 (call-interactively command))
11019 (or (org-at-table-p) (goto-char p))
11020 (move-marker pos (point))
11021 (select-window win)))
11023 (defun org-table-fedit-scroll (N)
11024 (interactive "p")
11025 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
11026 (scroll-other-window N)))
11028 (defun org-table-fedit-scroll-down (N)
11029 (interactive "p")
11030 (org-table-fedit-scroll (- N)))
11032 (defvar org-table-rectangle-overlays nil)
11034 (defun org-table-add-rectangle-overlay (beg end &optional face)
11035 "Add a new overlay."
11036 (let ((ov (org-make-overlay beg end)))
11037 (org-overlay-put ov 'face (or face 'secondary-selection))
11038 (push ov org-table-rectangle-overlays)))
11040 (defun org-table-highlight-rectangle (&optional beg end face)
11041 "Highlight rectangular region in a table."
11042 (setq beg (or beg (point)) end (or end (point)))
11043 (let ((b (min beg end))
11044 (e (max beg end))
11045 l1 c1 l2 c2 tmp)
11046 (and (boundp 'org-show-positions)
11047 (setq org-show-positions (cons b (cons e org-show-positions))))
11048 (goto-char (min beg end))
11049 (setq l1 (org-current-line)
11050 c1 (org-table-current-column))
11051 (goto-char (max beg end))
11052 (setq l2 (org-current-line)
11053 c2 (org-table-current-column))
11054 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
11055 (goto-line l1)
11056 (beginning-of-line 1)
11057 (loop for line from l1 to l2 do
11058 (when (looking-at org-table-dataline-regexp)
11059 (org-table-goto-column c1)
11060 (skip-chars-backward "^|\n") (setq beg (point))
11061 (org-table-goto-column c2)
11062 (skip-chars-forward "^|\n") (setq end (point))
11063 (org-table-add-rectangle-overlay beg end face))
11064 (beginning-of-line 2))
11065 (goto-char b))
11066 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
11068 (defun org-table-remove-rectangle-highlight (&rest ignore)
11069 "Remove the rectangle overlays."
11070 (unless org-inhibit-highlight-removal
11071 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
11072 (mapc 'org-delete-overlay org-table-rectangle-overlays)
11073 (setq org-table-rectangle-overlays nil)))
11075 (defvar org-table-coordinate-overlays nil
11076 "Collects the cooordinate grid overlays, so that they can be removed.")
11077 (make-variable-buffer-local 'org-table-coordinate-overlays)
11079 (defun org-table-overlay-coordinates ()
11080 "Add overlays to the table at point, to show row/column coordinates."
11081 (interactive)
11082 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11083 (setq org-table-coordinate-overlays nil)
11084 (save-excursion
11085 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
11086 (goto-char (org-table-begin))
11087 (while (org-at-table-p)
11088 (setq eol (point-at-eol))
11089 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
11090 (push ov org-table-coordinate-overlays)
11091 (setq hline (looking-at org-table-hline-regexp))
11092 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
11093 (format "%4d" (setq id (1+ id)))))
11094 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
11095 (when hline
11096 (setq ic 0)
11097 (while (re-search-forward "[+|]\\(-+\\)" eol t)
11098 (setq beg (1+ (match-beginning 0))
11099 ic (1+ ic)
11100 s1 (concat "$" (int-to-string ic))
11101 s2 (org-number-to-letters ic)
11102 str (if (eq org-table-use-standard-references t) s2 s1))
11103 (setq ov (org-make-overlay beg (+ beg (length str))))
11104 (push ov org-table-coordinate-overlays)
11105 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
11106 (beginning-of-line 2)))))
11108 (defun org-table-toggle-coordinate-overlays ()
11109 "Toggle the display of Row/Column numbers in tables."
11110 (interactive)
11111 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
11112 (message "Row/Column number display turned %s"
11113 (if org-table-overlay-coordinates "on" "off"))
11114 (if (and (org-at-table-p) org-table-overlay-coordinates)
11115 (org-table-align))
11116 (unless org-table-overlay-coordinates
11117 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11118 (setq org-table-coordinate-overlays nil)))
11120 (defun org-table-toggle-formula-debugger ()
11121 "Toggle the formula debugger in tables."
11122 (interactive)
11123 (setq org-table-formula-debug (not org-table-formula-debug))
11124 (message "Formula debugging has been turned %s"
11125 (if org-table-formula-debug "on" "off")))
11127 ;;; The orgtbl minor mode
11129 ;; Define a minor mode which can be used in other modes in order to
11130 ;; integrate the org-mode table editor.
11132 ;; This is really a hack, because the org-mode table editor uses several
11133 ;; keys which normally belong to the major mode, for example the TAB and
11134 ;; RET keys. Here is how it works: The minor mode defines all the keys
11135 ;; necessary to operate the table editor, but wraps the commands into a
11136 ;; function which tests if the cursor is currently inside a table. If that
11137 ;; is the case, the table editor command is executed. However, when any of
11138 ;; those keys is used outside a table, the function uses `key-binding' to
11139 ;; look up if the key has an associated command in another currently active
11140 ;; keymap (minor modes, major mode, global), and executes that command.
11141 ;; There might be problems if any of the keys used by the table editor is
11142 ;; otherwise used as a prefix key.
11144 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11145 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11146 ;; addresses this by checking explicitly for both bindings.
11148 ;; The optimized version (see variable `orgtbl-optimized') takes over
11149 ;; all keys which are bound to `self-insert-command' in the *global map*.
11150 ;; Some modes bind other commands to simple characters, for example
11151 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11152 ;; active, this binding is ignored inside tables and replaced with a
11153 ;; modified self-insert.
11155 (defvar orgtbl-mode nil
11156 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11157 table editor in arbitrary modes.")
11158 (make-variable-buffer-local 'orgtbl-mode)
11160 (defvar orgtbl-mode-map (make-keymap)
11161 "Keymap for `orgtbl-mode'.")
11163 ;;;###autoload
11164 (defun turn-on-orgtbl ()
11165 "Unconditionally turn on `orgtbl-mode'."
11166 (orgtbl-mode 1))
11168 (defvar org-old-auto-fill-inhibit-regexp nil
11169 "Local variable used by `orgtbl-mode'")
11171 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
11172 "Matches a line belonging to an orgtbl.")
11174 (defconst orgtbl-extra-font-lock-keywords
11175 (list (list (concat "^" orgtbl-line-start-regexp ".*")
11176 0 (quote 'org-table) 'prepend))
11177 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
11179 ;;;###autoload
11180 (defun orgtbl-mode (&optional arg)
11181 "The `org-mode' table editor as a minor mode for use in other modes."
11182 (interactive)
11183 (if (org-mode-p)
11184 ;; Exit without error, in case some hook functions calls this
11185 ;; by accident in org-mode.
11186 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11187 (setq orgtbl-mode
11188 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11189 (if orgtbl-mode
11190 (progn
11191 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11192 ;; Make sure we are first in minor-mode-map-alist
11193 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11194 (and c (setq minor-mode-map-alist
11195 (cons c (delq c minor-mode-map-alist)))))
11196 (org-set-local (quote org-table-may-need-update) t)
11197 (org-add-hook 'before-change-functions 'org-before-change-function
11198 nil 'local)
11199 (org-set-local 'org-old-auto-fill-inhibit-regexp
11200 auto-fill-inhibit-regexp)
11201 (org-set-local 'auto-fill-inhibit-regexp
11202 (if auto-fill-inhibit-regexp
11203 (concat orgtbl-line-start-regexp "\\|"
11204 auto-fill-inhibit-regexp)
11205 orgtbl-line-start-regexp))
11206 (org-add-to-invisibility-spec '(org-cwidth))
11207 (when (fboundp 'font-lock-add-keywords)
11208 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11209 (org-restart-font-lock))
11210 (easy-menu-add orgtbl-mode-menu)
11211 (run-hooks 'orgtbl-mode-hook))
11212 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11213 (org-cleanup-narrow-column-properties)
11214 (org-remove-from-invisibility-spec '(org-cwidth))
11215 (remove-hook 'before-change-functions 'org-before-change-function t)
11216 (when (fboundp 'font-lock-remove-keywords)
11217 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11218 (org-restart-font-lock))
11219 (easy-menu-remove orgtbl-mode-menu)
11220 (force-mode-line-update 'all))))
11222 (defun org-cleanup-narrow-column-properties ()
11223 "Remove all properties related to narrow-column invisibility."
11224 (let ((s 1))
11225 (while (setq s (text-property-any s (point-max)
11226 'display org-narrow-column-arrow))
11227 (remove-text-properties s (1+ s) '(display t)))
11228 (setq s 1)
11229 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11230 (remove-text-properties s (1+ s) '(org-cwidth t)))
11231 (setq s 1)
11232 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11233 (remove-text-properties s (1+ s) '(invisible t)))))
11235 ;; Install it as a minor mode.
11236 (put 'orgtbl-mode :included t)
11237 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11238 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11240 (defun orgtbl-make-binding (fun n &rest keys)
11241 "Create a function for binding in the table minor mode.
11242 FUN is the command to call inside a table. N is used to create a unique
11243 command name. KEYS are keys that should be checked in for a command
11244 to execute outside of tables."
11245 (eval
11246 (list 'defun
11247 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11248 '(arg)
11249 (concat "In tables, run `" (symbol-name fun) "'.\n"
11250 "Outside of tables, run the binding of `"
11251 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11252 "'.")
11253 '(interactive "p")
11254 (list 'if
11255 '(org-at-table-p)
11256 (list 'call-interactively (list 'quote fun))
11257 (list 'let '(orgtbl-mode)
11258 (list 'call-interactively
11259 (append '(or)
11260 (mapcar (lambda (k)
11261 (list 'key-binding k))
11262 keys)
11263 '('orgtbl-error))))))))
11265 (defun orgtbl-error ()
11266 "Error when there is no default binding for a table key."
11267 (interactive)
11268 (error "This key has no function outside tables"))
11270 (defun orgtbl-setup ()
11271 "Setup orgtbl keymaps."
11272 (let ((nfunc 0)
11273 (bindings
11274 (list
11275 '([(meta shift left)] org-table-delete-column)
11276 '([(meta left)] org-table-move-column-left)
11277 '([(meta right)] org-table-move-column-right)
11278 '([(meta shift right)] org-table-insert-column)
11279 '([(meta shift up)] org-table-kill-row)
11280 '([(meta shift down)] org-table-insert-row)
11281 '([(meta up)] org-table-move-row-up)
11282 '([(meta down)] org-table-move-row-down)
11283 '("\C-c\C-w" org-table-cut-region)
11284 '("\C-c\M-w" org-table-copy-region)
11285 '("\C-c\C-y" org-table-paste-rectangle)
11286 '("\C-c-" org-table-insert-hline)
11287 '("\C-c}" org-table-toggle-coordinate-overlays)
11288 '("\C-c{" org-table-toggle-formula-debugger)
11289 '("\C-m" org-table-next-row)
11290 '([(shift return)] org-table-copy-down)
11291 '("\C-c\C-q" org-table-wrap-region)
11292 '("\C-c?" org-table-field-info)
11293 '("\C-c " org-table-blank-field)
11294 '("\C-c+" org-table-sum)
11295 '("\C-c=" org-table-eval-formula)
11296 '("\C-c'" org-table-edit-formulas)
11297 '("\C-c`" org-table-edit-field)
11298 '("\C-c*" org-table-recalculate)
11299 '("\C-c|" org-table-create-or-convert-from-region)
11300 '("\C-c^" org-table-sort-lines)
11301 '([(control ?#)] org-table-rotate-recalc-marks)))
11302 elt key fun cmd)
11303 (while (setq elt (pop bindings))
11304 (setq nfunc (1+ nfunc))
11305 (setq key (org-key (car elt))
11306 fun (nth 1 elt)
11307 cmd (orgtbl-make-binding fun nfunc key))
11308 (org-defkey orgtbl-mode-map key cmd))
11310 ;; Special treatment needed for TAB and RET
11311 (org-defkey orgtbl-mode-map [(return)]
11312 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11313 (org-defkey orgtbl-mode-map "\C-m"
11314 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11316 (org-defkey orgtbl-mode-map [(tab)]
11317 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11318 (org-defkey orgtbl-mode-map "\C-i"
11319 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11321 (org-defkey orgtbl-mode-map [(shift tab)]
11322 (orgtbl-make-binding 'org-table-previous-field 104
11323 [(shift tab)] [(tab)] "\C-i"))
11325 (org-defkey orgtbl-mode-map "\M-\C-m"
11326 (orgtbl-make-binding 'org-table-wrap-region 105
11327 "\M-\C-m" [(meta return)]))
11328 (org-defkey orgtbl-mode-map [(meta return)]
11329 (orgtbl-make-binding 'org-table-wrap-region 106
11330 [(meta return)] "\M-\C-m"))
11332 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11333 (when orgtbl-optimized
11334 ;; If the user wants maximum table support, we need to hijack
11335 ;; some standard editing functions
11336 (org-remap orgtbl-mode-map
11337 'self-insert-command 'orgtbl-self-insert-command
11338 'delete-char 'org-delete-char
11339 'delete-backward-char 'org-delete-backward-char)
11340 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11341 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11342 '("OrgTbl"
11343 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11344 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11345 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11346 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11347 "--"
11348 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11349 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11350 ["Copy Field from Above"
11351 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11352 "--"
11353 ("Column"
11354 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11355 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11356 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11357 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11358 ("Row"
11359 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11360 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11361 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11362 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11363 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
11364 "--"
11365 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11366 ("Rectangle"
11367 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11368 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11369 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11370 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11371 "--"
11372 ("Radio tables"
11373 ["Insert table template" orgtbl-insert-radio-table
11374 (assq major-mode orgtbl-radio-table-templates)]
11375 ["Comment/uncomment table" orgtbl-toggle-comment t])
11376 "--"
11377 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11378 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11379 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11380 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11381 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11382 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11383 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11384 ["Sum Column/Rectangle" org-table-sum
11385 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11386 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11387 ["Debug Formulas"
11388 org-table-toggle-formula-debugger :active (org-at-table-p)
11389 :keys "C-c {"
11390 :style toggle :selected org-table-formula-debug]
11391 ["Show Col/Row Numbers"
11392 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11393 :keys "C-c }"
11394 :style toggle :selected org-table-overlay-coordinates]
11398 (defun orgtbl-ctrl-c-ctrl-c (arg)
11399 "If the cursor is inside a table, realign the table.
11400 It it is a table to be sent away to a receiver, do it.
11401 With prefix arg, also recompute table."
11402 (interactive "P")
11403 (let ((pos (point)) action)
11404 (save-excursion
11405 (beginning-of-line 1)
11406 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11407 ((looking-at "[ \t]*|") pos)
11408 ((looking-at "#\\+TBLFM:") 'recalc))))
11409 (cond
11410 ((integerp action)
11411 (goto-char action)
11412 (org-table-maybe-eval-formula)
11413 (if arg
11414 (call-interactively 'org-table-recalculate)
11415 (org-table-maybe-recalculate-line))
11416 (call-interactively 'org-table-align)
11417 (orgtbl-send-table 'maybe))
11418 ((eq action 'recalc)
11419 (save-excursion
11420 (beginning-of-line 1)
11421 (skip-chars-backward " \r\n\t")
11422 (if (org-at-table-p)
11423 (org-call-with-arg 'org-table-recalculate t))))
11424 (t (let (orgtbl-mode)
11425 (call-interactively (key-binding "\C-c\C-c")))))))
11427 (defun orgtbl-tab (arg)
11428 "Justification and field motion for `orgtbl-mode'."
11429 (interactive "P")
11430 (if arg (org-table-edit-field t)
11431 (org-table-justify-field-maybe)
11432 (org-table-next-field)))
11434 (defun orgtbl-ret ()
11435 "Justification and field motion for `orgtbl-mode'."
11436 (interactive)
11437 (org-table-justify-field-maybe)
11438 (org-table-next-row))
11440 (defun orgtbl-self-insert-command (N)
11441 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11442 If the cursor is in a table looking at whitespace, the whitespace is
11443 overwritten, and the table is not marked as requiring realignment."
11444 (interactive "p")
11445 (if (and (org-at-table-p)
11447 (and org-table-auto-blank-field
11448 (member last-command
11449 '(orgtbl-hijacker-command-100
11450 orgtbl-hijacker-command-101
11451 orgtbl-hijacker-command-102
11452 orgtbl-hijacker-command-103
11453 orgtbl-hijacker-command-104
11454 orgtbl-hijacker-command-105))
11455 (org-table-blank-field))
11457 (eq N 1)
11458 (looking-at "[^|\n]* +|"))
11459 (let (org-table-may-need-update)
11460 (goto-char (1- (match-end 0)))
11461 (delete-backward-char 1)
11462 (goto-char (match-beginning 0))
11463 (self-insert-command N))
11464 (setq org-table-may-need-update t)
11465 (let (orgtbl-mode)
11466 (call-interactively (key-binding (vector last-input-event))))))
11468 (defun org-force-self-insert (N)
11469 "Needed to enforce self-insert under remapping."
11470 (interactive "p")
11471 (self-insert-command N))
11473 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11474 "Regula expression matching exponentials as produced by calc.")
11476 (defvar org-table-clean-did-remove-column nil)
11478 (defun orgtbl-export (table target)
11479 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11480 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11481 org-table-last-alignment org-table-last-column-widths
11482 maxcol column)
11483 (if (not (fboundp func))
11484 (error "Cannot export orgtbl table to %s" target))
11485 (setq lines (org-table-clean-before-export lines))
11486 (setq table
11487 (mapcar
11488 (lambda (x)
11489 (if (string-match org-table-hline-regexp x)
11490 'hline
11491 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11492 lines))
11493 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11494 table)))
11495 (loop for i from (1- maxcol) downto 0 do
11496 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11497 (setq column (delq nil column))
11498 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11499 (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))
11500 (funcall func table nil)))
11502 (defun orgtbl-send-table (&optional maybe)
11503 "Send a tranformed version of this table to the receiver position.
11504 With argument MAYBE, fail quietly if no transformation is defined for
11505 this table."
11506 (interactive)
11507 (catch 'exit
11508 (unless (org-at-table-p) (error "Not at a table"))
11509 ;; when non-interactive, we assume align has just happened.
11510 (when (interactive-p) (org-table-align))
11511 (save-excursion
11512 (goto-char (org-table-begin))
11513 (beginning-of-line 0)
11514 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11515 (if maybe
11516 (throw 'exit nil)
11517 (error "Don't know how to transform this table."))))
11518 (let* ((name (match-string 1))
11520 (transform (intern (match-string 2)))
11521 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11522 (skip (plist-get params :skip))
11523 (skipcols (plist-get params :skipcols))
11524 (txt (buffer-substring-no-properties
11525 (org-table-begin) (org-table-end)))
11526 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11527 (lines (org-table-clean-before-export lines))
11528 (i0 (if org-table-clean-did-remove-column 2 1))
11529 (table (mapcar
11530 (lambda (x)
11531 (if (string-match org-table-hline-regexp x)
11532 'hline
11533 (org-remove-by-index
11534 (org-split-string (org-trim x) "\\s-*|\\s-*")
11535 skipcols i0)))
11536 lines))
11537 (fun (if (= i0 2) 'cdr 'identity))
11538 (org-table-last-alignment
11539 (org-remove-by-index (funcall fun org-table-last-alignment)
11540 skipcols i0))
11541 (org-table-last-column-widths
11542 (org-remove-by-index (funcall fun org-table-last-column-widths)
11543 skipcols i0)))
11545 (unless (fboundp transform)
11546 (error "No such transformation function %s" transform))
11547 (setq txt (funcall transform table params))
11548 ;; Find the insertion place
11549 (save-excursion
11550 (goto-char (point-min))
11551 (unless (re-search-forward
11552 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11553 (error "Don't know where to insert translated table"))
11554 (goto-char (match-beginning 0))
11555 (beginning-of-line 2)
11556 (setq beg (point))
11557 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11558 (error "Cannot find end of insertion region"))
11559 (beginning-of-line 1)
11560 (delete-region beg (point))
11561 (goto-char beg)
11562 (insert txt "\n"))
11563 (message "Table converted and installed at receiver location"))))
11565 (defun org-remove-by-index (list indices &optional i0)
11566 "Remove the elements in LIST with indices in INDICES.
11567 First element has index 0, or I0 if given."
11568 (if (not indices)
11569 list
11570 (if (integerp indices) (setq indices (list indices)))
11571 (setq i0 (1- (or i0 0)))
11572 (delq :rm (mapcar (lambda (x)
11573 (setq i0 (1+ i0))
11574 (if (memq i0 indices) :rm x))
11575 list))))
11577 (defun orgtbl-toggle-comment ()
11578 "Comment or uncomment the orgtbl at point."
11579 (interactive)
11580 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11581 (re2 (concat "^" orgtbl-line-start-regexp))
11582 (commented (save-excursion (beginning-of-line 1)
11583 (cond ((looking-at re1) t)
11584 ((looking-at re2) nil)
11585 (t (error "Not at an org table")))))
11586 (re (if commented re1 re2))
11587 beg end)
11588 (save-excursion
11589 (beginning-of-line 1)
11590 (while (looking-at re) (beginning-of-line 0))
11591 (beginning-of-line 2)
11592 (setq beg (point))
11593 (while (looking-at re) (beginning-of-line 2))
11594 (setq end (point)))
11595 (comment-region beg end (if commented '(4) nil))))
11597 (defun orgtbl-insert-radio-table ()
11598 "Insert a radio table template appropriate for this major mode."
11599 (interactive)
11600 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11601 (txt (nth 1 e))
11602 name pos)
11603 (unless e (error "No radio table setup defined for %s" major-mode))
11604 (setq name (read-string "Table name: "))
11605 (while (string-match "%n" txt)
11606 (setq txt (replace-match name t t txt)))
11607 (or (bolp) (insert "\n"))
11608 (setq pos (point))
11609 (insert txt)
11610 (goto-char pos)))
11612 (defun org-get-param (params header i sym &optional hsym)
11613 "Get parameter value for symbol SYM.
11614 If this is a header line, actually get the value for the symbol with an
11615 additional \"h\" inserted after the colon.
11616 If the value is a protperty list, get the element for the current column.
11617 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11618 (let ((val (plist-get params sym)))
11619 (and hsym header (setq val (or (plist-get params hsym) val)))
11620 (if (consp val) (plist-get val i) val)))
11622 (defun orgtbl-to-generic (table params)
11623 "Convert the orgtbl-mode TABLE to some other format.
11624 This generic routine can be used for many standard cases.
11625 TABLE is a list, each entry either the symbol `hline' for a horizontal
11626 separator line, or a list of fields for that line.
11627 PARAMS is a property list of parameters that can influence the conversion.
11628 For the generic converter, some parameters are obligatory: You need to
11629 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11630 :splice, you must have :tstart and :tend.
11632 Valid parameters are
11634 :tstart String to start the table. Ignored when :splice is t.
11635 :tend String to end the table. Ignored when :splice is t.
11637 :splice When set to t, return only table body lines, don't wrap
11638 them into :tstart and :tend. Default is nil.
11640 :hline String to be inserted on horizontal separation lines.
11641 May be nil to ignore hlines.
11643 :lstart String to start a new table line.
11644 :lend String to end a table line
11645 :sep Separator between two fields
11646 :lfmt Format for entire line, with enough %s to capture all fields.
11647 If this is present, :lstart, :lend, and :sep are ignored.
11648 :fmt A format to be used to wrap the field, should contain
11649 %s for the original field value. For example, to wrap
11650 everything in dollars, you could use :fmt \"$%s$\".
11651 This may also be a property list with column numbers and
11652 formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11654 :hlstart :hlend :hlsep :hlfmt :hfmt
11655 Same as above, specific for the header lines in the table.
11656 All lines before the first hline are treated as header.
11657 If any of these is not present, the data line value is used.
11659 :efmt Use this format to print numbers with exponentials.
11660 The format should have %s twice for inserting mantissa
11661 and exponent, for example \"%s\\\\times10^{%s}\". This
11662 may also be a property list with column numbers and
11663 formats. :fmt will still be applied after :efmt.
11665 In addition to this, the parameters :skip and :skipcols are always handled
11666 directly by `orgtbl-send-table'. See manual."
11667 (interactive)
11668 (let* ((p params)
11669 (splicep (plist-get p :splice))
11670 (hline (plist-get p :hline))
11671 rtn line i fm efm lfmt h)
11673 ;; Do we have a header?
11674 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11675 (setq h t))
11677 ;; Put header
11678 (unless splicep
11679 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11681 ;; Now loop over all lines
11682 (while (setq line (pop table))
11683 (if (eq line 'hline)
11684 ;; A horizontal separator line
11685 (progn (if hline (push hline rtn))
11686 (setq h nil)) ; no longer in header
11687 ;; A normal line. Convert the fields, push line onto the result list
11688 (setq i 0)
11689 (setq line
11690 (mapcar
11691 (lambda (f)
11692 (setq i (1+ i)
11693 fm (org-get-param p h i :fmt :hfmt)
11694 efm (org-get-param p h i :efmt))
11695 (if (and efm (string-match orgtbl-exp-regexp f))
11696 (setq f (format
11697 efm (match-string 1 f) (match-string 2 f))))
11698 (if fm (setq f (format fm f)))
11700 line))
11701 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11702 (push (apply 'format lfmt line) rtn)
11703 (push (concat
11704 (org-get-param p h i :lstart :hlstart)
11705 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11706 (org-get-param p h i :lend :hlend))
11707 rtn))))
11709 (unless splicep
11710 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11712 (mapconcat 'identity (nreverse rtn) "\n")))
11714 (defun orgtbl-to-latex (table params)
11715 "Convert the orgtbl-mode TABLE to LaTeX.
11716 TABLE is a list, each entry either the symbol `hline' for a horizontal
11717 separator line, or a list of fields for that line.
11718 PARAMS is a property list of parameters that can influence the conversion.
11719 Supports all parameters from `orgtbl-to-generic'. Most important for
11720 LaTeX are:
11722 :splice When set to t, return only table body lines, don't wrap
11723 them into a tabular environment. Default is nil.
11725 :fmt A format to be used to wrap the field, should contain %s for the
11726 original field value. For example, to wrap everything in dollars,
11727 use :fmt \"$%s$\". This may also be a property list with column
11728 numbers and formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11730 :efmt Format for transforming numbers with exponentials. The format
11731 should have %s twice for inserting mantissa and exponent, for
11732 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11733 This may also be a property list with column numbers and formats.
11735 The general parameters :skip and :skipcols have already been applied when
11736 this function is called."
11737 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11738 org-table-last-alignment ""))
11739 (params2
11740 (list
11741 :tstart (concat "\\begin{tabular}{" alignment "}")
11742 :tend "\\end{tabular}"
11743 :lstart "" :lend " \\\\" :sep " & "
11744 :efmt "%s\\,(%s)" :hline "\\hline")))
11745 (orgtbl-to-generic table (org-combine-plists params2 params))))
11747 (defun orgtbl-to-html (table params)
11748 "Convert the orgtbl-mode TABLE to LaTeX.
11749 TABLE is a list, each entry either the symbol `hline' for a horizontal
11750 separator line, or a list of fields for that line.
11751 PARAMS is a property list of parameters that can influence the conversion.
11752 Currently this function recognizes the following parameters:
11754 :splice When set to t, return only table body lines, don't wrap
11755 them into a <table> environment. Default is nil.
11757 The general parameters :skip and :skipcols have already been applied when
11758 this function is called. The function does *not* use `orgtbl-to-generic',
11759 so you cannot specify parameters for it."
11760 (let* ((splicep (plist-get params :splice))
11761 html)
11762 ;; Just call the formatter we already have
11763 ;; We need to make text lines for it, so put the fields back together.
11764 (setq html (org-format-org-table-html
11765 (mapcar
11766 (lambda (x)
11767 (if (eq x 'hline)
11768 "|----+----|"
11769 (concat "| " (mapconcat 'identity x " | ") " |")))
11770 table)
11771 splicep))
11772 (if (string-match "\n+\\'" html)
11773 (setq html (replace-match "" t t html)))
11774 html))
11776 (defun orgtbl-to-texinfo (table params)
11777 "Convert the orgtbl-mode TABLE to TeXInfo.
11778 TABLE is a list, each entry either the symbol `hline' for a horizontal
11779 separator line, or a list of fields for that line.
11780 PARAMS is a property list of parameters that can influence the conversion.
11781 Supports all parameters from `orgtbl-to-generic'. Most important for
11782 TeXInfo are:
11784 :splice nil/t When set to t, return only table body lines, don't wrap
11785 them into a multitable environment. Default is nil.
11787 :fmt fmt A format to be used to wrap the field, should contain
11788 %s for the original field value. For example, to wrap
11789 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
11790 This may also be a property list with column numbers and
11791 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
11793 :cf \"f1 f2..\" The column fractions for the table. By default these
11794 are computed automatically from the width of the columns
11795 under org-mode.
11797 The general parameters :skip and :skipcols have already been applied when
11798 this function is called."
11799 (let* ((total (float (apply '+ org-table-last-column-widths)))
11800 (colfrac (or (plist-get params :cf)
11801 (mapconcat
11802 (lambda (x) (format "%.3f" (/ (float x) total)))
11803 org-table-last-column-widths " ")))
11804 (params2
11805 (list
11806 :tstart (concat "@multitable @columnfractions " colfrac)
11807 :tend "@end multitable"
11808 :lstart "@item " :lend "" :sep " @tab "
11809 :hlstart "@headitem ")))
11810 (orgtbl-to-generic table (org-combine-plists params2 params))))
11812 ;;;; Link Stuff
11814 ;;; Link abbreviations
11816 (defun org-link-expand-abbrev (link)
11817 "Apply replacements as defined in `org-link-abbrev-alist."
11818 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
11819 (let* ((key (match-string 1 link))
11820 (as (or (assoc key org-link-abbrev-alist-local)
11821 (assoc key org-link-abbrev-alist)))
11822 (tag (and (match-end 2) (match-string 3 link)))
11823 rpl)
11824 (if (not as)
11825 link
11826 (setq rpl (cdr as))
11827 (cond
11828 ((symbolp rpl) (funcall rpl tag))
11829 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
11830 (t (concat rpl tag)))))
11831 link))
11833 ;;; Storing and inserting links
11835 (defvar org-insert-link-history nil
11836 "Minibuffer history for links inserted with `org-insert-link'.")
11838 (defvar org-stored-links nil
11839 "Contains the links stored with `org-store-link'.")
11841 (defvar org-store-link-plist nil
11842 "Plist with info about the most recently link created with `org-store-link'.")
11844 (defvar org-link-protocols nil
11845 "Link protocols added to Org-mode using `org-add-link-type'.")
11847 (defvar org-store-link-functions nil
11848 "List of functions that are called to create and store a link.
11849 Each function will be called in turn until one returns a non-nil
11850 value. Each function should check if it is responsible for creating
11851 this link (for example by looking at the major mode).
11852 If not, it must exit and return nil.
11853 If yes, it should return a non-nil value after a calling
11854 `org-store-link-props' with a list of properties and values.
11855 Special properties are:
11857 :type The link prefix. like \"http\". This must be given.
11858 :link The link, like \"http://www.astro.uva.nl/~dominik\".
11859 This is obligatory as well.
11860 :description Optional default description for the second pair
11861 of brackets in an Org-mode link. The user can still change
11862 this when inserting this link into an Org-mode buffer.
11864 In addition to these, any additional properties can be specified
11865 and then used in remember templates.")
11867 (defun org-add-link-type (type &optional follow publish)
11868 "Add TYPE to the list of `org-link-types'.
11869 Re-compute all regular expressions depending on `org-link-types'
11870 FOLLOW and PUBLISH are two functions. Both take the link path as
11871 an argument.
11872 FOLLOW should do whatever is necessary to follow the link, for example
11873 to find a file or display a mail message.
11875 PUBLISH takes the path and retuns the string that should be used when
11876 this document is published. FIMXE: This is actually not yet implemented."
11877 (add-to-list 'org-link-types type t)
11878 (org-make-link-regexps)
11879 (add-to-list 'org-link-protocols
11880 (list type follow publish)))
11882 (defun org-add-agenda-custom-command (entry)
11883 "Replace or add a command in `org-agenda-custom-commands'.
11884 This is mostly for hacking and trying a new command - once the command
11885 works you probably want to add it to `org-agenda-custom-commands' for good."
11886 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
11887 (if ass
11888 (setcdr ass (cdr entry))
11889 (push entry org-agenda-custom-commands))))
11891 ;;;###autoload
11892 (defun org-store-link (arg)
11893 "\\<org-mode-map>Store an org-link to the current location.
11894 This link can later be inserted into an org-buffer with
11895 \\[org-insert-link].
11896 For some link types, a prefix arg is interpreted:
11897 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
11898 For file links, arg negates `org-context-in-file-links'."
11899 (interactive "P")
11900 (setq org-store-link-plist nil) ; reset
11901 (let (link cpltxt desc description search txt)
11902 (cond
11904 ((run-hook-with-args-until-success 'org-store-link-functions)
11905 (setq link (plist-get org-store-link-plist :link)
11906 desc (or (plist-get org-store-link-plist :description) link)))
11908 ((eq major-mode 'bbdb-mode)
11909 (let ((name (bbdb-record-name (bbdb-current-record)))
11910 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
11911 (setq cpltxt (concat "bbdb:" (or name company))
11912 link (org-make-link cpltxt))
11913 (org-store-link-props :type "bbdb" :name name :company company)))
11915 ((eq major-mode 'Info-mode)
11916 (setq link (org-make-link "info:"
11917 (file-name-nondirectory Info-current-file)
11918 ":" Info-current-node))
11919 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
11920 ":" Info-current-node))
11921 (org-store-link-props :type "info" :file Info-current-file
11922 :node Info-current-node))
11924 ((eq major-mode 'calendar-mode)
11925 (let ((cd (calendar-cursor-to-date)))
11926 (setq link
11927 (format-time-string
11928 (car org-time-stamp-formats)
11929 (apply 'encode-time
11930 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
11931 nil nil nil))))
11932 (org-store-link-props :type "calendar" :date cd)))
11934 ((or (eq major-mode 'vm-summary-mode)
11935 (eq major-mode 'vm-presentation-mode))
11936 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
11937 (vm-follow-summary-cursor)
11938 (save-excursion
11939 (vm-select-folder-buffer)
11940 (let* ((message (car vm-message-pointer))
11941 (folder buffer-file-name)
11942 (subject (vm-su-subject message))
11943 (to (vm-get-header-contents message "To"))
11944 (from (vm-get-header-contents message "From"))
11945 (message-id (vm-su-message-id message)))
11946 (org-store-link-props :type "vm" :from from :to to :subject subject
11947 :message-id message-id)
11948 (setq message-id (org-remove-angle-brackets message-id))
11949 (setq folder (abbreviate-file-name folder))
11950 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
11951 folder)
11952 (setq folder (replace-match "" t t folder)))
11953 (setq cpltxt (org-email-link-description))
11954 (setq link (org-make-link "vm:" folder "#" message-id)))))
11956 ((eq major-mode 'wl-summary-mode)
11957 (let* ((msgnum (wl-summary-message-number))
11958 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
11959 msgnum 'message-id))
11960 (wl-message-entity
11961 (if (fboundp 'elmo-message-entity)
11962 (elmo-message-entity
11963 wl-summary-buffer-elmo-folder msgnum)
11964 (elmo-msgdb-overview-get-entity
11965 msgnum (wl-summary-buffer-msgdb))))
11966 (from (wl-summary-line-from))
11967 (to (car (elmo-message-entity-field wl-message-entity 'to)))
11968 (subject (let (wl-thr-indent-string wl-parent-message-entity)
11969 (wl-summary-line-subject))))
11970 (org-store-link-props :type "wl" :from from :to to
11971 :subject subject :message-id message-id)
11972 (setq message-id (org-remove-angle-brackets message-id))
11973 (setq cpltxt (org-email-link-description))
11974 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
11975 "#" message-id))))
11977 ((or (equal major-mode 'mh-folder-mode)
11978 (equal major-mode 'mh-show-mode))
11979 (let ((from (org-mhe-get-header "From:"))
11980 (to (org-mhe-get-header "To:"))
11981 (message-id (org-mhe-get-header "Message-Id:"))
11982 (subject (org-mhe-get-header "Subject:")))
11983 (org-store-link-props :type "mh" :from from :to to
11984 :subject subject :message-id message-id)
11985 (setq cpltxt (org-email-link-description))
11986 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
11987 (org-remove-angle-brackets message-id)))))
11989 ((eq major-mode 'rmail-mode)
11990 (save-excursion
11991 (save-restriction
11992 (rmail-narrow-to-non-pruned-header)
11993 (let ((folder buffer-file-name)
11994 (message-id (mail-fetch-field "message-id"))
11995 (from (mail-fetch-field "from"))
11996 (to (mail-fetch-field "to"))
11997 (subject (mail-fetch-field "subject")))
11998 (org-store-link-props
11999 :type "rmail" :from from :to to
12000 :subject subject :message-id message-id)
12001 (setq message-id (org-remove-angle-brackets message-id))
12002 (setq cpltxt (org-email-link-description))
12003 (setq link (org-make-link "rmail:" folder "#" message-id))))))
12005 ((eq major-mode 'gnus-group-mode)
12006 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
12007 (gnus-group-group-name)) ; version
12008 ((fboundp 'gnus-group-name)
12009 (gnus-group-name))
12010 (t "???"))))
12011 (unless group (error "Not on a group"))
12012 (org-store-link-props :type "gnus" :group group)
12013 (setq cpltxt (concat
12014 (if (org-xor arg org-usenet-links-prefer-google)
12015 "http://groups.google.com/groups?group="
12016 "gnus:")
12017 group)
12018 link (org-make-link cpltxt))))
12020 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
12021 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
12022 (let* ((group gnus-newsgroup-name)
12023 (article (gnus-summary-article-number))
12024 (header (gnus-summary-article-header article))
12025 (from (mail-header-from header))
12026 (message-id (mail-header-id header))
12027 (date (mail-header-date header))
12028 (subject (gnus-summary-subject-string)))
12029 (org-store-link-props :type "gnus" :from from :subject subject
12030 :message-id message-id :group group)
12031 (setq cpltxt (org-email-link-description))
12032 (if (org-xor arg org-usenet-links-prefer-google)
12033 (setq link
12034 (concat
12035 cpltxt "\n "
12036 (format "http://groups.google.com/groups?as_umsgid=%s"
12037 (org-fixup-message-id-for-http message-id))))
12038 (setq link (org-make-link "gnus:" group
12039 "#" (number-to-string article))))))
12041 ((eq major-mode 'w3-mode)
12042 (setq cpltxt (url-view-url t)
12043 link (org-make-link cpltxt))
12044 (org-store-link-props :type "w3" :url (url-view-url t)))
12046 ((eq major-mode 'w3m-mode)
12047 (setq cpltxt (or w3m-current-title w3m-current-url)
12048 link (org-make-link w3m-current-url))
12049 (org-store-link-props :type "w3m" :url (url-view-url t)))
12051 ((setq search (run-hook-with-args-until-success
12052 'org-create-file-search-functions))
12053 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
12054 "::" search))
12055 (setq cpltxt (or description link)))
12057 ((eq major-mode 'image-mode)
12058 (setq cpltxt (concat "file:"
12059 (abbreviate-file-name buffer-file-name))
12060 link (org-make-link cpltxt))
12061 (org-store-link-props :type "image" :file buffer-file-name))
12063 ((eq major-mode 'dired-mode)
12064 ;; link to the file in the current line
12065 (setq cpltxt (concat "file:"
12066 (abbreviate-file-name
12067 (expand-file-name
12068 (dired-get-filename nil t))))
12069 link (org-make-link cpltxt)))
12071 ((and buffer-file-name (org-mode-p))
12072 ;; Just link to current headline
12073 (setq cpltxt (concat "file:"
12074 (abbreviate-file-name buffer-file-name)))
12075 ;; Add a context search string
12076 (when (org-xor org-context-in-file-links arg)
12077 ;; Check if we are on a target
12078 (if (org-in-regexp "<<\\(.*?\\)>>")
12079 (setq cpltxt (concat cpltxt "::" (match-string 1)))
12080 (setq txt (cond
12081 ((org-on-heading-p) nil)
12082 ((org-region-active-p)
12083 (buffer-substring (region-beginning) (region-end)))
12084 (t (buffer-substring (point-at-bol) (point-at-eol)))))
12085 (when (or (null txt) (string-match "\\S-" txt))
12086 (setq cpltxt
12087 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12088 desc "NONE"))))
12089 (if (string-match "::\\'" cpltxt)
12090 (setq cpltxt (substring cpltxt 0 -2)))
12091 (setq link (org-make-link cpltxt)))
12093 ((buffer-file-name (buffer-base-buffer))
12094 ;; Just link to this file here.
12095 (setq cpltxt (concat "file:"
12096 (abbreviate-file-name
12097 (buffer-file-name (buffer-base-buffer)))))
12098 ;; Add a context string
12099 (when (org-xor org-context-in-file-links arg)
12100 (setq txt (if (org-region-active-p)
12101 (buffer-substring (region-beginning) (region-end))
12102 (buffer-substring (point-at-bol) (point-at-eol))))
12103 ;; Only use search option if there is some text.
12104 (when (string-match "\\S-" txt)
12105 (setq cpltxt
12106 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12107 desc "NONE")))
12108 (setq link (org-make-link cpltxt)))
12110 ((interactive-p)
12111 (error "Cannot link to a buffer which is not visiting a file"))
12113 (t (setq link nil)))
12115 (if (consp link) (setq cpltxt (car link) link (cdr link)))
12116 (setq link (or link cpltxt)
12117 desc (or desc cpltxt))
12118 (if (equal desc "NONE") (setq desc nil))
12120 (if (and (interactive-p) link)
12121 (progn
12122 (setq org-stored-links
12123 (cons (list link desc) org-stored-links))
12124 (message "Stored: %s" (or desc link)))
12125 (and link (org-make-link-string link desc)))))
12127 (defun org-store-link-props (&rest plist)
12128 "Store link properties, extract names and addresses."
12129 (let (x adr)
12130 (when (setq x (plist-get plist :from))
12131 (setq adr (mail-extract-address-components x))
12132 (plist-put plist :fromname (car adr))
12133 (plist-put plist :fromaddress (nth 1 adr)))
12134 (when (setq x (plist-get plist :to))
12135 (setq adr (mail-extract-address-components x))
12136 (plist-put plist :toname (car adr))
12137 (plist-put plist :toaddress (nth 1 adr))))
12138 (let ((from (plist-get plist :from))
12139 (to (plist-get plist :to)))
12140 (when (and from to org-from-is-user-regexp)
12141 (plist-put plist :fromto
12142 (if (string-match org-from-is-user-regexp from)
12143 (concat "to %t")
12144 (concat "from %f")))))
12145 (setq org-store-link-plist plist))
12147 (defun org-email-link-description (&optional fmt)
12148 "Return the description part of an email link.
12149 This takes information from `org-store-link-plist' and formats it
12150 according to FMT (default from `org-email-link-description-format')."
12151 (setq fmt (or fmt org-email-link-description-format))
12152 (let* ((p org-store-link-plist)
12153 (to (plist-get p :toaddress))
12154 (from (plist-get p :fromaddress))
12155 (table
12156 (list
12157 (cons "%c" (plist-get p :fromto))
12158 (cons "%F" (plist-get p :from))
12159 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12160 (cons "%T" (plist-get p :to))
12161 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12162 (cons "%s" (plist-get p :subject))
12163 (cons "%m" (plist-get p :message-id)))))
12164 (when (string-match "%c" fmt)
12165 ;; Check if the user wrote this message
12166 (if (and org-from-is-user-regexp from to
12167 (save-match-data (string-match org-from-is-user-regexp from)))
12168 (setq fmt (replace-match "to %t" t t fmt))
12169 (setq fmt (replace-match "from %f" t t fmt))))
12170 (org-replace-escapes fmt table)))
12172 (defun org-make-org-heading-search-string (&optional string heading)
12173 "Make search string for STRING or current headline."
12174 (interactive)
12175 (let ((s (or string (org-get-heading))))
12176 (unless (and string (not heading))
12177 ;; We are using a headline, clean up garbage in there.
12178 (if (string-match org-todo-regexp s)
12179 (setq s (replace-match "" t t s)))
12180 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12181 (setq s (replace-match "" t t s)))
12182 (setq s (org-trim s))
12183 (if (string-match (concat "^\\(" org-quote-string "\\|"
12184 org-comment-string "\\)") s)
12185 (setq s (replace-match "" t t s)))
12186 (while (string-match org-ts-regexp s)
12187 (setq s (replace-match "" t t s))))
12188 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12189 (setq s (replace-match " " t t s)))
12190 (or string (setq s (concat "*" s))) ; Add * for headlines
12191 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12193 (defun org-make-link (&rest strings)
12194 "Concatenate STRINGS."
12195 (apply 'concat strings))
12197 (defun org-make-link-string (link &optional description)
12198 "Make a link with brackets, consisting of LINK and DESCRIPTION."
12199 (unless (string-match "\\S-" link)
12200 (error "Empty link"))
12201 (when (stringp description)
12202 ;; Remove brackets from the description, they are fatal.
12203 (while (string-match "\\[" description)
12204 (setq description (replace-match "{" t t description)))
12205 (while (string-match "\\]" description)
12206 (setq description (replace-match "}" t t description))))
12207 (when (equal (org-link-escape link) description)
12208 ;; No description needed, it is identical
12209 (setq description nil))
12210 (when (and (not description)
12211 (not (equal link (org-link-escape link))))
12212 (setq description link))
12213 (concat "[[" (org-link-escape link) "]"
12214 (if description (concat "[" description "]") "")
12215 "]"))
12217 (defconst org-link-escape-chars
12218 '((?\ . "%20")
12219 (?\[ . "%5B")
12220 (?\] . "%5D")
12221 (?\340 . "%E0") ; `a
12222 (?\342 . "%E2") ; ^a
12223 (?\347 . "%E7") ; ,c
12224 (?\350 . "%E8") ; `e
12225 (?\351 . "%E9") ; 'e
12226 (?\352 . "%EA") ; ^e
12227 (?\356 . "%EE") ; ^i
12228 (?\364 . "%F4") ; ^o
12229 (?\371 . "%F9") ; `u
12230 (?\373 . "%FB") ; ^u
12231 (?\; . "%3B")
12232 (?? . "%3F")
12233 (?= . "%3D")
12234 (?+ . "%2B")
12236 "Association list of escapes for some characters problematic in links.
12237 This is the list that is used for internal purposes.")
12239 (defconst org-link-escape-chars-browser
12240 '((?\ . "%20")) ; 32 for the SPC char
12241 "Association list of escapes for some characters problematic in links.
12242 This is the list that is used before handing over to the browser.")
12244 (defun org-link-escape (text &optional table)
12245 "Escape charaters in TEXT that are problematic for links."
12246 (setq table (or table org-link-escape-chars))
12247 (when text
12248 (let ((re (mapconcat (lambda (x) (regexp-quote
12249 (char-to-string (car x))))
12250 table "\\|")))
12251 (while (string-match re text)
12252 (setq text
12253 (replace-match
12254 (cdr (assoc (string-to-char (match-string 0 text))
12255 table))
12256 t t text)))
12257 text)))
12259 (defun org-link-unescape (text &optional table)
12260 "Reverse the action of `org-link-escape'."
12261 (setq table (or table org-link-escape-chars))
12262 (when text
12263 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12264 table "\\|")))
12265 (while (string-match re text)
12266 (setq text
12267 (replace-match
12268 (char-to-string (car (rassoc (match-string 0 text) table)))
12269 t t text)))
12270 text)))
12272 (defun org-xor (a b)
12273 "Exclusive or."
12274 (if a (not b) b))
12276 (defun org-get-header (header)
12277 "Find a header field in the current buffer."
12278 (save-excursion
12279 (goto-char (point-min))
12280 (let ((case-fold-search t) s)
12281 (cond
12282 ((eq header 'from)
12283 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12284 (setq s (match-string 1)))
12285 (while (string-match "\"" s)
12286 (setq s (replace-match "" t t s)))
12287 (if (string-match "[<(].*" s)
12288 (setq s (replace-match "" t t s))))
12289 ((eq header 'message-id)
12290 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12291 (setq s (match-string 1))))
12292 ((eq header 'subject)
12293 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12294 (setq s (match-string 1)))))
12295 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12296 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12297 s)))
12300 (defun org-fixup-message-id-for-http (s)
12301 "Replace special characters in a message id, so it can be used in an http query."
12302 (while (string-match "<" s)
12303 (setq s (replace-match "%3C" t t s)))
12304 (while (string-match ">" s)
12305 (setq s (replace-match "%3E" t t s)))
12306 (while (string-match "@" s)
12307 (setq s (replace-match "%40" t t s)))
12310 ;;;###autoload
12311 (defun org-insert-link-global ()
12312 "Insert a link like Org-mode does.
12313 This command can be called in any mode to insert a link in Org-mode syntax."
12314 (interactive)
12315 (org-run-like-in-org-mode 'org-insert-link))
12317 (defun org-insert-link (&optional complete-file)
12318 "Insert a link. At the prompt, enter the link.
12320 Completion can be used to select a link previously stored with
12321 `org-store-link'. When the empty string is entered (i.e. if you just
12322 press RET at the prompt), the link defaults to the most recently
12323 stored link. As SPC triggers completion in the minibuffer, you need to
12324 use M-SPC or C-q SPC to force the insertion of a space character.
12326 You will also be prompted for a description, and if one is given, it will
12327 be displayed in the buffer instead of the link.
12329 If there is already a link at point, this command will allow you to edit link
12330 and description parts.
12332 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12333 selected using completion. The path to the file will be relative to
12334 the current directory if the file is in the current directory or a
12335 subdirectory. Otherwise, the link will be the absolute path as
12336 completed in the minibuffer (i.e. normally ~/path/to/file).
12338 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12339 is in the current directory or below.
12340 With three \\[universal-argument] prefixes, negate the meaning of
12341 `org-keep-stored-link-after-insertion'."
12342 (interactive "P")
12343 (let* ((wcf (current-window-configuration))
12344 (region (if (org-region-active-p)
12345 (buffer-substring (region-beginning) (region-end))))
12346 (remove (and region (list (region-beginning) (region-end))))
12347 (desc region)
12348 tmphist ; byte-compile incorrectly complains about this
12349 link entry file)
12350 (cond
12351 ((org-in-regexp org-bracket-link-regexp 1)
12352 ;; We do have a link at point, and we are going to edit it.
12353 (setq remove (list (match-beginning 0) (match-end 0)))
12354 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12355 (setq link (read-string "Link: "
12356 (org-link-unescape
12357 (org-match-string-no-properties 1)))))
12358 ((or (org-in-regexp org-angle-link-re)
12359 (org-in-regexp org-plain-link-re))
12360 ;; Convert to bracket link
12361 (setq remove (list (match-beginning 0) (match-end 0))
12362 link (read-string "Link: "
12363 (org-remove-angle-brackets (match-string 0)))))
12364 ((equal complete-file '(4))
12365 ;; Completing read for file names.
12366 (setq file (read-file-name "File: "))
12367 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12368 (pwd1 (file-name-as-directory (abbreviate-file-name
12369 (expand-file-name ".")))))
12370 (cond
12371 ((equal complete-file '(16))
12372 (setq link (org-make-link
12373 "file:"
12374 (abbreviate-file-name (expand-file-name file)))))
12375 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12376 (setq link (org-make-link "file:" (match-string 1 file))))
12377 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12378 (expand-file-name file))
12379 (setq link (org-make-link
12380 "file:" (match-string 1 (expand-file-name file)))))
12381 (t (setq link (org-make-link "file:" file))))))
12383 ;; Read link, with completion for stored links.
12384 (with-output-to-temp-buffer "*Org Links*"
12385 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12386 (when org-stored-links
12387 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12388 (princ (mapconcat
12389 (lambda (x)
12390 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12391 (reverse org-stored-links) "\n"))))
12392 (let ((cw (selected-window)))
12393 (select-window (get-buffer-window "*Org Links*"))
12394 (shrink-window-if-larger-than-buffer)
12395 (setq truncate-lines t)
12396 (select-window cw))
12397 ;; Fake a link history, containing the stored links.
12398 (setq tmphist (append (mapcar 'car org-stored-links)
12399 org-insert-link-history))
12400 (unwind-protect
12401 (setq link (org-completing-read
12402 "Link: "
12403 (append
12404 (mapcar (lambda (x) (list (concat (car x) ":")))
12405 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12406 (mapcar (lambda (x) (list (concat x ":")))
12407 org-link-types))
12408 nil nil nil
12409 'tmphist
12410 (or (car (car org-stored-links)))))
12411 (set-window-configuration wcf)
12412 (kill-buffer "*Org Links*"))
12413 (setq entry (assoc link org-stored-links))
12414 (or entry (push link org-insert-link-history))
12415 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12416 (not org-keep-stored-link-after-insertion))
12417 (setq org-stored-links (delq (assoc link org-stored-links)
12418 org-stored-links)))
12419 (setq desc (or desc (nth 1 entry)))))
12421 (if (string-match org-plain-link-re link)
12422 ;; URL-like link, normalize the use of angular brackets.
12423 (setq link (org-make-link (org-remove-angle-brackets link))))
12425 ;; Check if we are linking to the current file with a search option
12426 ;; If yes, simplify the link by using only the search option.
12427 (when (and buffer-file-name
12428 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12429 (let* ((path (match-string 1 link))
12430 (case-fold-search nil)
12431 (search (match-string 2 link)))
12432 (save-match-data
12433 (if (equal (file-truename buffer-file-name) (file-truename path))
12434 ;; We are linking to this same file, with a search option
12435 (setq link search)))))
12437 ;; Check if we can/should use a relative path. If yes, simplify the link
12438 (when (string-match "\\<file:\\(.*\\)" link)
12439 (let* ((path (match-string 1 link))
12440 (origpath path)
12441 (desc-is-link (equal link desc))
12442 (case-fold-search nil))
12443 (cond
12444 ((eq org-link-file-path-type 'absolute)
12445 (setq path (abbreviate-file-name (expand-file-name path))))
12446 ((eq org-link-file-path-type 'noabbrev)
12447 (setq path (expand-file-name path)))
12448 ((eq org-link-file-path-type 'relative)
12449 (setq path (file-relative-name path)))
12451 (save-match-data
12452 (if (string-match (concat "^" (regexp-quote
12453 (file-name-as-directory
12454 (expand-file-name "."))))
12455 (expand-file-name path))
12456 ;; We are linking a file with relative path name.
12457 (setq path (substring (expand-file-name path)
12458 (match-end 0)))))))
12459 (setq link (concat "file:" path))
12460 (if (equal desc origpath)
12461 (setq desc path))))
12463 (setq desc (read-string "Description: " desc))
12464 (unless (string-match "\\S-" desc) (setq desc nil))
12465 (if remove (apply 'delete-region remove))
12466 (insert (org-make-link-string link desc))))
12468 (defun org-completing-read (&rest args)
12469 (let ((minibuffer-local-completion-map
12470 (copy-keymap minibuffer-local-completion-map)))
12471 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12472 (apply 'completing-read args)))
12474 ;;; Opening/following a link
12475 (defvar org-link-search-failed nil)
12477 (defun org-next-link ()
12478 "Move forward to the next link.
12479 If the link is in hidden text, expose it."
12480 (interactive)
12481 (when (and org-link-search-failed (eq this-command last-command))
12482 (goto-char (point-min))
12483 (message "Link search wrapped back to beginning of buffer"))
12484 (setq org-link-search-failed nil)
12485 (let* ((pos (point))
12486 (ct (org-context))
12487 (a (assoc :link ct)))
12488 (if a (goto-char (nth 2 a)))
12489 (if (re-search-forward org-any-link-re nil t)
12490 (progn
12491 (goto-char (match-beginning 0))
12492 (if (org-invisible-p) (org-show-context)))
12493 (goto-char pos)
12494 (setq org-link-search-failed t)
12495 (error "No further link found"))))
12497 (defun org-previous-link ()
12498 "Move backward to the previous link.
12499 If the link is in hidden text, expose it."
12500 (interactive)
12501 (when (and org-link-search-failed (eq this-command last-command))
12502 (goto-char (point-max))
12503 (message "Link search wrapped back to end of buffer"))
12504 (setq org-link-search-failed nil)
12505 (let* ((pos (point))
12506 (ct (org-context))
12507 (a (assoc :link ct)))
12508 (if a (goto-char (nth 1 a)))
12509 (if (re-search-backward org-any-link-re nil t)
12510 (progn
12511 (goto-char (match-beginning 0))
12512 (if (org-invisible-p) (org-show-context)))
12513 (goto-char pos)
12514 (setq org-link-search-failed t)
12515 (error "No further link found"))))
12517 (defun org-find-file-at-mouse (ev)
12518 "Open file link or URL at mouse."
12519 (interactive "e")
12520 (mouse-set-point ev)
12521 (org-open-at-point 'in-emacs))
12523 (defun org-open-at-mouse (ev)
12524 "Open file link or URL at mouse."
12525 (interactive "e")
12526 (mouse-set-point ev)
12527 (org-open-at-point))
12529 (defvar org-window-config-before-follow-link nil
12530 "The window configuration before following a link.
12531 This is saved in case the need arises to restore it.")
12533 (defvar org-open-link-marker (make-marker)
12534 "Marker pointing to the location where `org-open-at-point; was called.")
12536 ;;;###autoload
12537 (defun org-open-at-point-global ()
12538 "Follow a link like Org-mode does.
12539 This command can be called in any mode to follow a link that has
12540 Org-mode syntax."
12541 (interactive)
12542 (org-run-like-in-org-mode 'org-open-at-point))
12544 (defun org-open-at-point (&optional in-emacs)
12545 "Open link at or after point.
12546 If there is no link at point, this function will search forward up to
12547 the end of the current subtree.
12548 Normally, files will be opened by an appropriate application. If the
12549 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12550 (interactive "P")
12551 (catch 'abort
12552 (move-marker org-open-link-marker (point))
12553 (setq org-window-config-before-follow-link (current-window-configuration))
12554 (org-remove-occur-highlights nil nil t)
12555 (if (org-at-timestamp-p t)
12556 (org-follow-timestamp-link)
12557 (let (type path link line search (pos (point)))
12558 (catch 'match
12559 (save-excursion
12560 (skip-chars-forward "^]\n\r")
12561 (when (org-in-regexp org-bracket-link-regexp)
12562 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12563 (while (string-match " *\n *" link)
12564 (setq link (replace-match " " t t link)))
12565 (setq link (org-link-expand-abbrev link))
12566 (if (string-match org-link-re-with-space2 link)
12567 (setq type (match-string 1 link) path (match-string 2 link))
12568 (setq type "thisfile" path link))
12569 (throw 'match t)))
12571 (when (get-text-property (point) 'org-linked-text)
12572 (setq type "thisfile"
12573 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12574 (1+ (point)) (point))
12575 path (buffer-substring
12576 (previous-single-property-change pos 'org-linked-text)
12577 (next-single-property-change pos 'org-linked-text)))
12578 (throw 'match t))
12580 (save-excursion
12581 (when (or (org-in-regexp org-angle-link-re)
12582 (org-in-regexp org-plain-link-re))
12583 (setq type (match-string 1) path (match-string 2))
12584 (throw 'match t)))
12585 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12586 (setq type "tree-match"
12587 path (match-string 1))
12588 (throw 'match t))
12589 (save-excursion
12590 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12591 (setq type "tags"
12592 path (match-string 1))
12593 (while (string-match ":" path)
12594 (setq path (replace-match "+" t t path)))
12595 (throw 'match t))))
12596 (unless path
12597 (error "No link found"))
12598 ;; Remove any trailing spaces in path
12599 (if (string-match " +\\'" path)
12600 (setq path (replace-match "" t t path)))
12602 (cond
12604 ((assoc type org-link-protocols)
12605 (funcall (nth 1 (assoc type org-link-protocols)) path))
12607 ((equal type "mailto")
12608 (let ((cmd (car org-link-mailto-program))
12609 (args (cdr org-link-mailto-program)) args1
12610 (address path) (subject "") a)
12611 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12612 (setq address (match-string 1 path)
12613 subject (org-link-escape (match-string 2 path))))
12614 (while args
12615 (cond
12616 ((not (stringp (car args))) (push (pop args) args1))
12617 (t (setq a (pop args))
12618 (if (string-match "%a" a)
12619 (setq a (replace-match address t t a)))
12620 (if (string-match "%s" a)
12621 (setq a (replace-match subject t t a)))
12622 (push a args1))))
12623 (apply cmd (nreverse args1))))
12625 ((member type '("http" "https" "ftp" "news"))
12626 (browse-url (concat type ":" (org-link-escape
12627 path org-link-escape-chars-browser))))
12629 ((member type '("message"))
12630 (browse-url (concat type ":" path)))
12632 ((string= type "tags")
12633 (org-tags-view in-emacs path))
12634 ((string= type "thisfile")
12635 (if in-emacs
12636 (switch-to-buffer-other-window
12637 (org-get-buffer-for-internal-link (current-buffer)))
12638 (org-mark-ring-push))
12639 (let ((cmd `(org-link-search
12640 ,path
12641 ,(cond ((equal in-emacs '(4)) 'occur)
12642 ((equal in-emacs '(16)) 'org-occur)
12643 (t nil))
12644 ,pos)))
12645 (condition-case nil (eval cmd)
12646 (error (progn (widen) (eval cmd))))))
12648 ((string= type "tree-match")
12649 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12651 ((string= type "file")
12652 (if (string-match "::\\([0-9]+\\)\\'" path)
12653 (setq line (string-to-number (match-string 1 path))
12654 path (substring path 0 (match-beginning 0)))
12655 (if (string-match "::\\(.+\\)\\'" path)
12656 (setq search (match-string 1 path)
12657 path (substring path 0 (match-beginning 0)))))
12658 (if (string-match "[*?{]" (file-name-nondirectory path))
12659 (dired path)
12660 (org-open-file path in-emacs line search)))
12662 ((string= type "news")
12663 (org-follow-gnus-link path))
12665 ((string= type "bbdb")
12666 (org-follow-bbdb-link path))
12668 ((string= type "info")
12669 (org-follow-info-link path))
12671 ((string= type "gnus")
12672 (let (group article)
12673 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12674 (error "Error in Gnus link"))
12675 (setq group (match-string 1 path)
12676 article (match-string 3 path))
12677 (org-follow-gnus-link group article)))
12679 ((string= type "vm")
12680 (let (folder article)
12681 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12682 (error "Error in VM link"))
12683 (setq folder (match-string 1 path)
12684 article (match-string 3 path))
12685 ;; in-emacs is the prefix arg, will be interpreted as read-only
12686 (org-follow-vm-link folder article in-emacs)))
12688 ((string= type "wl")
12689 (let (folder article)
12690 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12691 (error "Error in Wanderlust link"))
12692 (setq folder (match-string 1 path)
12693 article (match-string 3 path))
12694 (org-follow-wl-link folder article)))
12696 ((string= type "mhe")
12697 (let (folder article)
12698 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12699 (error "Error in MHE link"))
12700 (setq folder (match-string 1 path)
12701 article (match-string 3 path))
12702 (org-follow-mhe-link folder article)))
12704 ((string= type "rmail")
12705 (let (folder article)
12706 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12707 (error "Error in RMAIL link"))
12708 (setq folder (match-string 1 path)
12709 article (match-string 3 path))
12710 (org-follow-rmail-link folder article)))
12712 ((string= type "shell")
12713 (let ((cmd path))
12714 (if (or (not org-confirm-shell-link-function)
12715 (funcall org-confirm-shell-link-function
12716 (format "Execute \"%s\" in shell? "
12717 (org-add-props cmd nil
12718 'face 'org-warning))))
12719 (progn
12720 (message "Executing %s" cmd)
12721 (shell-command cmd))
12722 (error "Abort"))))
12724 ((string= type "elisp")
12725 (let ((cmd path))
12726 (if (or (not org-confirm-elisp-link-function)
12727 (funcall org-confirm-elisp-link-function
12728 (format "Execute \"%s\" as elisp? "
12729 (org-add-props cmd nil
12730 'face 'org-warning))))
12731 (message "%s => %s" cmd (eval (read cmd)))
12732 (error "Abort"))))
12735 (browse-url-at-point)))))
12736 (move-marker org-open-link-marker nil)))
12738 ;;; File search
12740 (defvar org-create-file-search-functions nil
12741 "List of functions to construct the right search string for a file link.
12742 These functions are called in turn with point at the location to
12743 which the link should point.
12745 A function in the hook should first test if it would like to
12746 handle this file type, for example by checking the major-mode or
12747 the file extension. If it decides not to handle this file, it
12748 should just return nil to give other functions a chance. If it
12749 does handle the file, it must return the search string to be used
12750 when following the link. The search string will be part of the
12751 file link, given after a double colon, and `org-open-at-point'
12752 will automatically search for it. If special measures must be
12753 taken to make the search successful, another function should be
12754 added to the companion hook `org-execute-file-search-functions',
12755 which see.
12757 A function in this hook may also use `setq' to set the variable
12758 `description' to provide a suggestion for the descriptive text to
12759 be used for this link when it gets inserted into an Org-mode
12760 buffer with \\[org-insert-link].")
12762 (defvar org-execute-file-search-functions nil
12763 "List of functions to execute a file search triggered by a link.
12765 Functions added to this hook must accept a single argument, the
12766 search string that was part of the file link, the part after the
12767 double colon. The function must first check if it would like to
12768 handle this search, for example by checking the major-mode or the
12769 file extension. If it decides not to handle this search, it
12770 should just return nil to give other functions a chance. If it
12771 does handle the search, it must return a non-nil value to keep
12772 other functions from trying.
12774 Each function can access the current prefix argument through the
12775 variable `current-prefix-argument'. Note that a single prefix is
12776 used to force opening a link in Emacs, so it may be good to only
12777 use a numeric or double prefix to guide the search function.
12779 In case this is needed, a function in this hook can also restore
12780 the window configuration before `org-open-at-point' was called using:
12782 (set-window-configuration org-window-config-before-follow-link)")
12784 (defun org-link-search (s &optional type avoid-pos)
12785 "Search for a link search option.
12786 If S is surrounded by forward slashes, it is interpreted as a
12787 regular expression. In org-mode files, this will create an `org-occur'
12788 sparse tree. In ordinary files, `occur' will be used to list matches.
12789 If the current buffer is in `dired-mode', grep will be used to search
12790 in all files. If AVOID-POS is given, ignore matches near that position."
12791 (let ((case-fold-search t)
12792 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12793 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12794 (append '(("") (" ") ("\t") ("\n"))
12795 org-emphasis-alist)
12796 "\\|") "\\)"))
12797 (pos (point))
12798 (pre "") (post "")
12799 words re0 re1 re2 re3 re4 re5 re2a reall)
12800 (cond
12801 ;; First check if there are any special
12802 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12803 ;; Now try the builtin stuff
12804 ((save-excursion
12805 (goto-char (point-min))
12806 (and
12807 (re-search-forward
12808 (concat "<<" (regexp-quote s0) ">>") nil t)
12809 (setq pos (match-beginning 0))))
12810 ;; There is an exact target for this
12811 (goto-char pos))
12812 ((string-match "^/\\(.*\\)/$" s)
12813 ;; A regular expression
12814 (cond
12815 ((org-mode-p)
12816 (org-occur (match-string 1 s)))
12817 ;;((eq major-mode 'dired-mode)
12818 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12819 (t (org-do-occur (match-string 1 s)))))
12821 ;; A normal search strings
12822 (when (equal (string-to-char s) ?*)
12823 ;; Anchor on headlines, post may include tags.
12824 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
12825 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
12826 s (substring s 1)))
12827 (remove-text-properties
12828 0 (length s)
12829 '(face nil mouse-face nil keymap nil fontified nil) s)
12830 ;; Make a series of regular expressions to find a match
12831 (setq words (org-split-string s "[ \n\r\t]+")
12832 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
12833 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
12834 "\\)" markers)
12835 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
12836 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
12837 re1 (concat pre re2 post)
12838 re3 (concat pre re4 post)
12839 re5 (concat pre ".*" re4)
12840 re2 (concat pre re2)
12841 re2a (concat pre re2a)
12842 re4 (concat pre re4)
12843 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
12844 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
12845 re5 "\\)"
12847 (cond
12848 ((eq type 'org-occur) (org-occur reall))
12849 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
12850 (t (goto-char (point-min))
12851 (if (or (org-search-not-self 1 re0 nil t)
12852 (org-search-not-self 1 re1 nil t)
12853 (org-search-not-self 1 re2 nil t)
12854 (org-search-not-self 1 re2a nil t)
12855 (org-search-not-self 1 re3 nil t)
12856 (org-search-not-self 1 re4 nil t)
12857 (org-search-not-self 1 re5 nil t)
12859 (goto-char (match-beginning 1))
12860 (goto-char pos)
12861 (error "No match")))))
12863 ;; Normal string-search
12864 (goto-char (point-min))
12865 (if (search-forward s nil t)
12866 (goto-char (match-beginning 0))
12867 (error "No match"))))
12868 (and (org-mode-p) (org-show-context 'link-search))))
12870 (defun org-search-not-self (group &rest args)
12871 "Execute `re-search-forward', but only accept matches that do not
12872 enclose the position of `org-open-link-marker'."
12873 (let ((m org-open-link-marker))
12874 (catch 'exit
12875 (while (apply 're-search-forward args)
12876 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
12877 (goto-char (match-end group))
12878 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
12879 (> (match-beginning 0) (marker-position m))
12880 (< (match-end 0) (marker-position m)))
12881 (save-match-data
12882 (or (not (org-in-regexp
12883 org-bracket-link-analytic-regexp 1))
12884 (not (match-end 4)) ; no description
12885 (and (<= (match-beginning 4) (point))
12886 (>= (match-end 4) (point))))))
12887 (throw 'exit (point))))))))
12889 (defun org-get-buffer-for-internal-link (buffer)
12890 "Return a buffer to be used for displaying the link target of internal links."
12891 (cond
12892 ((not org-display-internal-link-with-indirect-buffer)
12893 buffer)
12894 ((string-match "(Clone)$" (buffer-name buffer))
12895 (message "Buffer is already a clone, not making another one")
12896 ;; we also do not modify visibility in this case
12897 buffer)
12898 (t ; make a new indirect buffer for displaying the link
12899 (let* ((bn (buffer-name buffer))
12900 (ibn (concat bn "(Clone)"))
12901 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
12902 (with-current-buffer ib (org-overview))
12903 ib))))
12905 (defun org-do-occur (regexp &optional cleanup)
12906 "Call the Emacs command `occur'.
12907 If CLEANUP is non-nil, remove the printout of the regular expression
12908 in the *Occur* buffer. This is useful if the regex is long and not useful
12909 to read."
12910 (occur regexp)
12911 (when cleanup
12912 (let ((cwin (selected-window)) win beg end)
12913 (when (setq win (get-buffer-window "*Occur*"))
12914 (select-window win))
12915 (goto-char (point-min))
12916 (when (re-search-forward "match[a-z]+" nil t)
12917 (setq beg (match-end 0))
12918 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
12919 (setq end (1- (match-beginning 0)))))
12920 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
12921 (goto-char (point-min))
12922 (select-window cwin))))
12924 ;;; The mark ring for links jumps
12926 (defvar org-mark-ring nil
12927 "Mark ring for positions before jumps in Org-mode.")
12928 (defvar org-mark-ring-last-goto nil
12929 "Last position in the mark ring used to go back.")
12930 ;; Fill and close the ring
12931 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
12932 (loop for i from 1 to org-mark-ring-length do
12933 (push (make-marker) org-mark-ring))
12934 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
12935 org-mark-ring)
12937 (defun org-mark-ring-push (&optional pos buffer)
12938 "Put the current position or POS into the mark ring and rotate it."
12939 (interactive)
12940 (setq pos (or pos (point)))
12941 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
12942 (move-marker (car org-mark-ring)
12943 (or pos (point))
12944 (or buffer (current-buffer)))
12945 (message "%s"
12946 (substitute-command-keys
12947 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
12949 (defun org-mark-ring-goto (&optional n)
12950 "Jump to the previous position in the mark ring.
12951 With prefix arg N, jump back that many stored positions. When
12952 called several times in succession, walk through the entire ring.
12953 Org-mode commands jumping to a different position in the current file,
12954 or to another Org-mode file, automatically push the old position
12955 onto the ring."
12956 (interactive "p")
12957 (let (p m)
12958 (if (eq last-command this-command)
12959 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
12960 (setq p org-mark-ring))
12961 (setq org-mark-ring-last-goto p)
12962 (setq m (car p))
12963 (switch-to-buffer (marker-buffer m))
12964 (goto-char m)
12965 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
12967 (defun org-remove-angle-brackets (s)
12968 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
12969 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
12971 (defun org-add-angle-brackets (s)
12972 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
12973 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
12976 ;;; Following specific links
12978 (defun org-follow-timestamp-link ()
12979 (cond
12980 ((org-at-date-range-p t)
12981 (let ((org-agenda-start-on-weekday)
12982 (t1 (match-string 1))
12983 (t2 (match-string 2)))
12984 (setq t1 (time-to-days (org-time-string-to-time t1))
12985 t2 (time-to-days (org-time-string-to-time t2)))
12986 (org-agenda-list nil t1 (1+ (- t2 t1)))))
12987 ((org-at-timestamp-p t)
12988 (org-agenda-list nil (time-to-days (org-time-string-to-time
12989 (substring (match-string 1) 0 10)))
12991 (t (error "This should not happen"))))
12994 (defun org-follow-bbdb-link (name)
12995 "Follow a BBDB link to NAME."
12996 (require 'bbdb)
12997 (let ((inhibit-redisplay (not debug-on-error))
12998 (bbdb-electric-p nil))
12999 (catch 'exit
13000 ;; Exact match on name
13001 (bbdb-name (concat "\\`" name "\\'") nil)
13002 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13003 ;; Exact match on name
13004 (bbdb-company (concat "\\`" name "\\'") nil)
13005 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13006 ;; Partial match on name
13007 (bbdb-name name nil)
13008 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13009 ;; Partial match on company
13010 (bbdb-company name nil)
13011 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13012 ;; General match including network address and notes
13013 (bbdb name nil)
13014 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
13015 (delete-window (get-buffer-window "*BBDB*"))
13016 (error "No matching BBDB record")))))
13018 (defun org-follow-info-link (name)
13019 "Follow an info file & node link to NAME."
13020 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
13021 (string-match "\\(.*\\)" name))
13022 (progn
13023 (require 'info)
13024 (if (match-string 2 name) ; If there isn't a node, choose "Top"
13025 (Info-find-node (match-string 1 name) (match-string 2 name))
13026 (Info-find-node (match-string 1 name) "Top")))
13027 (message "Could not open: %s" name)))
13029 (defun org-follow-gnus-link (&optional group article)
13030 "Follow a Gnus link to GROUP and ARTICLE."
13031 (require 'gnus)
13032 (funcall (cdr (assq 'gnus org-link-frame-setup)))
13033 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
13034 (cond ((and group article)
13035 (gnus-group-read-group 1 nil group)
13036 (gnus-summary-goto-article (string-to-number article) nil t))
13037 (group (gnus-group-jump-to-group group))))
13039 (defun org-follow-vm-link (&optional folder article readonly)
13040 "Follow a VM link to FOLDER and ARTICLE."
13041 (require 'vm)
13042 (setq article (org-add-angle-brackets article))
13043 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
13044 ;; ange-ftp or efs or tramp access
13045 (let ((user (or (match-string 1 folder) (user-login-name)))
13046 (host (match-string 2 folder))
13047 (file (match-string 3 folder)))
13048 (cond
13049 ((featurep 'tramp)
13050 ;; use tramp to access the file
13051 (if (featurep 'xemacs)
13052 (setq folder (format "[%s@%s]%s" user host file))
13053 (setq folder (format "/%s@%s:%s" user host file))))
13055 ;; use ange-ftp or efs
13056 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
13057 (setq folder (format "/%s@%s:%s" user host file))))))
13058 (when folder
13059 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
13060 (sit-for 0.1)
13061 (when article
13062 (vm-select-folder-buffer)
13063 (widen)
13064 (let ((case-fold-search t))
13065 (goto-char (point-min))
13066 (if (not (re-search-forward
13067 (concat "^" "message-id: *" (regexp-quote article))))
13068 (error "Could not find the specified message in this folder"))
13069 (vm-isearch-update)
13070 (vm-isearch-narrow)
13071 (vm-beginning-of-message)
13072 (vm-summarize)))))
13074 (defun org-follow-wl-link (folder article)
13075 "Follow a Wanderlust link to FOLDER and ARTICLE."
13076 (if (and (string= folder "%")
13077 article
13078 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
13079 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
13080 ;; Thus, we recompose folder and article ids.
13081 (setq folder (format "%s#%s" folder (match-string 1 article))
13082 article (match-string 3 article)))
13083 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
13084 (error "No such folder: %s" folder))
13085 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
13086 (and article
13087 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
13088 (wl-summary-redisplay)))
13090 (defun org-follow-rmail-link (folder article)
13091 "Follow an RMAIL link to FOLDER and ARTICLE."
13092 (setq article (org-add-angle-brackets article))
13093 (let (message-number)
13094 (save-excursion
13095 (save-window-excursion
13096 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13097 (setq message-number
13098 (save-restriction
13099 (widen)
13100 (goto-char (point-max))
13101 (if (re-search-backward
13102 (concat "^Message-ID:\\s-+" (regexp-quote
13103 (or article "")))
13104 nil t)
13105 (rmail-what-message))))))
13106 (if message-number
13107 (progn
13108 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13109 (rmail-show-message message-number)
13110 message-number)
13111 (error "Message not found"))))
13113 ;;; mh-e integration based on planner-mode
13114 (defun org-mhe-get-message-real-folder ()
13115 "Return the name of the current message real folder, so if you use
13116 sequences, it will now work."
13117 (save-excursion
13118 (let* ((folder
13119 (if (equal major-mode 'mh-folder-mode)
13120 mh-current-folder
13121 ;; Refer to the show buffer
13122 mh-show-folder-buffer))
13123 (end-index
13124 (if (boundp 'mh-index-folder)
13125 (min (length mh-index-folder) (length folder))))
13127 ;; a simple test on mh-index-data does not work, because
13128 ;; mh-index-data is always nil in a show buffer.
13129 (if (and (boundp 'mh-index-folder)
13130 (string= mh-index-folder (substring folder 0 end-index)))
13131 (if (equal major-mode 'mh-show-mode)
13132 (save-window-excursion
13133 (let (pop-up-frames)
13134 (when (buffer-live-p (get-buffer folder))
13135 (progn
13136 (pop-to-buffer folder)
13137 (org-mhe-get-message-folder-from-index)
13140 (org-mhe-get-message-folder-from-index)
13142 folder
13146 (defun org-mhe-get-message-folder-from-index ()
13147 "Returns the name of the message folder in a index folder buffer."
13148 (save-excursion
13149 (mh-index-previous-folder)
13150 (re-search-forward "^\\(+.*\\)$" nil t)
13151 (message "%s" (match-string 1))))
13153 (defun org-mhe-get-message-folder ()
13154 "Return the name of the current message folder. Be careful if you
13155 use sequences."
13156 (save-excursion
13157 (if (equal major-mode 'mh-folder-mode)
13158 mh-current-folder
13159 ;; Refer to the show buffer
13160 mh-show-folder-buffer)))
13162 (defun org-mhe-get-message-num ()
13163 "Return the number of the current message. Be careful if you
13164 use sequences."
13165 (save-excursion
13166 (if (equal major-mode 'mh-folder-mode)
13167 (mh-get-msg-num nil)
13168 ;; Refer to the show buffer
13169 (mh-show-buffer-message-number))))
13171 (defun org-mhe-get-header (header)
13172 "Return a header of the message in folder mode. This will create a
13173 show buffer for the corresponding message. If you have a more clever
13174 idea..."
13175 (let* ((folder (org-mhe-get-message-folder))
13176 (num (org-mhe-get-message-num))
13177 (buffer (get-buffer-create (concat "show-" folder)))
13178 (header-field))
13179 (with-current-buffer buffer
13180 (mh-display-msg num folder)
13181 (if (equal major-mode 'mh-folder-mode)
13182 (mh-header-display)
13183 (mh-show-header-display))
13184 (set-buffer buffer)
13185 (setq header-field (mh-get-header-field header))
13186 (if (equal major-mode 'mh-folder-mode)
13187 (mh-show)
13188 (mh-show-show))
13189 header-field)))
13191 (defun org-follow-mhe-link (folder article)
13192 "Follow an MHE link to FOLDER and ARTICLE.
13193 If ARTICLE is nil FOLDER is shown. If the configuration variable
13194 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
13195 ARTICLE is searched in all folders. Indexed searches (swish++,
13196 namazu, and others supported by MH-E) will always search in all
13197 folders."
13198 (require 'mh-e)
13199 (require 'mh-search)
13200 (require 'mh-utils)
13201 (mh-find-path)
13202 (if (not article)
13203 (mh-visit-folder (mh-normalize-folder-name folder))
13204 (setq article (org-add-angle-brackets article))
13205 (mh-search-choose)
13206 (if (equal mh-searcher 'pick)
13207 (progn
13208 (mh-search folder (list "--message-id" article))
13209 (when (and org-mhe-search-all-folders
13210 (not (org-mhe-get-message-real-folder)))
13211 (kill-this-buffer)
13212 (mh-search "+" (list "--message-id" article))))
13213 (mh-search "+" article))
13214 (if (org-mhe-get-message-real-folder)
13215 (mh-show-msg 1)
13216 (kill-this-buffer)
13217 (error "Message not found"))))
13219 ;;; BibTeX links
13221 ;; Use the custom search meachnism to construct and use search strings for
13222 ;; file links to BibTeX database entries.
13224 (defun org-create-file-search-in-bibtex ()
13225 "Create the search string and description for a BibTeX database entry."
13226 (when (eq major-mode 'bibtex-mode)
13227 ;; yes, we want to construct this search string.
13228 ;; Make a good description for this entry, using names, year and the title
13229 ;; Put it into the `description' variable which is dynamically scoped.
13230 (let ((bibtex-autokey-names 1)
13231 (bibtex-autokey-names-stretch 1)
13232 (bibtex-autokey-name-case-convert-function 'identity)
13233 (bibtex-autokey-name-separator " & ")
13234 (bibtex-autokey-additional-names " et al.")
13235 (bibtex-autokey-year-length 4)
13236 (bibtex-autokey-name-year-separator " ")
13237 (bibtex-autokey-titlewords 3)
13238 (bibtex-autokey-titleword-separator " ")
13239 (bibtex-autokey-titleword-case-convert-function 'identity)
13240 (bibtex-autokey-titleword-length 'infty)
13241 (bibtex-autokey-year-title-separator ": "))
13242 (setq description (bibtex-generate-autokey)))
13243 ;; Now parse the entry, get the key and return it.
13244 (save-excursion
13245 (bibtex-beginning-of-entry)
13246 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13248 (defun org-execute-file-search-in-bibtex (s)
13249 "Find the link search string S as a key for a database entry."
13250 (when (eq major-mode 'bibtex-mode)
13251 ;; Yes, we want to do the search in this file.
13252 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13253 (goto-char (point-min))
13254 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13255 (regexp-quote s) "[ \t\n]*,") nil t)
13256 (goto-char (match-beginning 0)))
13257 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13258 ;; Use double prefix to indicate that any web link should be browsed
13259 (let ((b (current-buffer)) (p (point)))
13260 ;; Restore the window configuration because we just use the web link
13261 (set-window-configuration org-window-config-before-follow-link)
13262 (save-excursion (set-buffer b) (goto-char p)
13263 (bibtex-url)))
13264 (recenter 0)) ; Move entry start to beginning of window
13265 ;; return t to indicate that the search is done.
13268 ;; Finally add the functions to the right hooks.
13269 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13270 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13272 ;; end of Bibtex link setup
13274 ;;; Following file links
13276 (defun org-open-file (path &optional in-emacs line search)
13277 "Open the file at PATH.
13278 First, this expands any special file name abbreviations. Then the
13279 configuration variable `org-file-apps' is checked if it contains an
13280 entry for this file type, and if yes, the corresponding command is launched.
13281 If no application is found, Emacs simply visits the file.
13282 With optional argument IN-EMACS, Emacs will visit the file.
13283 Optional LINE specifies a line to go to, optional SEARCH a string to
13284 search for. If LINE or SEARCH is given, the file will always be
13285 opened in Emacs.
13286 If the file does not exist, an error is thrown."
13287 (setq in-emacs (or in-emacs line search))
13288 (let* ((file (if (equal path "")
13289 buffer-file-name
13290 (substitute-in-file-name (expand-file-name path))))
13291 (apps (append org-file-apps (org-default-apps)))
13292 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13293 (dirp (if remp nil (file-directory-p file)))
13294 (dfile (downcase file))
13295 (old-buffer (current-buffer))
13296 (old-pos (point))
13297 (old-mode major-mode)
13298 ext cmd)
13299 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13300 (setq ext (match-string 1 dfile))
13301 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13302 (setq ext (match-string 1 dfile))))
13303 (if in-emacs
13304 (setq cmd 'emacs)
13305 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13306 (and dirp (cdr (assoc 'directory apps)))
13307 (cdr (assoc ext apps))
13308 (cdr (assoc t apps)))))
13309 (when (eq cmd 'mailcap)
13310 (require 'mailcap)
13311 (mailcap-parse-mailcaps)
13312 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13313 (command (mailcap-mime-info mime-type)))
13314 (if (stringp command)
13315 (setq cmd command)
13316 (setq cmd 'emacs))))
13317 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13318 (not (file-exists-p file))
13319 (not org-open-non-existing-files))
13320 (error "No such file: %s" file))
13321 (cond
13322 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13323 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13324 (while (string-match "['\"]%s['\"]" cmd)
13325 (setq cmd (replace-match "%s" t t cmd)))
13326 (while (string-match "%s" cmd)
13327 (setq cmd (replace-match
13328 (save-match-data (shell-quote-argument file))
13329 t t cmd)))
13330 (save-window-excursion
13331 (start-process-shell-command cmd nil cmd)))
13332 ((or (stringp cmd)
13333 (eq cmd 'emacs))
13334 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13335 (widen)
13336 (if line (goto-line line)
13337 (if search (org-link-search search))))
13338 ((consp cmd)
13339 (eval cmd))
13340 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13341 (and (org-mode-p) (eq old-mode 'org-mode)
13342 (or (not (equal old-buffer (current-buffer)))
13343 (not (equal old-pos (point))))
13344 (org-mark-ring-push old-pos old-buffer))))
13346 (defun org-default-apps ()
13347 "Return the default applications for this operating system."
13348 (cond
13349 ((eq system-type 'darwin)
13350 org-file-apps-defaults-macosx)
13351 ((eq system-type 'windows-nt)
13352 org-file-apps-defaults-windowsnt)
13353 (t org-file-apps-defaults-gnu)))
13355 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13356 (defun org-file-remote-p (file)
13357 "Test whether FILE specifies a location on a remote system.
13358 Return non-nil if the location is indeed remote.
13360 For example, the filename \"/user@host:/foo\" specifies a location
13361 on the system \"/user@host:\"."
13362 (cond ((fboundp 'file-remote-p)
13363 (file-remote-p file))
13364 ((fboundp 'tramp-handle-file-remote-p)
13365 (tramp-handle-file-remote-p file))
13366 ((and (boundp 'ange-ftp-name-format)
13367 (string-match (car ange-ftp-name-format) file))
13369 (t nil)))
13372 ;;;; Hooks for remember.el, and refiling
13374 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13375 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13377 ;;;###autoload
13378 (defun org-remember-insinuate ()
13379 "Setup remember.el for use wiht Org-mode."
13380 (require 'remember)
13381 (setq remember-annotation-functions '(org-remember-annotation))
13382 (setq remember-handler-functions '(org-remember-handler))
13383 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13385 ;;;###autoload
13386 (defun org-remember-annotation ()
13387 "Return a link to the current location as an annotation for remember.el.
13388 If you are using Org-mode files as target for data storage with
13389 remember.el, then the annotations should include a link compatible with the
13390 conventions in Org-mode. This function returns such a link."
13391 (org-store-link nil))
13393 (defconst org-remember-help
13394 "Select a destination location for the note.
13395 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13396 RET on headline -> Store as sublevel entry to current headline
13397 RET at beg-of-buf -> Append to file as level 2 headline
13398 <left>/<right> -> before/after current headline, same headings level")
13400 (defvar org-remember-previous-location nil)
13401 (defvar org-force-remember-template-char) ;; dynamically scoped
13403 (defun org-select-remember-template (&optional use-char)
13404 (when org-remember-templates
13405 (let* ((templates (mapcar (lambda (x)
13406 (if (stringp (car x))
13407 (append (list (nth 1 x) (car x)) (cddr x))
13408 (append (list (car x) "") (cdr x))))
13409 org-remember-templates))
13410 (char (or use-char
13411 (cond
13412 ((= (length templates) 1)
13413 (caar templates))
13414 ((and (boundp 'org-force-remember-template-char)
13415 org-force-remember-template-char)
13416 (if (stringp org-force-remember-template-char)
13417 (string-to-char org-force-remember-template-char)
13418 org-force-remember-template-char))
13420 (message "Select template: %s"
13421 (mapconcat
13422 (lambda (x)
13423 (cond
13424 ((not (string-match "\\S-" (nth 1 x)))
13425 (format "[%c]" (car x)))
13426 ((equal (downcase (car x))
13427 (downcase (aref (nth 1 x) 0)))
13428 (format "[%c]%s" (car x)
13429 (substring (nth 1 x) 1)))
13430 (t (format "[%c]%s" (car x) (nth 1 x)))))
13431 templates " "))
13432 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13433 (when (equal char0 ?\C-g)
13434 (jump-to-register remember-register)
13435 (kill-buffer remember-buffer))
13436 char0))))))
13437 (cddr (assoc char templates)))))
13439 (defvar x-last-selected-text)
13440 (defvar x-last-selected-text-primary)
13442 ;;;###autoload
13443 (defun org-remember-apply-template (&optional use-char skip-interactive)
13444 "Initialize *remember* buffer with template, invoke `org-mode'.
13445 This function should be placed into `remember-mode-hook' and in fact requires
13446 to be run from that hook to function properly."
13447 (if org-remember-templates
13448 (let* ((entry (org-select-remember-template use-char))
13449 (tpl (car entry))
13450 (plist-p (if org-store-link-plist t nil))
13451 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13452 (string-match "\\S-" (nth 1 entry)))
13453 (nth 1 entry)
13454 org-default-notes-file))
13455 (headline (nth 2 entry))
13456 (v-c (or (and (eq window-system 'x)
13457 (fboundp 'x-cut-buffer-or-selection-value)
13458 (x-cut-buffer-or-selection-value))
13459 (org-bound-and-true-p x-last-selected-text)
13460 (org-bound-and-true-p x-last-selected-text-primary)
13461 (and (> (length kill-ring) 0) (current-kill 0))))
13462 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13463 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13464 (v-u (concat "[" (substring v-t 1 -1) "]"))
13465 (v-U (concat "[" (substring v-T 1 -1) "]"))
13466 ;; `initial' and `annotation' are bound in `remember'
13467 (v-i (if (boundp 'initial) initial))
13468 (v-a (if (and (boundp 'annotation) annotation)
13469 (if (equal annotation "[[]]") "" annotation)
13470 ""))
13471 (v-A (if (and v-a
13472 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13473 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13474 v-a))
13475 (v-n user-full-name)
13476 (org-startup-folded nil)
13477 org-time-was-given org-end-time-was-given x
13478 prompt completions char time pos default histvar)
13479 (setq org-store-link-plist
13480 (append (list :annotation v-a :initial v-i)
13481 org-store-link-plist))
13482 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13483 (erase-buffer)
13484 (insert (substitute-command-keys
13485 (format
13486 "## Filing location: Select interactively, default, or last used:
13487 ## %s to select file and header location interactively.
13488 ## %s \"%s\" -> \"* %s\"
13489 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13490 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13491 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13492 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13493 (abbreviate-file-name (or file org-default-notes-file))
13494 (or headline "")
13495 (or (car org-remember-previous-location) "???")
13496 (or (cdr org-remember-previous-location) "???"))))
13497 (insert tpl) (goto-char (point-min))
13498 ;; Simple %-escapes
13499 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13500 (when (and initial (equal (match-string 0) "%i"))
13501 (save-match-data
13502 (let* ((lead (buffer-substring
13503 (point-at-bol) (match-beginning 0))))
13504 (setq v-i (mapconcat 'identity
13505 (org-split-string initial "\n")
13506 (concat "\n" lead))))))
13507 (replace-match
13508 (or (eval (intern (concat "v-" (match-string 1)))) "")
13509 t t))
13511 ;; %[] Insert contents of a file.
13512 (goto-char (point-min))
13513 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13514 (let ((start (match-beginning 0))
13515 (end (match-end 0))
13516 (filename (expand-file-name (match-string 1))))
13517 (goto-char start)
13518 (delete-region start end)
13519 (condition-case error
13520 (insert-file-contents filename)
13521 (error (insert (format "%%![Couldn't insert %s: %s]"
13522 filename error))))))
13523 ;; %() embedded elisp
13524 (goto-char (point-min))
13525 (while (re-search-forward "%\\((.+)\\)" nil t)
13526 (goto-char (match-beginning 0))
13527 (let ((template-start (point)))
13528 (forward-char 1)
13529 (let ((result
13530 (condition-case error
13531 (eval (read (current-buffer)))
13532 (error (format "%%![Error: %s]" error)))))
13533 (delete-region template-start (point))
13534 (insert result))))
13536 ;; From the property list
13537 (when plist-p
13538 (goto-char (point-min))
13539 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13540 (and (setq x (or (plist-get org-store-link-plist
13541 (intern (match-string 1))) ""))
13542 (replace-match x t t))))
13544 ;; Turn on org-mode in the remember buffer, set local variables
13545 (org-mode)
13546 (org-set-local 'org-finish-function 'org-remember-finalize)
13547 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13548 (org-set-local 'org-default-notes-file file))
13549 (if (and headline (stringp headline) (string-match "\\S-" headline))
13550 (org-set-local 'org-remember-default-headline headline))
13551 ;; Interactive template entries
13552 (goto-char (point-min))
13553 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGuUtT]\\)?" nil t)
13554 (setq char (if (match-end 3) (match-string 3))
13555 prompt (if (match-end 2) (match-string 2)))
13556 (goto-char (match-beginning 0))
13557 (replace-match "")
13558 (setq completions nil default nil)
13559 (when prompt
13560 (setq completions (org-split-string prompt "|")
13561 prompt (pop completions)
13562 default (car completions)
13563 histvar (intern (concat
13564 "org-remember-template-prompt-history::"
13565 (or prompt "")))
13566 completions (mapcar 'list completions)))
13567 (cond
13568 ((member char '("G" "g"))
13569 (let* ((org-last-tags-completion-table
13570 (org-global-tags-completion-table
13571 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13572 (org-add-colon-after-tag-completion t)
13573 (ins (completing-read
13574 (if prompt (concat prompt ": ") "Tags: ")
13575 'org-tags-completion-function nil nil nil
13576 'org-tags-history)))
13577 (setq ins (mapconcat 'identity
13578 (org-split-string ins (org-re "[^[:alnum:]_@]+"))
13579 ":"))
13580 (when (string-match "\\S-" ins)
13581 (or (equal (char-before) ?:) (insert ":"))
13582 (insert ins)
13583 (or (equal (char-after) ?:) (insert ":")))))
13584 (char
13585 (setq org-time-was-given (equal (upcase char) char))
13586 (setq time (org-read-date (equal (upcase char) "U") t nil
13587 prompt))
13588 (org-insert-time-stamp time org-time-was-given
13589 (member char '("u" "U"))
13590 nil nil (list org-end-time-was-given)))
13592 (insert (org-completing-read
13593 (concat (if prompt prompt "Enter string")
13594 (if default (concat " [" default "]"))
13595 ": ")
13596 completions nil nil nil histvar default)))))
13597 (goto-char (point-min))
13598 (if (re-search-forward "%\\?" nil t)
13599 (replace-match "")
13600 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13601 (org-mode)
13602 (org-set-local 'org-finish-function 'org-remember-finalize))
13603 (when (save-excursion
13604 (goto-char (point-min))
13605 (re-search-forward "%!" nil t))
13606 (replace-match "")
13607 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13609 (defun org-remember-finish-immediately ()
13610 "File remember note immediately.
13611 This should be run in `post-command-hook' and will remove itself
13612 from that hook."
13613 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13614 (when org-finish-function
13615 (funcall org-finish-function)))
13617 (defvar org-clock-marker) ; Defined below
13618 (defun org-remember-finalize ()
13619 "Finalize the remember process."
13620 (unless (fboundp 'remember-finalize)
13621 (defalias 'remember-finalize 'remember-buffer))
13622 (when (and org-clock-marker
13623 (equal (marker-buffer org-clock-marker) (current-buffer)))
13624 ;; FIXME: test this, this is w/o notetaking!
13625 (let (org-log-done) (org-clock-out)))
13626 (when buffer-file-name
13627 (save-buffer)
13628 (setq buffer-file-name nil))
13629 (remember-finalize))
13631 ;;;###autoload
13632 (defun org-remember (&optional goto org-force-remember-template-char)
13633 "Call `remember'. If this is already a remember buffer, re-apply template.
13634 If there is an active region, make sure remember uses it as initial content
13635 of the remember buffer.
13637 When called interactively with a `C-u' prefix argument GOTO, don't remember
13638 anything, just go to the file/headline where the selected template usually
13639 stores its notes. With a double prefix arg `C-u C-u', go to the last
13640 note stored by remember.
13642 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13643 associated with a template in `org-remember-templates'."
13644 (interactive "P")
13645 (cond
13646 ((equal goto '(4)) (org-go-to-remember-target))
13647 ((equal goto '(16)) (org-remember-goto-last-stored))
13649 (if (memq org-finish-function '(remember-buffer remember-finalize))
13650 (progn
13651 (when (< (length org-remember-templates) 2)
13652 (error "No other template available"))
13653 (erase-buffer)
13654 (let ((annotation (plist-get org-store-link-plist :annotation))
13655 (initial (plist-get org-store-link-plist :initial)))
13656 (org-remember-apply-template))
13657 (message "Press C-c C-c to remember data"))
13658 (if (org-region-active-p)
13659 (remember (buffer-substring (point) (mark)))
13660 (call-interactively 'remember))))))
13662 (defun org-remember-goto-last-stored ()
13663 "Go to the location where the last remember note was stored."
13664 (interactive)
13665 (bookmark-jump "org-remember-last-stored")
13666 (message "This is the last note stored by remember"))
13668 (defun org-go-to-remember-target (&optional template-key)
13669 "Go to the target location of a remember template.
13670 The user is queried for the template."
13671 (interactive)
13672 (let* ((entry (org-select-remember-template template-key))
13673 (file (nth 1 entry))
13674 (heading (nth 2 entry))
13675 visiting)
13676 (unless (and file (stringp file) (string-match "\\S-" file))
13677 (setq file org-default-notes-file))
13678 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13679 (setq heading org-remember-default-headline))
13680 (setq visiting (org-find-base-buffer-visiting file))
13681 (if (not visiting) (find-file-noselect file))
13682 (switch-to-buffer (or visiting (get-file-buffer file)))
13683 (widen)
13684 (goto-char (point-min))
13685 (if (re-search-forward
13686 (concat "^\\*+[ \t]+" (regexp-quote heading)
13687 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13688 nil t)
13689 (goto-char (match-beginning 0))
13690 (error "Target headline not found: %s" heading))))
13692 (defvar org-note-abort nil) ; dynamically scoped
13694 ;;;###autoload
13695 (defun org-remember-handler ()
13696 "Store stuff from remember.el into an org file.
13697 First prompts for an org file. If the user just presses return, the value
13698 of `org-default-notes-file' is used.
13699 Then the command offers the headings tree of the selected file in order to
13700 file the text at a specific location.
13701 You can either immediately press RET to get the note appended to the
13702 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13703 find a better place. Then press RET or <left> or <right> in insert the note.
13705 Key Cursor position Note gets inserted
13706 -----------------------------------------------------------------------------
13707 RET buffer-start as level 1 heading at end of file
13708 RET on headline as sublevel of the heading at cursor
13709 RET no heading at cursor position, level taken from context.
13710 Or use prefix arg to specify level manually.
13711 <left> on headline as same level, before current heading
13712 <right> on headline as same level, after current heading
13714 So the fastest way to store the note is to press RET RET to append it to
13715 the default file. This way your current train of thought is not
13716 interrupted, in accordance with the principles of remember.el.
13717 You can also get the fast execution without prompting by using
13718 C-u C-c C-c to exit the remember buffer. See also the variable
13719 `org-remember-store-without-prompt'.
13721 Before being stored away, the function ensures that the text has a
13722 headline, i.e. a first line that starts with a \"*\". If not, a headline
13723 is constructed from the current date and some additional data.
13725 If the variable `org-adapt-indentation' is non-nil, the entire text is
13726 also indented so that it starts in the same column as the headline
13727 \(i.e. after the stars).
13729 See also the variable `org-reverse-note-order'."
13730 (goto-char (point-min))
13731 (while (looking-at "^[ \t]*\n\\|^##.*\n")
13732 (replace-match ""))
13733 (goto-char (point-max))
13734 (beginning-of-line 1)
13735 (while (looking-at "[ \t]*$\\|##.*")
13736 (delete-region (1- (point)) (point-max))
13737 (beginning-of-line 1))
13738 (catch 'quit
13739 (if org-note-abort (throw 'quit nil))
13740 (let* ((txt (buffer-substring (point-min) (point-max)))
13741 (fastp (org-xor (equal current-prefix-arg '(4))
13742 org-remember-store-without-prompt))
13743 (file (cond
13744 (fastp org-default-notes-file)
13745 ((and (eq org-remember-interactive-interface 'refile)
13746 org-refile-targets)
13747 org-default-notes-file)
13748 ((not (and (equal current-prefix-arg '(16))
13749 org-remember-previous-location))
13750 (org-get-org-file))))
13751 (heading org-remember-default-headline)
13752 (visiting (and file (org-find-base-buffer-visiting file)))
13753 (org-startup-folded nil)
13754 (org-startup-align-all-tables nil)
13755 (org-goto-start-pos 1)
13756 spos exitcmd level indent reversed)
13757 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
13758 (setq file (car org-remember-previous-location)
13759 heading (cdr org-remember-previous-location)
13760 fastp t))
13761 (setq current-prefix-arg nil)
13762 (if (string-match "[ \t\n]+\\'" txt)
13763 (setq txt (replace-match "" t t txt)))
13764 ;; Modify text so that it becomes a nice subtree which can be inserted
13765 ;; into an org tree.
13766 (let* ((lines (split-string txt "\n"))
13767 first)
13768 (setq first (car lines) lines (cdr lines))
13769 (if (string-match "^\\*+ " first)
13770 ;; Is already a headline
13771 (setq indent nil)
13772 ;; We need to add a headline: Use time and first buffer line
13773 (setq lines (cons first lines)
13774 first (concat "* " (current-time-string)
13775 " (" (remember-buffer-desc) ")")
13776 indent " "))
13777 (if (and org-adapt-indentation indent)
13778 (setq lines (mapcar
13779 (lambda (x)
13780 (if (string-match "\\S-" x)
13781 (concat indent x) x))
13782 lines)))
13783 (setq txt (concat first "\n"
13784 (mapconcat 'identity lines "\n"))))
13785 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
13786 (setq txt (replace-match "\n\n" t t txt))
13787 (if (string-match "[ \t\n]*\\'" txt)
13788 (setq txt (replace-match "\n" t t txt))))
13789 ;; Put the modified text back into the remember buffer, for refile.
13790 (erase-buffer)
13791 (insert txt)
13792 (goto-char (point-min))
13793 (when (and (eq org-remember-interactive-interface 'refile)
13794 (not fastp))
13795 (org-refile nil (or visiting (find-file-noselect file)))
13796 (throw 'quit t))
13797 ;; Find the file
13798 (if (not visiting) (find-file-noselect file))
13799 (with-current-buffer (or visiting (get-file-buffer file))
13800 (unless (org-mode-p)
13801 (error "Target files for remember notes must be in Org-mode"))
13802 (save-excursion
13803 (save-restriction
13804 (widen)
13805 (and (goto-char (point-min))
13806 (not (re-search-forward "^\\* " nil t))
13807 (insert "\n* " (or heading "Notes") "\n"))
13808 (setq reversed (org-notes-order-reversed-p))
13810 ;; Find the default location
13811 (when (and heading (stringp heading) (string-match "\\S-" heading))
13812 (goto-char (point-min))
13813 (if (re-search-forward
13814 (concat "^\\*+[ \t]+" (regexp-quote heading)
13815 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13816 nil t)
13817 (setq org-goto-start-pos (match-beginning 0))
13818 (when fastp
13819 (goto-char (point-max))
13820 (unless (bolp) (newline))
13821 (insert "* " heading "\n")
13822 (setq org-goto-start-pos (point-at-bol 0)))))
13824 ;; Ask the User for a location, using the appropriate interface
13825 (cond
13826 (fastp (setq spos org-goto-start-pos
13827 exitcmd 'return))
13828 ((eq org-remember-interactive-interface 'outline)
13829 (setq spos (org-get-location (current-buffer)
13830 org-remember-help)
13831 exitcmd (cdr spos)
13832 spos (car spos)))
13833 ((eq org-remember-interactive-interface 'outline-path-completion)
13834 (let ((org-refile-targets '((nil . (:maxlevel . 10))))
13835 (org-refile-use-outline-path t))
13836 (setq spos (org-refile-get-location "Heading: ")
13837 exitcmd 'return
13838 spos (nth 3 spos))))
13839 (t (error "this should not hapen")))
13840 (if (not spos) (throw 'quit nil)) ; return nil to show we did
13841 ; not handle this note
13842 (goto-char spos)
13843 (cond ((org-on-heading-p t)
13844 (org-back-to-heading t)
13845 (setq level (funcall outline-level))
13846 (cond
13847 ((eq exitcmd 'return)
13848 ;; sublevel of current
13849 (setq org-remember-previous-location
13850 (cons (abbreviate-file-name file)
13851 (org-get-heading 'notags)))
13852 (if reversed
13853 (outline-next-heading)
13854 (org-end-of-subtree t)
13855 (if (not (bolp))
13856 (if (looking-at "[ \t]*\n")
13857 (beginning-of-line 2)
13858 (end-of-line 1)
13859 (insert "\n"))))
13860 (bookmark-set "org-remember-last-stored")
13861 (org-paste-subtree (org-get-legal-level level 1) txt))
13862 ((eq exitcmd 'left)
13863 ;; before current
13864 (bookmark-set "org-remember-last-stored")
13865 (org-paste-subtree level txt))
13866 ((eq exitcmd 'right)
13867 ;; after current
13868 (org-end-of-subtree t)
13869 (bookmark-set "org-remember-last-stored")
13870 (org-paste-subtree level txt))
13871 (t (error "This should not happen"))))
13873 ((and (bobp) (not reversed))
13874 ;; Put it at the end, one level below level 1
13875 (save-restriction
13876 (widen)
13877 (goto-char (point-max))
13878 (if (not (bolp)) (newline))
13879 (bookmark-set "org-remember-last-stored")
13880 (org-paste-subtree (org-get-legal-level 1 1) txt)))
13882 ((and (bobp) reversed)
13883 ;; Put it at the start, as level 1
13884 (save-restriction
13885 (widen)
13886 (goto-char (point-min))
13887 (re-search-forward "^\\*+ " nil t)
13888 (beginning-of-line 1)
13889 (bookmark-set "org-remember-last-stored")
13890 (org-paste-subtree 1 txt)))
13892 ;; Put it right there, with automatic level determined by
13893 ;; org-paste-subtree or from prefix arg
13894 (bookmark-set "org-remember-last-stored")
13895 (org-paste-subtree
13896 (if (numberp current-prefix-arg) current-prefix-arg)
13897 txt)))
13898 (when remember-save-after-remembering
13899 (save-buffer)
13900 (if (not visiting) (kill-buffer (current-buffer)))))))))
13902 t) ;; return t to indicate that we took care of this note.
13904 (defun org-get-org-file ()
13905 "Read a filename, with default directory `org-directory'."
13906 (let ((default (or org-default-notes-file remember-data-file)))
13907 (read-file-name (format "File name [%s]: " default)
13908 (file-name-as-directory org-directory)
13909 default)))
13911 (defun org-notes-order-reversed-p ()
13912 "Check if the current file should receive notes in reversed order."
13913 (cond
13914 ((not org-reverse-note-order) nil)
13915 ((eq t org-reverse-note-order) t)
13916 ((not (listp org-reverse-note-order)) nil)
13917 (t (catch 'exit
13918 (let ((all org-reverse-note-order)
13919 entry)
13920 (while (setq entry (pop all))
13921 (if (string-match (car entry) buffer-file-name)
13922 (throw 'exit (cdr entry))))
13923 nil)))))
13925 ;;; Refiling
13927 (defvar org-refile-target-table nil
13928 "The list of refile targets, created by `org-refile'.")
13930 (defvar org-agenda-new-buffers nil
13931 "Buffers created to visit agenda files.")
13933 (defun org-get-refile-targets (&optional default-buffer)
13934 "Produce a table with refile targets."
13935 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
13936 targets txt re files f desc descre)
13937 (with-current-buffer (or default-buffer (current-buffer))
13938 (while (setq entry (pop entries))
13939 (setq files (car entry) desc (cdr entry))
13940 (cond
13941 ((null files) (setq files (list (current-buffer))))
13942 ((eq files 'org-agenda-files)
13943 (setq files (org-agenda-files 'unrestricted)))
13944 ((and (symbolp files) (fboundp files))
13945 (setq files (funcall files)))
13946 ((and (symbolp files) (boundp files))
13947 (setq files (symbol-value files))))
13948 (if (stringp files) (setq files (list files)))
13949 (cond
13950 ((eq (car desc) :tag)
13951 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
13952 ((eq (car desc) :todo)
13953 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
13954 ((eq (car desc) :regexp)
13955 (setq descre (cdr desc)))
13956 ((eq (car desc) :level)
13957 (setq descre (concat "^\\*\\{" (number-to-string
13958 (if org-odd-levels-only
13959 (1- (* 2 (cdr desc)))
13960 (cdr desc)))
13961 "\\}[ \t]")))
13962 ((eq (car desc) :maxlevel)
13963 (setq descre (concat "^\\*\\{1," (number-to-string
13964 (if org-odd-levels-only
13965 (1- (* 2 (cdr desc)))
13966 (cdr desc)))
13967 "\\}[ \t]")))
13968 (t (error "Bad refiling target description %s" desc)))
13969 (while (setq f (pop files))
13970 (save-excursion
13971 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
13972 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
13973 (save-excursion
13974 (save-restriction
13975 (widen)
13976 (goto-char (point-min))
13977 (while (re-search-forward descre nil t)
13978 (goto-char (point-at-bol))
13979 (when (looking-at org-complex-heading-regexp)
13980 (setq txt (match-string 4)
13981 re (concat "^" (regexp-quote
13982 (buffer-substring (match-beginning 1)
13983 (match-end 4)))))
13984 (if (match-end 5) (setq re (concat re "[ \t]+"
13985 (regexp-quote
13986 (match-string 5)))))
13987 (setq re (concat re "[ \t]*$"))
13988 (when org-refile-use-outline-path
13989 (setq txt (mapconcat 'identity
13990 (append
13991 (if (eq org-refile-use-outline-path 'file)
13992 (list (file-name-nondirectory
13993 (buffer-file-name (buffer-base-buffer))))
13994 (if (eq org-refile-use-outline-path 'full-file-path)
13995 (list (buffer-file-name (buffer-base-buffer)))))
13996 (org-get-outline-path)
13997 (list txt))
13998 "/")))
13999 (push (list txt f re (point)) targets))
14000 (goto-char (point-at-eol))))))))
14001 (nreverse targets))))
14003 (defun org-get-outline-path ()
14004 "Return the outline path to the current entry, as a list."
14005 (let (rtn)
14006 (save-excursion
14007 (while (org-up-heading-safe)
14008 (when (looking-at org-complex-heading-regexp)
14009 (push (org-match-string-no-properties 4) rtn)))
14010 rtn)))
14012 (defvar org-refile-history nil
14013 "History for refiling operations.")
14015 (defun org-refile (&optional goto default-buffer)
14016 "Move the entry at point to another heading.
14017 The list of target headings is compiled using the information in
14018 `org-refile-targets', which see. This list is created upon first use, and
14019 you can update it by calling this command with a double prefix (`C-u C-u').
14020 FIXME: Can we find a better way of updating?
14022 At the target location, the entry is filed as a subitem of the target heading.
14023 Depending on `org-reverse-note-order', the new subitem will either be the
14024 first of the last subitem.
14026 With prefix arg GOTO, the command will only visit the target location,
14027 not actually move anything.
14028 With a double prefix `C-c C-c', go to the location where the last refiling
14029 operation has put the subtree.
14031 With a double prefix argument, the command can be used to jump to any
14032 heading in the current buffer."
14033 (interactive "P")
14034 (let* ((cbuf (current-buffer))
14035 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14036 (fname (and filename (file-truename filename)))
14037 pos it nbuf file re level reversed)
14038 (if (equal goto '(16))
14039 (org-refile-goto-last-stored)
14040 (when (setq it (org-refile-get-location
14041 (if goto "Goto: " "Refile to: ") default-buffer))
14042 (setq file (nth 1 it)
14043 re (nth 2 it)
14044 pos (nth 3 it))
14045 (setq nbuf (or (find-buffer-visiting file)
14046 (find-file-noselect file)))
14047 (if goto
14048 (progn
14049 (switch-to-buffer nbuf)
14050 (goto-char pos)
14051 (org-show-context 'org-goto))
14052 (org-copy-special)
14053 (save-excursion
14054 (set-buffer (setq nbuf (or (find-buffer-visiting file)
14055 (find-file-noselect file))))
14056 (setq reversed (org-notes-order-reversed-p))
14057 (save-excursion
14058 (save-restriction
14059 (widen)
14060 (goto-char pos)
14061 (looking-at outline-regexp)
14062 (setq level (org-get-legal-level (funcall outline-level) 1))
14063 (goto-char (or (save-excursion
14064 (if reversed
14065 (outline-next-heading)
14066 (outline-get-next-sibling)))
14067 (point-max)))
14068 (bookmark-set "org-refile-last-stored")
14069 (org-paste-subtree level))))
14070 (org-cut-special)
14071 (message "Entry refiled to \"%s\"" (car it)))))))
14073 (defun org-refile-goto-last-stored ()
14074 "Go to the location where the last refile was stored."
14075 (interactive)
14076 (bookmark-jump "org-refile-last-stored")
14077 (message "This is the location of the last refile"))
14079 (defun org-refile-get-location (&optional prompt default-buffer)
14080 "Prompt the user for a refile location, using PROMPT."
14081 (let ((org-refile-targets org-refile-targets)
14082 (org-refile-use-outline-path org-refile-use-outline-path))
14083 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
14084 (unless org-refile-target-table
14085 (error "No refile targets"))
14086 (let* ((cbuf (current-buffer))
14087 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14088 (fname (and filename (file-truename filename)))
14089 (tbl (mapcar
14090 (lambda (x)
14091 (if (not (equal fname (file-truename (nth 1 x))))
14092 (cons (concat (car x) " (" (file-name-nondirectory
14093 (nth 1 x)) ")")
14094 (cdr x))
14096 org-refile-target-table))
14097 (completion-ignore-case t)
14098 pos it nbuf file re level reversed)
14099 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
14100 tbl)))
14102 ;;;; Dynamic blocks
14104 (defun org-find-dblock (name)
14105 "Find the first dynamic block with name NAME in the buffer.
14106 If not found, stay at current position and return nil."
14107 (let (pos)
14108 (save-excursion
14109 (goto-char (point-min))
14110 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
14111 nil t)
14112 (match-beginning 0))))
14113 (if pos (goto-char pos))
14114 pos))
14116 (defconst org-dblock-start-re
14117 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
14118 "Matches the startline of a dynamic block, with parameters.")
14120 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
14121 "Matches the end of a dyhamic block.")
14123 (defun org-create-dblock (plist)
14124 "Create a dynamic block section, with parameters taken from PLIST.
14125 PLIST must containe a :name entry which is used as name of the block."
14126 (unless (bolp) (newline))
14127 (let ((name (plist-get plist :name)))
14128 (insert "#+BEGIN: " name)
14129 (while plist
14130 (if (eq (car plist) :name)
14131 (setq plist (cddr plist))
14132 (insert " " (prin1-to-string (pop plist)))))
14133 (insert "\n\n#+END:\n")
14134 (beginning-of-line -2)))
14136 (defun org-prepare-dblock ()
14137 "Prepare dynamic block for refresh.
14138 This empties the block, puts the cursor at the insert position and returns
14139 the property list including an extra property :name with the block name."
14140 (unless (looking-at org-dblock-start-re)
14141 (error "Not at a dynamic block"))
14142 (let* ((begdel (1+ (match-end 0)))
14143 (name (org-no-properties (match-string 1)))
14144 (params (append (list :name name)
14145 (read (concat "(" (match-string 3) ")")))))
14146 (unless (re-search-forward org-dblock-end-re nil t)
14147 (error "Dynamic block not terminated"))
14148 (delete-region begdel (match-beginning 0))
14149 (goto-char begdel)
14150 (open-line 1)
14151 params))
14153 (defun org-map-dblocks (&optional command)
14154 "Apply COMMAND to all dynamic blocks in the current buffer.
14155 If COMMAND is not given, use `org-update-dblock'."
14156 (let ((cmd (or command 'org-update-dblock))
14157 pos)
14158 (save-excursion
14159 (goto-char (point-min))
14160 (while (re-search-forward org-dblock-start-re nil t)
14161 (goto-char (setq pos (match-beginning 0)))
14162 (condition-case nil
14163 (funcall cmd)
14164 (error (message "Error during update of dynamic block")))
14165 (goto-char pos)
14166 (unless (re-search-forward org-dblock-end-re nil t)
14167 (error "Dynamic block not terminated"))))))
14169 (defun org-dblock-update (&optional arg)
14170 "User command for updating dynamic blocks.
14171 Update the dynamic block at point. With prefix ARG, update all dynamic
14172 blocks in the buffer."
14173 (interactive "P")
14174 (if arg
14175 (org-update-all-dblocks)
14176 (or (looking-at org-dblock-start-re)
14177 (org-beginning-of-dblock))
14178 (org-update-dblock)))
14180 (defun org-update-dblock ()
14181 "Update the dynamic block at point
14182 This means to empty the block, parse for parameters and then call
14183 the correct writing function."
14184 (save-window-excursion
14185 (let* ((pos (point))
14186 (line (org-current-line))
14187 (params (org-prepare-dblock))
14188 (name (plist-get params :name))
14189 (cmd (intern (concat "org-dblock-write:" name))))
14190 (message "Updating dynamic block `%s' at line %d..." name line)
14191 (funcall cmd params)
14192 (message "Updating dynamic block `%s' at line %d...done" name line)
14193 (goto-char pos))))
14195 (defun org-beginning-of-dblock ()
14196 "Find the beginning of the dynamic block at point.
14197 Error if there is no scuh block at point."
14198 (let ((pos (point))
14199 beg)
14200 (end-of-line 1)
14201 (if (and (re-search-backward org-dblock-start-re nil t)
14202 (setq beg (match-beginning 0))
14203 (re-search-forward org-dblock-end-re nil t)
14204 (> (match-end 0) pos))
14205 (goto-char beg)
14206 (goto-char pos)
14207 (error "Not in a dynamic block"))))
14209 (defun org-update-all-dblocks ()
14210 "Update all dynamic blocks in the buffer.
14211 This function can be used in a hook."
14212 (when (org-mode-p)
14213 (org-map-dblocks 'org-update-dblock)))
14216 ;;;; Completion
14218 (defconst org-additional-option-like-keywords
14219 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14220 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
14221 "BEGIN_EXAMPLE" "END_EXAMPLE"))
14223 (defun org-complete (&optional arg)
14224 "Perform completion on word at point.
14225 At the beginning of a headline, this completes TODO keywords as given in
14226 `org-todo-keywords'.
14227 If the current word is preceded by a backslash, completes the TeX symbols
14228 that are supported for HTML support.
14229 If the current word is preceded by \"#+\", completes special words for
14230 setting file options.
14231 In the line after \"#+STARTUP:, complete valid keywords.\"
14232 At all other locations, this simply calls the value of
14233 `org-completion-fallback-command'."
14234 (interactive "P")
14235 (org-without-partial-completion
14236 (catch 'exit
14237 (let* ((end (point))
14238 (beg1 (save-excursion
14239 (skip-chars-backward (org-re "[:alnum:]_@"))
14240 (point)))
14241 (beg (save-excursion
14242 (skip-chars-backward "a-zA-Z0-9_:$")
14243 (point)))
14244 (confirm (lambda (x) (stringp (car x))))
14245 (searchhead (equal (char-before beg) ?*))
14246 (tag (and (equal (char-before beg1) ?:)
14247 (equal (char-after (point-at-bol)) ?*)))
14248 (prop (and (equal (char-before beg1) ?:)
14249 (not (equal (char-after (point-at-bol)) ?*))))
14250 (texp (equal (char-before beg) ?\\))
14251 (link (equal (char-before beg) ?\[))
14252 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14253 beg)
14254 "#+"))
14255 (startup (string-match "^#\\+STARTUP:.*"
14256 (buffer-substring (point-at-bol) (point))))
14257 (completion-ignore-case opt)
14258 (type nil)
14259 (tbl nil)
14260 (table (cond
14261 (opt
14262 (setq type :opt)
14263 (append
14264 (mapcar
14265 (lambda (x)
14266 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14267 (cons (match-string 2 x) (match-string 1 x)))
14268 (org-split-string (org-get-current-options) "\n"))
14269 (mapcar 'list org-additional-option-like-keywords)))
14270 (startup
14271 (setq type :startup)
14272 org-startup-options)
14273 (link (append org-link-abbrev-alist-local
14274 org-link-abbrev-alist))
14275 (texp
14276 (setq type :tex)
14277 org-html-entities)
14278 ((string-match "\\`\\*+[ \t]+\\'"
14279 (buffer-substring (point-at-bol) beg))
14280 (setq type :todo)
14281 (mapcar 'list org-todo-keywords-1))
14282 (searchhead
14283 (setq type :searchhead)
14284 (save-excursion
14285 (goto-char (point-min))
14286 (while (re-search-forward org-todo-line-regexp nil t)
14287 (push (list
14288 (org-make-org-heading-search-string
14289 (match-string 3) t))
14290 tbl)))
14291 tbl)
14292 (tag (setq type :tag beg beg1)
14293 (or org-tag-alist (org-get-buffer-tags)))
14294 (prop (setq type :prop beg beg1)
14295 (mapcar 'list (org-buffer-property-keys)))
14296 (t (progn
14297 (call-interactively org-completion-fallback-command)
14298 (throw 'exit nil)))))
14299 (pattern (buffer-substring-no-properties beg end))
14300 (completion (try-completion pattern table confirm)))
14301 (cond ((eq completion t)
14302 (if (not (assoc (upcase pattern) table))
14303 (message "Already complete")
14304 (if (equal type :opt)
14305 (insert (substring (cdr (assoc (upcase pattern) table))
14306 (length pattern)))
14307 (if (memq type '(:tag :prop)) (insert ":")))))
14308 ((null completion)
14309 (message "Can't find completion for \"%s\"" pattern)
14310 (ding))
14311 ((not (string= pattern completion))
14312 (delete-region beg end)
14313 (if (string-match " +$" completion)
14314 (setq completion (replace-match "" t t completion)))
14315 (insert completion)
14316 (if (get-buffer-window "*Completions*")
14317 (delete-window (get-buffer-window "*Completions*")))
14318 (if (assoc completion table)
14319 (if (eq type :todo) (insert " ")
14320 (if (memq type '(:tag :prop)) (insert ":"))))
14321 (if (and (equal type :opt) (assoc completion table))
14322 (message "%s" (substitute-command-keys
14323 "Press \\[org-complete] again to insert example settings"))))
14325 (message "Making completion list...")
14326 (let ((list (sort (all-completions pattern table confirm)
14327 'string<)))
14328 (with-output-to-temp-buffer "*Completions*"
14329 (condition-case nil
14330 ;; Protection needed for XEmacs and emacs 21
14331 (display-completion-list list pattern)
14332 (error (display-completion-list list)))))
14333 (message "Making completion list...%s" "done")))))))
14335 ;;;; TODO, DEADLINE, Comments
14337 (defun org-toggle-comment ()
14338 "Change the COMMENT state of an entry."
14339 (interactive)
14340 (save-excursion
14341 (org-back-to-heading)
14342 (let (case-fold-search)
14343 (if (looking-at (concat outline-regexp
14344 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14345 (replace-match "" t t nil 1)
14346 (if (looking-at outline-regexp)
14347 (progn
14348 (goto-char (match-end 0))
14349 (insert org-comment-string " ")))))))
14351 (defvar org-last-todo-state-is-todo nil
14352 "This is non-nil when the last TODO state change led to a TODO state.
14353 If the last change removed the TODO tag or switched to DONE, then
14354 this is nil.")
14356 (defvar org-setting-tags nil) ; dynamically skiped
14358 ;; FIXME: better place
14359 (defun org-property-or-variable-value (var &optional inherit)
14360 "Check if there is a property fixing the value of VAR.
14361 If yes, return this value. If not, return the current value of the variable."
14362 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14363 (if (and prop (stringp prop) (string-match "\\S-" prop))
14364 (read prop)
14365 (symbol-value var))))
14367 (defun org-parse-local-options (string var)
14368 "Parse STRING for startup setting relevant for variable VAR."
14369 (let ((rtn (symbol-value var))
14370 e opts)
14371 (save-match-data
14372 (if (or (not string) (not (string-match "\\S-" string)))
14374 (setq opts (delq nil (mapcar (lambda (x)
14375 (setq e (assoc x org-startup-options))
14376 (if (eq (nth 1 e) var) e nil))
14377 (org-split-string string "[ \t]+"))))
14378 (if (not opts)
14380 (setq rtn nil)
14381 (while (setq e (pop opts))
14382 (if (not (nth 3 e))
14383 (setq rtn (nth 2 e))
14384 (if (not (listp rtn)) (setq rtn nil))
14385 (push (nth 2 e) rtn)))
14386 rtn)))))
14388 (defvar org-blocker-hook nil
14389 "Hook for functions that are allowed to block a state change.
14391 Each function gets as its single argument a property list, see
14392 `org-trigger-hook' for more information about this list.
14394 If any of the functions in this hook returns nil, the state change
14395 is blocked.")
14397 (defvar org-trigger-hook nil
14398 "Hook for functions that are triggered by a state change.
14400 Each function gets as its single argument a property list with at least
14401 the following elements:
14403 (:type type-of-change :position pos-at-entry-start
14404 :from old-state :to new-state)
14406 Depending on the type, more properties may be present.
14408 This mechanism is currently implemented for:
14410 TODO state changes
14411 ------------------
14412 :type todo-state-change
14413 :from previous state (keyword as a string), or nil
14414 :to new state (keyword as a string), or nil")
14417 (defun org-todo (&optional arg)
14418 "Change the TODO state of an item.
14419 The state of an item is given by a keyword at the start of the heading,
14420 like
14421 *** TODO Write paper
14422 *** DONE Call mom
14424 The different keywords are specified in the variable `org-todo-keywords'.
14425 By default the available states are \"TODO\" and \"DONE\".
14426 So for this example: when the item starts with TODO, it is changed to DONE.
14427 When it starts with DONE, the DONE is removed. And when neither TODO nor
14428 DONE are present, add TODO at the beginning of the heading.
14430 With C-u prefix arg, use completion to determine the new state.
14431 With numeric prefix arg, switch to that state.
14433 For calling through lisp, arg is also interpreted in the following way:
14434 'none -> empty state
14435 \"\"(empty string) -> switch to empty state
14436 'done -> switch to DONE
14437 'nextset -> switch to the next set of keywords
14438 'previousset -> switch to the previous set of keywords
14439 \"WAITING\" -> switch to the specified keyword, but only if it
14440 really is a member of `org-todo-keywords'."
14441 (interactive "P")
14442 (save-excursion
14443 (catch 'exit
14444 (org-back-to-heading)
14445 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14446 (or (looking-at (concat " +" org-todo-regexp " *"))
14447 (looking-at " *"))
14448 (let* ((match-data (match-data))
14449 (startpos (point-at-bol))
14450 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14451 (org-log-done (org-parse-local-options logging 'org-log-done))
14452 (org-log-repeat (org-parse-local-options logging 'org-log-repeat))
14453 (this (match-string 1))
14454 (hl-pos (match-beginning 0))
14455 (head (org-get-todo-sequence-head this))
14456 (ass (assoc head org-todo-kwd-alist))
14457 (interpret (nth 1 ass))
14458 (done-word (nth 3 ass))
14459 (final-done-word (nth 4 ass))
14460 (last-state (or this ""))
14461 (completion-ignore-case t)
14462 (member (member this org-todo-keywords-1))
14463 (tail (cdr member))
14464 (state (cond
14465 ((and org-todo-key-trigger
14466 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14467 (and (not arg) org-use-fast-todo-selection
14468 (not (eq org-use-fast-todo-selection 'prefix)))))
14469 ;; Use fast selection
14470 (org-fast-todo-selection))
14471 ((and (equal arg '(4))
14472 (or (not org-use-fast-todo-selection)
14473 (not org-todo-key-trigger)))
14474 ;; Read a state with completion
14475 (completing-read "State: " (mapcar (lambda(x) (list x))
14476 org-todo-keywords-1)
14477 nil t))
14478 ((eq arg 'right)
14479 (if this
14480 (if tail (car tail) nil)
14481 (car org-todo-keywords-1)))
14482 ((eq arg 'left)
14483 (if (equal member org-todo-keywords-1)
14485 (if this
14486 (nth (- (length org-todo-keywords-1) (length tail) 2)
14487 org-todo-keywords-1)
14488 (org-last org-todo-keywords-1))))
14489 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14490 (setq arg nil))) ; hack to fall back to cycling
14491 (arg
14492 ;; user or caller requests a specific state
14493 (cond
14494 ((equal arg "") nil)
14495 ((eq arg 'none) nil)
14496 ((eq arg 'done) (or done-word (car org-done-keywords)))
14497 ((eq arg 'nextset)
14498 (or (car (cdr (member head org-todo-heads)))
14499 (car org-todo-heads)))
14500 ((eq arg 'previousset)
14501 (let ((org-todo-heads (reverse org-todo-heads)))
14502 (or (car (cdr (member head org-todo-heads)))
14503 (car org-todo-heads))))
14504 ((car (member arg org-todo-keywords-1)))
14505 ((nth (1- (prefix-numeric-value arg))
14506 org-todo-keywords-1))))
14507 ((null member) (or head (car org-todo-keywords-1)))
14508 ((equal this final-done-word) nil) ;; -> make empty
14509 ((null tail) nil) ;; -> first entry
14510 ((eq interpret 'sequence)
14511 (car tail))
14512 ((memq interpret '(type priority))
14513 (if (eq this-command last-command)
14514 (car tail)
14515 (if (> (length tail) 0)
14516 (or done-word (car org-done-keywords))
14517 nil)))
14518 (t nil)))
14519 (next (if state (concat " " state " ") " "))
14520 (change-plist (list :type 'todo-state-change :from this :to state
14521 :position startpos))
14522 dostates)
14523 (when org-blocker-hook
14524 (unless (save-excursion
14525 (save-match-data
14526 (run-hook-with-args-until-failure
14527 'org-blocker-hook change-plist)))
14528 (if (interactive-p)
14529 (error "TODO state change from %s to %s blocked" this state)
14530 ;; fail silently
14531 (message "TODO state change from %s to %s blocked" this state)
14532 (throw 'exit nil))))
14533 (store-match-data match-data)
14534 (replace-match next t t)
14535 (unless (pos-visible-in-window-p hl-pos)
14536 (message "TODO state changed to %s" (org-trim next)))
14537 (unless head
14538 (setq head (org-get-todo-sequence-head state)
14539 ass (assoc head org-todo-kwd-alist)
14540 interpret (nth 1 ass)
14541 done-word (nth 3 ass)
14542 final-done-word (nth 4 ass)))
14543 (when (memq arg '(nextset previousset))
14544 (message "Keyword-Set %d/%d: %s"
14545 (- (length org-todo-sets) -1
14546 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14547 (length org-todo-sets)
14548 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14549 (setq org-last-todo-state-is-todo
14550 (not (member state org-done-keywords)))
14551 (when (and org-log-done (not (memq arg '(nextset previousset))))
14552 (setq dostates (and (listp org-log-done) (memq 'state org-log-done)
14553 (or (not org-todo-log-states)
14554 (member state org-todo-log-states))))
14556 (cond
14557 ((and state (member state org-not-done-keywords)
14558 (not (member this org-not-done-keywords)))
14559 ;; This is now a todo state and was not one before
14560 ;; Remove any CLOSED timestamp, and possibly log the state change
14561 (org-add-planning-info nil nil 'closed)
14562 (and dostates (org-add-log-maybe 'state state 'findpos)))
14563 ((and state dostates)
14564 ;; This is a non-nil state, and we need to log it
14565 (org-add-log-maybe 'state state 'findpos))
14566 ((and (member state org-done-keywords)
14567 (not (member this org-done-keywords)))
14568 ;; It is now done, and it was not done before
14569 (org-add-planning-info 'closed (org-current-time))
14570 (org-add-log-maybe 'done state 'findpos))))
14571 ;; Fixup tag positioning
14572 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14573 (run-hooks 'org-after-todo-state-change-hook)
14574 (and (member state org-done-keywords) (org-auto-repeat-maybe))
14575 (if (and arg (not (member state org-done-keywords)))
14576 (setq head (org-get-todo-sequence-head state)))
14577 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14578 ;; Fixup cursor location if close to the keyword
14579 (if (and (outline-on-heading-p)
14580 (not (bolp))
14581 (save-excursion (beginning-of-line 1)
14582 (looking-at org-todo-line-regexp))
14583 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14584 (progn
14585 (goto-char (or (match-end 2) (match-end 1)))
14586 (just-one-space)))
14587 (when org-trigger-hook
14588 (save-excursion
14589 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14591 (defun org-get-todo-sequence-head (kwd)
14592 "Return the head of the TODO sequence to which KWD belongs.
14593 If KWD is not set, check if there is a text property remembering the
14594 right sequence."
14595 (let (p)
14596 (cond
14597 ((not kwd)
14598 (or (get-text-property (point-at-bol) 'org-todo-head)
14599 (progn
14600 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14601 nil (point-at-eol)))
14602 (get-text-property p 'org-todo-head))))
14603 ((not (member kwd org-todo-keywords-1))
14604 (car org-todo-keywords-1))
14605 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14607 (defun org-fast-todo-selection ()
14608 "Fast TODO keyword selection with single keys.
14609 Returns the new TODO keyword, or nil if no state change should occur."
14610 (let* ((fulltable org-todo-key-alist)
14611 (done-keywords org-done-keywords) ;; needed for the faces.
14612 (maxlen (apply 'max (mapcar
14613 (lambda (x)
14614 (if (stringp (car x)) (string-width (car x)) 0))
14615 fulltable)))
14616 (expert nil)
14617 (fwidth (+ maxlen 3 1 3))
14618 (ncol (/ (- (window-width) 4) fwidth))
14619 tg cnt e c tbl
14620 groups ingroup)
14621 (save-window-excursion
14622 (if expert
14623 (set-buffer (get-buffer-create " *Org todo*"))
14624 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14625 (erase-buffer)
14626 (org-set-local 'org-done-keywords done-keywords)
14627 (setq tbl fulltable cnt 0)
14628 (while (setq e (pop tbl))
14629 (cond
14630 ((equal e '(:startgroup))
14631 (push '() groups) (setq ingroup t)
14632 (when (not (= cnt 0))
14633 (setq cnt 0)
14634 (insert "\n"))
14635 (insert "{ "))
14636 ((equal e '(:endgroup))
14637 (setq ingroup nil cnt 0)
14638 (insert "}\n"))
14640 (setq tg (car e) c (cdr e))
14641 (if ingroup (push tg (car groups)))
14642 (setq tg (org-add-props tg nil 'face
14643 (org-get-todo-face tg)))
14644 (if (and (= cnt 0) (not ingroup)) (insert " "))
14645 (insert "[" c "] " tg (make-string
14646 (- fwidth 4 (length tg)) ?\ ))
14647 (when (= (setq cnt (1+ cnt)) ncol)
14648 (insert "\n")
14649 (if ingroup (insert " "))
14650 (setq cnt 0)))))
14651 (insert "\n")
14652 (goto-char (point-min))
14653 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14654 (fit-window-to-buffer))
14655 (message "[a-z..]:Set [SPC]:clear")
14656 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14657 (cond
14658 ((or (= c ?\C-g)
14659 (and (= c ?q) (not (rassoc c fulltable))))
14660 (setq quit-flag t))
14661 ((= c ?\ ) nil)
14662 ((setq e (rassoc c fulltable) tg (car e))
14664 (t (setq quit-flag t))))))
14666 (defun org-get-repeat ()
14667 "Check if tere is a deadline/schedule with repeater in this entry."
14668 (save-match-data
14669 (save-excursion
14670 (org-back-to-heading t)
14671 (if (re-search-forward
14672 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
14673 (match-string 1)))))
14675 (defvar org-last-changed-timestamp)
14676 (defvar org-log-post-message)
14677 (defun org-auto-repeat-maybe ()
14678 "Check if the current headline contains a repeated deadline/schedule.
14679 If yes, set TODO state back to what it was and change the base date
14680 of repeating deadline/scheduled time stamps to new date.
14681 This function should be run in the `org-after-todo-state-change-hook'."
14682 ;; last-state is dynamically scoped into this function
14683 (let* ((repeat (org-get-repeat))
14684 (aa (assoc last-state org-todo-kwd-alist))
14685 (interpret (nth 1 aa))
14686 (head (nth 2 aa))
14687 (done-word (nth 3 aa))
14688 (whata '(("d" . day) ("m" . month) ("y" . year)))
14689 (msg "Entry repeats: ")
14690 (org-log-done)
14691 re type n what ts)
14692 (when repeat
14693 (org-todo (if (eq interpret 'type) last-state head))
14694 (when (and org-log-repeat
14695 (not (memq 'org-add-log-note
14696 (default-value 'post-command-hook))))
14697 ;; Make sure a note is taken
14698 (let ((org-log-done '(done)))
14699 (org-add-log-maybe 'done (or done-word (car org-done-keywords))
14700 'findpos)))
14701 (org-back-to-heading t)
14702 (org-add-planning-info nil nil 'closed)
14703 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
14704 org-deadline-time-regexp "\\)\\|\\("
14705 org-ts-regexp "\\)"))
14706 (while (re-search-forward
14707 re (save-excursion (outline-next-heading) (point)) t)
14708 (setq type (if (match-end 1) org-scheduled-string
14709 (if (match-end 3) org-deadline-string "Plain:"))
14710 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
14711 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
14712 (setq n (string-to-number (match-string 1 ts))
14713 what (match-string 2 ts))
14714 (if (equal what "w") (setq n (* n 7) what "d"))
14715 (org-timestamp-change n (cdr (assoc what whata)))
14716 (setq msg (concat msg type org-last-changed-timestamp " "))))
14717 (setq org-log-post-message msg)
14718 (message "%s" msg))))
14720 (defun org-show-todo-tree (arg)
14721 "Make a compact tree which shows all headlines marked with TODO.
14722 The tree will show the lines where the regexp matches, and all higher
14723 headlines above the match.
14724 With \\[universal-argument] prefix, also show the DONE entries.
14725 With a numeric prefix N, construct a sparse tree for the Nth element
14726 of `org-todo-keywords-1'."
14727 (interactive "P")
14728 (let ((case-fold-search nil)
14729 (kwd-re
14730 (cond ((null arg) org-not-done-regexp)
14731 ((equal arg '(4))
14732 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
14733 (mapcar 'list org-todo-keywords-1))))
14734 (concat "\\("
14735 (mapconcat 'identity (org-split-string kwd "|") "\\|")
14736 "\\)\\>")))
14737 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
14738 (regexp-quote (nth (1- (prefix-numeric-value arg))
14739 org-todo-keywords-1)))
14740 (t (error "Invalid prefix argument: %s" arg)))))
14741 (message "%d TODO entries found"
14742 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
14744 (defun org-deadline (&optional remove)
14745 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
14746 With argument REMOVE, remove any deadline from the item."
14747 (interactive "P")
14748 (if remove
14749 (progn
14750 (org-remove-timestamp-with-keyword org-deadline-string)
14751 (message "Item no longer has a deadline."))
14752 (org-add-planning-info 'deadline nil 'closed)))
14754 (defun org-schedule (&optional remove)
14755 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
14756 With argument REMOVE, remove any scheduling date from the item."
14757 (interactive "P")
14758 (if remove
14759 (progn
14760 (org-remove-timestamp-with-keyword org-scheduled-string)
14761 (message "Item is no longer scheduled."))
14762 (org-add-planning-info 'scheduled nil 'closed)))
14764 (defun org-remove-timestamp-with-keyword (keyword)
14765 "Remove all time stamps with KEYWORD in the current entry."
14766 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
14767 beg)
14768 (save-excursion
14769 (org-back-to-heading t)
14770 (setq beg (point))
14771 (org-end-of-subtree t t)
14772 (while (re-search-backward re beg t)
14773 (replace-match "")
14774 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
14775 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
14777 (defun org-add-planning-info (what &optional time &rest remove)
14778 "Insert new timestamp with keyword in the line directly after the headline.
14779 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
14780 If non is given, the user is prompted for a date.
14781 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
14782 be removed."
14783 (interactive)
14784 (let (org-time-was-given org-end-time-was-given)
14785 (when what (setq time (or time (org-read-date nil 'to-time))))
14786 (when (and org-insert-labeled-timestamps-at-point
14787 (member what '(scheduled deadline)))
14788 (insert
14789 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
14790 (org-insert-time-stamp time org-time-was-given
14791 nil nil nil (list org-end-time-was-given))
14792 (setq what nil))
14793 (save-excursion
14794 (save-restriction
14795 (let (col list elt ts buffer-invisibility-spec)
14796 (org-back-to-heading t)
14797 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
14798 (goto-char (match-end 1))
14799 (setq col (current-column))
14800 (goto-char (match-end 0))
14801 (if (eobp) (insert "\n") (forward-char 1))
14802 (if (and (not (looking-at outline-regexp))
14803 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
14804 "[^\r\n]*"))
14805 (not (equal (match-string 1) org-clock-string)))
14806 (narrow-to-region (match-beginning 0) (match-end 0))
14807 (insert-before-markers "\n")
14808 (backward-char 1)
14809 (narrow-to-region (point) (point))
14810 (indent-to-column col))
14811 ;; Check if we have to remove something.
14812 (setq list (cons what remove))
14813 (while list
14814 (setq elt (pop list))
14815 (goto-char (point-min))
14816 (when (or (and (eq elt 'scheduled)
14817 (re-search-forward org-scheduled-time-regexp nil t))
14818 (and (eq elt 'deadline)
14819 (re-search-forward org-deadline-time-regexp nil t))
14820 (and (eq elt 'closed)
14821 (re-search-forward org-closed-time-regexp nil t)))
14822 (replace-match "")
14823 (if (looking-at "--+<[^>]+>") (replace-match ""))
14824 (if (looking-at " +") (replace-match ""))))
14825 (goto-char (point-max))
14826 (when what
14827 (insert
14828 (if (not (equal (char-before) ?\ )) " " "")
14829 (cond ((eq what 'scheduled) org-scheduled-string)
14830 ((eq what 'deadline) org-deadline-string)
14831 ((eq what 'closed) org-closed-string))
14832 " ")
14833 (setq ts (org-insert-time-stamp
14834 time
14835 (or org-time-was-given
14836 (and (eq what 'closed) org-log-done-with-time))
14837 (eq what 'closed)
14838 nil nil (list org-end-time-was-given)))
14839 (end-of-line 1))
14840 (goto-char (point-min))
14841 (widen)
14842 (if (looking-at "[ \t]+\r?\n")
14843 (replace-match ""))
14844 ts)))))
14846 (defvar org-log-note-marker (make-marker))
14847 (defvar org-log-note-purpose nil)
14848 (defvar org-log-note-state nil)
14849 (defvar org-log-note-window-configuration nil)
14850 (defvar org-log-note-return-to (make-marker))
14851 (defvar org-log-post-message nil
14852 "Message to be displayed after a log note has been stored.
14853 The auto-repeater uses this.")
14855 (defun org-add-log-maybe (&optional purpose state findpos)
14856 "Set up the post command hook to take a note."
14857 (save-excursion
14858 (when (and (listp org-log-done)
14859 (memq purpose org-log-done))
14860 (when findpos
14861 (org-back-to-heading t)
14862 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
14863 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
14864 "[^\r\n]*\\)?"))
14865 (goto-char (match-end 0))
14866 (unless org-log-states-order-reversed
14867 (and (= (char-after) ?\n) (forward-char 1))
14868 (org-skip-over-state-notes)
14869 (skip-chars-backward " \t\n\r")))
14870 (move-marker org-log-note-marker (point))
14871 (setq org-log-note-purpose purpose)
14872 (setq org-log-note-state state)
14873 (add-hook 'post-command-hook 'org-add-log-note 'append))))
14875 (defun org-skip-over-state-notes ()
14876 "Skip past the list of State notes in an entry."
14877 (if (looking-at "\n[ \t]*- State") (forward-char 1))
14878 (while (looking-at "[ \t]*- State")
14879 (condition-case nil
14880 (org-next-item)
14881 (error (org-end-of-item)))))
14883 (defun org-add-log-note (&optional purpose)
14884 "Pop up a window for taking a note, and add this note later at point."
14885 (remove-hook 'post-command-hook 'org-add-log-note)
14886 (setq org-log-note-window-configuration (current-window-configuration))
14887 (delete-other-windows)
14888 (move-marker org-log-note-return-to (point))
14889 (switch-to-buffer (marker-buffer org-log-note-marker))
14890 (goto-char org-log-note-marker)
14891 (org-switch-to-buffer-other-window "*Org Note*")
14892 (erase-buffer)
14893 (let ((org-inhibit-startup t)) (org-mode))
14894 (insert (format "# Insert note for %s.
14895 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
14896 (cond
14897 ((eq org-log-note-purpose 'clock-out) "stopped clock")
14898 ((eq org-log-note-purpose 'done) "closed todo item")
14899 ((eq org-log-note-purpose 'state)
14900 (format "state change to \"%s\"" org-log-note-state))
14901 (t (error "This should not happen")))))
14902 (org-set-local 'org-finish-function 'org-store-log-note))
14904 (defun org-store-log-note ()
14905 "Finish taking a log note, and insert it to where it belongs."
14906 (let ((txt (buffer-string))
14907 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
14908 lines ind)
14909 (kill-buffer (current-buffer))
14910 (while (string-match "\\`#.*\n[ \t\n]*" txt)
14911 (setq txt (replace-match "" t t txt)))
14912 (if (string-match "\\s-+\\'" txt)
14913 (setq txt (replace-match "" t t txt)))
14914 (setq lines (org-split-string txt "\n"))
14915 (when (and note (string-match "\\S-" note))
14916 (setq note
14917 (org-replace-escapes
14918 note
14919 (list (cons "%u" (user-login-name))
14920 (cons "%U" user-full-name)
14921 (cons "%t" (format-time-string
14922 (org-time-stamp-format 'long 'inactive)
14923 (current-time)))
14924 (cons "%s" (if org-log-note-state
14925 (concat "\"" org-log-note-state "\"")
14926 "")))))
14927 (if lines (setq note (concat note " \\\\")))
14928 (push note lines))
14929 (when (or current-prefix-arg org-note-abort) (setq lines nil))
14930 (when lines
14931 (save-excursion
14932 (set-buffer (marker-buffer org-log-note-marker))
14933 (save-excursion
14934 (goto-char org-log-note-marker)
14935 (move-marker org-log-note-marker nil)
14936 (end-of-line 1)
14937 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
14938 (indent-relative nil)
14939 (insert "- " (pop lines))
14940 (org-indent-line-function)
14941 (beginning-of-line 1)
14942 (looking-at "[ \t]*")
14943 (setq ind (concat (match-string 0) " "))
14944 (end-of-line 1)
14945 (while lines (insert "\n" ind (pop lines)))))))
14946 (set-window-configuration org-log-note-window-configuration)
14947 (with-current-buffer (marker-buffer org-log-note-return-to)
14948 (goto-char org-log-note-return-to))
14949 (move-marker org-log-note-return-to nil)
14950 (and org-log-post-message (message "%s" org-log-post-message)))
14952 ;; FIXME: what else would be useful?
14953 ;; - priority
14954 ;; - date
14956 (defun org-sparse-tree (&optional arg)
14957 "Create a sparse tree, prompt for the details.
14958 This command can create sparse trees. You first need to select the type
14959 of match used to create the tree:
14961 t Show entries with a specific TODO keyword.
14962 T Show entries selected by a tags match.
14963 p Enter a property name and its value (both with completion on existing
14964 names/values) and show entries with that property.
14965 r Show entries matching a regular expression
14966 d Show deadlines due within `org-deadline-warning-days'."
14967 (interactive "P")
14968 (let (ans kwd value)
14969 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
14970 (setq ans (read-char-exclusive))
14971 (cond
14972 ((equal ans ?d)
14973 (call-interactively 'org-check-deadlines))
14974 ((equal ans ?b)
14975 (call-interactively 'org-check-before-date))
14976 ((equal ans ?t)
14977 (org-show-todo-tree '(4)))
14978 ((equal ans ?T)
14979 (call-interactively 'org-tags-sparse-tree))
14980 ((member ans '(?p ?P))
14981 (setq kwd (completing-read "Property: "
14982 (mapcar 'list (org-buffer-property-keys))))
14983 (setq value (completing-read "Value: "
14984 (mapcar 'list (org-property-values kwd))))
14985 (unless (string-match "\\`{.*}\\'" value)
14986 (setq value (concat "\"" value "\"")))
14987 (org-tags-sparse-tree arg (concat kwd "=" value)))
14988 ((member ans '(?r ?R ?/))
14989 (call-interactively 'org-occur))
14990 (t (error "No such sparse tree command \"%c\"" ans)))))
14992 (defvar org-occur-highlights nil)
14993 (make-variable-buffer-local 'org-occur-highlights)
14995 (defun org-occur (regexp &optional keep-previous callback)
14996 "Make a compact tree which shows all matches of REGEXP.
14997 The tree will show the lines where the regexp matches, and all higher
14998 headlines above the match. It will also show the heading after the match,
14999 to make sure editing the matching entry is easy.
15000 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
15001 call to `org-occur' will be kept, to allow stacking of calls to this
15002 command.
15003 If CALLBACK is non-nil, it is a function which is called to confirm
15004 that the match should indeed be shown."
15005 (interactive "sRegexp: \nP")
15006 (or keep-previous (org-remove-occur-highlights nil nil t))
15007 (let ((cnt 0))
15008 (save-excursion
15009 (goto-char (point-min))
15010 (if (or (not keep-previous) ; do not want to keep
15011 (not org-occur-highlights)) ; no previous matches
15012 ;; hide everything
15013 (org-overview))
15014 (while (re-search-forward regexp nil t)
15015 (when (or (not callback)
15016 (save-match-data (funcall callback)))
15017 (setq cnt (1+ cnt))
15018 (when org-highlight-sparse-tree-matches
15019 (org-highlight-new-match (match-beginning 0) (match-end 0)))
15020 (org-show-context 'occur-tree))))
15021 (when org-remove-highlights-with-change
15022 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
15023 nil 'local))
15024 (unless org-sparse-tree-open-archived-trees
15025 (org-hide-archived-subtrees (point-min) (point-max)))
15026 (run-hooks 'org-occur-hook)
15027 (if (interactive-p)
15028 (message "%d match(es) for regexp %s" cnt regexp))
15029 cnt))
15031 (defun org-show-context (&optional key)
15032 "Make sure point and context and visible.
15033 How much context is shown depends upon the variables
15034 `org-show-hierarchy-above', `org-show-following-heading'. and
15035 `org-show-siblings'."
15036 (let ((heading-p (org-on-heading-p t))
15037 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
15038 (following-p (org-get-alist-option org-show-following-heading key))
15039 (entry-p (org-get-alist-option org-show-entry-below key))
15040 (siblings-p (org-get-alist-option org-show-siblings key)))
15041 (catch 'exit
15042 ;; Show heading or entry text
15043 (if (and heading-p (not entry-p))
15044 (org-flag-heading nil) ; only show the heading
15045 (and (or entry-p (org-invisible-p) (org-invisible-p2))
15046 (org-show-hidden-entry))) ; show entire entry
15047 (when following-p
15048 ;; Show next sibling, or heading below text
15049 (save-excursion
15050 (and (if heading-p (org-goto-sibling) (outline-next-heading))
15051 (org-flag-heading nil))))
15052 (when siblings-p (org-show-siblings))
15053 (when hierarchy-p
15054 ;; show all higher headings, possibly with siblings
15055 (save-excursion
15056 (while (and (condition-case nil
15057 (progn (org-up-heading-all 1) t)
15058 (error nil))
15059 (not (bobp)))
15060 (org-flag-heading nil)
15061 (when siblings-p (org-show-siblings))))))))
15063 (defun org-reveal (&optional siblings)
15064 "Show current entry, hierarchy above it, and the following headline.
15065 This can be used to show a consistent set of context around locations
15066 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
15067 not t for the search context.
15069 With optional argument SIBLINGS, on each level of the hierarchy all
15070 siblings are shown. This repairs the tree structure to what it would
15071 look like when opened with hierarchical calls to `org-cycle'."
15072 (interactive "P")
15073 (let ((org-show-hierarchy-above t)
15074 (org-show-following-heading t)
15075 (org-show-siblings (if siblings t org-show-siblings)))
15076 (org-show-context nil)))
15078 (defun org-highlight-new-match (beg end)
15079 "Highlight from BEG to END and mark the highlight is an occur headline."
15080 (let ((ov (org-make-overlay beg end)))
15081 (org-overlay-put ov 'face 'secondary-selection)
15082 (push ov org-occur-highlights)))
15084 (defun org-remove-occur-highlights (&optional beg end noremove)
15085 "Remove the occur highlights from the buffer.
15086 BEG and END are ignored. If NOREMOVE is nil, remove this function
15087 from the `before-change-functions' in the current buffer."
15088 (interactive)
15089 (unless org-inhibit-highlight-removal
15090 (mapc 'org-delete-overlay org-occur-highlights)
15091 (setq org-occur-highlights nil)
15092 (unless noremove
15093 (remove-hook 'before-change-functions
15094 'org-remove-occur-highlights 'local))))
15096 ;;;; Priorities
15098 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
15099 "Regular expression matching the priority indicator.")
15101 (defvar org-remove-priority-next-time nil)
15103 (defun org-priority-up ()
15104 "Increase the priority of the current item."
15105 (interactive)
15106 (org-priority 'up))
15108 (defun org-priority-down ()
15109 "Decrease the priority of the current item."
15110 (interactive)
15111 (org-priority 'down))
15113 (defun org-priority (&optional action)
15114 "Change the priority of an item by ARG.
15115 ACTION can be `set', `up', `down', or a character."
15116 (interactive)
15117 (setq action (or action 'set))
15118 (let (current new news have remove)
15119 (save-excursion
15120 (org-back-to-heading)
15121 (if (looking-at org-priority-regexp)
15122 (setq current (string-to-char (match-string 2))
15123 have t)
15124 (setq current org-default-priority))
15125 (cond
15126 ((or (eq action 'set) (integerp action))
15127 (if (integerp action)
15128 (setq new action)
15129 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
15130 (setq new (read-char-exclusive)))
15131 (if (and (= (upcase org-highest-priority) org-highest-priority)
15132 (= (upcase org-lowest-priority) org-lowest-priority))
15133 (setq new (upcase new)))
15134 (cond ((equal new ?\ ) (setq remove t))
15135 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
15136 (error "Priority must be between `%c' and `%c'"
15137 org-highest-priority org-lowest-priority))))
15138 ((eq action 'up)
15139 (if (and (not have) (eq last-command this-command))
15140 (setq new org-lowest-priority)
15141 (setq new (if (and org-priority-start-cycle-with-default (not have))
15142 org-default-priority (1- current)))))
15143 ((eq action 'down)
15144 (if (and (not have) (eq last-command this-command))
15145 (setq new org-highest-priority)
15146 (setq new (if (and org-priority-start-cycle-with-default (not have))
15147 org-default-priority (1+ current)))))
15148 (t (error "Invalid action")))
15149 (if (or (< (upcase new) org-highest-priority)
15150 (> (upcase new) org-lowest-priority))
15151 (setq remove t))
15152 (setq news (format "%c" new))
15153 (if have
15154 (if remove
15155 (replace-match "" t t nil 1)
15156 (replace-match news t t nil 2))
15157 (if remove
15158 (error "No priority cookie found in line")
15159 (looking-at org-todo-line-regexp)
15160 (if (match-end 2)
15161 (progn
15162 (goto-char (match-end 2))
15163 (insert " [#" news "]"))
15164 (goto-char (match-beginning 3))
15165 (insert "[#" news "] ")))))
15166 (org-preserve-lc (org-set-tags nil 'align))
15167 (if remove
15168 (message "Priority removed")
15169 (message "Priority of current item set to %s" news))))
15172 (defun org-get-priority (s)
15173 "Find priority cookie and return priority."
15174 (save-match-data
15175 (if (not (string-match org-priority-regexp s))
15176 (* 1000 (- org-lowest-priority org-default-priority))
15177 (* 1000 (- org-lowest-priority
15178 (string-to-char (match-string 2 s)))))))
15180 ;;;; Tags
15182 (defun org-scan-tags (action matcher &optional todo-only)
15183 "Scan headline tags with inheritance and produce output ACTION.
15184 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
15185 evaluated, testing if a given set of tags qualifies a headline for
15186 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
15187 are included in the output."
15188 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
15189 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
15190 (org-re
15191 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
15192 (props (list 'face nil
15193 'done-face 'org-done
15194 'undone-face nil
15195 'mouse-face 'highlight
15196 'org-not-done-regexp org-not-done-regexp
15197 'org-todo-regexp org-todo-regexp
15198 'keymap org-agenda-keymap
15199 'help-echo
15200 (format "mouse-2 or RET jump to org file %s"
15201 (abbreviate-file-name
15202 (or (buffer-file-name (buffer-base-buffer))
15203 (buffer-name (buffer-base-buffer)))))))
15204 (case-fold-search nil)
15205 lspos
15206 tags tags-list tags-alist (llast 0) rtn level category i txt
15207 todo marker entry priority)
15208 (save-excursion
15209 (goto-char (point-min))
15210 (when (eq action 'sparse-tree)
15211 (org-overview)
15212 (org-remove-occur-highlights))
15213 (while (re-search-forward re nil t)
15214 (catch :skip
15215 (setq todo (if (match-end 1) (match-string 2))
15216 tags (if (match-end 4) (match-string 4)))
15217 (goto-char (setq lspos (1+ (match-beginning 0))))
15218 (setq level (org-reduced-level (funcall outline-level))
15219 category (org-get-category))
15220 (setq i llast llast level)
15221 ;; remove tag lists from same and sublevels
15222 (while (>= i level)
15223 (when (setq entry (assoc i tags-alist))
15224 (setq tags-alist (delete entry tags-alist)))
15225 (setq i (1- i)))
15226 ;; add the nex tags
15227 (when tags
15228 (setq tags (mapcar 'downcase (org-split-string tags ":"))
15229 tags-alist
15230 (cons (cons level tags) tags-alist)))
15231 ;; compile tags for current headline
15232 (setq tags-list
15233 (if org-use-tag-inheritance
15234 (apply 'append (mapcar 'cdr tags-alist))
15235 tags))
15236 (when (and (or (not todo-only) (member todo org-not-done-keywords))
15237 (eval matcher)
15238 (or (not org-agenda-skip-archived-trees)
15239 (not (member org-archive-tag tags-list))))
15240 (and (eq action 'agenda) (org-agenda-skip))
15241 ;; list this headline
15243 (if (eq action 'sparse-tree)
15244 (progn
15245 (and org-highlight-sparse-tree-matches
15246 (org-get-heading) (match-end 0)
15247 (org-highlight-new-match
15248 (match-beginning 0) (match-beginning 1)))
15249 (org-show-context 'tags-tree))
15250 (setq txt (org-format-agenda-item
15252 (concat
15253 (if org-tags-match-list-sublevels
15254 (make-string (1- level) ?.) "")
15255 (org-get-heading))
15256 category tags-list)
15257 priority (org-get-priority txt))
15258 (goto-char lspos)
15259 (setq marker (org-agenda-new-marker))
15260 (org-add-props txt props
15261 'org-marker marker 'org-hd-marker marker 'org-category category
15262 'priority priority 'type "tagsmatch")
15263 (push txt rtn))
15264 ;; if we are to skip sublevels, jump to end of subtree
15265 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15266 (when (and (eq action 'sparse-tree)
15267 (not org-sparse-tree-open-archived-trees))
15268 (org-hide-archived-subtrees (point-min) (point-max)))
15269 (nreverse rtn)))
15271 (defvar todo-only) ;; dynamically scoped
15273 (defun org-tags-sparse-tree (&optional todo-only match)
15274 "Create a sparse tree according to tags string MATCH.
15275 MATCH can contain positive and negative selection of tags, like
15276 \"+WORK+URGENT-WITHBOSS\".
15277 If optional argument TODO_ONLY is non-nil, only select lines that are
15278 also TODO lines."
15279 (interactive "P")
15280 (org-prepare-agenda-buffers (list (current-buffer)))
15281 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15283 (defvar org-cached-props nil)
15284 (defun org-cached-entry-get (pom property)
15285 (if (or (eq t org-use-property-inheritance)
15286 (member property org-use-property-inheritance))
15287 ;; Caching is not possible, check it directly
15288 (org-entry-get pom property 'inherit)
15289 ;; Get all properties, so that we can do complicated checks easily
15290 (cdr (assoc property (or org-cached-props
15291 (setq org-cached-props
15292 (org-entry-properties pom)))))))
15294 (defun org-global-tags-completion-table (&optional files)
15295 "Return the list of all tags in all agenda buffer/files."
15296 (save-excursion
15297 (org-uniquify
15298 (delq nil
15299 (apply 'append
15300 (mapcar
15301 (lambda (file)
15302 (set-buffer (find-file-noselect file))
15303 (append (org-get-buffer-tags)
15304 (mapcar (lambda (x) (if (stringp (car-safe x))
15305 (list (car-safe x)) nil))
15306 org-tag-alist)))
15307 (if (and files (car files))
15308 files
15309 (org-agenda-files))))))))
15311 (defun org-make-tags-matcher (match)
15312 "Create the TAGS//TODO matcher form for the selection string MATCH."
15313 ;; todo-only is scoped dynamically into this function, and the function
15314 ;; may change it it the matcher asksk for it.
15315 (unless match
15316 ;; Get a new match request, with completion
15317 (let ((org-last-tags-completion-table
15318 (org-global-tags-completion-table)))
15319 (setq match (completing-read
15320 "Match: " 'org-tags-completion-function nil nil nil
15321 'org-tags-history))))
15323 ;; Parse the string and create a lisp form
15324 (let ((match0 match)
15325 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]+\"\\)\\|[[:alnum:]_@]+\\)"))
15326 minus tag mm
15327 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15328 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15329 (if (string-match "/+" match)
15330 ;; match contains also a todo-matching request
15331 (progn
15332 (setq tagsmatch (substring match 0 (match-beginning 0))
15333 todomatch (substring match (match-end 0)))
15334 (if (string-match "^!" todomatch)
15335 (setq todo-only t todomatch (substring todomatch 1)))
15336 (if (string-match "^\\s-*$" todomatch)
15337 (setq todomatch nil)))
15338 ;; only matching tags
15339 (setq tagsmatch match todomatch nil))
15341 ;; Make the tags matcher
15342 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15343 (setq tagsmatcher t)
15344 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15345 (while (setq term (pop orterms))
15346 (while (and (equal (substring term -1) "\\") orterms)
15347 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15348 (while (string-match re term)
15349 (setq minus (and (match-end 1)
15350 (equal (match-string 1 term) "-"))
15351 tag (match-string 2 term)
15352 re-p (equal (string-to-char tag) ?{)
15353 level-p (match-end 3)
15354 prop-p (match-end 4)
15355 mm (cond
15356 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15357 (level-p `(= level ,(string-to-number
15358 (match-string 3 term))))
15359 (prop-p
15360 (setq pn (match-string 4 term)
15361 pv (match-string 5 term)
15362 cat-p (equal pn "CATEGORY")
15363 re-p (equal (string-to-char pv) ?{)
15364 pv (substring pv 1 -1))
15365 (if (equal pn "CATEGORY")
15366 (setq gv '(get-text-property (point) 'org-category))
15367 (setq gv `(org-cached-entry-get nil ,pn)))
15368 (if re-p
15369 `(string-match ,pv (or ,gv ""))
15370 `(equal ,pv ,gv)))
15371 (t `(member ,(downcase tag) tags-list)))
15372 mm (if minus (list 'not mm) mm)
15373 term (substring term (match-end 0)))
15374 (push mm tagsmatcher))
15375 (push (if (> (length tagsmatcher) 1)
15376 (cons 'and tagsmatcher)
15377 (car tagsmatcher))
15378 orlist)
15379 (setq tagsmatcher nil))
15380 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15381 (setq tagsmatcher
15382 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15384 ;; Make the todo matcher
15385 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15386 (setq todomatcher t)
15387 (setq orterms (org-split-string todomatch "|") orlist nil)
15388 (while (setq term (pop orterms))
15389 (while (string-match re term)
15390 (setq minus (and (match-end 1)
15391 (equal (match-string 1 term) "-"))
15392 kwd (match-string 2 term)
15393 re-p (equal (string-to-char kwd) ?{)
15394 term (substring term (match-end 0))
15395 mm (if re-p
15396 `(string-match ,(substring kwd 1 -1) todo)
15397 (list 'equal 'todo kwd))
15398 mm (if minus (list 'not mm) mm))
15399 (push mm todomatcher))
15400 (push (if (> (length todomatcher) 1)
15401 (cons 'and todomatcher)
15402 (car todomatcher))
15403 orlist)
15404 (setq todomatcher nil))
15405 (setq todomatcher (if (> (length orlist) 1)
15406 (cons 'or orlist) (car orlist))))
15408 ;; Return the string and lisp forms of the matcher
15409 (setq matcher (if todomatcher
15410 (list 'and tagsmatcher todomatcher)
15411 tagsmatcher))
15412 (cons match0 matcher)))
15414 (defun org-match-any-p (re list)
15415 "Does re match any element of list?"
15416 (setq list (mapcar (lambda (x) (string-match re x)) list))
15417 (delq nil list))
15419 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15420 (defvar org-tags-overlay (org-make-overlay 1 1))
15421 (org-detach-overlay org-tags-overlay)
15423 (defun org-align-tags-here (to-col)
15424 ;; Assumes that this is a headline
15425 (let ((pos (point)) (col (current-column)) tags)
15426 (beginning-of-line 1)
15427 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15428 (< pos (match-beginning 2)))
15429 (progn
15430 (setq tags (match-string 2))
15431 (goto-char (match-beginning 1))
15432 (insert " ")
15433 (delete-region (point) (1+ (match-end 0)))
15434 (backward-char 1)
15435 (move-to-column
15436 (max (1+ (current-column))
15437 (1+ col)
15438 (if (> to-col 0)
15439 to-col
15440 (- (abs to-col) (length tags))))
15442 (insert tags)
15443 (move-to-column (min (current-column) col) t))
15444 (goto-char pos))))
15446 (defun org-set-tags (&optional arg just-align)
15447 "Set the tags for the current headline.
15448 With prefix ARG, realign all tags in headings in the current buffer."
15449 (interactive "P")
15450 (let* ((re (concat "^" outline-regexp))
15451 (current (org-get-tags-string))
15452 (col (current-column))
15453 (org-setting-tags t)
15454 table current-tags inherited-tags ; computed below when needed
15455 tags p0 c0 c1 rpl)
15456 (if arg
15457 (save-excursion
15458 (goto-char (point-min))
15459 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15460 (while (re-search-forward re nil t)
15461 (org-set-tags nil t)
15462 (end-of-line 1)))
15463 (message "All tags realigned to column %d" org-tags-column))
15464 (if just-align
15465 (setq tags current)
15466 ;; Get a new set of tags from the user
15467 (save-excursion
15468 (setq table (or org-tag-alist (org-get-buffer-tags))
15469 org-last-tags-completion-table table
15470 current-tags (org-split-string current ":")
15471 inherited-tags (nreverse
15472 (nthcdr (length current-tags)
15473 (nreverse (org-get-tags-at))))
15474 tags
15475 (if (or (eq t org-use-fast-tag-selection)
15476 (and org-use-fast-tag-selection
15477 (delq nil (mapcar 'cdr table))))
15478 (org-fast-tag-selection
15479 current-tags inherited-tags table
15480 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15481 (let ((org-add-colon-after-tag-completion t))
15482 (org-trim
15483 (org-without-partial-completion
15484 (completing-read "Tags: " 'org-tags-completion-function
15485 nil nil current 'org-tags-history)))))))
15486 (while (string-match "[-+&]+" tags)
15487 ;; No boolean logic, just a list
15488 (setq tags (replace-match ":" t t tags))))
15490 (if (string-match "\\`[\t ]*\\'" tags)
15491 (setq tags "")
15492 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15493 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15495 ;; Insert new tags at the correct column
15496 (beginning-of-line 1)
15497 (cond
15498 ((and (equal current "") (equal tags "")))
15499 ((re-search-forward
15500 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15501 (point-at-eol) t)
15502 (if (equal tags "")
15503 (setq rpl "")
15504 (goto-char (match-beginning 0))
15505 (setq c0 (current-column) p0 (point)
15506 c1 (max (1+ c0) (if (> org-tags-column 0)
15507 org-tags-column
15508 (- (- org-tags-column) (length tags))))
15509 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15510 (replace-match rpl t t)
15511 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
15512 tags)
15513 (t (error "Tags alignment failed")))
15514 (move-to-column col)
15515 (unless just-align
15516 (run-hooks 'org-after-tags-change-hook)))))
15518 (defun org-change-tag-in-region (beg end tag off)
15519 "Add or remove TAG for each entry in the region.
15520 This works in the agenda, and also in an org-mode buffer."
15521 (interactive
15522 (list (region-beginning) (region-end)
15523 (let ((org-last-tags-completion-table
15524 (if (org-mode-p)
15525 (org-get-buffer-tags)
15526 (org-global-tags-completion-table))))
15527 (completing-read
15528 "Tag: " 'org-tags-completion-function nil nil nil
15529 'org-tags-history))
15530 (progn
15531 (message "[s]et or [r]emove? ")
15532 (equal (read-char-exclusive) ?r))))
15533 (if (fboundp 'deactivate-mark) (deactivate-mark))
15534 (let ((agendap (equal major-mode 'org-agenda-mode))
15535 l1 l2 m buf pos newhead (cnt 0))
15536 (goto-char end)
15537 (setq l2 (1- (org-current-line)))
15538 (goto-char beg)
15539 (setq l1 (org-current-line))
15540 (loop for l from l1 to l2 do
15541 (goto-line l)
15542 (setq m (get-text-property (point) 'org-hd-marker))
15543 (when (or (and (org-mode-p) (org-on-heading-p))
15544 (and agendap m))
15545 (setq buf (if agendap (marker-buffer m) (current-buffer))
15546 pos (if agendap m (point)))
15547 (with-current-buffer buf
15548 (save-excursion
15549 (save-restriction
15550 (goto-char pos)
15551 (setq cnt (1+ cnt))
15552 (org-toggle-tag tag (if off 'off 'on))
15553 (setq newhead (org-get-heading)))))
15554 (and agendap (org-agenda-change-all-lines newhead m))))
15555 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15557 (defun org-tags-completion-function (string predicate &optional flag)
15558 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15559 (confirm (lambda (x) (stringp (car x)))))
15560 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15561 (setq s1 (match-string 1 string)
15562 s2 (match-string 2 string))
15563 (setq s1 "" s2 string))
15564 (cond
15565 ((eq flag nil)
15566 ;; try completion
15567 (setq rtn (try-completion s2 ctable confirm))
15568 (if (stringp rtn)
15569 (setq rtn
15570 (concat s1 s2 (substring rtn (length s2))
15571 (if (and org-add-colon-after-tag-completion
15572 (assoc rtn ctable))
15573 ":" ""))))
15574 rtn)
15575 ((eq flag t)
15576 ;; all-completions
15577 (all-completions s2 ctable confirm)
15579 ((eq flag 'lambda)
15580 ;; exact match?
15581 (assoc s2 ctable)))
15584 (defun org-fast-tag-insert (kwd tags face &optional end)
15585 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15586 (insert (format "%-12s" (concat kwd ":"))
15587 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15588 (or end "")))
15590 (defun org-fast-tag-show-exit (flag)
15591 (save-excursion
15592 (goto-line 3)
15593 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15594 (replace-match ""))
15595 (when flag
15596 (end-of-line 1)
15597 (move-to-column (- (window-width) 19) t)
15598 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15600 (defun org-set-current-tags-overlay (current prefix)
15601 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15602 (if (featurep 'xemacs)
15603 (org-overlay-display org-tags-overlay (concat prefix s)
15604 'secondary-selection)
15605 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15606 (org-overlay-display org-tags-overlay (concat prefix s)))))
15608 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15609 "Fast tag selection with single keys.
15610 CURRENT is the current list of tags in the headline, INHERITED is the
15611 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15612 possibly with grouping information. TODO-TABLE is a similar table with
15613 TODO keywords, should these have keys assigned to them.
15614 If the keys are nil, a-z are automatically assigned.
15615 Returns the new tags string, or nil to not change the current settings."
15616 (let* ((fulltable (append table todo-table))
15617 (maxlen (apply 'max (mapcar
15618 (lambda (x)
15619 (if (stringp (car x)) (string-width (car x)) 0))
15620 fulltable)))
15621 (buf (current-buffer))
15622 (expert (eq org-fast-tag-selection-single-key 'expert))
15623 (buffer-tags nil)
15624 (fwidth (+ maxlen 3 1 3))
15625 (ncol (/ (- (window-width) 4) fwidth))
15626 (i-face 'org-done)
15627 (c-face 'org-todo)
15628 tg cnt e c char c1 c2 ntable tbl rtn
15629 ov-start ov-end ov-prefix
15630 (exit-after-next org-fast-tag-selection-single-key)
15631 (done-keywords org-done-keywords)
15632 groups ingroup)
15633 (save-excursion
15634 (beginning-of-line 1)
15635 (if (looking-at
15636 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15637 (setq ov-start (match-beginning 1)
15638 ov-end (match-end 1)
15639 ov-prefix "")
15640 (setq ov-start (1- (point-at-eol))
15641 ov-end (1+ ov-start))
15642 (skip-chars-forward "^\n\r")
15643 (setq ov-prefix
15644 (concat
15645 (buffer-substring (1- (point)) (point))
15646 (if (> (current-column) org-tags-column)
15648 (make-string (- org-tags-column (current-column)) ?\ ))))))
15649 (org-move-overlay org-tags-overlay ov-start ov-end)
15650 (save-window-excursion
15651 (if expert
15652 (set-buffer (get-buffer-create " *Org tags*"))
15653 (delete-other-windows)
15654 (split-window-vertically)
15655 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
15656 (erase-buffer)
15657 (org-set-local 'org-done-keywords done-keywords)
15658 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15659 (org-fast-tag-insert "Current" current c-face "\n\n")
15660 (org-fast-tag-show-exit exit-after-next)
15661 (org-set-current-tags-overlay current ov-prefix)
15662 (setq tbl fulltable char ?a cnt 0)
15663 (while (setq e (pop tbl))
15664 (cond
15665 ((equal e '(:startgroup))
15666 (push '() groups) (setq ingroup t)
15667 (when (not (= cnt 0))
15668 (setq cnt 0)
15669 (insert "\n"))
15670 (insert "{ "))
15671 ((equal e '(:endgroup))
15672 (setq ingroup nil cnt 0)
15673 (insert "}\n"))
15675 (setq tg (car e) c2 nil)
15676 (if (cdr e)
15677 (setq c (cdr e))
15678 ;; automatically assign a character.
15679 (setq c1 (string-to-char
15680 (downcase (substring
15681 tg (if (= (string-to-char tg) ?@) 1 0)))))
15682 (if (or (rassoc c1 ntable) (rassoc c1 table))
15683 (while (or (rassoc char ntable) (rassoc char table))
15684 (setq char (1+ char)))
15685 (setq c2 c1))
15686 (setq c (or c2 char)))
15687 (if ingroup (push tg (car groups)))
15688 (setq tg (org-add-props tg nil 'face
15689 (cond
15690 ((not (assoc tg table))
15691 (org-get-todo-face tg))
15692 ((member tg current) c-face)
15693 ((member tg inherited) i-face)
15694 (t nil))))
15695 (if (and (= cnt 0) (not ingroup)) (insert " "))
15696 (insert "[" c "] " tg (make-string
15697 (- fwidth 4 (length tg)) ?\ ))
15698 (push (cons tg c) ntable)
15699 (when (= (setq cnt (1+ cnt)) ncol)
15700 (insert "\n")
15701 (if ingroup (insert " "))
15702 (setq cnt 0)))))
15703 (setq ntable (nreverse ntable))
15704 (insert "\n")
15705 (goto-char (point-min))
15706 (if (and (not expert) (fboundp 'fit-window-to-buffer))
15707 (fit-window-to-buffer))
15708 (setq rtn
15709 (catch 'exit
15710 (while t
15711 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
15712 (if groups " [!] no groups" " [!]groups")
15713 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15714 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15715 (cond
15716 ((= c ?\r) (throw 'exit t))
15717 ((= c ?!)
15718 (setq groups (not groups))
15719 (goto-char (point-min))
15720 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15721 ((= c ?\C-c)
15722 (if (not expert)
15723 (org-fast-tag-show-exit
15724 (setq exit-after-next (not exit-after-next)))
15725 (setq expert nil)
15726 (delete-other-windows)
15727 (split-window-vertically)
15728 (org-switch-to-buffer-other-window " *Org tags*")
15729 (and (fboundp 'fit-window-to-buffer)
15730 (fit-window-to-buffer))))
15731 ((or (= c ?\C-g)
15732 (and (= c ?q) (not (rassoc c ntable))))
15733 (org-detach-overlay org-tags-overlay)
15734 (setq quit-flag t))
15735 ((= c ?\ )
15736 (setq current nil)
15737 (if exit-after-next (setq exit-after-next 'now)))
15738 ((= c ?\t)
15739 (condition-case nil
15740 (setq tg (completing-read
15741 "Tag: "
15742 (or buffer-tags
15743 (with-current-buffer buf
15744 (org-get-buffer-tags)))))
15745 (quit (setq tg "")))
15746 (when (string-match "\\S-" tg)
15747 (add-to-list 'buffer-tags (list tg))
15748 (if (member tg current)
15749 (setq current (delete tg current))
15750 (push tg current)))
15751 (if exit-after-next (setq exit-after-next 'now)))
15752 ((setq e (rassoc c todo-table) tg (car e))
15753 (with-current-buffer buf
15754 (save-excursion (org-todo tg)))
15755 (if exit-after-next (setq exit-after-next 'now)))
15756 ((setq e (rassoc c ntable) tg (car e))
15757 (if (member tg current)
15758 (setq current (delete tg current))
15759 (loop for g in groups do
15760 (if (member tg g)
15761 (mapc (lambda (x)
15762 (setq current (delete x current)))
15763 g)))
15764 (push tg current))
15765 (if exit-after-next (setq exit-after-next 'now))))
15767 ;; Create a sorted list
15768 (setq current
15769 (sort current
15770 (lambda (a b)
15771 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15772 (if (eq exit-after-next 'now) (throw 'exit t))
15773 (goto-char (point-min))
15774 (beginning-of-line 2)
15775 (delete-region (point) (point-at-eol))
15776 (org-fast-tag-insert "Current" current c-face)
15777 (org-set-current-tags-overlay current ov-prefix)
15778 (while (re-search-forward
15779 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
15780 (setq tg (match-string 1))
15781 (add-text-properties
15782 (match-beginning 1) (match-end 1)
15783 (list 'face
15784 (cond
15785 ((member tg current) c-face)
15786 ((member tg inherited) i-face)
15787 (t (get-text-property (match-beginning 1) 'face))))))
15788 (goto-char (point-min)))))
15789 (org-detach-overlay org-tags-overlay)
15790 (if rtn
15791 (mapconcat 'identity current ":")
15792 nil))))
15794 (defun org-get-tags-string ()
15795 "Get the TAGS string in the current headline."
15796 (unless (org-on-heading-p t)
15797 (error "Not on a heading"))
15798 (save-excursion
15799 (beginning-of-line 1)
15800 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15801 (org-match-string-no-properties 1)
15802 "")))
15804 (defun org-get-tags ()
15805 "Get the list of tags specified in the current headline."
15806 (org-split-string (org-get-tags-string) ":"))
15808 (defun org-get-buffer-tags ()
15809 "Get a table of all tags used in the buffer, for completion."
15810 (let (tags)
15811 (save-excursion
15812 (goto-char (point-min))
15813 (while (re-search-forward
15814 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
15815 (when (equal (char-after (point-at-bol 0)) ?*)
15816 (mapc (lambda (x) (add-to-list 'tags x))
15817 (org-split-string (org-match-string-no-properties 1) ":")))))
15818 (mapcar 'list tags)))
15821 ;;;; Properties
15823 ;;; Setting and retrieving properties
15825 (defconst org-special-properties
15826 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
15827 "TIMESTAMP" "TIMESTAMP_IA")
15828 "The special properties valid in Org-mode.
15830 These are properties that are not defined in the property drawer,
15831 but in some other way.")
15833 (defconst org-default-properties
15834 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
15835 "LOCATION" "LOGGING" "COLUMNS")
15836 "Some properties that are used by Org-mode for various purposes.
15837 Being in this list makes sure that they are offered for completion.")
15839 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15840 "Regular expression matching the first line of a property drawer.")
15842 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15843 "Regular expression matching the first line of a property drawer.")
15845 (defun org-property-action ()
15846 "Do an action on properties."
15847 (interactive)
15848 (let (c)
15849 (org-at-property-p)
15850 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15851 (setq c (read-char-exclusive))
15852 (cond
15853 ((equal c ?s)
15854 (call-interactively 'org-set-property))
15855 ((equal c ?d)
15856 (call-interactively 'org-delete-property))
15857 ((equal c ?D)
15858 (call-interactively 'org-delete-property-globally))
15859 ((equal c ?c)
15860 (call-interactively 'org-compute-property-at-point))
15861 (t (error "No such property action %c" c)))))
15863 (defun org-at-property-p ()
15864 "Is the cursor in a property line?"
15865 ;; FIXME: Does not check if we are actually in the drawer.
15866 ;; FIXME: also returns true on any drawers.....
15867 ;; This is used by C-c C-c for property action.
15868 (save-excursion
15869 (beginning-of-line 1)
15870 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
15872 (defmacro org-with-point-at (pom &rest body)
15873 "Move to buffer and point of point-or-marker POM for the duration of BODY."
15874 (declare (indent 1) (debug t))
15875 `(save-excursion
15876 (if (markerp pom) (set-buffer (marker-buffer pom)))
15877 (save-excursion
15878 (goto-char (or pom (point)))
15879 ,@body)))
15881 (defun org-get-property-block (&optional beg end force)
15882 "Return the (beg . end) range of the body of the property drawer.
15883 BEG and END can be beginning and end of subtree, if not given
15884 they will be found.
15885 If the drawer does not exist and FORCE is non-nil, create the drawer."
15886 (catch 'exit
15887 (save-excursion
15888 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
15889 (end (or end (progn (outline-next-heading) (point)))))
15890 (goto-char beg)
15891 (if (re-search-forward org-property-start-re end t)
15892 (setq beg (1+ (match-end 0)))
15893 (if force
15894 (save-excursion
15895 (org-insert-property-drawer)
15896 (setq end (progn (outline-next-heading) (point))))
15897 (throw 'exit nil))
15898 (goto-char beg)
15899 (if (re-search-forward org-property-start-re end t)
15900 (setq beg (1+ (match-end 0)))))
15901 (if (re-search-forward org-property-end-re end t)
15902 (setq end (match-beginning 0))
15903 (or force (throw 'exit nil))
15904 (goto-char beg)
15905 (setq end beg)
15906 (org-indent-line-function)
15907 (insert ":END:\n"))
15908 (cons beg end)))))
15910 (defun org-entry-properties (&optional pom which)
15911 "Get all properties of the entry at point-or-marker POM.
15912 This includes the TODO keyword, the tags, time strings for deadline,
15913 scheduled, and clocking, and any additional properties defined in the
15914 entry. The return value is an alist, keys may occur multiple times
15915 if the property key was used several times.
15916 POM may also be nil, in which case the current entry is used.
15917 If WHICH is nil or `all', get all properties. If WHICH is
15918 `special' or `standard', only get that subclass."
15919 (setq which (or which 'all))
15920 (org-with-point-at pom
15921 (let ((clockstr (substring org-clock-string 0 -1))
15922 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
15923 beg end range props sum-props key value string clocksum)
15924 (save-excursion
15925 (when (condition-case nil (org-back-to-heading t) (error nil))
15926 (setq beg (point))
15927 (setq sum-props (get-text-property (point) 'org-summaries))
15928 (setq clocksum (get-text-property (point) :org-clock-minutes))
15929 (outline-next-heading)
15930 (setq end (point))
15931 (when (memq which '(all special))
15932 ;; Get the special properties, like TODO and tags
15933 (goto-char beg)
15934 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15935 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15936 (when (looking-at org-priority-regexp)
15937 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15938 (when (and (setq value (org-get-tags-string))
15939 (string-match "\\S-" value))
15940 (push (cons "TAGS" value) props))
15941 (when (setq value (org-get-tags-at))
15942 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
15943 props))
15944 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15945 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
15946 string (if (equal key clockstr)
15947 (org-no-properties
15948 (org-trim
15949 (buffer-substring
15950 (match-beginning 3) (goto-char (point-at-eol)))))
15951 (substring (org-match-string-no-properties 3) 1 -1)))
15952 (unless key
15953 (if (= (char-after (match-beginning 3)) ?\[)
15954 (setq key "TIMESTAMP_IA")
15955 (setq key "TIMESTAMP")))
15956 (when (or (equal key clockstr) (not (assoc key props)))
15957 (push (cons key string) props)))
15961 (when (memq which '(all standard))
15962 ;; Get the standard properties, like :PORP: ...
15963 (setq range (org-get-property-block beg end))
15964 (when range
15965 (goto-char (car range))
15966 (while (re-search-forward
15967 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15968 (cdr range) t)
15969 (setq key (org-match-string-no-properties 1)
15970 value (org-trim (or (org-match-string-no-properties 2) "")))
15971 (unless (member key excluded)
15972 (push (cons key (or value "")) props)))))
15973 (if clocksum
15974 (push (cons "CLOCKSUM"
15975 (org-column-number-to-string (/ (float clocksum) 60.)
15976 'add_times))
15977 props))
15978 (append sum-props (nreverse props)))))))
15980 (defun org-entry-get (pom property &optional inherit)
15981 "Get value of PROPERTY for entry at point-or-marker POM.
15982 If INHERIT is non-nil and the entry does not have the property,
15983 then also check higher levels of the hierarchy.
15984 If the property is present but empty, the return value is the empty string.
15985 If the property is not present at all, nil is returned."
15986 (org-with-point-at pom
15987 (if inherit
15988 (org-entry-get-with-inheritance property)
15989 (if (member property org-special-properties)
15990 ;; We need a special property. Use brute force, get all properties.
15991 (cdr (assoc property (org-entry-properties nil 'special)))
15992 (let ((range (org-get-property-block)))
15993 (if (and range
15994 (goto-char (car range))
15995 (re-search-forward
15996 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
15997 (cdr range) t))
15998 ;; Found the property, return it.
15999 (if (match-end 1)
16000 (org-match-string-no-properties 1)
16001 "")))))))
16003 (defun org-entry-delete (pom property)
16004 "Delete the property PROPERTY from entry at point-or-marker POM."
16005 (org-with-point-at pom
16006 (if (member property org-special-properties)
16007 nil ; cannot delete these properties.
16008 (let ((range (org-get-property-block)))
16009 (if (and range
16010 (goto-char (car range))
16011 (re-search-forward
16012 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
16013 (cdr range) t))
16014 (progn
16015 (delete-region (match-beginning 0) (1+ (point-at-eol)))
16017 nil)))))
16019 ;; Multi-values properties are properties that contain multiple values
16020 ;; These values are assumed to be single words, separated by whitespace.
16021 (defun org-entry-add-to-multivalued-property (pom property value)
16022 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16023 (let* ((old (org-entry-get pom property))
16024 (values (and old (org-split-string old "[ \t]"))))
16025 (unless (member value values)
16026 (setq values (cons value values))
16027 (org-entry-put pom property
16028 (mapconcat 'identity values " ")))))
16030 (defun org-entry-remove-from-multivalued-property (pom property value)
16031 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16032 (let* ((old (org-entry-get pom property))
16033 (values (and old (org-split-string old "[ \t]"))))
16034 (when (member value values)
16035 (setq values (delete value values))
16036 (org-entry-put pom property
16037 (mapconcat 'identity values " ")))))
16039 (defun org-entry-member-in-multivalued-property (pom property value)
16040 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16041 (let* ((old (org-entry-get pom property))
16042 (values (and old (org-split-string old "[ \t]"))))
16043 (member value values)))
16045 (defvar org-entry-property-inherited-from (make-marker))
16047 (defun org-entry-get-with-inheritance (property)
16048 "Get entry property, and search higher levels if not present."
16049 (let (tmp)
16050 (save-excursion
16051 (save-restriction
16052 (widen)
16053 (catch 'ex
16054 (while t
16055 (when (setq tmp (org-entry-get nil property))
16056 (org-back-to-heading t)
16057 (move-marker org-entry-property-inherited-from (point))
16058 (throw 'ex tmp))
16059 (or (org-up-heading-safe) (throw 'ex nil)))))
16060 (or tmp (cdr (assoc property org-local-properties))
16061 (cdr (assoc property org-global-properties))))))
16063 (defun org-entry-put (pom property value)
16064 "Set PROPERTY to VALUE for entry at point-or-marker POM."
16065 (org-with-point-at pom
16066 (org-back-to-heading t)
16067 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
16068 range)
16069 (cond
16070 ((equal property "TODO")
16071 (when (and (stringp value) (string-match "\\S-" value)
16072 (not (member value org-todo-keywords-1)))
16073 (error "\"%s\" is not a valid TODO state" value))
16074 (if (or (not value)
16075 (not (string-match "\\S-" value)))
16076 (setq value 'none))
16077 (org-todo value)
16078 (org-set-tags nil 'align))
16079 ((equal property "PRIORITY")
16080 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
16081 (string-to-char value) ?\ ))
16082 (org-set-tags nil 'align))
16083 ((equal property "SCHEDULED")
16084 (if (re-search-forward org-scheduled-time-regexp end t)
16085 (cond
16086 ((eq value 'earlier) (org-timestamp-change -1 'day))
16087 ((eq value 'later) (org-timestamp-change 1 'day))
16088 (t (call-interactively 'org-schedule)))
16089 (call-interactively 'org-schedule)))
16090 ((equal property "DEADLINE")
16091 (if (re-search-forward org-deadline-time-regexp end t)
16092 (cond
16093 ((eq value 'earlier) (org-timestamp-change -1 'day))
16094 ((eq value 'later) (org-timestamp-change 1 'day))
16095 (t (call-interactively 'org-deadline)))
16096 (call-interactively 'org-deadline)))
16097 ((member property org-special-properties)
16098 (error "The %s property can not yet be set with `org-entry-put'"
16099 property))
16100 (t ; a non-special property
16101 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
16102 (setq range (org-get-property-block beg end 'force))
16103 (goto-char (car range))
16104 (if (re-search-forward
16105 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
16106 (progn
16107 (delete-region (match-beginning 1) (match-end 1))
16108 (goto-char (match-beginning 1)))
16109 (goto-char (cdr range))
16110 (insert "\n")
16111 (backward-char 1)
16112 (org-indent-line-function)
16113 (insert ":" property ":"))
16114 (and value (insert " " value))
16115 (org-indent-line-function)))))))
16117 (defun org-buffer-property-keys (&optional include-specials include-defaults)
16118 "Get all property keys in the current buffer.
16119 With INCLUDE-SPECIALS, also list the special properties that relect things
16120 like tags and TODO state.
16121 With INCLUDE-DEFAULTS, also include properties that has special meaning
16122 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING."
16123 (let (rtn range)
16124 (save-excursion
16125 (save-restriction
16126 (widen)
16127 (goto-char (point-min))
16128 (while (re-search-forward org-property-start-re nil t)
16129 (setq range (org-get-property-block))
16130 (goto-char (car range))
16131 (while (re-search-forward
16132 (org-re "^[ \t]*:\\([[:alnum:]_-]+\\):")
16133 (cdr range) t)
16134 (add-to-list 'rtn (org-match-string-no-properties 1)))
16135 (outline-next-heading))))
16137 (when include-specials
16138 (setq rtn (append org-special-properties rtn)))
16140 (when include-defaults
16141 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
16143 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
16145 (defun org-property-values (key)
16146 "Return a list of all values of property KEY."
16147 (save-excursion
16148 (save-restriction
16149 (widen)
16150 (goto-char (point-min))
16151 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
16152 values)
16153 (while (re-search-forward re nil t)
16154 (add-to-list 'values (org-trim (match-string 1))))
16155 (delete "" values)))))
16157 (defun org-insert-property-drawer ()
16158 "Insert a property drawer into the current entry."
16159 (interactive)
16160 (org-back-to-heading t)
16161 (looking-at outline-regexp)
16162 (let ((indent (- (match-end 0)(match-beginning 0)))
16163 (beg (point))
16164 (re (concat "^[ \t]*" org-keyword-time-regexp))
16165 end hiddenp)
16166 (outline-next-heading)
16167 (setq end (point))
16168 (goto-char beg)
16169 (while (re-search-forward re end t))
16170 (setq hiddenp (org-invisible-p))
16171 (end-of-line 1)
16172 (and (equal (char-after) ?\n) (forward-char 1))
16173 (org-skip-over-state-notes)
16174 (skip-chars-backward " \t\n\r")
16175 (if (eq (char-before) ?*) (forward-char 1))
16176 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
16177 (beginning-of-line 0)
16178 (indent-to-column indent)
16179 (beginning-of-line 2)
16180 (indent-to-column indent)
16181 (beginning-of-line 0)
16182 (if hiddenp
16183 (save-excursion
16184 (org-back-to-heading t)
16185 (hide-entry))
16186 (org-flag-drawer t))))
16188 (defun org-set-property (property value)
16189 "In the current entry, set PROPERTY to VALUE.
16190 When called interactively, this will prompt for a property name, offering
16191 completion on existing and default properties. And then it will prompt
16192 for a value, offering competion either on allowed values (via an inherited
16193 xxx_ALL property) or on existing values in other instances of this property
16194 in the current file."
16195 (interactive
16196 (let* ((prop (completing-read
16197 "Property: " (mapcar 'list (org-buffer-property-keys nil t))))
16198 (cur (org-entry-get nil prop))
16199 (allowed (org-property-get-allowed-values nil prop 'table))
16200 (existing (mapcar 'list (org-property-values prop)))
16201 (val (if allowed
16202 (completing-read "Value: " allowed nil 'req-match)
16203 (completing-read
16204 (concat "Value" (if (and cur (string-match "\\S-" cur))
16205 (concat "[" cur "]") "")
16206 ": ")
16207 existing nil nil "" nil cur))))
16208 (list prop (if (equal val "") cur val))))
16209 (unless (equal (org-entry-get nil property) value)
16210 (org-entry-put nil property value)))
16212 (defun org-delete-property (property)
16213 "In the current entry, delete PROPERTY."
16214 (interactive
16215 (let* ((prop (completing-read
16216 "Property: " (org-entry-properties nil 'standard))))
16217 (list prop)))
16218 (message "Property %s %s" property
16219 (if (org-entry-delete nil property)
16220 "deleted"
16221 "was not present in the entry")))
16223 (defun org-delete-property-globally (property)
16224 "Remove PROPERTY globally, from all entries."
16225 (interactive
16226 (let* ((prop (completing-read
16227 "Globally remove property: "
16228 (mapcar 'list (org-buffer-property-keys)))))
16229 (list prop)))
16230 (save-excursion
16231 (save-restriction
16232 (widen)
16233 (goto-char (point-min))
16234 (let ((cnt 0))
16235 (while (re-search-forward
16236 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16237 nil t)
16238 (setq cnt (1+ cnt))
16239 (replace-match ""))
16240 (message "Property \"%s\" removed from %d entries" property cnt)))))
16242 (defvar org-columns-current-fmt-compiled) ; defined below
16244 (defun org-compute-property-at-point ()
16245 "Compute the property at point.
16246 This looks for an enclosing column format, extracts the operator and
16247 then applies it to the proerty in the column format's scope."
16248 (interactive)
16249 (unless (org-at-property-p)
16250 (error "Not at a property"))
16251 (let ((prop (org-match-string-no-properties 2)))
16252 (org-columns-get-format-and-top-level)
16253 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16254 (error "No operator defined for property %s" prop))
16255 (org-columns-compute prop)))
16257 (defun org-property-get-allowed-values (pom property &optional table)
16258 "Get allowed values for the property PROPERTY.
16259 When TABLE is non-nil, return an alist that can directly be used for
16260 completion."
16261 (let (vals)
16262 (cond
16263 ((equal property "TODO")
16264 (setq vals (org-with-point-at pom
16265 (append org-todo-keywords-1 '("")))))
16266 ((equal property "PRIORITY")
16267 (let ((n org-lowest-priority))
16268 (while (>= n org-highest-priority)
16269 (push (char-to-string n) vals)
16270 (setq n (1- n)))))
16271 ((member property org-special-properties))
16273 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16275 (when (and vals (string-match "\\S-" vals))
16276 (setq vals (car (read-from-string (concat "(" vals ")"))))
16277 (setq vals (mapcar (lambda (x)
16278 (cond ((stringp x) x)
16279 ((numberp x) (number-to-string x))
16280 ((symbolp x) (symbol-name x))
16281 (t "???")))
16282 vals)))))
16283 (if table (mapcar 'list vals) vals)))
16285 (defun org-property-previous-allowed-value (&optional previous)
16286 "Switch to the next allowed value for this property."
16287 (interactive)
16288 (org-property-next-allowed-value t))
16290 (defun org-property-next-allowed-value (&optional previous)
16291 "Switch to the next allowed value for this property."
16292 (interactive)
16293 (unless (org-at-property-p)
16294 (error "Not at a property"))
16295 (let* ((key (match-string 2))
16296 (value (match-string 3))
16297 (allowed (or (org-property-get-allowed-values (point) key)
16298 (and (member value '("[ ]" "[-]" "[X]"))
16299 '("[ ]" "[X]"))))
16300 nval)
16301 (unless allowed
16302 (error "Allowed values for this property have not been defined"))
16303 (if previous (setq allowed (reverse allowed)))
16304 (if (member value allowed)
16305 (setq nval (car (cdr (member value allowed)))))
16306 (setq nval (or nval (car allowed)))
16307 (if (equal nval value)
16308 (error "Only one allowed value for this property"))
16309 (org-at-property-p)
16310 (replace-match (concat " :" key ": " nval) t t)
16311 (org-indent-line-function)
16312 (beginning-of-line 1)
16313 (skip-chars-forward " \t")))
16315 (defun org-find-entry-with-id (ident)
16316 "Locate the entry that contains the ID property with exact value IDENT.
16317 IDENT can be a string, a symbol or a number, this function will search for
16318 the string representation of it.
16319 Return the position where this entry starts, or nil if there is no such entry."
16320 (let ((id (cond
16321 ((stringp ident) ident)
16322 ((symbol-name ident) (symbol-name ident))
16323 ((numberp ident) (number-to-string ident))
16324 (t (error "IDENT %s must be a string, symbol or number" ident))))
16325 (case-fold-search nil))
16326 (save-excursion
16327 (save-restriction
16328 (goto-char (point-min))
16329 (when (re-search-forward
16330 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16331 nil t)
16332 (org-back-to-heading)
16333 (point))))))
16335 ;;; Column View
16337 (defvar org-columns-overlays nil
16338 "Holds the list of current column overlays.")
16340 (defvar org-columns-current-fmt nil
16341 "Local variable, holds the currently active column format.")
16342 (defvar org-columns-current-fmt-compiled nil
16343 "Local variable, holds the currently active column format.
16344 This is the compiled version of the format.")
16345 (defvar org-columns-current-widths nil
16346 "Loval variable, holds the currently widths of fields.")
16347 (defvar org-columns-current-maxwidths nil
16348 "Loval variable, holds the currently active maximum column widths.")
16349 (defvar org-columns-begin-marker (make-marker)
16350 "Points to the position where last a column creation command was called.")
16351 (defvar org-columns-top-level-marker (make-marker)
16352 "Points to the position where current columns region starts.")
16354 (defvar org-columns-map (make-sparse-keymap)
16355 "The keymap valid in column display.")
16357 (defun org-columns-content ()
16358 "Switch to contents view while in columns view."
16359 (interactive)
16360 (org-overview)
16361 (org-content))
16363 (org-defkey org-columns-map "c" 'org-columns-content)
16364 (org-defkey org-columns-map "o" 'org-overview)
16365 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16366 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16367 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16368 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16369 (org-defkey org-columns-map "v" 'org-columns-show-value)
16370 (org-defkey org-columns-map "q" 'org-columns-quit)
16371 (org-defkey org-columns-map "r" 'org-columns-redo)
16372 (org-defkey org-columns-map "g" 'org-columns-redo)
16373 (org-defkey org-columns-map [left] 'backward-char)
16374 (org-defkey org-columns-map "\M-b" 'backward-char)
16375 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16376 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16377 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16378 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16379 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16380 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16381 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16382 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16383 (org-defkey org-columns-map "<" 'org-columns-narrow)
16384 (org-defkey org-columns-map ">" 'org-columns-widen)
16385 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16386 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16387 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16388 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16390 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16391 '("Column"
16392 ["Edit property" org-columns-edit-value t]
16393 ["Next allowed value" org-columns-next-allowed-value t]
16394 ["Previous allowed value" org-columns-previous-allowed-value t]
16395 ["Show full value" org-columns-show-value t]
16396 ["Edit allowed values" org-columns-edit-allowed t]
16397 "--"
16398 ["Edit column attributes" org-columns-edit-attributes t]
16399 ["Increase column width" org-columns-widen t]
16400 ["Decrease column width" org-columns-narrow t]
16401 "--"
16402 ["Move column right" org-columns-move-right t]
16403 ["Move column left" org-columns-move-left t]
16404 ["Add column" org-columns-new t]
16405 ["Delete column" org-columns-delete t]
16406 "--"
16407 ["CONTENTS" org-columns-content t]
16408 ["OVERVIEW" org-overview t]
16409 ["Refresh columns display" org-columns-redo t]
16410 "--"
16411 ["Open link" org-columns-open-link t]
16412 "--"
16413 ["Quit" org-columns-quit t]))
16415 (defun org-columns-new-overlay (beg end &optional string face)
16416 "Create a new column overlay and add it to the list."
16417 (let ((ov (org-make-overlay beg end)))
16418 (org-overlay-put ov 'face (or face 'secondary-selection))
16419 (org-overlay-display ov string face)
16420 (push ov org-columns-overlays)
16421 ov))
16423 (defun org-columns-display-here (&optional props)
16424 "Overlay the current line with column display."
16425 (interactive)
16426 (let* ((fmt org-columns-current-fmt-compiled)
16427 (beg (point-at-bol))
16428 (level-face (save-excursion
16429 (beginning-of-line 1)
16430 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16431 (org-get-level-face 2))))
16432 (color (list :foreground
16433 (face-attribute (or level-face 'default) :foreground)))
16434 props pom property ass width f string ov column val modval)
16435 ;; Check if the entry is in another buffer.
16436 (unless props
16437 (if (eq major-mode 'org-agenda-mode)
16438 (setq pom (or (get-text-property (point) 'org-hd-marker)
16439 (get-text-property (point) 'org-marker))
16440 props (if pom (org-entry-properties pom) nil))
16441 (setq props (org-entry-properties nil))))
16442 ;; Walk the format
16443 (while (setq column (pop fmt))
16444 (setq property (car column)
16445 ass (if (equal property "ITEM")
16446 (cons "ITEM"
16447 (save-match-data
16448 (org-no-properties
16449 (org-remove-tabs
16450 (buffer-substring-no-properties
16451 (point-at-bol) (point-at-eol))))))
16452 (assoc property props))
16453 width (or (cdr (assoc property org-columns-current-maxwidths))
16454 (nth 2 column)
16455 (length property))
16456 f (format "%%-%d.%ds | " width width)
16457 val (or (cdr ass) "")
16458 modval (if (equal property "ITEM")
16459 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16460 string (format f (or modval val)))
16461 ;; Create the overlay
16462 (org-unmodified
16463 (setq ov (org-columns-new-overlay
16464 beg (setq beg (1+ beg)) string
16465 (list color 'org-column)))
16466 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16467 (org-overlay-put ov 'keymap org-columns-map)
16468 (org-overlay-put ov 'org-columns-key property)
16469 (org-overlay-put ov 'org-columns-value (cdr ass))
16470 (org-overlay-put ov 'org-columns-value-modified modval)
16471 (org-overlay-put ov 'org-columns-pom pom)
16472 (org-overlay-put ov 'org-columns-format f))
16473 (if (or (not (char-after beg))
16474 (equal (char-after beg) ?\n))
16475 (let ((inhibit-read-only t))
16476 (save-excursion
16477 (goto-char beg)
16478 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16479 ;; Make the rest of the line disappear.
16480 (org-unmodified
16481 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16482 (org-overlay-put ov 'invisible t)
16483 (org-overlay-put ov 'keymap org-columns-map)
16484 (org-overlay-put ov 'intangible t)
16485 (push ov org-columns-overlays)
16486 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16487 (org-overlay-put ov 'keymap org-columns-map)
16488 (push ov org-columns-overlays)
16489 (let ((inhibit-read-only t))
16490 (put-text-property (max (point-min) (1- (point-at-bol)))
16491 (min (point-max) (1+ (point-at-eol)))
16492 'read-only "Type `e' to edit property")))))
16494 (defvar org-previous-header-line-format nil
16495 "The header line format before column view was turned on.")
16496 (defvar org-columns-inhibit-recalculation nil
16497 "Inhibit recomputing of columns on column view startup.")
16500 (defvar header-line-format)
16501 (defun org-columns-display-here-title ()
16502 "Overlay the newline before the current line with the table title."
16503 (interactive)
16504 (let ((fmt org-columns-current-fmt-compiled)
16505 string (title "")
16506 property width f column str widths)
16507 (while (setq column (pop fmt))
16508 (setq property (car column)
16509 str (or (nth 1 column) property)
16510 width (or (cdr (assoc property org-columns-current-maxwidths))
16511 (nth 2 column)
16512 (length str))
16513 widths (push width widths)
16514 f (format "%%-%d.%ds | " width width)
16515 string (format f str)
16516 title (concat title string)))
16517 (setq title (concat
16518 (org-add-props " " nil 'display '(space :align-to 0))
16519 (org-add-props title nil 'face '(:weight bold :underline t))))
16520 (org-set-local 'org-previous-header-line-format header-line-format)
16521 (org-set-local 'org-columns-current-widths (nreverse widths))
16522 (setq header-line-format title)))
16524 (defun org-columns-remove-overlays ()
16525 "Remove all currently active column overlays."
16526 (interactive)
16527 (when (marker-buffer org-columns-begin-marker)
16528 (with-current-buffer (marker-buffer org-columns-begin-marker)
16529 (when (local-variable-p 'org-previous-header-line-format)
16530 (setq header-line-format org-previous-header-line-format)
16531 (kill-local-variable 'org-previous-header-line-format))
16532 (move-marker org-columns-begin-marker nil)
16533 (move-marker org-columns-top-level-marker nil)
16534 (org-unmodified
16535 (mapc 'org-delete-overlay org-columns-overlays)
16536 (setq org-columns-overlays nil)
16537 (let ((inhibit-read-only t))
16538 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16540 (defun org-columns-cleanup-item (item fmt)
16541 "Remove from ITEM what is a column in the format FMT."
16542 (if (not org-complex-heading-regexp)
16543 item
16544 (when (string-match org-complex-heading-regexp item)
16545 (concat
16546 (org-add-props (concat (match-string 1 item) " ") nil
16547 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16548 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16549 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16550 " " (match-string 4 item)
16551 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16553 (defun org-columns-show-value ()
16554 "Show the full value of the property."
16555 (interactive)
16556 (let ((value (get-char-property (point) 'org-columns-value)))
16557 (message "Value is: %s" (or value ""))))
16559 (defun org-columns-quit ()
16560 "Remove the column overlays and in this way exit column editing."
16561 (interactive)
16562 (org-unmodified
16563 (org-columns-remove-overlays)
16564 (let ((inhibit-read-only t))
16565 (remove-text-properties (point-min) (point-max) '(read-only t))))
16566 (when (eq major-mode 'org-agenda-mode)
16567 (message
16568 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16570 (defun org-columns-check-computed ()
16571 "Check if this column value is computed.
16572 If yes, throw an error indicating that changing it does not make sense."
16573 (let ((val (get-char-property (point) 'org-columns-value)))
16574 (when (and (stringp val)
16575 (get-char-property 0 'org-computed val))
16576 (error "This value is computed from the entry's children"))))
16578 (defun org-columns-todo (&optional arg)
16579 "Change the TODO state during column view."
16580 (interactive "P")
16581 (org-columns-edit-value "TODO"))
16583 (defun org-columns-set-tags-or-toggle (&optional arg)
16584 "Toggle checkbox at point, or set tags for current headline."
16585 (interactive "P")
16586 (if (string-match "\\`\\[[ xX-]\\]\\'"
16587 (get-char-property (point) 'org-columns-value))
16588 (org-columns-next-allowed-value)
16589 (org-columns-edit-value "TAGS")))
16591 (defun org-columns-edit-value (&optional key)
16592 "Edit the value of the property at point in column view.
16593 Where possible, use the standard interface for changing this line."
16594 (interactive)
16595 (org-columns-check-computed)
16596 (let* ((external-key key)
16597 (col (current-column))
16598 (key (or key (get-char-property (point) 'org-columns-key)))
16599 (value (get-char-property (point) 'org-columns-value))
16600 (bol (point-at-bol)) (eol (point-at-eol))
16601 (pom (or (get-text-property bol 'org-hd-marker)
16602 (point))) ; keep despite of compiler waring
16603 (line-overlays
16604 (delq nil (mapcar (lambda (x)
16605 (and (eq (overlay-buffer x) (current-buffer))
16606 (>= (overlay-start x) bol)
16607 (<= (overlay-start x) eol)
16609 org-columns-overlays)))
16610 nval eval allowed)
16611 (cond
16612 ((equal key "CLOCKSUM")
16613 (error "This special column cannot be edited"))
16614 ((equal key "ITEM")
16615 (setq eval '(org-with-point-at pom
16616 (org-edit-headline))))
16617 ((equal key "TODO")
16618 (setq eval '(org-with-point-at pom
16619 (let ((current-prefix-arg
16620 (if external-key current-prefix-arg '(4))))
16621 (call-interactively 'org-todo)))))
16622 ((equal key "PRIORITY")
16623 (setq eval '(org-with-point-at pom
16624 (call-interactively 'org-priority))))
16625 ((equal key "TAGS")
16626 (setq eval '(org-with-point-at pom
16627 (let ((org-fast-tag-selection-single-key
16628 (if (eq org-fast-tag-selection-single-key 'expert)
16629 t org-fast-tag-selection-single-key)))
16630 (call-interactively 'org-set-tags)))))
16631 ((equal key "DEADLINE")
16632 (setq eval '(org-with-point-at pom
16633 (call-interactively 'org-deadline))))
16634 ((equal key "SCHEDULED")
16635 (setq eval '(org-with-point-at pom
16636 (call-interactively 'org-schedule))))
16638 (setq allowed (org-property-get-allowed-values pom key 'table))
16639 (if allowed
16640 (setq nval (completing-read "Value: " allowed nil t))
16641 (setq nval (read-string "Edit: " value)))
16642 (setq nval (org-trim nval))
16643 (when (not (equal nval value))
16644 (setq eval '(org-entry-put pom key nval)))))
16645 (when eval
16646 (let ((inhibit-read-only t))
16647 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
16648 (unwind-protect
16649 (progn
16650 (setq org-columns-overlays
16651 (org-delete-all line-overlays org-columns-overlays))
16652 (mapc 'org-delete-overlay line-overlays)
16653 (org-columns-eval eval))
16654 (org-columns-display-here))))
16655 (move-to-column col)
16656 (if (and (org-mode-p)
16657 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16658 (org-columns-update key))))
16660 (defun org-edit-headline () ; FIXME: this is not columns specific
16661 "Edit the current headline, the part without TODO keyword, TAGS."
16662 (org-back-to-heading)
16663 (when (looking-at org-todo-line-regexp)
16664 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
16665 (txt (match-string 3))
16666 (post "")
16667 txt2)
16668 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
16669 (setq post (match-string 0 txt)
16670 txt (substring txt 0 (match-beginning 0))))
16671 (setq txt2 (read-string "Edit: " txt))
16672 (when (not (equal txt txt2))
16673 (beginning-of-line 1)
16674 (insert pre txt2 post)
16675 (delete-region (point) (point-at-eol))
16676 (org-set-tags nil t)))))
16678 (defun org-columns-edit-allowed ()
16679 "Edit the list of allowed values for the current property."
16680 (interactive)
16681 (let* ((key (get-char-property (point) 'org-columns-key))
16682 (key1 (concat key "_ALL"))
16683 (allowed (org-entry-get (point) key1 t))
16684 nval)
16685 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
16686 (setq nval (read-string "Allowed: " allowed))
16687 (org-entry-put
16688 (cond ((marker-position org-entry-property-inherited-from)
16689 org-entry-property-inherited-from)
16690 ((marker-position org-columns-top-level-marker)
16691 org-columns-top-level-marker))
16692 key1 nval)))
16694 (defmacro org-no-warnings (&rest body)
16695 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
16697 (defun org-columns-eval (form)
16698 (let (hidep)
16699 (save-excursion
16700 (beginning-of-line 1)
16701 ;; `next-line' is needed here, because it skips invisible line.
16702 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
16703 (setq hidep (org-on-heading-p 1)))
16704 (eval form)
16705 (and hidep (hide-entry))))
16707 (defun org-columns-previous-allowed-value ()
16708 "Switch to the previous allowed value for this column."
16709 (interactive)
16710 (org-columns-next-allowed-value t))
16712 (defun org-columns-next-allowed-value (&optional previous)
16713 "Switch to the next allowed value for this column."
16714 (interactive)
16715 (org-columns-check-computed)
16716 (let* ((col (current-column))
16717 (key (get-char-property (point) 'org-columns-key))
16718 (value (get-char-property (point) 'org-columns-value))
16719 (bol (point-at-bol)) (eol (point-at-eol))
16720 (pom (or (get-text-property bol 'org-hd-marker)
16721 (point))) ; keep despite of compiler waring
16722 (line-overlays
16723 (delq nil (mapcar (lambda (x)
16724 (and (eq (overlay-buffer x) (current-buffer))
16725 (>= (overlay-start x) bol)
16726 (<= (overlay-start x) eol)
16728 org-columns-overlays)))
16729 (allowed (or (org-property-get-allowed-values pom key)
16730 (and (equal
16731 (nth 4 (assoc key org-columns-current-fmt-compiled))
16732 'checkbox) '("[ ]" "[X]"))))
16733 nval)
16734 (when (equal key "ITEM")
16735 (error "Cannot edit item headline from here"))
16736 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
16737 (error "Allowed values for this property have not been defined"))
16738 (if (member key '("SCHEDULED" "DEADLINE"))
16739 (setq nval (if previous 'earlier 'later))
16740 (if previous (setq allowed (reverse allowed)))
16741 (if (member value allowed)
16742 (setq nval (car (cdr (member value allowed)))))
16743 (setq nval (or nval (car allowed)))
16744 (if (equal nval value)
16745 (error "Only one allowed value for this property")))
16746 (let ((inhibit-read-only t))
16747 (remove-text-properties (1- bol) eol '(read-only t))
16748 (unwind-protect
16749 (progn
16750 (setq org-columns-overlays
16751 (org-delete-all line-overlays org-columns-overlays))
16752 (mapc 'org-delete-overlay line-overlays)
16753 (org-columns-eval '(org-entry-put pom key nval)))
16754 (org-columns-display-here)))
16755 (move-to-column col)
16756 (if (and (org-mode-p)
16757 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16758 (org-columns-update key))))
16760 (defun org-verify-version (task)
16761 (cond
16762 ((eq task 'columns)
16763 (if (or (featurep 'xemacs)
16764 (< emacs-major-version 22))
16765 (error "Emacs 22 is required for the columns feature")))))
16767 (defun org-columns-open-link (&optional arg)
16768 (interactive "P")
16769 (let ((key (get-char-property (point) 'org-columns-key))
16770 (value (get-char-property (point) 'org-columns-value)))
16771 (org-open-link-from-string arg)))
16773 (defun org-open-link-from-string (s &optional arg)
16774 "Open a link in the string S, as if it was in Org-mode."
16775 (interactive)
16776 (with-temp-buffer
16777 (let ((org-inhibit-startup t))
16778 (org-mode)
16779 (insert s)
16780 (goto-char (point-min))
16781 (org-open-at-point arg))))
16783 (defun org-columns-get-format-and-top-level ()
16784 (let (fmt)
16785 (when (condition-case nil (org-back-to-heading) (error nil))
16786 (move-marker org-entry-property-inherited-from nil)
16787 (setq fmt (org-entry-get nil "COLUMNS" t)))
16788 (setq fmt (or fmt org-columns-default-format))
16789 (org-set-local 'org-columns-current-fmt fmt)
16790 (org-columns-compile-format fmt)
16791 (if (marker-position org-entry-property-inherited-from)
16792 (move-marker org-columns-top-level-marker
16793 org-entry-property-inherited-from)
16794 (move-marker org-columns-top-level-marker (point)))
16795 fmt))
16797 (defun org-columns ()
16798 "Turn on column view on an org-mode file."
16799 (interactive)
16800 (org-verify-version 'columns)
16801 (org-columns-remove-overlays)
16802 (move-marker org-columns-begin-marker (point))
16803 (let (beg end fmt cache maxwidths clocksump)
16804 (setq fmt (org-columns-get-format-and-top-level))
16805 (save-excursion
16806 (goto-char org-columns-top-level-marker)
16807 (setq beg (point))
16808 (unless org-columns-inhibit-recalculation
16809 (org-columns-compute-all))
16810 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
16811 (point-max)))
16812 ;; Get and cache the properties
16813 (goto-char beg)
16814 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
16815 (setq clocksump t)
16816 (save-excursion
16817 (save-restriction
16818 (narrow-to-region beg end)
16819 (org-clock-sum))))
16820 (while (re-search-forward (concat "^" outline-regexp) end t)
16821 (push (cons (org-current-line) (org-entry-properties)) cache))
16822 (when cache
16823 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16824 (org-set-local 'org-columns-current-maxwidths maxwidths)
16825 (org-columns-display-here-title)
16826 (mapc (lambda (x)
16827 (goto-line (car x))
16828 (org-columns-display-here (cdr x)))
16829 cache)))))
16831 (defun org-columns-new (&optional prop title width op fmt &rest rest)
16832 "Insert a new column, to the leeft o the current column."
16833 (interactive)
16834 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
16835 cell)
16836 (setq prop (completing-read
16837 "Property: " (mapcar 'list (org-buffer-property-keys t))
16838 nil nil prop))
16839 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
16840 (setq width (read-string "Column width: " (if width (number-to-string width))))
16841 (if (string-match "\\S-" width)
16842 (setq width (string-to-number width))
16843 (setq width nil))
16844 (setq fmt (completing-read "Summary [none]: "
16845 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox"))
16846 nil t))
16847 (if (string-match "\\S-" fmt)
16848 (setq fmt (intern fmt))
16849 (setq fmt nil))
16850 (if (eq fmt 'none) (setq fmt nil))
16851 (if editp
16852 (progn
16853 (setcar editp prop)
16854 (setcdr editp (list title width nil fmt)))
16855 (setq cell (nthcdr (1- (current-column))
16856 org-columns-current-fmt-compiled))
16857 (setcdr cell (cons (list prop title width nil fmt)
16858 (cdr cell))))
16859 (org-columns-store-format)
16860 (org-columns-redo)))
16862 (defun org-columns-delete ()
16863 "Delete the column at point from columns view."
16864 (interactive)
16865 (let* ((n (current-column))
16866 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
16867 (when (y-or-n-p
16868 (format "Are you sure you want to remove column \"%s\"? " title))
16869 (setq org-columns-current-fmt-compiled
16870 (delq (nth n org-columns-current-fmt-compiled)
16871 org-columns-current-fmt-compiled))
16872 (org-columns-store-format)
16873 (org-columns-redo)
16874 (if (>= (current-column) (length org-columns-current-fmt-compiled))
16875 (backward-char 1)))))
16877 (defun org-columns-edit-attributes ()
16878 "Edit the attributes of the current column."
16879 (interactive)
16880 (let* ((n (current-column))
16881 (info (nth n org-columns-current-fmt-compiled)))
16882 (apply 'org-columns-new info)))
16884 (defun org-columns-widen (arg)
16885 "Make the column wider by ARG characters."
16886 (interactive "p")
16887 (let* ((n (current-column))
16888 (entry (nth n org-columns-current-fmt-compiled))
16889 (width (or (nth 2 entry)
16890 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
16891 (setq width (max 1 (+ width arg)))
16892 (setcar (nthcdr 2 entry) width)
16893 (org-columns-store-format)
16894 (org-columns-redo)))
16896 (defun org-columns-narrow (arg)
16897 "Make the column nrrower by ARG characters."
16898 (interactive "p")
16899 (org-columns-widen (- arg)))
16901 (defun org-columns-move-right ()
16902 "Swap this column with the one to the right."
16903 (interactive)
16904 (let* ((n (current-column))
16905 (cell (nthcdr n org-columns-current-fmt-compiled))
16907 (when (>= n (1- (length org-columns-current-fmt-compiled)))
16908 (error "Cannot shift this column further to the right"))
16909 (setq e (car cell))
16910 (setcar cell (car (cdr cell)))
16911 (setcdr cell (cons e (cdr (cdr cell))))
16912 (org-columns-store-format)
16913 (org-columns-redo)
16914 (forward-char 1)))
16916 (defun org-columns-move-left ()
16917 "Swap this column with the one to the left."
16918 (interactive)
16919 (let* ((n (current-column)))
16920 (when (= n 0)
16921 (error "Cannot shift this column further to the left"))
16922 (backward-char 1)
16923 (org-columns-move-right)
16924 (backward-char 1)))
16926 (defun org-columns-store-format ()
16927 "Store the text version of the current columns format in appropriate place.
16928 This is either in the COLUMNS property of the node starting the current column
16929 display, or in the #+COLUMNS line of the current buffer."
16930 (let (fmt (cnt 0))
16931 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
16932 (org-set-local 'org-columns-current-fmt fmt)
16933 (if (marker-position org-columns-top-level-marker)
16934 (save-excursion
16935 (goto-char org-columns-top-level-marker)
16936 (if (and (org-at-heading-p)
16937 (org-entry-get nil "COLUMNS"))
16938 (org-entry-put nil "COLUMNS" fmt)
16939 (goto-char (point-min))
16940 ;; Overwrite all #+COLUMNS lines....
16941 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
16942 (setq cnt (1+ cnt))
16943 (replace-match (concat "#+COLUMNS: " fmt) t t))
16944 (unless (> cnt 0)
16945 (goto-char (point-min))
16946 (or (org-on-heading-p t) (outline-next-heading))
16947 (let ((inhibit-read-only t))
16948 (insert-before-markers "#+COLUMNS: " fmt "\n")))
16949 (org-set-local 'org-columns-default-format fmt))))))
16951 (defvar org-overriding-columns-format nil
16952 "When set, overrides any other definition.")
16953 (defvar org-agenda-view-columns-initially nil
16954 "When set, switch to columns view immediately after creating the agenda.")
16956 (defun org-agenda-columns ()
16957 "Turn on column view in the agenda."
16958 (interactive)
16959 (org-verify-version 'columns)
16960 (org-columns-remove-overlays)
16961 (move-marker org-columns-begin-marker (point))
16962 (let (fmt cache maxwidths m)
16963 (cond
16964 ((and (local-variable-p 'org-overriding-columns-format)
16965 org-overriding-columns-format)
16966 (setq fmt org-overriding-columns-format))
16967 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
16968 (setq fmt (org-entry-get m "COLUMNS" t)))
16969 ((and (boundp 'org-columns-current-fmt)
16970 (local-variable-p 'org-columns-current-fmt)
16971 org-columns-current-fmt)
16972 (setq fmt org-columns-current-fmt))
16973 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
16974 (setq m (get-text-property m 'org-hd-marker))
16975 (setq fmt (org-entry-get m "COLUMNS" t))))
16976 (setq fmt (or fmt org-columns-default-format))
16977 (org-set-local 'org-columns-current-fmt fmt)
16978 (org-columns-compile-format fmt)
16979 (save-excursion
16980 ;; Get and cache the properties
16981 (goto-char (point-min))
16982 (while (not (eobp))
16983 (when (setq m (or (get-text-property (point) 'org-hd-marker)
16984 (get-text-property (point) 'org-marker)))
16985 (push (cons (org-current-line) (org-entry-properties m)) cache))
16986 (beginning-of-line 2))
16987 (when cache
16988 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16989 (org-set-local 'org-columns-current-maxwidths maxwidths)
16990 (org-columns-display-here-title)
16991 (mapc (lambda (x)
16992 (goto-line (car x))
16993 (org-columns-display-here (cdr x)))
16994 cache)))))
16996 (defun org-columns-get-autowidth-alist (s cache)
16997 "Derive the maximum column widths from the format and the cache."
16998 (let ((start 0) rtn)
16999 (while (string-match (org-re "%\\([[:alpha:]]\\S-*\\)") s start)
17000 (push (cons (match-string 1 s) 1) rtn)
17001 (setq start (match-end 0)))
17002 (mapc (lambda (x)
17003 (setcdr x (apply 'max
17004 (mapcar
17005 (lambda (y)
17006 (length (or (cdr (assoc (car x) (cdr y))) " ")))
17007 cache))))
17008 rtn)
17009 rtn))
17011 (defun org-columns-compute-all ()
17012 "Compute all columns that have operators defined."
17013 (org-unmodified
17014 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
17015 (let ((columns org-columns-current-fmt-compiled) col)
17016 (while (setq col (pop columns))
17017 (when (nth 3 col)
17018 (save-excursion
17019 (org-columns-compute (car col)))))))
17021 (defun org-columns-update (property)
17022 "Recompute PROPERTY, and update the columns display for it."
17023 (org-columns-compute property)
17024 (let (fmt val pos)
17025 (save-excursion
17026 (mapc (lambda (ov)
17027 (when (equal (org-overlay-get ov 'org-columns-key) property)
17028 (setq pos (org-overlay-start ov))
17029 (goto-char pos)
17030 (when (setq val (cdr (assoc property
17031 (get-text-property
17032 (point-at-bol) 'org-summaries))))
17033 (setq fmt (org-overlay-get ov 'org-columns-format))
17034 (org-overlay-put ov 'org-columns-value val)
17035 (org-overlay-put ov 'display (format fmt val)))))
17036 org-columns-overlays))))
17038 (defun org-columns-compute (property)
17039 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
17040 (interactive)
17041 (let* ((re (concat "^" outline-regexp))
17042 (lmax 30) ; Does anyone use deeper levels???
17043 (lsum (make-vector lmax 0))
17044 (lflag (make-vector lmax nil))
17045 (level 0)
17046 (ass (assoc property org-columns-current-fmt-compiled))
17047 (format (nth 4 ass))
17048 (printf (nth 5 ass))
17049 (beg org-columns-top-level-marker)
17050 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
17051 (save-excursion
17052 ;; Find the region to compute
17053 (goto-char beg)
17054 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
17055 (goto-char end)
17056 ;; Walk the tree from the back and do the computations
17057 (while (re-search-backward re beg t)
17058 (setq sumpos (match-beginning 0)
17059 last-level level
17060 level (org-outline-level)
17061 val (org-entry-get nil property)
17062 valflag (and val (string-match "\\S-" val)))
17063 (cond
17064 ((< level last-level)
17065 ;; put the sum of lower levels here as a property
17066 (setq sum (aref lsum last-level) ; current sum
17067 flag (aref lflag last-level) ; any valid entries from children?
17068 str (org-column-number-to-string sum format printf)
17069 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
17070 useval (if flag str1 (if valflag val ""))
17071 sum-alist (get-text-property sumpos 'org-summaries))
17072 (if (assoc property sum-alist)
17073 (setcdr (assoc property sum-alist) useval)
17074 (push (cons property useval) sum-alist)
17075 (org-unmodified
17076 (add-text-properties sumpos (1+ sumpos)
17077 (list 'org-summaries sum-alist))))
17078 (when val
17079 (org-entry-put nil property (if flag str val)))
17080 ;; add current to current level accumulator
17081 (when (or flag valflag)
17082 (aset lsum level (+ (aref lsum level)
17083 (if flag sum (org-column-string-to-number
17084 (if flag str val) format))))
17085 (aset lflag level t))
17086 ;; clear accumulators for deeper levels
17087 (loop for l from (1+ level) to (1- lmax) do
17088 (aset lsum l 0)
17089 (aset lflag l nil)))
17090 ((>= level last-level)
17091 ;; add what we have here to the accumulator for this level
17092 (aset lsum level (+ (aref lsum level)
17093 (org-column-string-to-number (or val "0") format)))
17094 (and valflag (aset lflag level t)))
17095 (t (error "This should not happen")))))))
17097 (defun org-columns-redo ()
17098 "Construct the column display again."
17099 (interactive)
17100 (message "Recomputing columns...")
17101 (save-excursion
17102 (if (marker-position org-columns-begin-marker)
17103 (goto-char org-columns-begin-marker))
17104 (org-columns-remove-overlays)
17105 (if (org-mode-p)
17106 (call-interactively 'org-columns)
17107 (call-interactively 'org-agenda-columns)))
17108 (message "Recomputing columns...done"))
17110 (defun org-columns-not-in-agenda ()
17111 (if (eq major-mode 'org-agenda-mode)
17112 (error "This command is only allowed in Org-mode buffers")))
17115 (defun org-string-to-number (s)
17116 "Convert string to number, and interpret hh:mm:ss."
17117 (if (not (string-match ":" s))
17118 (string-to-number s)
17119 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17120 (while l
17121 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17122 sum)))
17124 (defun org-column-number-to-string (n fmt &optional printf)
17125 "Convert a computed column number to a string value, according to FMT."
17126 (cond
17127 ((eq fmt 'add_times)
17128 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
17129 (format "%d:%02d" h m)))
17130 ((eq fmt 'checkbox)
17131 (cond ((= n (floor n)) "[X]")
17132 ((> n 1.) "[-]")
17133 (t "[ ]")))
17134 (printf (format printf n))
17135 ((eq fmt 'currency)
17136 (format "%.2f" n))
17137 (t (number-to-string n))))
17139 (defun org-column-string-to-number (s fmt)
17140 "Convert a column value to a number that can be used for column computing."
17141 (cond
17142 ((string-match ":" s)
17143 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17144 (while l
17145 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17146 sum))
17147 ((eq fmt 'checkbox)
17148 (if (equal s "[X]") 1. 0.000001))
17149 (t (string-to-number s))))
17151 (defun org-columns-uncompile-format (cfmt)
17152 "Turn the compiled columns format back into a string representation."
17153 (let ((rtn "") e s prop title op width fmt printf)
17154 (while (setq e (pop cfmt))
17155 (setq prop (car e)
17156 title (nth 1 e)
17157 width (nth 2 e)
17158 op (nth 3 e)
17159 fmt (nth 4 e)
17160 printf (nth 5 e))
17161 (cond
17162 ((eq fmt 'add_times) (setq op ":"))
17163 ((eq fmt 'checkbox) (setq op "X"))
17164 ((eq fmt 'add_numbers) (setq op "+"))
17165 ((eq fmt 'currency) (setq op "$")))
17166 (if (and op printf) (setq op (concat op ";" printf)))
17167 (if (equal title prop) (setq title nil))
17168 (setq s (concat "%" (if width (number-to-string width))
17169 prop
17170 (if title (concat "(" title ")"))
17171 (if op (concat "{" op "}"))))
17172 (setq rtn (concat rtn " " s)))
17173 (org-trim rtn)))
17175 (defun org-columns-compile-format (fmt)
17176 "Turn a column format string into an alist of specifications.
17177 The alist has one entry for each column in the format. The elements of
17178 that list are:
17179 property the property
17180 title the title field for the columns
17181 width the column width in characters, can be nil for automatic
17182 operator the operator if any
17183 format the output format for computed results, derived from operator
17184 printf a printf format for computed values"
17185 (let ((start 0) width prop title op f printf)
17186 (setq org-columns-current-fmt-compiled nil)
17187 (while (string-match
17188 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
17189 fmt start)
17190 (setq start (match-end 0)
17191 width (match-string 1 fmt)
17192 prop (match-string 2 fmt)
17193 title (or (match-string 3 fmt) prop)
17194 op (match-string 4 fmt)
17195 f nil
17196 printf nil)
17197 (if width (setq width (string-to-number width)))
17198 (when (and op (string-match ";" op))
17199 (setq printf (substring op (match-end 0))
17200 op (substring op 0 (match-beginning 0))))
17201 (cond
17202 ((equal op "+") (setq f 'add_numbers))
17203 ((equal op "$") (setq f 'currency))
17204 ((equal op ":") (setq f 'add_times))
17205 ((equal op "X") (setq f 'checkbox)))
17206 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
17207 (setq org-columns-current-fmt-compiled
17208 (nreverse org-columns-current-fmt-compiled))))
17211 ;;; Dynamic block for Column view
17213 (defun org-columns-capture-view ()
17214 "Get the column view of the current buffer and return it as a list.
17215 The list will contains the title row and all other rows. Each row is
17216 a list of fields."
17217 (save-excursion
17218 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
17219 (n (length title)) row tbl)
17220 (goto-char (point-min))
17221 (while (re-search-forward "^\\*+ " nil t)
17222 (when (get-char-property (match-beginning 0) 'org-columns-key)
17223 (setq row nil)
17224 (loop for i from 0 to (1- n) do
17225 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
17226 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
17228 row))
17229 (setq row (nreverse row))
17230 (push row tbl)))
17231 (append (list title 'hline) (nreverse tbl)))))
17233 (defun org-dblock-write:columnview (params)
17234 "Write the column view table.
17235 PARAMS is a property list of parameters:
17237 :width enforce same column widths with <N> specifiers.
17238 :id the :ID: property of the entry where the columns view
17239 should be built, as a string. When `local', call locally.
17240 When `global' call column view with the cursor at the beginning
17241 of the buffer (usually this means that the whole buffer switches
17242 to column view).
17243 :hlines When t, insert a hline before each item. When a number, insert
17244 a hline before each level <= that number.
17245 :vlines When t, make each column a colgroup to enforce vertical lines."
17246 (let ((pos (move-marker (make-marker) (point)))
17247 (hlines (plist-get params :hlines))
17248 (vlines (plist-get params :vlines))
17249 tbl id idpos nfields tmp)
17250 (save-excursion
17251 (save-restriction
17252 (when (setq id (plist-get params :id))
17253 (cond ((not id) nil)
17254 ((eq id 'global) (goto-char (point-min)))
17255 ((eq id 'local) nil)
17256 ((setq idpos (org-find-entry-with-id id))
17257 (goto-char idpos))
17258 (t (error "Cannot find entry with :ID: %s" id))))
17259 (org-columns)
17260 (setq tbl (org-columns-capture-view))
17261 (setq nfields (length (car tbl)))
17262 (org-columns-quit)))
17263 (goto-char pos)
17264 (move-marker pos nil)
17265 (when tbl
17266 (when (plist-get params :hlines)
17267 (setq tmp nil)
17268 (while tbl
17269 (if (eq (car tbl) 'hline)
17270 (push (pop tbl) tmp)
17271 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17272 (if (and (not (eq (car tmp) 'hline))
17273 (or (eq hlines t)
17274 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17275 (push 'hline tmp)))
17276 (push (pop tbl) tmp)))
17277 (setq tbl (nreverse tmp)))
17278 (when vlines
17279 (setq tbl (mapcar (lambda (x)
17280 (if (eq 'hline x) x (cons "" x)))
17281 tbl))
17282 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17283 (setq pos (point))
17284 (insert (org-listtable-to-string tbl))
17285 (when (plist-get params :width)
17286 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17287 org-columns-current-widths "|")))
17288 (goto-char pos)
17289 (org-table-align))))
17291 (defun org-listtable-to-string (tbl)
17292 "Convert a listtable TBL to a string that contains the Org-mode table.
17293 The table still need to be alligned. The resulting string has no leading
17294 and tailing newline characters."
17295 (mapconcat
17296 (lambda (x)
17297 (cond
17298 ((listp x)
17299 (concat "|" (mapconcat 'identity x "|") "|"))
17300 ((eq x 'hline) "|-|")
17301 (t (error "Garbage in listtable: %s" x))))
17302 tbl "\n"))
17304 (defun org-insert-columns-dblock ()
17305 "Create a dynamic block capturing a column view table."
17306 (interactive)
17307 (let ((defaults '(:name "columnview" :hlines 1))
17308 (id (completing-read
17309 "Capture columns (local, global, entry with :ID: property) [local]: "
17310 (append '(("global") ("local"))
17311 (mapcar 'list (org-property-values "ID"))))))
17312 (if (equal id "") (setq id 'local))
17313 (if (equal id "global") (setq id 'global))
17314 (setq defaults (append defaults (list :id id)))
17315 (org-create-dblock defaults)
17316 (org-update-dblock)))
17318 ;;;; Timestamps
17320 (defvar org-last-changed-timestamp nil)
17321 (defvar org-time-was-given) ; dynamically scoped parameter
17322 (defvar org-end-time-was-given) ; dynamically scoped parameter
17323 (defvar org-ts-what) ; dynamically scoped parameter
17325 (defun org-time-stamp (arg)
17326 "Prompt for a date/time and insert a time stamp.
17327 If the user specifies a time like HH:MM, or if this command is called
17328 with a prefix argument, the time stamp will contain date and time.
17329 Otherwise, only the date will be included. All parts of a date not
17330 specified by the user will be filled in from the current date/time.
17331 So if you press just return without typing anything, the time stamp
17332 will represent the current date/time. If there is already a timestamp
17333 at the cursor, it will be modified."
17334 (interactive "P")
17335 (let* ((ts nil)
17336 (default-time
17337 ;; Default time is either today, or, when entering a range,
17338 ;; the range start.
17339 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17340 (save-excursion
17341 (re-search-backward
17342 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17343 (- (point) 20) t)))
17344 (apply 'encode-time (org-parse-time-string (match-string 1)))
17345 (current-time)))
17346 (default-input (and ts (org-get-compact-tod ts)))
17347 org-time-was-given org-end-time-was-given time)
17348 (cond
17349 ((and (org-at-timestamp-p)
17350 (eq last-command 'org-time-stamp)
17351 (eq this-command 'org-time-stamp))
17352 (insert "--")
17353 (setq time (let ((this-command this-command))
17354 (org-read-date arg 'totime nil nil default-time default-input)))
17355 (org-insert-time-stamp time (or org-time-was-given arg)))
17356 ((org-at-timestamp-p)
17357 (setq time (let ((this-command this-command))
17358 (org-read-date arg 'totime nil nil default-time default-input)))
17359 (when (org-at-timestamp-p) ; just to get the match data
17360 (replace-match "")
17361 (setq org-last-changed-timestamp
17362 (org-insert-time-stamp
17363 time (or org-time-was-given arg)
17364 nil nil nil (list org-end-time-was-given))))
17365 (message "Timestamp updated"))
17367 (setq time (let ((this-command this-command))
17368 (org-read-date arg 'totime nil nil default-time default-input)))
17369 (org-insert-time-stamp time (or org-time-was-given arg)
17370 nil nil nil (list org-end-time-was-given))))))
17372 ;; FIXME: can we use this for something else????
17373 ;; like computing time differences?????
17374 (defun org-get-compact-tod (s)
17375 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17376 (let* ((t1 (match-string 1 s))
17377 (h1 (string-to-number (match-string 2 s)))
17378 (m1 (string-to-number (match-string 3 s)))
17379 (t2 (and (match-end 4) (match-string 5 s)))
17380 (h2 (and t2 (string-to-number (match-string 6 s))))
17381 (m2 (and t2 (string-to-number (match-string 7 s))))
17382 dh dm)
17383 (if (not t2)
17385 (setq dh (- h2 h1) dm (- m2 m1))
17386 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17387 (concat t1 "+" (number-to-string dh)
17388 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17390 (defun org-time-stamp-inactive (&optional arg)
17391 "Insert an inactive time stamp.
17392 An inactive time stamp is enclosed in square brackets instead of angle
17393 brackets. It is inactive in the sense that it does not trigger agenda entries,
17394 does not link to the calendar and cannot be changed with the S-cursor keys.
17395 So these are more for recording a certain time/date."
17396 (interactive "P")
17397 (let (org-time-was-given org-end-time-was-given time)
17398 (setq time (org-read-date arg 'totime))
17399 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17400 nil nil (list org-end-time-was-given))))
17402 (defvar org-date-ovl (org-make-overlay 1 1))
17403 (org-overlay-put org-date-ovl 'face 'org-warning)
17404 (org-detach-overlay org-date-ovl)
17406 (defvar org-ans1) ; dynamically scoped parameter
17407 (defvar org-ans2) ; dynamically scoped parameter
17409 (defvar org-plain-time-of-day-regexp) ; defined below
17411 (defvar org-read-date-overlay nil)
17412 (defvar org-dcst nil) ; dynamically scoped
17414 (defun org-read-date (&optional with-time to-time from-string prompt
17415 default-time default-input)
17416 "Read a date, possibly a time, and make things smooth for the user.
17417 The prompt will suggest to enter an ISO date, but you can also enter anything
17418 which will at least partially be understood by `parse-time-string'.
17419 Unrecognized parts of the date will default to the current day, month, year,
17420 hour and minute. If this command is called to replace a timestamp at point,
17421 of to enter the second timestamp of a range, the default time is taken from the
17422 existing stamp. For example,
17423 3-2-5 --> 2003-02-05
17424 feb 15 --> currentyear-02-15
17425 sep 12 9 --> 2009-09-12
17426 12:45 --> today 12:45
17427 22 sept 0:34 --> currentyear-09-22 0:34
17428 12 --> currentyear-currentmonth-12
17429 Fri --> nearest Friday (today or later)
17430 etc.
17432 Furthermore you can specify a relative date by giving, as the *first* thing
17433 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17434 change in days weeks, months, years.
17435 With a single plus or minus, the date is relative to today. With a double
17436 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17437 +4d --> four days from today
17438 +4 --> same as above
17439 +2w --> two weeks from today
17440 ++5 --> five days from default date
17442 The function understands only English month and weekday abbreviations,
17443 but this can be configured with the variables `parse-time-months' and
17444 `parse-time-weekdays'.
17446 While prompting, a calendar is popped up - you can also select the
17447 date with the mouse (button 1). The calendar shows a period of three
17448 months. To scroll it to other months, use the keys `>' and `<'.
17449 If you don't like the calendar, turn it off with
17450 \(setq org-read-date-popup-calendar nil)
17452 With optional argument TO-TIME, the date will immediately be converted
17453 to an internal time.
17454 With an optional argument WITH-TIME, the prompt will suggest to also
17455 insert a time. Note that when WITH-TIME is not set, you can still
17456 enter a time, and this function will inform the calling routine about
17457 this change. The calling routine may then choose to change the format
17458 used to insert the time stamp into the buffer to include the time.
17459 With optional argument FROM-STRING, read from this string instead from
17460 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17461 the time/date that is used for everything that is not specified by the
17462 user."
17463 (require 'parse-time)
17464 (let* ((org-time-stamp-rounding-minutes
17465 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
17466 (org-dcst org-display-custom-times)
17467 (ct (org-current-time))
17468 (def (or default-time ct))
17469 (defdecode (decode-time def))
17470 (dummy (progn
17471 (when (< (nth 2 defdecode) org-extend-today-until)
17472 (setcar (nthcdr 2 defdecode) -1)
17473 (setcar (nthcdr 1 defdecode) 59)
17474 (setq def (apply 'encode-time defdecode)
17475 defdecode (decode-time def)))))
17476 (calendar-move-hook nil)
17477 (view-diary-entries-initially nil)
17478 (view-calendar-holidays-initially nil)
17479 (timestr (format-time-string
17480 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17481 (prompt (concat (if prompt (concat prompt " ") "")
17482 (format "Date+time [%s]: " timestr)))
17483 ans (org-ans0 "") org-ans1 org-ans2 final)
17485 (cond
17486 (from-string (setq ans from-string))
17487 (org-read-date-popup-calendar
17488 (save-excursion
17489 (save-window-excursion
17490 (calendar)
17491 (calendar-forward-day (- (time-to-days def)
17492 (calendar-absolute-from-gregorian
17493 (calendar-current-date))))
17494 (org-eval-in-calendar nil t)
17495 (let* ((old-map (current-local-map))
17496 (map (copy-keymap calendar-mode-map))
17497 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17498 (org-defkey map (kbd "RET") 'org-calendar-select)
17499 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17500 'org-calendar-select-mouse)
17501 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17502 'org-calendar-select-mouse)
17503 (org-defkey minibuffer-local-map [(meta shift left)]
17504 (lambda () (interactive)
17505 (org-eval-in-calendar '(calendar-backward-month 1))))
17506 (org-defkey minibuffer-local-map [(meta shift right)]
17507 (lambda () (interactive)
17508 (org-eval-in-calendar '(calendar-forward-month 1))))
17509 (org-defkey minibuffer-local-map [(meta shift up)]
17510 (lambda () (interactive)
17511 (org-eval-in-calendar '(calendar-backward-year 1))))
17512 (org-defkey minibuffer-local-map [(meta shift down)]
17513 (lambda () (interactive)
17514 (org-eval-in-calendar '(calendar-forward-year 1))))
17515 (org-defkey minibuffer-local-map [(shift up)]
17516 (lambda () (interactive)
17517 (org-eval-in-calendar '(calendar-backward-week 1))))
17518 (org-defkey minibuffer-local-map [(shift down)]
17519 (lambda () (interactive)
17520 (org-eval-in-calendar '(calendar-forward-week 1))))
17521 (org-defkey minibuffer-local-map [(shift left)]
17522 (lambda () (interactive)
17523 (org-eval-in-calendar '(calendar-backward-day 1))))
17524 (org-defkey minibuffer-local-map [(shift right)]
17525 (lambda () (interactive)
17526 (org-eval-in-calendar '(calendar-forward-day 1))))
17527 (org-defkey minibuffer-local-map ">"
17528 (lambda () (interactive)
17529 (org-eval-in-calendar '(scroll-calendar-left 1))))
17530 (org-defkey minibuffer-local-map "<"
17531 (lambda () (interactive)
17532 (org-eval-in-calendar '(scroll-calendar-right 1))))
17533 (unwind-protect
17534 (progn
17535 (use-local-map map)
17536 (add-hook 'post-command-hook 'org-read-date-display)
17537 (setq org-ans0 (read-string prompt default-input nil nil))
17538 ;; org-ans0: from prompt
17539 ;; org-ans1: from mouse click
17540 ;; org-ans2: from calendar motion
17541 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17542 (remove-hook 'post-command-hook 'org-read-date-display)
17543 (use-local-map old-map)
17544 (when org-read-date-overlay
17545 (org-delete-overlay org-read-date-overlay)
17546 (setq org-read-date-overlay nil)))))))
17548 (t ; Naked prompt only
17549 (unwind-protect
17550 (setq ans (read-string prompt default-input nil timestr))
17551 (when org-read-date-overlay
17552 (org-delete-overlay org-read-date-overlay)
17553 (setq org-read-date-overlay nil)))))
17555 (setq final (org-read-date-analyze ans def defdecode))
17557 (if to-time
17558 (apply 'encode-time final)
17559 (if (and (boundp 'org-time-was-given) org-time-was-given)
17560 (format "%04d-%02d-%02d %02d:%02d"
17561 (nth 5 final) (nth 4 final) (nth 3 final)
17562 (nth 2 final) (nth 1 final))
17563 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17564 (defvar def)
17565 (defvar defdecode)
17566 (defvar with-time)
17567 (defun org-read-date-display ()
17568 "Display the currrent date prompt interpretation in the minibuffer."
17569 (when org-read-date-display-live
17570 (when org-read-date-overlay
17571 (org-delete-overlay org-read-date-overlay))
17572 (let ((p (point)))
17573 (end-of-line 1)
17574 (while (not (equal (buffer-substring
17575 (max (point-min) (- (point) 4)) (point))
17576 " "))
17577 (insert " "))
17578 (goto-char p))
17579 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17580 " " (or org-ans1 org-ans2)))
17581 (org-end-time-was-given nil)
17582 (f (org-read-date-analyze ans def defdecode))
17583 (fmts (if org-dcst
17584 org-time-stamp-custom-formats
17585 org-time-stamp-formats))
17586 (fmt (if (or with-time
17587 (and (boundp 'org-time-was-given) org-time-was-given))
17588 (cdr fmts)
17589 (car fmts)))
17590 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
17591 (when (and org-end-time-was-given
17592 (string-match org-plain-time-of-day-regexp txt))
17593 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17594 org-end-time-was-given
17595 (substring txt (match-end 0)))))
17596 (setq org-read-date-overlay
17597 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17598 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
17600 (defun org-read-date-analyze (ans def defdecode)
17601 "Analyze the combined answer of the date prompt."
17602 ;; FIXME: cleanup and comment
17603 (let (delta deltan deltaw deltadef year month day
17604 hour minute second wday pm h2 m2 tl wday1)
17606 (when (setq delta (org-read-date-get-relative ans (current-time) def))
17607 (setq ans (replace-match "" t t ans)
17608 deltan (car delta)
17609 deltaw (nth 1 delta)
17610 deltadef (nth 2 delta)))
17612 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
17613 (when (string-match
17614 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17615 (setq year (if (match-end 2)
17616 (string-to-number (match-string 2 ans))
17617 (string-to-number (format-time-string "%Y")))
17618 month (string-to-number (match-string 3 ans))
17619 day (string-to-number (match-string 4 ans)))
17620 (if (< year 100) (setq year (+ 2000 year)))
17621 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17622 t nil ans)))
17623 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17624 ;; If there is a time with am/pm, and *no* time without it, we convert
17625 ;; so that matching will be successful.
17626 (loop for i from 1 to 2 do ; twice, for end time as well
17627 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17628 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17629 (setq hour (string-to-number (match-string 1 ans))
17630 minute (if (match-end 3)
17631 (string-to-number (match-string 3 ans))
17633 pm (equal ?p
17634 (string-to-char (downcase (match-string 4 ans)))))
17635 (if (and (= hour 12) (not pm))
17636 (setq hour 0)
17637 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17638 (setq ans (replace-match (format "%02d:%02d" hour minute)
17639 t t ans))))
17641 ;; Check if a time range is given as a duration
17642 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17643 (setq hour (string-to-number (match-string 1 ans))
17644 h2 (+ hour (string-to-number (match-string 3 ans)))
17645 minute (string-to-number (match-string 2 ans))
17646 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
17647 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17648 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
17650 ;; Check if there is a time range
17651 (when (boundp 'org-end-time-was-given)
17652 (setq org-time-was-given nil)
17653 (when (and (string-match org-plain-time-of-day-regexp ans)
17654 (match-end 8))
17655 (setq org-end-time-was-given (match-string 8 ans))
17656 (setq ans (concat (substring ans 0 (match-beginning 7))
17657 (substring ans (match-end 7))))))
17659 (setq tl (parse-time-string ans)
17660 day (or (nth 3 tl) (nth 3 defdecode))
17661 month (or (nth 4 tl)
17662 (if (and org-read-date-prefer-future
17663 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
17664 (1+ (nth 4 defdecode))
17665 (nth 4 defdecode)))
17666 year (or (nth 5 tl)
17667 (if (and org-read-date-prefer-future
17668 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
17669 (1+ (nth 5 defdecode))
17670 (nth 5 defdecode)))
17671 hour (or (nth 2 tl) (nth 2 defdecode))
17672 minute (or (nth 1 tl) (nth 1 defdecode))
17673 second (or (nth 0 tl) 0)
17674 wday (nth 6 tl))
17675 (when deltan
17676 (unless deltadef
17677 (let ((now (decode-time (current-time))))
17678 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17679 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17680 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17681 ((equal deltaw "m") (setq month (+ month deltan)))
17682 ((equal deltaw "y") (setq year (+ year deltan)))))
17683 (when (and wday (not (nth 3 tl)))
17684 ;; Weekday was given, but no day, so pick that day in the week
17685 ;; on or after the derived date.
17686 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17687 (unless (equal wday wday1)
17688 (setq day (+ day (% (- wday wday1 -7) 7)))))
17689 (if (and (boundp 'org-time-was-given)
17690 (nth 2 tl))
17691 (setq org-time-was-given t))
17692 (if (< year 100) (setq year (+ 2000 year)))
17693 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
17694 (list second minute hour day month year)))
17696 (defvar parse-time-weekdays)
17698 (defun org-read-date-get-relative (s today default)
17699 "Check string S for special relative date string.
17700 TODAY and DEFAULT are internal times, for today and for a default.
17701 Return shift list (N what def-flag)
17702 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17703 N is the number of WHATs to shift.
17704 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17705 the DEFAULT date rather than TODAY."
17706 (when (string-match
17707 (concat
17708 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
17709 "\\([0-9]+\\)?"
17710 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17711 "\\([ \t]\\|$\\)") s)
17712 (let* ((dir (if (match-end 1)
17713 (string-to-char (substring (match-string 1 s) -1))
17714 ?+))
17715 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17716 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17717 (what (if (match-end 3) (match-string 3 s) "d"))
17718 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17719 (date (if rel default today))
17720 (wday (nth 6 (decode-time date)))
17721 delta)
17722 (if wday1
17723 (progn
17724 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17725 (if (= dir ?-) (setq delta (- delta 7)))
17726 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17727 (list delta "d" rel))
17728 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17730 (defun org-eval-in-calendar (form &optional keepdate)
17731 "Eval FORM in the calendar window and return to current window.
17732 Also, store the cursor date in variable org-ans2."
17733 (let ((sw (selected-window)))
17734 (select-window (get-buffer-window "*Calendar*"))
17735 (eval form)
17736 (when (and (not keepdate) (calendar-cursor-to-date))
17737 (let* ((date (calendar-cursor-to-date))
17738 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17739 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17740 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17741 (select-window sw)))
17743 ; ;; Update the prompt to show new default date
17744 ; (save-excursion
17745 ; (goto-char (point-min))
17746 ; (when (and org-ans2
17747 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
17748 ; (get-text-property (match-end 0) 'field))
17749 ; (let ((inhibit-read-only t))
17750 ; (replace-match (concat "[" org-ans2 "]") t t)
17751 ; (add-text-properties (point-min) (1+ (match-end 0))
17752 ; (text-properties-at (1+ (point-min)))))))))
17754 (defun org-calendar-select ()
17755 "Return to `org-read-date' with the date currently selected.
17756 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17757 (interactive)
17758 (when (calendar-cursor-to-date)
17759 (let* ((date (calendar-cursor-to-date))
17760 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17761 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17762 (if (active-minibuffer-window) (exit-minibuffer))))
17764 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17765 "Insert a date stamp for the date given by the internal TIME.
17766 WITH-HM means, use the stamp format that includes the time of the day.
17767 INACTIVE means use square brackets instead of angular ones, so that the
17768 stamp will not contribute to the agenda.
17769 PRE and POST are optional strings to be inserted before and after the
17770 stamp.
17771 The command returns the inserted time stamp."
17772 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17773 stamp)
17774 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17775 (insert-before-markers (or pre ""))
17776 (insert-before-markers (setq stamp (format-time-string fmt time)))
17777 (when (listp extra)
17778 (setq extra (car extra))
17779 (if (and (stringp extra)
17780 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17781 (setq extra (format "-%02d:%02d"
17782 (string-to-number (match-string 1 extra))
17783 (string-to-number (match-string 2 extra))))
17784 (setq extra nil)))
17785 (when extra
17786 (backward-char 1)
17787 (insert-before-markers extra)
17788 (forward-char 1))
17789 (insert-before-markers (or post ""))
17790 stamp))
17792 (defun org-toggle-time-stamp-overlays ()
17793 "Toggle the use of custom time stamp formats."
17794 (interactive)
17795 (setq org-display-custom-times (not org-display-custom-times))
17796 (unless org-display-custom-times
17797 (let ((p (point-min)) (bmp (buffer-modified-p)))
17798 (while (setq p (next-single-property-change p 'display))
17799 (if (and (get-text-property p 'display)
17800 (eq (get-text-property p 'face) 'org-date))
17801 (remove-text-properties
17802 p (setq p (next-single-property-change p 'display))
17803 '(display t))))
17804 (set-buffer-modified-p bmp)))
17805 (if (featurep 'xemacs)
17806 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17807 (org-restart-font-lock)
17808 (setq org-table-may-need-update t)
17809 (if org-display-custom-times
17810 (message "Time stamps are overlayed with custom format")
17811 (message "Time stamp overlays removed")))
17813 (defun org-display-custom-time (beg end)
17814 "Overlay modified time stamp format over timestamp between BED and END."
17815 (let* ((ts (buffer-substring beg end))
17816 t1 w1 with-hm tf time str w2 (off 0))
17817 (save-match-data
17818 (setq t1 (org-parse-time-string ts t))
17819 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
17820 (setq off (- (match-end 0) (match-beginning 0)))))
17821 (setq end (- end off))
17822 (setq w1 (- end beg)
17823 with-hm (and (nth 1 t1) (nth 2 t1))
17824 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17825 time (org-fix-decoded-time t1)
17826 str (org-add-props
17827 (format-time-string
17828 (substring tf 1 -1) (apply 'encode-time time))
17829 nil 'mouse-face 'highlight)
17830 w2 (length str))
17831 (if (not (= w2 w1))
17832 (add-text-properties (1+ beg) (+ 2 beg)
17833 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17834 (if (featurep 'xemacs)
17835 (progn
17836 (put-text-property beg end 'invisible t)
17837 (put-text-property beg end 'end-glyph (make-glyph str)))
17838 (put-text-property beg end 'display str))))
17840 (defun org-translate-time (string)
17841 "Translate all timestamps in STRING to custom format.
17842 But do this only if the variable `org-display-custom-times' is set."
17843 (when org-display-custom-times
17844 (save-match-data
17845 (let* ((start 0)
17846 (re org-ts-regexp-both)
17847 t1 with-hm inactive tf time str beg end)
17848 (while (setq start (string-match re string start))
17849 (setq beg (match-beginning 0)
17850 end (match-end 0)
17851 t1 (save-match-data
17852 (org-parse-time-string (substring string beg end) t))
17853 with-hm (and (nth 1 t1) (nth 2 t1))
17854 inactive (equal (substring string beg (1+ beg)) "[")
17855 tf (funcall (if with-hm 'cdr 'car)
17856 org-time-stamp-custom-formats)
17857 time (org-fix-decoded-time t1)
17858 str (format-time-string
17859 (concat
17860 (if inactive "[" "<") (substring tf 1 -1)
17861 (if inactive "]" ">"))
17862 (apply 'encode-time time))
17863 string (replace-match str t t string)
17864 start (+ start (length str)))))))
17865 string)
17867 (defun org-fix-decoded-time (time)
17868 "Set 0 instead of nil for the first 6 elements of time.
17869 Don't touch the rest."
17870 (let ((n 0))
17871 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17873 (defun org-days-to-time (timestamp-string)
17874 "Difference between TIMESTAMP-STRING and now in days."
17875 (- (time-to-days (org-time-string-to-time timestamp-string))
17876 (time-to-days (current-time))))
17878 (defun org-deadline-close (timestamp-string &optional ndays)
17879 "Is the time in TIMESTAMP-STRING close to the current date?"
17880 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17881 (and (< (org-days-to-time timestamp-string) ndays)
17882 (not (org-entry-is-done-p))))
17884 (defun org-get-wdays (ts)
17885 "Get the deadline lead time appropriate for timestring TS."
17886 (cond
17887 ((<= org-deadline-warning-days 0)
17888 ;; 0 or negative, enforce this value no matter what
17889 (- org-deadline-warning-days))
17890 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
17891 ;; lead time is specified.
17892 (floor (* (string-to-number (match-string 1 ts))
17893 (cdr (assoc (match-string 2 ts)
17894 '(("d" . 1) ("w" . 7)
17895 ("m" . 30.4) ("y" . 365.25)))))))
17896 ;; go for the default.
17897 (t org-deadline-warning-days)))
17899 (defun org-calendar-select-mouse (ev)
17900 "Return to `org-read-date' with the date currently selected.
17901 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17902 (interactive "e")
17903 (mouse-set-point ev)
17904 (when (calendar-cursor-to-date)
17905 (let* ((date (calendar-cursor-to-date))
17906 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17907 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17908 (if (active-minibuffer-window) (exit-minibuffer))))
17910 (defun org-check-deadlines (ndays)
17911 "Check if there are any deadlines due or past due.
17912 A deadline is considered due if it happens within `org-deadline-warning-days'
17913 days from today's date. If the deadline appears in an entry marked DONE,
17914 it is not shown. The prefix arg NDAYS can be used to test that many
17915 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17916 (interactive "P")
17917 (let* ((org-warn-days
17918 (cond
17919 ((equal ndays '(4)) 100000)
17920 (ndays (prefix-numeric-value ndays))
17921 (t (abs org-deadline-warning-days))))
17922 (case-fold-search nil)
17923 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17924 (callback
17925 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17927 (message "%d deadlines past-due or due within %d days"
17928 (org-occur regexp nil callback)
17929 org-warn-days)))
17931 (defun org-check-before-date (date)
17932 "Check if there are deadlines or scheduled entries before DATE."
17933 (interactive (list (org-read-date)))
17934 (let ((case-fold-search nil)
17935 (regexp (concat "\\<\\(" org-deadline-string
17936 "\\|" org-scheduled-string
17937 "\\) *<\\([^>]+\\)>"))
17938 (callback
17939 (lambda () (time-less-p
17940 (org-time-string-to-time (match-string 2))
17941 (org-time-string-to-time date)))))
17942 (message "%d entries before %s"
17943 (org-occur regexp nil callback) date)))
17945 (defun org-evaluate-time-range (&optional to-buffer)
17946 "Evaluate a time range by computing the difference between start and end.
17947 Normally the result is just printed in the echo area, but with prefix arg
17948 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17949 If the time range is actually in a table, the result is inserted into the
17950 next column.
17951 For time difference computation, a year is assumed to be exactly 365
17952 days in order to avoid rounding problems."
17953 (interactive "P")
17955 (org-clock-update-time-maybe)
17956 (save-excursion
17957 (unless (org-at-date-range-p t)
17958 (goto-char (point-at-bol))
17959 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17960 (if (not (org-at-date-range-p t))
17961 (error "Not at a time-stamp range, and none found in current line")))
17962 (let* ((ts1 (match-string 1))
17963 (ts2 (match-string 2))
17964 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17965 (match-end (match-end 0))
17966 (time1 (org-time-string-to-time ts1))
17967 (time2 (org-time-string-to-time ts2))
17968 (t1 (time-to-seconds time1))
17969 (t2 (time-to-seconds time2))
17970 (diff (abs (- t2 t1)))
17971 (negative (< (- t2 t1) 0))
17972 ;; (ys (floor (* 365 24 60 60)))
17973 (ds (* 24 60 60))
17974 (hs (* 60 60))
17975 (fy "%dy %dd %02d:%02d")
17976 (fy1 "%dy %dd")
17977 (fd "%dd %02d:%02d")
17978 (fd1 "%dd")
17979 (fh "%02d:%02d")
17980 y d h m align)
17981 (if havetime
17982 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17984 d (floor (/ diff ds)) diff (mod diff ds)
17985 h (floor (/ diff hs)) diff (mod diff hs)
17986 m (floor (/ diff 60)))
17987 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17989 d (floor (+ (/ diff ds) 0.5))
17990 h 0 m 0))
17991 (if (not to-buffer)
17992 (message "%s" (org-make-tdiff-string y d h m))
17993 (if (org-at-table-p)
17994 (progn
17995 (goto-char match-end)
17996 (setq align t)
17997 (and (looking-at " *|") (goto-char (match-end 0))))
17998 (goto-char match-end))
17999 (if (looking-at
18000 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
18001 (replace-match ""))
18002 (if negative (insert " -"))
18003 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
18004 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
18005 (insert " " (format fh h m))))
18006 (if align (org-table-align))
18007 (message "Time difference inserted")))))
18009 (defun org-make-tdiff-string (y d h m)
18010 (let ((fmt "")
18011 (l nil))
18012 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
18013 l (push y l)))
18014 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
18015 l (push d l)))
18016 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
18017 l (push h l)))
18018 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
18019 l (push m l)))
18020 (apply 'format fmt (nreverse l))))
18022 (defun org-time-string-to-time (s)
18023 (apply 'encode-time (org-parse-time-string s)))
18025 (defun org-time-string-to-absolute (s &optional daynr prefer)
18026 "Convert a time stamp to an absolute day number.
18027 If there is a specifyer for a cyclic time stamp, get the closest date to
18028 DAYNR."
18029 (cond
18030 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
18031 (if (org-diary-sexp-entry (match-string 1 s) "" date)
18032 daynr
18033 (+ daynr 1000)))
18034 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
18035 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
18036 (time-to-days (current-time))) (match-string 0 s)
18037 prefer))
18038 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
18040 (defun org-time-from-absolute (d)
18041 "Return the time corresponding to date D.
18042 D may be an absolute day number, or a calendar-type list (month day year)."
18043 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
18044 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
18046 (defun org-calendar-holiday ()
18047 "List of holidays, for Diary display in Org-mode."
18048 (require 'holidays)
18049 (let ((hl (funcall
18050 (if (fboundp 'calendar-check-holidays)
18051 'calendar-check-holidays 'check-calendar-holidays) date)))
18052 (if hl (mapconcat 'identity hl "; "))))
18054 (defun org-diary-sexp-entry (sexp entry date)
18055 "Process a SEXP diary ENTRY for DATE."
18056 (require 'diary-lib)
18057 (let ((result (if calendar-debug-sexp
18058 (let ((stack-trace-on-error t))
18059 (eval (car (read-from-string sexp))))
18060 (condition-case nil
18061 (eval (car (read-from-string sexp)))
18062 (error
18063 (beep)
18064 (message "Bad sexp at line %d in %s: %s"
18065 (org-current-line)
18066 (buffer-file-name) sexp)
18067 (sleep-for 2))))))
18068 (cond ((stringp result) result)
18069 ((and (consp result)
18070 (stringp (cdr result))) (cdr result))
18071 (result entry)
18072 (t nil))))
18074 (defun org-diary-to-ical-string (frombuf)
18075 "Get iCalendar entries from diary entries in buffer FROMBUF.
18076 This uses the icalendar.el library."
18077 (let* ((tmpdir (if (featurep 'xemacs)
18078 (temp-directory)
18079 temporary-file-directory))
18080 (tmpfile (make-temp-name
18081 (expand-file-name "orgics" tmpdir)))
18082 buf rtn b e)
18083 (save-excursion
18084 (set-buffer frombuf)
18085 (icalendar-export-region (point-min) (point-max) tmpfile)
18086 (setq buf (find-buffer-visiting tmpfile))
18087 (set-buffer buf)
18088 (goto-char (point-min))
18089 (if (re-search-forward "^BEGIN:VEVENT" nil t)
18090 (setq b (match-beginning 0)))
18091 (goto-char (point-max))
18092 (if (re-search-backward "^END:VEVENT" nil t)
18093 (setq e (match-end 0)))
18094 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
18095 (kill-buffer buf)
18096 (kill-buffer frombuf)
18097 (delete-file tmpfile)
18098 rtn))
18100 (defun org-closest-date (start current change prefer)
18101 "Find the date closest to CURRENT that is consistent with START and CHANGE.
18102 When PREFER is `past' return a date that is either CURRENT or past.
18103 When PREFER is `future', return a date that is either CURRENT or future."
18104 ;; Make the proper lists from the dates
18105 (catch 'exit
18106 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
18107 dn dw sday cday n1 n2
18108 d m y y1 y2 date1 date2 nmonths nm ny m2)
18110 (setq start (org-date-to-gregorian start)
18111 current (org-date-to-gregorian
18112 (if org-agenda-repeating-timestamp-show-all
18113 current
18114 (time-to-days (current-time))))
18115 sday (calendar-absolute-from-gregorian start)
18116 cday (calendar-absolute-from-gregorian current))
18118 (if (<= cday sday) (throw 'exit sday))
18120 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
18121 (setq dn (string-to-number (match-string 1 change))
18122 dw (cdr (assoc (match-string 2 change) a1)))
18123 (error "Invalid change specifyer: %s" change))
18124 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
18125 (cond
18126 ((eq dw 'day)
18127 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
18128 n2 (+ n1 dn)))
18129 ((eq dw 'year)
18130 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
18131 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
18132 (setq date1 (list m d y1)
18133 n1 (calendar-absolute-from-gregorian date1)
18134 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
18135 n2 (calendar-absolute-from-gregorian date2)))
18136 ((eq dw 'month)
18137 ;; approx number of month between the tow dates
18138 (setq nmonths (floor (/ (- cday sday) 30.436875)))
18139 ;; How often does dn fit in there?
18140 (setq d (nth 1 start) m (car start) y (nth 2 start)
18141 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
18142 m (+ m nm)
18143 ny (floor (/ m 12))
18144 y (+ y ny)
18145 m (- m (* ny 12)))
18146 (while (> m 12) (setq m (- m 12) y (1+ y)))
18147 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
18148 (setq m2 (+ m dn) y2 y)
18149 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18150 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
18151 (while (< n2 cday)
18152 (setq n1 n2 m m2 y y2)
18153 (setq m2 (+ m dn) y2 y)
18154 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18155 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
18157 (if org-agenda-repeating-timestamp-show-all
18158 (cond
18159 ((eq prefer 'past) n1)
18160 ((eq prefer 'future) (if (= cday n1) n1 n2))
18161 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
18162 (cond
18163 ((eq prefer 'past) n1)
18164 ((eq prefer 'future) (if (= cday n1) n1 n2))
18165 (t (if (= cday n1) n1 n2)))))))
18167 (defun org-date-to-gregorian (date)
18168 "Turn any specification of DATE into a gregorian date for the calendar."
18169 (cond ((integerp date) (calendar-gregorian-from-absolute date))
18170 ((and (listp date) (= (length date) 3)) date)
18171 ((stringp date)
18172 (setq date (org-parse-time-string date))
18173 (list (nth 4 date) (nth 3 date) (nth 5 date)))
18174 ((listp date)
18175 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
18177 (defun org-parse-time-string (s &optional nodefault)
18178 "Parse the standard Org-mode time string.
18179 This should be a lot faster than the normal `parse-time-string'.
18180 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18181 hour and minute fields will be nil if not given."
18182 (if (string-match org-ts-regexp0 s)
18183 (list 0
18184 (if (or (match-beginning 8) (not nodefault))
18185 (string-to-number (or (match-string 8 s) "0")))
18186 (if (or (match-beginning 7) (not nodefault))
18187 (string-to-number (or (match-string 7 s) "0")))
18188 (string-to-number (match-string 4 s))
18189 (string-to-number (match-string 3 s))
18190 (string-to-number (match-string 2 s))
18191 nil nil nil)
18192 (make-list 9 0)))
18194 (defun org-timestamp-up (&optional arg)
18195 "Increase the date item at the cursor by one.
18196 If the cursor is on the year, change the year. If it is on the month or
18197 the day, change that.
18198 With prefix ARG, change by that many units."
18199 (interactive "p")
18200 (org-timestamp-change (prefix-numeric-value arg)))
18202 (defun org-timestamp-down (&optional arg)
18203 "Decrease the date item at the cursor by one.
18204 If the cursor is on the year, change the year. If it is on the month or
18205 the day, change that.
18206 With prefix ARG, change by that many units."
18207 (interactive "p")
18208 (org-timestamp-change (- (prefix-numeric-value arg))))
18210 (defun org-timestamp-up-day (&optional arg)
18211 "Increase the date in the time stamp by one day.
18212 With prefix ARG, change that many days."
18213 (interactive "p")
18214 (if (and (not (org-at-timestamp-p t))
18215 (org-on-heading-p))
18216 (org-todo 'up)
18217 (org-timestamp-change (prefix-numeric-value arg) 'day)))
18219 (defun org-timestamp-down-day (&optional arg)
18220 "Decrease the date in the time stamp by one day.
18221 With prefix ARG, change that many days."
18222 (interactive "p")
18223 (if (and (not (org-at-timestamp-p t))
18224 (org-on-heading-p))
18225 (org-todo 'down)
18226 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
18228 (defsubst org-pos-in-match-range (pos n)
18229 (and (match-beginning n)
18230 (<= (match-beginning n) pos)
18231 (>= (match-end n) pos)))
18233 (defun org-at-timestamp-p (&optional inactive-ok)
18234 "Determine if the cursor is in or at a timestamp."
18235 (interactive)
18236 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18237 (pos (point))
18238 (ans (or (looking-at tsr)
18239 (save-excursion
18240 (skip-chars-backward "^[<\n\r\t")
18241 (if (> (point) (point-min)) (backward-char 1))
18242 (and (looking-at tsr)
18243 (> (- (match-end 0) pos) -1))))))
18244 (and ans
18245 (boundp 'org-ts-what)
18246 (setq org-ts-what
18247 (cond
18248 ((= pos (match-beginning 0)) 'bracket)
18249 ((= pos (1- (match-end 0))) 'bracket)
18250 ((org-pos-in-match-range pos 2) 'year)
18251 ((org-pos-in-match-range pos 3) 'month)
18252 ((org-pos-in-match-range pos 7) 'hour)
18253 ((org-pos-in-match-range pos 8) 'minute)
18254 ((or (org-pos-in-match-range pos 4)
18255 (org-pos-in-match-range pos 5)) 'day)
18256 ((and (> pos (or (match-end 8) (match-end 5)))
18257 (< pos (match-end 0)))
18258 (- pos (or (match-end 8) (match-end 5))))
18259 (t 'day))))
18260 ans))
18262 (defun org-toggle-timestamp-type ()
18264 (interactive)
18265 (when (org-at-timestamp-p t)
18266 (save-excursion
18267 (goto-char (match-beginning 0))
18268 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18269 (goto-char (1- (match-end 0)))
18270 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18271 (message "Timestamp is now %sactive"
18272 (if (equal (char-before) ?>) "in" ""))))
18274 (defun org-timestamp-change (n &optional what)
18275 "Change the date in the time stamp at point.
18276 The date will be changed by N times WHAT. WHAT can be `day', `month',
18277 `year', `minute', `second'. If WHAT is not given, the cursor position
18278 in the timestamp determines what will be changed."
18279 (let ((pos (point))
18280 with-hm inactive
18281 org-ts-what
18282 extra
18283 ts time time0)
18284 (if (not (org-at-timestamp-p t))
18285 (error "Not at a timestamp"))
18286 (if (and (not what) (eq org-ts-what 'bracket))
18287 (org-toggle-timestamp-type)
18288 (if (and (not what) (not (eq org-ts-what 'day))
18289 org-display-custom-times
18290 (get-text-property (point) 'display)
18291 (not (get-text-property (1- (point)) 'display)))
18292 (setq org-ts-what 'day))
18293 (setq org-ts-what (or what org-ts-what)
18294 inactive (= (char-after (match-beginning 0)) ?\[)
18295 ts (match-string 0))
18296 (replace-match "")
18297 (if (string-match
18298 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
18300 (setq extra (match-string 1 ts)))
18301 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18302 (setq with-hm t))
18303 (setq time0 (org-parse-time-string ts))
18304 (setq time
18305 (encode-time (or (car time0) 0)
18306 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18307 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18308 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18309 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18310 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18311 (nthcdr 6 time0)))
18312 (when (integerp org-ts-what)
18313 (setq extra (org-modify-ts-extra extra org-ts-what n)))
18314 (if (eq what 'calendar)
18315 (let ((cal-date (org-get-date-from-calendar)))
18316 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18317 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18318 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18319 (setcar time0 (or (car time0) 0))
18320 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18321 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18322 (setq time (apply 'encode-time time0))))
18323 (setq org-last-changed-timestamp
18324 (org-insert-time-stamp time with-hm inactive nil nil extra))
18325 (org-clock-update-time-maybe)
18326 (goto-char pos)
18327 ;; Try to recenter the calendar window, if any
18328 (if (and org-calendar-follow-timestamp-change
18329 (get-buffer-window "*Calendar*" t)
18330 (memq org-ts-what '(day month year)))
18331 (org-recenter-calendar (time-to-days time))))))
18333 ;; FIXME: does not yet work for lead times
18334 (defun org-modify-ts-extra (s pos n)
18335 "Change the different parts of the lead-time and repeat fields in timestamp."
18336 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18337 ng h m new)
18338 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18339 (cond
18340 ((or (org-pos-in-match-range pos 2)
18341 (org-pos-in-match-range pos 3))
18342 (setq m (string-to-number (match-string 3 s))
18343 h (string-to-number (match-string 2 s)))
18344 (if (org-pos-in-match-range pos 2)
18345 (setq h (+ h n))
18346 (setq m (+ m n)))
18347 (if (< m 0) (setq m (+ m 60) h (1- h)))
18348 (if (> m 59) (setq m (- m 60) h (1+ h)))
18349 (setq h (min 24 (max 0 h)))
18350 (setq ng 1 new (format "-%02d:%02d" h m)))
18351 ((org-pos-in-match-range pos 6)
18352 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18353 ((org-pos-in-match-range pos 5)
18354 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
18356 (when ng
18357 (setq s (concat
18358 (substring s 0 (match-beginning ng))
18360 (substring s (match-end ng))))))
18363 (defun org-recenter-calendar (date)
18364 "If the calendar is visible, recenter it to DATE."
18365 (let* ((win (selected-window))
18366 (cwin (get-buffer-window "*Calendar*" t))
18367 (calendar-move-hook nil))
18368 (when cwin
18369 (select-window cwin)
18370 (calendar-goto-date (if (listp date) date
18371 (calendar-gregorian-from-absolute date)))
18372 (select-window win))))
18374 (defun org-goto-calendar (&optional arg)
18375 "Go to the Emacs calendar at the current date.
18376 If there is a time stamp in the current line, go to that date.
18377 A prefix ARG can be used to force the current date."
18378 (interactive "P")
18379 (let ((tsr org-ts-regexp) diff
18380 (calendar-move-hook nil)
18381 (view-calendar-holidays-initially nil)
18382 (view-diary-entries-initially nil))
18383 (if (or (org-at-timestamp-p)
18384 (save-excursion
18385 (beginning-of-line 1)
18386 (looking-at (concat ".*" tsr))))
18387 (let ((d1 (time-to-days (current-time)))
18388 (d2 (time-to-days
18389 (org-time-string-to-time (match-string 1)))))
18390 (setq diff (- d2 d1))))
18391 (calendar)
18392 (calendar-goto-today)
18393 (if (and diff (not arg)) (calendar-forward-day diff))))
18395 (defun org-get-date-from-calendar ()
18396 "Return a list (month day year) of date at point in calendar."
18397 (with-current-buffer "*Calendar*"
18398 (save-match-data
18399 (calendar-cursor-to-date))))
18401 (defun org-date-from-calendar ()
18402 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18403 If there is already a time stamp at the cursor position, update it."
18404 (interactive)
18405 (if (org-at-timestamp-p t)
18406 (org-timestamp-change 0 'calendar)
18407 (let ((cal-date (org-get-date-from-calendar)))
18408 (org-insert-time-stamp
18409 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18411 ;; Make appt aware of appointments from the agenda
18412 ;;;###autoload
18413 (defun org-agenda-to-appt (&optional filter)
18414 "Activate appointments found in `org-agenda-files'.
18415 When prefixed, prompt for a regular expression and use it as a
18416 filter: only add entries if they match this regular expression.
18418 FILTER can be a string. In this case, use this string as a
18419 regular expression to filter results.
18421 FILTER can also be an alist, with the car of each cell being
18422 either 'headline or 'category. For example:
18424 '((headline \"IMPORTANT\")
18425 (category \"Work\"))
18427 will only add headlines containing IMPORTANT or headlines
18428 belonging to the category \"Work\"."
18429 (interactive "P")
18430 (require 'calendar)
18431 (if (equal filter '(4))
18432 (setq filter (read-from-minibuffer "Regexp filter: ")))
18433 (let* ((cnt 0) ; count added events
18434 (org-agenda-new-buffers nil)
18435 (today (org-date-to-gregorian
18436 (time-to-days (current-time))))
18437 (files (org-agenda-files)) entries file)
18438 ;; Get all entries which may contain an appt
18439 (while (setq file (pop files))
18440 (setq entries
18441 (append entries
18442 (org-agenda-get-day-entries
18443 file today
18444 :timestamp :scheduled :deadline))))
18445 (setq entries (delq nil entries))
18446 ;; Map thru entries and find if they pass thru the filter
18447 (mapc
18448 (lambda(x)
18449 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18450 (cat (get-text-property 1 'org-category x))
18451 (tod (get-text-property 1 'time-of-day x))
18452 (ok (or (null filter)
18453 (and (stringp filter) (string-match filter evt))
18454 (and (listp filter)
18455 (or (string-match
18456 (cadr (assoc 'category filter)) cat)
18457 (string-match
18458 (cadr (assoc 'headline filter)) evt))))))
18459 ;; FIXME: Shall we remove text-properties for the appt text?
18460 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18461 (when (and ok tod)
18462 (setq tod (number-to-string tod)
18463 tod (when (string-match
18464 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18465 (concat (match-string 1 tod) ":"
18466 (match-string 2 tod))))
18467 (appt-add tod evt)
18468 (setq cnt (1+ cnt))))) entries)
18469 (org-release-buffers org-agenda-new-buffers)
18470 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" ""))))
18472 ;;; The clock for measuring work time.
18474 (defvar org-mode-line-string "")
18475 (put 'org-mode-line-string 'risky-local-variable t)
18477 (defvar org-mode-line-timer nil)
18478 (defvar org-clock-heading "")
18479 (defvar org-clock-start-time "")
18481 (defun org-update-mode-line ()
18482 (let* ((delta (- (time-to-seconds (current-time))
18483 (time-to-seconds org-clock-start-time)))
18484 (h (floor delta 3600))
18485 (m (floor (- delta (* 3600 h)) 60)))
18486 (setq org-mode-line-string
18487 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18488 'help-echo "Org-mode clock is running"))
18489 (force-mode-line-update)))
18491 (defvar org-clock-marker (make-marker)
18492 "Marker recording the last clock-in.")
18493 (defvar org-clock-mode-line-entry nil
18494 "Information for the modeline about the running clock.")
18496 (defun org-clock-in ()
18497 "Start the clock on the current item.
18498 If necessary, clock-out of the currently active clock."
18499 (interactive)
18500 (org-clock-out t)
18501 (let (ts)
18502 (save-excursion
18503 (org-back-to-heading t)
18504 (when (and org-clock-in-switch-to-state
18505 (not (looking-at (concat outline-regexp "[ \t]*"
18506 org-clock-in-switch-to-state
18507 "\\>"))))
18508 (org-todo org-clock-in-switch-to-state))
18509 (if (and org-clock-heading-function
18510 (functionp org-clock-heading-function))
18511 (setq org-clock-heading (funcall org-clock-heading-function))
18512 (if (looking-at org-complex-heading-regexp)
18513 (setq org-clock-heading (match-string 4))
18514 (setq org-clock-heading "???")))
18515 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18516 (org-clock-find-position)
18518 (insert "\n") (backward-char 1)
18519 (indent-relative)
18520 (insert org-clock-string " ")
18521 (setq org-clock-start-time (current-time))
18522 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18523 (move-marker org-clock-marker (point) (buffer-base-buffer))
18524 (or global-mode-string (setq global-mode-string '("")))
18525 (or (memq 'org-mode-line-string global-mode-string)
18526 (setq global-mode-string
18527 (append global-mode-string '(org-mode-line-string))))
18528 (org-update-mode-line)
18529 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18530 (message "Clock started at %s" ts))))
18532 (defun org-clock-find-position ()
18533 "Find the location where the next clock line should be inserted."
18534 (org-back-to-heading t)
18535 (catch 'exit
18536 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
18537 (re (concat "^[ \t]*" org-clock-string))
18538 (cnt 0)
18539 first last)
18540 (goto-char beg)
18541 (when (eobp) (newline) (setq end (max (point) end)))
18542 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
18543 ;; we seem to have a CLOCK drawer, so go there.
18544 (beginning-of-line 2)
18545 (throw 'exit t))
18546 ;; Lets count the CLOCK lines
18547 (goto-char beg)
18548 (while (re-search-forward re end t)
18549 (setq first (or first (match-beginning 0))
18550 last (match-beginning 0)
18551 cnt (1+ cnt)))
18552 (when (and (integerp org-clock-into-drawer)
18553 (>= (1+ cnt) org-clock-into-drawer))
18554 ;; Wrap current entries into a new drawer
18555 (goto-char last)
18556 (beginning-of-line 2)
18557 (if (org-at-item-p) (org-end-of-item))
18558 (insert ":END:\n")
18559 (beginning-of-line 0)
18560 (org-indent-line-function)
18561 (goto-char first)
18562 (insert ":CLOCK:\n")
18563 (beginning-of-line 0)
18564 (org-indent-line-function)
18565 (org-flag-drawer t)
18566 (beginning-of-line 2)
18567 (throw 'exit nil))
18569 (goto-char beg)
18570 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18571 (not (equal (match-string 1) org-clock-string)))
18572 ;; Planning info, skip to after it
18573 (beginning-of-line 2)
18574 (or (bolp) (newline)))
18575 (when (eq t org-clock-into-drawer)
18576 (insert ":CLOCK:\n:END:\n")
18577 (beginning-of-line -1)
18578 (org-indent-line-function)
18579 (org-flag-drawer t)
18580 (beginning-of-line 2)
18581 (org-indent-line-function)))))
18583 (defun org-clock-out (&optional fail-quietly)
18584 "Stop the currently running clock.
18585 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
18586 (interactive)
18587 (catch 'exit
18588 (if (not (marker-buffer org-clock-marker))
18589 (if fail-quietly (throw 'exit t) (error "No active clock")))
18590 (let (ts te s h m)
18591 (save-excursion
18592 (set-buffer (marker-buffer org-clock-marker))
18593 (goto-char org-clock-marker)
18594 (beginning-of-line 1)
18595 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18596 (equal (match-string 1) org-clock-string))
18597 (setq ts (match-string 2))
18598 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
18599 (goto-char (match-end 0))
18600 (delete-region (point) (point-at-eol))
18601 (insert "--")
18602 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18603 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
18604 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
18605 h (floor (/ s 3600))
18606 s (- s (* 3600 h))
18607 m (floor (/ s 60))
18608 s (- s (* 60 s)))
18609 (insert " => " (format "%2d:%02d" h m))
18610 (move-marker org-clock-marker nil)
18611 (let* ((logging (save-match-data (org-entry-get nil "LOGGING" t)))
18612 (org-log-done (org-parse-local-options logging 'org-log-done))
18613 (org-log-repeat (org-parse-local-options logging 'org-log-repeat)))
18614 (org-add-log-maybe 'clock-out))
18615 (when org-mode-line-timer
18616 (cancel-timer org-mode-line-timer)
18617 (setq org-mode-line-timer nil))
18618 (setq global-mode-string
18619 (delq 'org-mode-line-string global-mode-string))
18620 (force-mode-line-update)
18621 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
18623 (defun org-clock-cancel ()
18624 "Cancel the running clock be removing the start timestamp."
18625 (interactive)
18626 (if (not (marker-buffer org-clock-marker))
18627 (error "No active clock"))
18628 (save-excursion
18629 (set-buffer (marker-buffer org-clock-marker))
18630 (goto-char org-clock-marker)
18631 (delete-region (1- (point-at-bol)) (point-at-eol)))
18632 (setq global-mode-string
18633 (delq 'org-mode-line-string global-mode-string))
18634 (force-mode-line-update)
18635 (message "Clock canceled"))
18637 (defun org-clock-goto (&optional delete-windows)
18638 "Go to the currently clocked-in entry."
18639 (interactive "P")
18640 (if (not (marker-buffer org-clock-marker))
18641 (error "No active clock"))
18642 (switch-to-buffer-other-window
18643 (marker-buffer org-clock-marker))
18644 (if delete-windows (delete-other-windows))
18645 (goto-char org-clock-marker)
18646 (org-show-entry)
18647 (org-back-to-heading)
18648 (recenter))
18650 (defvar org-clock-file-total-minutes nil
18651 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
18652 (make-variable-buffer-local 'org-clock-file-total-minutes)
18654 (defun org-clock-sum (&optional tstart tend)
18655 "Sum the times for each subtree.
18656 Puts the resulting times in minutes as a text property on each headline."
18657 (interactive)
18658 (let* ((bmp (buffer-modified-p))
18659 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
18660 org-clock-string
18661 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
18662 (lmax 30)
18663 (ltimes (make-vector lmax 0))
18664 (t1 0)
18665 (level 0)
18666 ts te dt
18667 time)
18668 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
18669 (save-excursion
18670 (goto-char (point-max))
18671 (while (re-search-backward re nil t)
18672 (cond
18673 ((match-end 2)
18674 ;; Two time stamps
18675 (setq ts (match-string 2)
18676 te (match-string 3)
18677 ts (time-to-seconds
18678 (apply 'encode-time (org-parse-time-string ts)))
18679 te (time-to-seconds
18680 (apply 'encode-time (org-parse-time-string te)))
18681 ts (if tstart (max ts tstart) ts)
18682 te (if tend (min te tend) te)
18683 dt (- te ts)
18684 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
18685 ((match-end 4)
18686 ;; A naket time
18687 (setq t1 (+ t1 (string-to-number (match-string 5))
18688 (* 60 (string-to-number (match-string 4))))))
18689 (t ;; A headline
18690 (setq level (- (match-end 1) (match-beginning 1)))
18691 (when (or (> t1 0) (> (aref ltimes level) 0))
18692 (loop for l from 0 to level do
18693 (aset ltimes l (+ (aref ltimes l) t1)))
18694 (setq t1 0 time (aref ltimes level))
18695 (loop for l from level to (1- lmax) do
18696 (aset ltimes l 0))
18697 (goto-char (match-beginning 0))
18698 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
18699 (setq org-clock-file-total-minutes (aref ltimes 0)))
18700 (set-buffer-modified-p bmp)))
18702 (defun org-clock-display (&optional total-only)
18703 "Show subtree times in the entire buffer.
18704 If TOTAL-ONLY is non-nil, only show the total time for the entire file
18705 in the echo area."
18706 (interactive)
18707 (org-remove-clock-overlays)
18708 (let (time h m p)
18709 (org-clock-sum)
18710 (unless total-only
18711 (save-excursion
18712 (goto-char (point-min))
18713 (while (or (and (equal (setq p (point)) (point-min))
18714 (get-text-property p :org-clock-minutes))
18715 (setq p (next-single-property-change
18716 (point) :org-clock-minutes)))
18717 (goto-char p)
18718 (when (setq time (get-text-property p :org-clock-minutes))
18719 (org-put-clock-overlay time (funcall outline-level))))
18720 (setq h (/ org-clock-file-total-minutes 60)
18721 m (- org-clock-file-total-minutes (* 60 h)))
18722 ;; Arrange to remove the overlays upon next change.
18723 (when org-remove-highlights-with-change
18724 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
18725 nil 'local))))
18726 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
18728 (defvar org-clock-overlays nil)
18729 (make-variable-buffer-local 'org-clock-overlays)
18731 (defun org-put-clock-overlay (time &optional level)
18732 "Put an overlays on the current line, displaying TIME.
18733 If LEVEL is given, prefix time with a corresponding number of stars.
18734 This creates a new overlay and stores it in `org-clock-overlays', so that it
18735 will be easy to remove."
18736 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
18737 (l (if level (org-get-legal-level level 0) 0))
18738 (off 0)
18739 ov tx)
18740 (move-to-column c)
18741 (unless (eolp) (skip-chars-backward "^ \t"))
18742 (skip-chars-backward " \t")
18743 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
18744 tx (concat (buffer-substring (1- (point)) (point))
18745 (make-string (+ off (max 0 (- c (current-column)))) ?.)
18746 (org-add-props (format "%s %2d:%02d%s"
18747 (make-string l ?*) h m
18748 (make-string (- 10 l) ?\ ))
18749 '(face secondary-selection))
18750 ""))
18751 (if (not (featurep 'xemacs))
18752 (org-overlay-put ov 'display tx)
18753 (org-overlay-put ov 'invisible t)
18754 (org-overlay-put ov 'end-glyph (make-glyph tx)))
18755 (push ov org-clock-overlays)))
18757 (defun org-remove-clock-overlays (&optional beg end noremove)
18758 "Remove the occur highlights from the buffer.
18759 BEG and END are ignored. If NOREMOVE is nil, remove this function
18760 from the `before-change-functions' in the current buffer."
18761 (interactive)
18762 (unless org-inhibit-highlight-removal
18763 (mapc 'org-delete-overlay org-clock-overlays)
18764 (setq org-clock-overlays nil)
18765 (unless noremove
18766 (remove-hook 'before-change-functions
18767 'org-remove-clock-overlays 'local))))
18769 (defun org-clock-out-if-current ()
18770 "Clock out if the current entry contains the running clock.
18771 This is used to stop the clock after a TODO entry is marked DONE,
18772 and is only done if the variable `org-clock-out-when-done' is not nil."
18773 (when (and org-clock-out-when-done
18774 (member state org-done-keywords)
18775 (equal (marker-buffer org-clock-marker) (current-buffer))
18776 (< (point) org-clock-marker)
18777 (> (save-excursion (outline-next-heading) (point))
18778 org-clock-marker))
18779 ;; Clock out, but don't accept a logging message for this.
18780 (let ((org-log-done (if (and (listp org-log-done)
18781 (member 'clock-out org-log-done))
18782 '(done)
18783 org-log-done)))
18784 (org-clock-out))))
18786 (add-hook 'org-after-todo-state-change-hook
18787 'org-clock-out-if-current)
18789 (defun org-check-running-clock ()
18790 "Check if the current buffer contains the running clock.
18791 If yes, offer to stop it and to save the buffer with the changes."
18792 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
18793 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
18794 (buffer-name))))
18795 (org-clock-out)
18796 (when (y-or-n-p "Save changed buffer?")
18797 (save-buffer))))
18799 (defun org-clock-report (&optional arg)
18800 "Create a table containing a report about clocked time.
18801 If the cursor is inside an existing clocktable block, then the table
18802 will be updated. If not, a new clocktable will be inserted.
18803 When called with a prefix argument, move to the first clock table in the
18804 buffer and update it."
18805 (interactive "P")
18806 (org-remove-clock-overlays)
18807 (when arg (org-find-dblock "clocktable"))
18808 (if (org-in-clocktable-p)
18809 (goto-char (org-in-clocktable-p))
18810 (org-create-dblock (list :name "clocktable"
18811 :maxlevel 2 :scope 'file)))
18812 (org-update-dblock))
18814 (defun org-in-clocktable-p ()
18815 "Check if the cursor is in a clocktable."
18816 (let ((pos (point)) start)
18817 (save-excursion
18818 (end-of-line 1)
18819 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
18820 (setq start (match-beginning 0))
18821 (re-search-forward "^#\\+END:.*" nil t)
18822 (>= (match-end 0) pos)
18823 start))))
18825 (defun org-clock-update-time-maybe ()
18826 "If this is a CLOCK line, update it and return t.
18827 Otherwise, return nil."
18828 (interactive)
18829 (save-excursion
18830 (beginning-of-line 1)
18831 (skip-chars-forward " \t")
18832 (when (looking-at org-clock-string)
18833 (let ((re (concat "[ \t]*" org-clock-string
18834 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
18835 "\\([ \t]*=>.*\\)?"))
18836 ts te h m s)
18837 (if (not (looking-at re))
18839 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
18840 (end-of-line 1)
18841 (setq ts (match-string 1)
18842 te (match-string 2))
18843 (setq s (- (time-to-seconds
18844 (apply 'encode-time (org-parse-time-string te)))
18845 (time-to-seconds
18846 (apply 'encode-time (org-parse-time-string ts))))
18847 h (floor (/ s 3600))
18848 s (- s (* 3600 h))
18849 m (floor (/ s 60))
18850 s (- s (* 60 s)))
18851 (insert " => " (format "%2d:%02d" h m))
18852 t)))))
18854 (defun org-clock-special-range (key &optional time as-strings)
18855 "Return two times bordering a special time range.
18856 Key is a symbol specifying the range and can be one of `today', `yesterday',
18857 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
18858 A week starts Monday 0:00 and ends Sunday 24:00.
18859 The range is determined relative to TIME. TIME defaults to the current time.
18860 The return value is a cons cell with two internal times like the ones
18861 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
18862 the returned times will be formatted strings."
18863 (let* ((tm (decode-time (or time (current-time))))
18864 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
18865 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
18866 (dow (nth 6 tm))
18867 s1 m1 h1 d1 month1 y1 diff ts te fm)
18868 (cond
18869 ((eq key 'today)
18870 (setq h 0 m 0 h1 24 m1 0))
18871 ((eq key 'yesterday)
18872 (setq d (1- d) h 0 m 0 h1 24 m1 0))
18873 ((eq key 'thisweek)
18874 (setq diff (if (= dow 0) 6 (1- dow))
18875 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18876 ((eq key 'lastweek)
18877 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
18878 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18879 ((eq key 'thismonth)
18880 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
18881 ((eq key 'lastmonth)
18882 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
18883 ((eq key 'thisyear)
18884 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
18885 ((eq key 'lastyear)
18886 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
18887 (t (error "No such time block %s" key)))
18888 (setq ts (encode-time s m h d month y)
18889 te (encode-time (or s1 s) (or m1 m) (or h1 h)
18890 (or d1 d) (or month1 month) (or y1 y)))
18891 (setq fm (cdr org-time-stamp-formats))
18892 (if as-strings
18893 (cons (format-time-string fm ts) (format-time-string fm te))
18894 (cons ts te))))
18896 (defun org-dblock-write:clocktable (params)
18897 "Write the standard clocktable."
18898 (catch 'exit
18899 (let* ((hlchars '((1 . "*") (2 . "/")))
18900 (ins (make-marker))
18901 (total-time nil)
18902 (scope (plist-get params :scope))
18903 (tostring (plist-get params :tostring))
18904 (multifile (plist-get params :multifile))
18905 (header (plist-get params :header))
18906 (maxlevel (or (plist-get params :maxlevel) 3))
18907 (step (plist-get params :step))
18908 (emph (plist-get params :emphasize))
18909 (ts (plist-get params :tstart))
18910 (te (plist-get params :tend))
18911 (block (plist-get params :block))
18912 ipos time h m p level hlc hdl
18913 cc beg end pos tbl)
18914 (when step
18915 (org-clocktable-steps params)
18916 (throw 'exit nil))
18917 (when block
18918 (setq cc (org-clock-special-range block nil t)
18919 ts (car cc) te (cdr cc)))
18920 (if ts (setq ts (time-to-seconds
18921 (apply 'encode-time (org-parse-time-string ts)))))
18922 (if te (setq te (time-to-seconds
18923 (apply 'encode-time (org-parse-time-string te)))))
18924 (move-marker ins (point))
18925 (setq ipos (point))
18927 ;; Get the right scope
18928 (setq pos (point))
18929 (save-restriction
18930 (cond
18931 ((not scope))
18932 ((eq scope 'file) (widen))
18933 ((eq scope 'subtree) (org-narrow-to-subtree))
18934 ((eq scope 'tree)
18935 (while (org-up-heading-safe))
18936 (org-narrow-to-subtree))
18937 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
18938 (symbol-name scope)))
18939 (setq level (string-to-number (match-string 1 (symbol-name scope))))
18940 (catch 'exit
18941 (while (org-up-heading-safe)
18942 (looking-at outline-regexp)
18943 (if (<= (org-reduced-level (funcall outline-level)) level)
18944 (throw 'exit nil))))
18945 (org-narrow-to-subtree))
18946 ((or (listp scope) (eq scope 'agenda))
18947 (let* ((files (if (listp scope) scope (org-agenda-files)))
18948 (scope 'agenda)
18949 (p1 (copy-sequence params))
18950 file)
18951 (plist-put p1 :tostring t)
18952 (plist-put p1 :multifile t)
18953 (plist-put p1 :scope 'file)
18954 (org-prepare-agenda-buffers files)
18955 (while (setq file (pop files))
18956 (with-current-buffer (find-buffer-visiting file)
18957 (push (org-clocktable-add-file
18958 file (org-dblock-write:clocktable p1)) tbl)
18959 (setq total-time (+ (or total-time 0)
18960 org-clock-file-total-minutes)))))))
18961 (goto-char pos)
18963 (unless (eq scope 'agenda)
18964 (org-clock-sum ts te)
18965 (goto-char (point-min))
18966 (while (setq p (next-single-property-change (point) :org-clock-minutes))
18967 (goto-char p)
18968 (when (setq time (get-text-property p :org-clock-minutes))
18969 (save-excursion
18970 (beginning-of-line 1)
18971 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
18972 (setq level (org-reduced-level
18973 (- (match-end 1) (match-beginning 1))))
18974 (<= level maxlevel))
18975 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
18976 hdl (match-string 2)
18977 h (/ time 60)
18978 m (- time (* 60 h)))
18979 (if (and (not multifile) (= level 1)) (push "|-" tbl))
18980 (push (concat
18981 "| " (int-to-string level) "|" hlc hdl hlc " |"
18982 (make-string (1- level) ?|)
18983 hlc (format "%d:%02d" h m) hlc
18984 " |") tbl))))))
18985 (setq tbl (nreverse tbl))
18986 (if tostring
18987 (if tbl (mapconcat 'identity tbl "\n") nil)
18988 (goto-char ins)
18989 (insert-before-markers
18990 (or header
18991 (concat
18992 "Clock summary at ["
18993 (substring
18994 (format-time-string (cdr org-time-stamp-formats))
18995 1 -1)
18996 "]."
18997 (if block
18998 (format " Considered range is /%s/." block)
19000 "\n\n"))
19001 (if (eq scope 'agenda) "|File" "")
19002 "|L|Headline|Time|\n")
19003 (setq total-time (or total-time org-clock-file-total-minutes)
19004 h (/ total-time 60)
19005 m (- total-time (* 60 h)))
19006 (insert-before-markers
19007 "|-\n|"
19008 (if (eq scope 'agenda) "|" "")
19010 "*Total time*| "
19011 (format "*%d:%02d*" h m)
19012 "|\n|-\n")
19013 (setq tbl (delq nil tbl))
19014 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
19015 (equal (substring (car tbl) 0 2) "|-"))
19016 (pop tbl))
19017 (insert-before-markers (mapconcat
19018 'identity (delq nil tbl)
19019 (if (eq scope 'agenda) "\n|-\n" "\n")))
19020 (backward-delete-char 1)
19021 (goto-char ipos)
19022 (skip-chars-forward "^|")
19023 (org-table-align))))))
19025 (defun org-clocktable-steps (params)
19026 (let* ((p1 (copy-sequence params))
19027 (ts (plist-get p1 :tstart))
19028 (te (plist-get p1 :tend))
19029 (step0 (plist-get p1 :step))
19030 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
19031 (block (plist-get p1 :block))
19033 (when block
19034 (setq cc (org-clock-special-range block nil t)
19035 ts (car cc) te (cdr cc)))
19036 (if ts (setq ts (time-to-seconds
19037 (apply 'encode-time (org-parse-time-string ts)))))
19038 (if te (setq te (time-to-seconds
19039 (apply 'encode-time (org-parse-time-string te)))))
19040 (plist-put p1 :header "")
19041 (plist-put p1 :step nil)
19042 (plist-put p1 :block nil)
19043 (while (< ts te)
19044 (or (bolp) (insert "\n"))
19045 (plist-put p1 :tstart (format-time-string
19046 (car org-time-stamp-formats)
19047 (seconds-to-time ts)))
19048 (plist-put p1 :tend (format-time-string
19049 (car org-time-stamp-formats)
19050 (seconds-to-time (setq ts (+ ts step)))))
19051 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
19052 (plist-get p1 :tstart) "\n")
19053 (org-dblock-write:clocktable p1)
19054 (re-search-forward "#\\+END:")
19055 (end-of-line 0))))
19058 (defun org-clocktable-add-file (file table)
19059 (if table
19060 (let ((lines (org-split-string table "\n"))
19061 (ff (file-name-nondirectory file)))
19062 (mapconcat 'identity
19063 (mapcar (lambda (x)
19064 (if (string-match org-table-dataline-regexp x)
19065 (concat "|" ff x)
19067 lines)
19068 "\n"))))
19070 ;; FIXME: I don't think anybody uses this, ask David
19071 (defun org-collect-clock-time-entries ()
19072 "Return an internal list with clocking information.
19073 This list has one entry for each CLOCK interval.
19074 FIXME: describe the elements."
19075 (interactive)
19076 (let ((re (concat "^[ \t]*" org-clock-string
19077 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
19078 rtn beg end next cont level title total closedp leafp
19079 clockpos titlepos h m donep)
19080 (save-excursion
19081 (org-clock-sum)
19082 (goto-char (point-min))
19083 (while (re-search-forward re nil t)
19084 (setq clockpos (match-beginning 0)
19085 beg (match-string 1) end (match-string 2)
19086 cont (match-end 0))
19087 (setq beg (apply 'encode-time (org-parse-time-string beg))
19088 end (apply 'encode-time (org-parse-time-string end)))
19089 (org-back-to-heading t)
19090 (setq donep (org-entry-is-done-p))
19091 (setq titlepos (point)
19092 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
19093 h (/ total 60) m (- total (* 60 h))
19094 total (cons h m))
19095 (looking-at "\\(\\*+\\) +\\(.*\\)")
19096 (setq level (- (match-end 1) (match-beginning 1))
19097 title (org-match-string-no-properties 2))
19098 (save-excursion (outline-next-heading) (setq next (point)))
19099 (setq closedp (re-search-forward org-closed-time-regexp next t))
19100 (goto-char next)
19101 (setq leafp (and (looking-at "^\\*+ ")
19102 (<= (- (match-end 0) (point)) level)))
19103 (push (list beg end clockpos closedp donep
19104 total title titlepos level leafp)
19105 rtn)
19106 (goto-char cont)))
19107 (nreverse rtn)))
19109 ;;;; Agenda, and Diary Integration
19111 ;;; Define the Org-agenda-mode
19113 (defvar org-agenda-mode-map (make-sparse-keymap)
19114 "Keymap for `org-agenda-mode'.")
19116 (defvar org-agenda-menu) ; defined later in this file.
19117 (defvar org-agenda-follow-mode nil)
19118 (defvar org-agenda-show-log nil)
19119 (defvar org-agenda-redo-command nil)
19120 (defvar org-agenda-mode-hook nil)
19121 (defvar org-agenda-type nil)
19122 (defvar org-agenda-force-single-file nil)
19124 (defun org-agenda-mode ()
19125 "Mode for time-sorted view on action items in Org-mode files.
19127 The following commands are available:
19129 \\{org-agenda-mode-map}"
19130 (interactive)
19131 (kill-all-local-variables)
19132 (setq org-agenda-undo-list nil
19133 org-agenda-pending-undo-list nil)
19134 (setq major-mode 'org-agenda-mode)
19135 ;; Keep global-font-lock-mode from turning on font-lock-mode
19136 (org-set-local 'font-lock-global-modes (list 'not major-mode))
19137 (setq mode-name "Org-Agenda")
19138 (use-local-map org-agenda-mode-map)
19139 (easy-menu-add org-agenda-menu)
19140 (if org-startup-truncated (setq truncate-lines t))
19141 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
19142 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
19143 ;; Make sure properties are removed when copying text
19144 (when (boundp 'buffer-substring-filters)
19145 (org-set-local 'buffer-substring-filters
19146 (cons (lambda (x)
19147 (set-text-properties 0 (length x) nil x) x)
19148 buffer-substring-filters)))
19149 (unless org-agenda-keep-modes
19150 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
19151 org-agenda-show-log nil))
19152 (easy-menu-change
19153 '("Agenda") "Agenda Files"
19154 (append
19155 (list
19156 (vector
19157 (if (get 'org-agenda-files 'org-restrict)
19158 "Restricted to single file"
19159 "Edit File List")
19160 '(org-edit-agenda-file-list)
19161 (not (get 'org-agenda-files 'org-restrict)))
19162 "--")
19163 (mapcar 'org-file-menu-entry (org-agenda-files))))
19164 (org-agenda-set-mode-name)
19165 (apply
19166 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
19167 (list 'org-agenda-mode-hook)))
19169 (substitute-key-definition 'undo 'org-agenda-undo
19170 org-agenda-mode-map global-map)
19171 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
19172 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
19173 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
19174 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
19175 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
19176 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
19177 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
19178 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
19179 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
19180 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
19181 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
19182 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
19183 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
19184 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
19185 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
19186 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
19187 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
19188 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
19189 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
19190 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
19191 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
19192 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
19193 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
19194 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
19195 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
19196 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
19197 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
19198 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
19199 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
19201 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
19202 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
19203 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
19204 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
19205 (while l (org-defkey org-agenda-mode-map
19206 (int-to-string (pop l)) 'digit-argument)))
19208 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
19209 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
19210 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
19211 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
19212 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
19213 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
19214 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
19215 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
19216 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
19217 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
19218 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
19219 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
19220 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
19221 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
19222 (org-defkey org-agenda-mode-map "n" 'next-line)
19223 (org-defkey org-agenda-mode-map "p" 'previous-line)
19224 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
19225 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
19226 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
19227 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
19228 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
19229 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
19230 (eval-after-load "calendar"
19231 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
19232 'org-calendar-goto-agenda))
19233 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
19234 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
19235 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
19236 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
19237 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
19238 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
19239 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
19240 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
19241 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
19242 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
19243 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
19244 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19245 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
19246 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
19247 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
19248 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
19249 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
19250 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
19251 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
19252 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
19253 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
19254 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
19256 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
19257 "Local keymap for agenda entries from Org-mode.")
19259 (org-defkey org-agenda-keymap
19260 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
19261 (org-defkey org-agenda-keymap
19262 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
19263 (when org-agenda-mouse-1-follows-link
19264 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
19265 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
19266 '("Agenda"
19267 ("Agenda Files")
19268 "--"
19269 ["Show" org-agenda-show t]
19270 ["Go To (other window)" org-agenda-goto t]
19271 ["Go To (this window)" org-agenda-switch-to t]
19272 ["Follow Mode" org-agenda-follow-mode
19273 :style toggle :selected org-agenda-follow-mode :active t]
19274 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
19275 "--"
19276 ["Cycle TODO" org-agenda-todo t]
19277 ["Archive subtree" org-agenda-archive t]
19278 ["Delete subtree" org-agenda-kill t]
19279 "--"
19280 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
19281 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
19282 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
19283 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
19284 "--"
19285 ("Tags and Properties"
19286 ["Show all Tags" org-agenda-show-tags t]
19287 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
19288 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
19289 "--"
19290 ["Column View" org-columns t])
19291 ("Date/Schedule"
19292 ["Schedule" org-agenda-schedule t]
19293 ["Set Deadline" org-agenda-deadline t]
19294 "--"
19295 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19296 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19297 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19298 ("Clock"
19299 ["Clock in" org-agenda-clock-in t]
19300 ["Clock out" org-agenda-clock-out t]
19301 ["Clock cancel" org-agenda-clock-cancel t]
19302 ["Goto running clock" org-clock-goto t])
19303 ("Priority"
19304 ["Set Priority" org-agenda-priority t]
19305 ["Increase Priority" org-agenda-priority-up t]
19306 ["Decrease Priority" org-agenda-priority-down t]
19307 ["Show Priority" org-agenda-show-priority t])
19308 ("Calendar/Diary"
19309 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19310 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19311 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19312 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19313 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19314 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19315 "--"
19316 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19317 "--"
19318 ("View"
19319 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19320 :style radio :selected (equal org-agenda-ndays 1)]
19321 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19322 :style radio :selected (equal org-agenda-ndays 7)]
19323 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19324 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19325 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19326 :style radio :selected (member org-agenda-ndays '(365 366))]
19327 "--"
19328 ["Show Logbook entries" org-agenda-log-mode
19329 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19330 ["Include Diary" org-agenda-toggle-diary
19331 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19332 ["Use Time Grid" org-agenda-toggle-time-grid
19333 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19334 ["Write view to file" org-write-agenda t]
19335 ["Rebuild buffer" org-agenda-redo t]
19336 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19337 "--"
19338 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19339 "--"
19340 ["Quit" org-agenda-quit t]
19341 ["Exit and Release Buffers" org-agenda-exit t]
19344 ;;; Agenda undo
19346 (defvar org-agenda-allow-remote-undo t
19347 "Non-nil means, allow remote undo from the agenda buffer.")
19348 (defvar org-agenda-undo-list nil
19349 "List of undoable operations in the agenda since last refresh.")
19350 (defvar org-agenda-undo-has-started-in nil
19351 "Buffers that have already seen `undo-start' in the current undo sequence.")
19352 (defvar org-agenda-pending-undo-list nil
19353 "In a series of undo commands, this is the list of remaning undo items.")
19355 (defmacro org-if-unprotected (&rest body)
19356 "Execute BODY if there is no `org-protected' text property at point."
19357 (declare (debug t))
19358 `(unless (get-text-property (point) 'org-protected)
19359 ,@body))
19361 (defmacro org-with-remote-undo (_buffer &rest _body)
19362 "Execute BODY while recording undo information in two buffers."
19363 (declare (indent 1) (debug t))
19364 `(let ((_cline (org-current-line))
19365 (_cmd this-command)
19366 (_buf1 (current-buffer))
19367 (_buf2 ,_buffer)
19368 (_undo1 buffer-undo-list)
19369 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19370 _c1 _c2)
19371 ,@_body
19372 (when org-agenda-allow-remote-undo
19373 (setq _c1 (org-verify-change-for-undo
19374 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19375 _c2 (org-verify-change-for-undo
19376 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19377 (when (or _c1 _c2)
19378 ;; make sure there are undo boundaries
19379 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19380 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19381 ;; remember which buffer to undo
19382 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19383 org-agenda-undo-list)))))
19385 (defun org-agenda-undo ()
19386 "Undo a remote editing step in the agenda.
19387 This undoes changes both in the agenda buffer and in the remote buffer
19388 that have been changed along."
19389 (interactive)
19390 (or org-agenda-allow-remote-undo
19391 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19392 (if (not (eq this-command last-command))
19393 (setq org-agenda-undo-has-started-in nil
19394 org-agenda-pending-undo-list org-agenda-undo-list))
19395 (if (not org-agenda-pending-undo-list)
19396 (error "No further undo information"))
19397 (let* ((entry (pop org-agenda-pending-undo-list))
19398 buf line cmd rembuf)
19399 (setq cmd (pop entry) line (pop entry))
19400 (setq rembuf (nth 2 entry))
19401 (org-with-remote-undo rembuf
19402 (while (bufferp (setq buf (pop entry)))
19403 (if (pop entry)
19404 (with-current-buffer buf
19405 (let ((last-undo-buffer buf)
19406 (inhibit-read-only t))
19407 (unless (memq buf org-agenda-undo-has-started-in)
19408 (push buf org-agenda-undo-has-started-in)
19409 (make-local-variable 'pending-undo-list)
19410 (undo-start))
19411 (while (and pending-undo-list
19412 (listp pending-undo-list)
19413 (not (car pending-undo-list)))
19414 (pop pending-undo-list))
19415 (undo-more 1))))))
19416 (goto-line line)
19417 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19419 (defun org-verify-change-for-undo (l1 l2)
19420 "Verify that a real change occurred between the undo lists L1 and L2."
19421 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19422 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19423 (not (eq l1 l2)))
19425 ;;; Agenda dispatch
19427 (defvar org-agenda-restrict nil)
19428 (defvar org-agenda-restrict-begin (make-marker))
19429 (defvar org-agenda-restrict-end (make-marker))
19430 (defvar org-agenda-last-dispatch-buffer nil)
19431 (defvar org-agenda-overriding-restriction nil)
19433 ;;;###autoload
19434 (defun org-agenda (arg &optional keys restriction)
19435 "Dispatch agenda commands to collect entries to the agenda buffer.
19436 Prompts for a command to execute. Any prefix arg will be passed
19437 on to the selected command. The default selections are:
19439 a Call `org-agenda-list' to display the agenda for current day or week.
19440 t Call `org-todo-list' to display the global todo list.
19441 T Call `org-todo-list' to display the global todo list, select only
19442 entries with a specific TODO keyword (the user gets a prompt).
19443 m Call `org-tags-view' to display headlines with tags matching
19444 a condition (the user is prompted for the condition).
19445 M Like `m', but select only TODO entries, no ordinary headlines.
19446 L Create a timeline for the current buffer.
19447 e Export views to associated files.
19449 More commands can be added by configuring the variable
19450 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19451 searches can be pre-defined in this way.
19453 If the current buffer is in Org-mode and visiting a file, you can also
19454 first press `<' once to indicate that the agenda should be temporarily
19455 \(until the next use of \\[org-agenda]) restricted to the current file.
19456 Pressing `<' twice means to restrict to the current subtree or region
19457 \(if active)."
19458 (interactive "P")
19459 (catch 'exit
19460 (let* ((prefix-descriptions nil)
19461 (org-agenda-custom-commands-orig org-agenda-custom-commands)
19462 (org-agenda-custom-commands
19463 ;; normalize different versions
19464 (delq nil
19465 (mapcar
19466 (lambda (x)
19467 (cond ((stringp (cdr x))
19468 (push x prefix-descriptions)
19469 nil)
19470 ((stringp (nth 1 x)) x)
19471 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19472 (t (cons (car x) (cons "" (cdr x))))))
19473 org-agenda-custom-commands)))
19474 (buf (current-buffer))
19475 (bfn (buffer-file-name (buffer-base-buffer)))
19476 entry key type match lprops ans)
19477 ;; Turn off restriction unless there is an overriding one
19478 (unless org-agenda-overriding-restriction
19479 (put 'org-agenda-files 'org-restrict nil)
19480 (setq org-agenda-restrict nil)
19481 (move-marker org-agenda-restrict-begin nil)
19482 (move-marker org-agenda-restrict-end nil))
19483 ;; Delete old local properties
19484 (put 'org-agenda-redo-command 'org-lprops nil)
19485 ;; Remember where this call originated
19486 (setq org-agenda-last-dispatch-buffer (current-buffer))
19487 (unless keys
19488 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19489 keys (car ans)
19490 restriction (cdr ans)))
19491 ;; Estabish the restriction, if any
19492 (when (and (not org-agenda-overriding-restriction) restriction)
19493 (put 'org-agenda-files 'org-restrict (list bfn))
19494 (cond
19495 ((eq restriction 'region)
19496 (setq org-agenda-restrict t)
19497 (move-marker org-agenda-restrict-begin (region-beginning))
19498 (move-marker org-agenda-restrict-end (region-end)))
19499 ((eq restriction 'subtree)
19500 (save-excursion
19501 (setq org-agenda-restrict t)
19502 (org-back-to-heading t)
19503 (move-marker org-agenda-restrict-begin (point))
19504 (move-marker org-agenda-restrict-end
19505 (progn (org-end-of-subtree t)))))))
19507 (require 'calendar) ; FIXME: can we avoid this for some commands?
19508 ;; For example the todo list should not need it (but does...)
19509 (cond
19510 ((setq entry (assoc keys org-agenda-custom-commands))
19511 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19512 (progn
19513 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19514 (put 'org-agenda-redo-command 'org-lprops lprops)
19515 (cond
19516 ((eq type 'agenda)
19517 (org-let lprops '(org-agenda-list current-prefix-arg)))
19518 ((eq type 'alltodo)
19519 (org-let lprops '(org-todo-list current-prefix-arg)))
19520 ((eq type 'stuck)
19521 (org-let lprops '(org-agenda-list-stuck-projects
19522 current-prefix-arg)))
19523 ((eq type 'tags)
19524 (org-let lprops '(org-tags-view current-prefix-arg match)))
19525 ((eq type 'tags-todo)
19526 (org-let lprops '(org-tags-view '(4) match)))
19527 ((eq type 'todo)
19528 (org-let lprops '(org-todo-list match)))
19529 ((eq type 'tags-tree)
19530 (org-check-for-org-mode)
19531 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
19532 ((eq type 'todo-tree)
19533 (org-check-for-org-mode)
19534 (org-let lprops
19535 '(org-occur (concat "^" outline-regexp "[ \t]*"
19536 (regexp-quote match) "\\>"))))
19537 ((eq type 'occur-tree)
19538 (org-check-for-org-mode)
19539 (org-let lprops '(org-occur match)))
19540 ((functionp type)
19541 (org-let lprops '(funcall type match)))
19542 ((fboundp type)
19543 (org-let lprops '(funcall type match)))
19544 (t (error "Invalid custom agenda command type %s" type))))
19545 (org-run-agenda-series (nth 1 entry) (cddr entry))))
19546 ((equal keys "C")
19547 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
19548 (customize-variable 'org-agenda-custom-commands))
19549 ((equal keys "a") (call-interactively 'org-agenda-list))
19550 ((equal keys "t") (call-interactively 'org-todo-list))
19551 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
19552 ((equal keys "m") (call-interactively 'org-tags-view))
19553 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
19554 ((equal keys "e") (call-interactively 'org-store-agenda-views))
19555 ((equal keys "L")
19556 (unless (org-mode-p)
19557 (error "This is not an Org-mode file"))
19558 (unless restriction
19559 (put 'org-agenda-files 'org-restrict (list bfn))
19560 (org-call-with-arg 'org-timeline arg)))
19561 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
19562 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
19563 ((equal keys "!") (customize-variable 'org-stuck-projects))
19564 (t (error "Invalid agenda key"))))))
19566 (defun org-agenda-normalize-custom-commands (cmds)
19567 (delq nil
19568 (mapcar
19569 (lambda (x)
19570 (cond ((stringp (cdr x)) nil)
19571 ((stringp (nth 1 x)) x)
19572 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19573 (t (cons (car x) (cons "" (cdr x))))))
19574 cmds)))
19576 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
19577 "The user interface for selecting an agenda command."
19578 (catch 'exit
19579 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
19580 (restrict-ok (and bfn (org-mode-p)))
19581 (region-p (org-region-active-p))
19582 (custom org-agenda-custom-commands)
19583 (selstring "")
19584 restriction second-time
19585 c entry key type match prefixes rmheader header-end custom1 desc)
19586 (save-window-excursion
19587 (delete-other-windows)
19588 (org-switch-to-buffer-other-window " *Agenda Commands*")
19589 (erase-buffer)
19590 (insert (eval-when-compile
19591 (let ((header
19593 Press key for an agenda command: < Buffer,subtree/region restriction
19594 -------------------------------- > Remove restriction
19595 a Agenda for current week or day e Export agenda views
19596 t List of all TODO entries T Entries with special TODO kwd
19597 m Match a TAGS query M Like m, but only TODO entries
19598 L Timeline for current buffer # List stuck projects (!=configure)
19599 / Multi-occur C Configure custom agenda commands
19601 (start 0))
19602 (while (string-match
19603 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
19604 header start)
19605 (setq start (match-end 0))
19606 (add-text-properties (match-beginning 2) (match-end 2)
19607 '(face bold) header))
19608 header)))
19609 (setq header-end (move-marker (make-marker) (point)))
19610 (while t
19611 (setq custom1 custom)
19612 (when (eq rmheader t)
19613 (goto-line 1)
19614 (re-search-forward ":" nil t)
19615 (delete-region (match-end 0) (point-at-eol))
19616 (forward-char 1)
19617 (looking-at "-+")
19618 (delete-region (match-end 0) (point-at-eol))
19619 (move-marker header-end (match-end 0)))
19620 (goto-char header-end)
19621 (delete-region (point) (point-max))
19622 (while (setq entry (pop custom1))
19623 (setq key (car entry) desc (nth 1 entry)
19624 type (nth 2 entry) match (nth 3 entry))
19625 (if (> (length key) 1)
19626 (add-to-list 'prefixes (string-to-char key))
19627 (insert
19628 (format
19629 "\n%-4s%-14s: %s"
19630 (org-add-props (copy-sequence key)
19631 '(face bold))
19632 (cond
19633 ((string-match "\\S-" desc) desc)
19634 ((eq type 'agenda) "Agenda for current week or day")
19635 ((eq type 'alltodo) "List of all TODO entries")
19636 ((eq type 'stuck) "List of stuck projects")
19637 ((eq type 'todo) "TODO keyword")
19638 ((eq type 'tags) "Tags query")
19639 ((eq type 'tags-todo) "Tags (TODO)")
19640 ((eq type 'tags-tree) "Tags tree")
19641 ((eq type 'todo-tree) "TODO kwd tree")
19642 ((eq type 'occur-tree) "Occur tree")
19643 ((functionp type) (if (symbolp type)
19644 (symbol-name type)
19645 "Lambda expression"))
19646 (t "???"))
19647 (cond
19648 ((stringp match)
19649 (org-add-props match nil 'face 'org-warning))
19650 (match
19651 (format "set of %d commands" (length match)))
19652 (t ""))))))
19653 (when prefixes
19654 (mapc (lambda (x)
19655 (insert
19656 (format "\n%s %s"
19657 (org-add-props (char-to-string x)
19658 nil 'face 'bold)
19659 (or (cdr (assoc (concat selstring (char-to-string x))
19660 prefix-descriptions))
19661 "Prefix key"))))
19662 prefixes))
19663 (goto-char (point-min))
19664 (when (fboundp 'fit-window-to-buffer)
19665 (if second-time
19666 (if (not (pos-visible-in-window-p (point-max)))
19667 (fit-window-to-buffer))
19668 (setq second-time t)
19669 (fit-window-to-buffer)))
19670 (message "Press key for agenda command%s:"
19671 (if (or restrict-ok org-agenda-overriding-restriction)
19672 (if org-agenda-overriding-restriction
19673 " (restriction lock active)"
19674 (if restriction
19675 (format " (restricted to %s)" restriction)
19676 " (unrestricted)"))
19677 ""))
19678 (setq c (read-char-exclusive))
19679 (message "")
19680 (cond
19681 ((assoc (char-to-string c) custom)
19682 (setq selstring (concat selstring (char-to-string c)))
19683 (throw 'exit (cons selstring restriction)))
19684 ((memq c prefixes)
19685 (setq selstring (concat selstring (char-to-string c))
19686 prefixes nil
19687 rmheader (or rmheader t)
19688 custom (delq nil (mapcar
19689 (lambda (x)
19690 (if (or (= (length (car x)) 1)
19691 (/= (string-to-char (car x)) c))
19693 (cons (substring (car x) 1) (cdr x))))
19694 custom))))
19695 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
19696 (message "Restriction is only possible in Org-mode buffers")
19697 (ding) (sit-for 1))
19698 ((eq c ?1)
19699 (org-agenda-remove-restriction-lock 'noupdate)
19700 (setq restriction 'buffer))
19701 ((eq c ?0)
19702 (org-agenda-remove-restriction-lock 'noupdate)
19703 (setq restriction (if region-p 'region 'subtree)))
19704 ((eq c ?<)
19705 (org-agenda-remove-restriction-lock 'noupdate)
19706 (setq restriction
19707 (cond
19708 ((eq restriction 'buffer)
19709 (if region-p 'region 'subtree))
19710 ((memq restriction '(subtree region))
19711 nil)
19712 (t 'buffer))))
19713 ((eq c ?>)
19714 (org-agenda-remove-restriction-lock 'noupdate)
19715 (setq restriction nil))
19716 ((and (equal selstring "") (memq c '(?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
19717 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
19718 ((and (> (length selstring) 0) (eq c ?\d))
19719 (delete-window)
19720 (org-agenda-get-restriction-and-command prefix-descriptions))
19722 ((equal c ?q) (error "Abort"))
19723 (t (error "Invalid key %c" c))))))))
19725 (defun org-run-agenda-series (name series)
19726 (org-prepare-agenda name)
19727 (let* ((org-agenda-multi t)
19728 (redo (list 'org-run-agenda-series name (list 'quote series)))
19729 (cmds (car series))
19730 (gprops (nth 1 series))
19731 match ;; The byte compiler incorrectly complains about this. Keep it!
19732 cmd type lprops)
19733 (while (setq cmd (pop cmds))
19734 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
19735 (cond
19736 ((eq type 'agenda)
19737 (org-let2 gprops lprops
19738 '(call-interactively 'org-agenda-list)))
19739 ((eq type 'alltodo)
19740 (org-let2 gprops lprops
19741 '(call-interactively 'org-todo-list)))
19742 ((eq type 'stuck)
19743 (org-let2 gprops lprops
19744 '(call-interactively 'org-agenda-list-stuck-projects)))
19745 ((eq type 'tags)
19746 (org-let2 gprops lprops
19747 '(org-tags-view current-prefix-arg match)))
19748 ((eq type 'tags-todo)
19749 (org-let2 gprops lprops
19750 '(org-tags-view '(4) match)))
19751 ((eq type 'todo)
19752 (org-let2 gprops lprops
19753 '(org-todo-list match)))
19754 ((fboundp type)
19755 (org-let2 gprops lprops
19756 '(funcall type match)))
19757 (t (error "Invalid type in command series"))))
19758 (widen)
19759 (setq org-agenda-redo-command redo)
19760 (goto-char (point-min)))
19761 (org-finalize-agenda))
19763 ;;;###autoload
19764 (defmacro org-batch-agenda (cmd-key &rest parameters)
19765 "Run an agenda command in batch mode and send the result to STDOUT.
19766 If CMD-KEY is a string of length 1, it is used as a key in
19767 `org-agenda-custom-commands' and triggers this command. If it is a
19768 longer string it is used as a tags/todo match string.
19769 Paramters are alternating variable names and values that will be bound
19770 before running the agenda command."
19771 (let (pars)
19772 (while parameters
19773 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19774 (if (> (length cmd-key) 2)
19775 (eval (list 'let (nreverse pars)
19776 (list 'org-tags-view nil cmd-key)))
19777 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19778 (set-buffer org-agenda-buffer-name)
19779 (princ (org-encode-for-stdout (buffer-string)))))
19781 (defun org-encode-for-stdout (string)
19782 (if (fboundp 'encode-coding-string)
19783 (encode-coding-string string buffer-file-coding-system)
19784 string))
19786 (defvar org-agenda-info nil)
19788 ;;;###autoload
19789 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
19790 "Run an agenda command in batch mode and send the result to STDOUT.
19791 If CMD-KEY is a string of length 1, it is used as a key in
19792 `org-agenda-custom-commands' and triggers this command. If it is a
19793 longer string it is used as a tags/todo match string.
19794 Paramters are alternating variable names and values that will be bound
19795 before running the agenda command.
19797 The output gives a line for each selected agenda item. Each
19798 item is a list of comma-separated values, like this:
19800 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
19802 category The category of the item
19803 head The headline, without TODO kwd, TAGS and PRIORITY
19804 type The type of the agenda entry, can be
19805 todo selected in TODO match
19806 tagsmatch selected in tags match
19807 diary imported from diary
19808 deadline a deadline on given date
19809 scheduled scheduled on given date
19810 timestamp entry has timestamp on given date
19811 closed entry was closed on given date
19812 upcoming-deadline warning about deadline
19813 past-scheduled forwarded scheduled item
19814 block entry has date block including g. date
19815 todo The todo keyword, if any
19816 tags All tags including inherited ones, separated by colons
19817 date The relevant date, like 2007-2-14
19818 time The time, like 15:00-16:50
19819 extra Sting with extra planning info
19820 priority-l The priority letter if any was given
19821 priority-n The computed numerical priority
19822 agenda-day The day in the agenda where this is listed"
19824 (let (pars)
19825 (while parameters
19826 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19827 (push (list 'org-agenda-remove-tags t) pars)
19828 (if (> (length cmd-key) 2)
19829 (eval (list 'let (nreverse pars)
19830 (list 'org-tags-view nil cmd-key)))
19831 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19832 (set-buffer org-agenda-buffer-name)
19833 (let* ((lines (org-split-string (buffer-string) "\n"))
19834 line)
19835 (while (setq line (pop lines))
19836 (catch 'next
19837 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
19838 (setq org-agenda-info
19839 (org-fix-agenda-info (text-properties-at 0 line)))
19840 (princ
19841 (org-encode-for-stdout
19842 (mapconcat 'org-agenda-export-csv-mapper
19843 '(org-category txt type todo tags date time-of-day extra
19844 priority-letter priority agenda-day)
19845 ",")))
19846 (princ "\n"))))))
19848 (defun org-fix-agenda-info (props)
19849 "Make sure all properties on an agenda item have a canonical form,
19850 so the export commands can easily use it."
19851 (let (tmp re)
19852 (when (setq tmp (plist-get props 'tags))
19853 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
19854 (when (setq tmp (plist-get props 'date))
19855 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19856 (let ((calendar-date-display-form '(year "-" month "-" day)))
19857 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
19859 (setq tmp (calendar-date-string tmp)))
19860 (setq props (plist-put props 'date tmp)))
19861 (when (setq tmp (plist-get props 'day))
19862 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19863 (let ((calendar-date-display-form '(year "-" month "-" day)))
19864 (setq tmp (calendar-date-string tmp)))
19865 (setq props (plist-put props 'day tmp))
19866 (setq props (plist-put props 'agenda-day tmp)))
19867 (when (setq tmp (plist-get props 'txt))
19868 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
19869 (plist-put props 'priority-letter (match-string 1 tmp))
19870 (setq tmp (replace-match "" t t tmp)))
19871 (when (and (setq re (plist-get props 'org-todo-regexp))
19872 (setq re (concat "\\`\\.*" re " ?"))
19873 (string-match re tmp))
19874 (plist-put props 'todo (match-string 1 tmp))
19875 (setq tmp (replace-match "" t t tmp)))
19876 (plist-put props 'txt tmp)))
19877 props)
19879 (defun org-agenda-export-csv-mapper (prop)
19880 (let ((res (plist-get org-agenda-info prop)))
19881 (setq res
19882 (cond
19883 ((not res) "")
19884 ((stringp res) res)
19885 (t (prin1-to-string res))))
19886 (while (string-match "," res)
19887 (setq res (replace-match ";" t t res)))
19888 (org-trim res)))
19891 ;;;###autoload
19892 (defun org-store-agenda-views (&rest parameters)
19893 (interactive)
19894 (eval (list 'org-batch-store-agenda-views)))
19896 ;; FIXME, why is this a macro?????
19897 ;;;###autoload
19898 (defmacro org-batch-store-agenda-views (&rest parameters)
19899 "Run all custom agenda commands that have a file argument."
19900 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
19901 (pop-up-frames nil)
19902 (dir default-directory)
19903 pars cmd thiscmdkey files opts)
19904 (while parameters
19905 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19906 (setq pars (reverse pars))
19907 (save-window-excursion
19908 (while cmds
19909 (setq cmd (pop cmds)
19910 thiscmdkey (car cmd)
19911 opts (nth 4 cmd)
19912 files (nth 5 cmd))
19913 (if (stringp files) (setq files (list files)))
19914 (when files
19915 (eval (list 'let (append org-agenda-exporter-settings opts pars)
19916 (list 'org-agenda nil thiscmdkey)))
19917 (set-buffer org-agenda-buffer-name)
19918 (while files
19919 (eval (list 'let (append org-agenda-exporter-settings opts pars)
19920 (list 'org-write-agenda
19921 (expand-file-name (pop files) dir) t))))
19922 (and (get-buffer org-agenda-buffer-name)
19923 (kill-buffer org-agenda-buffer-name)))))))
19925 (defun org-write-agenda (file &optional nosettings)
19926 "Write the current buffer (an agenda view) as a file.
19927 Depending on the extension of the file name, plain text (.txt),
19928 HTML (.html or .htm) or Postscript (.ps) is produced.
19929 If NOSETTINGS is given, do not scope the settings of
19930 `org-agenda-exporter-settings' into the export commands. This is used when
19931 the settings have already been scoped and we do not wish to overrule other,
19932 higher priority settings."
19933 (interactive "FWrite agenda to file: ")
19934 (if (not (file-writable-p file))
19935 (error "Cannot write agenda to file %s" file))
19936 (cond
19937 ((string-match "\\.html?\\'" file) (require 'htmlize))
19938 ((string-match "\\.ps\\'" file) (require 'ps-print)))
19939 (org-let (if nosettings nil org-agenda-exporter-settings)
19940 '(save-excursion
19941 (save-window-excursion
19942 (cond
19943 ((string-match "\\.html?\\'" file)
19944 (set-buffer (htmlize-buffer (current-buffer)))
19946 (when (and org-agenda-export-html-style
19947 (string-match "<style>" org-agenda-export-html-style))
19948 ;; replace <style> section with org-agenda-export-html-style
19949 (goto-char (point-min))
19950 (kill-region (- (search-forward "<style") 6)
19951 (search-forward "</style>"))
19952 (insert org-agenda-export-html-style))
19953 (write-file file)
19954 (kill-buffer (current-buffer))
19955 (message "HTML written to %s" file))
19956 ((string-match "\\.ps\\'" file)
19957 (ps-print-buffer-with-faces file)
19958 (message "Postscript written to %s" file))
19960 (let ((bs (buffer-string)))
19961 (find-file file)
19962 (insert bs)
19963 (save-buffer 0)
19964 (kill-buffer (current-buffer))
19965 (message "Plain text written to %s" file))))))
19966 (set-buffer org-agenda-buffer-name)))
19968 (defmacro org-no-read-only (&rest body)
19969 "Inhibit read-only for BODY."
19970 `(let ((inhibit-read-only t)) ,@body))
19972 (defun org-check-for-org-mode ()
19973 "Make sure current buffer is in org-mode. Error if not."
19974 (or (org-mode-p)
19975 (error "Cannot execute org-mode agenda command on buffer in %s."
19976 major-mode)))
19978 (defun org-fit-agenda-window ()
19979 "Fit the window to the buffer size."
19980 (and (memq org-agenda-window-setup '(reorganize-frame))
19981 (fboundp 'fit-window-to-buffer)
19982 (fit-window-to-buffer
19984 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
19985 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
19987 ;;; Agenda file list
19989 (defun org-agenda-files (&optional unrestricted)
19990 "Get the list of agenda files.
19991 Optional UNRESTRICTED means return the full list even if a restriction
19992 is currently in place."
19993 (let ((files
19994 (cond
19995 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
19996 ((stringp org-agenda-files) (org-read-agenda-file-list))
19997 ((listp org-agenda-files) org-agenda-files)
19998 (t (error "Invalid value of `org-agenda-files'")))))
19999 (setq files (apply 'append
20000 (mapcar (lambda (f)
20001 (if (file-directory-p f)
20002 (directory-files f t
20003 org-agenda-file-regexp)
20004 (list f)))
20005 files)))
20006 (if org-agenda-skip-unavailable-files
20007 (delq nil
20008 (mapcar (function
20009 (lambda (file)
20010 (and (file-readable-p file) file)))
20011 files))
20012 files))) ; `org-check-agenda-file' will remove them from the list
20014 (defun org-edit-agenda-file-list ()
20015 "Edit the list of agenda files.
20016 Depending on setup, this either uses customize to edit the variable
20017 `org-agenda-files', or it visits the file that is holding the list. In the
20018 latter case, the buffer is set up in a way that saving it automatically kills
20019 the buffer and restores the previous window configuration."
20020 (interactive)
20021 (if (stringp org-agenda-files)
20022 (let ((cw (current-window-configuration)))
20023 (find-file org-agenda-files)
20024 (org-set-local 'org-window-configuration cw)
20025 (org-add-hook 'after-save-hook
20026 (lambda ()
20027 (set-window-configuration
20028 (prog1 org-window-configuration
20029 (kill-buffer (current-buffer))))
20030 (org-install-agenda-files-menu)
20031 (message "New agenda file list installed"))
20032 nil 'local)
20033 (message "%s" (substitute-command-keys
20034 "Edit list and finish with \\[save-buffer]")))
20035 (customize-variable 'org-agenda-files)))
20037 (defun org-store-new-agenda-file-list (list)
20038 "Set new value for the agenda file list and save it correcly."
20039 (if (stringp org-agenda-files)
20040 (let ((f org-agenda-files) b)
20041 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
20042 (with-temp-file f
20043 (insert (mapconcat 'identity list "\n") "\n")))
20044 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
20045 (setq org-agenda-files list)
20046 (customize-save-variable 'org-agenda-files org-agenda-files))))
20048 (defun org-read-agenda-file-list ()
20049 "Read the list of agenda files from a file."
20050 (when (stringp org-agenda-files)
20051 (with-temp-buffer
20052 (insert-file-contents org-agenda-files)
20053 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
20056 ;;;###autoload
20057 (defun org-cycle-agenda-files ()
20058 "Cycle through the files in `org-agenda-files'.
20059 If the current buffer visits an agenda file, find the next one in the list.
20060 If the current buffer does not, find the first agenda file."
20061 (interactive)
20062 (let* ((fs (org-agenda-files t))
20063 (files (append fs (list (car fs))))
20064 (tcf (if buffer-file-name (file-truename buffer-file-name)))
20065 file)
20066 (unless files (error "No agenda files"))
20067 (catch 'exit
20068 (while (setq file (pop files))
20069 (if (equal (file-truename file) tcf)
20070 (when (car files)
20071 (find-file (car files))
20072 (throw 'exit t))))
20073 (find-file (car fs)))
20074 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
20076 (defun org-agenda-file-to-front (&optional to-end)
20077 "Move/add the current file to the top of the agenda file list.
20078 If the file is not present in the list, it is added to the front. If it is
20079 present, it is moved there. With optional argument TO-END, add/move to the
20080 end of the list."
20081 (interactive "P")
20082 (let ((org-agenda-skip-unavailable-files nil)
20083 (file-alist (mapcar (lambda (x)
20084 (cons (file-truename x) x))
20085 (org-agenda-files t)))
20086 (ctf (file-truename buffer-file-name))
20087 x had)
20088 (setq x (assoc ctf file-alist) had x)
20090 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
20091 (if to-end
20092 (setq file-alist (append (delq x file-alist) (list x)))
20093 (setq file-alist (cons x (delq x file-alist))))
20094 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
20095 (org-install-agenda-files-menu)
20096 (message "File %s to %s of agenda file list"
20097 (if had "moved" "added") (if to-end "end" "front"))))
20099 (defun org-remove-file (&optional file)
20100 "Remove current file from the list of files in variable `org-agenda-files'.
20101 These are the files which are being checked for agenda entries.
20102 Optional argument FILE means, use this file instead of the current."
20103 (interactive)
20104 (let* ((org-agenda-skip-unavailable-files nil)
20105 (file (or file buffer-file-name))
20106 (true-file (file-truename file))
20107 (afile (abbreviate-file-name file))
20108 (files (delq nil (mapcar
20109 (lambda (x)
20110 (if (equal true-file
20111 (file-truename x))
20112 nil x))
20113 (org-agenda-files t)))))
20114 (if (not (= (length files) (length (org-agenda-files t))))
20115 (progn
20116 (org-store-new-agenda-file-list files)
20117 (org-install-agenda-files-menu)
20118 (message "Removed file: %s" afile))
20119 (message "File was not in list: %s (not removed)" afile))))
20121 (defun org-file-menu-entry (file)
20122 (vector file (list 'find-file file) t))
20124 (defun org-check-agenda-file (file)
20125 "Make sure FILE exists. If not, ask user what to do."
20126 (when (not (file-exists-p file))
20127 (message "non-existent file %s. [R]emove from list or [A]bort?"
20128 (abbreviate-file-name file))
20129 (let ((r (downcase (read-char-exclusive))))
20130 (cond
20131 ((equal r ?r)
20132 (org-remove-file file)
20133 (throw 'nextfile t))
20134 (t (error "Abort"))))))
20136 ;;; Agenda prepare and finalize
20138 (defvar org-agenda-multi nil) ; dynammically scoped
20139 (defvar org-agenda-buffer-name "*Org Agenda*")
20140 (defvar org-pre-agenda-window-conf nil)
20141 (defvar org-agenda-name nil)
20142 (defun org-prepare-agenda (&optional name)
20143 (setq org-todo-keywords-for-agenda nil)
20144 (setq org-done-keywords-for-agenda nil)
20145 (if org-agenda-multi
20146 (progn
20147 (setq buffer-read-only nil)
20148 (goto-char (point-max))
20149 (unless (or (bobp) org-agenda-compact-blocks)
20150 (insert "\n" (make-string (window-width) ?=) "\n"))
20151 (narrow-to-region (point) (point-max)))
20152 (org-agenda-maybe-reset-markers 'force)
20153 (org-prepare-agenda-buffers (org-agenda-files))
20154 (setq org-todo-keywords-for-agenda
20155 (org-uniquify org-todo-keywords-for-agenda))
20156 (setq org-done-keywords-for-agenda
20157 (org-uniquify org-done-keywords-for-agenda))
20158 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
20159 (awin (get-buffer-window abuf)))
20160 (cond
20161 ((equal (current-buffer) abuf) nil)
20162 (awin (select-window awin))
20163 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
20164 ((equal org-agenda-window-setup 'current-window)
20165 (switch-to-buffer abuf))
20166 ((equal org-agenda-window-setup 'other-window)
20167 (org-switch-to-buffer-other-window abuf))
20168 ((equal org-agenda-window-setup 'other-frame)
20169 (switch-to-buffer-other-frame abuf))
20170 ((equal org-agenda-window-setup 'reorganize-frame)
20171 (delete-other-windows)
20172 (org-switch-to-buffer-other-window abuf))))
20173 (setq buffer-read-only nil)
20174 (erase-buffer)
20175 (org-agenda-mode)
20176 (and name (not org-agenda-name)
20177 (org-set-local 'org-agenda-name name)))
20178 (setq buffer-read-only nil))
20180 (defun org-finalize-agenda ()
20181 "Finishing touch for the agenda buffer, called just before displaying it."
20182 (unless org-agenda-multi
20183 (save-excursion
20184 (let ((inhibit-read-only t))
20185 (goto-char (point-min))
20186 (while (org-activate-bracket-links (point-max))
20187 (add-text-properties (match-beginning 0) (match-end 0)
20188 '(face org-link)))
20189 (org-agenda-align-tags)
20190 (unless org-agenda-with-colors
20191 (remove-text-properties (point-min) (point-max) '(face nil))))
20192 (if (and (boundp 'org-overriding-columns-format)
20193 org-overriding-columns-format)
20194 (org-set-local 'org-overriding-columns-format
20195 org-overriding-columns-format))
20196 (if (and (boundp 'org-agenda-view-columns-initially)
20197 org-agenda-view-columns-initially)
20198 (org-agenda-columns))
20199 (when org-agenda-fontify-priorities
20200 (org-fontify-priorities))
20201 (run-hooks 'org-finalize-agenda-hook)
20202 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20205 (defun org-fontify-priorities ()
20206 "Make highest priority lines bold, and lowest italic."
20207 (interactive)
20208 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
20209 (org-delete-overlay o)))
20210 (org-overlays-in (point-min) (point-max)))
20211 (save-excursion
20212 (let ((inhibit-read-only t)
20213 b e p ov h l)
20214 (goto-char (point-min))
20215 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
20216 (setq h (or (get-char-property (point) 'org-highest-priority)
20217 org-highest-priority)
20218 l (or (get-char-property (point) 'org-lowest-priority)
20219 org-lowest-priority)
20220 p (string-to-char (match-string 1))
20221 b (match-beginning 0) e (point-at-eol)
20222 ov (org-make-overlay b e))
20223 (org-overlay-put
20224 ov 'face
20225 (cond ((listp org-agenda-fontify-priorities)
20226 (cdr (assoc p org-agenda-fontify-priorities)))
20227 ((equal p l) 'italic)
20228 ((equal p h) 'bold)))
20229 (org-overlay-put ov 'org-type 'org-priority)))))
20231 (defun org-prepare-agenda-buffers (files)
20232 "Create buffers for all agenda files, protect archived trees and comments."
20233 (interactive)
20234 (let ((pa '(:org-archived t))
20235 (pc '(:org-comment t))
20236 (pall '(:org-archived t :org-comment t))
20237 (inhibit-read-only t)
20238 (rea (concat ":" org-archive-tag ":"))
20239 bmp file re)
20240 (save-excursion
20241 (save-restriction
20242 (while (setq file (pop files))
20243 (if (bufferp file)
20244 (set-buffer file)
20245 (org-check-agenda-file file)
20246 (set-buffer (org-get-agenda-file-buffer file)))
20247 (widen)
20248 (setq bmp (buffer-modified-p))
20249 (org-refresh-category-properties)
20250 (setq org-todo-keywords-for-agenda
20251 (append org-todo-keywords-for-agenda org-todo-keywords-1))
20252 (setq org-done-keywords-for-agenda
20253 (append org-done-keywords-for-agenda org-done-keywords))
20254 (save-excursion
20255 (remove-text-properties (point-min) (point-max) pall)
20256 (when org-agenda-skip-archived-trees
20257 (goto-char (point-min))
20258 (while (re-search-forward rea nil t)
20259 (if (org-on-heading-p t)
20260 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
20261 (goto-char (point-min))
20262 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
20263 (while (re-search-forward re nil t)
20264 (add-text-properties
20265 (match-beginning 0) (org-end-of-subtree t) pc)))
20266 (set-buffer-modified-p bmp))))))
20268 (defvar org-agenda-skip-function nil
20269 "Function to be called at each match during agenda construction.
20270 If this function returns nil, the current match should not be skipped.
20271 Otherwise, the function must return a position from where the search
20272 should be continued.
20273 This may also be a Lisp form, it will be evaluated.
20274 Never set this variable using `setq' or so, because then it will apply
20275 to all future agenda commands. Instead, bind it with `let' to scope
20276 it dynamically into the agenda-constructing command. A good way to set
20277 it is through options in org-agenda-custom-commands.")
20279 (defun org-agenda-skip ()
20280 "Throw to `:skip' in places that should be skipped.
20281 Also moves point to the end of the skipped region, so that search can
20282 continue from there."
20283 (let ((p (point-at-bol)) to fp)
20284 (and org-agenda-skip-archived-trees
20285 (get-text-property p :org-archived)
20286 (org-end-of-subtree t)
20287 (throw :skip t))
20288 (and (get-text-property p :org-comment)
20289 (org-end-of-subtree t)
20290 (throw :skip t))
20291 (if (equal (char-after p) ?#) (throw :skip t))
20292 (when (and (or (setq fp (functionp org-agenda-skip-function))
20293 (consp org-agenda-skip-function))
20294 (setq to (save-excursion
20295 (save-match-data
20296 (if fp
20297 (funcall org-agenda-skip-function)
20298 (eval org-agenda-skip-function))))))
20299 (goto-char to)
20300 (throw :skip t))))
20302 (defvar org-agenda-markers nil
20303 "List of all currently active markers created by `org-agenda'.")
20304 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20305 "Creation time of the last agenda marker.")
20307 (defun org-agenda-new-marker (&optional pos)
20308 "Return a new agenda marker.
20309 Org-mode keeps a list of these markers and resets them when they are
20310 no longer in use."
20311 (let ((m (copy-marker (or pos (point)))))
20312 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20313 (push m org-agenda-markers)
20316 (defun org-agenda-maybe-reset-markers (&optional force)
20317 "Reset markers created by `org-agenda'. But only if they are old enough."
20318 (if (or (and force (not org-agenda-multi))
20319 (> (- (time-to-seconds (current-time))
20320 org-agenda-last-marker-time)
20322 (while org-agenda-markers
20323 (move-marker (pop org-agenda-markers) nil))))
20325 (defun org-get-agenda-file-buffer (file)
20326 "Get a buffer visiting FILE. If the buffer needs to be created, add
20327 it to the list of buffers which might be released later."
20328 (let ((buf (org-find-base-buffer-visiting file)))
20329 (if buf
20330 buf ; just return it
20331 ;; Make a new buffer and remember it
20332 (setq buf (find-file-noselect file))
20333 (if buf (push buf org-agenda-new-buffers))
20334 buf)))
20336 (defun org-release-buffers (blist)
20337 "Release all buffers in list, asking the user for confirmation when needed.
20338 When a buffer is unmodified, it is just killed. When modified, it is saved
20339 \(if the user agrees) and then killed."
20340 (let (buf file)
20341 (while (setq buf (pop blist))
20342 (setq file (buffer-file-name buf))
20343 (when (and (buffer-modified-p buf)
20344 file
20345 (y-or-n-p (format "Save file %s? " file)))
20346 (with-current-buffer buf (save-buffer)))
20347 (kill-buffer buf))))
20349 (defun org-get-category (&optional pos)
20350 "Get the category applying to position POS."
20351 (get-text-property (or pos (point)) 'org-category))
20353 ;;; Agenda timeline
20355 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20357 (defun org-timeline (&optional include-all)
20358 "Show a time-sorted view of the entries in the current org file.
20359 Only entries with a time stamp of today or later will be listed. With
20360 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20361 under the current date.
20362 If the buffer contains an active region, only check the region for
20363 dates."
20364 (interactive "P")
20365 (require 'calendar)
20366 (org-compile-prefix-format 'timeline)
20367 (org-set-sorting-strategy 'timeline)
20368 (let* ((dopast t)
20369 (dotodo include-all)
20370 (doclosed org-agenda-show-log)
20371 (entry buffer-file-name)
20372 (date (calendar-current-date))
20373 (beg (if (org-region-active-p) (region-beginning) (point-min)))
20374 (end (if (org-region-active-p) (region-end) (point-max)))
20375 (day-numbers (org-get-all-dates beg end 'no-ranges
20376 t doclosed ; always include today
20377 org-timeline-show-empty-dates))
20378 (org-deadline-warning-days 0)
20379 (org-agenda-only-exact-dates t)
20380 (today (time-to-days (current-time)))
20381 (past t)
20382 args
20383 s e rtn d emptyp)
20384 (setq org-agenda-redo-command
20385 (list 'progn
20386 (list 'org-switch-to-buffer-other-window (current-buffer))
20387 (list 'org-timeline (list 'quote include-all))))
20388 (if (not dopast)
20389 ;; Remove past dates from the list of dates.
20390 (setq day-numbers (delq nil (mapcar (lambda(x)
20391 (if (>= x today) x nil))
20392 day-numbers))))
20393 (org-prepare-agenda (concat "Timeline "
20394 (file-name-nondirectory buffer-file-name)))
20395 (if doclosed (push :closed args))
20396 (push :timestamp args)
20397 (push :deadline args)
20398 (push :scheduled args)
20399 (push :sexp args)
20400 (if dotodo (push :todo args))
20401 (while (setq d (pop day-numbers))
20402 (if (and (listp d) (eq (car d) :omitted))
20403 (progn
20404 (setq s (point))
20405 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20406 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20407 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20408 (if (and (>= d today)
20409 dopast
20410 past)
20411 (progn
20412 (setq past nil)
20413 (insert (make-string 79 ?-) "\n")))
20414 (setq date (calendar-gregorian-from-absolute d))
20415 (setq s (point))
20416 (setq rtn (and (not emptyp)
20417 (apply 'org-agenda-get-day-entries entry
20418 date args)))
20419 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20420 (progn
20421 (insert
20422 (if (stringp org-agenda-format-date)
20423 (format-time-string org-agenda-format-date
20424 (org-time-from-absolute date))
20425 (funcall org-agenda-format-date date))
20426 "\n")
20427 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20428 (put-text-property s (1- (point)) 'org-date-line t)
20429 (if (equal d today)
20430 (put-text-property s (1- (point)) 'org-today t))
20431 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20432 (put-text-property s (1- (point)) 'day d)))))
20433 (goto-char (point-min))
20434 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20435 (point-min)))
20436 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20437 (org-finalize-agenda)
20438 (setq buffer-read-only t)))
20440 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty pre-re)
20441 "Return a list of all relevant day numbers from BEG to END buffer positions.
20442 If NO-RANGES is non-nil, include only the start and end dates of a range,
20443 not every single day in the range. If FORCE-TODAY is non-nil, make
20444 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20445 inactive time stamps (those in square brackets) are included.
20446 When EMPTY is non-nil, also include days without any entries."
20447 (let ((re (concat
20448 (if pre-re pre-re "")
20449 (if inactive org-ts-regexp-both org-ts-regexp)))
20450 dates dates1 date day day1 day2 ts1 ts2)
20451 (if force-today
20452 (setq dates (list (time-to-days (current-time)))))
20453 (save-excursion
20454 (goto-char beg)
20455 (while (re-search-forward re end t)
20456 (setq day (time-to-days (org-time-string-to-time
20457 (substring (match-string 1) 0 10))))
20458 (or (memq day dates) (push day dates)))
20459 (unless no-ranges
20460 (goto-char beg)
20461 (while (re-search-forward org-tr-regexp end t)
20462 (setq ts1 (substring (match-string 1) 0 10)
20463 ts2 (substring (match-string 2) 0 10)
20464 day1 (time-to-days (org-time-string-to-time ts1))
20465 day2 (time-to-days (org-time-string-to-time ts2)))
20466 (while (< (setq day1 (1+ day1)) day2)
20467 (or (memq day1 dates) (push day1 dates)))))
20468 (setq dates (sort dates '<))
20469 (when empty
20470 (while (setq day (pop dates))
20471 (setq day2 (car dates))
20472 (push day dates1)
20473 (when (and day2 empty)
20474 (if (or (eq empty t)
20475 (and (numberp empty) (<= (- day2 day) empty)))
20476 (while (< (setq day (1+ day)) day2)
20477 (push (list day) dates1))
20478 (push (cons :omitted (- day2 day)) dates1))))
20479 (setq dates (nreverse dates1)))
20480 dates)))
20482 ;;; Agenda Daily/Weekly
20484 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
20485 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
20486 (defvar org-agenda-last-arguments nil
20487 "The arguments of the previous call to org-agenda")
20488 (defvar org-starting-day nil) ; local variable in the agenda buffer
20489 (defvar org-agenda-span nil) ; local variable in the agenda buffer
20490 (defvar org-include-all-loc nil) ; local variable
20491 (defvar org-agenda-remove-date nil) ; dynamically scoped
20493 ;;;###autoload
20494 (defun org-agenda-list (&optional include-all start-day ndays)
20495 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
20496 The view will be for the current day or week, but from the overview buffer
20497 you will be able to go to other days/weeks.
20499 With one \\[universal-argument] prefix argument INCLUDE-ALL,
20500 all unfinished TODO items will also be shown, before the agenda.
20501 This feature is considered obsolete, please use the TODO list or a block
20502 agenda instead.
20504 With a numeric prefix argument in an interactive call, the agenda will
20505 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
20506 the number of days. NDAYS defaults to `org-agenda-ndays'.
20508 START-DAY defaults to TODAY, or to the most recent match for the weekday
20509 given in `org-agenda-start-on-weekday'."
20510 (interactive "P")
20511 (if (and (integerp include-all) (> include-all 0))
20512 (setq ndays include-all include-all nil))
20513 (setq ndays (or ndays org-agenda-ndays)
20514 start-day (or start-day org-agenda-start-day))
20515 (if org-agenda-overriding-arguments
20516 (setq include-all (car org-agenda-overriding-arguments)
20517 start-day (nth 1 org-agenda-overriding-arguments)
20518 ndays (nth 2 org-agenda-overriding-arguments)))
20519 (if (stringp start-day)
20520 ;; Convert to an absolute day number
20521 (setq start-day (time-to-days (org-read-date nil t start-day))))
20522 (setq org-agenda-last-arguments (list include-all start-day ndays))
20523 (org-compile-prefix-format 'agenda)
20524 (org-set-sorting-strategy 'agenda)
20525 (require 'calendar)
20526 (let* ((org-agenda-start-on-weekday
20527 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
20528 org-agenda-start-on-weekday nil))
20529 (thefiles (org-agenda-files))
20530 (files thefiles)
20531 (today (time-to-days
20532 (time-subtract (current-time)
20533 (list 0 (* 3600 org-extend-today-until) 0))))
20534 (sd (or start-day today))
20535 (start (if (or (null org-agenda-start-on-weekday)
20536 (< org-agenda-ndays 7))
20538 (let* ((nt (calendar-day-of-week
20539 (calendar-gregorian-from-absolute sd)))
20540 (n1 org-agenda-start-on-weekday)
20541 (d (- nt n1)))
20542 (- sd (+ (if (< d 0) 7 0) d)))))
20543 (day-numbers (list start))
20544 (day-cnt 0)
20545 (inhibit-redisplay (not debug-on-error))
20546 s e rtn rtnall file date d start-pos end-pos todayp nd)
20547 (setq org-agenda-redo-command
20548 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
20549 ;; Make the list of days
20550 (setq ndays (or ndays org-agenda-ndays)
20551 nd ndays)
20552 (while (> ndays 1)
20553 (push (1+ (car day-numbers)) day-numbers)
20554 (setq ndays (1- ndays)))
20555 (setq day-numbers (nreverse day-numbers))
20556 (org-prepare-agenda "Day/Week")
20557 (org-set-local 'org-starting-day (car day-numbers))
20558 (org-set-local 'org-include-all-loc include-all)
20559 (org-set-local 'org-agenda-span
20560 (org-agenda-ndays-to-span nd))
20561 (when (and (or include-all org-agenda-include-all-todo)
20562 (member today day-numbers))
20563 (setq files thefiles
20564 rtnall nil)
20565 (while (setq file (pop files))
20566 (catch 'nextfile
20567 (org-check-agenda-file file)
20568 (setq date (calendar-gregorian-from-absolute today)
20569 rtn (org-agenda-get-day-entries
20570 file date :todo))
20571 (setq rtnall (append rtnall rtn))))
20572 (when rtnall
20573 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
20574 (add-text-properties (point-min) (1- (point))
20575 (list 'face 'org-agenda-structure))
20576 (insert (org-finalize-agenda-entries rtnall) "\n")))
20577 (unless org-agenda-compact-blocks
20578 (setq s (point))
20579 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
20580 "-agenda:\n")
20581 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
20582 'org-date-line t)))
20583 (while (setq d (pop day-numbers))
20584 (setq date (calendar-gregorian-from-absolute d)
20585 s (point))
20586 (if (or (setq todayp (= d today))
20587 (and (not start-pos) (= d sd)))
20588 (setq start-pos (point))
20589 (if (and start-pos (not end-pos))
20590 (setq end-pos (point))))
20591 (setq files thefiles
20592 rtnall nil)
20593 (while (setq file (pop files))
20594 (catch 'nextfile
20595 (org-check-agenda-file file)
20596 (if org-agenda-show-log
20597 (setq rtn (org-agenda-get-day-entries
20598 file date
20599 :deadline :scheduled :timestamp :sexp :closed))
20600 (setq rtn (org-agenda-get-day-entries
20601 file date
20602 :deadline :scheduled :sexp :timestamp)))
20603 (setq rtnall (append rtnall rtn))))
20604 (if org-agenda-include-diary
20605 (progn
20606 (require 'diary-lib)
20607 (setq rtn (org-get-entries-from-diary date))
20608 (setq rtnall (append rtnall rtn))))
20609 (if (or rtnall org-agenda-show-all-dates)
20610 (progn
20611 (setq day-cnt (1+ day-cnt))
20612 (insert
20613 (if (stringp org-agenda-format-date)
20614 (format-time-string org-agenda-format-date
20615 (org-time-from-absolute date))
20616 (funcall org-agenda-format-date date))
20617 "\n")
20618 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20619 (put-text-property s (1- (point)) 'org-date-line t)
20620 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
20621 (if todayp (put-text-property s (1- (point)) 'org-today t))
20622 (if rtnall (insert
20623 (org-finalize-agenda-entries
20624 (org-agenda-add-time-grid-maybe
20625 rtnall nd todayp))
20626 "\n"))
20627 (put-text-property s (1- (point)) 'day d)
20628 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
20629 (goto-char (point-min))
20630 (org-fit-agenda-window)
20631 (unless (and (pos-visible-in-window-p (point-min))
20632 (pos-visible-in-window-p (point-max)))
20633 (goto-char (1- (point-max)))
20634 (recenter -1)
20635 (if (not (pos-visible-in-window-p (or start-pos 1)))
20636 (progn
20637 (goto-char (or start-pos 1))
20638 (recenter 1))))
20639 (goto-char (or start-pos 1))
20640 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
20641 (org-finalize-agenda)
20642 (setq buffer-read-only t)
20643 (message "")))
20645 (defun org-agenda-ndays-to-span (n)
20646 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
20648 ;;; Agenda TODO list
20650 (defvar org-select-this-todo-keyword nil)
20651 (defvar org-last-arg nil)
20653 ;;;###autoload
20654 (defun org-todo-list (arg)
20655 "Show all TODO entries from all agenda file in a single list.
20656 The prefix arg can be used to select a specific TODO keyword and limit
20657 the list to these. When using \\[universal-argument], you will be prompted
20658 for a keyword. A numeric prefix directly selects the Nth keyword in
20659 `org-todo-keywords-1'."
20660 (interactive "P")
20661 (require 'calendar)
20662 (org-compile-prefix-format 'todo)
20663 (org-set-sorting-strategy 'todo)
20664 (org-prepare-agenda "TODO")
20665 (let* ((today (time-to-days (current-time)))
20666 (date (calendar-gregorian-from-absolute today))
20667 (kwds org-todo-keywords-for-agenda)
20668 (completion-ignore-case t)
20669 (org-select-this-todo-keyword
20670 (if (stringp arg) arg
20671 (and arg (integerp arg) (> arg 0)
20672 (nth (1- arg) kwds))))
20673 rtn rtnall files file pos)
20674 (when (equal arg '(4))
20675 (setq org-select-this-todo-keyword
20676 (completing-read "Keyword (or KWD1|K2D2|...): "
20677 (mapcar 'list kwds) nil nil)))
20678 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
20679 (org-set-local 'org-last-arg arg)
20680 (setq org-agenda-redo-command
20681 '(org-todo-list (or current-prefix-arg org-last-arg)))
20682 (setq files (org-agenda-files)
20683 rtnall nil)
20684 (while (setq file (pop files))
20685 (catch 'nextfile
20686 (org-check-agenda-file file)
20687 (setq rtn (org-agenda-get-day-entries file date :todo))
20688 (setq rtnall (append rtnall rtn))))
20689 (if org-agenda-overriding-header
20690 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20691 nil 'face 'org-agenda-structure) "\n")
20692 (insert "Global list of TODO items of type: ")
20693 (add-text-properties (point-min) (1- (point))
20694 (list 'face 'org-agenda-structure))
20695 (setq pos (point))
20696 (insert (or org-select-this-todo-keyword "ALL") "\n")
20697 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20698 (setq pos (point))
20699 (unless org-agenda-multi
20700 (insert "Available with `N r': (0)ALL")
20701 (let ((n 0) s)
20702 (mapc (lambda (x)
20703 (setq s (format "(%d)%s" (setq n (1+ n)) x))
20704 (if (> (+ (current-column) (string-width s) 1) (frame-width))
20705 (insert "\n "))
20706 (insert " " s))
20707 kwds))
20708 (insert "\n"))
20709 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20710 (when rtnall
20711 (insert (org-finalize-agenda-entries rtnall) "\n"))
20712 (goto-char (point-min))
20713 (org-fit-agenda-window)
20714 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
20715 (org-finalize-agenda)
20716 (setq buffer-read-only t)))
20718 ;;; Agenda tags match
20720 ;;;###autoload
20721 (defun org-tags-view (&optional todo-only match)
20722 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
20723 The prefix arg TODO-ONLY limits the search to TODO entries."
20724 (interactive "P")
20725 (org-compile-prefix-format 'tags)
20726 (org-set-sorting-strategy 'tags)
20727 (let* ((org-tags-match-list-sublevels
20728 (if todo-only t org-tags-match-list-sublevels))
20729 (completion-ignore-case t)
20730 rtn rtnall files file pos matcher
20731 buffer)
20732 (setq matcher (org-make-tags-matcher match)
20733 match (car matcher) matcher (cdr matcher))
20734 (org-prepare-agenda (concat "TAGS " match))
20735 (setq org-agenda-redo-command
20736 (list 'org-tags-view (list 'quote todo-only)
20737 (list 'if 'current-prefix-arg nil match)))
20738 (setq files (org-agenda-files)
20739 rtnall nil)
20740 (while (setq file (pop files))
20741 (catch 'nextfile
20742 (org-check-agenda-file file)
20743 (setq buffer (if (file-exists-p file)
20744 (org-get-agenda-file-buffer file)
20745 (error "No such file %s" file)))
20746 (if (not buffer)
20747 ;; If file does not exist, merror message to agenda
20748 (setq rtn (list
20749 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
20750 rtnall (append rtnall rtn))
20751 (with-current-buffer buffer
20752 (unless (org-mode-p)
20753 (error "Agenda file %s is not in `org-mode'" file))
20754 (save-excursion
20755 (save-restriction
20756 (if org-agenda-restrict
20757 (narrow-to-region org-agenda-restrict-begin
20758 org-agenda-restrict-end)
20759 (widen))
20760 (setq rtn (org-scan-tags 'agenda matcher todo-only))
20761 (setq rtnall (append rtnall rtn))))))))
20762 (if org-agenda-overriding-header
20763 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20764 nil 'face 'org-agenda-structure) "\n")
20765 (insert "Headlines with TAGS match: ")
20766 (add-text-properties (point-min) (1- (point))
20767 (list 'face 'org-agenda-structure))
20768 (setq pos (point))
20769 (insert match "\n")
20770 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20771 (setq pos (point))
20772 (unless org-agenda-multi
20773 (insert "Press `C-u r' to search again with new search string\n"))
20774 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20775 (when rtnall
20776 (insert (org-finalize-agenda-entries rtnall) "\n"))
20777 (goto-char (point-min))
20778 (org-fit-agenda-window)
20779 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
20780 (org-finalize-agenda)
20781 (setq buffer-read-only t)))
20783 ;;; Agenda Finding stuck projects
20785 (defvar org-agenda-skip-regexp nil
20786 "Regular expression used in skipping subtrees for the agenda.
20787 This is basically a temporary global variable that can be set and then
20788 used by user-defined selections using `org-agenda-skip-function'.")
20790 (defvar org-agenda-overriding-header nil
20791 "When this is set during todo and tags searches, will replace header.")
20793 (defun org-agenda-skip-subtree-when-regexp-matches ()
20794 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
20795 If yes, it returns the end position of this tree, causing agenda commands
20796 to skip this subtree. This is a function that can be put into
20797 `org-agenda-skip-function' for the duration of a command."
20798 (let ((end (save-excursion (org-end-of-subtree t)))
20799 skip)
20800 (save-excursion
20801 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
20802 (and skip end)))
20804 (defun org-agenda-skip-entry-if (&rest conditions)
20805 "Skip entry if any of CONDITIONS is true.
20806 See `org-agenda-skip-if' for details."
20807 (org-agenda-skip-if nil conditions))
20809 (defun org-agenda-skip-subtree-if (&rest conditions)
20810 "Skip entry if any of CONDITIONS is true.
20811 See `org-agenda-skip-if' for details."
20812 (org-agenda-skip-if t conditions))
20814 (defun org-agenda-skip-if (subtree conditions)
20815 "Checks current entity for CONDITIONS.
20816 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
20817 the entry, i.e. the text before the next heading is checked.
20819 CONDITIONS is a list of symbols, boolean OR is used to combine the results
20820 from different tests. Valid conditions are:
20822 scheduled Check if there is a scheduled cookie
20823 notscheduled Check if there is no scheduled cookie
20824 deadline Check if there is a deadline
20825 notdeadline Check if there is no deadline
20826 regexp Check if regexp matches
20827 notregexp Check if regexp does not match.
20829 The regexp is taken from the conditions list, it must come right after
20830 the `regexp' or `notregexp' element.
20832 If any of these conditions is met, this function returns the end point of
20833 the entity, causing the search to continue from there. This is a function
20834 that can be put into `org-agenda-skip-function' for the duration of a command."
20835 (let (beg end m)
20836 (org-back-to-heading t)
20837 (setq beg (point)
20838 end (if subtree
20839 (progn (org-end-of-subtree t) (point))
20840 (progn (outline-next-heading) (1- (point)))))
20841 (goto-char beg)
20842 (and
20844 (and (memq 'scheduled conditions)
20845 (re-search-forward org-scheduled-time-regexp end t))
20846 (and (memq 'notscheduled conditions)
20847 (not (re-search-forward org-scheduled-time-regexp end t)))
20848 (and (memq 'deadline conditions)
20849 (re-search-forward org-deadline-time-regexp end t))
20850 (and (memq 'notdeadline conditions)
20851 (not (re-search-forward org-deadline-time-regexp end t)))
20852 (and (setq m (memq 'regexp conditions))
20853 (stringp (nth 1 m))
20854 (re-search-forward (nth 1 m) end t))
20855 (and (setq m (memq 'notregexp conditions))
20856 (stringp (nth 1 m))
20857 (not (re-search-forward (nth 1 m) end t))))
20858 end)))
20860 ;;;###autoload
20861 (defun org-agenda-list-stuck-projects (&rest ignore)
20862 "Create agenda view for projects that are stuck.
20863 Stuck projects are project that have no next actions. For the definitions
20864 of what a project is and how to check if it stuck, customize the variable
20865 `org-stuck-projects'.
20866 MATCH is being ignored."
20867 (interactive)
20868 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
20869 ;; FIXME: we could have used org-agenda-skip-if here.
20870 (org-agenda-overriding-header "List of stuck projects: ")
20871 (matcher (nth 0 org-stuck-projects))
20872 (todo (nth 1 org-stuck-projects))
20873 (todo-wds (if (member "*" todo)
20874 (progn
20875 (org-prepare-agenda-buffers (org-agenda-files))
20876 (org-delete-all
20877 org-done-keywords-for-agenda
20878 (copy-sequence org-todo-keywords-for-agenda)))
20879 todo))
20880 (todo-re (concat "^\\*+[ \t]+\\("
20881 (mapconcat 'identity todo-wds "\\|")
20882 "\\)\\>"))
20883 (tags (nth 2 org-stuck-projects))
20884 (tags-re (if (member "*" tags)
20885 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
20886 (concat "^\\*+ .*:\\("
20887 (mapconcat 'identity tags "\\|")
20888 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
20889 (gen-re (nth 3 org-stuck-projects))
20890 (re-list
20891 (delq nil
20892 (list
20893 (if todo todo-re)
20894 (if tags tags-re)
20895 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
20896 gen-re)))))
20897 (setq org-agenda-skip-regexp
20898 (if re-list
20899 (mapconcat 'identity re-list "\\|")
20900 (error "No information how to identify unstuck projects")))
20901 (org-tags-view nil matcher)
20902 (with-current-buffer org-agenda-buffer-name
20903 (setq org-agenda-redo-command
20904 '(org-agenda-list-stuck-projects
20905 (or current-prefix-arg org-last-arg))))))
20907 ;;; Diary integration
20909 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
20911 (defun org-get-entries-from-diary (date)
20912 "Get the (Emacs Calendar) diary entries for DATE."
20913 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
20914 (diary-display-hook '(fancy-diary-display))
20915 (pop-up-frames nil)
20916 (list-diary-entries-hook
20917 (cons 'org-diary-default-entry list-diary-entries-hook))
20918 (diary-file-name-prefix-function nil) ; turn this feature off
20919 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
20920 entries
20921 (org-disable-agenda-to-diary t))
20922 (save-excursion
20923 (save-window-excursion
20924 (funcall (if (fboundp 'diary-list-entries)
20925 'diary-list-entries 'list-diary-entries)
20926 date 1)))
20927 (if (not (get-buffer fancy-diary-buffer))
20928 (setq entries nil)
20929 (with-current-buffer fancy-diary-buffer
20930 (setq buffer-read-only nil)
20931 (if (zerop (buffer-size))
20932 ;; No entries
20933 (setq entries nil)
20934 ;; Omit the date and other unnecessary stuff
20935 (org-agenda-cleanup-fancy-diary)
20936 ;; Add prefix to each line and extend the text properties
20937 (if (zerop (buffer-size))
20938 (setq entries nil)
20939 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
20940 (set-buffer-modified-p nil)
20941 (kill-buffer fancy-diary-buffer)))
20942 (when entries
20943 (setq entries (org-split-string entries "\n"))
20944 (setq entries
20945 (mapcar
20946 (lambda (x)
20947 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
20948 ;; Extend the text properties to the beginning of the line
20949 (org-add-props x (text-properties-at (1- (length x)) x)
20950 'type "diary" 'date date))
20951 entries)))))
20953 (defun org-agenda-cleanup-fancy-diary ()
20954 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
20955 This gets rid of the date, the underline under the date, and
20956 the dummy entry installed by `org-mode' to ensure non-empty diary for each
20957 date. It also removes lines that contain only whitespace."
20958 (goto-char (point-min))
20959 (if (looking-at ".*?:[ \t]*")
20960 (progn
20961 (replace-match "")
20962 (re-search-forward "\n=+$" nil t)
20963 (replace-match "")
20964 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
20965 (re-search-forward "\n=+$" nil t)
20966 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
20967 (goto-char (point-min))
20968 (while (re-search-forward "^ +\n" nil t)
20969 (replace-match ""))
20970 (goto-char (point-min))
20971 (if (re-search-forward "^Org-mode dummy\n?" nil t)
20972 (replace-match "")))
20974 ;; Make sure entries from the diary have the right text properties.
20975 (eval-after-load "diary-lib"
20976 '(if (boundp 'diary-modify-entry-list-string-function)
20977 ;; We can rely on the hook, nothing to do
20979 ;; Hook not avaiable, must use advice to make this work
20980 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
20981 "Make the position visible."
20982 (if (and org-disable-agenda-to-diary ;; called from org-agenda
20983 (stringp string)
20984 buffer-file-name)
20985 (setq string (org-modify-diary-entry-string string))))))
20987 (defun org-modify-diary-entry-string (string)
20988 "Add text properties to string, allowing org-mode to act on it."
20989 (org-add-props string nil
20990 'mouse-face 'highlight
20991 'keymap org-agenda-keymap
20992 'help-echo (if buffer-file-name
20993 (format "mouse-2 or RET jump to diary file %s"
20994 (abbreviate-file-name buffer-file-name))
20996 'org-agenda-diary-link t
20997 'org-marker (org-agenda-new-marker (point-at-bol))))
20999 (defun org-diary-default-entry ()
21000 "Add a dummy entry to the diary.
21001 Needed to avoid empty dates which mess up holiday display."
21002 ;; Catch the error if dealing with the new add-to-diary-alist
21003 (when org-disable-agenda-to-diary
21004 (condition-case nil
21005 (add-to-diary-list original-date "Org-mode dummy" "")
21006 (error
21007 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
21009 ;;;###autoload
21010 (defun org-diary (&rest args)
21011 "Return diary information from org-files.
21012 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
21013 It accesses org files and extracts information from those files to be
21014 listed in the diary. The function accepts arguments specifying what
21015 items should be listed. The following arguments are allowed:
21017 :timestamp List the headlines of items containing a date stamp or
21018 date range matching the selected date. Deadlines will
21019 also be listed, on the expiration day.
21021 :sexp List entries resulting from diary-like sexps.
21023 :deadline List any deadlines past due, or due within
21024 `org-deadline-warning-days'. The listing occurs only
21025 in the diary for *today*, not at any other date. If
21026 an entry is marked DONE, it is no longer listed.
21028 :scheduled List all items which are scheduled for the given date.
21029 The diary for *today* also contains items which were
21030 scheduled earlier and are not yet marked DONE.
21032 :todo List all TODO items from the org-file. This may be a
21033 long list - so this is not turned on by default.
21034 Like deadlines, these entries only show up in the
21035 diary for *today*, not at any other date.
21037 The call in the diary file should look like this:
21039 &%%(org-diary) ~/path/to/some/orgfile.org
21041 Use a separate line for each org file to check. Or, if you omit the file name,
21042 all files listed in `org-agenda-files' will be checked automatically:
21044 &%%(org-diary)
21046 If you don't give any arguments (as in the example above), the default
21047 arguments (:deadline :scheduled :timestamp :sexp) are used.
21048 So the example above may also be written as
21050 &%%(org-diary :deadline :timestamp :sexp :scheduled)
21052 The function expects the lisp variables `entry' and `date' to be provided
21053 by the caller, because this is how the calendar works. Don't use this
21054 function from a program - use `org-agenda-get-day-entries' instead."
21055 (org-agenda-maybe-reset-markers)
21056 (org-compile-prefix-format 'agenda)
21057 (org-set-sorting-strategy 'agenda)
21058 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21059 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
21060 (list entry)
21061 (org-agenda-files t)))
21062 file rtn results)
21063 (org-prepare-agenda-buffers files)
21064 ;; If this is called during org-agenda, don't return any entries to
21065 ;; the calendar. Org Agenda will list these entries itself.
21066 (if org-disable-agenda-to-diary (setq files nil))
21067 (while (setq file (pop files))
21068 (setq rtn (apply 'org-agenda-get-day-entries file date args))
21069 (setq results (append results rtn)))
21070 (if results
21071 (concat (org-finalize-agenda-entries results) "\n"))))
21073 ;;; Agenda entry finders
21075 (defun org-agenda-get-day-entries (file date &rest args)
21076 "Does the work for `org-diary' and `org-agenda'.
21077 FILE is the path to a file to be checked for entries. DATE is date like
21078 the one returned by `calendar-current-date'. ARGS are symbols indicating
21079 which kind of entries should be extracted. For details about these, see
21080 the documentation of `org-diary'."
21081 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21082 (let* ((org-startup-folded nil)
21083 (org-startup-align-all-tables nil)
21084 (buffer (if (file-exists-p file)
21085 (org-get-agenda-file-buffer file)
21086 (error "No such file %s" file)))
21087 arg results rtn)
21088 (if (not buffer)
21089 ;; If file does not exist, make sure an error message ends up in diary
21090 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21091 (with-current-buffer buffer
21092 (unless (org-mode-p)
21093 (error "Agenda file %s is not in `org-mode'" file))
21094 (let ((case-fold-search nil))
21095 (save-excursion
21096 (save-restriction
21097 (if org-agenda-restrict
21098 (narrow-to-region org-agenda-restrict-begin
21099 org-agenda-restrict-end)
21100 (widen))
21101 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
21102 (while (setq arg (pop args))
21103 (cond
21104 ((and (eq arg :todo)
21105 (equal date (calendar-current-date)))
21106 (setq rtn (org-agenda-get-todos))
21107 (setq results (append results rtn)))
21108 ((eq arg :timestamp)
21109 (setq rtn (org-agenda-get-blocks))
21110 (setq results (append results rtn))
21111 (setq rtn (org-agenda-get-timestamps))
21112 (setq results (append results rtn)))
21113 ((eq arg :sexp)
21114 (setq rtn (org-agenda-get-sexps))
21115 (setq results (append results rtn)))
21116 ((eq arg :scheduled)
21117 (setq rtn (org-agenda-get-scheduled))
21118 (setq results (append results rtn)))
21119 ((eq arg :closed)
21120 (setq rtn (org-agenda-get-closed))
21121 (setq results (append results rtn)))
21122 ((eq arg :deadline)
21123 (setq rtn (org-agenda-get-deadlines))
21124 (setq results (append results rtn))))))))
21125 results))))
21127 (defun org-entry-is-todo-p ()
21128 (member (org-get-todo-state) org-not-done-keywords))
21130 (defun org-entry-is-done-p ()
21131 (member (org-get-todo-state) org-done-keywords))
21133 (defun org-get-todo-state ()
21134 (save-excursion
21135 (org-back-to-heading t)
21136 (and (looking-at org-todo-line-regexp)
21137 (match-end 2)
21138 (match-string 2))))
21140 (defun org-at-date-range-p (&optional inactive-ok)
21141 "Is the cursor inside a date range?"
21142 (interactive)
21143 (save-excursion
21144 (catch 'exit
21145 (let ((pos (point)))
21146 (skip-chars-backward "^[<\r\n")
21147 (skip-chars-backward "<[")
21148 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21149 (>= (match-end 0) pos)
21150 (throw 'exit t))
21151 (skip-chars-backward "^<[\r\n")
21152 (skip-chars-backward "<[")
21153 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21154 (>= (match-end 0) pos)
21155 (throw 'exit t)))
21156 nil)))
21158 (defun org-agenda-get-todos ()
21159 "Return the TODO information for agenda display."
21160 (let* ((props (list 'face nil
21161 'done-face 'org-done
21162 'org-not-done-regexp org-not-done-regexp
21163 'org-todo-regexp org-todo-regexp
21164 'mouse-face 'highlight
21165 'keymap org-agenda-keymap
21166 'help-echo
21167 (format "mouse-2 or RET jump to org file %s"
21168 (abbreviate-file-name buffer-file-name))))
21169 ;; FIXME: get rid of the \n at some point but watch out
21170 (regexp (concat "^\\*+[ \t]+\\("
21171 (if org-select-this-todo-keyword
21172 (if (equal org-select-this-todo-keyword "*")
21173 org-todo-regexp
21174 (concat "\\<\\("
21175 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
21176 "\\)\\>"))
21177 org-not-done-regexp)
21178 "[^\n\r]*\\)"))
21179 marker priority category tags
21180 ee txt beg end)
21181 (goto-char (point-min))
21182 (while (re-search-forward regexp nil t)
21183 (catch :skip
21184 (save-match-data
21185 (beginning-of-line)
21186 (setq beg (point) end (progn (outline-next-heading) (point)))
21187 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
21188 (re-search-forward org-ts-regexp end t))
21189 (and org-agenda-todo-ignore-scheduled (goto-char beg)
21190 (re-search-forward org-scheduled-time-regexp end t))
21191 (and org-agenda-todo-ignore-deadlines (goto-char beg)
21192 (re-search-forward org-deadline-time-regexp end t)
21193 (org-deadline-close (match-string 1))))
21194 (goto-char (1+ beg))
21195 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
21196 (throw :skip nil)))
21197 (goto-char beg)
21198 (org-agenda-skip)
21199 (goto-char (match-beginning 1))
21200 (setq marker (org-agenda-new-marker (match-beginning 0))
21201 category (org-get-category)
21202 tags (org-get-tags-at (point))
21203 txt (org-format-agenda-item "" (match-string 1) category tags)
21204 priority (1+ (org-get-priority txt)))
21205 (org-add-props txt props
21206 'org-marker marker 'org-hd-marker marker
21207 'priority priority 'org-category category
21208 'type "todo")
21209 (push txt ee)
21210 (if org-agenda-todo-list-sublevels
21211 (goto-char (match-end 1))
21212 (org-end-of-subtree 'invisible))))
21213 (nreverse ee)))
21215 (defconst org-agenda-no-heading-message
21216 "No heading for this item in buffer or region.")
21218 (defun org-agenda-get-timestamps ()
21219 "Return the date stamp information for agenda display."
21220 (let* ((props (list 'face nil
21221 'org-not-done-regexp org-not-done-regexp
21222 'org-todo-regexp org-todo-regexp
21223 'mouse-face 'highlight
21224 'keymap org-agenda-keymap
21225 'help-echo
21226 (format "mouse-2 or RET jump to org file %s"
21227 (abbreviate-file-name buffer-file-name))))
21228 (d1 (calendar-absolute-from-gregorian date))
21229 (remove-re
21230 (concat
21231 (regexp-quote
21232 (format-time-string
21233 "<%Y-%m-%d"
21234 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
21235 ".*?>"))
21236 (regexp
21237 (concat
21238 (regexp-quote
21239 (substring
21240 (format-time-string
21241 (car org-time-stamp-formats)
21242 (apply 'encode-time ; DATE bound by calendar
21243 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21244 0 11))
21245 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
21246 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
21247 marker hdmarker deadlinep scheduledp donep tmp priority category
21248 ee txt timestr tags b0 b3 e3 head)
21249 (goto-char (point-min))
21250 (while (re-search-forward regexp nil t)
21251 (setq b0 (match-beginning 0)
21252 b3 (match-beginning 3) e3 (match-end 3))
21253 (catch :skip
21254 (and (org-at-date-range-p) (throw :skip nil))
21255 (org-agenda-skip)
21256 (if (and (match-end 1)
21257 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
21258 (throw :skip nil))
21259 (if (and e3
21260 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
21261 (throw :skip nil))
21262 (setq marker (org-agenda-new-marker b0)
21263 category (org-get-category b0)
21264 tmp (buffer-substring (max (point-min)
21265 (- b0 org-ds-keyword-length))
21267 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
21268 deadlinep (string-match org-deadline-regexp tmp)
21269 scheduledp (string-match org-scheduled-regexp tmp)
21270 donep (org-entry-is-done-p))
21271 (if (or scheduledp deadlinep) (throw :skip t))
21272 (if (string-match ">" timestr)
21273 ;; substring should only run to end of time stamp
21274 (setq timestr (substring timestr 0 (match-end 0))))
21275 (save-excursion
21276 (if (re-search-backward "^\\*+ " nil t)
21277 (progn
21278 (goto-char (match-beginning 0))
21279 (setq hdmarker (org-agenda-new-marker)
21280 tags (org-get-tags-at))
21281 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21282 (setq head (match-string 1))
21283 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
21284 (setq txt (org-format-agenda-item
21285 nil head category tags timestr nil
21286 remove-re)))
21287 (setq txt org-agenda-no-heading-message))
21288 (setq priority (org-get-priority txt))
21289 (org-add-props txt props
21290 'org-marker marker 'org-hd-marker hdmarker)
21291 (org-add-props txt nil 'priority priority
21292 'org-category category 'date date
21293 'type "timestamp")
21294 (push txt ee))
21295 (outline-next-heading)))
21296 (nreverse ee)))
21298 (defun org-agenda-get-sexps ()
21299 "Return the sexp information for agenda display."
21300 (require 'diary-lib)
21301 (let* ((props (list 'face nil
21302 'mouse-face 'highlight
21303 'keymap org-agenda-keymap
21304 'help-echo
21305 (format "mouse-2 or RET jump to org file %s"
21306 (abbreviate-file-name buffer-file-name))))
21307 (regexp "^&?%%(")
21308 marker category ee txt tags entry result beg b sexp sexp-entry)
21309 (goto-char (point-min))
21310 (while (re-search-forward regexp nil t)
21311 (catch :skip
21312 (org-agenda-skip)
21313 (setq beg (match-beginning 0))
21314 (goto-char (1- (match-end 0)))
21315 (setq b (point))
21316 (forward-sexp 1)
21317 (setq sexp (buffer-substring b (point)))
21318 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
21319 (org-trim (match-string 1))
21320 ""))
21321 (setq result (org-diary-sexp-entry sexp sexp-entry date))
21322 (when result
21323 (setq marker (org-agenda-new-marker beg)
21324 category (org-get-category beg))
21326 (if (string-match "\\S-" result)
21327 (setq txt result)
21328 (setq txt "SEXP entry returned empty string"))
21330 (setq txt (org-format-agenda-item
21331 "" txt category tags 'time))
21332 (org-add-props txt props 'org-marker marker)
21333 (org-add-props txt nil
21334 'org-category category 'date date
21335 'type "sexp")
21336 (push txt ee))))
21337 (nreverse ee)))
21339 (defun org-agenda-get-closed ()
21340 "Return the logged TODO entries for agenda display."
21341 (let* ((props (list 'mouse-face 'highlight
21342 'org-not-done-regexp org-not-done-regexp
21343 'org-todo-regexp org-todo-regexp
21344 'keymap org-agenda-keymap
21345 'help-echo
21346 (format "mouse-2 or RET jump to org file %s"
21347 (abbreviate-file-name buffer-file-name))))
21348 (regexp (concat
21349 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
21350 (regexp-quote
21351 (substring
21352 (format-time-string
21353 (car org-time-stamp-formats)
21354 (apply 'encode-time ; DATE bound by calendar
21355 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21356 1 11))))
21357 marker hdmarker priority category tags closedp
21358 ee txt timestr)
21359 (goto-char (point-min))
21360 (while (re-search-forward regexp nil t)
21361 (catch :skip
21362 (org-agenda-skip)
21363 (setq marker (org-agenda-new-marker (match-beginning 0))
21364 closedp (equal (match-string 1) org-closed-string)
21365 category (org-get-category (match-beginning 0))
21366 timestr (buffer-substring (match-beginning 0) (point-at-eol))
21367 ;; donep (org-entry-is-done-p)
21369 (if (string-match "\\]" timestr)
21370 ;; substring should only run to end of time stamp
21371 (setq timestr (substring timestr 0 (match-end 0))))
21372 (save-excursion
21373 (if (re-search-backward "^\\*+ " nil t)
21374 (progn
21375 (goto-char (match-beginning 0))
21376 (setq hdmarker (org-agenda-new-marker)
21377 tags (org-get-tags-at))
21378 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21379 (setq txt (org-format-agenda-item
21380 (if closedp "Closed: " "Clocked: ")
21381 (match-string 1) category tags timestr)))
21382 (setq txt org-agenda-no-heading-message))
21383 (setq priority 100000)
21384 (org-add-props txt props
21385 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
21386 'priority priority 'org-category category
21387 'type "closed" 'date date
21388 'undone-face 'org-warning 'done-face 'org-done)
21389 (push txt ee))
21390 (goto-char (point-at-eol))))
21391 ; (outline-next-heading)))
21392 (nreverse ee)))
21394 (defun org-agenda-get-deadlines ()
21395 "Return the deadline information for agenda display."
21396 (let* ((props (list 'mouse-face 'highlight
21397 'org-not-done-regexp org-not-done-regexp
21398 'org-todo-regexp org-todo-regexp
21399 'keymap org-agenda-keymap
21400 'help-echo
21401 (format "mouse-2 or RET jump to org file %s"
21402 (abbreviate-file-name buffer-file-name))))
21403 (regexp org-deadline-time-regexp)
21404 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21405 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21406 d2 diff dfrac wdays pos pos1 category tags
21407 ee txt head face s upcomingp donep timestr)
21408 (goto-char (point-min))
21409 (while (re-search-forward regexp nil t)
21410 (catch :skip
21411 (org-agenda-skip)
21412 (setq s (match-string 1)
21413 pos (1- (match-beginning 1))
21414 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21415 diff (- d2 d1)
21416 wdays (org-get-wdays s)
21417 dfrac (/ (* 1.0 (- wdays diff)) (max wdays 1))
21418 upcomingp (and todayp (> diff 0)))
21419 ;; When to show a deadline in the calendar:
21420 ;; If the expiration is within wdays warning time.
21421 ;; Past-due deadlines are only shown on the current date
21422 (if (or (and (<= diff wdays)
21423 (and todayp (not org-agenda-only-exact-dates)))
21424 (= diff 0))
21425 (save-excursion
21426 (setq category (org-get-category))
21427 (if (re-search-backward "^\\*+[ \t]+" nil t)
21428 (progn
21429 (goto-char (match-end 0))
21430 (setq pos1 (match-beginning 0))
21431 (setq tags (org-get-tags-at pos1))
21432 (setq head (buffer-substring-no-properties
21433 (point)
21434 (progn (skip-chars-forward "^\r\n")
21435 (point))))
21436 (setq donep (string-match org-looking-at-done-regexp head))
21437 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21438 (setq timestr
21439 (concat (substring s (match-beginning 1)) " "))
21440 (setq timestr 'time))
21441 (if (and donep
21442 (or org-agenda-skip-deadline-if-done
21443 (not (= diff 0))))
21444 (setq txt nil)
21445 (setq txt (org-format-agenda-item
21446 (if (= diff 0)
21447 (car org-agenda-deadline-leaders)
21448 (format (nth 1 org-agenda-deadline-leaders)
21449 diff))
21450 head category tags timestr))))
21451 (setq txt org-agenda-no-heading-message))
21452 (when txt
21453 (setq face (org-agenda-deadline-face dfrac))
21454 (org-add-props txt props
21455 'org-marker (org-agenda-new-marker pos)
21456 'org-hd-marker (org-agenda-new-marker pos1)
21457 'priority (+ (floor (* dfrac 100.))
21458 (org-get-priority txt))
21459 'org-category category
21460 'type (if upcomingp "upcoming-deadline" "deadline")
21461 'date (if upcomingp date d2)
21462 'face (if donep 'org-done face)
21463 'undone-face face 'done-face 'org-done)
21464 (push txt ee))))))
21465 (nreverse ee)))
21467 (defun org-agenda-deadline-face (fraction)
21468 "Return the face to displaying a deadline item.
21469 FRACTION is what fraction of the head-warning time has passed."
21470 (let ((faces org-agenda-deadline-faces) f)
21471 (catch 'exit
21472 (while (setq f (pop faces))
21473 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
21475 (defun org-agenda-get-scheduled ()
21476 "Return the scheduled information for agenda display."
21477 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
21478 'org-todo-regexp org-todo-regexp
21479 'done-face 'org-done
21480 'mouse-face 'highlight
21481 'keymap org-agenda-keymap
21482 'help-echo
21483 (format "mouse-2 or RET jump to org file %s"
21484 (abbreviate-file-name buffer-file-name))))
21485 (regexp org-scheduled-time-regexp)
21486 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21487 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21488 d2 diff pos pos1 category tags
21489 ee txt head pastschedp donep face timestr s)
21490 (goto-char (point-min))
21491 (while (re-search-forward regexp nil t)
21492 (catch :skip
21493 (org-agenda-skip)
21494 (setq s (match-string 1)
21495 pos (1- (match-beginning 1))
21496 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21497 ;;; is this right?
21498 ;;; do we need to do this for deadleine too????
21499 ;;; d2 (org-time-string-to-absolute (match-string 1) (if todayp nil d1))
21500 diff (- d2 d1))
21501 (setq pastschedp (and todayp (< diff 0)))
21502 ;; When to show a scheduled item in the calendar:
21503 ;; If it is on or past the date.
21504 (if (or (and (< diff 0)
21505 (and todayp (not org-agenda-only-exact-dates)))
21506 (= diff 0))
21507 (save-excursion
21508 (setq category (org-get-category))
21509 (if (re-search-backward "^\\*+[ \t]+" nil t)
21510 (progn
21511 (goto-char (match-end 0))
21512 (setq pos1 (match-beginning 0))
21513 (setq tags (org-get-tags-at))
21514 (setq head (buffer-substring-no-properties
21515 (point)
21516 (progn (skip-chars-forward "^\r\n") (point))))
21517 (setq donep (string-match org-looking-at-done-regexp head))
21518 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21519 (setq timestr
21520 (concat (substring s (match-beginning 1)) " "))
21521 (setq timestr 'time))
21522 (if (and donep
21523 (or org-agenda-skip-scheduled-if-done
21524 (not (= diff 0))))
21525 (setq txt nil)
21526 (setq txt (org-format-agenda-item
21527 (if (= diff 0)
21528 (car org-agenda-scheduled-leaders)
21529 (format (nth 1 org-agenda-scheduled-leaders)
21530 (- 1 diff)))
21531 head category tags timestr))))
21532 (setq txt org-agenda-no-heading-message))
21533 (when txt
21534 (setq face (if pastschedp
21535 'org-scheduled-previously
21536 'org-scheduled-today))
21537 (org-add-props txt props
21538 'undone-face face
21539 'face (if donep 'org-done face)
21540 'org-marker (org-agenda-new-marker pos)
21541 'org-hd-marker (org-agenda-new-marker pos1)
21542 'type (if pastschedp "past-scheduled" "scheduled")
21543 'date (if pastschedp d2 date)
21544 'priority (+ 94 (- 5 diff) (org-get-priority txt))
21545 'org-category category)
21546 (push txt ee))))))
21547 (nreverse ee)))
21549 (defun org-agenda-get-blocks ()
21550 "Return the date-range information for agenda display."
21551 (let* ((props (list 'face nil
21552 'org-not-done-regexp org-not-done-regexp
21553 'org-todo-regexp org-todo-regexp
21554 'mouse-face 'highlight
21555 'keymap org-agenda-keymap
21556 'help-echo
21557 (format "mouse-2 or RET jump to org file %s"
21558 (abbreviate-file-name buffer-file-name))))
21559 (regexp org-tr-regexp)
21560 (d0 (calendar-absolute-from-gregorian date))
21561 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
21562 donep head)
21563 (goto-char (point-min))
21564 (while (re-search-forward regexp nil t)
21565 (catch :skip
21566 (org-agenda-skip)
21567 (setq pos (point))
21568 (setq timestr (match-string 0)
21569 s1 (match-string 1)
21570 s2 (match-string 2)
21571 d1 (time-to-days (org-time-string-to-time s1))
21572 d2 (time-to-days (org-time-string-to-time s2)))
21573 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
21574 ;; Only allow days between the limits, because the normal
21575 ;; date stamps will catch the limits.
21576 (save-excursion
21577 (setq marker (org-agenda-new-marker (point)))
21578 (setq category (org-get-category))
21579 (if (re-search-backward "^\\*+ " nil t)
21580 (progn
21581 (goto-char (match-beginning 0))
21582 (setq hdmarker (org-agenda-new-marker (point)))
21583 (setq tags (org-get-tags-at))
21584 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21585 (setq head (match-string 1))
21586 (and org-agenda-skip-timestamp-if-done
21587 (org-entry-is-done-p)
21588 (throw :skip t))
21589 (setq txt (org-format-agenda-item
21590 (format (if (= d1 d2) "" "(%d/%d): ")
21591 (1+ (- d0 d1)) (1+ (- d2 d1)))
21592 head category tags
21593 (if (= d0 d1) timestr))))
21594 (setq txt org-agenda-no-heading-message))
21595 (org-add-props txt props
21596 'org-marker marker 'org-hd-marker hdmarker
21597 'type "block" 'date date
21598 'priority (org-get-priority txt) 'org-category category)
21599 (push txt ee)))
21600 (goto-char pos)))
21601 ;; Sort the entries by expiration date.
21602 (nreverse ee)))
21604 ;;; Agenda presentation and sorting
21606 (defconst org-plain-time-of-day-regexp
21607 (concat
21608 "\\(\\<[012]?[0-9]"
21609 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21610 "\\(--?"
21611 "\\(\\<[012]?[0-9]"
21612 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21613 "\\)?")
21614 "Regular expression to match a plain time or time range.
21615 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
21616 groups carry important information:
21617 0 the full match
21618 1 the first time, range or not
21619 8 the second time, if it is a range.")
21621 (defconst org-plain-time-extension-regexp
21622 (concat
21623 "\\(\\<[012]?[0-9]"
21624 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21625 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
21626 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
21627 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
21628 groups carry important information:
21629 0 the full match
21630 7 hours of duration
21631 9 minutes of duration")
21633 (defconst org-stamp-time-of-day-regexp
21634 (concat
21635 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
21636 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
21637 "\\(--?"
21638 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
21639 "Regular expression to match a timestamp time or time range.
21640 After a match, the following groups carry important information:
21641 0 the full match
21642 1 date plus weekday, for backreferencing to make sure both times on same day
21643 2 the first time, range or not
21644 4 the second time, if it is a range.")
21646 (defvar org-prefix-has-time nil
21647 "A flag, set by `org-compile-prefix-format'.
21648 The flag is set if the currently compiled format contains a `%t'.")
21649 (defvar org-prefix-has-tag nil
21650 "A flag, set by `org-compile-prefix-format'.
21651 The flag is set if the currently compiled format contains a `%T'.")
21653 (defun org-format-agenda-item (extra txt &optional category tags dotime
21654 noprefix remove-re)
21655 "Format TXT to be inserted into the agenda buffer.
21656 In particular, it adds the prefix and corresponding text properties. EXTRA
21657 must be a string and replaces the `%s' specifier in the prefix format.
21658 CATEGORY (string, symbol or nil) may be used to overrule the default
21659 category taken from local variable or file name. It will replace the `%c'
21660 specifier in the format. DOTIME, when non-nil, indicates that a
21661 time-of-day should be extracted from TXT for sorting of this entry, and for
21662 the `%t' specifier in the format. When DOTIME is a string, this string is
21663 searched for a time before TXT is. NOPREFIX is a flag and indicates that
21664 only the correctly processes TXT should be returned - this is used by
21665 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
21666 Any match of REMOVE-RE will be removed from TXT."
21667 (save-match-data
21668 ;; Diary entries sometimes have extra whitespace at the beginning
21669 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
21670 (let* ((category (or category
21671 org-category
21672 (if buffer-file-name
21673 (file-name-sans-extension
21674 (file-name-nondirectory buffer-file-name))
21675 "")))
21676 (tag (if tags (nth (1- (length tags)) tags) ""))
21677 time ; time and tag are needed for the eval of the prefix format
21678 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
21679 (time-of-day (and dotime (org-get-time-of-day ts)))
21680 stamp plain s0 s1 s2 rtn srp)
21681 (when (and dotime time-of-day org-prefix-has-time)
21682 ;; Extract starting and ending time and move them to prefix
21683 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
21684 (setq plain (string-match org-plain-time-of-day-regexp ts)))
21685 (setq s0 (match-string 0 ts)
21686 srp (and stamp (match-end 3))
21687 s1 (match-string (if plain 1 2) ts)
21688 s2 (match-string (if plain 8 (if srp 4 6)) ts))
21690 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
21691 ;; them, we might want to remove them there to avoid duplication.
21692 ;; The user can turn this off with a variable.
21693 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
21694 (string-match (concat (regexp-quote s0) " *") txt)
21695 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
21696 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
21697 (= (match-beginning 0) 0)
21699 (setq txt (replace-match "" nil nil txt))))
21700 ;; Normalize the time(s) to 24 hour
21701 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
21702 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
21704 (when (and s1 (not s2) org-agenda-default-appointment-duration
21705 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
21706 (let ((m (+ (string-to-number (match-string 2 s1))
21707 (* 60 (string-to-number (match-string 1 s1)))
21708 org-agenda-default-appointment-duration))
21710 (setq h (/ m 60) m (- m (* h 60)))
21711 (setq s2 (format "%02d:%02d" h m))))
21713 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
21714 txt)
21715 ;; Tags are in the string
21716 (if (or (eq org-agenda-remove-tags t)
21717 (and org-agenda-remove-tags
21718 org-prefix-has-tag))
21719 (setq txt (replace-match "" t t txt))
21720 (setq txt (replace-match
21721 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
21722 (match-string 2 txt))
21723 t t txt))))
21725 (when remove-re
21726 (while (string-match remove-re txt)
21727 (setq txt (replace-match "" t t txt))))
21729 ;; Create the final string
21730 (if noprefix
21731 (setq rtn txt)
21732 ;; Prepare the variables needed in the eval of the compiled format
21733 (setq time (cond (s2 (concat s1 "-" s2))
21734 (s1 (concat s1 "......"))
21735 (t ""))
21736 extra (or extra "")
21737 category (if (symbolp category) (symbol-name category) category))
21738 ;; Evaluate the compiled format
21739 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
21741 ;; And finally add the text properties
21742 (org-add-props rtn nil
21743 'org-category (downcase category) 'tags tags
21744 'org-highest-priority org-highest-priority
21745 'org-lowest-priority org-lowest-priority
21746 'prefix-length (- (length rtn) (length txt))
21747 'time-of-day time-of-day
21748 'txt txt
21749 'time time
21750 'extra extra
21751 'dotime dotime))))
21753 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
21754 (defvar org-agenda-sorting-strategy-selected nil)
21756 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
21757 (catch 'exit
21758 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
21759 ((and todayp (member 'today (car org-agenda-time-grid))))
21760 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
21761 ((member 'weekly (car org-agenda-time-grid)))
21762 (t (throw 'exit list)))
21763 (let* ((have (delq nil (mapcar
21764 (lambda (x) (get-text-property 1 'time-of-day x))
21765 list)))
21766 (string (nth 1 org-agenda-time-grid))
21767 (gridtimes (nth 2 org-agenda-time-grid))
21768 (req (car org-agenda-time-grid))
21769 (remove (member 'remove-match req))
21770 new time)
21771 (if (and (member 'require-timed req) (not have))
21772 ;; don't show empty grid
21773 (throw 'exit list))
21774 (while (setq time (pop gridtimes))
21775 (unless (and remove (member time have))
21776 (setq time (int-to-string time))
21777 (push (org-format-agenda-item
21778 nil string "" nil
21779 (concat (substring time 0 -2) ":" (substring time -2)))
21780 new)
21781 (put-text-property
21782 1 (length (car new)) 'face 'org-time-grid (car new))))
21783 (if (member 'time-up org-agenda-sorting-strategy-selected)
21784 (append new list)
21785 (append list new)))))
21787 (defun org-compile-prefix-format (key)
21788 "Compile the prefix format into a Lisp form that can be evaluated.
21789 The resulting form is returned and stored in the variable
21790 `org-prefix-format-compiled'."
21791 (setq org-prefix-has-time nil org-prefix-has-tag nil)
21792 (let ((s (cond
21793 ((stringp org-agenda-prefix-format)
21794 org-agenda-prefix-format)
21795 ((assq key org-agenda-prefix-format)
21796 (cdr (assq key org-agenda-prefix-format)))
21797 (t " %-12:c%?-12t% s")))
21798 (start 0)
21799 varform vars var e c f opt)
21800 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
21801 s start)
21802 (setq var (cdr (assoc (match-string 4 s)
21803 '(("c" . category) ("t" . time) ("s" . extra)
21804 ("T" . tag))))
21805 c (or (match-string 3 s) "")
21806 opt (match-beginning 1)
21807 start (1+ (match-beginning 0)))
21808 (if (equal var 'time) (setq org-prefix-has-time t))
21809 (if (equal var 'tag) (setq org-prefix-has-tag t))
21810 (setq f (concat "%" (match-string 2 s) "s"))
21811 (if opt
21812 (setq varform
21813 `(if (equal "" ,var)
21815 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
21816 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
21817 (setq s (replace-match "%s" t nil s))
21818 (push varform vars))
21819 (setq vars (nreverse vars))
21820 (setq org-prefix-format-compiled `(format ,s ,@vars))))
21822 (defun org-set-sorting-strategy (key)
21823 (if (symbolp (car org-agenda-sorting-strategy))
21824 ;; the old format
21825 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
21826 (setq org-agenda-sorting-strategy-selected
21827 (or (cdr (assq key org-agenda-sorting-strategy))
21828 (cdr (assq 'agenda org-agenda-sorting-strategy))
21829 '(time-up category-keep priority-down)))))
21831 (defun org-get-time-of-day (s &optional string mod24)
21832 "Check string S for a time of day.
21833 If found, return it as a military time number between 0 and 2400.
21834 If not found, return nil.
21835 The optional STRING argument forces conversion into a 5 character wide string
21836 HH:MM."
21837 (save-match-data
21838 (when
21839 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
21840 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
21841 (let* ((h (string-to-number (match-string 1 s)))
21842 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
21843 (ampm (if (match-end 4) (downcase (match-string 4 s))))
21844 (am-p (equal ampm "am"))
21845 (h1 (cond ((not ampm) h)
21846 ((= h 12) (if am-p 0 12))
21847 (t (+ h (if am-p 0 12)))))
21848 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
21849 (mod h1 24) h1))
21850 (t0 (+ (* 100 h2) m))
21851 (t1 (concat (if (>= h1 24) "+" " ")
21852 (if (< t0 100) "0" "")
21853 (if (< t0 10) "0" "")
21854 (int-to-string t0))))
21855 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
21857 (defun org-finalize-agenda-entries (list &optional nosort)
21858 "Sort and concatenate the agenda items."
21859 (setq list (mapcar 'org-agenda-highlight-todo list))
21860 (if nosort
21861 list
21862 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
21864 (defun org-agenda-highlight-todo (x)
21865 (let (re pl)
21866 (if (eq x 'line)
21867 (save-excursion
21868 (beginning-of-line 1)
21869 (setq re (get-text-property (point) 'org-todo-regexp))
21870 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
21871 (when (looking-at (concat "[ \t]*\\.*" re " +"))
21872 (add-text-properties (match-beginning 0) (match-end 0)
21873 (list 'face (org-get-todo-face 0)))
21874 (let ((s (buffer-substring (match-beginning 1) (match-end 1))))
21875 (delete-region (match-beginning 1) (1- (match-end 0)))
21876 (goto-char (match-beginning 1))
21877 (insert (format org-agenda-todo-keyword-format s)))))
21878 (setq re (concat (get-text-property 0 'org-todo-regexp x))
21879 pl (get-text-property 0 'prefix-length x))
21880 ; (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
21881 ; (add-text-properties
21882 ; (or (match-end 1) (match-end 0)) (match-end 0)
21883 ; (list 'face (org-get-todo-face (match-string 2 x)))
21884 ; x))
21885 (when (and re
21886 (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)")
21887 x (or pl 0)) pl))
21888 (add-text-properties
21889 (or (match-end 1) (match-end 0)) (match-end 0)
21890 (list 'face (org-get-todo-face (match-string 2 x)))
21892 (setq x (concat (substring x 0 (match-end 1))
21893 (format org-agenda-todo-keyword-format
21894 (match-string 2 x))
21896 (substring x (match-end 3)))))
21897 x)))
21899 (defsubst org-cmp-priority (a b)
21900 "Compare the priorities of string A and B."
21901 (let ((pa (or (get-text-property 1 'priority a) 0))
21902 (pb (or (get-text-property 1 'priority b) 0)))
21903 (cond ((> pa pb) +1)
21904 ((< pa pb) -1)
21905 (t nil))))
21907 (defsubst org-cmp-category (a b)
21908 "Compare the string values of categories of strings A and B."
21909 (let ((ca (or (get-text-property 1 'org-category a) ""))
21910 (cb (or (get-text-property 1 'org-category b) "")))
21911 (cond ((string-lessp ca cb) -1)
21912 ((string-lessp cb ca) +1)
21913 (t nil))))
21915 (defsubst org-cmp-tag (a b)
21916 "Compare the string values of categories of strings A and B."
21917 (let ((ta (car (last (get-text-property 1 'tags a))))
21918 (tb (car (last (get-text-property 1 'tags b)))))
21919 (cond ((not ta) +1)
21920 ((not tb) -1)
21921 ((string-lessp ta tb) -1)
21922 ((string-lessp tb ta) +1)
21923 (t nil))))
21925 (defsubst org-cmp-time (a b)
21926 "Compare the time-of-day values of strings A and B."
21927 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
21928 (ta (or (get-text-property 1 'time-of-day a) def))
21929 (tb (or (get-text-property 1 'time-of-day b) def)))
21930 (cond ((< ta tb) -1)
21931 ((< tb ta) +1)
21932 (t nil))))
21934 (defun org-entries-lessp (a b)
21935 "Predicate for sorting agenda entries."
21936 ;; The following variables will be used when the form is evaluated.
21937 ;; So even though the compiler complains, keep them.
21938 (let* ((time-up (org-cmp-time a b))
21939 (time-down (if time-up (- time-up) nil))
21940 (priority-up (org-cmp-priority a b))
21941 (priority-down (if priority-up (- priority-up) nil))
21942 (category-up (org-cmp-category a b))
21943 (category-down (if category-up (- category-up) nil))
21944 (category-keep (if category-up +1 nil))
21945 (tag-up (org-cmp-tag a b))
21946 (tag-down (if tag-up (- tag-up) nil)))
21947 (cdr (assoc
21948 (eval (cons 'or org-agenda-sorting-strategy-selected))
21949 '((-1 . t) (1 . nil) (nil . nil))))))
21951 ;;; Agenda restriction lock
21953 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
21954 "Overlay to mark the headline to which arenda commands are restricted.")
21955 (org-overlay-put org-agenda-restriction-lock-overlay
21956 'face 'org-agenda-restriction-lock)
21957 (org-overlay-put org-agenda-restriction-lock-overlay
21958 'help-echo "Agendas are currently limited to this subtree.")
21959 (org-detach-overlay org-agenda-restriction-lock-overlay)
21960 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
21961 "Overlay marking the agenda restriction line in speedbar.")
21962 (org-overlay-put org-speedbar-restriction-lock-overlay
21963 'face 'org-agenda-restriction-lock)
21964 (org-overlay-put org-speedbar-restriction-lock-overlay
21965 'help-echo "Agendas are currently limited to this item.")
21966 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21968 (defun org-agenda-set-restriction-lock (&optional type)
21969 "Set restriction lock for agenda, to current subtree or file.
21970 Restriction will be the file if TYPE is `file', or if type is the
21971 universal prefix '(4), or if the cursor is before the first headline
21972 in the file. Otherwise, restriction will be to the current subtree."
21973 (interactive "P")
21974 (and (equal type '(4)) (setq type 'file))
21975 (setq type (cond
21976 (type type)
21977 ((org-at-heading-p) 'subtree)
21978 ((condition-case nil (org-back-to-heading t) (error nil))
21979 'subtree)
21980 (t 'file)))
21981 (if (eq type 'subtree)
21982 (progn
21983 (setq org-agenda-restrict t)
21984 (setq org-agenda-overriding-restriction 'subtree)
21985 (put 'org-agenda-files 'org-restrict
21986 (list (buffer-file-name (buffer-base-buffer))))
21987 (org-back-to-heading t)
21988 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
21989 (move-marker org-agenda-restrict-begin (point))
21990 (move-marker org-agenda-restrict-end
21991 (save-excursion (org-end-of-subtree t)))
21992 (message "Locking agenda restriction to subtree"))
21993 (put 'org-agenda-files 'org-restrict
21994 (list (buffer-file-name (buffer-base-buffer))))
21995 (setq org-agenda-restrict nil)
21996 (setq org-agenda-overriding-restriction 'file)
21997 (move-marker org-agenda-restrict-begin nil)
21998 (move-marker org-agenda-restrict-end nil)
21999 (message "Locking agenda restriction to file"))
22000 (setq current-prefix-arg nil)
22001 (org-agenda-maybe-redo))
22003 (defun org-agenda-remove-restriction-lock (&optional noupdate)
22004 "Remove the agenda restriction lock."
22005 (interactive "P")
22006 (org-detach-overlay org-agenda-restriction-lock-overlay)
22007 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22008 (setq org-agenda-overriding-restriction nil)
22009 (setq org-agenda-restrict nil)
22010 (put 'org-agenda-files 'org-restrict nil)
22011 (move-marker org-agenda-restrict-begin nil)
22012 (move-marker org-agenda-restrict-end nil)
22013 (setq current-prefix-arg nil)
22014 (message "Agenda restriction lock removed")
22015 (or noupdate (org-agenda-maybe-redo)))
22017 (defun org-agenda-maybe-redo ()
22018 "If there is any window showing the agenda view, update it."
22019 (let ((w (get-buffer-window org-agenda-buffer-name t))
22020 (w0 (selected-window)))
22021 (when w
22022 (select-window w)
22023 (org-agenda-redo)
22024 (select-window w0)
22025 (if org-agenda-overriding-restriction
22026 (message "Agenda view shifted to new %s restriction"
22027 org-agenda-overriding-restriction)
22028 (message "Agenda restriction lock removed")))))
22030 ;;; Agenda commands
22032 (defun org-agenda-check-type (error &rest types)
22033 "Check if agenda buffer is of allowed type.
22034 If ERROR is non-nil, throw an error, otherwise just return nil."
22035 (if (memq org-agenda-type types)
22037 (if error
22038 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
22039 nil)))
22041 (defun org-agenda-quit ()
22042 "Exit agenda by removing the window or the buffer."
22043 (interactive)
22044 (let ((buf (current-buffer)))
22045 (if (not (one-window-p)) (delete-window))
22046 (kill-buffer buf)
22047 (org-agenda-maybe-reset-markers 'force)
22048 (org-columns-remove-overlays))
22049 ;; Maybe restore the pre-agenda window configuration.
22050 (and org-agenda-restore-windows-after-quit
22051 (not (eq org-agenda-window-setup 'other-frame))
22052 org-pre-agenda-window-conf
22053 (set-window-configuration org-pre-agenda-window-conf)))
22055 (defun org-agenda-exit ()
22056 "Exit agenda by removing the window or the buffer.
22057 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
22058 Org-mode buffers visited directly by the user will not be touched."
22059 (interactive)
22060 (org-release-buffers org-agenda-new-buffers)
22061 (setq org-agenda-new-buffers nil)
22062 (org-agenda-quit))
22064 (defun org-agenda-execute (arg)
22065 "Execute another agenda command, keeping same window.\\<global-map>
22066 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
22067 (interactive "P")
22068 (let ((org-agenda-window-setup 'current-window))
22069 (org-agenda arg)))
22071 (defun org-save-all-org-buffers ()
22072 "Save all Org-mode buffers without user confirmation."
22073 (interactive)
22074 (message "Saving all Org-mode buffers...")
22075 (save-some-buffers t 'org-mode-p)
22076 (message "Saving all Org-mode buffers... done"))
22078 (defun org-agenda-redo ()
22079 "Rebuild Agenda.
22080 When this is the global TODO list, a prefix argument will be interpreted."
22081 (interactive)
22082 (let* ((org-agenda-keep-modes t)
22083 (line (org-current-line))
22084 (window-line (- line (org-current-line (window-start))))
22085 (lprops (get 'org-agenda-redo-command 'org-lprops)))
22086 (message "Rebuilding agenda buffer...")
22087 (org-let lprops '(eval org-agenda-redo-command))
22088 (setq org-agenda-undo-list nil
22089 org-agenda-pending-undo-list nil)
22090 (message "Rebuilding agenda buffer...done")
22091 (goto-line line)
22092 (recenter window-line)))
22094 (defun org-agenda-goto-date (date)
22095 "Jump to DATE in agenda."
22096 (interactive (list (org-read-date)))
22097 (org-agenda-list nil date))
22099 (defun org-agenda-goto-today ()
22100 "Go to today."
22101 (interactive)
22102 (org-agenda-check-type t 'timeline 'agenda)
22103 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
22104 (cond
22105 (tdpos (goto-char tdpos))
22106 ((eq org-agenda-type 'agenda)
22107 (let* ((sd (time-to-days
22108 (time-subtract (current-time)
22109 (list 0 (* 3600 org-extend-today-until) 0))))
22110 (comp (org-agenda-compute-time-span sd org-agenda-span))
22111 (org-agenda-overriding-arguments org-agenda-last-arguments))
22112 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
22113 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
22114 (org-agenda-redo)
22115 (org-agenda-find-same-or-today-or-agenda)))
22116 (t (error "Cannot find today")))))
22118 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
22119 (goto-char
22120 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
22121 (text-property-any (point-min) (point-max) 'org-today t)
22122 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
22123 (point-min))))
22125 (defun org-agenda-later (arg)
22126 "Go forward in time by thee current span.
22127 With prefix ARG, go forward that many times the current span."
22128 (interactive "p")
22129 (org-agenda-check-type t 'agenda)
22130 (let* ((span org-agenda-span)
22131 (sd org-starting-day)
22132 (greg (calendar-gregorian-from-absolute sd))
22133 (cnt (get-text-property (point) 'org-day-cnt))
22134 greg2 nd)
22135 (cond
22136 ((eq span 'day)
22137 (setq sd (+ arg sd) nd 1))
22138 ((eq span 'week)
22139 (setq sd (+ (* 7 arg) sd) nd 7))
22140 ((eq span 'month)
22141 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
22142 sd (calendar-absolute-from-gregorian greg2))
22143 (setcar greg2 (1+ (car greg2)))
22144 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
22145 ((eq span 'year)
22146 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
22147 sd (calendar-absolute-from-gregorian greg2))
22148 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
22149 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
22150 (let ((org-agenda-overriding-arguments
22151 (list (car org-agenda-last-arguments) sd nd t)))
22152 (org-agenda-redo)
22153 (org-agenda-find-same-or-today-or-agenda cnt))))
22155 (defun org-agenda-earlier (arg)
22156 "Go backward in time by the current span.
22157 With prefix ARG, go backward that many times the current span."
22158 (interactive "p")
22159 (org-agenda-later (- arg)))
22161 (defun org-agenda-day-view ()
22162 "Switch to daily view for agenda."
22163 (interactive)
22164 (setq org-agenda-ndays 1)
22165 (org-agenda-change-time-span 'day))
22166 (defun org-agenda-week-view ()
22167 "Switch to daily view for agenda."
22168 (interactive)
22169 (setq org-agenda-ndays 7)
22170 (org-agenda-change-time-span 'week))
22171 (defun org-agenda-month-view ()
22172 "Switch to daily view for agenda."
22173 (interactive)
22174 (org-agenda-change-time-span 'month))
22175 (defun org-agenda-year-view ()
22176 "Switch to daily view for agenda."
22177 (interactive)
22178 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
22179 (org-agenda-change-time-span 'year)
22180 (error "Abort")))
22182 (defun org-agenda-change-time-span (span)
22183 "Change the agenda view to SPAN.
22184 SPAN may be `day', `week', `month', `year'."
22185 (org-agenda-check-type t 'agenda)
22186 (if (equal org-agenda-span span)
22187 (error "Viewing span is already \"%s\"" span))
22188 (let* ((sd (or (get-text-property (point) 'day)
22189 org-starting-day))
22190 (computed (org-agenda-compute-time-span sd span))
22191 (org-agenda-overriding-arguments
22192 (list (car org-agenda-last-arguments)
22193 (car computed) (cdr computed) t)))
22194 (org-agenda-redo)
22195 (org-agenda-find-same-or-today-or-agenda))
22196 (org-agenda-set-mode-name)
22197 (message "Switched to %s view" span))
22199 (defun org-agenda-compute-time-span (sd span)
22200 "Compute starting date and number of days for agenda.
22201 SPAN may be `day', `week', `month', `year'. The return value
22202 is a cons cell with the starting date and the number of days,
22203 so that the date SD will be in that range."
22204 (let* ((greg (calendar-gregorian-from-absolute sd))
22206 (cond
22207 ((eq span 'day)
22208 (setq nd 1))
22209 ((eq span 'week)
22210 (let* ((nt (calendar-day-of-week
22211 (calendar-gregorian-from-absolute sd)))
22212 (d (if org-agenda-start-on-weekday
22213 (- nt org-agenda-start-on-weekday)
22214 0)))
22215 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
22216 (setq nd 7)))
22217 ((eq span 'month)
22218 (setq sd (calendar-absolute-from-gregorian
22219 (list (car greg) 1 (nth 2 greg)))
22220 nd (- (calendar-absolute-from-gregorian
22221 (list (1+ (car greg)) 1 (nth 2 greg)))
22222 sd)))
22223 ((eq span 'year)
22224 (setq sd (calendar-absolute-from-gregorian
22225 (list 1 1 (nth 2 greg)))
22226 nd (- (calendar-absolute-from-gregorian
22227 (list 1 1 (1+ (nth 2 greg))))
22228 sd))))
22229 (cons sd nd)))
22231 ;; FIXME: does not work if user makes date format that starts with a blank
22232 (defun org-agenda-next-date-line (&optional arg)
22233 "Jump to the next line indicating a date in agenda buffer."
22234 (interactive "p")
22235 (org-agenda-check-type t 'agenda 'timeline)
22236 (beginning-of-line 1)
22237 (if (looking-at "^\\S-") (forward-char 1))
22238 (if (not (re-search-forward "^\\S-" nil t arg))
22239 (progn
22240 (backward-char 1)
22241 (error "No next date after this line in this buffer")))
22242 (goto-char (match-beginning 0)))
22244 (defun org-agenda-previous-date-line (&optional arg)
22245 "Jump to the previous line indicating a date in agenda buffer."
22246 (interactive "p")
22247 (org-agenda-check-type t 'agenda 'timeline)
22248 (beginning-of-line 1)
22249 (if (not (re-search-backward "^\\S-" nil t arg))
22250 (error "No previous date before this line in this buffer")))
22252 ;; Initialize the highlight
22253 (defvar org-hl (org-make-overlay 1 1))
22254 (org-overlay-put org-hl 'face 'highlight)
22256 (defun org-highlight (begin end &optional buffer)
22257 "Highlight a region with overlay."
22258 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
22259 org-hl begin end (or buffer (current-buffer))))
22261 (defun org-unhighlight ()
22262 "Detach overlay INDEX."
22263 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
22265 ;; FIXME this is currently not used.
22266 (defun org-highlight-until-next-command (beg end &optional buffer)
22267 (org-highlight beg end buffer)
22268 (add-hook 'pre-command-hook 'org-unhighlight-once))
22269 (defun org-unhighlight-once ()
22270 (remove-hook 'pre-command-hook 'org-unhighlight-once)
22271 (org-unhighlight))
22273 (defun org-agenda-follow-mode ()
22274 "Toggle follow mode in an agenda buffer."
22275 (interactive)
22276 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
22277 (org-agenda-set-mode-name)
22278 (message "Follow mode is %s"
22279 (if org-agenda-follow-mode "on" "off")))
22281 (defun org-agenda-log-mode ()
22282 "Toggle log mode in an agenda buffer."
22283 (interactive)
22284 (org-agenda-check-type t 'agenda 'timeline)
22285 (setq org-agenda-show-log (not org-agenda-show-log))
22286 (org-agenda-set-mode-name)
22287 (org-agenda-redo)
22288 (message "Log mode is %s"
22289 (if org-agenda-show-log "on" "off")))
22291 (defun org-agenda-toggle-diary ()
22292 "Toggle diary inclusion in an agenda buffer."
22293 (interactive)
22294 (org-agenda-check-type t 'agenda)
22295 (setq org-agenda-include-diary (not org-agenda-include-diary))
22296 (org-agenda-redo)
22297 (org-agenda-set-mode-name)
22298 (message "Diary inclusion turned %s"
22299 (if org-agenda-include-diary "on" "off")))
22301 (defun org-agenda-toggle-time-grid ()
22302 "Toggle time grid in an agenda buffer."
22303 (interactive)
22304 (org-agenda-check-type t 'agenda)
22305 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
22306 (org-agenda-redo)
22307 (org-agenda-set-mode-name)
22308 (message "Time-grid turned %s"
22309 (if org-agenda-use-time-grid "on" "off")))
22311 (defun org-agenda-set-mode-name ()
22312 "Set the mode name to indicate all the small mode settings."
22313 (setq mode-name
22314 (concat "Org-Agenda"
22315 (if (equal org-agenda-ndays 1) " Day" "")
22316 (if (equal org-agenda-ndays 7) " Week" "")
22317 (if org-agenda-follow-mode " Follow" "")
22318 (if org-agenda-include-diary " Diary" "")
22319 (if org-agenda-use-time-grid " Grid" "")
22320 (if org-agenda-show-log " Log" "")))
22321 (force-mode-line-update))
22323 (defun org-agenda-post-command-hook ()
22324 (and (eolp) (not (bolp)) (backward-char 1))
22325 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
22326 (if (and org-agenda-follow-mode
22327 (get-text-property (point) 'org-marker))
22328 (org-agenda-show)))
22330 (defun org-agenda-show-priority ()
22331 "Show the priority of the current item.
22332 This priority is composed of the main priority given with the [#A] cookies,
22333 and by additional input from the age of a schedules or deadline entry."
22334 (interactive)
22335 (let* ((pri (get-text-property (point-at-bol) 'priority)))
22336 (message "Priority is %d" (if pri pri -1000))))
22338 (defun org-agenda-show-tags ()
22339 "Show the tags applicable to the current item."
22340 (interactive)
22341 (let* ((tags (get-text-property (point-at-bol) 'tags)))
22342 (if tags
22343 (message "Tags are :%s:"
22344 (org-no-properties (mapconcat 'identity tags ":")))
22345 (message "No tags associated with this line"))))
22347 (defun org-agenda-goto (&optional highlight)
22348 "Go to the Org-mode file which contains the item at point."
22349 (interactive)
22350 (let* ((marker (or (get-text-property (point) 'org-marker)
22351 (org-agenda-error)))
22352 (buffer (marker-buffer marker))
22353 (pos (marker-position marker)))
22354 (switch-to-buffer-other-window buffer)
22355 (widen)
22356 (goto-char pos)
22357 (when (org-mode-p)
22358 (org-show-context 'agenda)
22359 (save-excursion
22360 (and (outline-next-heading)
22361 (org-flag-heading nil)))) ; show the next heading
22362 (recenter (/ (window-height) 2))
22363 (run-hooks 'org-agenda-after-show-hook)
22364 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
22366 (defvar org-agenda-after-show-hook nil
22367 "Normal hook run after an item has been shown from the agenda.
22368 Point is in the buffer where the item originated.")
22370 (defun org-agenda-kill ()
22371 "Kill the entry or subtree belonging to the current agenda entry."
22372 (interactive)
22373 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22374 (let* ((marker (or (get-text-property (point) 'org-marker)
22375 (org-agenda-error)))
22376 (buffer (marker-buffer marker))
22377 (pos (marker-position marker))
22378 (type (get-text-property (point) 'type))
22379 dbeg dend (n 0) conf)
22380 (org-with-remote-undo buffer
22381 (with-current-buffer buffer
22382 (save-excursion
22383 (goto-char pos)
22384 (if (and (org-mode-p) (not (member type '("sexp"))))
22385 (setq dbeg (progn (org-back-to-heading t) (point))
22386 dend (org-end-of-subtree t t))
22387 (setq dbeg (point-at-bol)
22388 dend (min (point-max) (1+ (point-at-eol)))))
22389 (goto-char dbeg)
22390 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
22391 (setq conf (or (eq t org-agenda-confirm-kill)
22392 (and (numberp org-agenda-confirm-kill)
22393 (> n org-agenda-confirm-kill))))
22394 (and conf
22395 (not (y-or-n-p
22396 (format "Delete entry with %d lines in buffer \"%s\"? "
22397 n (buffer-name buffer))))
22398 (error "Abort"))
22399 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
22400 (with-current-buffer buffer (delete-region dbeg dend))
22401 (message "Agenda item and source killed"))))
22403 (defun org-agenda-archive ()
22404 "Kill the entry or subtree belonging to the current agenda entry."
22405 (interactive)
22406 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22407 (let* ((marker (or (get-text-property (point) 'org-marker)
22408 (org-agenda-error)))
22409 (buffer (marker-buffer marker))
22410 (pos (marker-position marker)))
22411 (org-with-remote-undo buffer
22412 (with-current-buffer buffer
22413 (if (org-mode-p)
22414 (save-excursion
22415 (goto-char pos)
22416 (org-remove-subtree-entries-from-agenda)
22417 (org-back-to-heading t)
22418 (org-archive-subtree))
22419 (error "Archiving works only in Org-mode files"))))))
22421 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
22422 "Remove all lines in the agenda that correspond to a given subtree.
22423 The subtree is the one in buffer BUF, starting at BEG and ending at END.
22424 If this information is not given, the function uses the tree at point."
22425 (let ((buf (or buf (current-buffer))) m p)
22426 (save-excursion
22427 (unless (and beg end)
22428 (org-back-to-heading t)
22429 (setq beg (point))
22430 (org-end-of-subtree t)
22431 (setq end (point)))
22432 (set-buffer (get-buffer org-agenda-buffer-name))
22433 (save-excursion
22434 (goto-char (point-max))
22435 (beginning-of-line 1)
22436 (while (not (bobp))
22437 (when (and (setq m (get-text-property (point) 'org-marker))
22438 (equal buf (marker-buffer m))
22439 (setq p (marker-position m))
22440 (>= p beg)
22441 (<= p end))
22442 (let ((inhibit-read-only t))
22443 (delete-region (point-at-bol) (1+ (point-at-eol)))))
22444 (beginning-of-line 0))))))
22446 (defun org-agenda-open-link ()
22447 "Follow the link in the current line, if any."
22448 (interactive)
22449 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
22450 (save-excursion
22451 (save-restriction
22452 (narrow-to-region (point-at-bol) (point-at-eol))
22453 (org-open-at-point))))
22455 (defun org-agenda-copy-local-variable (var)
22456 "Get a variable from a referenced buffer and install it here."
22457 (let ((m (get-text-property (point) 'org-marker)))
22458 (when (and m (buffer-live-p (marker-buffer m)))
22459 (org-set-local var (with-current-buffer (marker-buffer m)
22460 (symbol-value var))))))
22462 (defun org-agenda-switch-to (&optional delete-other-windows)
22463 "Go to the Org-mode file which contains the item at point."
22464 (interactive)
22465 (let* ((marker (or (get-text-property (point) 'org-marker)
22466 (org-agenda-error)))
22467 (buffer (marker-buffer marker))
22468 (pos (marker-position marker)))
22469 (switch-to-buffer buffer)
22470 (and delete-other-windows (delete-other-windows))
22471 (widen)
22472 (goto-char pos)
22473 (when (org-mode-p)
22474 (org-show-context 'agenda)
22475 (save-excursion
22476 (and (outline-next-heading)
22477 (org-flag-heading nil)))))) ; show the next heading
22479 (defun org-agenda-goto-mouse (ev)
22480 "Go to the Org-mode file which contains the item at the mouse click."
22481 (interactive "e")
22482 (mouse-set-point ev)
22483 (org-agenda-goto))
22485 (defun org-agenda-show ()
22486 "Display the Org-mode file which contains the item at point."
22487 (interactive)
22488 (let ((win (selected-window)))
22489 (org-agenda-goto t)
22490 (select-window win)))
22492 (defun org-agenda-recenter (arg)
22493 "Display the Org-mode file which contains the item at point and recenter."
22494 (interactive "P")
22495 (let ((win (selected-window)))
22496 (org-agenda-goto t)
22497 (recenter arg)
22498 (select-window win)))
22500 (defun org-agenda-show-mouse (ev)
22501 "Display the Org-mode file which contains the item at the mouse click."
22502 (interactive "e")
22503 (mouse-set-point ev)
22504 (org-agenda-show))
22506 (defun org-agenda-check-no-diary ()
22507 "Check if the entry is a diary link and abort if yes."
22508 (if (get-text-property (point) 'org-agenda-diary-link)
22509 (org-agenda-error)))
22511 (defun org-agenda-error ()
22512 (error "Command not allowed in this line"))
22514 (defun org-agenda-tree-to-indirect-buffer ()
22515 "Show the subtree corresponding to the current entry in an indirect buffer.
22516 This calls the command `org-tree-to-indirect-buffer' from the original
22517 Org-mode buffer.
22518 With numerical prefix arg ARG, go up to this level and then take that tree.
22519 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
22520 dedicated frame)."
22521 (interactive)
22522 (org-agenda-check-no-diary)
22523 (let* ((marker (or (get-text-property (point) 'org-marker)
22524 (org-agenda-error)))
22525 (buffer (marker-buffer marker))
22526 (pos (marker-position marker)))
22527 (with-current-buffer buffer
22528 (save-excursion
22529 (goto-char pos)
22530 (call-interactively 'org-tree-to-indirect-buffer)))))
22532 (defvar org-last-heading-marker (make-marker)
22533 "Marker pointing to the headline that last changed its TODO state
22534 by a remote command from the agenda.")
22536 (defun org-agenda-todo-nextset ()
22537 "Switch TODO entry to next sequence."
22538 (interactive)
22539 (org-agenda-todo 'nextset))
22541 (defun org-agenda-todo-previousset ()
22542 "Switch TODO entry to previous sequence."
22543 (interactive)
22544 (org-agenda-todo 'previousset))
22546 (defun org-agenda-todo (&optional arg)
22547 "Cycle TODO state of line at point, also in Org-mode file.
22548 This changes the line at point, all other lines in the agenda referring to
22549 the same tree node, and the headline of the tree node in the Org-mode file."
22550 (interactive "P")
22551 (org-agenda-check-no-diary)
22552 (let* ((col (current-column))
22553 (marker (or (get-text-property (point) 'org-marker)
22554 (org-agenda-error)))
22555 (buffer (marker-buffer marker))
22556 (pos (marker-position marker))
22557 (hdmarker (get-text-property (point) 'org-hd-marker))
22558 (inhibit-read-only t)
22559 newhead)
22560 (org-with-remote-undo buffer
22561 (with-current-buffer buffer
22562 (widen)
22563 (goto-char pos)
22564 (org-show-context 'agenda)
22565 (save-excursion
22566 (and (outline-next-heading)
22567 (org-flag-heading nil))) ; show the next heading
22568 (org-todo arg)
22569 (and (bolp) (forward-char 1))
22570 (setq newhead (org-get-heading))
22571 (save-excursion
22572 (org-back-to-heading)
22573 (move-marker org-last-heading-marker (point))))
22574 (beginning-of-line 1)
22575 (save-excursion
22576 (org-agenda-change-all-lines newhead hdmarker 'fixface))
22577 (move-to-column col))))
22579 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
22580 "Change all lines in the agenda buffer which match HDMARKER.
22581 The new content of the line will be NEWHEAD (as modified by
22582 `org-format-agenda-item'). HDMARKER is checked with
22583 `equal' against all `org-hd-marker' text properties in the file.
22584 If FIXFACE is non-nil, the face of each item is modified acording to
22585 the new TODO state."
22586 (let* ((inhibit-read-only t)
22587 props m pl undone-face done-face finish new dotime cat tags)
22588 (save-excursion
22589 (goto-char (point-max))
22590 (beginning-of-line 1)
22591 (while (not finish)
22592 (setq finish (bobp))
22593 (when (and (setq m (get-text-property (point) 'org-hd-marker))
22594 (equal m hdmarker))
22595 (setq props (text-properties-at (point))
22596 dotime (get-text-property (point) 'dotime)
22597 cat (get-text-property (point) 'org-category)
22598 tags (get-text-property (point) 'tags)
22599 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
22600 pl (get-text-property (point) 'prefix-length)
22601 undone-face (get-text-property (point) 'undone-face)
22602 done-face (get-text-property (point) 'done-face))
22603 (move-to-column pl)
22604 (cond
22605 ((equal new "")
22606 (beginning-of-line 1)
22607 (and (looking-at ".*\n?") (replace-match "")))
22608 ((looking-at ".*")
22609 (replace-match new t t)
22610 (beginning-of-line 1)
22611 (add-text-properties (point-at-bol) (point-at-eol) props)
22612 (when fixface
22613 (add-text-properties
22614 (point-at-bol) (point-at-eol)
22615 (list 'face
22616 (if org-last-todo-state-is-todo
22617 undone-face done-face))))
22618 (org-agenda-highlight-todo 'line)
22619 (beginning-of-line 1))
22620 (t (error "Line update did not work"))))
22621 (beginning-of-line 0)))
22622 (org-finalize-agenda)))
22624 (defun org-agenda-align-tags (&optional line)
22625 "Align all tags in agenda items to `org-agenda-tags-column'."
22626 (let ((inhibit-read-only t) l c)
22627 (save-excursion
22628 (goto-char (if line (point-at-bol) (point-min)))
22629 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22630 (if line (point-at-eol) nil) t)
22631 (add-text-properties
22632 (match-beginning 2) (match-end 2)
22633 (list 'face (list 'org-tag (get-text-property
22634 (match-beginning 2) 'face))))
22635 (setq l (- (match-end 2) (match-beginning 2))
22636 c (if (< org-agenda-tags-column 0)
22637 (- (abs org-agenda-tags-column) l)
22638 org-agenda-tags-column))
22639 (delete-region (match-beginning 1) (match-end 1))
22640 (goto-char (match-beginning 1))
22641 (insert (org-add-props
22642 (make-string (max 1 (- c (current-column))) ?\ )
22643 (text-properties-at (point))))))))
22645 (defun org-agenda-priority-up ()
22646 "Increase the priority of line at point, also in Org-mode file."
22647 (interactive)
22648 (org-agenda-priority 'up))
22650 (defun org-agenda-priority-down ()
22651 "Decrease the priority of line at point, also in Org-mode file."
22652 (interactive)
22653 (org-agenda-priority 'down))
22655 (defun org-agenda-priority (&optional force-direction)
22656 "Set the priority of line at point, also in Org-mode file.
22657 This changes the line at point, all other lines in the agenda referring to
22658 the same tree node, and the headline of the tree node in the Org-mode file."
22659 (interactive)
22660 (org-agenda-check-no-diary)
22661 (let* ((marker (or (get-text-property (point) 'org-marker)
22662 (org-agenda-error)))
22663 (hdmarker (get-text-property (point) 'org-hd-marker))
22664 (buffer (marker-buffer hdmarker))
22665 (pos (marker-position hdmarker))
22666 (inhibit-read-only t)
22667 newhead)
22668 (org-with-remote-undo buffer
22669 (with-current-buffer buffer
22670 (widen)
22671 (goto-char pos)
22672 (org-show-context 'agenda)
22673 (save-excursion
22674 (and (outline-next-heading)
22675 (org-flag-heading nil))) ; show the next heading
22676 (funcall 'org-priority force-direction)
22677 (end-of-line 1)
22678 (setq newhead (org-get-heading)))
22679 (org-agenda-change-all-lines newhead hdmarker)
22680 (beginning-of-line 1))))
22682 (defun org-get-tags-at (&optional pos)
22683 "Get a list of all headline tags applicable at POS.
22684 POS defaults to point. If tags are inherited, the list contains
22685 the targets in the same sequence as the headlines appear, i.e.
22686 the tags of the current headline come last."
22687 (interactive)
22688 (let (tags lastpos)
22689 (save-excursion
22690 (save-restriction
22691 (widen)
22692 (goto-char (or pos (point)))
22693 (save-match-data
22694 (org-back-to-heading t)
22695 (condition-case nil
22696 (while (not (equal lastpos (point)))
22697 (setq lastpos (point))
22698 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
22699 (setq tags (append (org-split-string
22700 (org-match-string-no-properties 1) ":")
22701 tags)))
22702 (or org-use-tag-inheritance (error ""))
22703 (org-up-heading-all 1))
22704 (error nil))))
22705 tags)))
22707 ;; FIXME: should fix the tags property of the agenda line.
22708 (defun org-agenda-set-tags ()
22709 "Set tags for the current headline."
22710 (interactive)
22711 (org-agenda-check-no-diary)
22712 (if (and (org-region-active-p) (interactive-p))
22713 (call-interactively 'org-change-tag-in-region)
22714 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22715 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22716 (org-agenda-error)))
22717 (buffer (marker-buffer hdmarker))
22718 (pos (marker-position hdmarker))
22719 (inhibit-read-only t)
22720 newhead)
22721 (org-with-remote-undo buffer
22722 (with-current-buffer buffer
22723 (widen)
22724 (goto-char pos)
22725 (save-excursion
22726 (org-show-context 'agenda))
22727 (save-excursion
22728 (and (outline-next-heading)
22729 (org-flag-heading nil))) ; show the next heading
22730 (goto-char pos)
22731 (call-interactively 'org-set-tags)
22732 (end-of-line 1)
22733 (setq newhead (org-get-heading)))
22734 (org-agenda-change-all-lines newhead hdmarker)
22735 (beginning-of-line 1)))))
22737 (defun org-agenda-toggle-archive-tag ()
22738 "Toggle the archive tag for the current entry."
22739 (interactive)
22740 (org-agenda-check-no-diary)
22741 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22742 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22743 (org-agenda-error)))
22744 (buffer (marker-buffer hdmarker))
22745 (pos (marker-position hdmarker))
22746 (inhibit-read-only t)
22747 newhead)
22748 (org-with-remote-undo buffer
22749 (with-current-buffer buffer
22750 (widen)
22751 (goto-char pos)
22752 (org-show-context 'agenda)
22753 (save-excursion
22754 (and (outline-next-heading)
22755 (org-flag-heading nil))) ; show the next heading
22756 (call-interactively 'org-toggle-archive-tag)
22757 (end-of-line 1)
22758 (setq newhead (org-get-heading)))
22759 (org-agenda-change-all-lines newhead hdmarker)
22760 (beginning-of-line 1))))
22762 (defun org-agenda-date-later (arg &optional what)
22763 "Change the date of this item to one day later."
22764 (interactive "p")
22765 (org-agenda-check-type t 'agenda 'timeline)
22766 (org-agenda-check-no-diary)
22767 (let* ((marker (or (get-text-property (point) 'org-marker)
22768 (org-agenda-error)))
22769 (buffer (marker-buffer marker))
22770 (pos (marker-position marker)))
22771 (org-with-remote-undo buffer
22772 (with-current-buffer buffer
22773 (widen)
22774 (goto-char pos)
22775 (if (not (org-at-timestamp-p))
22776 (error "Cannot find time stamp"))
22777 (org-timestamp-change arg (or what 'day)))
22778 (org-agenda-show-new-time marker org-last-changed-timestamp))
22779 (message "Time stamp changed to %s" org-last-changed-timestamp)))
22781 (defun org-agenda-date-earlier (arg &optional what)
22782 "Change the date of this item to one day earlier."
22783 (interactive "p")
22784 (org-agenda-date-later (- arg) what))
22786 (defun org-agenda-show-new-time (marker stamp &optional prefix)
22787 "Show new date stamp via text properties."
22788 ;; We use text properties to make this undoable
22789 (let ((inhibit-read-only t))
22790 (setq stamp (concat " " prefix " => " stamp))
22791 (save-excursion
22792 (goto-char (point-max))
22793 (while (not (bobp))
22794 (when (equal marker (get-text-property (point) 'org-marker))
22795 (move-to-column (- (window-width) (length stamp)) t)
22796 (if (featurep 'xemacs)
22797 ;; Use `duplicable' property to trigger undo recording
22798 (let ((ex (make-extent nil nil))
22799 (gl (make-glyph stamp)))
22800 (set-glyph-face gl 'secondary-selection)
22801 (set-extent-properties
22802 ex (list 'invisible t 'end-glyph gl 'duplicable t))
22803 (insert-extent ex (1- (point)) (point-at-eol)))
22804 (add-text-properties
22805 (1- (point)) (point-at-eol)
22806 (list 'display (org-add-props stamp nil
22807 'face 'secondary-selection))))
22808 (beginning-of-line 1))
22809 (beginning-of-line 0)))))
22811 (defun org-agenda-date-prompt (arg)
22812 "Change the date of this item. Date is prompted for, with default today.
22813 The prefix ARG is passed to the `org-time-stamp' command and can therefore
22814 be used to request time specification in the time stamp."
22815 (interactive "P")
22816 (org-agenda-check-type t 'agenda 'timeline)
22817 (org-agenda-check-no-diary)
22818 (let* ((marker (or (get-text-property (point) 'org-marker)
22819 (org-agenda-error)))
22820 (buffer (marker-buffer marker))
22821 (pos (marker-position marker)))
22822 (org-with-remote-undo buffer
22823 (with-current-buffer buffer
22824 (widen)
22825 (goto-char pos)
22826 (if (not (org-at-timestamp-p))
22827 (error "Cannot find time stamp"))
22828 (org-time-stamp arg)
22829 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
22831 (defun org-agenda-schedule (arg)
22832 "Schedule the item at point."
22833 (interactive "P")
22834 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22835 (org-agenda-check-no-diary)
22836 (let* ((marker (or (get-text-property (point) 'org-marker)
22837 (org-agenda-error)))
22838 (buffer (marker-buffer marker))
22839 (pos (marker-position marker))
22840 (org-insert-labeled-timestamps-at-point nil)
22842 (org-with-remote-undo buffer
22843 (with-current-buffer buffer
22844 (widen)
22845 (goto-char pos)
22846 (setq ts (org-schedule arg)))
22847 (org-agenda-show-new-time marker ts "S"))
22848 (message "Item scheduled for %s" ts)))
22850 (defun org-agenda-deadline (arg)
22851 "Schedule the item at point."
22852 (interactive "P")
22853 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22854 (org-agenda-check-no-diary)
22855 (let* ((marker (or (get-text-property (point) 'org-marker)
22856 (org-agenda-error)))
22857 (buffer (marker-buffer marker))
22858 (pos (marker-position marker))
22859 (org-insert-labeled-timestamps-at-point nil)
22861 (org-with-remote-undo buffer
22862 (with-current-buffer buffer
22863 (widen)
22864 (goto-char pos)
22865 (setq ts (org-deadline arg)))
22866 (org-agenda-show-new-time marker ts "S"))
22867 (message "Deadline for this item set to %s" ts)))
22869 (defun org-get-heading (&optional no-tags)
22870 "Return the heading of the current entry, without the stars."
22871 (save-excursion
22872 (org-back-to-heading t)
22873 (if (looking-at
22874 (if no-tags
22875 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
22876 "\\*+[ \t]+\\([^\r\n]*\\)"))
22877 (match-string 1) "")))
22879 (defun org-agenda-clock-in (&optional arg)
22880 "Start the clock on the currently selected item."
22881 (interactive "P")
22882 (org-agenda-check-no-diary)
22883 (let* ((marker (or (get-text-property (point) 'org-marker)
22884 (org-agenda-error)))
22885 (pos (marker-position marker)))
22886 (org-with-remote-undo (marker-buffer marker)
22887 (with-current-buffer (marker-buffer marker)
22888 (widen)
22889 (goto-char pos)
22890 (org-clock-in)))))
22892 (defun org-agenda-clock-out (&optional arg)
22893 "Stop the currently running clock."
22894 (interactive "P")
22895 (unless (marker-buffer org-clock-marker)
22896 (error "No running clock"))
22897 (org-with-remote-undo (marker-buffer org-clock-marker)
22898 (org-clock-out)))
22900 (defun org-agenda-clock-cancel (&optional arg)
22901 "Cancel the currently running clock."
22902 (interactive "P")
22903 (unless (marker-buffer org-clock-marker)
22904 (error "No running clock"))
22905 (org-with-remote-undo (marker-buffer org-clock-marker)
22906 (org-clock-cancel)))
22908 (defun org-agenda-diary-entry ()
22909 "Make a diary entry, like the `i' command from the calendar.
22910 All the standard commands work: block, weekly etc."
22911 (interactive)
22912 (org-agenda-check-type t 'agenda 'timeline)
22913 (require 'diary-lib)
22914 (let* ((char (progn
22915 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
22916 (read-char-exclusive)))
22917 (cmd (cdr (assoc char
22918 '((?d . insert-diary-entry)
22919 (?w . insert-weekly-diary-entry)
22920 (?m . insert-monthly-diary-entry)
22921 (?y . insert-yearly-diary-entry)
22922 (?a . insert-anniversary-diary-entry)
22923 (?b . insert-block-diary-entry)
22924 (?c . insert-cyclic-diary-entry)))))
22925 (oldf (symbol-function 'calendar-cursor-to-date))
22926 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
22927 (point (point))
22928 (mark (or (mark t) (point))))
22929 (unless cmd
22930 (error "No command associated with <%c>" char))
22931 (unless (and (get-text-property point 'day)
22932 (or (not (equal ?b char))
22933 (get-text-property mark 'day)))
22934 (error "Don't know which date to use for diary entry"))
22935 ;; We implement this by hacking the `calendar-cursor-to-date' function
22936 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
22937 (let ((calendar-mark-ring
22938 (list (calendar-gregorian-from-absolute
22939 (or (get-text-property mark 'day)
22940 (get-text-property point 'day))))))
22941 (unwind-protect
22942 (progn
22943 (fset 'calendar-cursor-to-date
22944 (lambda (&optional error)
22945 (calendar-gregorian-from-absolute
22946 (get-text-property point 'day))))
22947 (call-interactively cmd))
22948 (fset 'calendar-cursor-to-date oldf)))))
22951 (defun org-agenda-execute-calendar-command (cmd)
22952 "Execute a calendar command from the agenda, with the date associated to
22953 the cursor position."
22954 (org-agenda-check-type t 'agenda 'timeline)
22955 (require 'diary-lib)
22956 (unless (get-text-property (point) 'day)
22957 (error "Don't know which date to use for calendar command"))
22958 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
22959 (point (point))
22960 (date (calendar-gregorian-from-absolute
22961 (get-text-property point 'day)))
22962 ;; the following 3 vars are needed in the calendar
22963 (displayed-day (extract-calendar-day date))
22964 (displayed-month (extract-calendar-month date))
22965 (displayed-year (extract-calendar-year date)))
22966 (unwind-protect
22967 (progn
22968 (fset 'calendar-cursor-to-date
22969 (lambda (&optional error)
22970 (calendar-gregorian-from-absolute
22971 (get-text-property point 'day))))
22972 (call-interactively cmd))
22973 (fset 'calendar-cursor-to-date oldf))))
22975 (defun org-agenda-phases-of-moon ()
22976 "Display the phases of the moon for the 3 months around the cursor date."
22977 (interactive)
22978 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
22980 (defun org-agenda-holidays ()
22981 "Display the holidays for the 3 months around the cursor date."
22982 (interactive)
22983 (org-agenda-execute-calendar-command 'list-calendar-holidays))
22985 (defun org-agenda-sunrise-sunset (arg)
22986 "Display sunrise and sunset for the cursor date.
22987 Latitude and longitude can be specified with the variables
22988 `calendar-latitude' and `calendar-longitude'. When called with prefix
22989 argument, latitude and longitude will be prompted for."
22990 (interactive "P")
22991 (let ((calendar-longitude (if arg nil calendar-longitude))
22992 (calendar-latitude (if arg nil calendar-latitude))
22993 (calendar-location-name
22994 (if arg "the given coordinates" calendar-location-name)))
22995 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
22997 (defun org-agenda-goto-calendar ()
22998 "Open the Emacs calendar with the date at the cursor."
22999 (interactive)
23000 (org-agenda-check-type t 'agenda 'timeline)
23001 (let* ((day (or (get-text-property (point) 'day)
23002 (error "Don't know which date to open in calendar")))
23003 (date (calendar-gregorian-from-absolute day))
23004 (calendar-move-hook nil)
23005 (view-calendar-holidays-initially nil)
23006 (view-diary-entries-initially nil))
23007 (calendar)
23008 (calendar-goto-date date)))
23010 (defun org-calendar-goto-agenda ()
23011 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
23012 This is a command that has to be installed in `calendar-mode-map'."
23013 (interactive)
23014 (org-agenda-list nil (calendar-absolute-from-gregorian
23015 (calendar-cursor-to-date))
23016 nil))
23018 (defun org-agenda-convert-date ()
23019 (interactive)
23020 (org-agenda-check-type t 'agenda 'timeline)
23021 (let ((day (get-text-property (point) 'day))
23022 date s)
23023 (unless day
23024 (error "Don't know which date to convert"))
23025 (setq date (calendar-gregorian-from-absolute day))
23026 (setq s (concat
23027 "Gregorian: " (calendar-date-string date) "\n"
23028 "ISO: " (calendar-iso-date-string date) "\n"
23029 "Day of Yr: " (calendar-day-of-year-string date) "\n"
23030 "Julian: " (calendar-julian-date-string date) "\n"
23031 "Astron. JD: " (calendar-astro-date-string date)
23032 " (Julian date number at noon UTC)\n"
23033 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
23034 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
23035 "French: " (calendar-french-date-string date) "\n"
23036 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
23037 "Mayan: " (calendar-mayan-date-string date) "\n"
23038 "Coptic: " (calendar-coptic-date-string date) "\n"
23039 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
23040 "Persian: " (calendar-persian-date-string date) "\n"
23041 "Chinese: " (calendar-chinese-date-string date) "\n"))
23042 (with-output-to-temp-buffer "*Dates*"
23043 (princ s))
23044 (if (fboundp 'fit-window-to-buffer)
23045 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
23048 ;;;; Embedded LaTeX
23050 (defvar org-cdlatex-mode-map (make-sparse-keymap)
23051 "Keymap for the minor `org-cdlatex-mode'.")
23053 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
23054 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
23055 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
23056 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
23057 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
23059 (defvar org-cdlatex-texmathp-advice-is-done nil
23060 "Flag remembering if we have applied the advice to texmathp already.")
23062 (define-minor-mode org-cdlatex-mode
23063 "Toggle the minor `org-cdlatex-mode'.
23064 This mode supports entering LaTeX environment and math in LaTeX fragments
23065 in Org-mode.
23066 \\{org-cdlatex-mode-map}"
23067 nil " OCDL" nil
23068 (when org-cdlatex-mode (require 'cdlatex))
23069 (unless org-cdlatex-texmathp-advice-is-done
23070 (setq org-cdlatex-texmathp-advice-is-done t)
23071 (defadvice texmathp (around org-math-always-on activate)
23072 "Always return t in org-mode buffers.
23073 This is because we want to insert math symbols without dollars even outside
23074 the LaTeX math segments. If Orgmode thinks that point is actually inside
23075 en embedded LaTeX fragement, let texmathp do its job.
23076 \\[org-cdlatex-mode-map]"
23077 (interactive)
23078 (let (p)
23079 (cond
23080 ((not (org-mode-p)) ad-do-it)
23081 ((eq this-command 'cdlatex-math-symbol)
23082 (setq ad-return-value t
23083 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
23085 (let ((p (org-inside-LaTeX-fragment-p)))
23086 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
23087 (setq ad-return-value t
23088 texmathp-why '("Org-mode embedded math" . 0))
23089 (if p ad-do-it)))))))))
23091 (defun turn-on-org-cdlatex ()
23092 "Unconditionally turn on `org-cdlatex-mode'."
23093 (org-cdlatex-mode 1))
23095 (defun org-inside-LaTeX-fragment-p ()
23096 "Test if point is inside a LaTeX fragment.
23097 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
23098 sequence appearing also before point.
23099 Even though the matchers for math are configurable, this function assumes
23100 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
23101 delimiters are skipped when they have been removed by customization.
23102 The return value is nil, or a cons cell with the delimiter and
23103 and the position of this delimiter.
23105 This function does a reasonably good job, but can locally be fooled by
23106 for example currency specifications. For example it will assume being in
23107 inline math after \"$22.34\". The LaTeX fragment formatter will only format
23108 fragments that are properly closed, but during editing, we have to live
23109 with the uncertainty caused by missing closing delimiters. This function
23110 looks only before point, not after."
23111 (catch 'exit
23112 (let ((pos (point))
23113 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
23114 (lim (progn
23115 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
23116 (point)))
23117 dd-on str (start 0) m re)
23118 (goto-char pos)
23119 (when dodollar
23120 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
23121 re (nth 1 (assoc "$" org-latex-regexps)))
23122 (while (string-match re str start)
23123 (cond
23124 ((= (match-end 0) (length str))
23125 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
23126 ((= (match-end 0) (- (length str) 5))
23127 (throw 'exit nil))
23128 (t (setq start (match-end 0))))))
23129 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
23130 (goto-char pos)
23131 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
23132 (and (match-beginning 2) (throw 'exit nil))
23133 ;; count $$
23134 (while (re-search-backward "\\$\\$" lim t)
23135 (setq dd-on (not dd-on)))
23136 (goto-char pos)
23137 (if dd-on (cons "$$" m))))))
23140 (defun org-try-cdlatex-tab ()
23141 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
23142 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
23143 - inside a LaTeX fragment, or
23144 - after the first word in a line, where an abbreviation expansion could
23145 insert a LaTeX environment."
23146 (when org-cdlatex-mode
23147 (cond
23148 ((save-excursion
23149 (skip-chars-backward "a-zA-Z0-9*")
23150 (skip-chars-backward " \t")
23151 (bolp))
23152 (cdlatex-tab) t)
23153 ((org-inside-LaTeX-fragment-p)
23154 (cdlatex-tab) t)
23155 (t nil))))
23157 (defun org-cdlatex-underscore-caret (&optional arg)
23158 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
23159 Revert to the normal definition outside of these fragments."
23160 (interactive "P")
23161 (if (org-inside-LaTeX-fragment-p)
23162 (call-interactively 'cdlatex-sub-superscript)
23163 (let (org-cdlatex-mode)
23164 (call-interactively (key-binding (vector last-input-event))))))
23166 (defun org-cdlatex-math-modify (&optional arg)
23167 "Execute `cdlatex-math-modify' in LaTeX fragments.
23168 Revert to the normal definition outside of these fragments."
23169 (interactive "P")
23170 (if (org-inside-LaTeX-fragment-p)
23171 (call-interactively 'cdlatex-math-modify)
23172 (let (org-cdlatex-mode)
23173 (call-interactively (key-binding (vector last-input-event))))))
23175 (defvar org-latex-fragment-image-overlays nil
23176 "List of overlays carrying the images of latex fragments.")
23177 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
23179 (defun org-remove-latex-fragment-image-overlays ()
23180 "Remove all overlays with LaTeX fragment images in current buffer."
23181 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
23182 (setq org-latex-fragment-image-overlays nil))
23184 (defun org-preview-latex-fragment (&optional subtree)
23185 "Preview the LaTeX fragment at point, or all locally or globally.
23186 If the cursor is in a LaTeX fragment, create the image and overlay
23187 it over the source code. If there is no fragment at point, display
23188 all fragments in the current text, from one headline to the next. With
23189 prefix SUBTREE, display all fragments in the current subtree. With a
23190 double prefix `C-u C-u', or when the cursor is before the first headline,
23191 display all fragments in the buffer.
23192 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
23193 (interactive "P")
23194 (org-remove-latex-fragment-image-overlays)
23195 (save-excursion
23196 (save-restriction
23197 (let (beg end at msg)
23198 (cond
23199 ((or (equal subtree '(16))
23200 (not (save-excursion
23201 (re-search-backward (concat "^" outline-regexp) nil t))))
23202 (setq beg (point-min) end (point-max)
23203 msg "Creating images for buffer...%s"))
23204 ((equal subtree '(4))
23205 (org-back-to-heading)
23206 (setq beg (point) end (org-end-of-subtree t)
23207 msg "Creating images for subtree...%s"))
23209 (if (setq at (org-inside-LaTeX-fragment-p))
23210 (goto-char (max (point-min) (- (cdr at) 2)))
23211 (org-back-to-heading))
23212 (setq beg (point) end (progn (outline-next-heading) (point))
23213 msg (if at "Creating image...%s"
23214 "Creating images for entry...%s"))))
23215 (message msg "")
23216 (narrow-to-region beg end)
23217 (goto-char beg)
23218 (org-format-latex
23219 (concat "ltxpng/" (file-name-sans-extension
23220 (file-name-nondirectory
23221 buffer-file-name)))
23222 default-directory 'overlays msg at 'forbuffer)
23223 (message msg "done. Use `C-c C-c' to remove images.")))))
23225 (defvar org-latex-regexps
23226 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
23227 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
23228 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
23229 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
23230 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
23231 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
23232 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
23233 "Regular expressions for matching embedded LaTeX.")
23235 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
23236 "Replace LaTeX fragments with links to an image, and produce images."
23237 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
23238 (let* ((prefixnodir (file-name-nondirectory prefix))
23239 (absprefix (expand-file-name prefix dir))
23240 (todir (file-name-directory absprefix))
23241 (opt org-format-latex-options)
23242 (matchers (plist-get opt :matchers))
23243 (re-list org-latex-regexps)
23244 (cnt 0) txt link beg end re e checkdir
23245 m n block linkfile movefile ov)
23246 ;; Check if there are old images files with this prefix, and remove them
23247 (when (file-directory-p todir)
23248 (mapc 'delete-file
23249 (directory-files
23250 todir 'full
23251 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
23252 ;; Check the different regular expressions
23253 (while (setq e (pop re-list))
23254 (setq m (car e) re (nth 1 e) n (nth 2 e)
23255 block (if (nth 3 e) "\n\n" ""))
23256 (when (member m matchers)
23257 (goto-char (point-min))
23258 (while (re-search-forward re nil t)
23259 (when (or (not at) (equal (cdr at) (match-beginning n)))
23260 (setq txt (match-string n)
23261 beg (match-beginning n) end (match-end n)
23262 cnt (1+ cnt)
23263 linkfile (format "%s_%04d.png" prefix cnt)
23264 movefile (format "%s_%04d.png" absprefix cnt)
23265 link (concat block "[[file:" linkfile "]]" block))
23266 (if msg (message msg cnt))
23267 (goto-char beg)
23268 (unless checkdir ; make sure the directory exists
23269 (setq checkdir t)
23270 (or (file-directory-p todir) (make-directory todir)))
23271 (org-create-formula-image
23272 txt movefile opt forbuffer)
23273 (if overlays
23274 (progn
23275 (setq ov (org-make-overlay beg end))
23276 (if (featurep 'xemacs)
23277 (progn
23278 (org-overlay-put ov 'invisible t)
23279 (org-overlay-put
23280 ov 'end-glyph
23281 (make-glyph (vector 'png :file movefile))))
23282 (org-overlay-put
23283 ov 'display
23284 (list 'image :type 'png :file movefile :ascent 'center)))
23285 (push ov org-latex-fragment-image-overlays)
23286 (goto-char end))
23287 (delete-region beg end)
23288 (insert link))))))))
23290 ;; This function borrows from Ganesh Swami's latex2png.el
23291 (defun org-create-formula-image (string tofile options buffer)
23292 (let* ((tmpdir (if (featurep 'xemacs)
23293 (temp-directory)
23294 temporary-file-directory))
23295 (texfilebase (make-temp-name
23296 (expand-file-name "orgtex" tmpdir)))
23297 (texfile (concat texfilebase ".tex"))
23298 (dvifile (concat texfilebase ".dvi"))
23299 (pngfile (concat texfilebase ".png"))
23300 (fnh (face-attribute 'default :height nil))
23301 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
23302 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
23303 (fg (or (plist-get options (if buffer :foreground :html-foreground))
23304 "Black"))
23305 (bg (or (plist-get options (if buffer :background :html-background))
23306 "Transparent")))
23307 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
23308 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
23309 (with-temp-file texfile
23310 (insert org-format-latex-header
23311 "\n\\begin{document}\n" string "\n\\end{document}\n"))
23312 (let ((dir default-directory))
23313 (condition-case nil
23314 (progn
23315 (cd tmpdir)
23316 (call-process "latex" nil nil nil texfile))
23317 (error nil))
23318 (cd dir))
23319 (if (not (file-exists-p dvifile))
23320 (progn (message "Failed to create dvi file from %s" texfile) nil)
23321 (call-process "dvipng" nil nil nil
23322 "-E" "-fg" fg "-bg" bg
23323 "-D" dpi
23324 ;;"-x" scale "-y" scale
23325 "-T" "tight"
23326 "-o" pngfile
23327 dvifile)
23328 (if (not (file-exists-p pngfile))
23329 (progn (message "Failed to create png file from %s" texfile) nil)
23330 ;; Use the requested file name and clean up
23331 (copy-file pngfile tofile 'replace)
23332 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
23333 (delete-file (concat texfilebase e)))
23334 pngfile))))
23336 (defun org-dvipng-color (attr)
23337 "Return an rgb color specification for dvipng."
23338 (apply 'format "rgb %s %s %s"
23339 (mapcar 'org-normalize-color
23340 (color-values (face-attribute 'default attr nil)))))
23342 (defun org-normalize-color (value)
23343 "Return string to be used as color value for an RGB component."
23344 (format "%g" (/ value 65535.0)))
23346 ;;;; Exporting
23348 ;;; Variables, constants, and parameter plists
23350 (defconst org-level-max 20)
23352 (defvar org-export-html-preamble nil
23353 "Preamble, to be inserted just after <body>. Set by publishing functions.")
23354 (defvar org-export-html-postamble nil
23355 "Preamble, to be inserted just before </body>. Set by publishing functions.")
23356 (defvar org-export-html-auto-preamble t
23357 "Should default preamble be inserted? Set by publishing functions.")
23358 (defvar org-export-html-auto-postamble t
23359 "Should default postamble be inserted? Set by publishing functions.")
23360 (defvar org-current-export-file nil) ; dynamically scoped parameter
23361 (defvar org-current-export-dir nil) ; dynamically scoped parameter
23364 (defconst org-export-plist-vars
23365 '((:language . org-export-default-language)
23366 (:customtime . org-display-custom-times)
23367 (:headline-levels . org-export-headline-levels)
23368 (:section-numbers . org-export-with-section-numbers)
23369 (:table-of-contents . org-export-with-toc)
23370 (:preserve-breaks . org-export-preserve-breaks)
23371 (:archived-trees . org-export-with-archived-trees)
23372 (:emphasize . org-export-with-emphasize)
23373 (:sub-superscript . org-export-with-sub-superscripts)
23374 (:special-strings . org-export-with-special-strings)
23375 (:footnotes . org-export-with-footnotes)
23376 (:drawers . org-export-with-drawers)
23377 (:tags . org-export-with-tags)
23378 (:TeX-macros . org-export-with-TeX-macros)
23379 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
23380 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
23381 (:fixed-width . org-export-with-fixed-width)
23382 (:timestamps . org-export-with-timestamps)
23383 (:author-info . org-export-author-info)
23384 (:time-stamp-file . org-export-time-stamp-file)
23385 (:tables . org-export-with-tables)
23386 (:table-auto-headline . org-export-highlight-first-table-line)
23387 (:style . org-export-html-style)
23388 (:agenda-style . org-agenda-export-html-style)
23389 (:convert-org-links . org-export-html-link-org-files-as-html)
23390 (:inline-images . org-export-html-inline-images)
23391 (:html-extension . org-export-html-extension)
23392 (:html-table-tag . org-export-html-table-tag)
23393 (:expand-quoted-html . org-export-html-expand)
23394 (:timestamp . org-export-html-with-timestamp)
23395 (:publishing-directory . org-export-publishing-directory)
23396 (:preamble . org-export-html-preamble)
23397 (:postamble . org-export-html-postamble)
23398 (:auto-preamble . org-export-html-auto-preamble)
23399 (:auto-postamble . org-export-html-auto-postamble)
23400 (:author . user-full-name)
23401 (:email . user-mail-address)))
23403 (defun org-default-export-plist ()
23404 "Return the property list with default settings for the export variables."
23405 (let ((l org-export-plist-vars) rtn e)
23406 (while (setq e (pop l))
23407 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
23408 rtn))
23410 (defun org-infile-export-plist ()
23411 "Return the property list with file-local settings for export."
23412 (save-excursion
23413 (save-restriction
23414 (widen)
23415 (goto-char 0)
23416 (let ((re (org-make-options-regexp
23417 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
23418 p key val text options)
23419 (while (re-search-forward re nil t)
23420 (setq key (org-match-string-no-properties 1)
23421 val (org-match-string-no-properties 2))
23422 (cond
23423 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
23424 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
23425 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
23426 ((string-equal key "DATE") (setq p (plist-put p :date val)))
23427 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
23428 ((string-equal key "TEXT")
23429 (setq text (if text (concat text "\n" val) val)))
23430 ((string-equal key "OPTIONS") (setq options val))))
23431 (setq p (plist-put p :text text))
23432 (when options
23433 (let ((op '(("H" . :headline-levels)
23434 ("num" . :section-numbers)
23435 ("toc" . :table-of-contents)
23436 ("\\n" . :preserve-breaks)
23437 ("@" . :expand-quoted-html)
23438 (":" . :fixed-width)
23439 ("|" . :tables)
23440 ("^" . :sub-superscript)
23441 ("-" . :special-strings)
23442 ("f" . :footnotes)
23443 ("d" . :drawers)
23444 ("tags" . :tags)
23445 ("*" . :emphasize)
23446 ("TeX" . :TeX-macros)
23447 ("LaTeX" . :LaTeX-fragments)
23448 ("skip" . :skip-before-1st-heading)
23449 ("author" . :author-info)
23450 ("timestamp" . :time-stamp-file)))
23452 (while (setq o (pop op))
23453 (if (string-match (concat (regexp-quote (car o))
23454 ":\\([^ \t\n\r;,.]*\\)")
23455 options)
23456 (setq p (plist-put p (cdr o)
23457 (car (read-from-string
23458 (match-string 1 options)))))))))
23459 p))))
23461 (defun org-export-directory (type plist)
23462 (let* ((val (plist-get plist :publishing-directory))
23463 (dir (if (listp val)
23464 (or (cdr (assoc type val)) ".")
23465 val)))
23466 dir))
23468 (defun org-skip-comments (lines)
23469 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
23470 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
23471 (re2 "^\\(\\*+\\)[ \t\n\r]")
23472 (case-fold-search nil)
23473 rtn line level)
23474 (while (setq line (pop lines))
23475 (cond
23476 ((and (string-match re1 line)
23477 (setq level (- (match-end 1) (match-beginning 1))))
23478 ;; Beginning of a COMMENT subtree. Skip it.
23479 (while (and (setq line (pop lines))
23480 (or (not (string-match re2 line))
23481 (> (- (match-end 1) (match-beginning 1)) level))))
23482 (setq lines (cons line lines)))
23483 ((string-match "^#" line)
23484 ;; an ordinary comment line
23486 ((and org-export-table-remove-special-lines
23487 (string-match "^[ \t]*|" line)
23488 (or (string-match "^[ \t]*| *[!_^] *|" line)
23489 (and (string-match "| *<[0-9]+> *|" line)
23490 (not (string-match "| *[^ <|]" line)))))
23491 ;; a special table line that should be removed
23493 (t (setq rtn (cons line rtn)))))
23494 (nreverse rtn)))
23496 (defun org-export (&optional arg)
23497 (interactive)
23498 (let ((help "[t] insert the export option template
23499 \[v] limit export to visible part of outline tree
23501 \[a] export as ASCII
23503 \[h] export as HTML
23504 \[H] export as HTML to temporary buffer
23505 \[R] export region as HTML
23506 \[b] export as HTML and browse immediately
23507 \[x] export as XOXO
23509 \[l] export as LaTeX
23510 \[L] export as LaTeX to temporary buffer
23512 \[i] export current file as iCalendar file
23513 \[I] export all agenda files as iCalendar files
23514 \[c] export agenda files into combined iCalendar file
23516 \[F] publish current file
23517 \[P] publish current project
23518 \[X] publish... (project will be prompted for)
23519 \[A] publish all projects")
23520 (cmds
23521 '((?t . org-insert-export-options-template)
23522 (?v . org-export-visible)
23523 (?a . org-export-as-ascii)
23524 (?h . org-export-as-html)
23525 (?b . org-export-as-html-and-open)
23526 (?H . org-export-as-html-to-buffer)
23527 (?R . org-export-region-as-html)
23528 (?x . org-export-as-xoxo)
23529 (?l . org-export-as-latex)
23530 (?L . org-export-as-latex-to-buffer)
23531 (?i . org-export-icalendar-this-file)
23532 (?I . org-export-icalendar-all-agenda-files)
23533 (?c . org-export-icalendar-combine-agenda-files)
23534 (?F . org-publish-current-file)
23535 (?P . org-publish-current-project)
23536 (?X . org-publish)
23537 (?A . org-publish-all)))
23538 r1 r2 ass)
23539 (save-window-excursion
23540 (delete-other-windows)
23541 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
23542 (princ help))
23543 (message "Select command: ")
23544 (setq r1 (read-char-exclusive)))
23545 (setq r2 (if (< r1 27) (+ r1 96) r1))
23546 (if (setq ass (assq r2 cmds))
23547 (call-interactively (cdr ass))
23548 (error "No command associated with key %c" r1))))
23550 (defconst org-html-entities
23551 '(("nbsp")
23552 ("iexcl")
23553 ("cent")
23554 ("pound")
23555 ("curren")
23556 ("yen")
23557 ("brvbar")
23558 ("vert" . "&#124;")
23559 ("sect")
23560 ("uml")
23561 ("copy")
23562 ("ordf")
23563 ("laquo")
23564 ("not")
23565 ("shy")
23566 ("reg")
23567 ("macr")
23568 ("deg")
23569 ("plusmn")
23570 ("sup2")
23571 ("sup3")
23572 ("acute")
23573 ("micro")
23574 ("para")
23575 ("middot")
23576 ("odot"."o")
23577 ("star"."*")
23578 ("cedil")
23579 ("sup1")
23580 ("ordm")
23581 ("raquo")
23582 ("frac14")
23583 ("frac12")
23584 ("frac34")
23585 ("iquest")
23586 ("Agrave")
23587 ("Aacute")
23588 ("Acirc")
23589 ("Atilde")
23590 ("Auml")
23591 ("Aring") ("AA"."&Aring;")
23592 ("AElig")
23593 ("Ccedil")
23594 ("Egrave")
23595 ("Eacute")
23596 ("Ecirc")
23597 ("Euml")
23598 ("Igrave")
23599 ("Iacute")
23600 ("Icirc")
23601 ("Iuml")
23602 ("ETH")
23603 ("Ntilde")
23604 ("Ograve")
23605 ("Oacute")
23606 ("Ocirc")
23607 ("Otilde")
23608 ("Ouml")
23609 ("times")
23610 ("Oslash")
23611 ("Ugrave")
23612 ("Uacute")
23613 ("Ucirc")
23614 ("Uuml")
23615 ("Yacute")
23616 ("THORN")
23617 ("szlig")
23618 ("agrave")
23619 ("aacute")
23620 ("acirc")
23621 ("atilde")
23622 ("auml")
23623 ("aring")
23624 ("aelig")
23625 ("ccedil")
23626 ("egrave")
23627 ("eacute")
23628 ("ecirc")
23629 ("euml")
23630 ("igrave")
23631 ("iacute")
23632 ("icirc")
23633 ("iuml")
23634 ("eth")
23635 ("ntilde")
23636 ("ograve")
23637 ("oacute")
23638 ("ocirc")
23639 ("otilde")
23640 ("ouml")
23641 ("divide")
23642 ("oslash")
23643 ("ugrave")
23644 ("uacute")
23645 ("ucirc")
23646 ("uuml")
23647 ("yacute")
23648 ("thorn")
23649 ("yuml")
23650 ("fnof")
23651 ("Alpha")
23652 ("Beta")
23653 ("Gamma")
23654 ("Delta")
23655 ("Epsilon")
23656 ("Zeta")
23657 ("Eta")
23658 ("Theta")
23659 ("Iota")
23660 ("Kappa")
23661 ("Lambda")
23662 ("Mu")
23663 ("Nu")
23664 ("Xi")
23665 ("Omicron")
23666 ("Pi")
23667 ("Rho")
23668 ("Sigma")
23669 ("Tau")
23670 ("Upsilon")
23671 ("Phi")
23672 ("Chi")
23673 ("Psi")
23674 ("Omega")
23675 ("alpha")
23676 ("beta")
23677 ("gamma")
23678 ("delta")
23679 ("epsilon")
23680 ("varepsilon"."&epsilon;")
23681 ("zeta")
23682 ("eta")
23683 ("theta")
23684 ("iota")
23685 ("kappa")
23686 ("lambda")
23687 ("mu")
23688 ("nu")
23689 ("xi")
23690 ("omicron")
23691 ("pi")
23692 ("rho")
23693 ("sigmaf") ("varsigma"."&sigmaf;")
23694 ("sigma")
23695 ("tau")
23696 ("upsilon")
23697 ("phi")
23698 ("chi")
23699 ("psi")
23700 ("omega")
23701 ("thetasym") ("vartheta"."&thetasym;")
23702 ("upsih")
23703 ("piv")
23704 ("bull") ("bullet"."&bull;")
23705 ("hellip") ("dots"."&hellip;")
23706 ("prime")
23707 ("Prime")
23708 ("oline")
23709 ("frasl")
23710 ("weierp")
23711 ("image")
23712 ("real")
23713 ("trade")
23714 ("alefsym")
23715 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
23716 ("uarr") ("uparrow"."&uarr;")
23717 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
23718 ("darr")("downarrow"."&darr;")
23719 ("harr") ("leftrightarrow"."&harr;")
23720 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
23721 ("lArr") ("Leftarrow"."&lArr;")
23722 ("uArr") ("Uparrow"."&uArr;")
23723 ("rArr") ("Rightarrow"."&rArr;")
23724 ("dArr") ("Downarrow"."&dArr;")
23725 ("hArr") ("Leftrightarrow"."&hArr;")
23726 ("forall")
23727 ("part") ("partial"."&part;")
23728 ("exist") ("exists"."&exist;")
23729 ("empty") ("emptyset"."&empty;")
23730 ("nabla")
23731 ("isin") ("in"."&isin;")
23732 ("notin")
23733 ("ni")
23734 ("prod")
23735 ("sum")
23736 ("minus")
23737 ("lowast") ("ast"."&lowast;")
23738 ("radic")
23739 ("prop") ("proptp"."&prop;")
23740 ("infin") ("infty"."&infin;")
23741 ("ang") ("angle"."&ang;")
23742 ("and") ("wedge"."&and;")
23743 ("or") ("vee"."&or;")
23744 ("cap")
23745 ("cup")
23746 ("int")
23747 ("there4")
23748 ("sim")
23749 ("cong") ("simeq"."&cong;")
23750 ("asymp")("approx"."&asymp;")
23751 ("ne") ("neq"."&ne;")
23752 ("equiv")
23753 ("le")
23754 ("ge")
23755 ("sub") ("subset"."&sub;")
23756 ("sup") ("supset"."&sup;")
23757 ("nsub")
23758 ("sube")
23759 ("supe")
23760 ("oplus")
23761 ("otimes")
23762 ("perp")
23763 ("sdot") ("cdot"."&sdot;")
23764 ("lceil")
23765 ("rceil")
23766 ("lfloor")
23767 ("rfloor")
23768 ("lang")
23769 ("rang")
23770 ("loz") ("Diamond"."&loz;")
23771 ("spades") ("spadesuit"."&spades;")
23772 ("clubs") ("clubsuit"."&clubs;")
23773 ("hearts") ("diamondsuit"."&hearts;")
23774 ("diams") ("diamondsuit"."&diams;")
23775 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
23776 ("quot")
23777 ("amp")
23778 ("lt")
23779 ("gt")
23780 ("OElig")
23781 ("oelig")
23782 ("Scaron")
23783 ("scaron")
23784 ("Yuml")
23785 ("circ")
23786 ("tilde")
23787 ("ensp")
23788 ("emsp")
23789 ("thinsp")
23790 ("zwnj")
23791 ("zwj")
23792 ("lrm")
23793 ("rlm")
23794 ("ndash")
23795 ("mdash")
23796 ("lsquo")
23797 ("rsquo")
23798 ("sbquo")
23799 ("ldquo")
23800 ("rdquo")
23801 ("bdquo")
23802 ("dagger")
23803 ("Dagger")
23804 ("permil")
23805 ("lsaquo")
23806 ("rsaquo")
23807 ("euro")
23809 ("arccos"."arccos")
23810 ("arcsin"."arcsin")
23811 ("arctan"."arctan")
23812 ("arg"."arg")
23813 ("cos"."cos")
23814 ("cosh"."cosh")
23815 ("cot"."cot")
23816 ("coth"."coth")
23817 ("csc"."csc")
23818 ("deg"."deg")
23819 ("det"."det")
23820 ("dim"."dim")
23821 ("exp"."exp")
23822 ("gcd"."gcd")
23823 ("hom"."hom")
23824 ("inf"."inf")
23825 ("ker"."ker")
23826 ("lg"."lg")
23827 ("lim"."lim")
23828 ("liminf"."liminf")
23829 ("limsup"."limsup")
23830 ("ln"."ln")
23831 ("log"."log")
23832 ("max"."max")
23833 ("min"."min")
23834 ("Pr"."Pr")
23835 ("sec"."sec")
23836 ("sin"."sin")
23837 ("sinh"."sinh")
23838 ("sup"."sup")
23839 ("tan"."tan")
23840 ("tanh"."tanh")
23842 "Entities for TeX->HTML translation.
23843 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
23844 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
23845 In that case, \"\\ent\" will be translated to \"&other;\".
23846 The list contains HTML entities for Latin-1, Greek and other symbols.
23847 It is supplemented by a number of commonly used TeX macros with appropriate
23848 translations. There is currently no way for users to extend this.")
23850 ;;; General functions for all backends
23852 (defun org-cleaned-string-for-export (string &rest parameters)
23853 "Cleanup a buffer STRING so that links can be created safely."
23854 (interactive)
23855 (let* ((re-radio (and org-target-link-regexp
23856 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
23857 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
23858 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
23859 (re-archive (concat ":" org-archive-tag ":"))
23860 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
23861 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
23862 (htmlp (plist-get parameters :for-html))
23863 (asciip (plist-get parameters :for-ascii))
23864 (latexp (plist-get parameters :for-LaTeX))
23865 (commentsp (plist-get parameters :comments))
23866 (archived-trees (plist-get parameters :archived-trees))
23867 (inhibit-read-only t)
23868 (drawers org-drawers)
23869 (exp-drawers (plist-get parameters :drawers))
23870 (outline-regexp "\\*+ ")
23871 a b xx
23872 rtn p)
23873 (with-current-buffer (get-buffer-create " org-mode-tmp")
23874 (erase-buffer)
23875 (insert string)
23876 ;; Remove license-to-kill stuff
23877 (while (setq p (text-property-any (point-min) (point-max)
23878 :org-license-to-kill t))
23879 (delete-region p (next-single-property-change p :org-license-to-kill)))
23881 (let ((org-inhibit-startup t)) (org-mode))
23882 (untabify (point-min) (point-max))
23884 ;; Get the correct stuff before the first headline
23885 (when (plist-get parameters :skip-before-1st-heading)
23886 (goto-char (point-min))
23887 (when (re-search-forward "^\\*+[ \t]" nil t)
23888 (delete-region (point-min) (match-beginning 0))
23889 (goto-char (point-min))
23890 (insert "\n")))
23891 (when (plist-get parameters :add-text)
23892 (goto-char (point-min))
23893 (insert (plist-get parameters :add-text) "\n"))
23895 ;; Get rid of archived trees
23896 (when (not (eq archived-trees t))
23897 (goto-char (point-min))
23898 (while (re-search-forward re-archive nil t)
23899 (if (not (org-on-heading-p t))
23900 (org-end-of-subtree t)
23901 (beginning-of-line 1)
23902 (setq a (if archived-trees
23903 (1+ (point-at-eol)) (point))
23904 b (org-end-of-subtree t))
23905 (if (> b a) (delete-region a b)))))
23907 ;; Get rid of drawers
23908 (unless (eq t exp-drawers)
23909 (goto-char (point-min))
23910 (let ((re (concat "^[ \t]*:\\("
23911 (mapconcat
23912 'identity
23913 (org-delete-all exp-drawers
23914 (copy-sequence drawers))
23915 "\\|")
23916 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
23917 (while (re-search-forward re nil t)
23918 (replace-match ""))))
23920 ;; Find targets in comments and move them out of comments,
23921 ;; but mark them as targets that should be invisible
23922 (goto-char (point-min))
23923 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
23924 (replace-match "\\1(INVISIBLE)"))
23926 ;; Protect backend specific stuff, throw away the others.
23927 (let ((formatters
23928 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
23929 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
23930 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
23931 fmt)
23932 (goto-char (point-min))
23933 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
23934 (goto-char (match-end 0))
23935 (while (not (looking-at "#\\+END_EXAMPLE"))
23936 (insert ": ")
23937 (beginning-of-line 2)))
23938 (goto-char (point-min))
23939 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
23940 (add-text-properties (match-beginning 0) (match-end 0)
23941 '(org-protected t)))
23942 (while formatters
23943 (setq fmt (pop formatters))
23944 (when (car fmt)
23945 (goto-char (point-min))
23946 (while (re-search-forward (concat "^#\\+" (cadr fmt)
23947 ":[ \t]*\\(.*\\)") nil t)
23948 (replace-match "\\1" t)
23949 (add-text-properties
23950 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
23951 '(org-protected t))))
23952 (goto-char (point-min))
23953 (while (re-search-forward
23954 (concat "^#\\+"
23955 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
23956 (cadddr fmt) "\\>.*\n?") nil t)
23957 (if (car fmt)
23958 (add-text-properties (match-beginning 1) (1+ (match-end 1))
23959 '(org-protected t))
23960 (delete-region (match-beginning 0) (match-end 0))))))
23962 ;; Protect quoted subtrees
23963 (goto-char (point-min))
23964 (while (re-search-forward re-quote nil t)
23965 (goto-char (match-beginning 0))
23966 (end-of-line 1)
23967 (add-text-properties (point) (org-end-of-subtree t)
23968 '(org-protected t)))
23970 ;; Protect verbatim elements
23971 (goto-char (point-min))
23972 (while (re-search-forward org-verbatim-re nil t)
23973 (add-text-properties (match-beginning 4) (match-end 4)
23974 '(org-protected t))
23975 (goto-char (1+ (match-end 4))))
23977 ;; Remove subtrees that are commented
23978 (goto-char (point-min))
23979 (while (re-search-forward re-commented nil t)
23980 (goto-char (match-beginning 0))
23981 (delete-region (point) (org-end-of-subtree t)))
23983 ;; Remove special table lines
23984 (when org-export-table-remove-special-lines
23985 (goto-char (point-min))
23986 (while (re-search-forward "^[ \t]*|" nil t)
23987 (beginning-of-line 1)
23988 (if (or (looking-at "[ \t]*| *[!_^] *|")
23989 (and (looking-at ".*?| *<[0-9]+> *|")
23990 (not (looking-at ".*?| *[^ <|]"))))
23991 (delete-region (max (point-min) (1- (point-at-bol)))
23992 (point-at-eol))
23993 (end-of-line 1))))
23995 ;; Specific LaTeX stuff
23996 (when latexp
23997 (require 'org-export-latex nil)
23998 (org-export-latex-cleaned-string))
24000 (when asciip
24001 (org-export-ascii-clean-string))
24003 ;; Specific HTML stuff
24004 (when htmlp
24005 ;; Convert LaTeX fragments to images
24006 (when (plist-get parameters :LaTeX-fragments)
24007 (org-format-latex
24008 (concat "ltxpng/" (file-name-sans-extension
24009 (file-name-nondirectory
24010 org-current-export-file)))
24011 org-current-export-dir nil "Creating LaTeX image %s"))
24012 (message "Exporting..."))
24014 ;; Remove or replace comments
24015 (goto-char (point-min))
24016 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
24017 (if commentsp
24018 (progn (add-text-properties
24019 (match-beginning 0) (match-end 0) '(org-protected t))
24020 (replace-match (format commentsp (match-string 1)) t t))
24021 (replace-match "")))
24023 ;; Find matches for radio targets and turn them into internal links
24024 (goto-char (point-min))
24025 (when re-radio
24026 (while (re-search-forward re-radio nil t)
24027 (org-if-unprotected
24028 (replace-match "\\1[[\\2]]"))))
24030 ;; Find all links that contain a newline and put them into a single line
24031 (goto-char (point-min))
24032 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
24033 (org-if-unprotected
24034 (replace-match "\\1 \\3")
24035 (goto-char (match-beginning 0))))
24038 ;; Normalize links: Convert angle and plain links into bracket links
24039 ;; Expand link abbreviations
24040 (goto-char (point-min))
24041 (while (re-search-forward re-plain-link nil t)
24042 (goto-char (1- (match-end 0)))
24043 (org-if-unprotected
24044 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24045 ":" (match-string 3) "]]")))
24046 ;; added 'org-link face to links
24047 (put-text-property 0 (length s) 'face 'org-link s)
24048 (replace-match s t t))))
24049 (goto-char (point-min))
24050 (while (re-search-forward re-angle-link nil t)
24051 (goto-char (1- (match-end 0)))
24052 (org-if-unprotected
24053 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24054 ":" (match-string 3) "]]")))
24055 (put-text-property 0 (length s) 'face 'org-link s)
24056 (replace-match s t t))))
24057 (goto-char (point-min))
24058 (while (re-search-forward org-bracket-link-regexp nil t)
24059 (org-if-unprotected
24060 (let* ((s (concat "[[" (setq xx (save-match-data
24061 (org-link-expand-abbrev (match-string 1))))
24063 (if (match-end 3)
24064 (match-string 2)
24065 (concat "[" xx "]"))
24066 "]")))
24067 (put-text-property 0 (length s) 'face 'org-link s)
24068 (replace-match s t t))))
24070 ;; Find multiline emphasis and put them into single line
24071 (when (plist-get parameters :emph-multiline)
24072 (goto-char (point-min))
24073 (while (re-search-forward org-emph-re nil t)
24074 (if (not (= (char-after (match-beginning 3))
24075 (char-after (match-beginning 4))))
24076 (org-if-unprotected
24077 (subst-char-in-region (match-beginning 0) (match-end 0)
24078 ?\n ?\ t)
24079 (goto-char (1- (match-end 0))))
24080 (goto-char (1+ (match-beginning 0))))))
24082 (setq rtn (buffer-string)))
24083 (kill-buffer " org-mode-tmp")
24084 rtn))
24086 (defun org-export-grab-title-from-buffer ()
24087 "Get a title for the current document, from looking at the buffer."
24088 (let ((inhibit-read-only t))
24089 (save-excursion
24090 (goto-char (point-min))
24091 (let ((end (save-excursion (outline-next-heading) (point))))
24092 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
24093 ;; Mark the line so that it will not be exported as normal text.
24094 (org-unmodified
24095 (add-text-properties (match-beginning 0) (match-end 0)
24096 (list :org-license-to-kill t)))
24097 ;; Return the title string
24098 (org-trim (match-string 0)))))))
24100 (defun org-export-get-title-from-subtree ()
24101 "Return subtree title and exclude it from export."
24102 (let (title (m (mark)))
24103 (save-excursion
24104 (goto-char (region-beginning))
24105 (when (and (org-at-heading-p)
24106 (>= (org-end-of-subtree t t) (region-end)))
24107 ;; This is a subtree, we take the title from the first heading
24108 (goto-char (region-beginning))
24109 (looking-at org-todo-line-regexp)
24110 (setq title (match-string 3))
24111 (org-unmodified
24112 (add-text-properties (point) (1+ (point-at-eol))
24113 (list :org-license-to-kill t)))))
24114 title))
24116 (defun org-solidify-link-text (s &optional alist)
24117 "Take link text and make a safe target out of it."
24118 (save-match-data
24119 (let* ((rtn
24120 (mapconcat
24121 'identity
24122 (org-split-string s "[ \t\r\n]+") "--"))
24123 (a (assoc rtn alist)))
24124 (or (cdr a) rtn))))
24126 (defun org-get-min-level (lines)
24127 "Get the minimum level in LINES."
24128 (let ((re "^\\(\\*+\\) ") l min)
24129 (catch 'exit
24130 (while (setq l (pop lines))
24131 (if (string-match re l)
24132 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24133 1)))
24135 ;; Variable holding the vector with section numbers
24136 (defvar org-section-numbers (make-vector org-level-max 0))
24138 (defun org-init-section-numbers ()
24139 "Initialize the vector for the section numbers."
24140 (let* ((level -1)
24141 (numbers (nreverse (org-split-string "" "\\.")))
24142 (depth (1- (length org-section-numbers)))
24143 (i depth) number-string)
24144 (while (>= i 0)
24145 (if (> i level)
24146 (aset org-section-numbers i 0)
24147 (setq number-string (or (car numbers) "0"))
24148 (if (string-match "\\`[A-Z]\\'" number-string)
24149 (aset org-section-numbers i
24150 (- (string-to-char number-string) ?A -1))
24151 (aset org-section-numbers i (string-to-number number-string)))
24152 (pop numbers))
24153 (setq i (1- i)))))
24155 (defun org-section-number (&optional level)
24156 "Return a string with the current section number.
24157 When LEVEL is non-nil, increase section numbers on that level."
24158 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
24159 (when level
24160 (when (> level -1)
24161 (aset org-section-numbers
24162 level (1+ (aref org-section-numbers level))))
24163 (setq idx (1+ level))
24164 (while (<= idx depth)
24165 (if (not (= idx 1))
24166 (aset org-section-numbers idx 0))
24167 (setq idx (1+ idx))))
24168 (setq idx 0)
24169 (while (<= idx depth)
24170 (setq n (aref org-section-numbers idx))
24171 (setq string (concat string (if (not (string= string "")) "." "")
24172 (int-to-string n)))
24173 (setq idx (1+ idx)))
24174 (save-match-data
24175 (if (string-match "\\`\\([@0]\\.\\)+" string)
24176 (setq string (replace-match "" t nil string)))
24177 (if (string-match "\\(\\.0\\)+\\'" string)
24178 (setq string (replace-match "" t nil string))))
24179 string))
24181 ;;; ASCII export
24183 (defvar org-last-level nil) ; dynamically scoped variable
24184 (defvar org-min-level nil) ; dynamically scoped variable
24185 (defvar org-levels-open nil) ; dynamically scoped parameter
24186 (defvar org-ascii-current-indentation nil) ; For communication
24188 (defun org-export-as-ascii (arg)
24189 "Export the outline as a pretty ASCII file.
24190 If there is an active region, export only the region.
24191 The prefix ARG specifies how many levels of the outline should become
24192 underlined headlines. The default is 3."
24193 (interactive "P")
24194 (setq-default org-todo-line-regexp org-todo-line-regexp)
24195 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24196 (org-infile-export-plist)))
24197 (region-p (org-region-active-p))
24198 (subtree-p
24199 (when region-p
24200 (save-excursion
24201 (goto-char (region-beginning))
24202 (and (org-at-heading-p)
24203 (>= (org-end-of-subtree t t) (region-end))))))
24204 (custom-times org-display-custom-times)
24205 (org-ascii-current-indentation '(0 . 0))
24206 (level 0) line txt
24207 (umax nil)
24208 (umax-toc nil)
24209 (case-fold-search nil)
24210 (filename (concat (file-name-as-directory
24211 (org-export-directory :ascii opt-plist))
24212 (file-name-sans-extension
24213 (or (and subtree-p
24214 (org-entry-get (region-beginning)
24215 "EXPORT_FILE_NAME" t))
24216 (file-name-nondirectory buffer-file-name)))
24217 ".txt"))
24218 (filename (if (equal (file-truename filename)
24219 (file-truename buffer-file-name))
24220 (concat filename ".txt")
24221 filename))
24222 (buffer (find-file-noselect filename))
24223 (org-levels-open (make-vector org-level-max nil))
24224 (odd org-odd-levels-only)
24225 (date (plist-get opt-plist :date))
24226 (author (plist-get opt-plist :author))
24227 (title (or (and subtree-p (org-export-get-title-from-subtree))
24228 (plist-get opt-plist :title)
24229 (and (not
24230 (plist-get opt-plist :skip-before-1st-heading))
24231 (org-export-grab-title-from-buffer))
24232 (file-name-sans-extension
24233 (file-name-nondirectory buffer-file-name))))
24234 (email (plist-get opt-plist :email))
24235 (language (plist-get opt-plist :language))
24236 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24237 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
24238 (todo nil)
24239 (lang-words nil)
24240 (region
24241 (buffer-substring
24242 (if (org-region-active-p) (region-beginning) (point-min))
24243 (if (org-region-active-p) (region-end) (point-max))))
24244 (lines (org-split-string
24245 (org-cleaned-string-for-export
24246 region
24247 :for-ascii t
24248 :skip-before-1st-heading
24249 (plist-get opt-plist :skip-before-1st-heading)
24250 :drawers (plist-get opt-plist :drawers)
24251 :verbatim-multiline t
24252 :archived-trees
24253 (plist-get opt-plist :archived-trees)
24254 :add-text (plist-get opt-plist :text))
24255 "\n"))
24256 thetoc have-headings first-heading-pos
24257 table-open table-buffer)
24259 (let ((inhibit-read-only t))
24260 (org-unmodified
24261 (remove-text-properties (point-min) (point-max)
24262 '(:org-license-to-kill t))))
24264 (setq org-min-level (org-get-min-level lines))
24265 (setq org-last-level org-min-level)
24266 (org-init-section-numbers)
24268 (find-file-noselect filename)
24270 (setq lang-words (or (assoc language org-export-language-setup)
24271 (assoc "en" org-export-language-setup)))
24272 (switch-to-buffer-other-window buffer)
24273 (erase-buffer)
24274 (fundamental-mode)
24275 ;; create local variables for all options, to make sure all called
24276 ;; functions get the correct information
24277 (mapc (lambda (x)
24278 (set (make-local-variable (cdr x))
24279 (plist-get opt-plist (car x))))
24280 org-export-plist-vars)
24281 (org-set-local 'org-odd-levels-only odd)
24282 (setq umax (if arg (prefix-numeric-value arg)
24283 org-export-headline-levels))
24284 (setq umax-toc (if (integerp org-export-with-toc)
24285 (min org-export-with-toc umax)
24286 umax))
24288 ;; File header
24289 (if title (org-insert-centered title ?=))
24290 (insert "\n")
24291 (if (and (or author email)
24292 org-export-author-info)
24293 (insert (concat (nth 1 lang-words) ": " (or author "")
24294 (if email (concat " <" email ">") "")
24295 "\n")))
24297 (cond
24298 ((and date (string-match "%" date))
24299 (setq date (format-time-string date (current-time))))
24300 (date)
24301 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24303 (if (and date org-export-time-stamp-file)
24304 (insert (concat (nth 2 lang-words) ": " date"\n")))
24306 (insert "\n\n")
24308 (if org-export-with-toc
24309 (progn
24310 (push (concat (nth 3 lang-words) "\n") thetoc)
24311 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
24312 (mapc '(lambda (line)
24313 (if (string-match org-todo-line-regexp
24314 line)
24315 ;; This is a headline
24316 (progn
24317 (setq have-headings t)
24318 (setq level (- (match-end 1) (match-beginning 1))
24319 level (org-tr-level level)
24320 txt (match-string 3 line)
24321 todo
24322 (or (and org-export-mark-todo-in-toc
24323 (match-beginning 2)
24324 (not (member (match-string 2 line)
24325 org-done-keywords)))
24326 ; TODO, not DONE
24327 (and org-export-mark-todo-in-toc
24328 (= level umax-toc)
24329 (org-search-todo-below
24330 line lines level))))
24331 (setq txt (org-html-expand-for-ascii txt))
24333 (while (string-match org-bracket-link-regexp txt)
24334 (setq txt
24335 (replace-match
24336 (match-string (if (match-end 2) 3 1) txt)
24337 t t txt)))
24339 (if (and (memq org-export-with-tags '(not-in-toc nil))
24340 (string-match
24341 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
24342 txt))
24343 (setq txt (replace-match "" t t txt)))
24344 (if (string-match quote-re0 txt)
24345 (setq txt (replace-match "" t t txt)))
24347 (if org-export-with-section-numbers
24348 (setq txt (concat (org-section-number level)
24349 " " txt)))
24350 (if (<= level umax-toc)
24351 (progn
24352 (push
24353 (concat
24354 (make-string
24355 (* (max 0 (- level org-min-level)) 4) ?\ )
24356 (format (if todo "%s (*)\n" "%s\n") txt))
24357 thetoc)
24358 (setq org-last-level level))
24359 ))))
24360 lines)
24361 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24363 (org-init-section-numbers)
24364 (while (setq line (pop lines))
24365 ;; Remove the quoted HTML tags.
24366 (setq line (org-html-expand-for-ascii line))
24367 ;; Remove targets
24368 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
24369 (setq line (replace-match "" t t line)))
24370 ;; Replace internal links
24371 (while (string-match org-bracket-link-regexp line)
24372 (setq line (replace-match
24373 (if (match-end 3) "[\\3]" "[\\1]")
24374 t nil line)))
24375 (when custom-times
24376 (setq line (org-translate-time line)))
24377 (cond
24378 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24379 ;; a Headline
24380 (setq first-heading-pos (or first-heading-pos (point)))
24381 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24382 txt (match-string 2 line))
24383 (org-ascii-level-start level txt umax lines))
24385 ((and org-export-with-tables
24386 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24387 (if (not table-open)
24388 ;; New table starts
24389 (setq table-open t table-buffer nil))
24390 ;; Accumulate lines
24391 (setq table-buffer (cons line table-buffer))
24392 (when (or (not lines)
24393 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24394 (car lines))))
24395 (setq table-open nil
24396 table-buffer (nreverse table-buffer))
24397 (insert (mapconcat
24398 (lambda (x)
24399 (org-fix-indentation x org-ascii-current-indentation))
24400 (org-format-table-ascii table-buffer)
24401 "\n") "\n")))
24403 (setq line (org-fix-indentation line org-ascii-current-indentation))
24404 (if (and org-export-with-fixed-width
24405 (string-match "^\\([ \t]*\\)\\(:\\)" line))
24406 (setq line (replace-match "\\1" nil nil line)))
24407 (insert line "\n"))))
24409 (normal-mode)
24411 ;; insert the table of contents
24412 (when thetoc
24413 (goto-char (point-min))
24414 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
24415 (progn
24416 (goto-char (match-beginning 0))
24417 (replace-match ""))
24418 (goto-char first-heading-pos))
24419 (mapc 'insert thetoc)
24420 (or (looking-at "[ \t]*\n[ \t]*\n")
24421 (insert "\n\n")))
24423 ;; Convert whitespace place holders
24424 (goto-char (point-min))
24425 (let (beg end)
24426 (while (setq beg (next-single-property-change (point) 'org-whitespace))
24427 (setq end (next-single-property-change beg 'org-whitespace))
24428 (goto-char beg)
24429 (delete-region beg end)
24430 (insert (make-string (- end beg) ?\ ))))
24432 (save-buffer)
24433 ;; remove display and invisible chars
24434 (let (beg end)
24435 (goto-char (point-min))
24436 (while (setq beg (next-single-property-change (point) 'display))
24437 (setq end (next-single-property-change beg 'display))
24438 (delete-region beg end)
24439 (goto-char beg)
24440 (insert "=>"))
24441 (goto-char (point-min))
24442 (while (setq beg (next-single-property-change (point) 'org-cwidth))
24443 (setq end (next-single-property-change beg 'org-cwidth))
24444 (delete-region beg end)
24445 (goto-char beg)))
24446 (goto-char (point-min))))
24448 (defun org-export-ascii-clean-string ()
24449 "Do extra work for ASCII export"
24450 (goto-char (point-min))
24451 (while (re-search-forward org-verbatim-re nil t)
24452 (goto-char (match-end 2))
24453 (backward-delete-char 1) (insert "'")
24454 (goto-char (match-beginning 2))
24455 (delete-char 1) (insert "`")
24456 (goto-char (match-end 2))))
24458 (defun org-search-todo-below (line lines level)
24459 "Search the subtree below LINE for any TODO entries."
24460 (let ((rest (cdr (memq line lines)))
24461 (re org-todo-line-regexp)
24462 line lv todo)
24463 (catch 'exit
24464 (while (setq line (pop rest))
24465 (if (string-match re line)
24466 (progn
24467 (setq lv (- (match-end 1) (match-beginning 1))
24468 todo (and (match-beginning 2)
24469 (not (member (match-string 2 line)
24470 org-done-keywords))))
24471 ; TODO, not DONE
24472 (if (<= lv level) (throw 'exit nil))
24473 (if todo (throw 'exit t))))))))
24475 (defun org-html-expand-for-ascii (line)
24476 "Handle quoted HTML for ASCII export."
24477 (if org-export-html-expand
24478 (while (string-match "@<[^<>\n]*>" line)
24479 ;; We just remove the tags for now.
24480 (setq line (replace-match "" nil nil line))))
24481 line)
24483 (defun org-insert-centered (s &optional underline)
24484 "Insert the string S centered and underline it with character UNDERLINE."
24485 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
24486 (insert (make-string ind ?\ ) s "\n")
24487 (if underline
24488 (insert (make-string ind ?\ )
24489 (make-string (string-width s) underline)
24490 "\n"))))
24492 (defun org-ascii-level-start (level title umax &optional lines)
24493 "Insert a new level in ASCII export."
24494 (let (char (n (- level umax 1)) (ind 0))
24495 (if (> level umax)
24496 (progn
24497 (insert (make-string (* 2 n) ?\ )
24498 (char-to-string (nth (% n (length org-export-ascii-bullets))
24499 org-export-ascii-bullets))
24500 " " title "\n")
24501 ;; find the indentation of the next non-empty line
24502 (catch 'stop
24503 (while lines
24504 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
24505 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
24506 (throw 'stop (setq ind (org-get-indentation (car lines)))))
24507 (pop lines)))
24508 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
24509 (if (or (not (equal (char-before) ?\n))
24510 (not (equal (char-before (1- (point))) ?\n)))
24511 (insert "\n"))
24512 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
24513 (unless org-export-with-tags
24514 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
24515 (setq title (replace-match "" t t title))))
24516 (if org-export-with-section-numbers
24517 (setq title (concat (org-section-number level) " " title)))
24518 (insert title "\n" (make-string (string-width title) char) "\n")
24519 (setq org-ascii-current-indentation '(0 . 0)))))
24521 (defun org-export-visible (type arg)
24522 "Create a copy of the visible part of the current buffer, and export it.
24523 The copy is created in a temporary buffer and removed after use.
24524 TYPE is the final key (as a string) that also select the export command in
24525 the `C-c C-e' export dispatcher.
24526 As a special case, if the you type SPC at the prompt, the temporary
24527 org-mode file will not be removed but presented to you so that you can
24528 continue to use it. The prefix arg ARG is passed through to the exporting
24529 command."
24530 (interactive
24531 (list (progn
24532 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
24533 (read-char-exclusive))
24534 current-prefix-arg))
24535 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
24536 (error "Invalid export key"))
24537 (let* ((binding (cdr (assoc type
24538 '((?a . org-export-as-ascii)
24539 (?\C-a . org-export-as-ascii)
24540 (?b . org-export-as-html-and-open)
24541 (?\C-b . org-export-as-html-and-open)
24542 (?h . org-export-as-html)
24543 (?H . org-export-as-html-to-buffer)
24544 (?R . org-export-region-as-html)
24545 (?x . org-export-as-xoxo)))))
24546 (keepp (equal type ?\ ))
24547 (file buffer-file-name)
24548 (buffer (get-buffer-create "*Org Export Visible*"))
24549 s e)
24550 ;; Need to hack the drawers here.
24551 (save-excursion
24552 (goto-char (point-min))
24553 (while (re-search-forward org-drawer-regexp nil t)
24554 (goto-char (match-beginning 1))
24555 (or (org-invisible-p) (org-flag-drawer nil))))
24556 (with-current-buffer buffer (erase-buffer))
24557 (save-excursion
24558 (setq s (goto-char (point-min)))
24559 (while (not (= (point) (point-max)))
24560 (goto-char (org-find-invisible))
24561 (append-to-buffer buffer s (point))
24562 (setq s (goto-char (org-find-visible))))
24563 (org-cycle-hide-drawers 'all)
24564 (goto-char (point-min))
24565 (unless keepp
24566 ;; Copy all comment lines to the end, to make sure #+ settings are
24567 ;; still available for the second export step. Kind of a hack, but
24568 ;; does do the trick.
24569 (if (looking-at "#[^\r\n]*")
24570 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
24571 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
24572 (append-to-buffer buffer (1+ (match-beginning 0))
24573 (min (point-max) (1+ (match-end 0))))))
24574 (set-buffer buffer)
24575 (let ((buffer-file-name file)
24576 (org-inhibit-startup t))
24577 (org-mode)
24578 (show-all)
24579 (unless keepp (funcall binding arg))))
24580 (if (not keepp)
24581 (kill-buffer buffer)
24582 (switch-to-buffer-other-window buffer)
24583 (goto-char (point-min)))))
24585 (defun org-find-visible ()
24586 (let ((s (point)))
24587 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24588 (get-char-property s 'invisible)))
24590 (defun org-find-invisible ()
24591 (let ((s (point)))
24592 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24593 (not (get-char-property s 'invisible))))
24596 ;;; HTML export
24598 (defun org-get-current-options ()
24599 "Return a string with current options as keyword options.
24600 Does include HTML export options as well as TODO and CATEGORY stuff."
24601 (format
24602 "#+TITLE: %s
24603 #+AUTHOR: %s
24604 #+EMAIL: %s
24605 #+LANGUAGE: %s
24606 #+TEXT: Some descriptive text to be emitted. Several lines OK.
24607 #+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
24608 #+CATEGORY: %s
24609 #+SEQ_TODO: %s
24610 #+TYP_TODO: %s
24611 #+PRIORITIES: %c %c %c
24612 #+DRAWERS: %s
24613 #+STARTUP: %s %s %s %s %s
24614 #+TAGS: %s
24615 #+ARCHIVE: %s
24616 #+LINK: %s
24618 (buffer-name) (user-full-name) user-mail-address org-export-default-language
24619 org-export-headline-levels
24620 org-export-with-section-numbers
24621 org-export-with-toc
24622 org-export-preserve-breaks
24623 org-export-html-expand
24624 org-export-with-fixed-width
24625 org-export-with-tables
24626 org-export-with-sub-superscripts
24627 org-export-with-special-strings
24628 org-export-with-footnotes
24629 org-export-with-emphasize
24630 org-export-with-TeX-macros
24631 org-export-with-LaTeX-fragments
24632 org-export-skip-text-before-1st-heading
24633 org-export-with-drawers
24634 org-export-with-tags
24635 (file-name-nondirectory buffer-file-name)
24636 "TODO FEEDBACK VERIFY DONE"
24637 "Me Jason Marie DONE"
24638 org-highest-priority org-lowest-priority org-default-priority
24639 (mapconcat 'identity org-drawers " ")
24640 (cdr (assoc org-startup-folded
24641 '((nil . "showall") (t . "overview") (content . "content"))))
24642 (if org-odd-levels-only "odd" "oddeven")
24643 (if org-hide-leading-stars "hidestars" "showstars")
24644 (if org-startup-align-all-tables "align" "noalign")
24645 (cond ((eq t org-log-done) "logdone")
24646 ((not org-log-done) "nologging")
24647 ((listp org-log-done)
24648 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
24649 org-log-done " ")))
24650 (or (mapconcat (lambda (x)
24651 (cond
24652 ((equal '(:startgroup) x) "{")
24653 ((equal '(:endgroup) x) "}")
24654 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
24655 (t (car x))))
24656 (or org-tag-alist (org-get-buffer-tags)) " ") "")
24657 org-archive-location
24658 "org file:~/org/%s.org"
24661 (defun org-insert-export-options-template ()
24662 "Insert into the buffer a template with information for exporting."
24663 (interactive)
24664 (if (not (bolp)) (newline))
24665 (let ((s (org-get-current-options)))
24666 (and (string-match "#\\+CATEGORY" s)
24667 (setq s (substring s 0 (match-beginning 0))))
24668 (insert s)))
24670 (defun org-toggle-fixed-width-section (arg)
24671 "Toggle the fixed-width export.
24672 If there is no active region, the QUOTE keyword at the current headline is
24673 inserted or removed. When present, it causes the text between this headline
24674 and the next to be exported as fixed-width text, and unmodified.
24675 If there is an active region, this command adds or removes a colon as the
24676 first character of this line. If the first character of a line is a colon,
24677 this line is also exported in fixed-width font."
24678 (interactive "P")
24679 (let* ((cc 0)
24680 (regionp (org-region-active-p))
24681 (beg (if regionp (region-beginning) (point)))
24682 (end (if regionp (region-end)))
24683 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
24684 (case-fold-search nil)
24685 (re "[ \t]*\\(:\\)")
24686 off)
24687 (if regionp
24688 (save-excursion
24689 (goto-char beg)
24690 (setq cc (current-column))
24691 (beginning-of-line 1)
24692 (setq off (looking-at re))
24693 (while (> nlines 0)
24694 (setq nlines (1- nlines))
24695 (beginning-of-line 1)
24696 (cond
24697 (arg
24698 (move-to-column cc t)
24699 (insert ":\n")
24700 (forward-line -1))
24701 ((and off (looking-at re))
24702 (replace-match "" t t nil 1))
24703 ((not off) (move-to-column cc t) (insert ":")))
24704 (forward-line 1)))
24705 (save-excursion
24706 (org-back-to-heading)
24707 (if (looking-at (concat outline-regexp
24708 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
24709 (replace-match "" t t nil 1)
24710 (if (looking-at outline-regexp)
24711 (progn
24712 (goto-char (match-end 0))
24713 (insert org-quote-string " "))))))))
24715 (defun org-export-as-html-and-open (arg)
24716 "Export the outline as HTML and immediately open it with a browser.
24717 If there is an active region, export only the region.
24718 The prefix ARG specifies how many levels of the outline should become
24719 headlines. The default is 3. Lower levels will become bulleted lists."
24720 (interactive "P")
24721 (org-export-as-html arg 'hidden)
24722 (org-open-file buffer-file-name))
24724 (defun org-export-as-html-batch ()
24725 "Call `org-export-as-html', may be used in batch processing as
24726 emacs --batch
24727 --load=$HOME/lib/emacs/org.el
24728 --eval \"(setq org-export-headline-levels 2)\"
24729 --visit=MyFile --funcall org-export-as-html-batch"
24730 (org-export-as-html org-export-headline-levels 'hidden))
24732 (defun org-export-as-html-to-buffer (arg)
24733 "Call `org-exort-as-html` with output to a temporary buffer.
24734 No file is created. The prefix ARG is passed through to `org-export-as-html'."
24735 (interactive "P")
24736 (org-export-as-html arg nil nil "*Org HTML Export*")
24737 (switch-to-buffer-other-window "*Org HTML Export*"))
24739 (defun org-replace-region-by-html (beg end)
24740 "Assume the current region has org-mode syntax, and convert it to HTML.
24741 This can be used in any buffer. For example, you could write an
24742 itemized list in org-mode syntax in an HTML buffer and then use this
24743 command to convert it."
24744 (interactive "r")
24745 (let (reg html buf pop-up-frames)
24746 (save-window-excursion
24747 (if (org-mode-p)
24748 (setq html (org-export-region-as-html
24749 beg end t 'string))
24750 (setq reg (buffer-substring beg end)
24751 buf (get-buffer-create "*Org tmp*"))
24752 (with-current-buffer buf
24753 (erase-buffer)
24754 (insert reg)
24755 (org-mode)
24756 (setq html (org-export-region-as-html
24757 (point-min) (point-max) t 'string)))
24758 (kill-buffer buf)))
24759 (delete-region beg end)
24760 (insert html)))
24762 (defun org-export-region-as-html (beg end &optional body-only buffer)
24763 "Convert region from BEG to END in org-mode buffer to HTML.
24764 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
24765 contents, and only produce the region of converted text, useful for
24766 cut-and-paste operations.
24767 If BUFFER is a buffer or a string, use/create that buffer as a target
24768 of the converted HTML. If BUFFER is the symbol `string', return the
24769 produced HTML as a string and leave not buffer behind. For example,
24770 a Lisp program could call this function in the following way:
24772 (setq html (org-export-region-as-html beg end t 'string))
24774 When called interactively, the output buffer is selected, and shown
24775 in a window. A non-interactive call will only retunr the buffer."
24776 (interactive "r\nP")
24777 (when (interactive-p)
24778 (setq buffer "*Org HTML Export*"))
24779 (let ((transient-mark-mode t) (zmacs-regions t)
24780 rtn)
24781 (goto-char end)
24782 (set-mark (point)) ;; to activate the region
24783 (goto-char beg)
24784 (setq rtn (org-export-as-html
24785 nil nil nil
24786 buffer body-only))
24787 (if (fboundp 'deactivate-mark) (deactivate-mark))
24788 (if (and (interactive-p) (bufferp rtn))
24789 (switch-to-buffer-other-window rtn)
24790 rtn)))
24792 (defvar html-table-tag nil) ; dynamically scoped into this.
24793 (defun org-export-as-html (arg &optional hidden ext-plist
24794 to-buffer body-only)
24795 "Export the outline as a pretty HTML file.
24796 If there is an active region, export only the region. The prefix
24797 ARG specifies how many levels of the outline should become
24798 headlines. The default is 3. Lower levels will become bulleted
24799 lists. When HIDDEN is non-nil, don't display the HTML buffer.
24800 EXT-PLIST is a property list with external parameters overriding
24801 org-mode's default settings, but still inferior to file-local
24802 settings. When TO-BUFFER is non-nil, create a buffer with that
24803 name and export to that buffer. If TO-BUFFER is the symbol `string',
24804 don't leave any buffer behind but just return the resulting HTML as
24805 a string. When BODY-ONLY is set, don't produce the file header and footer,
24806 simply return the content of <body>...</body>, without even
24807 the body tags themselves."
24808 (interactive "P")
24810 ;; Make sure we have a file name when we need it.
24811 (when (and (not (or to-buffer body-only))
24812 (not buffer-file-name))
24813 (if (buffer-base-buffer)
24814 (org-set-local 'buffer-file-name
24815 (with-current-buffer (buffer-base-buffer)
24816 buffer-file-name))
24817 (error "Need a file name to be able to export.")))
24819 (message "Exporting...")
24820 (setq-default org-todo-line-regexp org-todo-line-regexp)
24821 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
24822 (setq-default org-done-keywords org-done-keywords)
24823 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
24824 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24825 ext-plist
24826 (org-infile-export-plist)))
24828 (style (plist-get opt-plist :style))
24829 (link-validate (plist-get opt-plist :link-validation-function))
24830 valid thetoc have-headings first-heading-pos
24831 (odd org-odd-levels-only)
24832 (region-p (org-region-active-p))
24833 (subtree-p
24834 (when region-p
24835 (save-excursion
24836 (goto-char (region-beginning))
24837 (and (org-at-heading-p)
24838 (>= (org-end-of-subtree t t) (region-end))))))
24839 ;; The following two are dynamically scoped into other
24840 ;; routines below.
24841 (org-current-export-dir (org-export-directory :html opt-plist))
24842 (org-current-export-file buffer-file-name)
24843 (level 0) (line "") (origline "") txt todo
24844 (umax nil)
24845 (umax-toc nil)
24846 (filename (if to-buffer nil
24847 (expand-file-name
24848 (concat
24849 (file-name-sans-extension
24850 (or (and subtree-p
24851 (org-entry-get (region-beginning)
24852 "EXPORT_FILE_NAME" t))
24853 (file-name-nondirectory buffer-file-name)))
24854 "." org-export-html-extension)
24855 (file-name-as-directory
24856 (org-export-directory :html opt-plist)))))
24857 (current-dir (if buffer-file-name
24858 (file-name-directory buffer-file-name)
24859 default-directory))
24860 (buffer (if to-buffer
24861 (cond
24862 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
24863 (t (get-buffer-create to-buffer)))
24864 (find-file-noselect filename)))
24865 (org-levels-open (make-vector org-level-max nil))
24866 (date (plist-get opt-plist :date))
24867 (author (plist-get opt-plist :author))
24868 (title (or (and subtree-p (org-export-get-title-from-subtree))
24869 (plist-get opt-plist :title)
24870 (and (not
24871 (plist-get opt-plist :skip-before-1st-heading))
24872 (org-export-grab-title-from-buffer))
24873 (and buffer-file-name
24874 (file-name-sans-extension
24875 (file-name-nondirectory buffer-file-name)))
24876 "UNTITLED"))
24877 (html-table-tag (plist-get opt-plist :html-table-tag))
24878 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24879 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
24880 (inquote nil)
24881 (infixed nil)
24882 (in-local-list nil)
24883 (local-list-num nil)
24884 (local-list-indent nil)
24885 (llt org-plain-list-ordered-item-terminator)
24886 (email (plist-get opt-plist :email))
24887 (language (plist-get opt-plist :language))
24888 (lang-words nil)
24889 (target-alist nil) tg
24890 (head-count 0) cnt
24891 (start 0)
24892 (coding-system (and (boundp 'buffer-file-coding-system)
24893 buffer-file-coding-system))
24894 (coding-system-for-write (or org-export-html-coding-system
24895 coding-system))
24896 (save-buffer-coding-system (or org-export-html-coding-system
24897 coding-system))
24898 (charset (and coding-system-for-write
24899 (fboundp 'coding-system-get)
24900 (coding-system-get coding-system-for-write
24901 'mime-charset)))
24902 (region
24903 (buffer-substring
24904 (if region-p (region-beginning) (point-min))
24905 (if region-p (region-end) (point-max))))
24906 (lines
24907 (org-split-string
24908 (org-cleaned-string-for-export
24909 region
24910 :emph-multiline t
24911 :for-html t
24912 :skip-before-1st-heading
24913 (plist-get opt-plist :skip-before-1st-heading)
24914 :drawers (plist-get opt-plist :drawers)
24915 :archived-trees
24916 (plist-get opt-plist :archived-trees)
24917 :add-text
24918 (plist-get opt-plist :text)
24919 :LaTeX-fragments
24920 (plist-get opt-plist :LaTeX-fragments))
24921 "[\r\n]"))
24922 table-open type
24923 table-buffer table-orig-buffer
24924 ind start-is-num starter didclose
24925 rpl path desc descp desc1 desc2 link
24928 (let ((inhibit-read-only t))
24929 (org-unmodified
24930 (remove-text-properties (point-min) (point-max)
24931 '(:org-license-to-kill t))))
24933 (message "Exporting...")
24935 (setq org-min-level (org-get-min-level lines))
24936 (setq org-last-level org-min-level)
24937 (org-init-section-numbers)
24939 (cond
24940 ((and date (string-match "%" date))
24941 (setq date (format-time-string date (current-time))))
24942 (date)
24943 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24945 ;; Get the language-dependent settings
24946 (setq lang-words (or (assoc language org-export-language-setup)
24947 (assoc "en" org-export-language-setup)))
24949 ;; Switch to the output buffer
24950 (set-buffer buffer)
24951 (let ((inhibit-read-only t)) (erase-buffer))
24952 (fundamental-mode)
24954 (and (fboundp 'set-buffer-file-coding-system)
24955 (set-buffer-file-coding-system coding-system-for-write))
24957 (let ((case-fold-search nil)
24958 (org-odd-levels-only odd))
24959 ;; create local variables for all options, to make sure all called
24960 ;; functions get the correct information
24961 (mapc (lambda (x)
24962 (set (make-local-variable (cdr x))
24963 (plist-get opt-plist (car x))))
24964 org-export-plist-vars)
24965 (setq umax (if arg (prefix-numeric-value arg)
24966 org-export-headline-levels))
24967 (setq umax-toc (if (integerp org-export-with-toc)
24968 (min org-export-with-toc umax)
24969 umax))
24970 (unless body-only
24971 ;; File header
24972 (insert (format
24973 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
24974 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
24975 <html xmlns=\"http://www.w3.org/1999/xhtml\"
24976 lang=\"%s\" xml:lang=\"%s\">
24977 <head>
24978 <title>%s</title>
24979 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
24980 <meta name=\"generator\" content=\"Org-mode\"/>
24981 <meta name=\"generated\" content=\"%s\"/>
24982 <meta name=\"author\" content=\"%s\"/>
24984 </head><body>
24986 language language (org-html-expand title)
24987 (or charset "iso-8859-1") date author style))
24989 (insert (or (plist-get opt-plist :preamble) ""))
24991 (when (plist-get opt-plist :auto-preamble)
24992 (if title (insert (format org-export-html-title-format
24993 (org-html-expand title))))))
24995 (if (and org-export-with-toc (not body-only))
24996 (progn
24997 (push (format "<h%d>%s</h%d>\n"
24998 org-export-html-toplevel-hlevel
24999 (nth 3 lang-words)
25000 org-export-html-toplevel-hlevel)
25001 thetoc)
25002 (push "<ul>\n<li>" thetoc)
25003 (setq lines
25004 (mapcar '(lambda (line)
25005 (if (string-match org-todo-line-regexp line)
25006 ;; This is a headline
25007 (progn
25008 (setq have-headings t)
25009 (setq level (- (match-end 1) (match-beginning 1))
25010 level (org-tr-level level)
25011 txt (save-match-data
25012 (org-html-expand
25013 (org-export-cleanup-toc-line
25014 (match-string 3 line))))
25015 todo
25016 (or (and org-export-mark-todo-in-toc
25017 (match-beginning 2)
25018 (not (member (match-string 2 line)
25019 org-done-keywords)))
25020 ; TODO, not DONE
25021 (and org-export-mark-todo-in-toc
25022 (= level umax-toc)
25023 (org-search-todo-below
25024 line lines level))))
25025 (if (string-match
25026 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
25027 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
25028 (if (string-match quote-re0 txt)
25029 (setq txt (replace-match "" t t txt)))
25030 (if org-export-with-section-numbers
25031 (setq txt (concat (org-section-number level)
25032 " " txt)))
25033 (if (<= level (max umax umax-toc))
25034 (setq head-count (+ head-count 1)))
25035 (if (<= level umax-toc)
25036 (progn
25037 (if (> level org-last-level)
25038 (progn
25039 (setq cnt (- level org-last-level))
25040 (while (>= (setq cnt (1- cnt)) 0)
25041 (push "\n<ul>\n<li>" thetoc))
25042 (push "\n" thetoc)))
25043 (if (< level org-last-level)
25044 (progn
25045 (setq cnt (- org-last-level level))
25046 (while (>= (setq cnt (1- cnt)) 0)
25047 (push "</li>\n</ul>" thetoc))
25048 (push "\n" thetoc)))
25049 ;; Check for targets
25050 (while (string-match org-target-regexp line)
25051 (setq tg (match-string 1 line)
25052 line (replace-match
25053 (concat "@<span class=\"target\">" tg "@</span> ")
25054 t t line))
25055 (push (cons (org-solidify-link-text tg)
25056 (format "sec-%d" head-count))
25057 target-alist))
25058 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
25059 (setq txt (replace-match "" t t txt)))
25060 (push
25061 (format
25062 (if todo
25063 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
25064 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
25065 head-count txt) thetoc)
25067 (setq org-last-level level))
25069 line)
25070 lines))
25071 (while (> org-last-level (1- org-min-level))
25072 (setq org-last-level (1- org-last-level))
25073 (push "</li>\n</ul>\n" thetoc))
25074 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25076 (setq head-count 0)
25077 (org-init-section-numbers)
25079 (while (setq line (pop lines) origline line)
25080 (catch 'nextline
25082 ;; end of quote section?
25083 (when (and inquote (string-match "^\\*+ " line))
25084 (insert "</pre>\n")
25085 (setq inquote nil))
25086 ;; inside a quote section?
25087 (when inquote
25088 (insert (org-html-protect line) "\n")
25089 (throw 'nextline nil))
25091 ;; verbatim lines
25092 (when (and org-export-with-fixed-width
25093 (string-match "^[ \t]*:\\(.*\\)" line))
25094 (when (not infixed)
25095 (setq infixed t)
25096 (insert "<pre>\n"))
25097 (insert (org-html-protect (match-string 1 line)) "\n")
25098 (when (and lines
25099 (not (string-match "^[ \t]*\\(:.*\\)"
25100 (car lines))))
25101 (setq infixed nil)
25102 (insert "</pre>\n"))
25103 (throw 'nextline nil))
25105 ;; Protected HTML
25106 (when (get-text-property 0 'org-protected line)
25107 (let (par)
25108 (when (re-search-backward
25109 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
25110 (setq par (match-string 1))
25111 (replace-match "\\2\n"))
25112 (insert line "\n")
25113 (while (and lines
25114 (or (= (length (car lines)) 0)
25115 (get-text-property 0 'org-protected (car lines))))
25116 (insert (pop lines) "\n"))
25117 (and par (insert "<p>\n")))
25118 (throw 'nextline nil))
25120 ;; Horizontal line
25121 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
25122 (insert "\n<hr/>\n")
25123 (throw 'nextline nil))
25125 ;; make targets to anchors
25126 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
25127 (cond
25128 ((match-end 2)
25129 (setq line (replace-match
25130 (concat "@<a name=\""
25131 (org-solidify-link-text (match-string 1 line))
25132 "\">\\nbsp@</a>")
25133 t t line)))
25134 ((and org-export-with-toc (equal (string-to-char line) ?*))
25135 (setq line (replace-match
25136 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
25137 ; (concat "@<i>" (match-string 1 line) "@</i> ")
25138 t t line)))
25140 (setq line (replace-match
25141 (concat "@<a name=\""
25142 (org-solidify-link-text (match-string 1 line))
25143 "\" class=\"target\">" (match-string 1 line) "@</a> ")
25144 t t line)))))
25146 (setq line (org-html-handle-time-stamps line))
25148 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
25149 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
25150 ;; Also handle sub_superscripts and checkboxes
25151 (or (string-match org-table-hline-regexp line)
25152 (setq line (org-html-expand line)))
25154 ;; Format the links
25155 (setq start 0)
25156 (while (string-match org-bracket-link-analytic-regexp line start)
25157 (setq start (match-beginning 0))
25158 (setq type (if (match-end 2) (match-string 2 line) "internal"))
25159 (setq path (match-string 3 line))
25160 (setq desc1 (if (match-end 5) (match-string 5 line))
25161 desc2 (if (match-end 2) (concat type ":" path) path)
25162 descp (and desc1 (not (equal desc1 desc2)))
25163 desc (or desc1 desc2))
25164 ;; Make an image out of the description if that is so wanted
25165 (when (and descp (org-file-image-p desc))
25166 (save-match-data
25167 (if (string-match "^file:" desc)
25168 (setq desc (substring desc (match-end 0)))))
25169 (setq desc (concat "<img src=\"" desc "\"/>")))
25170 ;; FIXME: do we need to unescape here somewhere?
25171 (cond
25172 ((equal type "internal")
25173 (setq rpl
25174 (concat
25175 "<a href=\"#"
25176 (org-solidify-link-text
25177 (save-match-data (org-link-unescape path)) target-alist)
25178 "\">" desc "</a>")))
25179 ((member type '("http" "https"))
25180 ;; standard URL, just check if we need to inline an image
25181 (if (and (or (eq t org-export-html-inline-images)
25182 (and org-export-html-inline-images (not descp)))
25183 (org-file-image-p path))
25184 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
25185 (setq link (concat type ":" path))
25186 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
25187 ((member type '("ftp" "mailto" "news"))
25188 ;; standard URL
25189 (setq link (concat type ":" path))
25190 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
25191 ((string= type "file")
25192 ;; FILE link
25193 (let* ((filename path)
25194 (abs-p (file-name-absolute-p filename))
25195 thefile file-is-image-p search)
25196 (save-match-data
25197 (if (string-match "::\\(.*\\)" filename)
25198 (setq search (match-string 1 filename)
25199 filename (replace-match "" t nil filename)))
25200 (setq valid
25201 (if (functionp link-validate)
25202 (funcall link-validate filename current-dir)
25204 (setq file-is-image-p (org-file-image-p filename))
25205 (setq thefile (if abs-p (expand-file-name filename) filename))
25206 (when (and org-export-html-link-org-files-as-html
25207 (string-match "\\.org$" thefile))
25208 (setq thefile (concat (substring thefile 0
25209 (match-beginning 0))
25210 "." org-export-html-extension))
25211 (if (and search
25212 ;; make sure this is can be used as target search
25213 (not (string-match "^[0-9]*$" search))
25214 (not (string-match "^\\*" search))
25215 (not (string-match "^/.*/$" search)))
25216 (setq thefile (concat thefile "#"
25217 (org-solidify-link-text
25218 (org-link-unescape search)))))
25219 (when (string-match "^file:" desc)
25220 (setq desc (replace-match "" t t desc))
25221 (if (string-match "\\.org$" desc)
25222 (setq desc (replace-match "" t t desc))))))
25223 (setq rpl (if (and file-is-image-p
25224 (or (eq t org-export-html-inline-images)
25225 (and org-export-html-inline-images
25226 (not descp))))
25227 (concat "<img src=\"" thefile "\"/>")
25228 (concat "<a href=\"" thefile "\">" desc "</a>")))
25229 (if (not valid) (setq rpl desc))))
25230 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
25231 (setq rpl (concat "<i>&lt;" type ":"
25232 (save-match-data (org-link-unescape path))
25233 "&gt;</i>"))))
25234 (setq line (replace-match rpl t t line)
25235 start (+ start (length rpl))))
25237 ;; TODO items
25238 (if (and (string-match org-todo-line-regexp line)
25239 (match-beginning 2))
25241 (setq line
25242 (concat (substring line 0 (match-beginning 2))
25243 "<span class=\""
25244 (if (member (match-string 2 line)
25245 org-done-keywords)
25246 "done" "todo")
25247 "\">" (match-string 2 line)
25248 "</span>" (substring line (match-end 2)))))
25250 ;; Does this contain a reference to a footnote?
25251 (when org-export-with-footnotes
25252 (setq start 0)
25253 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
25254 (if (get-text-property (match-beginning 2) 'org-protected line)
25255 (setq start (match-end 2))
25256 (let ((n (match-string 2 line)))
25257 (setq line
25258 (replace-match
25259 (format
25260 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
25261 (match-string 1 line) n n n)
25262 t t line))))))
25264 (cond
25265 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25266 ;; This is a headline
25267 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25268 txt (match-string 2 line))
25269 (if (string-match quote-re0 txt)
25270 (setq txt (replace-match "" t t txt)))
25271 (if (<= level (max umax umax-toc))
25272 (setq head-count (+ head-count 1)))
25273 (when in-local-list
25274 ;; Close any local lists before inserting a new header line
25275 (while local-list-num
25276 (org-close-li)
25277 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25278 (pop local-list-num))
25279 (setq local-list-indent nil
25280 in-local-list nil))
25281 (setq first-heading-pos (or first-heading-pos (point)))
25282 (org-html-level-start level txt umax
25283 (and org-export-with-toc (<= level umax))
25284 head-count)
25285 ;; QUOTES
25286 (when (string-match quote-re line)
25287 (insert "<pre>")
25288 (setq inquote t)))
25290 ((and org-export-with-tables
25291 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25292 (if (not table-open)
25293 ;; New table starts
25294 (setq table-open t table-buffer nil table-orig-buffer nil))
25295 ;; Accumulate lines
25296 (setq table-buffer (cons line table-buffer)
25297 table-orig-buffer (cons origline table-orig-buffer))
25298 (when (or (not lines)
25299 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25300 (car lines))))
25301 (setq table-open nil
25302 table-buffer (nreverse table-buffer)
25303 table-orig-buffer (nreverse table-orig-buffer))
25304 (org-close-par-maybe)
25305 (insert (org-format-table-html table-buffer table-orig-buffer))))
25307 ;; Normal lines
25308 (when (string-match
25309 (cond
25310 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25311 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25312 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25313 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
25314 line)
25315 (setq ind (org-get-string-indentation line)
25316 start-is-num (match-beginning 4)
25317 starter (if (match-beginning 2)
25318 (substring (match-string 2 line) 0 -1))
25319 line (substring line (match-beginning 5)))
25320 (unless (string-match "[^ \t]" line)
25321 ;; empty line. Pretend indentation is large.
25322 (setq ind (if org-empty-line-terminates-plain-lists
25324 (1+ (or (car local-list-indent) 1)))))
25325 (setq didclose nil)
25326 (while (and in-local-list
25327 (or (and (= ind (car local-list-indent))
25328 (not starter))
25329 (< ind (car local-list-indent))))
25330 (setq didclose t)
25331 (org-close-li)
25332 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25333 (pop local-list-num) (pop local-list-indent)
25334 (setq in-local-list local-list-indent))
25335 (cond
25336 ((and starter
25337 (or (not in-local-list)
25338 (> ind (car local-list-indent))))
25339 ;; Start new (level of) list
25340 (org-close-par-maybe)
25341 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
25342 (push start-is-num local-list-num)
25343 (push ind local-list-indent)
25344 (setq in-local-list t))
25345 (starter
25346 ;; continue current list
25347 (org-close-li)
25348 (insert "<li>\n"))
25349 (didclose
25350 ;; we did close a list, normal text follows: need <p>
25351 (org-open-par)))
25352 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
25353 (setq line
25354 (replace-match
25355 (if (equal (match-string 1 line) "X")
25356 "<b>[X]</b>"
25357 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
25358 t t line))))
25360 ;; Empty lines start a new paragraph. If hand-formatted lists
25361 ;; are not fully interpreted, lines starting with "-", "+", "*"
25362 ;; also start a new paragraph.
25363 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
25365 ;; Is this the start of a footnote?
25366 (when org-export-with-footnotes
25367 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
25368 (org-close-par-maybe)
25369 (let ((n (match-string 1 line)))
25370 (setq line (replace-match
25371 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
25373 ;; Check if the line break needs to be conserved
25374 (cond
25375 ((string-match "\\\\\\\\[ \t]*$" line)
25376 (setq line (replace-match "<br/>" t t line)))
25377 (org-export-preserve-breaks
25378 (setq line (concat line "<br/>"))))
25380 (insert line "\n")))))
25382 ;; Properly close all local lists and other lists
25383 (when inquote (insert "</pre>\n"))
25384 (when in-local-list
25385 ;; Close any local lists before inserting a new header line
25386 (while local-list-num
25387 (org-close-li)
25388 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
25389 (pop local-list-num))
25390 (setq local-list-indent nil
25391 in-local-list nil))
25392 (org-html-level-start 1 nil umax
25393 (and org-export-with-toc (<= level umax))
25394 head-count)
25396 (unless body-only
25397 (when (plist-get opt-plist :auto-postamble)
25398 (insert "<div id=\"postamble\">")
25399 (when (and org-export-author-info author)
25400 (insert "<p class=\"author\"> "
25401 (nth 1 lang-words) ": " author "\n")
25402 (when email
25403 (if (listp (split-string email ",+ *"))
25404 (mapc (lambda(e)
25405 (insert "<a href=\"mailto:" e "\">&lt;"
25406 e "&gt;</a>\n"))
25407 (split-string email ",+ *"))
25408 (insert "<a href=\"mailto:" email "\">&lt;"
25409 email "&gt;</a>\n")))
25410 (insert "</p>\n"))
25411 (when (and date org-export-time-stamp-file)
25412 (insert "<p class=\"date\"> "
25413 (nth 2 lang-words) ": "
25414 date "</p>\n"))
25415 (insert "</div>"))
25417 (if org-export-html-with-timestamp
25418 (insert org-export-html-html-helper-timestamp))
25419 (insert (or (plist-get opt-plist :postamble) ""))
25420 (insert "</body>\n</html>\n"))
25422 (normal-mode)
25423 (if (eq major-mode default-major-mode) (html-mode))
25425 ;; insert the table of contents
25426 (goto-char (point-min))
25427 (when thetoc
25428 (if (or (re-search-forward
25429 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
25430 (re-search-forward
25431 "\\[TABLE-OF-CONTENTS\\]" nil t))
25432 (progn
25433 (goto-char (match-beginning 0))
25434 (replace-match ""))
25435 (goto-char first-heading-pos)
25436 (when (looking-at "\\s-*</p>")
25437 (goto-char (match-end 0))
25438 (insert "\n")))
25439 (insert "<div id=\"table-of-contents\">\n")
25440 (mapc 'insert thetoc)
25441 (insert "</div>\n"))
25442 ;; remove empty paragraphs and lists
25443 (goto-char (point-min))
25444 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
25445 (replace-match ""))
25446 (goto-char (point-min))
25447 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
25448 (replace-match ""))
25449 ;; Convert whitespace place holders
25450 (goto-char (point-min))
25451 (let (beg end n)
25452 (while (setq beg (next-single-property-change (point) 'org-whitespace))
25453 (setq n (get-text-property beg 'org-whitespace)
25454 end (next-single-property-change beg 'org-whitespace))
25455 (goto-char beg)
25456 (delete-region beg end)
25457 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
25458 (make-string n ?x)))))
25460 (or to-buffer (save-buffer))
25461 (goto-char (point-min))
25462 (message "Exporting... done")
25463 (if (eq to-buffer 'string)
25464 (prog1 (buffer-substring (point-min) (point-max))
25465 (kill-buffer (current-buffer)))
25466 (current-buffer)))))
25468 (defvar org-table-colgroup-info nil)
25469 (defun org-format-table-ascii (lines)
25470 "Format a table for ascii export."
25471 (if (stringp lines)
25472 (setq lines (org-split-string lines "\n")))
25473 (if (not (string-match "^[ \t]*|" (car lines)))
25474 ;; Table made by table.el - test for spanning
25475 lines
25477 ;; A normal org table
25478 ;; Get rid of hlines at beginning and end
25479 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25480 (setq lines (nreverse lines))
25481 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25482 (setq lines (nreverse lines))
25483 (when org-export-table-remove-special-lines
25484 ;; Check if the table has a marking column. If yes remove the
25485 ;; column and the special lines
25486 (setq lines (org-table-clean-before-export lines)))
25487 ;; Get rid of the vertical lines except for grouping
25488 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
25489 rtn line vl1 start)
25490 (while (setq line (pop lines))
25491 (if (string-match org-table-hline-regexp line)
25492 (and (string-match "|\\(.*\\)|" line)
25493 (setq line (replace-match " \\1" t nil line)))
25494 (setq start 0 vl1 vl)
25495 (while (string-match "|" line start)
25496 (setq start (match-end 0))
25497 (or (pop vl1) (setq line (replace-match " " t t line)))))
25498 (push line rtn))
25499 (nreverse rtn))))
25501 (defun org-colgroup-info-to-vline-list (info)
25502 (let (vl new last)
25503 (while info
25504 (setq last new new (pop info))
25505 (if (or (memq last '(:end :startend))
25506 (memq new '(:start :startend)))
25507 (push t vl)
25508 (push nil vl)))
25509 (setq vl (nreverse vl))
25510 (and vl (setcar vl nil))
25511 vl))
25513 (defun org-format-table-html (lines olines)
25514 "Find out which HTML converter to use and return the HTML code."
25515 (if (stringp lines)
25516 (setq lines (org-split-string lines "\n")))
25517 (if (string-match "^[ \t]*|" (car lines))
25518 ;; A normal org table
25519 (org-format-org-table-html lines)
25520 ;; Table made by table.el - test for spanning
25521 (let* ((hlines (delq nil (mapcar
25522 (lambda (x)
25523 (if (string-match "^[ \t]*\\+-" x) x
25524 nil))
25525 lines)))
25526 (first (car hlines))
25527 (ll (and (string-match "\\S-+" first)
25528 (match-string 0 first)))
25529 (re (concat "^[ \t]*" (regexp-quote ll)))
25530 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
25531 hlines))))
25532 (if (and (not spanning)
25533 (not org-export-prefer-native-exporter-for-tables))
25534 ;; We can use my own converter with HTML conversions
25535 (org-format-table-table-html lines)
25536 ;; Need to use the code generator in table.el, with the original text.
25537 (org-format-table-table-html-using-table-generate-source olines)))))
25539 (defun org-format-org-table-html (lines &optional splice)
25540 "Format a table into HTML."
25541 ;; Get rid of hlines at beginning and end
25542 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25543 (setq lines (nreverse lines))
25544 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25545 (setq lines (nreverse lines))
25546 (when org-export-table-remove-special-lines
25547 ;; Check if the table has a marking column. If yes remove the
25548 ;; column and the special lines
25549 (setq lines (org-table-clean-before-export lines)))
25551 (let ((head (and org-export-highlight-first-table-line
25552 (delq nil (mapcar
25553 (lambda (x) (string-match "^[ \t]*|-" x))
25554 (cdr lines)))))
25555 (nlines 0) fnum i
25556 tbopen line fields html gr colgropen)
25557 (if splice (setq head nil))
25558 (unless splice (push (if head "<thead>" "<tbody>") html))
25559 (setq tbopen t)
25560 (while (setq line (pop lines))
25561 (catch 'next-line
25562 (if (string-match "^[ \t]*|-" line)
25563 (progn
25564 (unless splice
25565 (push (if head "</thead>" "</tbody>") html)
25566 (if lines (push "<tbody>" html) (setq tbopen nil)))
25567 (setq head nil) ;; head ends here, first time around
25568 ;; ignore this line
25569 (throw 'next-line t)))
25570 ;; Break the line into fields
25571 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25572 (unless fnum (setq fnum (make-vector (length fields) 0)))
25573 (setq nlines (1+ nlines) i -1)
25574 (push (concat "<tr>"
25575 (mapconcat
25576 (lambda (x)
25577 (setq i (1+ i))
25578 (if (and (< i nlines)
25579 (string-match org-table-number-regexp x))
25580 (incf (aref fnum i)))
25581 (if head
25582 (concat (car org-export-table-header-tags) x
25583 (cdr org-export-table-header-tags))
25584 (concat (car org-export-table-data-tags) x
25585 (cdr org-export-table-data-tags))))
25586 fields "")
25587 "</tr>")
25588 html)))
25589 (unless splice (if tbopen (push "</tbody>" html)))
25590 (unless splice (push "</table>\n" html))
25591 (setq html (nreverse html))
25592 (unless splice
25593 ;; Put in col tags with the alignment (unfortuntely often ignored...)
25594 (push (mapconcat
25595 (lambda (x)
25596 (setq gr (pop org-table-colgroup-info))
25597 (format "%s<col align=\"%s\"></col>%s"
25598 (if (memq gr '(:start :startend))
25599 (prog1
25600 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
25601 (setq colgropen t))
25603 (if (> (/ (float x) nlines) org-table-number-fraction)
25604 "right" "left")
25605 (if (memq gr '(:end :startend))
25606 (progn (setq colgropen nil) "</colgroup>")
25607 "")))
25608 fnum "")
25609 html)
25610 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
25611 (push html-table-tag html))
25612 (concat (mapconcat 'identity html "\n") "\n")))
25614 (defun org-table-clean-before-export (lines)
25615 "Check if the table has a marking column.
25616 If yes remove the column and the special lines."
25617 (setq org-table-colgroup-info nil)
25618 (if (memq nil
25619 (mapcar
25620 (lambda (x) (or (string-match "^[ \t]*|-" x)
25621 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
25622 lines))
25623 (progn
25624 (setq org-table-clean-did-remove-column nil)
25625 (delq nil
25626 (mapcar
25627 (lambda (x)
25628 (cond
25629 ((string-match "^[ \t]*| */ *|" x)
25630 (setq org-table-colgroup-info
25631 (mapcar (lambda (x)
25632 (cond ((member x '("<" "&lt;")) :start)
25633 ((member x '(">" "&gt;")) :end)
25634 ((member x '("<>" "&lt;&gt;")) :startend)
25635 (t nil)))
25636 (org-split-string x "[ \t]*|[ \t]*")))
25637 nil)
25638 (t x)))
25639 lines)))
25640 (setq org-table-clean-did-remove-column t)
25641 (delq nil
25642 (mapcar
25643 (lambda (x)
25644 (cond
25645 ((string-match "^[ \t]*| */ *|" x)
25646 (setq org-table-colgroup-info
25647 (mapcar (lambda (x)
25648 (cond ((member x '("<" "&lt;")) :start)
25649 ((member x '(">" "&gt;")) :end)
25650 ((member x '("<>" "&lt;&gt;")) :startend)
25651 (t nil)))
25652 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
25653 nil)
25654 ((string-match "^[ \t]*| *[!_^/] *|" x)
25655 nil) ; ignore this line
25656 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
25657 (string-match "^\\([ \t]*\\)|[^|]*|" x))
25658 ;; remove the first column
25659 (replace-match "\\1|" t nil x))))
25660 lines))))
25662 (defun org-format-table-table-html (lines)
25663 "Format a table generated by table.el into HTML.
25664 This conversion does *not* use `table-generate-source' from table.el.
25665 This has the advantage that Org-mode's HTML conversions can be used.
25666 But it has the disadvantage, that no cell- or row-spanning is allowed."
25667 (let (line field-buffer
25668 (head org-export-highlight-first-table-line)
25669 fields html empty)
25670 (setq html (concat html-table-tag "\n"))
25671 (while (setq line (pop lines))
25672 (setq empty "&nbsp;")
25673 (catch 'next-line
25674 (if (string-match "^[ \t]*\\+-" line)
25675 (progn
25676 (if field-buffer
25677 (progn
25678 (setq
25679 html
25680 (concat
25681 html
25682 "<tr>"
25683 (mapconcat
25684 (lambda (x)
25685 (if (equal x "") (setq x empty))
25686 (if head
25687 (concat (car org-export-table-header-tags) x
25688 (cdr org-export-table-header-tags))
25689 (concat (car org-export-table-data-tags) x
25690 (cdr org-export-table-data-tags))))
25691 field-buffer "\n")
25692 "</tr>\n"))
25693 (setq head nil)
25694 (setq field-buffer nil)))
25695 ;; Ignore this line
25696 (throw 'next-line t)))
25697 ;; Break the line into fields and store the fields
25698 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25699 (if field-buffer
25700 (setq field-buffer (mapcar
25701 (lambda (x)
25702 (concat x "<br/>" (pop fields)))
25703 field-buffer))
25704 (setq field-buffer fields))))
25705 (setq html (concat html "</table>\n"))
25706 html))
25708 (defun org-format-table-table-html-using-table-generate-source (lines)
25709 "Format a table into html, using `table-generate-source' from table.el.
25710 This has the advantage that cell- or row-spanning is allowed.
25711 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
25712 (require 'table)
25713 (with-current-buffer (get-buffer-create " org-tmp1 ")
25714 (erase-buffer)
25715 (insert (mapconcat 'identity lines "\n"))
25716 (goto-char (point-min))
25717 (if (not (re-search-forward "|[^+]" nil t))
25718 (error "Error processing table"))
25719 (table-recognize-table)
25720 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
25721 (table-generate-source 'html " org-tmp2 ")
25722 (set-buffer " org-tmp2 ")
25723 (buffer-substring (point-min) (point-max))))
25725 (defun org-html-handle-time-stamps (s)
25726 "Format time stamps in string S, or remove them."
25727 (catch 'exit
25728 (let (r b)
25729 (while (string-match org-maybe-keyword-time-regexp s)
25730 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
25731 ;; never export CLOCK
25732 (throw 'exit ""))
25733 (or b (setq b (substring s 0 (match-beginning 0))))
25734 (if (not org-export-with-timestamps)
25735 (setq r (concat r (substring s 0 (match-beginning 0)))
25736 s (substring s (match-end 0)))
25737 (setq r (concat
25738 r (substring s 0 (match-beginning 0))
25739 (if (match-end 1)
25740 (format "@<span class=\"timestamp-kwd\">%s @</span>"
25741 (match-string 1 s)))
25742 (format " @<span class=\"timestamp\">%s@</span>"
25743 (substring
25744 (org-translate-time (match-string 3 s)) 1 -1)))
25745 s (substring s (match-end 0)))))
25746 ;; Line break if line started and ended with time stamp stuff
25747 (if (not r)
25749 (setq r (concat r s))
25750 (unless (string-match "\\S-" (concat b s))
25751 (setq r (concat r "@<br/>")))
25752 r))))
25754 (defun org-html-protect (s)
25755 ;; convert & to &amp;, < to &lt; and > to &gt;
25756 (let ((start 0))
25757 (while (string-match "&" s start)
25758 (setq s (replace-match "&amp;" t t s)
25759 start (1+ (match-beginning 0))))
25760 (while (string-match "<" s)
25761 (setq s (replace-match "&lt;" t t s)))
25762 (while (string-match ">" s)
25763 (setq s (replace-match "&gt;" t t s))))
25766 (defun org-export-cleanup-toc-line (s)
25767 "Remove tags and time staps from lines going into the toc."
25768 (when (memq org-export-with-tags '(not-in-toc nil))
25769 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
25770 (setq s (replace-match "" t t s))))
25771 (when org-export-remove-timestamps-from-toc
25772 (while (string-match org-maybe-keyword-time-regexp s)
25773 (setq s (replace-match "" t t s))))
25774 (while (string-match org-bracket-link-regexp s)
25775 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
25776 t t s)))
25779 (defun org-html-expand (string)
25780 "Prepare STRING for HTML export. Applies all active conversions.
25781 If there are links in the string, don't modify these."
25782 (let* ((re (concat org-bracket-link-regexp "\\|"
25783 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
25784 m s l res)
25785 (while (setq m (string-match re string))
25786 (setq s (substring string 0 m)
25787 l (match-string 0 string)
25788 string (substring string (match-end 0)))
25789 (push (org-html-do-expand s) res)
25790 (push l res))
25791 (push (org-html-do-expand string) res)
25792 (apply 'concat (nreverse res))))
25794 (defun org-html-do-expand (s)
25795 "Apply all active conversions to translate special ASCII to HTML."
25796 (setq s (org-html-protect s))
25797 (if org-export-html-expand
25798 (let ((start 0))
25799 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
25800 (setq s (replace-match "<\\1>" t nil s)))))
25801 (if org-export-with-emphasize
25802 (setq s (org-export-html-convert-emphasize s)))
25803 (if org-export-with-special-strings
25804 (setq s (org-export-html-convert-special-strings s)))
25805 (if org-export-with-sub-superscripts
25806 (setq s (org-export-html-convert-sub-super s)))
25807 (if org-export-with-TeX-macros
25808 (let ((start 0) wd ass)
25809 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
25810 (if (get-text-property (match-beginning 0) 'org-protected s)
25811 (setq start (match-end 0))
25812 (setq wd (match-string 1 s))
25813 (if (setq ass (assoc wd org-html-entities))
25814 (setq s (replace-match (or (cdr ass)
25815 (concat "&" (car ass) ";"))
25816 t t s))
25817 (setq start (+ start (length wd))))))))
25820 (defun org-create-multibrace-regexp (left right n)
25821 "Create a regular expression which will match a balanced sexp.
25822 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
25823 as single character strings.
25824 The regexp returned will match the entire expression including the
25825 delimiters. It will also define a single group which contains the
25826 match except for the outermost delimiters. The maximum depth of
25827 stacked delimiters is N. Escaping delimiters is not possible."
25828 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
25829 (or "\\|")
25830 (re nothing)
25831 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
25832 (while (> n 1)
25833 (setq n (1- n)
25834 re (concat re or next)
25835 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
25836 (concat left "\\(" re "\\)" right)))
25838 (defvar org-match-substring-regexp
25839 (concat
25840 "\\([^\\]\\)\\([_^]\\)\\("
25841 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
25842 "\\|"
25843 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
25844 "\\|"
25845 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
25846 "The regular expression matching a sub- or superscript.")
25848 (defvar org-match-substring-with-braces-regexp
25849 (concat
25850 "\\([^\\]\\)\\([_^]\\)\\("
25851 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
25852 "\\)")
25853 "The regular expression matching a sub- or superscript, forcing braces.")
25855 (defconst org-export-html-special-string-regexps
25856 '(("\\\\-" . "&shy;")
25857 ("---\\([^-]\\)" . "&mdash;\\1")
25858 ("--\\([^-]\\)" . "&ndash;\\1")
25859 ("\\.\\.\\." . "&hellip;"))
25860 "Regular expressions for special string conversion.")
25862 (defun org-export-html-convert-special-strings (string)
25863 "Convert special characters in STRING to HTML."
25864 (let ((all org-export-html-special-string-regexps)
25865 e a re rpl start)
25866 (while (setq a (pop all))
25867 (setq re (car a) rpl (cdr a) start 0)
25868 (while (string-match re string start)
25869 (if (get-text-property (match-beginning 0) 'org-protected string)
25870 (setq start (match-end 0))
25871 (setq string (replace-match rpl t nil string)))))
25872 string))
25874 (defun org-export-html-convert-sub-super (string)
25875 "Convert sub- and superscripts in STRING to HTML."
25876 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
25877 (while (string-match org-match-substring-regexp string s)
25878 (cond
25879 ((and requireb (match-end 8)) (setq s (match-end 2)))
25880 ((get-text-property (match-beginning 2) 'org-protected string)
25881 (setq s (match-end 2)))
25883 (setq s (match-end 1)
25884 key (if (string= (match-string 2 string) "_") "sub" "sup")
25885 c (or (match-string 8 string)
25886 (match-string 6 string)
25887 (match-string 5 string))
25888 string (replace-match
25889 (concat (match-string 1 string)
25890 "<" key ">" c "</" key ">")
25891 t t string)))))
25892 (while (string-match "\\\\\\([_^]\\)" string)
25893 (setq string (replace-match (match-string 1 string) t t string)))
25894 string))
25896 (defun org-export-html-convert-emphasize (string)
25897 "Apply emphasis."
25898 (let ((s 0) rpl)
25899 (while (string-match org-emph-re string s)
25900 (if (not (equal
25901 (substring string (match-beginning 3) (1+ (match-beginning 3)))
25902 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
25903 (setq s (match-beginning 0)
25905 (concat
25906 (match-string 1 string)
25907 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
25908 (match-string 4 string)
25909 (nth 3 (assoc (match-string 3 string)
25910 org-emphasis-alist))
25911 (match-string 5 string))
25912 string (replace-match rpl t t string)
25913 s (+ s (- (length rpl) 2)))
25914 (setq s (1+ s))))
25915 string))
25917 (defvar org-par-open nil)
25918 (defun org-open-par ()
25919 "Insert <p>, but first close previous paragraph if any."
25920 (org-close-par-maybe)
25921 (insert "\n<p>")
25922 (setq org-par-open t))
25923 (defun org-close-par-maybe ()
25924 "Close paragraph if there is one open."
25925 (when org-par-open
25926 (insert "</p>")
25927 (setq org-par-open nil)))
25928 (defun org-close-li ()
25929 "Close <li> if necessary."
25930 (org-close-par-maybe)
25931 (insert "</li>\n"))
25933 (defvar body-only) ; dynamically scoped into this.
25934 (defun org-html-level-start (level title umax with-toc head-count)
25935 "Insert a new level in HTML export.
25936 When TITLE is nil, just close all open levels."
25937 (org-close-par-maybe)
25938 (let ((l org-level-max))
25939 (while (>= l level)
25940 (if (aref org-levels-open (1- l))
25941 (progn
25942 (org-html-level-close l umax)
25943 (aset org-levels-open (1- l) nil)))
25944 (setq l (1- l)))
25945 (when title
25946 ;; If title is nil, this means this function is called to close
25947 ;; all levels, so the rest is done only if title is given
25948 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
25949 (setq title (replace-match
25950 (if org-export-with-tags
25951 (save-match-data
25952 (concat
25953 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
25954 (mapconcat 'identity (org-split-string
25955 (match-string 1 title) ":")
25956 "&nbsp;")
25957 "</span>"))
25959 t t title)))
25960 (if (> level umax)
25961 (progn
25962 (if (aref org-levels-open (1- level))
25963 (progn
25964 (org-close-li)
25965 (insert "<li>" title "<br/>\n"))
25966 (aset org-levels-open (1- level) t)
25967 (org-close-par-maybe)
25968 (insert "<ul>\n<li>" title "<br/>\n")))
25969 (aset org-levels-open (1- level) t)
25970 (if (and org-export-with-section-numbers (not body-only))
25971 (setq title (concat (org-section-number level) " " title)))
25972 (setq level (+ level org-export-html-toplevel-hlevel -1))
25973 (if with-toc
25974 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
25975 level level head-count title level))
25976 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
25977 (org-open-par)))))
25979 (defun org-html-level-close (level max-outline-level)
25980 "Terminate one level in HTML export."
25981 (if (<= level max-outline-level)
25982 (insert "</div>\n")
25983 (org-close-li)
25984 (insert "</ul>\n")))
25986 ;;; iCalendar export
25988 ;;;###autoload
25989 (defun org-export-icalendar-this-file ()
25990 "Export current file as an iCalendar file.
25991 The iCalendar file will be located in the same directory as the Org-mode
25992 file, but with extension `.ics'."
25993 (interactive)
25994 (org-export-icalendar nil buffer-file-name))
25996 ;;;###autoload
25997 (defun org-export-icalendar-all-agenda-files ()
25998 "Export all files in `org-agenda-files' to iCalendar .ics files.
25999 Each iCalendar file will be located in the same directory as the Org-mode
26000 file, but with extension `.ics'."
26001 (interactive)
26002 (apply 'org-export-icalendar nil (org-agenda-files t)))
26004 ;;;###autoload
26005 (defun org-export-icalendar-combine-agenda-files ()
26006 "Export all files in `org-agenda-files' to a single combined iCalendar file.
26007 The file is stored under the name `org-combined-agenda-icalendar-file'."
26008 (interactive)
26009 (apply 'org-export-icalendar t (org-agenda-files t)))
26011 (defun org-export-icalendar (combine &rest files)
26012 "Create iCalendar files for all elements of FILES.
26013 If COMBINE is non-nil, combine all calendar entries into a single large
26014 file and store it under the name `org-combined-agenda-icalendar-file'."
26015 (save-excursion
26016 (org-prepare-agenda-buffers files)
26017 (let* ((dir (org-export-directory
26018 :ical (list :publishing-directory
26019 org-export-publishing-directory)))
26020 file ical-file ical-buffer category started org-agenda-new-buffers)
26022 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
26023 (when combine
26024 (setq ical-file
26025 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
26026 org-combined-agenda-icalendar-file
26027 (expand-file-name org-combined-agenda-icalendar-file dir))
26028 ical-buffer (org-get-agenda-file-buffer ical-file))
26029 (set-buffer ical-buffer) (erase-buffer))
26030 (while (setq file (pop files))
26031 (catch 'nextfile
26032 (org-check-agenda-file file)
26033 (set-buffer (org-get-agenda-file-buffer file))
26034 (unless combine
26035 (setq ical-file (concat (file-name-as-directory dir)
26036 (file-name-sans-extension
26037 (file-name-nondirectory buffer-file-name))
26038 ".ics"))
26039 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
26040 (with-current-buffer ical-buffer (erase-buffer)))
26041 (setq category (or org-category
26042 (file-name-sans-extension
26043 (file-name-nondirectory buffer-file-name))))
26044 (if (symbolp category) (setq category (symbol-name category)))
26045 (let ((standard-output ical-buffer))
26046 (if combine
26047 (and (not started) (setq started t)
26048 (org-start-icalendar-file org-icalendar-combined-name))
26049 (org-start-icalendar-file category))
26050 (org-print-icalendar-entries combine)
26051 (when (or (and combine (not files)) (not combine))
26052 (org-finish-icalendar-file)
26053 (set-buffer ical-buffer)
26054 (save-buffer)
26055 (run-hooks 'org-after-save-iCalendar-file-hook)))))
26056 (org-release-buffers org-agenda-new-buffers))))
26058 (defvar org-after-save-iCalendar-file-hook nil
26059 "Hook run after an iCalendar file has been saved.
26060 The iCalendar buffer is still current when this hook is run.
26061 A good way to use this is to tell a desktop calenndar application to re-read
26062 the iCalendar file.")
26064 (defun org-print-icalendar-entries (&optional combine)
26065 "Print iCalendar entries for the current Org-mode file to `standard-output'.
26066 When COMBINE is non nil, add the category to each line."
26067 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
26068 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
26069 (dts (org-ical-ts-to-string
26070 (format-time-string (cdr org-time-stamp-formats) (current-time))
26071 "DTSTART"))
26072 hd ts ts2 state status (inc t) pos b sexp rrule
26073 scheduledp deadlinep tmp pri category entry location summary desc
26074 (sexp-buffer (get-buffer-create "*ical-tmp*")))
26075 (org-refresh-category-properties)
26076 (save-excursion
26077 (goto-char (point-min))
26078 (while (re-search-forward re1 nil t)
26079 (catch :skip
26080 (org-agenda-skip)
26081 (setq pos (match-beginning 0)
26082 ts (match-string 0)
26083 inc t
26084 hd (org-get-heading)
26085 summary (org-icalendar-cleanup-string
26086 (org-entry-get nil "SUMMARY"))
26087 desc (org-icalendar-cleanup-string
26088 (or (org-entry-get nil "DESCRIPTION")
26089 (and org-icalendar-include-body (org-get-entry)))
26090 t org-icalendar-include-body)
26091 location (org-icalendar-cleanup-string
26092 (org-entry-get nil "LOCATION"))
26093 category (org-get-category))
26094 (if (looking-at re2)
26095 (progn
26096 (goto-char (match-end 0))
26097 (setq ts2 (match-string 1) inc nil))
26098 (setq tmp (buffer-substring (max (point-min)
26099 (- pos org-ds-keyword-length))
26100 pos)
26101 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
26102 (progn
26103 (setq inc nil)
26104 (replace-match "\\1" t nil ts))
26106 deadlinep (string-match org-deadline-regexp tmp)
26107 scheduledp (string-match org-scheduled-regexp tmp)
26108 ;; donep (org-entry-is-done-p)
26110 (if (or (string-match org-tr-regexp hd)
26111 (string-match org-ts-regexp hd))
26112 (setq hd (replace-match "" t t hd)))
26113 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
26114 (setq rrule
26115 (concat "\nRRULE:FREQ="
26116 (cdr (assoc
26117 (match-string 2 ts)
26118 '(("d" . "DAILY")("w" . "WEEKLY")
26119 ("m" . "MONTHLY")("y" . "YEARLY"))))
26120 ";INTERVAL=" (match-string 1 ts)))
26121 (setq rrule ""))
26122 (setq summary (or summary hd))
26123 (if (string-match org-bracket-link-regexp summary)
26124 (setq summary
26125 (replace-match (if (match-end 3)
26126 (match-string 3 summary)
26127 (match-string 1 summary))
26128 t t summary)))
26129 (if deadlinep (setq summary (concat "DL: " summary)))
26130 (if scheduledp (setq summary (concat "S: " summary)))
26131 (if (string-match "\\`<%%" ts)
26132 (with-current-buffer sexp-buffer
26133 (insert (substring ts 1 -1) " " summary "\n"))
26134 (princ (format "BEGIN:VEVENT
26136 %s%s
26137 SUMMARY:%s%s%s
26138 CATEGORIES:%s
26139 END:VEVENT\n"
26140 (org-ical-ts-to-string ts "DTSTART")
26141 (org-ical-ts-to-string ts2 "DTEND" inc)
26142 rrule summary
26143 (if (and desc (string-match "\\S-" desc))
26144 (concat "\nDESCRIPTION: " desc) "")
26145 (if (and location (string-match "\\S-" location))
26146 (concat "\nLOCATION: " location) "")
26147 category)))))
26149 (when (and org-icalendar-include-sexps
26150 (condition-case nil (require 'icalendar) (error nil))
26151 (fboundp 'icalendar-export-region))
26152 ;; Get all the literal sexps
26153 (goto-char (point-min))
26154 (while (re-search-forward "^&?%%(" nil t)
26155 (catch :skip
26156 (org-agenda-skip)
26157 (setq b (match-beginning 0))
26158 (goto-char (1- (match-end 0)))
26159 (forward-sexp 1)
26160 (end-of-line 1)
26161 (setq sexp (buffer-substring b (point)))
26162 (with-current-buffer sexp-buffer
26163 (insert sexp "\n"))
26164 (princ (org-diary-to-ical-string sexp-buffer)))))
26166 (when org-icalendar-include-todo
26167 (goto-char (point-min))
26168 (while (re-search-forward org-todo-line-regexp nil t)
26169 (catch :skip
26170 (org-agenda-skip)
26171 (setq state (match-string 2))
26172 (setq status (if (member state org-done-keywords)
26173 "COMPLETED" "NEEDS-ACTION"))
26174 (when (and state
26175 (or (not (member state org-done-keywords))
26176 (eq org-icalendar-include-todo 'all))
26177 (not (member org-archive-tag (org-get-tags-at)))
26179 (setq hd (match-string 3)
26180 summary (org-icalendar-cleanup-string
26181 (org-entry-get nil "SUMMARY"))
26182 desc (org-icalendar-cleanup-string
26183 (or (org-entry-get nil "DESCRIPTION")
26184 (and org-icalendar-include-body (org-get-entry)))
26185 t org-icalendar-include-body)
26186 location (org-icalendar-cleanup-string
26187 (org-entry-get nil "LOCATION")))
26188 (if (string-match org-bracket-link-regexp hd)
26189 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
26190 (match-string 1 hd))
26191 t t hd)))
26192 (if (string-match org-priority-regexp hd)
26193 (setq pri (string-to-char (match-string 2 hd))
26194 hd (concat (substring hd 0 (match-beginning 1))
26195 (substring hd (match-end 1))))
26196 (setq pri org-default-priority))
26197 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
26198 (- org-lowest-priority org-highest-priority))))))
26200 (princ (format "BEGIN:VTODO
26202 SUMMARY:%s%s%s
26203 CATEGORIES:%s
26204 SEQUENCE:1
26205 PRIORITY:%d
26206 STATUS:%s
26207 END:VTODO\n"
26209 (or summary hd)
26210 (if (and location (string-match "\\S-" location))
26211 (concat "\nLOCATION: " location) "")
26212 (if (and desc (string-match "\\S-" desc))
26213 (concat "\nDESCRIPTION: " desc) "")
26214 category pri status)))))))))
26216 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
26217 "Take out stuff and quote what needs to be quoted.
26218 When IS-BODY is non-nil, assume that this is the body of an item, clean up
26219 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
26220 characters."
26221 (if (not s)
26223 (when is-body
26224 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
26225 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
26226 (while (string-match re s) (setq s (replace-match "" t t s)))
26227 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
26228 (let ((start 0))
26229 (while (string-match "\\([,;\\]\\)" s start)
26230 (setq start (+ (match-beginning 0) 2)
26231 s (replace-match "\\\\\\1" nil nil s))))
26232 (when is-body
26233 (while (string-match "[ \t]*\n[ \t]*" s)
26234 (setq s (replace-match "\\n" t t s))))
26235 (setq s (org-trim s))
26236 (if is-body
26237 (if maxlength
26238 (if (and (numberp maxlength)
26239 (> (length s) maxlength))
26240 (setq s (substring s 0 maxlength)))))
26243 (defun org-get-entry ()
26244 "Clean-up description string."
26245 (save-excursion
26246 (org-back-to-heading t)
26247 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
26249 (defun org-start-icalendar-file (name)
26250 "Start an iCalendar file by inserting the header."
26251 (let ((user user-full-name)
26252 (name (or name "unknown"))
26253 (timezone (cadr (current-time-zone))))
26254 (princ
26255 (format "BEGIN:VCALENDAR
26256 VERSION:2.0
26257 X-WR-CALNAME:%s
26258 PRODID:-//%s//Emacs with Org-mode//EN
26259 X-WR-TIMEZONE:%s
26260 CALSCALE:GREGORIAN\n" name user timezone))))
26262 (defun org-finish-icalendar-file ()
26263 "Finish an iCalendar file by inserting the END statement."
26264 (princ "END:VCALENDAR\n"))
26266 (defun org-ical-ts-to-string (s keyword &optional inc)
26267 "Take a time string S and convert it to iCalendar format.
26268 KEYWORD is added in front, to make a complete line like DTSTART....
26269 When INC is non-nil, increase the hour by two (if time string contains
26270 a time), or the day by one (if it does not contain a time)."
26271 (let ((t1 (org-parse-time-string s 'nodefault))
26272 t2 fmt have-time time)
26273 (if (and (car t1) (nth 1 t1) (nth 2 t1))
26274 (setq t2 t1 have-time t)
26275 (setq t2 (org-parse-time-string s)))
26276 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
26277 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
26278 (when inc
26279 (if have-time
26280 (if org-agenda-default-appointment-duration
26281 (setq mi (+ org-agenda-default-appointment-duration mi))
26282 (setq h (+ 2 h)))
26283 (setq d (1+ d))))
26284 (setq time (encode-time s mi h d m y)))
26285 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
26286 (concat keyword (format-time-string fmt time))))
26288 ;;; XOXO export
26290 (defun org-export-as-xoxo-insert-into (buffer &rest output)
26291 (with-current-buffer buffer
26292 (apply 'insert output)))
26293 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
26295 (defun org-export-as-xoxo (&optional buffer)
26296 "Export the org buffer as XOXO.
26297 The XOXO buffer is named *xoxo-<source buffer name>*"
26298 (interactive (list (current-buffer)))
26299 ;; A quickie abstraction
26301 ;; Output everything as XOXO
26302 (with-current-buffer (get-buffer buffer)
26303 (let* ((pos (point))
26304 (opt-plist (org-combine-plists (org-default-export-plist)
26305 (org-infile-export-plist)))
26306 (filename (concat (file-name-as-directory
26307 (org-export-directory :xoxo opt-plist))
26308 (file-name-sans-extension
26309 (file-name-nondirectory buffer-file-name))
26310 ".html"))
26311 (out (find-file-noselect filename))
26312 (last-level 1)
26313 (hanging-li nil))
26314 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
26315 ;; Check the output buffer is empty.
26316 (with-current-buffer out (erase-buffer))
26317 ;; Kick off the output
26318 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
26319 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
26320 (let* ((hd (match-string-no-properties 1))
26321 (level (length hd))
26322 (text (concat
26323 (match-string-no-properties 2)
26324 (save-excursion
26325 (goto-char (match-end 0))
26326 (let ((str ""))
26327 (catch 'loop
26328 (while 't
26329 (forward-line)
26330 (if (looking-at "^[ \t]\\(.*\\)")
26331 (setq str (concat str (match-string-no-properties 1)))
26332 (throw 'loop str)))))))))
26334 ;; Handle level rendering
26335 (cond
26336 ((> level last-level)
26337 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
26339 ((< level last-level)
26340 (dotimes (- (- last-level level) 1)
26341 (if hanging-li
26342 (org-export-as-xoxo-insert-into out "</li>\n"))
26343 (org-export-as-xoxo-insert-into out "</ol>\n"))
26344 (when hanging-li
26345 (org-export-as-xoxo-insert-into out "</li>\n")
26346 (setq hanging-li nil)))
26348 ((equal level last-level)
26349 (if hanging-li
26350 (org-export-as-xoxo-insert-into out "</li>\n")))
26353 (setq last-level level)
26355 ;; And output the new li
26356 (setq hanging-li 't)
26357 (if (equal ?+ (elt text 0))
26358 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
26359 (org-export-as-xoxo-insert-into out "<li>" text))))
26361 ;; Finally finish off the ol
26362 (dotimes (- last-level 1)
26363 (if hanging-li
26364 (org-export-as-xoxo-insert-into out "</li>\n"))
26365 (org-export-as-xoxo-insert-into out "</ol>\n"))
26367 (goto-char pos)
26368 ;; Finish the buffer off and clean it up.
26369 (switch-to-buffer-other-window out)
26370 (indent-region (point-min) (point-max) nil)
26371 (save-buffer)
26372 (goto-char (point-min))
26376 ;;;; Key bindings
26378 ;; Make `C-c C-x' a prefix key
26379 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
26381 ;; TAB key with modifiers
26382 (org-defkey org-mode-map "\C-i" 'org-cycle)
26383 (org-defkey org-mode-map [(tab)] 'org-cycle)
26384 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
26385 (org-defkey org-mode-map [(meta tab)] 'org-complete)
26386 (org-defkey org-mode-map "\M-\t" 'org-complete)
26387 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
26388 ;; The following line is necessary under Suse GNU/Linux
26389 (unless (featurep 'xemacs)
26390 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
26391 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
26392 (define-key org-mode-map [backtab] 'org-shifttab)
26394 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
26395 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
26396 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
26398 ;; Cursor keys with modifiers
26399 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
26400 (org-defkey org-mode-map [(meta right)] 'org-metaright)
26401 (org-defkey org-mode-map [(meta up)] 'org-metaup)
26402 (org-defkey org-mode-map [(meta down)] 'org-metadown)
26404 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
26405 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
26406 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
26407 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
26409 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
26410 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
26411 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
26412 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
26414 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
26415 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
26417 ;;; Extra keys for tty access.
26418 ;; We only set them when really needed because otherwise the
26419 ;; menus don't show the simple keys
26421 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
26422 (not window-system))
26423 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
26424 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
26425 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
26426 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
26427 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
26428 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
26429 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
26430 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
26431 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
26432 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
26433 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
26434 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
26435 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
26436 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
26437 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
26438 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
26439 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
26440 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
26441 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
26442 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
26443 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
26444 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
26446 ;; All the other keys
26448 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
26449 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
26450 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
26451 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
26452 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
26453 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
26454 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
26455 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
26456 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
26457 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
26458 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
26459 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
26460 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
26461 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
26462 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
26463 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
26464 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
26465 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
26466 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
26467 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
26468 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
26469 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
26470 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
26471 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
26472 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
26473 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
26474 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
26475 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
26476 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
26477 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
26478 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
26479 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
26480 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
26481 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
26482 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
26483 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
26484 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
26485 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
26486 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
26487 (org-defkey org-mode-map "\C-c^" 'org-sort)
26488 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
26489 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
26490 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
26491 (org-defkey org-mode-map "\C-m" 'org-return)
26492 (org-defkey org-mode-map "\C-j" 'org-return-indent)
26493 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
26494 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
26495 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
26496 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
26497 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
26498 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
26499 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
26500 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
26501 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
26502 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
26503 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
26504 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
26505 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
26506 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
26507 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
26508 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
26510 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
26511 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
26512 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
26513 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
26515 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
26516 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
26517 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
26518 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
26519 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
26520 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
26521 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
26522 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
26523 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
26524 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
26525 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
26526 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
26528 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
26530 (when (featurep 'xemacs)
26531 (org-defkey org-mode-map 'button3 'popup-mode-menu))
26533 (defsubst org-table-p () (org-at-table-p))
26535 (defun org-self-insert-command (N)
26536 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
26537 If the cursor is in a table looking at whitespace, the whitespace is
26538 overwritten, and the table is not marked as requiring realignment."
26539 (interactive "p")
26540 (if (and (org-table-p)
26541 (progn
26542 ;; check if we blank the field, and if that triggers align
26543 (and org-table-auto-blank-field
26544 (member last-command
26545 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
26546 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
26547 ;; got extra space, this field does not determine column width
26548 (let (org-table-may-need-update) (org-table-blank-field))
26549 ;; no extra space, this field may determine column width
26550 (org-table-blank-field)))
26552 (eq N 1)
26553 (looking-at "[^|\n]* |"))
26554 (let (org-table-may-need-update)
26555 (goto-char (1- (match-end 0)))
26556 (delete-backward-char 1)
26557 (goto-char (match-beginning 0))
26558 (self-insert-command N))
26559 (setq org-table-may-need-update t)
26560 (self-insert-command N)
26561 (org-fix-tags-on-the-fly)))
26563 (defun org-fix-tags-on-the-fly ()
26564 (when (and (equal (char-after (point-at-bol)) ?*)
26565 (org-on-heading-p))
26566 (org-align-tags-here org-tags-column)))
26568 (defun org-delete-backward-char (N)
26569 "Like `delete-backward-char', insert whitespace at field end in tables.
26570 When deleting backwards, in tables this function will insert whitespace in
26571 front of the next \"|\" separator, to keep the table aligned. The table will
26572 still be marked for re-alignment if the field did fill the entire column,
26573 because, in this case the deletion might narrow the column."
26574 (interactive "p")
26575 (if (and (org-table-p)
26576 (eq N 1)
26577 (string-match "|" (buffer-substring (point-at-bol) (point)))
26578 (looking-at ".*?|"))
26579 (let ((pos (point))
26580 (noalign (looking-at "[^|\n\r]* |"))
26581 (c org-table-may-need-update))
26582 (backward-delete-char N)
26583 (skip-chars-forward "^|")
26584 (insert " ")
26585 (goto-char (1- pos))
26586 ;; noalign: if there were two spaces at the end, this field
26587 ;; does not determine the width of the column.
26588 (if noalign (setq org-table-may-need-update c)))
26589 (backward-delete-char N)
26590 (org-fix-tags-on-the-fly)))
26592 (defun org-delete-char (N)
26593 "Like `delete-char', but insert whitespace at field end in tables.
26594 When deleting characters, in tables this function will insert whitespace in
26595 front of the next \"|\" separator, to keep the table aligned. The table will
26596 still be marked for re-alignment if the field did fill the entire column,
26597 because, in this case the deletion might narrow the column."
26598 (interactive "p")
26599 (if (and (org-table-p)
26600 (not (bolp))
26601 (not (= (char-after) ?|))
26602 (eq N 1))
26603 (if (looking-at ".*?|")
26604 (let ((pos (point))
26605 (noalign (looking-at "[^|\n\r]* |"))
26606 (c org-table-may-need-update))
26607 (replace-match (concat
26608 (substring (match-string 0) 1 -1)
26609 " |"))
26610 (goto-char pos)
26611 ;; noalign: if there were two spaces at the end, this field
26612 ;; does not determine the width of the column.
26613 (if noalign (setq org-table-may-need-update c)))
26614 (delete-char N))
26615 (delete-char N)
26616 (org-fix-tags-on-the-fly)))
26618 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
26619 (put 'org-self-insert-command 'delete-selection t)
26620 (put 'orgtbl-self-insert-command 'delete-selection t)
26621 (put 'org-delete-char 'delete-selection 'supersede)
26622 (put 'org-delete-backward-char 'delete-selection 'supersede)
26624 ;; Make `flyspell-mode' delay after some commands
26625 (put 'org-self-insert-command 'flyspell-delayed t)
26626 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
26627 (put 'org-delete-char 'flyspell-delayed t)
26628 (put 'org-delete-backward-char 'flyspell-delayed t)
26630 ;; Make pabbrev-mode expand after org-mode commands
26631 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
26632 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
26634 ;; How to do this: Measure non-white length of current string
26635 ;; If equal to column width, we should realign.
26637 (defun org-remap (map &rest commands)
26638 "In MAP, remap the functions given in COMMANDS.
26639 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
26640 (let (new old)
26641 (while commands
26642 (setq old (pop commands) new (pop commands))
26643 (if (fboundp 'command-remapping)
26644 (org-defkey map (vector 'remap old) new)
26645 (substitute-key-definition old new map global-map)))))
26647 (when (eq org-enable-table-editor 'optimized)
26648 ;; If the user wants maximum table support, we need to hijack
26649 ;; some standard editing functions
26650 (org-remap org-mode-map
26651 'self-insert-command 'org-self-insert-command
26652 'delete-char 'org-delete-char
26653 'delete-backward-char 'org-delete-backward-char)
26654 (org-defkey org-mode-map "|" 'org-force-self-insert))
26656 (defun org-shiftcursor-error ()
26657 "Throw an error because Shift-Cursor command was applied in wrong context."
26658 (error "This command is active in special context like tables, headlines or timestamps"))
26660 (defun org-shifttab (&optional arg)
26661 "Global visibility cycling or move to previous table field.
26662 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
26663 on context.
26664 See the individual commands for more information."
26665 (interactive "P")
26666 (cond
26667 ((org-at-table-p) (call-interactively 'org-table-previous-field))
26668 (arg (message "Content view to level: ")
26669 (org-content (prefix-numeric-value arg))
26670 (setq org-cycle-global-status 'overview))
26671 (t (call-interactively 'org-global-cycle))))
26673 (defun org-shiftmetaleft ()
26674 "Promote subtree or delete table column.
26675 Calls `org-promote-subtree', `org-outdent-item',
26676 or `org-table-delete-column', depending on context.
26677 See the individual commands for more information."
26678 (interactive)
26679 (cond
26680 ((org-at-table-p) (call-interactively 'org-table-delete-column))
26681 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
26682 ((org-at-item-p) (call-interactively 'org-outdent-item))
26683 (t (org-shiftcursor-error))))
26685 (defun org-shiftmetaright ()
26686 "Demote subtree or insert table column.
26687 Calls `org-demote-subtree', `org-indent-item',
26688 or `org-table-insert-column', depending on context.
26689 See the individual commands for more information."
26690 (interactive)
26691 (cond
26692 ((org-at-table-p) (call-interactively 'org-table-insert-column))
26693 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
26694 ((org-at-item-p) (call-interactively 'org-indent-item))
26695 (t (org-shiftcursor-error))))
26697 (defun org-shiftmetaup (&optional arg)
26698 "Move subtree up or kill table row.
26699 Calls `org-move-subtree-up' or `org-table-kill-row' or
26700 `org-move-item-up' depending on context. See the individual commands
26701 for more information."
26702 (interactive "P")
26703 (cond
26704 ((org-at-table-p) (call-interactively 'org-table-kill-row))
26705 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26706 ((org-at-item-p) (call-interactively 'org-move-item-up))
26707 (t (org-shiftcursor-error))))
26708 (defun org-shiftmetadown (&optional arg)
26709 "Move subtree down or insert table row.
26710 Calls `org-move-subtree-down' or `org-table-insert-row' or
26711 `org-move-item-down', depending on context. See the individual
26712 commands for more information."
26713 (interactive "P")
26714 (cond
26715 ((org-at-table-p) (call-interactively 'org-table-insert-row))
26716 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26717 ((org-at-item-p) (call-interactively 'org-move-item-down))
26718 (t (org-shiftcursor-error))))
26720 (defun org-metaleft (&optional arg)
26721 "Promote heading or move table column to left.
26722 Calls `org-do-promote' or `org-table-move-column', depending on context.
26723 With no specific context, calls the Emacs default `backward-word'.
26724 See the individual commands for more information."
26725 (interactive "P")
26726 (cond
26727 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
26728 ((or (org-on-heading-p) (org-region-active-p))
26729 (call-interactively 'org-do-promote))
26730 ((org-at-item-p) (call-interactively 'org-outdent-item))
26731 (t (call-interactively 'backward-word))))
26733 (defun org-metaright (&optional arg)
26734 "Demote subtree or move table column to right.
26735 Calls `org-do-demote' or `org-table-move-column', depending on context.
26736 With no specific context, calls the Emacs default `forward-word'.
26737 See the individual commands for more information."
26738 (interactive "P")
26739 (cond
26740 ((org-at-table-p) (call-interactively 'org-table-move-column))
26741 ((or (org-on-heading-p) (org-region-active-p))
26742 (call-interactively 'org-do-demote))
26743 ((org-at-item-p) (call-interactively 'org-indent-item))
26744 (t (call-interactively 'forward-word))))
26746 (defun org-metaup (&optional arg)
26747 "Move subtree up or move table row up.
26748 Calls `org-move-subtree-up' or `org-table-move-row' or
26749 `org-move-item-up', depending on context. See the individual commands
26750 for more information."
26751 (interactive "P")
26752 (cond
26753 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
26754 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26755 ((org-at-item-p) (call-interactively 'org-move-item-up))
26756 (t (transpose-lines 1) (beginning-of-line -1))))
26758 (defun org-metadown (&optional arg)
26759 "Move subtree down or move table row down.
26760 Calls `org-move-subtree-down' or `org-table-move-row' or
26761 `org-move-item-down', depending on context. See the individual
26762 commands for more information."
26763 (interactive "P")
26764 (cond
26765 ((org-at-table-p) (call-interactively 'org-table-move-row))
26766 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26767 ((org-at-item-p) (call-interactively 'org-move-item-down))
26768 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
26770 (defun org-shiftup (&optional arg)
26771 "Increase item in timestamp or increase priority of current headline.
26772 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
26773 depending on context. See the individual commands for more information."
26774 (interactive "P")
26775 (cond
26776 ((org-at-timestamp-p t)
26777 (call-interactively (if org-edit-timestamp-down-means-later
26778 'org-timestamp-down 'org-timestamp-up)))
26779 ((org-on-heading-p) (call-interactively 'org-priority-up))
26780 ((org-at-item-p) (call-interactively 'org-previous-item))
26781 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
26783 (defun org-shiftdown (&optional arg)
26784 "Decrease item in timestamp or decrease priority of current headline.
26785 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
26786 depending on context. See the individual commands for more information."
26787 (interactive "P")
26788 (cond
26789 ((org-at-timestamp-p t)
26790 (call-interactively (if org-edit-timestamp-down-means-later
26791 'org-timestamp-up 'org-timestamp-down)))
26792 ((org-on-heading-p) (call-interactively 'org-priority-down))
26793 (t (call-interactively 'org-next-item))))
26795 (defun org-shiftright ()
26796 "Next TODO keyword or timestamp one day later, depending on context."
26797 (interactive)
26798 (cond
26799 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
26800 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
26801 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
26802 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
26803 (t (org-shiftcursor-error))))
26805 (defun org-shiftleft ()
26806 "Previous TODO keyword or timestamp one day earlier, depending on context."
26807 (interactive)
26808 (cond
26809 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
26810 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
26811 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
26812 ((org-at-property-p)
26813 (call-interactively 'org-property-previous-allowed-value))
26814 (t (org-shiftcursor-error))))
26816 (defun org-shiftcontrolright ()
26817 "Switch to next TODO set."
26818 (interactive)
26819 (cond
26820 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
26821 (t (org-shiftcursor-error))))
26823 (defun org-shiftcontrolleft ()
26824 "Switch to previous TODO set."
26825 (interactive)
26826 (cond
26827 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
26828 (t (org-shiftcursor-error))))
26830 (defun org-ctrl-c-ret ()
26831 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
26832 (interactive)
26833 (cond
26834 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
26835 (t (call-interactively 'org-insert-heading))))
26837 (defun org-copy-special ()
26838 "Copy region in table or copy current subtree.
26839 Calls `org-table-copy' or `org-copy-subtree', depending on context.
26840 See the individual commands for more information."
26841 (interactive)
26842 (call-interactively
26843 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
26845 (defun org-cut-special ()
26846 "Cut region in table or cut current subtree.
26847 Calls `org-table-copy' or `org-cut-subtree', depending on context.
26848 See the individual commands for more information."
26849 (interactive)
26850 (call-interactively
26851 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
26853 (defun org-paste-special (arg)
26854 "Paste rectangular region into table, or past subtree relative to level.
26855 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
26856 See the individual commands for more information."
26857 (interactive "P")
26858 (if (org-at-table-p)
26859 (org-table-paste-rectangle)
26860 (org-paste-subtree arg)))
26862 (defun org-ctrl-c-ctrl-c (&optional arg)
26863 "Set tags in headline, or update according to changed information at point.
26865 This command does many different things, depending on context:
26867 - If the cursor is in a headline, prompt for tags and insert them
26868 into the current line, aligned to `org-tags-column'. When called
26869 with prefix arg, realign all tags in the current buffer.
26871 - If the cursor is in one of the special #+KEYWORD lines, this
26872 triggers scanning the buffer for these lines and updating the
26873 information.
26875 - If the cursor is inside a table, realign the table. This command
26876 works even if the automatic table editor has been turned off.
26878 - If the cursor is on a #+TBLFM line, re-apply the formulas to
26879 the entire table.
26881 - If the cursor is a the beginning of a dynamic block, update it.
26883 - If the cursor is inside a table created by the table.el package,
26884 activate that table.
26886 - If the current buffer is a remember buffer, close note and file it.
26887 with a prefix argument, file it without further interaction to the default
26888 location.
26890 - If the cursor is on a <<<target>>>, update radio targets and corresponding
26891 links in this buffer.
26893 - If the cursor is on a numbered item in a plain list, renumber the
26894 ordered list.
26896 - If the cursor is on a checkbox, toggle it."
26897 (interactive "P")
26898 (let ((org-enable-table-editor t))
26899 (cond
26900 ((or org-clock-overlays
26901 org-occur-highlights
26902 org-latex-fragment-image-overlays)
26903 (org-remove-clock-overlays)
26904 (org-remove-occur-highlights)
26905 (org-remove-latex-fragment-image-overlays)
26906 (message "Temporary highlights/overlays removed from current buffer"))
26907 ((and (local-variable-p 'org-finish-function (current-buffer))
26908 (fboundp org-finish-function))
26909 (funcall org-finish-function))
26910 ((org-at-property-p)
26911 (call-interactively 'org-property-action))
26912 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
26913 ((org-on-heading-p) (call-interactively 'org-set-tags))
26914 ((org-at-table.el-p)
26915 (require 'table)
26916 (beginning-of-line 1)
26917 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
26918 (call-interactively 'table-recognize-table))
26919 ((org-at-table-p)
26920 (org-table-maybe-eval-formula)
26921 (if arg
26922 (call-interactively 'org-table-recalculate)
26923 (org-table-maybe-recalculate-line))
26924 (call-interactively 'org-table-align))
26925 ((org-at-item-checkbox-p)
26926 (call-interactively 'org-toggle-checkbox))
26927 ((org-at-item-p)
26928 (call-interactively 'org-maybe-renumber-ordered-list))
26929 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
26930 ;; Dynamic block
26931 (beginning-of-line 1)
26932 (org-update-dblock))
26933 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
26934 (cond
26935 ((equal (match-string 1) "TBLFM")
26936 ;; Recalculate the table before this line
26937 (save-excursion
26938 (beginning-of-line 1)
26939 (skip-chars-backward " \r\n\t")
26940 (if (org-at-table-p)
26941 (org-call-with-arg 'org-table-recalculate t))))
26943 (call-interactively 'org-mode-restart))))
26944 (t (error "C-c C-c can do nothing useful at this location.")))))
26946 (defun org-mode-restart ()
26947 "Restart Org-mode, to scan again for special lines.
26948 Also updates the keyword regular expressions."
26949 (interactive)
26950 (let ((org-inhibit-startup t)) (org-mode))
26951 (message "Org-mode restarted to refresh keyword and special line setup"))
26953 (defun org-kill-note-or-show-branches ()
26954 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
26955 (interactive)
26956 (if (not org-finish-function)
26957 (call-interactively 'show-branches)
26958 (let ((org-note-abort t))
26959 (funcall org-finish-function))))
26961 (defun org-return (&optional indent)
26962 "Goto next table row or insert a newline.
26963 Calls `org-table-next-row' or `newline', depending on context.
26964 See the individual commands for more information."
26965 (interactive)
26966 (cond
26967 ((bobp) (if indent (newline-and-indent) (newline)))
26968 ((org-at-table-p)
26969 (org-table-justify-field-maybe)
26970 (call-interactively 'org-table-next-row))
26971 (t (if indent (newline-and-indent) (newline)))))
26973 (defun org-return-indent ()
26974 (interactive)
26975 "Goto next table row or insert a newline and indent.
26976 Calls `org-table-next-row' or `newline-and-indent', depending on
26977 context. See the individual commands for more information."
26978 (org-return t))
26980 (defun org-ctrl-c-minus ()
26981 "Insert separator line in table or modify bullet type in list.
26982 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
26983 depending on context."
26984 (interactive)
26985 (cond
26986 ((org-at-table-p)
26987 (call-interactively 'org-table-insert-hline))
26988 ((org-on-heading-p)
26989 ;; Convert to item
26990 (save-excursion
26991 (beginning-of-line 1)
26992 (if (looking-at "\\*+ ")
26993 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
26994 ((org-in-item-p)
26995 (call-interactively 'org-cycle-list-bullet))
26996 (t (error "`C-c -' does have no function here."))))
26998 (defun org-meta-return (&optional arg)
26999 "Insert a new heading or wrap a region in a table.
27000 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
27001 See the individual commands for more information."
27002 (interactive "P")
27003 (cond
27004 ((org-at-table-p)
27005 (call-interactively 'org-table-wrap-region))
27006 (t (call-interactively 'org-insert-heading))))
27008 ;;; Menu entries
27010 ;; Define the Org-mode menus
27011 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
27012 '("Tbl"
27013 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
27014 ["Next Field" org-cycle (org-at-table-p)]
27015 ["Previous Field" org-shifttab (org-at-table-p)]
27016 ["Next Row" org-return (org-at-table-p)]
27017 "--"
27018 ["Blank Field" org-table-blank-field (org-at-table-p)]
27019 ["Edit Field" org-table-edit-field (org-at-table-p)]
27020 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
27021 "--"
27022 ("Column"
27023 ["Move Column Left" org-metaleft (org-at-table-p)]
27024 ["Move Column Right" org-metaright (org-at-table-p)]
27025 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
27026 ["Insert Column" org-shiftmetaright (org-at-table-p)])
27027 ("Row"
27028 ["Move Row Up" org-metaup (org-at-table-p)]
27029 ["Move Row Down" org-metadown (org-at-table-p)]
27030 ["Delete Row" org-shiftmetaup (org-at-table-p)]
27031 ["Insert Row" org-shiftmetadown (org-at-table-p)]
27032 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
27033 "--"
27034 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
27035 ("Rectangle"
27036 ["Copy Rectangle" org-copy-special (org-at-table-p)]
27037 ["Cut Rectangle" org-cut-special (org-at-table-p)]
27038 ["Paste Rectangle" org-paste-special (org-at-table-p)]
27039 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
27040 "--"
27041 ("Calculate"
27042 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
27043 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
27044 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
27045 "--"
27046 ["Recalculate line" org-table-recalculate (org-at-table-p)]
27047 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
27048 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
27049 "--"
27050 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
27051 "--"
27052 ["Sum Column/Rectangle" org-table-sum
27053 (or (org-at-table-p) (org-region-active-p))]
27054 ["Which Column?" org-table-current-column (org-at-table-p)])
27055 ["Debug Formulas"
27056 org-table-toggle-formula-debugger
27057 :style toggle :selected org-table-formula-debug]
27058 ["Show Col/Row Numbers"
27059 org-table-toggle-coordinate-overlays
27060 :style toggle :selected org-table-overlay-coordinates]
27061 "--"
27062 ["Create" org-table-create (and (not (org-at-table-p))
27063 org-enable-table-editor)]
27064 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
27065 ["Import from File" org-table-import (not (org-at-table-p))]
27066 ["Export to File" org-table-export (org-at-table-p)]
27067 "--"
27068 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
27070 (easy-menu-define org-org-menu org-mode-map "Org menu"
27071 '("Org"
27072 ("Show/Hide"
27073 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
27074 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
27075 ["Sparse Tree" org-occur t]
27076 ["Reveal Context" org-reveal t]
27077 ["Show All" show-all t]
27078 "--"
27079 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
27080 "--"
27081 ["New Heading" org-insert-heading t]
27082 ("Navigate Headings"
27083 ["Up" outline-up-heading t]
27084 ["Next" outline-next-visible-heading t]
27085 ["Previous" outline-previous-visible-heading t]
27086 ["Next Same Level" outline-forward-same-level t]
27087 ["Previous Same Level" outline-backward-same-level t]
27088 "--"
27089 ["Jump" org-goto t])
27090 ("Edit Structure"
27091 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
27092 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
27093 "--"
27094 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
27095 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
27096 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
27097 "--"
27098 ["Promote Heading" org-metaleft (not (org-at-table-p))]
27099 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
27100 ["Demote Heading" org-metaright (not (org-at-table-p))]
27101 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
27102 "--"
27103 ["Sort Region/Children" org-sort (not (org-at-table-p))]
27104 "--"
27105 ["Convert to odd levels" org-convert-to-odd-levels t]
27106 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
27107 ("Editing"
27108 ["Emphasis..." org-emphasize t])
27109 ("Archive"
27110 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
27111 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
27112 ; :active t :keys "C-u C-c C-x C-a"]
27113 ["Sparse trees open ARCHIVE trees"
27114 (setq org-sparse-tree-open-archived-trees
27115 (not org-sparse-tree-open-archived-trees))
27116 :style toggle :selected org-sparse-tree-open-archived-trees]
27117 ["Cycling opens ARCHIVE trees"
27118 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
27119 :style toggle :selected org-cycle-open-archived-trees]
27120 ["Agenda includes ARCHIVE trees"
27121 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
27122 :style toggle :selected (not org-agenda-skip-archived-trees)]
27123 "--"
27124 ["Move Subtree to Archive" org-advertized-archive-subtree t]
27125 ; ["Check and Move Children" (org-archive-subtree '(4))
27126 ; :active t :keys "C-u C-c C-x C-s"]
27128 "--"
27129 ("TODO Lists"
27130 ["TODO/DONE/-" org-todo t]
27131 ("Select keyword"
27132 ["Next keyword" org-shiftright (org-on-heading-p)]
27133 ["Previous keyword" org-shiftleft (org-on-heading-p)]
27134 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
27135 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
27136 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
27137 ["Show TODO Tree" org-show-todo-tree t]
27138 ["Global TODO list" org-todo-list t]
27139 "--"
27140 ["Set Priority" org-priority t]
27141 ["Priority Up" org-shiftup t]
27142 ["Priority Down" org-shiftdown t])
27143 ("TAGS and Properties"
27144 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
27145 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
27146 "--"
27147 ["Set property" 'org-set-property t]
27148 ["Column view of properties" org-columns t]
27149 ["Insert Column View DBlock" org-insert-columns-dblock t])
27150 ("Dates and Scheduling"
27151 ["Timestamp" org-time-stamp t]
27152 ["Timestamp (inactive)" org-time-stamp-inactive t]
27153 ("Change Date"
27154 ["1 Day Later" org-shiftright t]
27155 ["1 Day Earlier" org-shiftleft t]
27156 ["1 ... Later" org-shiftup t]
27157 ["1 ... Earlier" org-shiftdown t])
27158 ["Compute Time Range" org-evaluate-time-range t]
27159 ["Schedule Item" org-schedule t]
27160 ["Deadline" org-deadline t]
27161 "--"
27162 ["Custom time format" org-toggle-time-stamp-overlays
27163 :style radio :selected org-display-custom-times]
27164 "--"
27165 ["Goto Calendar" org-goto-calendar t]
27166 ["Date from Calendar" org-date-from-calendar t])
27167 ("Logging work"
27168 ["Clock in" org-clock-in t]
27169 ["Clock out" org-clock-out t]
27170 ["Clock cancel" org-clock-cancel t]
27171 ["Goto running clock" org-clock-goto t]
27172 ["Display times" org-clock-display t]
27173 ["Create clock table" org-clock-report t]
27174 "--"
27175 ["Record DONE time"
27176 (progn (setq org-log-done (not org-log-done))
27177 (message "Switching to %s will %s record a timestamp"
27178 (car org-done-keywords)
27179 (if org-log-done "automatically" "not")))
27180 :style toggle :selected org-log-done])
27181 "--"
27182 ["Agenda Command..." org-agenda t]
27183 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
27184 ("File List for Agenda")
27185 ("Special views current file"
27186 ["TODO Tree" org-show-todo-tree t]
27187 ["Check Deadlines" org-check-deadlines t]
27188 ["Timeline" org-timeline t]
27189 ["Tags Tree" org-tags-sparse-tree t])
27190 "--"
27191 ("Hyperlinks"
27192 ["Store Link (Global)" org-store-link t]
27193 ["Insert Link" org-insert-link t]
27194 ["Follow Link" org-open-at-point t]
27195 "--"
27196 ["Next link" org-next-link t]
27197 ["Previous link" org-previous-link t]
27198 "--"
27199 ["Descriptive Links"
27200 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
27201 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
27202 ["Literal Links"
27203 (progn
27204 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
27205 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
27206 "--"
27207 ["Export/Publish..." org-export t]
27208 ("LaTeX"
27209 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
27210 :selected org-cdlatex-mode]
27211 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
27212 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
27213 ["Modify math symbol" org-cdlatex-math-modify
27214 (org-inside-LaTeX-fragment-p)]
27215 ["Export LaTeX fragments as images"
27216 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
27217 :style toggle :selected org-export-with-LaTeX-fragments])
27218 "--"
27219 ("Documentation"
27220 ["Show Version" org-version t]
27221 ["Info Documentation" org-info t])
27222 ("Customize"
27223 ["Browse Org Group" org-customize t]
27224 "--"
27225 ["Expand This Menu" org-create-customize-menu
27226 (fboundp 'customize-menu-create)])
27227 "--"
27228 ["Refresh setup" org-mode-restart t]
27231 (defun org-info (&optional node)
27232 "Read documentation for Org-mode in the info system.
27233 With optional NODE, go directly to that node."
27234 (interactive)
27235 (require 'info)
27236 (Info-goto-node (format "(org)%s" (or node ""))))
27238 (defun org-install-agenda-files-menu ()
27239 (let ((bl (buffer-list)))
27240 (save-excursion
27241 (while bl
27242 (set-buffer (pop bl))
27243 (if (org-mode-p) (setq bl nil)))
27244 (when (org-mode-p)
27245 (easy-menu-change
27246 '("Org") "File List for Agenda"
27247 (append
27248 (list
27249 ["Edit File List" (org-edit-agenda-file-list) t]
27250 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
27251 ["Remove Current File from List" org-remove-file t]
27252 ["Cycle through agenda files" org-cycle-agenda-files t]
27253 ["Occur in all agenda files" org-occur-in-agenda-files t]
27254 "--")
27255 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
27257 ;;;; Documentation
27259 (defun org-customize ()
27260 "Call the customize function with org as argument."
27261 (interactive)
27262 (customize-browse 'org))
27264 (defun org-create-customize-menu ()
27265 "Create a full customization menu for Org-mode, insert it into the menu."
27266 (interactive)
27267 (if (fboundp 'customize-menu-create)
27268 (progn
27269 (easy-menu-change
27270 '("Org") "Customize"
27271 `(["Browse Org group" org-customize t]
27272 "--"
27273 ,(customize-menu-create 'org)
27274 ["Set" Custom-set t]
27275 ["Save" Custom-save t]
27276 ["Reset to Current" Custom-reset-current t]
27277 ["Reset to Saved" Custom-reset-saved t]
27278 ["Reset to Standard Settings" Custom-reset-standard t]))
27279 (message "\"Org\"-menu now contains full customization menu"))
27280 (error "Cannot expand menu (outdated version of cus-edit.el)")))
27282 ;;;; Miscellaneous stuff
27285 ;;; Generally useful functions
27287 (defun org-context ()
27288 "Return a list of contexts of the current cursor position.
27289 If several contexts apply, all are returned.
27290 Each context entry is a list with a symbol naming the context, and
27291 two positions indicating start and end of the context. Possible
27292 contexts are:
27294 :headline anywhere in a headline
27295 :headline-stars on the leading stars in a headline
27296 :todo-keyword on a TODO keyword (including DONE) in a headline
27297 :tags on the TAGS in a headline
27298 :priority on the priority cookie in a headline
27299 :item on the first line of a plain list item
27300 :item-bullet on the bullet/number of a plain list item
27301 :checkbox on the checkbox in a plain list item
27302 :table in an org-mode table
27303 :table-special on a special filed in a table
27304 :table-table in a table.el table
27305 :link on a hyperlink
27306 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
27307 :target on a <<target>>
27308 :radio-target on a <<<radio-target>>>
27309 :latex-fragment on a LaTeX fragment
27310 :latex-preview on a LaTeX fragment with overlayed preview image
27312 This function expects the position to be visible because it uses font-lock
27313 faces as a help to recognize the following contexts: :table-special, :link,
27314 and :keyword."
27315 (let* ((f (get-text-property (point) 'face))
27316 (faces (if (listp f) f (list f)))
27317 (p (point)) clist o)
27318 ;; First the large context
27319 (cond
27320 ((org-on-heading-p t)
27321 (push (list :headline (point-at-bol) (point-at-eol)) clist)
27322 (when (progn
27323 (beginning-of-line 1)
27324 (looking-at org-todo-line-tags-regexp))
27325 (push (org-point-in-group p 1 :headline-stars) clist)
27326 (push (org-point-in-group p 2 :todo-keyword) clist)
27327 (push (org-point-in-group p 4 :tags) clist))
27328 (goto-char p)
27329 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
27330 (if (looking-at "\\[#[A-Z0-9]\\]")
27331 (push (org-point-in-group p 0 :priority) clist)))
27333 ((org-at-item-p)
27334 (push (org-point-in-group p 2 :item-bullet) clist)
27335 (push (list :item (point-at-bol)
27336 (save-excursion (org-end-of-item) (point)))
27337 clist)
27338 (and (org-at-item-checkbox-p)
27339 (push (org-point-in-group p 0 :checkbox) clist)))
27341 ((org-at-table-p)
27342 (push (list :table (org-table-begin) (org-table-end)) clist)
27343 (if (memq 'org-formula faces)
27344 (push (list :table-special
27345 (previous-single-property-change p 'face)
27346 (next-single-property-change p 'face)) clist)))
27347 ((org-at-table-p 'any)
27348 (push (list :table-table) clist)))
27349 (goto-char p)
27351 ;; Now the small context
27352 (cond
27353 ((org-at-timestamp-p)
27354 (push (org-point-in-group p 0 :timestamp) clist))
27355 ((memq 'org-link faces)
27356 (push (list :link
27357 (previous-single-property-change p 'face)
27358 (next-single-property-change p 'face)) clist))
27359 ((memq 'org-special-keyword faces)
27360 (push (list :keyword
27361 (previous-single-property-change p 'face)
27362 (next-single-property-change p 'face)) clist))
27363 ((org-on-target-p)
27364 (push (org-point-in-group p 0 :target) clist)
27365 (goto-char (1- (match-beginning 0)))
27366 (if (looking-at org-radio-target-regexp)
27367 (push (org-point-in-group p 0 :radio-target) clist))
27368 (goto-char p))
27369 ((setq o (car (delq nil
27370 (mapcar
27371 (lambda (x)
27372 (if (memq x org-latex-fragment-image-overlays) x))
27373 (org-overlays-at (point))))))
27374 (push (list :latex-fragment
27375 (org-overlay-start o) (org-overlay-end o)) clist)
27376 (push (list :latex-preview
27377 (org-overlay-start o) (org-overlay-end o)) clist))
27378 ((org-inside-LaTeX-fragment-p)
27379 ;; FIXME: positions wrong.
27380 (push (list :latex-fragment (point) (point)) clist)))
27382 (setq clist (nreverse (delq nil clist)))
27383 clist))
27385 ;; FIXME: Compare with at-regexp-p Do we need both?
27386 (defun org-in-regexp (re &optional nlines visually)
27387 "Check if point is inside a match of regexp.
27388 Normally only the current line is checked, but you can include NLINES extra
27389 lines both before and after point into the search.
27390 If VISUALLY is set, require that the cursor is not after the match but
27391 really on, so that the block visually is on the match."
27392 (catch 'exit
27393 (let ((pos (point))
27394 (eol (point-at-eol (+ 1 (or nlines 0))))
27395 (inc (if visually 1 0)))
27396 (save-excursion
27397 (beginning-of-line (- 1 (or nlines 0)))
27398 (while (re-search-forward re eol t)
27399 (if (and (<= (match-beginning 0) pos)
27400 (>= (+ inc (match-end 0)) pos))
27401 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
27403 (defun org-at-regexp-p (regexp)
27404 "Is point inside a match of REGEXP in the current line?"
27405 (catch 'exit
27406 (save-excursion
27407 (let ((pos (point)) (end (point-at-eol)))
27408 (beginning-of-line 1)
27409 (while (re-search-forward regexp end t)
27410 (if (and (<= (match-beginning 0) pos)
27411 (>= (match-end 0) pos))
27412 (throw 'exit t)))
27413 nil))))
27415 (defun org-occur-in-agenda-files (regexp &optional nlines)
27416 "Call `multi-occur' with buffers for all agenda files."
27417 (interactive "sOrg-files matching: \np")
27418 (let* ((files (org-agenda-files))
27419 (tnames (mapcar 'file-truename files))
27420 (extra org-agenda-multi-occur-extra-files)
27422 (while (setq f (pop extra))
27423 (unless (member (file-truename f) tnames)
27424 (add-to-list 'files f 'append)
27425 (add-to-list 'tnames (file-truename f) 'append)))
27426 (multi-occur
27427 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
27428 regexp)))
27430 (if (boundp 'occur-mode-find-occurrence-hook)
27431 ;; Emacs 23
27432 (add-hook 'occur-mode-find-occurrence-hook
27433 (lambda ()
27434 (when (org-mode-p)
27435 (org-reveal))))
27436 ;; Emacs 22
27437 (defadvice occur-mode-goto-occurrence
27438 (after org-occur-reveal activate)
27439 (and (org-mode-p) (org-reveal)))
27440 (defadvice occur-mode-goto-occurrence-other-window
27441 (after org-occur-reveal activate)
27442 (and (org-mode-p) (org-reveal)))
27443 (defadvice occur-mode-display-occurrence
27444 (after org-occur-reveal activate)
27445 (when (org-mode-p)
27446 (let ((pos (occur-mode-find-occurrence)))
27447 (with-current-buffer (marker-buffer pos)
27448 (save-excursion
27449 (goto-char pos)
27450 (org-reveal)))))))
27452 (defun org-uniquify (list)
27453 "Remove duplicate elements from LIST."
27454 (let (res)
27455 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
27456 res))
27458 (defun org-delete-all (elts list)
27459 "Remove all elements in ELTS from LIST."
27460 (while elts
27461 (setq list (delete (pop elts) list)))
27462 list)
27464 (defun org-back-over-empty-lines ()
27465 "Move backwards over witespace, to the beginning of the first empty line.
27466 Returns the number o empty lines passed."
27467 (let ((pos (point)))
27468 (skip-chars-backward " \t\n\r")
27469 (beginning-of-line 2)
27470 (goto-char (min (point) pos))
27471 (count-lines (point) pos)))
27473 (defun org-skip-whitespace ()
27474 (skip-chars-forward " \t\n\r"))
27476 (defun org-point-in-group (point group &optional context)
27477 "Check if POINT is in match-group GROUP.
27478 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
27479 match. If the match group does ot exist or point is not inside it,
27480 return nil."
27481 (and (match-beginning group)
27482 (>= point (match-beginning group))
27483 (<= point (match-end group))
27484 (if context
27485 (list context (match-beginning group) (match-end group))
27486 t)))
27488 (defun org-switch-to-buffer-other-window (&rest args)
27489 "Switch to buffer in a second window on the current frame.
27490 In particular, do not allow pop-up frames."
27491 (let (pop-up-frames special-display-buffer-names special-display-regexps
27492 special-display-function)
27493 (apply 'switch-to-buffer-other-window args)))
27495 (defun org-combine-plists (&rest plists)
27496 "Create a single property list from all plists in PLISTS.
27497 The process starts by copying the first list, and then setting properties
27498 from the other lists. Settings in the last list are the most significant
27499 ones and overrule settings in the other lists."
27500 (let ((rtn (copy-sequence (pop plists)))
27501 p v ls)
27502 (while plists
27503 (setq ls (pop plists))
27504 (while ls
27505 (setq p (pop ls) v (pop ls))
27506 (setq rtn (plist-put rtn p v))))
27507 rtn))
27509 (defun org-move-line-down (arg)
27510 "Move the current line down. With prefix argument, move it past ARG lines."
27511 (interactive "p")
27512 (let ((col (current-column))
27513 beg end pos)
27514 (beginning-of-line 1) (setq beg (point))
27515 (beginning-of-line 2) (setq end (point))
27516 (beginning-of-line (+ 1 arg))
27517 (setq pos (move-marker (make-marker) (point)))
27518 (insert (delete-and-extract-region beg end))
27519 (goto-char pos)
27520 (move-to-column col)))
27522 (defun org-move-line-up (arg)
27523 "Move the current line up. With prefix argument, move it past ARG lines."
27524 (interactive "p")
27525 (let ((col (current-column))
27526 beg end pos)
27527 (beginning-of-line 1) (setq beg (point))
27528 (beginning-of-line 2) (setq end (point))
27529 (beginning-of-line (- arg))
27530 (setq pos (move-marker (make-marker) (point)))
27531 (insert (delete-and-extract-region beg end))
27532 (goto-char pos)
27533 (move-to-column col)))
27535 (defun org-replace-escapes (string table)
27536 "Replace %-escapes in STRING with values in TABLE.
27537 TABLE is an association list with keys like \"%a\" and string values.
27538 The sequences in STRING may contain normal field width and padding information,
27539 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
27540 so values can contain further %-escapes if they are define later in TABLE."
27541 (let ((case-fold-search nil)
27542 e re rpl)
27543 (while (setq e (pop table))
27544 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
27545 (while (string-match re string)
27546 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
27547 (cdr e)))
27548 (setq string (replace-match rpl t t string))))
27549 string))
27552 (defun org-sublist (list start end)
27553 "Return a section of LIST, from START to END.
27554 Counting starts at 1."
27555 (let (rtn (c start))
27556 (setq list (nthcdr (1- start) list))
27557 (while (and list (<= c end))
27558 (push (pop list) rtn)
27559 (setq c (1+ c)))
27560 (nreverse rtn)))
27562 (defun org-find-base-buffer-visiting (file)
27563 "Like `find-buffer-visiting' but alway return the base buffer and
27564 not an indirect buffer"
27565 (let ((buf (find-buffer-visiting file)))
27566 (if buf
27567 (or (buffer-base-buffer buf) buf)
27568 nil)))
27570 (defun org-image-file-name-regexp ()
27571 "Return regexp matching the file names of images."
27572 (if (fboundp 'image-file-name-regexp)
27573 (image-file-name-regexp)
27574 (let ((image-file-name-extensions
27575 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
27576 "xbm" "xpm" "pbm" "pgm" "ppm")))
27577 (concat "\\."
27578 (regexp-opt (nconc (mapcar 'upcase
27579 image-file-name-extensions)
27580 image-file-name-extensions)
27582 "\\'"))))
27584 (defun org-file-image-p (file)
27585 "Return non-nil if FILE is an image."
27586 (save-match-data
27587 (string-match (org-image-file-name-regexp) file)))
27589 ;;; Paragraph filling stuff.
27590 ;; We want this to be just right, so use the full arsenal.
27592 (defun org-indent-line-function ()
27593 "Indent line like previous, but further if previous was headline or item."
27594 (interactive)
27595 (let* ((pos (point))
27596 (itemp (org-at-item-p))
27597 column bpos bcol tpos tcol bullet btype bullet-type)
27598 ;; Find the previous relevant line
27599 (beginning-of-line 1)
27600 (cond
27601 ((looking-at "#") (setq column 0))
27602 ((looking-at "\\*+ ") (setq column 0))
27604 (beginning-of-line 0)
27605 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
27606 (beginning-of-line 0))
27607 (cond
27608 ((looking-at "\\*+[ \t]+")
27609 (goto-char (match-end 0))
27610 (setq column (current-column)))
27611 ((org-in-item-p)
27612 (org-beginning-of-item)
27613 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
27614 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
27615 (setq bpos (match-beginning 1) tpos (match-end 0)
27616 bcol (progn (goto-char bpos) (current-column))
27617 tcol (progn (goto-char tpos) (current-column))
27618 bullet (match-string 1)
27619 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
27620 (if (not itemp)
27621 (setq column tcol)
27622 (goto-char pos)
27623 (beginning-of-line 1)
27624 (if (looking-at "\\S-")
27625 (progn
27626 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
27627 (setq bullet (match-string 1)
27628 btype (if (string-match "[0-9]" bullet) "n" bullet))
27629 (setq column (if (equal btype bullet-type) bcol tcol)))
27630 (setq column (org-get-indentation)))))
27631 (t (setq column (org-get-indentation))))))
27632 (goto-char pos)
27633 (if (<= (current-column) (current-indentation))
27634 (indent-line-to column)
27635 (save-excursion (indent-line-to column)))
27636 (setq column (current-column))
27637 (beginning-of-line 1)
27638 (if (looking-at
27639 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
27640 (replace-match (concat "\\1" (format org-property-format
27641 (match-string 2) (match-string 3)))
27642 t nil))
27643 (move-to-column column)))
27645 (defun org-set-autofill-regexps ()
27646 (interactive)
27647 ;; In the paragraph separator we include headlines, because filling
27648 ;; text in a line directly attached to a headline would otherwise
27649 ;; fill the headline as well.
27650 (org-set-local 'comment-start-skip "^#+[ \t]*")
27651 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
27652 ;; The paragraph starter includes hand-formatted lists.
27653 (org-set-local 'paragraph-start
27654 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
27655 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
27656 ;; But only if the user has not turned off tables or fixed-width regions
27657 (org-set-local
27658 'auto-fill-inhibit-regexp
27659 (concat "\\*+ \\|#\\+"
27660 "\\|[ \t]*" org-keyword-time-regexp
27661 (if (or org-enable-table-editor org-enable-fixed-width-editor)
27662 (concat
27663 "\\|[ \t]*["
27664 (if org-enable-table-editor "|" "")
27665 (if org-enable-fixed-width-editor ":" "")
27666 "]"))))
27667 ;; We use our own fill-paragraph function, to make sure that tables
27668 ;; and fixed-width regions are not wrapped. That function will pass
27669 ;; through to `fill-paragraph' when appropriate.
27670 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
27671 ; Adaptive filling: To get full control, first make sure that
27672 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
27673 (org-set-local 'adaptive-fill-regexp "\000")
27674 (org-set-local 'adaptive-fill-function
27675 'org-adaptive-fill-function)
27676 (org-set-local
27677 'align-mode-rules-list
27678 '((org-in-buffer-settings
27679 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
27680 (modes . '(org-mode))))))
27682 (defun org-fill-paragraph (&optional justify)
27683 "Re-align a table, pass through to fill-paragraph if no table."
27684 (let ((table-p (org-at-table-p))
27685 (table.el-p (org-at-table.el-p)))
27686 (cond ((and (equal (char-after (point-at-bol)) ?*)
27687 (save-excursion (goto-char (point-at-bol))
27688 (looking-at outline-regexp)))
27689 t) ; skip headlines
27690 (table.el-p t) ; skip table.el tables
27691 (table-p (org-table-align) t) ; align org-mode tables
27692 (t nil)))) ; call paragraph-fill
27694 ;; For reference, this is the default value of adaptive-fill-regexp
27695 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
27697 (defun org-adaptive-fill-function ()
27698 "Return a fill prefix for org-mode files.
27699 In particular, this makes sure hanging paragraphs for hand-formatted lists
27700 work correctly."
27701 (cond ((looking-at "#[ \t]+")
27702 (match-string 0))
27703 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
27704 (save-excursion
27705 (goto-char (match-end 0))
27706 (make-string (current-column) ?\ )))
27707 (t nil)))
27709 ;;;; Functions extending outline functionality
27712 (defun org-beginning-of-line (&optional arg)
27713 "Go to the beginning of the current line. If that is invisible, continue
27714 to a visible line beginning. This makes the function of C-a more intuitive.
27715 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27716 first attempt, and only move to after the tags when the cursor is already
27717 beyond the end of the headline."
27718 (interactive "P")
27719 (let ((pos (point)))
27720 (beginning-of-line 1)
27721 (if (bobp)
27723 (backward-char 1)
27724 (if (org-invisible-p)
27725 (while (and (not (bobp)) (org-invisible-p))
27726 (backward-char 1)
27727 (beginning-of-line 1))
27728 (forward-char 1)))
27729 (when org-special-ctrl-a/e
27730 (cond
27731 ((and (looking-at org-todo-line-regexp)
27732 (= (char-after (match-end 1)) ?\ ))
27733 (goto-char
27734 (if (eq org-special-ctrl-a/e t)
27735 (cond ((> pos (match-beginning 3)) (match-beginning 3))
27736 ((= pos (point)) (match-beginning 3))
27737 (t (point)))
27738 (cond ((> pos (point)) (point))
27739 ((not (eq last-command this-command)) (point))
27740 (t (match-beginning 3))))))
27741 ((org-at-item-p)
27742 (goto-char
27743 (if (eq org-special-ctrl-a/e t)
27744 (cond ((> pos (match-end 4)) (match-end 4))
27745 ((= pos (point)) (match-end 4))
27746 (t (point)))
27747 (cond ((> pos (point)) (point))
27748 ((not (eq last-command this-command)) (point))
27749 (t (match-end 4))))))))))
27751 (defun org-end-of-line (&optional arg)
27752 "Go to the end of the line.
27753 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27754 first attempt, and only move to after the tags when the cursor is already
27755 beyond the end of the headline."
27756 (interactive "P")
27757 (if (or (not org-special-ctrl-a/e)
27758 (not (org-on-heading-p)))
27759 (end-of-line arg)
27760 (let ((pos (point)))
27761 (beginning-of-line 1)
27762 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
27763 (if (eq org-special-ctrl-a/e t)
27764 (if (or (< pos (match-beginning 1))
27765 (= pos (match-end 0)))
27766 (goto-char (match-beginning 1))
27767 (goto-char (match-end 0)))
27768 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
27769 (goto-char (match-end 0))
27770 (goto-char (match-beginning 1))))
27771 (end-of-line arg)))))
27773 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
27774 (define-key org-mode-map "\C-e" 'org-end-of-line)
27776 (defun org-kill-line (&optional arg)
27777 "Kill line, to tags or end of line."
27778 (interactive "P")
27779 (cond
27780 ((or (not org-special-ctrl-k)
27781 (bolp)
27782 (not (org-on-heading-p)))
27783 (call-interactively 'kill-line))
27784 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
27785 (kill-region (point) (match-beginning 1))
27786 (org-set-tags nil t))
27787 (t (kill-region (point) (point-at-eol)))))
27789 (define-key org-mode-map "\C-k" 'org-kill-line)
27791 (defun org-invisible-p ()
27792 "Check if point is at a character currently not visible."
27793 ;; Early versions of noutline don't have `outline-invisible-p'.
27794 (if (fboundp 'outline-invisible-p)
27795 (outline-invisible-p)
27796 (get-char-property (point) 'invisible)))
27798 (defun org-invisible-p2 ()
27799 "Check if point is at a character currently not visible."
27800 (save-excursion
27801 (if (and (eolp) (not (bobp))) (backward-char 1))
27802 ;; Early versions of noutline don't have `outline-invisible-p'.
27803 (if (fboundp 'outline-invisible-p)
27804 (outline-invisible-p)
27805 (get-char-property (point) 'invisible))))
27807 (defalias 'org-back-to-heading 'outline-back-to-heading)
27808 (defalias 'org-on-heading-p 'outline-on-heading-p)
27809 (defalias 'org-at-heading-p 'outline-on-heading-p)
27810 (defun org-at-heading-or-item-p ()
27811 (or (org-on-heading-p) (org-at-item-p)))
27813 (defun org-on-target-p ()
27814 (or (org-in-regexp org-radio-target-regexp)
27815 (org-in-regexp org-target-regexp)))
27817 (defun org-up-heading-all (arg)
27818 "Move to the heading line of which the present line is a subheading.
27819 This function considers both visible and invisible heading lines.
27820 With argument, move up ARG levels."
27821 (if (fboundp 'outline-up-heading-all)
27822 (outline-up-heading-all arg) ; emacs 21 version of outline.el
27823 (outline-up-heading arg t))) ; emacs 22 version of outline.el
27825 (defun org-up-heading-safe ()
27826 "Move to the heading line of which the present line is a subheading.
27827 This version will not throw an error. It will return the level of the
27828 headline found, or nil if no higher level is found."
27829 (let ((pos (point)) start-level level
27830 (re (concat "^" outline-regexp)))
27831 (catch 'exit
27832 (outline-back-to-heading t)
27833 (setq start-level (funcall outline-level))
27834 (if (equal start-level 1) (throw 'exit nil))
27835 (while (re-search-backward re nil t)
27836 (setq level (funcall outline-level))
27837 (if (< level start-level) (throw 'exit level)))
27838 nil)))
27840 (defun org-first-sibling-p ()
27841 "Is this heading the first child of its parents?"
27842 (interactive)
27843 (let ((re (concat "^" outline-regexp))
27844 level l)
27845 (unless (org-at-heading-p t)
27846 (error "Not at a heading"))
27847 (setq level (funcall outline-level))
27848 (save-excursion
27849 (if (not (re-search-backward re nil t))
27851 (setq l (funcall outline-level))
27852 (< l level)))))
27854 (defun org-goto-sibling (&optional previous)
27855 "Goto the next sibling, even if it is invisible.
27856 When PREVIOUS is set, go to the previous sibling instead. Returns t
27857 when a sibling was found. When none is found, return nil and don't
27858 move point."
27859 (let ((fun (if previous 're-search-backward 're-search-forward))
27860 (pos (point))
27861 (re (concat "^" outline-regexp))
27862 level l)
27863 (when (condition-case nil (org-back-to-heading t) (error nil))
27864 (setq level (funcall outline-level))
27865 (catch 'exit
27866 (or previous (forward-char 1))
27867 (while (funcall fun re nil t)
27868 (setq l (funcall outline-level))
27869 (when (< l level) (goto-char pos) (throw 'exit nil))
27870 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
27871 (goto-char pos)
27872 nil))))
27874 (defun org-show-siblings ()
27875 "Show all siblings of the current headline."
27876 (save-excursion
27877 (while (org-goto-sibling) (org-flag-heading nil)))
27878 (save-excursion
27879 (while (org-goto-sibling 'previous)
27880 (org-flag-heading nil))))
27882 (defun org-show-hidden-entry ()
27883 "Show an entry where even the heading is hidden."
27884 (save-excursion
27885 (org-show-entry)))
27887 (defun org-flag-heading (flag &optional entry)
27888 "Flag the current heading. FLAG non-nil means make invisible.
27889 When ENTRY is non-nil, show the entire entry."
27890 (save-excursion
27891 (org-back-to-heading t)
27892 ;; Check if we should show the entire entry
27893 (if entry
27894 (progn
27895 (org-show-entry)
27896 (save-excursion
27897 (and (outline-next-heading)
27898 (org-flag-heading nil))))
27899 (outline-flag-region (max (point-min) (1- (point)))
27900 (save-excursion (outline-end-of-heading) (point))
27901 flag))))
27903 (defun org-end-of-subtree (&optional invisible-OK to-heading)
27904 ;; This is an exact copy of the original function, but it uses
27905 ;; `org-back-to-heading', to make it work also in invisible
27906 ;; trees. And is uses an invisible-OK argument.
27907 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
27908 (org-back-to-heading invisible-OK)
27909 (let ((first t)
27910 (level (funcall outline-level)))
27911 (while (and (not (eobp))
27912 (or first (> (funcall outline-level) level)))
27913 (setq first nil)
27914 (outline-next-heading))
27915 (unless to-heading
27916 (if (memq (preceding-char) '(?\n ?\^M))
27917 (progn
27918 ;; Go to end of line before heading
27919 (forward-char -1)
27920 (if (memq (preceding-char) '(?\n ?\^M))
27921 ;; leave blank line before heading
27922 (forward-char -1))))))
27923 (point))
27925 (defun org-show-subtree ()
27926 "Show everything after this heading at deeper levels."
27927 (outline-flag-region
27928 (point)
27929 (save-excursion
27930 (outline-end-of-subtree) (outline-next-heading) (point))
27931 nil))
27933 (defun org-show-entry ()
27934 "Show the body directly following this heading.
27935 Show the heading too, if it is currently invisible."
27936 (interactive)
27937 (save-excursion
27938 (condition-case nil
27939 (progn
27940 (org-back-to-heading t)
27941 (outline-flag-region
27942 (max (point-min) (1- (point)))
27943 (save-excursion
27944 (re-search-forward
27945 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
27946 (or (match-beginning 1) (point-max)))
27947 nil))
27948 (error nil))))
27950 (defun org-make-options-regexp (kwds)
27951 "Make a regular expression for keyword lines."
27952 (concat
27954 "#?[ \t]*\\+\\("
27955 (mapconcat 'regexp-quote kwds "\\|")
27956 "\\):[ \t]*"
27957 "\\(.+\\)"))
27959 ;; Make isearch reveal the necessary context
27960 (defun org-isearch-end ()
27961 "Reveal context after isearch exits."
27962 (when isearch-success ; only if search was successful
27963 (if (featurep 'xemacs)
27964 ;; Under XEmacs, the hook is run in the correct place,
27965 ;; we directly show the context.
27966 (org-show-context 'isearch)
27967 ;; In Emacs the hook runs *before* restoring the overlays.
27968 ;; So we have to use a one-time post-command-hook to do this.
27969 ;; (Emacs 22 has a special variable, see function `org-mode')
27970 (unless (and (boundp 'isearch-mode-end-hook-quit)
27971 isearch-mode-end-hook-quit)
27972 ;; Only when the isearch was not quitted.
27973 (org-add-hook 'post-command-hook 'org-isearch-post-command
27974 'append 'local)))))
27976 (defun org-isearch-post-command ()
27977 "Remove self from hook, and show context."
27978 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
27979 (org-show-context 'isearch))
27982 ;;;; Integration with and fixes for other packages
27984 ;;; Imenu support
27986 (defvar org-imenu-markers nil
27987 "All markers currently used by Imenu.")
27988 (make-variable-buffer-local 'org-imenu-markers)
27990 (defun org-imenu-new-marker (&optional pos)
27991 "Return a new marker for use by Imenu, and remember the marker."
27992 (let ((m (make-marker)))
27993 (move-marker m (or pos (point)))
27994 (push m org-imenu-markers)
27997 (defun org-imenu-get-tree ()
27998 "Produce the index for Imenu."
27999 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
28000 (setq org-imenu-markers nil)
28001 (let* ((n org-imenu-depth)
28002 (re (concat "^" outline-regexp))
28003 (subs (make-vector (1+ n) nil))
28004 (last-level 0)
28005 m tree level head)
28006 (save-excursion
28007 (save-restriction
28008 (widen)
28009 (goto-char (point-max))
28010 (while (re-search-backward re nil t)
28011 (setq level (org-reduced-level (funcall outline-level)))
28012 (when (<= level n)
28013 (looking-at org-complex-heading-regexp)
28014 (setq head (org-match-string-no-properties 4)
28015 m (org-imenu-new-marker))
28016 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
28017 (if (>= level last-level)
28018 (push (cons head m) (aref subs level))
28019 (push (cons head (aref subs (1+ level))) (aref subs level))
28020 (loop for i from (1+ level) to n do (aset subs i nil)))
28021 (setq last-level level)))))
28022 (aref subs 1)))
28024 (eval-after-load "imenu"
28025 '(progn
28026 (add-hook 'imenu-after-jump-hook
28027 (lambda () (org-show-context 'org-goto)))))
28029 ;; Speedbar support
28031 (defun org-speedbar-set-agenda-restriction ()
28032 "Restrict future agenda commands to the location at point in speedbar.
28033 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
28034 (interactive)
28035 (let (p m tp np dir txt w)
28036 (cond
28037 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28038 'org-imenu t))
28039 (setq m (get-text-property p 'org-imenu-marker))
28040 (save-excursion
28041 (save-restriction
28042 (set-buffer (marker-buffer m))
28043 (goto-char m)
28044 (org-agenda-set-restriction-lock 'subtree))))
28045 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28046 'speedbar-function 'speedbar-find-file))
28047 (setq tp (previous-single-property-change
28048 (1+ p) 'speedbar-function)
28049 np (next-single-property-change
28050 tp 'speedbar-function)
28051 dir (speedbar-line-directory)
28052 txt (buffer-substring-no-properties (or tp (point-min))
28053 (or np (point-max))))
28054 (save-excursion
28055 (save-restriction
28056 (set-buffer (find-file-noselect
28057 (let ((default-directory dir))
28058 (expand-file-name txt))))
28059 (unless (org-mode-p)
28060 (error "Cannot restrict to non-Org-mode file"))
28061 (org-agenda-set-restriction-lock 'file))))
28062 (t (error "Don't know how to restrict Org-mode's agenda")))
28063 (org-move-overlay org-speedbar-restriction-lock-overlay
28064 (point-at-bol) (point-at-eol))
28065 (setq current-prefix-arg nil)
28066 (org-agenda-maybe-redo)))
28068 (eval-after-load "speedbar"
28069 '(progn
28070 (speedbar-add-supported-extension ".org")
28071 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
28072 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
28073 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
28074 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
28075 (add-hook 'speedbar-visiting-tag-hook
28076 (lambda () (org-show-context 'org-goto)))))
28079 ;;; Fixes and Hacks
28081 ;; Make flyspell not check words in links, to not mess up our keymap
28082 (defun org-mode-flyspell-verify ()
28083 "Don't let flyspell put overlays at active buttons."
28084 (not (get-text-property (point) 'keymap)))
28086 ;; Make `bookmark-jump' show the jump location if it was hidden.
28087 (eval-after-load "bookmark"
28088 '(if (boundp 'bookmark-after-jump-hook)
28089 ;; We can use the hook
28090 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
28091 ;; Hook not available, use advice
28092 (defadvice bookmark-jump (after org-make-visible activate)
28093 "Make the position visible."
28094 (org-bookmark-jump-unhide))))
28096 (defun org-bookmark-jump-unhide ()
28097 "Unhide the current position, to show the bookmark location."
28098 (and (org-mode-p)
28099 (or (org-invisible-p)
28100 (save-excursion (goto-char (max (point-min) (1- (point))))
28101 (org-invisible-p)))
28102 (org-show-context 'bookmark-jump)))
28104 ;; Fix a bug in htmlize where there are text properties (face nil)
28105 (eval-after-load "htmlize"
28106 '(progn
28107 (defadvice htmlize-faces-in-buffer (after org-no-nil-faces activate)
28108 "Make sure there are no nil faces"
28109 (setq ad-return-value (delq nil ad-return-value)))))
28111 ;; Make session.el ignore our circular variable
28112 (eval-after-load "session"
28113 '(add-to-list 'session-globals-exclude 'org-mark-ring))
28115 ;;;; Experimental code
28117 (defun org-closed-in-range ()
28118 "Sparse tree of items closed in a certain time range.
28119 Still experimental, may disappear in the future."
28120 (interactive)
28121 ;; Get the time interval from the user.
28122 (let* ((time1 (time-to-seconds
28123 (org-read-date nil 'to-time nil "Starting date: ")))
28124 (time2 (time-to-seconds
28125 (org-read-date nil 'to-time nil "End date:")))
28126 ;; callback function
28127 (callback (lambda ()
28128 (let ((time
28129 (time-to-seconds
28130 (apply 'encode-time
28131 (org-parse-time-string
28132 (match-string 1))))))
28133 ;; check if time in interval
28134 (and (>= time time1) (<= time time2))))))
28135 ;; make tree, check each match with the callback
28136 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
28138 ;;;; Finish up
28140 (provide 'org)
28142 (run-hooks 'org-load-hook)
28144 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
28145 ;;; org.el ends here