Reverted Addition to ChangeLog
[org-mode.git] / org.el
blobd42b1b2dddb5d1cafc2a31e4445bf7eb1be3711c
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.20a
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.20a"
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 (debug)
7007 (save-excursion
7008 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
7009 (beg (condition-case nil
7010 (progn (outline-back-to-heading) (point))
7011 (error (point-min))))
7012 (end (move-marker (make-marker)
7013 (progn (outline-next-heading) (point))))
7014 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
7015 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
7016 (re-find (concat re "\\|" re-box))
7017 beg-cookie end-cookie is-percent c-on c-off lim
7018 eline curr-ind next-ind continue-from startsearch
7019 (cstat 0)
7021 (when all
7022 (goto-char (point-min))
7023 (outline-next-heading)
7024 (setq beg (point) end (point-max)))
7025 (goto-char end)
7026 ;; find each statistic cookie
7027 (while (re-search-backward re-find beg t)
7028 (setq beg-cookie (match-beginning 1)
7029 end-cookie (match-end 1)
7030 cstat (+ cstat (if end-cookie 1 0))
7031 startsearch (point-at-eol)
7032 continue-from (point-at-bol)
7033 is-percent (match-beginning 2)
7034 lim (cond
7035 ((org-on-heading-p) (outline-next-heading) (point))
7036 ((org-at-item-p) (org-end-of-item) (point))
7037 (t nil))
7038 c-on 0
7039 c-off 0)
7040 (when lim
7041 ;; find first checkbox for this cookie and gather
7042 ;; statistics from all that are at this indentation level
7043 (goto-char startsearch)
7044 (if (re-search-forward re-box lim t)
7045 (progn
7046 (org-beginning-of-item)
7047 (setq curr-ind (org-get-indentation))
7048 (setq next-ind curr-ind)
7049 (while (= curr-ind next-ind)
7050 (save-excursion (end-of-line) (setq eline (point)))
7051 (if (re-search-forward re-box eline t)
7052 (if (member (match-string 2) '("[ ]" "[-]"))
7053 (setq c-off (1+ c-off))
7054 (setq c-on (1+ c-on))
7057 (org-end-of-item)
7058 (setq next-ind (org-get-indentation))
7060 (goto-char continue-from)
7061 ;; update cookie
7062 (when end-cookie
7063 (delete-region beg-cookie end-cookie)
7064 (goto-char beg-cookie)
7065 (insert
7066 (if is-percent
7067 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
7068 (format "[%d/%d]" c-on (+ c-on c-off)))))
7069 ;; update items checkbox if it has one
7070 (when (org-at-item-p)
7071 (org-beginning-of-item)
7072 (when (and (> (+ c-on c-off) 0)
7073 (re-search-forward re-box (point-at-eol) t))
7074 (setq beg-cookie (match-beginning 2)
7075 end-cookie (match-end 2))
7076 (delete-region beg-cookie end-cookie)
7077 (goto-char beg-cookie)
7078 (cond ((= c-off 0) (insert "[X]"))
7079 ((= c-on 0) (insert "[ ]"))
7080 (t (insert "[-]")))
7082 (goto-char continue-from))
7083 (when (interactive-p)
7084 (message "Checkbox satistics updated %s (%d places)"
7085 (if all "in entire file" "in current outline entry") cstat)))))
7087 (defun org-get-checkbox-statistics-face ()
7088 "Select the face for checkbox statistics.
7089 The face will be `org-done' when all relevant boxes are checked. Otherwise
7090 it will be `org-todo'."
7091 (if (match-end 1)
7092 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
7093 (if (and (> (match-end 2) (match-beginning 2))
7094 (equal (match-string 2) (match-string 3)))
7095 'org-done
7096 'org-todo)))
7098 (defun org-get-indentation (&optional line)
7099 "Get the indentation of the current line, interpreting tabs.
7100 When LINE is given, assume it represents a line and compute its indentation."
7101 (if line
7102 (if (string-match "^ *" (org-remove-tabs line))
7103 (match-end 0))
7104 (save-excursion
7105 (beginning-of-line 1)
7106 (skip-chars-forward " \t")
7107 (current-column))))
7109 (defun org-remove-tabs (s &optional width)
7110 "Replace tabulators in S with spaces.
7111 Assumes that s is a single line, starting in column 0."
7112 (setq width (or width tab-width))
7113 (while (string-match "\t" s)
7114 (setq s (replace-match
7115 (make-string
7116 (- (* width (/ (+ (match-beginning 0) width) width))
7117 (match-beginning 0)) ?\ )
7118 t t s)))
7121 (defun org-fix-indentation (line ind)
7122 "Fix indentation in LINE.
7123 IND is a cons cell with target and minimum indentation.
7124 If the current indenation in LINE is smaller than the minimum,
7125 leave it alone. If it is larger than ind, set it to the target."
7126 (let* ((l (org-remove-tabs line))
7127 (i (org-get-indentation l))
7128 (i1 (car ind)) (i2 (cdr ind)))
7129 (if (>= i i2) (setq l (substring line i2)))
7130 (if (> i1 0)
7131 (concat (make-string i1 ?\ ) l)
7132 l)))
7134 (defcustom org-empty-line-terminates-plain-lists nil
7135 "Non-nil means, an empty line ends all plain list levels.
7136 When nil, empty lines are part of the preceeding item."
7137 :group 'org-plain-lists
7138 :type 'boolean)
7140 (defun org-beginning-of-item ()
7141 "Go to the beginning of the current hand-formatted item.
7142 If the cursor is not in an item, throw an error."
7143 (interactive)
7144 (let ((pos (point))
7145 (limit (save-excursion
7146 (condition-case nil
7147 (progn
7148 (org-back-to-heading)
7149 (beginning-of-line 2) (point))
7150 (error (point-min)))))
7151 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7152 ind ind1)
7153 (if (org-at-item-p)
7154 (beginning-of-line 1)
7155 (beginning-of-line 1)
7156 (skip-chars-forward " \t")
7157 (setq ind (current-column))
7158 (if (catch 'exit
7159 (while t
7160 (beginning-of-line 0)
7161 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
7163 (if (looking-at "[ \t]*$")
7164 (setq ind1 ind-empty)
7165 (skip-chars-forward " \t")
7166 (setq ind1 (current-column)))
7167 (if (< ind1 ind)
7168 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
7170 (goto-char pos)
7171 (error "Not in an item")))))
7173 (defun org-end-of-item ()
7174 "Go to the end of the current hand-formatted item.
7175 If the cursor is not in an item, throw an error."
7176 (interactive)
7177 (let* ((pos (point))
7178 ind1
7179 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7180 (limit (save-excursion (outline-next-heading) (point)))
7181 (ind (save-excursion
7182 (org-beginning-of-item)
7183 (skip-chars-forward " \t")
7184 (current-column)))
7185 (end (catch 'exit
7186 (while t
7187 (beginning-of-line 2)
7188 (if (eobp) (throw 'exit (point)))
7189 (if (>= (point) limit) (throw 'exit (point-at-bol)))
7190 (if (looking-at "[ \t]*$")
7191 (setq ind1 ind-empty)
7192 (skip-chars-forward " \t")
7193 (setq ind1 (current-column)))
7194 (if (<= ind1 ind)
7195 (throw 'exit (point-at-bol)))))))
7196 (if end
7197 (goto-char end)
7198 (goto-char pos)
7199 (error "Not in an item"))))
7201 (defun org-next-item ()
7202 "Move to the beginning of the next item in the current plain list.
7203 Error if not at a plain list, or if this is the last item in the list."
7204 (interactive)
7205 (let (ind ind1 (pos (point)))
7206 (org-beginning-of-item)
7207 (setq ind (org-get-indentation))
7208 (org-end-of-item)
7209 (setq ind1 (org-get-indentation))
7210 (unless (and (org-at-item-p) (= ind ind1))
7211 (goto-char pos)
7212 (error "On last item"))))
7214 (defun org-previous-item ()
7215 "Move to the beginning of the previous item in the current plain list.
7216 Error if not at a plain list, or if this is the first item in the list."
7217 (interactive)
7218 (let (beg ind ind1 (pos (point)))
7219 (org-beginning-of-item)
7220 (setq beg (point))
7221 (setq ind (org-get-indentation))
7222 (goto-char beg)
7223 (catch 'exit
7224 (while t
7225 (beginning-of-line 0)
7226 (if (looking-at "[ \t]*$")
7228 (if (<= (setq ind1 (org-get-indentation)) ind)
7229 (throw 'exit t)))))
7230 (condition-case nil
7231 (if (or (not (org-at-item-p))
7232 (< ind1 (1- ind)))
7233 (error "")
7234 (org-beginning-of-item))
7235 (error (goto-char pos)
7236 (error "On first item")))))
7238 (defun org-first-list-item-p ()
7239 "Is this heading the item in a plain list?"
7240 (unless (org-at-item-p)
7241 (error "Not at a plain list item"))
7242 (org-beginning-of-item)
7243 (= (point) (save-excursion (org-beginning-of-item-list))))
7245 (defun org-move-item-down ()
7246 "Move the plain list item at point down, i.e. swap with following item.
7247 Subitems (items with larger indentation) are considered part of the item,
7248 so this really moves item trees."
7249 (interactive)
7250 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
7251 (org-beginning-of-item)
7252 (setq beg0 (point))
7253 (save-excursion
7254 (setq ne-beg (org-back-over-empty-lines))
7255 (setq beg (point)))
7256 (goto-char beg0)
7257 (setq ind (org-get-indentation))
7258 (org-end-of-item)
7259 (setq end0 (point))
7260 (setq ind1 (org-get-indentation))
7261 (setq ne-end (org-back-over-empty-lines))
7262 (setq end (point))
7263 (goto-char beg0)
7264 (when (and (org-first-list-item-p) (< ne-end ne-beg))
7265 ;; include less whitespace
7266 (save-excursion
7267 (goto-char beg)
7268 (forward-line (- ne-beg ne-end))
7269 (setq beg (point))))
7270 (goto-char end0)
7271 (if (and (org-at-item-p) (= ind ind1))
7272 (progn
7273 (org-end-of-item)
7274 (org-back-over-empty-lines)
7275 (setq txt (buffer-substring beg end))
7276 (save-excursion
7277 (delete-region beg end))
7278 (setq pos (point))
7279 (insert txt)
7280 (goto-char pos) (org-skip-whitespace)
7281 (org-maybe-renumber-ordered-list))
7282 (goto-char pos)
7283 (error "Cannot move this item further down"))))
7285 (defun org-move-item-up (arg)
7286 "Move the plain list item at point up, i.e. swap with previous item.
7287 Subitems (items with larger indentation) are considered part of the item,
7288 so this really moves item trees."
7289 (interactive "p")
7290 (let (beg beg0 end end0 ind ind1 (pos (point)) txt
7291 ne-beg ne-end ne-ins ins-end)
7292 (org-beginning-of-item)
7293 (setq beg0 (point))
7294 (setq ind (org-get-indentation))
7295 (save-excursion
7296 (setq ne-beg (org-back-over-empty-lines))
7297 (setq beg (point)))
7298 (goto-char beg0)
7299 (org-end-of-item)
7300 (setq ne-end (org-back-over-empty-lines))
7301 (setq end (point))
7302 (goto-char beg0)
7303 (catch 'exit
7304 (while t
7305 (beginning-of-line 0)
7306 (if (looking-at "[ \t]*$")
7307 (if org-empty-line-terminates-plain-lists
7308 (progn
7309 (goto-char pos)
7310 (error "Cannot move this item further up"))
7311 nil)
7312 (if (<= (setq ind1 (org-get-indentation)) ind)
7313 (throw 'exit t)))))
7314 (condition-case nil
7315 (org-beginning-of-item)
7316 (error (goto-char beg)
7317 (error "Cannot move this item further up")))
7318 (setq ind1 (org-get-indentation))
7319 (if (and (org-at-item-p) (= ind ind1))
7320 (progn
7321 (setq ne-ins (org-back-over-empty-lines))
7322 (setq txt (buffer-substring beg end))
7323 (save-excursion
7324 (delete-region beg end))
7325 (setq pos (point))
7326 (insert txt)
7327 (setq ins-end (point))
7328 (goto-char pos) (org-skip-whitespace)
7330 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
7331 ;; Move whitespace back to beginning
7332 (save-excursion
7333 (goto-char ins-end)
7334 (let ((kill-whole-line t))
7335 (kill-line (- ne-ins ne-beg)) (point)))
7336 (insert (make-string (- ne-ins ne-beg) ?\n)))
7338 (org-maybe-renumber-ordered-list))
7339 (goto-char pos)
7340 (error "Cannot move this item further up"))))
7342 (defun org-maybe-renumber-ordered-list ()
7343 "Renumber the ordered list at point if setup allows it.
7344 This tests the user option `org-auto-renumber-ordered-lists' before
7345 doing the renumbering."
7346 (interactive)
7347 (when (and org-auto-renumber-ordered-lists
7348 (org-at-item-p))
7349 (if (match-beginning 3)
7350 (org-renumber-ordered-list 1)
7351 (org-fix-bullet-type))))
7353 (defun org-maybe-renumber-ordered-list-safe ()
7354 (condition-case nil
7355 (save-excursion
7356 (org-maybe-renumber-ordered-list))
7357 (error nil)))
7359 (defun org-cycle-list-bullet (&optional which)
7360 "Cycle through the different itemize/enumerate bullets.
7361 This cycle the entire list level through the sequence:
7363 `-' -> `+' -> `*' -> `1.' -> `1)'
7365 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7366 0 meand `-', 1 means `+' etc."
7367 (interactive "P")
7368 (org-preserve-lc
7369 (org-beginning-of-item-list)
7370 (org-at-item-p)
7371 (beginning-of-line 1)
7372 (let ((current (match-string 0))
7373 (prevp (eq which 'previous))
7374 new)
7375 (setq new (cond
7376 ((and (numberp which)
7377 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7378 ((string-match "-" current) (if prevp "1)" "+"))
7379 ((string-match "\\+" current)
7380 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7381 ((string-match "\\*" current) (if prevp "+" "1."))
7382 ((string-match "\\." current) (if prevp "*" "1)"))
7383 ((string-match ")" current) (if prevp "1." "-"))
7384 (t (error "This should not happen"))))
7385 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7386 (org-fix-bullet-type)
7387 (org-maybe-renumber-ordered-list))))
7389 (defun org-get-string-indentation (s)
7390 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7391 (let ((n -1) (i 0) (w tab-width) c)
7392 (catch 'exit
7393 (while (< (setq n (1+ n)) (length s))
7394 (setq c (aref s n))
7395 (cond ((= c ?\ ) (setq i (1+ i)))
7396 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7397 (t (throw 'exit t)))))
7400 (defun org-renumber-ordered-list (arg)
7401 "Renumber an ordered plain list.
7402 Cursor needs to be in the first line of an item, the line that starts
7403 with something like \"1.\" or \"2)\"."
7404 (interactive "p")
7405 (unless (and (org-at-item-p)
7406 (match-beginning 3))
7407 (error "This is not an ordered list"))
7408 (let ((line (org-current-line))
7409 (col (current-column))
7410 (ind (org-get-string-indentation
7411 (buffer-substring (point-at-bol) (match-beginning 3))))
7412 ;; (term (substring (match-string 3) -1))
7413 ind1 (n (1- arg))
7414 fmt)
7415 ;; find where this list begins
7416 (org-beginning-of-item-list)
7417 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7418 (setq fmt (concat "%d" (match-string 1)))
7419 (beginning-of-line 0)
7420 ;; walk forward and replace these numbers
7421 (catch 'exit
7422 (while t
7423 (catch 'next
7424 (beginning-of-line 2)
7425 (if (eobp) (throw 'exit nil))
7426 (if (looking-at "[ \t]*$") (throw 'next nil))
7427 (skip-chars-forward " \t") (setq ind1 (current-column))
7428 (if (> ind1 ind) (throw 'next t))
7429 (if (< ind1 ind) (throw 'exit t))
7430 (if (not (org-at-item-p)) (throw 'exit nil))
7431 (delete-region (match-beginning 2) (match-end 2))
7432 (goto-char (match-beginning 2))
7433 (insert (format fmt (setq n (1+ n)))))))
7434 (goto-line line)
7435 (move-to-column col)))
7437 (defun org-fix-bullet-type ()
7438 "Make sure all items in this list have the same bullet as the firsst item."
7439 (interactive)
7440 (unless (org-at-item-p) (error "This is not a list"))
7441 (let ((line (org-current-line))
7442 (col (current-column))
7443 (ind (current-indentation))
7444 ind1 bullet)
7445 ;; find where this list begins
7446 (org-beginning-of-item-list)
7447 (beginning-of-line 1)
7448 ;; find out what the bullet type is
7449 (looking-at "[ \t]*\\(\\S-+\\)")
7450 (setq bullet (match-string 1))
7451 ;; walk forward and replace these numbers
7452 (beginning-of-line 0)
7453 (catch 'exit
7454 (while t
7455 (catch 'next
7456 (beginning-of-line 2)
7457 (if (eobp) (throw 'exit nil))
7458 (if (looking-at "[ \t]*$") (throw 'next nil))
7459 (skip-chars-forward " \t") (setq ind1 (current-column))
7460 (if (> ind1 ind) (throw 'next t))
7461 (if (< ind1 ind) (throw 'exit t))
7462 (if (not (org-at-item-p)) (throw 'exit nil))
7463 (skip-chars-forward " \t")
7464 (looking-at "\\S-+")
7465 (replace-match bullet))))
7466 (goto-line line)
7467 (move-to-column col)
7468 (if (string-match "[0-9]" bullet)
7469 (org-renumber-ordered-list 1))))
7471 (defun org-beginning-of-item-list ()
7472 "Go to the beginning of the current item list.
7473 I.e. to the first item in this list."
7474 (interactive)
7475 (org-beginning-of-item)
7476 (let ((pos (point-at-bol))
7477 (ind (org-get-indentation))
7478 ind1)
7479 ;; find where this list begins
7480 (catch 'exit
7481 (while t
7482 (catch 'next
7483 (beginning-of-line 0)
7484 (if (looking-at "[ \t]*$")
7485 (throw (if (bobp) 'exit 'next) t))
7486 (skip-chars-forward " \t") (setq ind1 (current-column))
7487 (if (or (< ind1 ind)
7488 (and (= ind1 ind)
7489 (not (org-at-item-p)))
7490 (bobp))
7491 (throw 'exit t)
7492 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7493 (goto-char pos)))
7496 (defun org-end-of-item-list ()
7497 "Go to the end of the current item list.
7498 I.e. to the text after the last item."
7499 (interactive)
7500 (org-beginning-of-item)
7501 (let ((pos (point-at-bol))
7502 (ind (org-get-indentation))
7503 ind1)
7504 ;; find where this list begins
7505 (catch 'exit
7506 (while t
7507 (catch 'next
7508 (beginning-of-line 2)
7509 (if (looking-at "[ \t]*$")
7510 (throw (if (eobp) 'exit 'next) t))
7511 (skip-chars-forward " \t") (setq ind1 (current-column))
7512 (if (or (< ind1 ind)
7513 (and (= ind1 ind)
7514 (not (org-at-item-p)))
7515 (eobp))
7516 (progn
7517 (setq pos (point-at-bol))
7518 (throw 'exit t))))))
7519 (goto-char pos)))
7522 (defvar org-last-indent-begin-marker (make-marker))
7523 (defvar org-last-indent-end-marker (make-marker))
7525 (defun org-outdent-item (arg)
7526 "Outdent a local list item."
7527 (interactive "p")
7528 (org-indent-item (- arg)))
7530 (defun org-indent-item (arg)
7531 "Indent a local list item."
7532 (interactive "p")
7533 (unless (org-at-item-p)
7534 (error "Not on an item"))
7535 (save-excursion
7536 (let (beg end ind ind1 tmp delta ind-down ind-up)
7537 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7538 (setq beg org-last-indent-begin-marker
7539 end org-last-indent-end-marker)
7540 (org-beginning-of-item)
7541 (setq beg (move-marker org-last-indent-begin-marker (point)))
7542 (org-end-of-item)
7543 (setq end (move-marker org-last-indent-end-marker (point))))
7544 (goto-char beg)
7545 (setq tmp (org-item-indent-positions)
7546 ind (car tmp)
7547 ind-down (nth 2 tmp)
7548 ind-up (nth 1 tmp)
7549 delta (if (> arg 0)
7550 (if ind-down (- ind-down ind) 2)
7551 (if ind-up (- ind-up ind) -2)))
7552 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7553 (while (< (point) end)
7554 (beginning-of-line 1)
7555 (skip-chars-forward " \t") (setq ind1 (current-column))
7556 (delete-region (point-at-bol) (point))
7557 (or (eolp) (indent-to-column (+ ind1 delta)))
7558 (beginning-of-line 2))))
7559 (org-fix-bullet-type)
7560 (org-maybe-renumber-ordered-list-safe)
7561 (save-excursion
7562 (beginning-of-line 0)
7563 (condition-case nil (org-beginning-of-item) (error nil))
7564 (org-maybe-renumber-ordered-list-safe)))
7566 (defun org-item-indent-positions ()
7567 "Return indentation for plain list items.
7568 This returns a list with three values: The current indentation, the
7569 parent indentation and the indentation a child should habe.
7570 Assumes cursor in item line."
7571 (let* ((bolpos (point-at-bol))
7572 (ind (org-get-indentation))
7573 ind-down ind-up pos)
7574 (save-excursion
7575 (org-beginning-of-item-list)
7576 (skip-chars-backward "\n\r \t")
7577 (when (org-in-item-p)
7578 (org-beginning-of-item)
7579 (setq ind-up (org-get-indentation))))
7580 (setq pos (point))
7581 (save-excursion
7582 (cond
7583 ((and (condition-case nil (progn (org-previous-item) t)
7584 (error nil))
7585 (or (forward-char 1) t)
7586 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7587 (setq ind-down (org-get-indentation)))
7588 ((and (goto-char pos)
7589 (org-at-item-p))
7590 (goto-char (match-end 0))
7591 (skip-chars-forward " \t")
7592 (setq ind-down (current-column)))))
7593 (list ind ind-up ind-down)))
7595 ;;; The orgstruct minor mode
7597 ;; Define a minor mode which can be used in other modes in order to
7598 ;; integrate the org-mode structure editing commands.
7600 ;; This is really a hack, because the org-mode structure commands use
7601 ;; keys which normally belong to the major mode. Here is how it
7602 ;; works: The minor mode defines all the keys necessary to operate the
7603 ;; structure commands, but wraps the commands into a function which
7604 ;; tests if the cursor is currently at a headline or a plain list
7605 ;; item. If that is the case, the structure command is used,
7606 ;; temporarily setting many Org-mode variables like regular
7607 ;; expressions for filling etc. However, when any of those keys is
7608 ;; used at a different location, function uses `key-binding' to look
7609 ;; up if the key has an associated command in another currently active
7610 ;; keymap (minor modes, major mode, global), and executes that
7611 ;; command. There might be problems if any of the keys is otherwise
7612 ;; used as a prefix key.
7614 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7615 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7616 ;; addresses this by checking explicitly for both bindings.
7618 (defvar orgstruct-mode-map (make-sparse-keymap)
7619 "Keymap for the minor `orgstruct-mode'.")
7621 (defvar org-local-vars nil
7622 "List of local variables, for use by `orgstruct-mode'")
7624 ;;;###autoload
7625 (define-minor-mode orgstruct-mode
7626 "Toggle the minor more `orgstruct-mode'.
7627 This mode is for using Org-mode structure commands in other modes.
7628 The following key behave as if Org-mode was active, if the cursor
7629 is on a headline, or on a plain list item (both in the definition
7630 of Org-mode).
7632 M-up Move entry/item up
7633 M-down Move entry/item down
7634 M-left Promote
7635 M-right Demote
7636 M-S-up Move entry/item up
7637 M-S-down Move entry/item down
7638 M-S-left Promote subtree
7639 M-S-right Demote subtree
7640 M-q Fill paragraph and items like in Org-mode
7641 C-c ^ Sort entries
7642 C-c - Cycle list bullet
7643 TAB Cycle item visibility
7644 M-RET Insert new heading/item
7645 S-M-RET Insert new TODO heading / Chekbox item
7646 C-c C-c Set tags / toggle checkbox"
7647 nil " OrgStruct" nil
7648 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7650 ;;;###autoload
7651 (defun turn-on-orgstruct ()
7652 "Unconditionally turn on `orgstruct-mode'."
7653 (orgstruct-mode 1))
7655 ;;;###autoload
7656 (defun turn-on-orgstruct++ ()
7657 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7658 In addition to setting orgstruct-mode, this also exports all indentation and
7659 autofilling variables from org-mode into the buffer. Note that turning
7660 off orgstruct-mode will *not* remove these additional settings."
7661 (orgstruct-mode 1)
7662 (let (var val)
7663 (mapc
7664 (lambda (x)
7665 (when (string-match
7666 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7667 (symbol-name (car x)))
7668 (setq var (car x) val (nth 1 x))
7669 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7670 org-local-vars)))
7672 (defun orgstruct-error ()
7673 "Error when there is no default binding for a structure key."
7674 (interactive)
7675 (error "This key has no function outside structure elements"))
7677 (defun orgstruct-setup ()
7678 "Setup orgstruct keymaps."
7679 (let ((nfunc 0)
7680 (bindings
7681 (list
7682 '([(meta up)] org-metaup)
7683 '([(meta down)] org-metadown)
7684 '([(meta left)] org-metaleft)
7685 '([(meta right)] org-metaright)
7686 '([(meta shift up)] org-shiftmetaup)
7687 '([(meta shift down)] org-shiftmetadown)
7688 '([(meta shift left)] org-shiftmetaleft)
7689 '([(meta shift right)] org-shiftmetaright)
7690 '([(shift up)] org-shiftup)
7691 '([(shift down)] org-shiftdown)
7692 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7693 '("\M-q" fill-paragraph)
7694 '("\C-c^" org-sort)
7695 '("\C-c-" org-cycle-list-bullet)))
7696 elt key fun cmd)
7697 (while (setq elt (pop bindings))
7698 (setq nfunc (1+ nfunc))
7699 (setq key (org-key (car elt))
7700 fun (nth 1 elt)
7701 cmd (orgstruct-make-binding fun nfunc key))
7702 (org-defkey orgstruct-mode-map key cmd))
7704 ;; Special treatment needed for TAB and RET
7705 (org-defkey orgstruct-mode-map [(tab)]
7706 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7707 (org-defkey orgstruct-mode-map "\C-i"
7708 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7710 (org-defkey orgstruct-mode-map "\M-\C-m"
7711 (orgstruct-make-binding 'org-insert-heading 105
7712 "\M-\C-m" [(meta return)]))
7713 (org-defkey orgstruct-mode-map [(meta return)]
7714 (orgstruct-make-binding 'org-insert-heading 106
7715 [(meta return)] "\M-\C-m"))
7717 (org-defkey orgstruct-mode-map [(shift meta return)]
7718 (orgstruct-make-binding 'org-insert-todo-heading 107
7719 [(meta return)] "\M-\C-m"))
7721 (unless org-local-vars
7722 (setq org-local-vars (org-get-local-variables)))
7726 (defun orgstruct-make-binding (fun n &rest keys)
7727 "Create a function for binding in the structure minor mode.
7728 FUN is the command to call inside a table. N is used to create a unique
7729 command name. KEYS are keys that should be checked in for a command
7730 to execute outside of tables."
7731 (eval
7732 (list 'defun
7733 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7734 '(arg)
7735 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7736 "Outside of structure, run the binding of `"
7737 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7738 "'.")
7739 '(interactive "p")
7740 (list 'if
7741 '(org-context-p 'headline 'item)
7742 (list 'org-run-like-in-org-mode (list 'quote fun))
7743 (list 'let '(orgstruct-mode)
7744 (list 'call-interactively
7745 (append '(or)
7746 (mapcar (lambda (k)
7747 (list 'key-binding k))
7748 keys)
7749 '('orgstruct-error))))))))
7751 (defun org-context-p (&rest contexts)
7752 "Check if local context is and of CONTEXTS.
7753 Possible values in the list of contexts are `table', `headline', and `item'."
7754 (let ((pos (point)))
7755 (goto-char (point-at-bol))
7756 (prog1 (or (and (memq 'table contexts)
7757 (looking-at "[ \t]*|"))
7758 (and (memq 'headline contexts)
7759 (looking-at "\\*+"))
7760 (and (memq 'item contexts)
7761 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
7762 (goto-char pos))))
7764 (defun org-get-local-variables ()
7765 "Return a list of all local variables in an org-mode buffer."
7766 (let (varlist)
7767 (with-current-buffer (get-buffer-create "*Org tmp*")
7768 (erase-buffer)
7769 (org-mode)
7770 (setq varlist (buffer-local-variables)))
7771 (kill-buffer "*Org tmp*")
7772 (delq nil
7773 (mapcar
7774 (lambda (x)
7775 (setq x
7776 (if (symbolp x)
7777 (list x)
7778 (list (car x) (list 'quote (cdr x)))))
7779 (if (string-match
7780 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7781 (symbol-name (car x)))
7782 x nil))
7783 varlist))))
7785 ;;;###autoload
7786 (defun org-run-like-in-org-mode (cmd)
7787 (unless org-local-vars
7788 (setq org-local-vars (org-get-local-variables)))
7789 (eval (list 'let org-local-vars
7790 (list 'call-interactively (list 'quote cmd)))))
7792 ;;;; Archiving
7794 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
7796 (defun org-archive-subtree (&optional find-done)
7797 "Move the current subtree to the archive.
7798 The archive can be a certain top-level heading in the current file, or in
7799 a different file. The tree will be moved to that location, the subtree
7800 heading be marked DONE, and the current time will be added.
7802 When called with prefix argument FIND-DONE, find whole trees without any
7803 open TODO items and archive them (after getting confirmation from the user).
7804 If the cursor is not at a headline when this comand is called, try all level
7805 1 trees. If the cursor is on a headline, only try the direct children of
7806 this heading."
7807 (interactive "P")
7808 (if find-done
7809 (org-archive-all-done)
7810 ;; Save all relevant TODO keyword-relatex variables
7812 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
7813 (tr-org-todo-keywords-1 org-todo-keywords-1)
7814 (tr-org-todo-kwd-alist org-todo-kwd-alist)
7815 (tr-org-done-keywords org-done-keywords)
7816 (tr-org-todo-regexp org-todo-regexp)
7817 (tr-org-todo-line-regexp org-todo-line-regexp)
7818 (tr-org-odd-levels-only org-odd-levels-only)
7819 (this-buffer (current-buffer))
7820 (org-archive-location org-archive-location)
7821 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
7822 ;; start of variables that will be used for saving context
7823 ;; The compiler complains about them - keep them anyway!
7824 (file (abbreviate-file-name (buffer-file-name)))
7825 (olpath (mapconcat 'identity (org-get-outline-path) "/"))
7826 (time (format-time-string
7827 (substring (cdr org-time-stamp-formats) 1 -1)
7828 (current-time)))
7829 afile heading buffer level newfile-p
7830 category todo priority
7831 ;; start of variables that will be used for savind context
7832 ltags itags prop)
7834 ;; Try to find a local archive location
7835 (save-excursion
7836 (save-restriction
7837 (widen)
7838 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
7839 (if (and prop (string-match "\\S-" prop))
7840 (setq org-archive-location prop)
7841 (if (or (re-search-backward re nil t)
7842 (re-search-forward re nil t))
7843 (setq org-archive-location (match-string 1))))))
7845 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
7846 (progn
7847 (setq afile (format (match-string 1 org-archive-location)
7848 (file-name-nondirectory buffer-file-name))
7849 heading (match-string 2 org-archive-location)))
7850 (error "Invalid `org-archive-location'"))
7851 (if (> (length afile) 0)
7852 (setq newfile-p (not (file-exists-p afile))
7853 buffer (find-file-noselect afile))
7854 (setq buffer (current-buffer)))
7855 (unless buffer
7856 (error "Cannot access file \"%s\"" afile))
7857 (if (and (> (length heading) 0)
7858 (string-match "^\\*+" heading))
7859 (setq level (match-end 0))
7860 (setq heading nil level 0))
7861 (save-excursion
7862 (org-back-to-heading t)
7863 ;; Get context information that will be lost by moving the tree
7864 (org-refresh-category-properties)
7865 (setq category (org-get-category)
7866 todo (and (looking-at org-todo-line-regexp)
7867 (match-string 2))
7868 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
7869 ltags (org-get-tags)
7870 itags (org-delete-all ltags (org-get-tags-at)))
7871 (setq ltags (mapconcat 'identity ltags " ")
7872 itags (mapconcat 'identity itags " "))
7873 ;; We first only copy, in case something goes wrong
7874 ;; we need to protect this-command, to avoid kill-region sets it,
7875 ;; which would lead to duplication of subtrees
7876 (let (this-command) (org-copy-subtree))
7877 (set-buffer buffer)
7878 ;; Enforce org-mode for the archive buffer
7879 (if (not (org-mode-p))
7880 ;; Force the mode for future visits.
7881 (let ((org-insert-mode-line-in-empty-file t)
7882 (org-inhibit-startup t))
7883 (call-interactively 'org-mode)))
7884 (when newfile-p
7885 (goto-char (point-max))
7886 (insert (format "\nArchived entries from file %s\n\n"
7887 (buffer-file-name this-buffer))))
7888 ;; Force the TODO keywords of the original buffer
7889 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
7890 (org-todo-keywords-1 tr-org-todo-keywords-1)
7891 (org-todo-kwd-alist tr-org-todo-kwd-alist)
7892 (org-done-keywords tr-org-done-keywords)
7893 (org-todo-regexp tr-org-todo-regexp)
7894 (org-todo-line-regexp tr-org-todo-line-regexp)
7895 (org-odd-levels-only
7896 (if (local-variable-p 'org-odd-levels-only (current-buffer))
7897 org-odd-levels-only
7898 tr-org-odd-levels-only)))
7899 (goto-char (point-min))
7900 (if heading
7901 (progn
7902 (if (re-search-forward
7903 (concat "^" (regexp-quote heading)
7904 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
7905 nil t)
7906 (goto-char (match-end 0))
7907 ;; Heading not found, just insert it at the end
7908 (goto-char (point-max))
7909 (or (bolp) (insert "\n"))
7910 (insert "\n" heading "\n")
7911 (end-of-line 0))
7912 ;; Make the subtree visible
7913 (show-subtree)
7914 (org-end-of-subtree t)
7915 (skip-chars-backward " \t\r\n")
7916 (and (looking-at "[ \t\r\n]*")
7917 (replace-match "\n\n")))
7918 ;; No specific heading, just go to end of file.
7919 (goto-char (point-max)) (insert "\n"))
7920 ;; Paste
7921 (org-paste-subtree (org-get-legal-level level 1))
7923 ;; Mark the entry as done
7924 (when (and org-archive-mark-done
7925 (looking-at org-todo-line-regexp)
7926 (or (not (match-end 2))
7927 (not (member (match-string 2) org-done-keywords))))
7928 (let (org-log-done)
7929 (org-todo
7930 (car (or (member org-archive-mark-done org-done-keywords)
7931 org-done-keywords)))))
7933 ;; Add the context info
7934 (when org-archive-save-context-info
7935 (let ((l org-archive-save-context-info) e n v)
7936 (while (setq e (pop l))
7937 (when (and (setq v (symbol-value e))
7938 (stringp v) (string-match "\\S-" v))
7939 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
7940 (org-entry-put (point) n v)))))
7942 ;; Save the buffer, if it is not the same buffer.
7943 (if (not (eq this-buffer buffer)) (save-buffer))))
7944 ;; Here we are back in the original buffer. Everything seems to have
7945 ;; worked. So now cut the tree and finish up.
7946 (let (this-command) (org-cut-subtree))
7947 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
7948 (message "Subtree archived %s"
7949 (if (eq this-buffer buffer)
7950 (concat "under heading: " heading)
7951 (concat "in file: " (abbreviate-file-name afile)))))))
7953 (defun org-refresh-category-properties ()
7954 "Refresh category text properties in teh buffer."
7955 (let ((def-cat (cond
7956 ((null org-category)
7957 (if buffer-file-name
7958 (file-name-sans-extension
7959 (file-name-nondirectory buffer-file-name))
7960 "???"))
7961 ((symbolp org-category) (symbol-name org-category))
7962 (t org-category)))
7963 beg end cat pos optionp)
7964 (org-unmodified
7965 (save-excursion
7966 (save-restriction
7967 (widen)
7968 (goto-char (point-min))
7969 (put-text-property (point) (point-max) 'org-category def-cat)
7970 (while (re-search-forward
7971 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7972 (setq pos (match-end 0)
7973 optionp (equal (char-after (match-beginning 0)) ?#)
7974 cat (org-trim (match-string 2)))
7975 (if optionp
7976 (setq beg (point-at-bol) end (point-max))
7977 (org-back-to-heading t)
7978 (setq beg (point) end (org-end-of-subtree t t)))
7979 (put-text-property beg end 'org-category cat)
7980 (goto-char pos)))))))
7982 (defun org-archive-all-done (&optional tag)
7983 "Archive sublevels of the current tree without open TODO items.
7984 If the cursor is not on a headline, try all level 1 trees. If
7985 it is on a headline, try all direct children.
7986 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
7987 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
7988 (rea (concat ".*:" org-archive-tag ":"))
7989 (begm (make-marker))
7990 (endm (make-marker))
7991 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
7992 "Move subtree to archive (no open TODO items)? "))
7993 beg end (cntarch 0))
7994 (if (org-on-heading-p)
7995 (progn
7996 (setq re1 (concat "^" (regexp-quote
7997 (make-string
7998 (1+ (- (match-end 0) (match-beginning 0) 1))
7999 ?*))
8000 " "))
8001 (move-marker begm (point))
8002 (move-marker endm (org-end-of-subtree t)))
8003 (setq re1 "^* ")
8004 (move-marker begm (point-min))
8005 (move-marker endm (point-max)))
8006 (save-excursion
8007 (goto-char begm)
8008 (while (re-search-forward re1 endm t)
8009 (setq beg (match-beginning 0)
8010 end (save-excursion (org-end-of-subtree t) (point)))
8011 (goto-char beg)
8012 (if (re-search-forward re end t)
8013 (goto-char end)
8014 (goto-char beg)
8015 (if (and (or (not tag) (not (looking-at rea)))
8016 (y-or-n-p question))
8017 (progn
8018 (if tag
8019 (org-toggle-tag org-archive-tag 'on)
8020 (org-archive-subtree))
8021 (setq cntarch (1+ cntarch)))
8022 (goto-char end)))))
8023 (message "%d trees archived" cntarch)))
8025 (defun org-cycle-hide-drawers (state)
8026 "Re-hide all drawers after a visibility state change."
8027 (when (and (org-mode-p)
8028 (not (memq state '(overview folded))))
8029 (save-excursion
8030 (let* ((globalp (memq state '(contents all)))
8031 (beg (if globalp (point-min) (point)))
8032 (end (if globalp (point-max) (org-end-of-subtree t))))
8033 (goto-char beg)
8034 (while (re-search-forward org-drawer-regexp end t)
8035 (org-flag-drawer t))))))
8037 (defun org-flag-drawer (flag)
8038 (save-excursion
8039 (beginning-of-line 1)
8040 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
8041 (let ((b (match-end 0))
8042 (outline-regexp org-outline-regexp))
8043 (if (re-search-forward
8044 "^[ \t]*:END:"
8045 (save-excursion (outline-next-heading) (point)) t)
8046 (outline-flag-region b (point-at-eol) flag)
8047 (error ":END: line missing"))))))
8049 (defun org-cycle-hide-archived-subtrees (state)
8050 "Re-hide all archived subtrees after a visibility state change."
8051 (when (and (not org-cycle-open-archived-trees)
8052 (not (memq state '(overview folded))))
8053 (save-excursion
8054 (let* ((globalp (memq state '(contents all)))
8055 (beg (if globalp (point-min) (point)))
8056 (end (if globalp (point-max) (org-end-of-subtree t))))
8057 (org-hide-archived-subtrees beg end)
8058 (goto-char beg)
8059 (if (looking-at (concat ".*:" org-archive-tag ":"))
8060 (message "%s" (substitute-command-keys
8061 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
8063 (defun org-force-cycle-archived ()
8064 "Cycle subtree even if it is archived."
8065 (interactive)
8066 (setq this-command 'org-cycle)
8067 (let ((org-cycle-open-archived-trees t))
8068 (call-interactively 'org-cycle)))
8070 (defun org-hide-archived-subtrees (beg end)
8071 "Re-hide all archived subtrees after a visibility state change."
8072 (save-excursion
8073 (let* ((re (concat ":" org-archive-tag ":")))
8074 (goto-char beg)
8075 (while (re-search-forward re end t)
8076 (and (org-on-heading-p) (hide-subtree))
8077 (org-end-of-subtree t)))))
8079 (defun org-toggle-tag (tag &optional onoff)
8080 "Toggle the tag TAG for the current line.
8081 If ONOFF is `on' or `off', don't toggle but set to this state."
8082 (unless (org-on-heading-p t) (error "Not on headling"))
8083 (let (res current)
8084 (save-excursion
8085 (beginning-of-line)
8086 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8087 (point-at-eol) t)
8088 (progn
8089 (setq current (match-string 1))
8090 (replace-match ""))
8091 (setq current ""))
8092 (setq current (nreverse (org-split-string current ":")))
8093 (cond
8094 ((eq onoff 'on)
8095 (setq res t)
8096 (or (member tag current) (push tag current)))
8097 ((eq onoff 'off)
8098 (or (not (member tag current)) (setq current (delete tag current))))
8099 (t (if (member tag current)
8100 (setq current (delete tag current))
8101 (setq res t)
8102 (push tag current))))
8103 (end-of-line 1)
8104 (if current
8105 (progn
8106 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8107 (org-set-tags nil t))
8108 (delete-horizontal-space))
8109 (run-hooks 'org-after-tags-change-hook))
8110 res))
8112 (defun org-toggle-archive-tag (&optional arg)
8113 "Toggle the archive tag for the current headline.
8114 With prefix ARG, check all children of current headline and offer tagging
8115 the children that do not contain any open TODO items."
8116 (interactive "P")
8117 (if arg
8118 (org-archive-all-done 'tag)
8119 (let (set)
8120 (save-excursion
8121 (org-back-to-heading t)
8122 (setq set (org-toggle-tag org-archive-tag))
8123 (when set (hide-subtree)))
8124 (and set (beginning-of-line 1))
8125 (message "Subtree %s" (if set "archived" "unarchived")))))
8128 ;;;; Tables
8130 ;;; The table editor
8132 ;; Watch out: Here we are talking about two different kind of tables.
8133 ;; Most of the code is for the tables created with the Org-mode table editor.
8134 ;; Sometimes, we talk about tables created and edited with the table.el
8135 ;; Emacs package. We call the former org-type tables, and the latter
8136 ;; table.el-type tables.
8138 (defun org-before-change-function (beg end)
8139 "Every change indicates that a table might need an update."
8140 (setq org-table-may-need-update t))
8142 (defconst org-table-line-regexp "^[ \t]*|"
8143 "Detects an org-type table line.")
8144 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8145 "Detects an org-type table line.")
8146 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8147 "Detects a table line marked for automatic recalculation.")
8148 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8149 "Detects a table line marked for automatic recalculation.")
8150 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8151 "Detects a table line marked for automatic recalculation.")
8152 (defconst org-table-hline-regexp "^[ \t]*|-"
8153 "Detects an org-type table hline.")
8154 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8155 "Detects a table-type table hline.")
8156 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8157 "Detects an org-type or table-type table.")
8158 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8159 "Searching from within a table (any type) this finds the first line
8160 outside the table.")
8161 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8162 "Searching from within a table (any type) this finds the first line
8163 outside the table.")
8165 (defvar org-table-last-highlighted-reference nil)
8166 (defvar org-table-formula-history nil)
8168 (defvar org-table-column-names nil
8169 "Alist with column names, derived from the `!' line.")
8170 (defvar org-table-column-name-regexp nil
8171 "Regular expression matching the current column names.")
8172 (defvar org-table-local-parameters nil
8173 "Alist with parameter names, derived from the `$' line.")
8174 (defvar org-table-named-field-locations nil
8175 "Alist with locations of named fields.")
8177 (defvar org-table-current-line-types nil
8178 "Table row types, non-nil only for the duration of a comand.")
8179 (defvar org-table-current-begin-line nil
8180 "Table begin line, non-nil only for the duration of a comand.")
8181 (defvar org-table-current-begin-pos nil
8182 "Table begin position, non-nil only for the duration of a comand.")
8183 (defvar org-table-dlines nil
8184 "Vector of data line line numbers in the current table.")
8185 (defvar org-table-hlines nil
8186 "Vector of hline line numbers in the current table.")
8188 (defconst org-table-range-regexp
8189 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
8190 ;; 1 2 3 4 5
8191 "Regular expression for matching ranges in formulas.")
8193 (defconst org-table-range-regexp2
8194 (concat
8195 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
8196 "\\.\\."
8197 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8198 "Match a range for reference display.")
8200 (defconst org-table-translate-regexp
8201 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8202 "Match a reference that needs translation, for reference display.")
8204 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8206 (defun org-table-create-with-table.el ()
8207 "Use the table.el package to insert a new table.
8208 If there is already a table at point, convert between Org-mode tables
8209 and table.el tables."
8210 (interactive)
8211 (require 'table)
8212 (cond
8213 ((org-at-table.el-p)
8214 (if (y-or-n-p "Convert table to Org-mode table? ")
8215 (org-table-convert)))
8216 ((org-at-table-p)
8217 (if (y-or-n-p "Convert table to table.el table? ")
8218 (org-table-convert)))
8219 (t (call-interactively 'table-insert))))
8221 (defun org-table-create-or-convert-from-region (arg)
8222 "Convert region to table, or create an empty table.
8223 If there is an active region, convert it to a table, using the function
8224 `org-table-convert-region'. See the documentation of that function
8225 to learn how the prefix argument is interpreted to determine the field
8226 separator.
8227 If there is no such region, create an empty table with `org-table-create'."
8228 (interactive "P")
8229 (if (org-region-active-p)
8230 (org-table-convert-region (region-beginning) (region-end) arg)
8231 (org-table-create arg)))
8233 (defun org-table-create (&optional size)
8234 "Query for a size and insert a table skeleton.
8235 SIZE is a string Columns x Rows like for example \"3x2\"."
8236 (interactive "P")
8237 (unless size
8238 (setq size (read-string
8239 (concat "Table size Columns x Rows [e.g. "
8240 org-table-default-size "]: ")
8241 "" nil org-table-default-size)))
8243 (let* ((pos (point))
8244 (indent (make-string (current-column) ?\ ))
8245 (split (org-split-string size " *x *"))
8246 (rows (string-to-number (nth 1 split)))
8247 (columns (string-to-number (car split)))
8248 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8249 "\n")))
8250 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8251 (point-at-bol) (point)))
8252 (beginning-of-line 1)
8253 (newline))
8254 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8255 (dotimes (i rows) (insert line))
8256 (goto-char pos)
8257 (if (> rows 1)
8258 ;; Insert a hline after the first row.
8259 (progn
8260 (end-of-line 1)
8261 (insert "\n|-")
8262 (goto-char pos)))
8263 (org-table-align)))
8265 (defun org-table-convert-region (beg0 end0 &optional separator)
8266 "Convert region to a table.
8267 The region goes from BEG0 to END0, but these borders will be moved
8268 slightly, to make sure a beginning of line in the first line is included.
8270 SEPARATOR specifies the field separator in the lines. It can have the
8271 following values:
8273 '(4) Use the comma as a field separator
8274 '(16) Use a TAB as field separator
8275 integer When a number, use that many spaces as field separator
8276 nil When nil, the command tries to be smart and figure out the
8277 separator in the following way:
8278 - when each line contains a TAB, assume TAB-separated material
8279 - when each line contains a comme, assume CSV material
8280 - else, assume one or more SPACE charcters as separator."
8281 (interactive "rP")
8282 (let* ((beg (min beg0 end0))
8283 (end (max beg0 end0))
8285 (goto-char beg)
8286 (beginning-of-line 1)
8287 (setq beg (move-marker (make-marker) (point)))
8288 (goto-char end)
8289 (if (bolp) (backward-char 1) (end-of-line 1))
8290 (setq end (move-marker (make-marker) (point)))
8291 ;; Get the right field separator
8292 (unless separator
8293 (goto-char beg)
8294 (setq separator
8295 (cond
8296 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8297 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8298 (t 1))))
8299 (setq re (cond
8300 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8301 ((equal separator '(16)) "^\\|\t")
8302 ((integerp separator)
8303 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8304 (t (error "This should not happen"))))
8305 (goto-char beg)
8306 (while (re-search-forward re end t)
8307 (replace-match "| " t t))
8308 (goto-char beg)
8309 (insert " ")
8310 (org-table-align)))
8312 (defun org-table-import (file arg)
8313 "Import FILE as a table.
8314 The file is assumed to be tab-separated. Such files can be produced by most
8315 spreadsheet and database applications. If no tabs (at least one per line)
8316 are found, lines will be split on whitespace into fields."
8317 (interactive "f\nP")
8318 (or (bolp) (newline))
8319 (let ((beg (point))
8320 (pm (point-max)))
8321 (insert-file-contents file)
8322 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8324 (defun org-table-export ()
8325 "Export table as a tab-separated file.
8326 Such a file can be imported into a spreadsheet program like Excel."
8327 (interactive)
8328 (let* ((beg (org-table-begin))
8329 (end (org-table-end))
8330 (table (buffer-substring beg end))
8331 (file (read-file-name "Export table to: "))
8332 buf)
8333 (unless (or (not (file-exists-p file))
8334 (y-or-n-p (format "Overwrite file %s? " file)))
8335 (error "Abort"))
8336 (with-current-buffer (find-file-noselect file)
8337 (setq buf (current-buffer))
8338 (erase-buffer)
8339 (fundamental-mode)
8340 (insert table)
8341 (goto-char (point-min))
8342 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8343 (replace-match "" t t)
8344 (end-of-line 1))
8345 (goto-char (point-min))
8346 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8347 (replace-match "" t t)
8348 (goto-char (min (1+ (point)) (point-max))))
8349 (goto-char (point-min))
8350 (while (re-search-forward "^-[-+]*$" nil t)
8351 (replace-match "")
8352 (if (looking-at "\n")
8353 (delete-char 1)))
8354 (goto-char (point-min))
8355 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8356 (replace-match "\t" t t))
8357 (save-buffer))
8358 (kill-buffer buf)))
8360 (defvar org-table-aligned-begin-marker (make-marker)
8361 "Marker at the beginning of the table last aligned.
8362 Used to check if cursor still is in that table, to minimize realignment.")
8363 (defvar org-table-aligned-end-marker (make-marker)
8364 "Marker at the end of the table last aligned.
8365 Used to check if cursor still is in that table, to minimize realignment.")
8366 (defvar org-table-last-alignment nil
8367 "List of flags for flushright alignment, from the last re-alignment.
8368 This is being used to correctly align a single field after TAB or RET.")
8369 (defvar org-table-last-column-widths nil
8370 "List of max width of fields in each column.
8371 This is being used to correctly align a single field after TAB or RET.")
8372 (defvar org-table-overlay-coordinates nil
8373 "Overlay coordinates after each align of a table.")
8374 (make-variable-buffer-local 'org-table-overlay-coordinates)
8376 (defvar org-last-recalc-line nil)
8377 (defconst org-narrow-column-arrow "=>"
8378 "Used as display property in narrowed table columns.")
8380 (defun org-table-align ()
8381 "Align the table at point by aligning all vertical bars."
8382 (interactive)
8383 (let* (
8384 ;; Limits of table
8385 (beg (org-table-begin))
8386 (end (org-table-end))
8387 ;; Current cursor position
8388 (linepos (org-current-line))
8389 (colpos (org-table-current-column))
8390 (winstart (window-start))
8391 (winstartline (org-current-line (min winstart (1- (point-max)))))
8392 lines (new "") lengths l typenums ty fields maxfields i
8393 column
8394 (indent "") cnt frac
8395 rfmt hfmt
8396 (spaces '(1 . 1))
8397 (sp1 (car spaces))
8398 (sp2 (cdr spaces))
8399 (rfmt1 (concat
8400 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8401 (hfmt1 (concat
8402 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8403 emptystrings links dates emph narrow fmax f1 len c e)
8404 (untabify beg end)
8405 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8406 ;; Check if we have links or dates
8407 (goto-char beg)
8408 (setq links (re-search-forward org-bracket-link-regexp end t))
8409 (goto-char beg)
8410 (setq emph (and org-hide-emphasis-markers
8411 (re-search-forward org-emph-re end t)))
8412 (goto-char beg)
8413 (setq dates (and org-display-custom-times
8414 (re-search-forward org-ts-regexp-both end t)))
8415 ;; Make sure the link properties are right
8416 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8417 ;; Make sure the date properties are right
8418 (when dates (goto-char beg) (while (org-activate-dates end)))
8419 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8421 ;; Check if we are narrowing any columns
8422 (goto-char beg)
8423 (setq narrow (and org-format-transports-properties-p
8424 (re-search-forward "<[0-9]+>" end t)))
8425 ;; Get the rows
8426 (setq lines (org-split-string
8427 (buffer-substring beg end) "\n"))
8428 ;; Store the indentation of the first line
8429 (if (string-match "^ *" (car lines))
8430 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8431 ;; Mark the hlines by setting the corresponding element to nil
8432 ;; At the same time, we remove trailing space.
8433 (setq lines (mapcar (lambda (l)
8434 (if (string-match "^ *|-" l)
8436 (if (string-match "[ \t]+$" l)
8437 (substring l 0 (match-beginning 0))
8438 l)))
8439 lines))
8440 ;; Get the data fields by splitting the lines.
8441 (setq fields (mapcar
8442 (lambda (l)
8443 (org-split-string l " *| *"))
8444 (delq nil (copy-sequence lines))))
8445 ;; How many fields in the longest line?
8446 (condition-case nil
8447 (setq maxfields (apply 'max (mapcar 'length fields)))
8448 (error
8449 (kill-region beg end)
8450 (org-table-create org-table-default-size)
8451 (error "Empty table - created default table")))
8452 ;; A list of empty strings to fill any short rows on output
8453 (setq emptystrings (make-list maxfields ""))
8454 ;; Check for special formatting.
8455 (setq i -1)
8456 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8457 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8458 ;; Check if there is an explicit width specified
8459 (when narrow
8460 (setq c column fmax nil)
8461 (while c
8462 (setq e (pop c))
8463 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8464 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8465 ;; Find fields that are wider than fmax, and shorten them
8466 (when fmax
8467 (loop for xx in column do
8468 (when (and (stringp xx)
8469 (> (org-string-width xx) fmax))
8470 (org-add-props xx nil
8471 'help-echo
8472 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8473 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8474 (unless (> f1 1)
8475 (error "Cannot narrow field starting with wide link \"%s\""
8476 (match-string 0 xx)))
8477 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8478 (add-text-properties (- f1 2) f1
8479 (list 'display org-narrow-column-arrow)
8480 xx)))))
8481 ;; Get the maximum width for each column
8482 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8483 ;; Get the fraction of numbers, to decide about alignment of the column
8484 (setq cnt 0 frac 0.0)
8485 (loop for x in column do
8486 (if (equal x "")
8488 (setq frac ( / (+ (* frac cnt)
8489 (if (string-match org-table-number-regexp x) 1 0))
8490 (setq cnt (1+ cnt))))))
8491 (push (>= frac org-table-number-fraction) typenums))
8492 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8494 ;; Store the alignment of this table, for later editing of single fields
8495 (setq org-table-last-alignment typenums
8496 org-table-last-column-widths lengths)
8498 ;; With invisible characters, `format' does not get the field width right
8499 ;; So we need to make these fields wide by hand.
8500 (when (or links emph)
8501 (loop for i from 0 upto (1- maxfields) do
8502 (setq len (nth i lengths))
8503 (loop for j from 0 upto (1- (length fields)) do
8504 (setq c (nthcdr i (car (nthcdr j fields))))
8505 (if (and (stringp (car c))
8506 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8507 ; (string-match org-bracket-link-regexp (car c))
8508 (< (org-string-width (car c)) len))
8509 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8511 ;; Compute the formats needed for output of the table
8512 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8513 (while (setq l (pop lengths))
8514 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8515 (setq rfmt (concat rfmt (format rfmt1 ty l))
8516 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8517 (setq rfmt (concat rfmt "\n")
8518 hfmt (concat (substring hfmt 0 -1) "|\n"))
8520 (setq new (mapconcat
8521 (lambda (l)
8522 (if l (apply 'format rfmt
8523 (append (pop fields) emptystrings))
8524 hfmt))
8525 lines ""))
8526 ;; Replace the old one
8527 (delete-region beg end)
8528 (move-marker end nil)
8529 (move-marker org-table-aligned-begin-marker (point))
8530 (insert new)
8531 (move-marker org-table-aligned-end-marker (point))
8532 (when (and orgtbl-mode (not (org-mode-p)))
8533 (goto-char org-table-aligned-begin-marker)
8534 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8535 ;; Try to move to the old location
8536 (goto-line winstartline)
8537 (setq winstart (point-at-bol))
8538 (goto-line linepos)
8539 (set-window-start (selected-window) winstart 'noforce)
8540 (org-table-goto-column colpos)
8541 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8542 (setq org-table-may-need-update nil)
8545 (defun org-string-width (s)
8546 "Compute width of string, ignoring invisible characters.
8547 This ignores character with invisibility property `org-link', and also
8548 characters with property `org-cwidth', because these will become invisible
8549 upon the next fontification round."
8550 (let (b l)
8551 (when (or (eq t buffer-invisibility-spec)
8552 (assq 'org-link buffer-invisibility-spec))
8553 (while (setq b (text-property-any 0 (length s)
8554 'invisible 'org-link s))
8555 (setq s (concat (substring s 0 b)
8556 (substring s (or (next-single-property-change
8557 b 'invisible s) (length s)))))))
8558 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8559 (setq s (concat (substring s 0 b)
8560 (substring s (or (next-single-property-change
8561 b 'org-cwidth s) (length s))))))
8562 (setq l (string-width s) b -1)
8563 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8564 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8567 (defun org-table-begin (&optional table-type)
8568 "Find the beginning of the table and return its position.
8569 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8570 (save-excursion
8571 (if (not (re-search-backward
8572 (if table-type org-table-any-border-regexp
8573 org-table-border-regexp)
8574 nil t))
8575 (progn (goto-char (point-min)) (point))
8576 (goto-char (match-beginning 0))
8577 (beginning-of-line 2)
8578 (point))))
8580 (defun org-table-end (&optional table-type)
8581 "Find the end of the table and return its position.
8582 With argument TABLE-TYPE, go to the end of a table.el-type table."
8583 (save-excursion
8584 (if (not (re-search-forward
8585 (if table-type org-table-any-border-regexp
8586 org-table-border-regexp)
8587 nil t))
8588 (goto-char (point-max))
8589 (goto-char (match-beginning 0)))
8590 (point-marker)))
8592 (defun org-table-justify-field-maybe (&optional new)
8593 "Justify the current field, text to left, number to right.
8594 Optional argument NEW may specify text to replace the current field content."
8595 (cond
8596 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8597 ((org-at-table-hline-p))
8598 ((and (not new)
8599 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8600 (current-buffer)))
8601 (< (point) org-table-aligned-begin-marker)
8602 (>= (point) org-table-aligned-end-marker)))
8603 ;; This is not the same table, force a full re-align
8604 (setq org-table-may-need-update t))
8605 (t ;; realign the current field, based on previous full realign
8606 (let* ((pos (point)) s
8607 (col (org-table-current-column))
8608 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8609 l f n o e)
8610 (when (> col 0)
8611 (skip-chars-backward "^|\n")
8612 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8613 (progn
8614 (setq s (match-string 1)
8615 o (match-string 0)
8616 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8617 e (not (= (match-beginning 2) (match-end 2))))
8618 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8619 l (if e "|" (setq org-table-may-need-update t) ""))
8620 n (format f s))
8621 (if new
8622 (if (<= (length new) l) ;; FIXME: length -> str-width?
8623 (setq n (format f new))
8624 (setq n (concat new "|") org-table-may-need-update t)))
8625 (or (equal n o)
8626 (let (org-table-may-need-update)
8627 (replace-match n t t))))
8628 (setq org-table-may-need-update t))
8629 (goto-char pos))))))
8631 (defun org-table-next-field ()
8632 "Go to the next field in the current table, creating new lines as needed.
8633 Before doing so, re-align the table if necessary."
8634 (interactive)
8635 (org-table-maybe-eval-formula)
8636 (org-table-maybe-recalculate-line)
8637 (if (and org-table-automatic-realign
8638 org-table-may-need-update)
8639 (org-table-align))
8640 (let ((end (org-table-end)))
8641 (if (org-at-table-hline-p)
8642 (end-of-line 1))
8643 (condition-case nil
8644 (progn
8645 (re-search-forward "|" end)
8646 (if (looking-at "[ \t]*$")
8647 (re-search-forward "|" end))
8648 (if (and (looking-at "-")
8649 org-table-tab-jumps-over-hlines
8650 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8651 (goto-char (match-beginning 1)))
8652 (if (looking-at "-")
8653 (progn
8654 (beginning-of-line 0)
8655 (org-table-insert-row 'below))
8656 (if (looking-at " ") (forward-char 1))))
8657 (error
8658 (org-table-insert-row 'below)))))
8660 (defun org-table-previous-field ()
8661 "Go to the previous field in the table.
8662 Before doing so, re-align the table if necessary."
8663 (interactive)
8664 (org-table-justify-field-maybe)
8665 (org-table-maybe-recalculate-line)
8666 (if (and org-table-automatic-realign
8667 org-table-may-need-update)
8668 (org-table-align))
8669 (if (org-at-table-hline-p)
8670 (end-of-line 1))
8671 (re-search-backward "|" (org-table-begin))
8672 (re-search-backward "|" (org-table-begin))
8673 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8674 (re-search-backward "|" (org-table-begin)))
8675 (if (looking-at "| ?")
8676 (goto-char (match-end 0))))
8678 (defun org-table-next-row ()
8679 "Go to the next row (same column) in the current table.
8680 Before doing so, re-align the table if necessary."
8681 (interactive)
8682 (org-table-maybe-eval-formula)
8683 (org-table-maybe-recalculate-line)
8684 (if (or (looking-at "[ \t]*$")
8685 (save-excursion (skip-chars-backward " \t") (bolp)))
8686 (newline)
8687 (if (and org-table-automatic-realign
8688 org-table-may-need-update)
8689 (org-table-align))
8690 (let ((col (org-table-current-column)))
8691 (beginning-of-line 2)
8692 (if (or (not (org-at-table-p))
8693 (org-at-table-hline-p))
8694 (progn
8695 (beginning-of-line 0)
8696 (org-table-insert-row 'below)))
8697 (org-table-goto-column col)
8698 (skip-chars-backward "^|\n\r")
8699 (if (looking-at " ") (forward-char 1)))))
8701 (defun org-table-copy-down (n)
8702 "Copy a field down in the current column.
8703 If the field at the cursor is empty, copy into it the content of the nearest
8704 non-empty field above. With argument N, use the Nth non-empty field.
8705 If the current field is not empty, it is copied down to the next row, and
8706 the cursor is moved with it. Therefore, repeating this command causes the
8707 column to be filled row-by-row.
8708 If the variable `org-table-copy-increment' is non-nil and the field is an
8709 integer or a timestamp, it will be incremented while copying. In the case of
8710 a timestamp, if the cursor is on the year, change the year. If it is on the
8711 month or the day, change that. Point will stay on the current date field
8712 in order to easily repeat the interval."
8713 (interactive "p")
8714 (let* ((colpos (org-table-current-column))
8715 (col (current-column))
8716 (field (org-table-get-field))
8717 (non-empty (string-match "[^ \t]" field))
8718 (beg (org-table-begin))
8719 txt)
8720 (org-table-check-inside-data-field)
8721 (if non-empty
8722 (progn
8723 (setq txt (org-trim field))
8724 (org-table-next-row)
8725 (org-table-blank-field))
8726 (save-excursion
8727 (setq txt
8728 (catch 'exit
8729 (while (progn (beginning-of-line 1)
8730 (re-search-backward org-table-dataline-regexp
8731 beg t))
8732 (org-table-goto-column colpos t)
8733 (if (and (looking-at
8734 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8735 (= (setq n (1- n)) 0))
8736 (throw 'exit (match-string 1))))))))
8737 (if txt
8738 (progn
8739 (if (and org-table-copy-increment
8740 (string-match "^[0-9]+$" txt))
8741 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8742 (insert txt)
8743 (move-to-column col)
8744 (if (and org-table-copy-increment (org-at-timestamp-p t))
8745 (org-timestamp-up 1)
8746 (org-table-maybe-recalculate-line))
8747 (org-table-align)
8748 (move-to-column col))
8749 (error "No non-empty field found"))))
8751 (defun org-table-check-inside-data-field ()
8752 "Is point inside a table data field?
8753 I.e. not on a hline or before the first or after the last column?
8754 This actually throws an error, so it aborts the current command."
8755 (if (or (not (org-at-table-p))
8756 (= (org-table-current-column) 0)
8757 (org-at-table-hline-p)
8758 (looking-at "[ \t]*$"))
8759 (error "Not in table data field")))
8761 (defvar org-table-clip nil
8762 "Clipboard for table regions.")
8764 (defun org-table-blank-field ()
8765 "Blank the current table field or active region."
8766 (interactive)
8767 (org-table-check-inside-data-field)
8768 (if (and (interactive-p) (org-region-active-p))
8769 (let (org-table-clip)
8770 (org-table-cut-region (region-beginning) (region-end)))
8771 (skip-chars-backward "^|")
8772 (backward-char 1)
8773 (if (looking-at "|[^|\n]+")
8774 (let* ((pos (match-beginning 0))
8775 (match (match-string 0))
8776 (len (org-string-width match)))
8777 (replace-match (concat "|" (make-string (1- len) ?\ )))
8778 (goto-char (+ 2 pos))
8779 (substring match 1)))))
8781 (defun org-table-get-field (&optional n replace)
8782 "Return the value of the field in column N of current row.
8783 N defaults to current field.
8784 If REPLACE is a string, replace field with this value. The return value
8785 is always the old value."
8786 (and n (org-table-goto-column n))
8787 (skip-chars-backward "^|\n")
8788 (backward-char 1)
8789 (if (looking-at "|[^|\r\n]*")
8790 (let* ((pos (match-beginning 0))
8791 (val (buffer-substring (1+ pos) (match-end 0))))
8792 (if replace
8793 (replace-match (concat "|" replace) t t))
8794 (goto-char (min (point-at-eol) (+ 2 pos)))
8795 val)
8796 (forward-char 1) ""))
8798 (defun org-table-field-info (arg)
8799 "Show info about the current field, and highlight any reference at point."
8800 (interactive "P")
8801 (org-table-get-specials)
8802 (save-excursion
8803 (let* ((pos (point))
8804 (col (org-table-current-column))
8805 (cname (car (rassoc (int-to-string col) org-table-column-names)))
8806 (name (car (rassoc (list (org-current-line) col)
8807 org-table-named-field-locations)))
8808 (eql (org-table-get-stored-formulas))
8809 (dline (org-table-current-dline))
8810 (ref (format "@%d$%d" dline col))
8811 (ref1 (org-table-convert-refs-to-an ref))
8812 (fequation (or (assoc name eql) (assoc ref eql)))
8813 (cequation (assoc (int-to-string col) eql))
8814 (eqn (or fequation cequation)))
8815 (goto-char pos)
8816 (condition-case nil
8817 (org-table-show-reference 'local)
8818 (error nil))
8819 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
8820 dline col
8821 (if cname (concat " or $" cname) "")
8822 dline col ref1
8823 (if name (concat " or $" name) "")
8824 ;; FIXME: formula info not correct if special table line
8825 (if eqn
8826 (concat ", formula: "
8827 (org-table-formula-to-user
8828 (concat
8829 (if (string-match "^[$@]"(car eqn)) "" "$")
8830 (car eqn) "=" (cdr eqn))))
8831 "")))))
8833 (defun org-table-current-column ()
8834 "Find out which column we are in.
8835 When called interactively, column is also displayed in echo area."
8836 (interactive)
8837 (if (interactive-p) (org-table-check-inside-data-field))
8838 (save-excursion
8839 (let ((cnt 0) (pos (point)))
8840 (beginning-of-line 1)
8841 (while (search-forward "|" pos t)
8842 (setq cnt (1+ cnt)))
8843 (if (interactive-p) (message "This is table column %d" cnt))
8844 cnt)))
8846 (defun org-table-current-dline ()
8847 "Find out what table data line we are in.
8848 Only datalins count for this."
8849 (interactive)
8850 (if (interactive-p) (org-table-check-inside-data-field))
8851 (save-excursion
8852 (let ((cnt 0) (pos (point)))
8853 (goto-char (org-table-begin))
8854 (while (<= (point) pos)
8855 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
8856 (beginning-of-line 2))
8857 (if (interactive-p) (message "This is table line %d" cnt))
8858 cnt)))
8860 (defun org-table-goto-column (n &optional on-delim force)
8861 "Move the cursor to the Nth column in the current table line.
8862 With optional argument ON-DELIM, stop with point before the left delimiter
8863 of the field.
8864 If there are less than N fields, just go to after the last delimiter.
8865 However, when FORCE is non-nil, create new columns if necessary."
8866 (interactive "p")
8867 (let ((pos (point-at-eol)))
8868 (beginning-of-line 1)
8869 (when (> n 0)
8870 (while (and (> (setq n (1- n)) -1)
8871 (or (search-forward "|" pos t)
8872 (and force
8873 (progn (end-of-line 1)
8874 (skip-chars-backward "^|")
8875 (insert " | "))))))
8876 ; (backward-char 2) t)))))
8877 (when (and force (not (looking-at ".*|")))
8878 (save-excursion (end-of-line 1) (insert " | ")))
8879 (if on-delim
8880 (backward-char 1)
8881 (if (looking-at " ") (forward-char 1))))))
8883 (defun org-at-table-p (&optional table-type)
8884 "Return t if the cursor is inside an org-type table.
8885 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8886 (if org-enable-table-editor
8887 (save-excursion
8888 (beginning-of-line 1)
8889 (looking-at (if table-type org-table-any-line-regexp
8890 org-table-line-regexp)))
8891 nil))
8893 (defun org-at-table.el-p ()
8894 "Return t if and only if we are at a table.el table."
8895 (and (org-at-table-p 'any)
8896 (save-excursion
8897 (goto-char (org-table-begin 'any))
8898 (looking-at org-table1-hline-regexp))))
8900 (defun org-table-recognize-table.el ()
8901 "If there is a table.el table nearby, recognize it and move into it."
8902 (if org-table-tab-recognizes-table.el
8903 (if (org-at-table.el-p)
8904 (progn
8905 (beginning-of-line 1)
8906 (if (looking-at org-table-dataline-regexp)
8908 (if (looking-at org-table1-hline-regexp)
8909 (progn
8910 (beginning-of-line 2)
8911 (if (looking-at org-table-any-border-regexp)
8912 (beginning-of-line -1)))))
8913 (if (re-search-forward "|" (org-table-end t) t)
8914 (progn
8915 (require 'table)
8916 (if (table--at-cell-p (point))
8918 (message "recognizing table.el table...")
8919 (table-recognize-table)
8920 (message "recognizing table.el table...done")))
8921 (error "This should not happen..."))
8923 nil)
8924 nil))
8926 (defun org-at-table-hline-p ()
8927 "Return t if the cursor is inside a hline in a table."
8928 (if org-enable-table-editor
8929 (save-excursion
8930 (beginning-of-line 1)
8931 (looking-at org-table-hline-regexp))
8932 nil))
8934 (defun org-table-insert-column ()
8935 "Insert a new column into the table."
8936 (interactive)
8937 (if (not (org-at-table-p))
8938 (error "Not at a table"))
8939 (org-table-find-dataline)
8940 (let* ((col (max 1 (org-table-current-column)))
8941 (beg (org-table-begin))
8942 (end (org-table-end))
8943 ;; Current cursor position
8944 (linepos (org-current-line))
8945 (colpos col))
8946 (goto-char beg)
8947 (while (< (point) end)
8948 (if (org-at-table-hline-p)
8950 (org-table-goto-column col t)
8951 (insert "| "))
8952 (beginning-of-line 2))
8953 (move-marker end nil)
8954 (goto-line linepos)
8955 (org-table-goto-column colpos)
8956 (org-table-align)
8957 (org-table-fix-formulas "$" nil (1- col) 1)))
8959 (defun org-table-find-dataline ()
8960 "Find a dataline in the current table, which is needed for column commands."
8961 (if (and (org-at-table-p)
8962 (not (org-at-table-hline-p)))
8964 (let ((col (current-column))
8965 (end (org-table-end)))
8966 (move-to-column col)
8967 (while (and (< (point) end)
8968 (or (not (= (current-column) col))
8969 (org-at-table-hline-p)))
8970 (beginning-of-line 2)
8971 (move-to-column col))
8972 (if (and (org-at-table-p)
8973 (not (org-at-table-hline-p)))
8975 (error
8976 "Please position cursor in a data line for column operations")))))
8978 (defun org-table-delete-column ()
8979 "Delete a column from the table."
8980 (interactive)
8981 (if (not (org-at-table-p))
8982 (error "Not at a table"))
8983 (org-table-find-dataline)
8984 (org-table-check-inside-data-field)
8985 (let* ((col (org-table-current-column))
8986 (beg (org-table-begin))
8987 (end (org-table-end))
8988 ;; Current cursor position
8989 (linepos (org-current-line))
8990 (colpos col))
8991 (goto-char beg)
8992 (while (< (point) end)
8993 (if (org-at-table-hline-p)
8995 (org-table-goto-column col t)
8996 (and (looking-at "|[^|\n]+|")
8997 (replace-match "|")))
8998 (beginning-of-line 2))
8999 (move-marker end nil)
9000 (goto-line linepos)
9001 (org-table-goto-column colpos)
9002 (org-table-align)
9003 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
9004 col -1 col)))
9006 (defun org-table-move-column-right ()
9007 "Move column to the right."
9008 (interactive)
9009 (org-table-move-column nil))
9010 (defun org-table-move-column-left ()
9011 "Move column to the left."
9012 (interactive)
9013 (org-table-move-column 'left))
9015 (defun org-table-move-column (&optional left)
9016 "Move the current column to the right. With arg LEFT, move to the left."
9017 (interactive "P")
9018 (if (not (org-at-table-p))
9019 (error "Not at a table"))
9020 (org-table-find-dataline)
9021 (org-table-check-inside-data-field)
9022 (let* ((col (org-table-current-column))
9023 (col1 (if left (1- col) col))
9024 (beg (org-table-begin))
9025 (end (org-table-end))
9026 ;; Current cursor position
9027 (linepos (org-current-line))
9028 (colpos (if left (1- col) (1+ col))))
9029 (if (and left (= col 1))
9030 (error "Cannot move column further left"))
9031 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9032 (error "Cannot move column further right"))
9033 (goto-char beg)
9034 (while (< (point) end)
9035 (if (org-at-table-hline-p)
9037 (org-table-goto-column col1 t)
9038 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9039 (replace-match "|\\2|\\1|")))
9040 (beginning-of-line 2))
9041 (move-marker end nil)
9042 (goto-line linepos)
9043 (org-table-goto-column colpos)
9044 (org-table-align)
9045 (org-table-fix-formulas
9046 "$" (list (cons (number-to-string col) (number-to-string colpos))
9047 (cons (number-to-string colpos) (number-to-string col))))))
9049 (defun org-table-move-row-down ()
9050 "Move table row down."
9051 (interactive)
9052 (org-table-move-row nil))
9053 (defun org-table-move-row-up ()
9054 "Move table row up."
9055 (interactive)
9056 (org-table-move-row 'up))
9058 (defun org-table-move-row (&optional up)
9059 "Move the current table line down. With arg UP, move it up."
9060 (interactive "P")
9061 (let* ((col (current-column))
9062 (pos (point))
9063 (hline1p (save-excursion (beginning-of-line 1)
9064 (looking-at org-table-hline-regexp)))
9065 (dline1 (org-table-current-dline))
9066 (dline2 (+ dline1 (if up -1 1)))
9067 (tonew (if up 0 2))
9068 txt hline2p)
9069 (beginning-of-line tonew)
9070 (unless (org-at-table-p)
9071 (goto-char pos)
9072 (error "Cannot move row further"))
9073 (setq hline2p (looking-at org-table-hline-regexp))
9074 (goto-char pos)
9075 (beginning-of-line 1)
9076 (setq pos (point))
9077 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9078 (delete-region (point) (1+ (point-at-eol)))
9079 (beginning-of-line tonew)
9080 (insert txt)
9081 (beginning-of-line 0)
9082 (move-to-column col)
9083 (unless (or hline1p hline2p)
9084 (org-table-fix-formulas
9085 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
9086 (cons (number-to-string dline2) (number-to-string dline1)))))))
9088 (defun org-table-insert-row (&optional arg)
9089 "Insert a new row above the current line into the table.
9090 With prefix ARG, insert below the current line."
9091 (interactive "P")
9092 (if (not (org-at-table-p))
9093 (error "Not at a table"))
9094 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9095 (new (org-table-clean-line line)))
9096 ;; Fix the first field if necessary
9097 (if (string-match "^[ \t]*| *[#$] *|" line)
9098 (setq new (replace-match (match-string 0 line) t t new)))
9099 (beginning-of-line (if arg 2 1))
9100 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9101 (beginning-of-line 0)
9102 (re-search-forward "| ?" (point-at-eol) t)
9103 (and (or org-table-may-need-update org-table-overlay-coordinates)
9104 (org-table-align))
9105 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
9107 (defun org-table-insert-hline (&optional above)
9108 "Insert a horizontal-line below the current line into the table.
9109 With prefix ABOVE, insert above the current line."
9110 (interactive "P")
9111 (if (not (org-at-table-p))
9112 (error "Not at a table"))
9113 (let ((line (org-table-clean-line
9114 (buffer-substring (point-at-bol) (point-at-eol))))
9115 (col (current-column)))
9116 (while (string-match "|\\( +\\)|" line)
9117 (setq line (replace-match
9118 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9119 ?-) "|") t t line)))
9120 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9121 (beginning-of-line (if above 1 2))
9122 (insert line "\n")
9123 (beginning-of-line (if above 1 -1))
9124 (move-to-column col)
9125 (and org-table-overlay-coordinates (org-table-align))))
9127 (defun org-table-hline-and-move (&optional same-column)
9128 "Insert a hline and move to the row below that line."
9129 (interactive "P")
9130 (let ((col (org-table-current-column)))
9131 (org-table-maybe-eval-formula)
9132 (org-table-maybe-recalculate-line)
9133 (org-table-insert-hline)
9134 (end-of-line 2)
9135 (if (looking-at "\n[ \t]*|-")
9136 (progn (insert "\n|") (org-table-align))
9137 (org-table-next-field))
9138 (if same-column (org-table-goto-column col))))
9140 (defun org-table-clean-line (s)
9141 "Convert a table line S into a string with only \"|\" and space.
9142 In particular, this does handle wide and invisible characters."
9143 (if (string-match "^[ \t]*|-" s)
9144 ;; It's a hline, just map the characters
9145 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
9146 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9147 (setq s (replace-match
9148 (concat "|" (make-string (org-string-width (match-string 1 s))
9149 ?\ ) "|")
9150 t t s)))
9153 (defun org-table-kill-row ()
9154 "Delete the current row or horizontal line from the table."
9155 (interactive)
9156 (if (not (org-at-table-p))
9157 (error "Not at a table"))
9158 (let ((col (current-column))
9159 (dline (org-table-current-dline)))
9160 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9161 (if (not (org-at-table-p)) (beginning-of-line 0))
9162 (move-to-column col)
9163 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
9164 dline -1 dline)))
9166 (defun org-table-sort-lines (with-case &optional sorting-type)
9167 "Sort table lines according to the column at point.
9169 The position of point indicates the column to be used for
9170 sorting, and the range of lines is the range between the nearest
9171 horizontal separator lines, or the entire table of no such lines
9172 exist. If point is before the first column, you will be prompted
9173 for the sorting column. If there is an active region, the mark
9174 specifies the first line and the sorting column, while point
9175 should be in the last line to be included into the sorting.
9177 The command then prompts for the sorting type which can be
9178 alphabetically, numerically, or by time (as given in a time stamp
9179 in the field). Sorting in reverse order is also possible.
9181 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
9183 If SORTING-TYPE is specified when this function is called from a Lisp
9184 program, no prompting will take place. SORTING-TYPE must be a character,
9185 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
9186 should be done in reverse order."
9187 (interactive "P")
9188 (let* ((thisline (org-current-line))
9189 (thiscol (org-table-current-column))
9190 beg end bcol ecol tend tbeg column lns pos)
9191 (when (equal thiscol 0)
9192 (if (interactive-p)
9193 (setq thiscol
9194 (string-to-number
9195 (read-string "Use column N for sorting: ")))
9196 (setq thiscol 1))
9197 (org-table-goto-column thiscol))
9198 (org-table-check-inside-data-field)
9199 (if (org-region-active-p)
9200 (progn
9201 (setq beg (region-beginning) end (region-end))
9202 (goto-char beg)
9203 (setq column (org-table-current-column)
9204 beg (point-at-bol))
9205 (goto-char end)
9206 (setq end (point-at-bol 2)))
9207 (setq column (org-table-current-column)
9208 pos (point)
9209 tbeg (org-table-begin)
9210 tend (org-table-end))
9211 (if (re-search-backward org-table-hline-regexp tbeg t)
9212 (setq beg (point-at-bol 2))
9213 (goto-char tbeg)
9214 (setq beg (point-at-bol 1)))
9215 (goto-char pos)
9216 (if (re-search-forward org-table-hline-regexp tend t)
9217 (setq end (point-at-bol 1))
9218 (goto-char tend)
9219 (setq end (point-at-bol))))
9220 (setq beg (move-marker (make-marker) beg)
9221 end (move-marker (make-marker) end))
9222 (untabify beg end)
9223 (goto-char beg)
9224 (org-table-goto-column column)
9225 (skip-chars-backward "^|")
9226 (setq bcol (current-column))
9227 (org-table-goto-column (1+ column))
9228 (skip-chars-backward "^|")
9229 (setq ecol (1- (current-column)))
9230 (org-table-goto-column column)
9231 (setq lns (mapcar (lambda(x) (cons
9232 (org-sort-remove-invisible
9233 (nth (1- column)
9234 (org-split-string x "[ \t]*|[ \t]*")))
9236 (org-split-string (buffer-substring beg end) "\n")))
9237 (setq lns (org-do-sort lns "Table" with-case sorting-type))
9238 (delete-region beg end)
9239 (move-marker beg nil)
9240 (move-marker end nil)
9241 (insert (mapconcat 'cdr lns "\n") "\n")
9242 (goto-line thisline)
9243 (org-table-goto-column thiscol)
9244 (message "%d lines sorted, based on column %d" (length lns) column)))
9246 ;; FIXME: maybe we will not need this? Table sorting is broken....
9247 (defun org-sort-remove-invisible (s)
9248 (remove-text-properties 0 (length s) org-rm-props s)
9249 (while (string-match org-bracket-link-regexp s)
9250 (setq s (replace-match (if (match-end 2)
9251 (match-string 3 s)
9252 (match-string 1 s)) t t s)))
9255 (defun org-table-cut-region (beg end)
9256 "Copy region in table to the clipboard and blank all relevant fields."
9257 (interactive "r")
9258 (org-table-copy-region beg end 'cut))
9260 (defun org-table-copy-region (beg end &optional cut)
9261 "Copy rectangular region in table to clipboard.
9262 A special clipboard is used which can only be accessed
9263 with `org-table-paste-rectangle'."
9264 (interactive "rP")
9265 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9266 region cols
9267 (rpl (if cut " " nil)))
9268 (goto-char beg)
9269 (org-table-check-inside-data-field)
9270 (setq l01 (org-current-line)
9271 c01 (org-table-current-column))
9272 (goto-char end)
9273 (org-table-check-inside-data-field)
9274 (setq l02 (org-current-line)
9275 c02 (org-table-current-column))
9276 (setq l1 (min l01 l02) l2 (max l01 l02)
9277 c1 (min c01 c02) c2 (max c01 c02))
9278 (catch 'exit
9279 (while t
9280 (catch 'nextline
9281 (if (> l1 l2) (throw 'exit t))
9282 (goto-line l1)
9283 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9284 (setq cols nil ic1 c1 ic2 c2)
9285 (while (< ic1 (1+ ic2))
9286 (push (org-table-get-field ic1 rpl) cols)
9287 (setq ic1 (1+ ic1)))
9288 (push (nreverse cols) region)
9289 (setq l1 (1+ l1)))))
9290 (setq org-table-clip (nreverse region))
9291 (if cut (org-table-align))
9292 org-table-clip))
9294 (defun org-table-paste-rectangle ()
9295 "Paste a rectangular region into a table.
9296 The upper right corner ends up in the current field. All involved fields
9297 will be overwritten. If the rectangle does not fit into the present table,
9298 the table is enlarged as needed. The process ignores horizontal separator
9299 lines."
9300 (interactive)
9301 (unless (and org-table-clip (listp org-table-clip))
9302 (error "First cut/copy a region to paste!"))
9303 (org-table-check-inside-data-field)
9304 (let* ((clip org-table-clip)
9305 (line (org-current-line))
9306 (col (org-table-current-column))
9307 (org-enable-table-editor t)
9308 (org-table-automatic-realign nil)
9309 c cols field)
9310 (while (setq cols (pop clip))
9311 (while (org-at-table-hline-p) (beginning-of-line 2))
9312 (if (not (org-at-table-p))
9313 (progn (end-of-line 0) (org-table-next-field)))
9314 (setq c col)
9315 (while (setq field (pop cols))
9316 (org-table-goto-column c nil 'force)
9317 (org-table-get-field nil field)
9318 (setq c (1+ c)))
9319 (beginning-of-line 2))
9320 (goto-line line)
9321 (org-table-goto-column col)
9322 (org-table-align)))
9324 (defun org-table-convert ()
9325 "Convert from `org-mode' table to table.el and back.
9326 Obviously, this only works within limits. When an Org-mode table is
9327 converted to table.el, all horizontal separator lines get lost, because
9328 table.el uses these as cell boundaries and has no notion of horizontal lines.
9329 A table.el table can be converted to an Org-mode table only if it does not
9330 do row or column spanning. Multiline cells will become multiple cells.
9331 Beware, Org-mode does not test if the table can be successfully converted - it
9332 blindly applies a recipe that works for simple tables."
9333 (interactive)
9334 (require 'table)
9335 (if (org-at-table.el-p)
9336 ;; convert to Org-mode table
9337 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9338 (end (move-marker (make-marker) (org-table-end t))))
9339 (table-unrecognize-region beg end)
9340 (goto-char beg)
9341 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9342 (replace-match ""))
9343 (goto-char beg))
9344 (if (org-at-table-p)
9345 ;; convert to table.el table
9346 (let ((beg (move-marker (make-marker) (org-table-begin)))
9347 (end (move-marker (make-marker) (org-table-end))))
9348 ;; first, get rid of all horizontal lines
9349 (goto-char beg)
9350 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9351 (replace-match ""))
9352 ;; insert a hline before first
9353 (goto-char beg)
9354 (org-table-insert-hline 'above)
9355 (beginning-of-line -1)
9356 ;; insert a hline after each line
9357 (while (progn (beginning-of-line 3) (< (point) end))
9358 (org-table-insert-hline))
9359 (goto-char beg)
9360 (setq end (move-marker end (org-table-end)))
9361 ;; replace "+" at beginning and ending of hlines
9362 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9363 (replace-match "\\1+-"))
9364 (goto-char beg)
9365 (while (re-search-forward "-|[ \t]*$" end t)
9366 (replace-match "-+"))
9367 (goto-char beg)))))
9369 (defun org-table-wrap-region (arg)
9370 "Wrap several fields in a column like a paragraph.
9371 This is useful if you'd like to spread the contents of a field over several
9372 lines, in order to keep the table compact.
9374 If there is an active region, and both point and mark are in the same column,
9375 the text in the column is wrapped to minimum width for the given number of
9376 lines. Generally, this makes the table more compact. A prefix ARG may be
9377 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9378 formats the selected text to two lines. If the region was longer than two
9379 lines, the remaining lines remain empty. A negative prefix argument reduces
9380 the current number of lines by that amount. The wrapped text is pasted back
9381 into the table. If you formatted it to more lines than it was before, fields
9382 further down in the table get overwritten - so you might need to make space in
9383 the table first.
9385 If there is no region, the current field is split at the cursor position and
9386 the text fragment to the right of the cursor is prepended to the field one
9387 line down.
9389 If there is no region, but you specify a prefix ARG, the current field gets
9390 blank, and the content is appended to the field above."
9391 (interactive "P")
9392 (org-table-check-inside-data-field)
9393 (if (org-region-active-p)
9394 ;; There is a region: fill as a paragraph
9395 (let* ((beg (region-beginning))
9396 (cline (save-excursion (goto-char beg) (org-current-line)))
9397 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9398 nlines)
9399 (org-table-cut-region (region-beginning) (region-end))
9400 (if (> (length (car org-table-clip)) 1)
9401 (error "Region must be limited to single column"))
9402 (setq nlines (if arg
9403 (if (< arg 1)
9404 (+ (length org-table-clip) arg)
9405 arg)
9406 (length org-table-clip)))
9407 (setq org-table-clip
9408 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9409 nil nlines)))
9410 (goto-line cline)
9411 (org-table-goto-column ccol)
9412 (org-table-paste-rectangle))
9413 ;; No region, split the current field at point
9414 (if arg
9415 ;; combine with field above
9416 (let ((s (org-table-blank-field))
9417 (col (org-table-current-column)))
9418 (beginning-of-line 0)
9419 (while (org-at-table-hline-p) (beginning-of-line 0))
9420 (org-table-goto-column col)
9421 (skip-chars-forward "^|")
9422 (skip-chars-backward " ")
9423 (insert " " (org-trim s))
9424 (org-table-align))
9425 ;; split field
9426 (when (looking-at "\\([^|]+\\)+|")
9427 (let ((s (match-string 1)))
9428 (replace-match " |")
9429 (goto-char (match-beginning 0))
9430 (org-table-next-row)
9431 (insert (org-trim s) " ")
9432 (org-table-align))))))
9434 (defvar org-field-marker nil)
9436 (defun org-table-edit-field (arg)
9437 "Edit table field in a different window.
9438 This is mainly useful for fields that contain hidden parts.
9439 When called with a \\[universal-argument] prefix, just make the full field visible so that
9440 it can be edited in place."
9441 (interactive "P")
9442 (if arg
9443 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9444 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9445 (remove-text-properties b e '(org-cwidth t invisible t
9446 display t intangible t))
9447 (if (and (boundp 'font-lock-mode) font-lock-mode)
9448 (font-lock-fontify-block)))
9449 (let ((pos (move-marker (make-marker) (point)))
9450 (field (org-table-get-field))
9451 (cw (current-window-configuration))
9453 (org-switch-to-buffer-other-window "*Org tmp*")
9454 (erase-buffer)
9455 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9456 (let ((org-inhibit-startup t)) (org-mode))
9457 (goto-char (setq p (point-max)))
9458 (insert (org-trim field))
9459 (remove-text-properties p (point-max)
9460 '(invisible t org-cwidth t display t
9461 intangible t))
9462 (goto-char p)
9463 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9464 (org-set-local 'org-window-configuration cw)
9465 (org-set-local 'org-field-marker pos)
9466 (message "Edit and finish with C-c C-c"))))
9468 (defun org-table-finish-edit-field ()
9469 "Finish editing a table data field.
9470 Remove all newline characters, insert the result into the table, realign
9471 the table and kill the editing buffer."
9472 (let ((pos org-field-marker)
9473 (cw org-window-configuration)
9474 (cb (current-buffer))
9475 text)
9476 (goto-char (point-min))
9477 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9478 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9479 (replace-match " "))
9480 (setq text (org-trim (buffer-string)))
9481 (set-window-configuration cw)
9482 (kill-buffer cb)
9483 (select-window (get-buffer-window (marker-buffer pos)))
9484 (goto-char pos)
9485 (move-marker pos nil)
9486 (org-table-check-inside-data-field)
9487 (org-table-get-field nil text)
9488 (org-table-align)
9489 (message "New field value inserted")))
9491 (defun org-trim (s)
9492 "Remove whitespace at beginning and end of string."
9493 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9494 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9497 (defun org-wrap (string &optional width lines)
9498 "Wrap string to either a number of lines, or a width in characters.
9499 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9500 that costs. If there is a word longer than WIDTH, the text is actually
9501 wrapped to the length of that word.
9502 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9503 many lines, whatever width that takes.
9504 The return value is a list of lines, without newlines at the end."
9505 (let* ((words (org-split-string string "[ \t\n]+"))
9506 (maxword (apply 'max (mapcar 'org-string-width words)))
9507 w ll)
9508 (cond (width
9509 (org-do-wrap words (max maxword width)))
9510 (lines
9511 (setq w maxword)
9512 (setq ll (org-do-wrap words maxword))
9513 (if (<= (length ll) lines)
9515 (setq ll words)
9516 (while (> (length ll) lines)
9517 (setq w (1+ w))
9518 (setq ll (org-do-wrap words w)))
9519 ll))
9520 (t (error "Cannot wrap this")))))
9523 (defun org-do-wrap (words width)
9524 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9525 (let (lines line)
9526 (while words
9527 (setq line (pop words))
9528 (while (and words (< (+ (length line) (length (car words))) width))
9529 (setq line (concat line " " (pop words))))
9530 (setq lines (push line lines)))
9531 (nreverse lines)))
9533 (defun org-split-string (string &optional separators)
9534 "Splits STRING into substrings at SEPARATORS.
9535 No empty strings are returned if there are matches at the beginning
9536 and end of string."
9537 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9538 (start 0)
9539 notfirst
9540 (list nil))
9541 (while (and (string-match rexp string
9542 (if (and notfirst
9543 (= start (match-beginning 0))
9544 (< start (length string)))
9545 (1+ start) start))
9546 (< (match-beginning 0) (length string)))
9547 (setq notfirst t)
9548 (or (eq (match-beginning 0) 0)
9549 (and (eq (match-beginning 0) (match-end 0))
9550 (eq (match-beginning 0) start))
9551 (setq list
9552 (cons (substring string start (match-beginning 0))
9553 list)))
9554 (setq start (match-end 0)))
9555 (or (eq start (length string))
9556 (setq list
9557 (cons (substring string start)
9558 list)))
9559 (nreverse list)))
9561 (defun org-table-map-tables (function)
9562 "Apply FUNCTION to the start of all tables in the buffer."
9563 (save-excursion
9564 (save-restriction
9565 (widen)
9566 (goto-char (point-min))
9567 (while (re-search-forward org-table-any-line-regexp nil t)
9568 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9569 (beginning-of-line 1)
9570 (if (looking-at org-table-line-regexp)
9571 (save-excursion (funcall function)))
9572 (re-search-forward org-table-any-border-regexp nil 1))))
9573 (message "Mapping tables: done"))
9575 (defvar org-timecnt) ; dynamically scoped parameter
9577 (defun org-table-sum (&optional beg end nlast)
9578 "Sum numbers in region of current table column.
9579 The result will be displayed in the echo area, and will be available
9580 as kill to be inserted with \\[yank].
9582 If there is an active region, it is interpreted as a rectangle and all
9583 numbers in that rectangle will be summed. If there is no active
9584 region and point is located in a table column, sum all numbers in that
9585 column.
9587 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9588 numbers are assumed to be times as well (in decimal hours) and the
9589 numbers are added as such.
9591 If NLAST is a number, only the NLAST fields will actually be summed."
9592 (interactive)
9593 (save-excursion
9594 (let (col (org-timecnt 0) diff h m s org-table-clip)
9595 (cond
9596 ((and beg end)) ; beg and end given explicitly
9597 ((org-region-active-p)
9598 (setq beg (region-beginning) end (region-end)))
9600 (setq col (org-table-current-column))
9601 (goto-char (org-table-begin))
9602 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9603 (error "No table data"))
9604 (org-table-goto-column col)
9605 (setq beg (point))
9606 (goto-char (org-table-end))
9607 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9608 (error "No table data"))
9609 (org-table-goto-column col)
9610 (setq end (point))))
9611 (let* ((items (apply 'append (org-table-copy-region beg end)))
9612 (items1 (cond ((not nlast) items)
9613 ((>= nlast (length items)) items)
9614 (t (setq items (reverse items))
9615 (setcdr (nthcdr (1- nlast) items) nil)
9616 (nreverse items))))
9617 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9618 items1)))
9619 (res (apply '+ numbers))
9620 (sres (if (= org-timecnt 0)
9621 (format "%g" res)
9622 (setq diff (* 3600 res)
9623 h (floor (/ diff 3600)) diff (mod diff 3600)
9624 m (floor (/ diff 60)) diff (mod diff 60)
9625 s diff)
9626 (format "%d:%02d:%02d" h m s))))
9627 (kill-new sres)
9628 (if (interactive-p)
9629 (message "%s"
9630 (substitute-command-keys
9631 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9632 (length numbers) sres))))
9633 sres))))
9635 (defun org-table-get-number-for-summing (s)
9636 (let (n)
9637 (if (string-match "^ *|? *" s)
9638 (setq s (replace-match "" nil nil s)))
9639 (if (string-match " *|? *$" s)
9640 (setq s (replace-match "" nil nil s)))
9641 (setq n (string-to-number s))
9642 (cond
9643 ((and (string-match "0" s)
9644 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9645 ((string-match "\\`[ \t]+\\'" s) nil)
9646 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9647 (let ((h (string-to-number (or (match-string 1 s) "0")))
9648 (m (string-to-number (or (match-string 2 s) "0")))
9649 (s (string-to-number (or (match-string 4 s) "0"))))
9650 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9651 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9652 ((equal n 0) nil)
9653 (t n))))
9655 (defun org-table-current-field-formula (&optional key noerror)
9656 "Return the formula active for the current field.
9657 Assumes that specials are in place.
9658 If KEY is given, return the key to this formula.
9659 Otherwise return the formula preceeded with \"=\" or \":=\"."
9660 (let* ((name (car (rassoc (list (org-current-line)
9661 (org-table-current-column))
9662 org-table-named-field-locations)))
9663 (col (org-table-current-column))
9664 (scol (int-to-string col))
9665 (ref (format "@%d$%d" (org-table-current-dline) col))
9666 (stored-list (org-table-get-stored-formulas noerror))
9667 (ass (or (assoc name stored-list)
9668 (assoc ref stored-list)
9669 (assoc scol stored-list))))
9670 (if key
9671 (car ass)
9672 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9673 (cdr ass))))))
9675 (defun org-table-get-formula (&optional equation named)
9676 "Read a formula from the minibuffer, offer stored formula as default.
9677 When NAMED is non-nil, look for a named equation."
9678 (let* ((stored-list (org-table-get-stored-formulas))
9679 (name (car (rassoc (list (org-current-line)
9680 (org-table-current-column))
9681 org-table-named-field-locations)))
9682 (ref (format "@%d$%d" (org-table-current-dline)
9683 (org-table-current-column)))
9684 (refass (assoc ref stored-list))
9685 (scol (if named
9686 (if name name ref)
9687 (int-to-string (org-table-current-column))))
9688 (dummy (and (or name refass) (not named)
9689 (not (y-or-n-p "Replace field formula with column formula? " ))
9690 (error "Abort")))
9691 (name (or name ref))
9692 (org-table-may-need-update nil)
9693 (stored (cdr (assoc scol stored-list)))
9694 (eq (cond
9695 ((and stored equation (string-match "^ *=? *$" equation))
9696 stored)
9697 ((stringp equation)
9698 equation)
9699 (t (org-table-formula-from-user
9700 (read-string
9701 (org-table-formula-to-user
9702 (format "%s formula %s%s="
9703 (if named "Field" "Column")
9704 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9705 scol))
9706 (if stored (org-table-formula-to-user stored) "")
9707 'org-table-formula-history
9708 )))))
9709 mustsave)
9710 (when (not (string-match "\\S-" eq))
9711 ;; remove formula
9712 (setq stored-list (delq (assoc scol stored-list) stored-list))
9713 (org-table-store-formulas stored-list)
9714 (error "Formula removed"))
9715 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9716 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9717 (if (and name (not named))
9718 ;; We set the column equation, delete the named one.
9719 (setq stored-list (delq (assoc name stored-list) stored-list)
9720 mustsave t))
9721 (if stored
9722 (setcdr (assoc scol stored-list) eq)
9723 (setq stored-list (cons (cons scol eq) stored-list)))
9724 (if (or mustsave (not (equal stored eq)))
9725 (org-table-store-formulas stored-list))
9726 eq))
9728 (defun org-table-store-formulas (alist)
9729 "Store the list of formulas below the current table."
9730 (setq alist (sort alist 'org-table-formula-less-p))
9731 (save-excursion
9732 (goto-char (org-table-end))
9733 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9734 (progn
9735 ;; don't overwrite TBLFM, we might use text properties to store stuff
9736 (goto-char (match-beginning 2))
9737 (delete-region (match-beginning 2) (match-end 0)))
9738 (insert "#+TBLFM:"))
9739 (insert " "
9740 (mapconcat (lambda (x)
9741 (concat
9742 (if (equal (string-to-char (car x)) ?@) "" "$")
9743 (car x) "=" (cdr x)))
9744 alist "::")
9745 "\n")))
9747 (defsubst org-table-formula-make-cmp-string (a)
9748 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9749 (concat
9750 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9751 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9752 (if (match-end 5) (concat "@@" (match-string 5 a))))))
9754 (defun org-table-formula-less-p (a b)
9755 "Compare two formulas for sorting."
9756 (let ((as (org-table-formula-make-cmp-string (car a)))
9757 (bs (org-table-formula-make-cmp-string (car b))))
9758 (and as bs (string< as bs))))
9760 (defun org-table-get-stored-formulas (&optional noerror)
9761 "Return an alist with the stored formulas directly after current table."
9762 (interactive)
9763 (let (scol eq eq-alist strings string seen)
9764 (save-excursion
9765 (goto-char (org-table-end))
9766 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9767 (setq strings (org-split-string (match-string 2) " *:: *"))
9768 (while (setq string (pop strings))
9769 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
9770 (setq scol (if (match-end 2)
9771 (match-string 2 string)
9772 (match-string 1 string))
9773 eq (match-string 3 string)
9774 eq-alist (cons (cons scol eq) eq-alist))
9775 (if (member scol seen)
9776 (if noerror
9777 (progn
9778 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9779 (ding)
9780 (sit-for 2))
9781 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
9782 (push scol seen))))))
9783 (nreverse eq-alist)))
9785 (defun org-table-fix-formulas (key replace &optional limit delta remove)
9786 "Modify the equations after the table structure has been edited.
9787 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
9788 For all numbers larger than LIMIT, shift them by DELTA."
9789 (save-excursion
9790 (goto-char (org-table-end))
9791 (when (looking-at "#\\+TBLFM:")
9792 (let ((re (concat key "\\([0-9]+\\)"))
9793 (re2
9794 (when remove
9795 (if (equal key "$")
9796 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
9797 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
9798 s n a)
9799 (when remove
9800 (while (re-search-forward re2 (point-at-eol) t)
9801 (replace-match "")))
9802 (while (re-search-forward re (point-at-eol) t)
9803 (setq s (match-string 1) n (string-to-number s))
9804 (cond
9805 ((setq a (assoc s replace))
9806 (replace-match (concat key (cdr a)) t t))
9807 ((and limit (> n limit))
9808 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
9810 (defun org-table-get-specials ()
9811 "Get the column names and local parameters for this table."
9812 (save-excursion
9813 (let ((beg (org-table-begin)) (end (org-table-end))
9814 names name fields fields1 field cnt
9815 c v l line col types dlines hlines)
9816 (setq org-table-column-names nil
9817 org-table-local-parameters nil
9818 org-table-named-field-locations nil
9819 org-table-current-begin-line nil
9820 org-table-current-begin-pos nil
9821 org-table-current-line-types nil)
9822 (goto-char beg)
9823 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9824 (setq names (org-split-string (match-string 1) " *| *")
9825 cnt 1)
9826 (while (setq name (pop names))
9827 (setq cnt (1+ cnt))
9828 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9829 (push (cons name (int-to-string cnt)) org-table-column-names))))
9830 (setq org-table-column-names (nreverse org-table-column-names))
9831 (setq org-table-column-name-regexp
9832 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9833 (goto-char beg)
9834 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9835 (setq fields (org-split-string (match-string 1) " *| *"))
9836 (while (setq field (pop fields))
9837 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9838 (push (cons (match-string 1 field) (match-string 2 field))
9839 org-table-local-parameters))))
9840 (goto-char beg)
9841 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9842 (setq c (match-string 1)
9843 fields (org-split-string (match-string 2) " *| *"))
9844 (save-excursion
9845 (beginning-of-line (if (equal c "_") 2 0))
9846 (setq line (org-current-line) col 1)
9847 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9848 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9849 (while (and fields1 (setq field (pop fields)))
9850 (setq v (pop fields1) col (1+ col))
9851 (when (and (stringp field) (stringp v)
9852 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9853 (push (cons field v) org-table-local-parameters)
9854 (push (list field line col) org-table-named-field-locations))))
9855 ;; Analyse the line types
9856 (goto-char beg)
9857 (setq org-table-current-begin-line (org-current-line)
9858 org-table-current-begin-pos (point)
9859 l org-table-current-begin-line)
9860 (while (looking-at "[ \t]*|\\(-\\)?")
9861 (push (if (match-end 1) 'hline 'dline) types)
9862 (if (match-end 1) (push l hlines) (push l dlines))
9863 (beginning-of-line 2)
9864 (setq l (1+ l)))
9865 (setq org-table-current-line-types (apply 'vector (nreverse types))
9866 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
9867 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
9869 (defun org-table-maybe-eval-formula ()
9870 "Check if the current field starts with \"=\" or \":=\".
9871 If yes, store the formula and apply it."
9872 ;; We already know we are in a table. Get field will only return a formula
9873 ;; when appropriate. It might return a separator line, but no problem.
9874 (when org-table-formula-evaluate-inline
9875 (let* ((field (org-trim (or (org-table-get-field) "")))
9876 named eq)
9877 (when (string-match "^:?=\\(.*\\)" field)
9878 (setq named (equal (string-to-char field) ?:)
9879 eq (match-string 1 field))
9880 (if (or (fboundp 'calc-eval)
9881 (equal (substring eq 0 (min 2 (length eq))) "'("))
9882 (org-table-eval-formula (if named '(4) nil)
9883 (org-table-formula-from-user eq))
9884 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
9886 (defvar org-recalc-commands nil
9887 "List of commands triggering the recalculation of a line.
9888 Will be filled automatically during use.")
9890 (defvar org-recalc-marks
9891 '((" " . "Unmarked: no special line, no automatic recalculation")
9892 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9893 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9894 ("!" . "Column name definition line. Reference in formula as $name.")
9895 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9896 ("_" . "Names for values in row below this one.")
9897 ("^" . "Names for values in row above this one.")))
9899 (defun org-table-rotate-recalc-marks (&optional newchar)
9900 "Rotate the recalculation mark in the first column.
9901 If in any row, the first field is not consistent with a mark,
9902 insert a new column for the markers.
9903 When there is an active region, change all the lines in the region,
9904 after prompting for the marking character.
9905 After each change, a message will be displayed indicating the meaning
9906 of the new mark."
9907 (interactive)
9908 (unless (org-at-table-p) (error "Not at a table"))
9909 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9910 (beg (org-table-begin))
9911 (end (org-table-end))
9912 (l (org-current-line))
9913 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9914 (l2 (if (org-region-active-p) (org-current-line (region-end))))
9915 (have-col
9916 (save-excursion
9917 (goto-char beg)
9918 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
9919 (col (org-table-current-column))
9920 (forcenew (car (assoc newchar org-recalc-marks)))
9921 epos new)
9922 (when l1
9923 (message "Change region to what mark? Type # * ! $ or SPC: ")
9924 (setq newchar (char-to-string (read-char-exclusive))
9925 forcenew (car (assoc newchar org-recalc-marks))))
9926 (if (and newchar (not forcenew))
9927 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
9928 newchar))
9929 (if l1 (goto-line l1))
9930 (save-excursion
9931 (beginning-of-line 1)
9932 (unless (looking-at org-table-dataline-regexp)
9933 (error "Not at a table data line")))
9934 (unless have-col
9935 (org-table-goto-column 1)
9936 (org-table-insert-column)
9937 (org-table-goto-column (1+ col)))
9938 (setq epos (point-at-eol))
9939 (save-excursion
9940 (beginning-of-line 1)
9941 (org-table-get-field
9942 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
9943 (concat " "
9944 (setq new (or forcenew
9945 (cadr (member (match-string 1) marks))))
9946 " ")
9947 " # ")))
9948 (if (and l1 l2)
9949 (progn
9950 (goto-line l1)
9951 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
9952 (and (looking-at org-table-dataline-regexp)
9953 (org-table-get-field 1 (concat " " new " "))))
9954 (goto-line l1)))
9955 (if (not (= epos (point-at-eol))) (org-table-align))
9956 (goto-line l)
9957 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
9959 (defun org-table-maybe-recalculate-line ()
9960 "Recompute the current line if marked for it, and if we haven't just done it."
9961 (interactive)
9962 (and org-table-allow-automatic-line-recalculation
9963 (not (and (memq last-command org-recalc-commands)
9964 (equal org-last-recalc-line (org-current-line))))
9965 (save-excursion (beginning-of-line 1)
9966 (looking-at org-table-auto-recalculate-regexp))
9967 (org-table-recalculate) t))
9969 (defvar org-table-formula-debug nil
9970 "Non-nil means, debug table formulas.
9971 When nil, simply write \"#ERROR\" in corrupted fields.")
9972 (make-variable-buffer-local 'org-table-formula-debug)
9974 (defvar modes)
9975 (defsubst org-set-calc-mode (var &optional value)
9976 (if (stringp var)
9977 (setq var (assoc var '(("D" calc-angle-mode deg)
9978 ("R" calc-angle-mode rad)
9979 ("F" calc-prefer-frac t)
9980 ("S" calc-symbolic-mode t)))
9981 value (nth 2 var) var (nth 1 var)))
9982 (if (memq var modes)
9983 (setcar (cdr (memq var modes)) value)
9984 (cons var (cons value modes)))
9985 modes)
9987 (defun org-table-eval-formula (&optional arg equation
9988 suppress-align suppress-const
9989 suppress-store suppress-analysis)
9990 "Replace the table field value at the cursor by the result of a calculation.
9992 This function makes use of Dave Gillespie's Calc package, in my view the
9993 most exciting program ever written for GNU Emacs. So you need to have Calc
9994 installed in order to use this function.
9996 In a table, this command replaces the value in the current field with the
9997 result of a formula. It also installs the formula as the \"current\" column
9998 formula, by storing it in a special line below the table. When called
9999 with a `C-u' prefix, the current field must ba a named field, and the
10000 formula is installed as valid in only this specific field.
10002 When called with two `C-u' prefixes, insert the active equation
10003 for the field back into the current field, so that it can be
10004 edited there. This is useful in order to use \\[org-table-show-reference]
10005 to check the referenced fields.
10007 When called, the command first prompts for a formula, which is read in
10008 the minibuffer. Previously entered formulas are available through the
10009 history list, and the last used formula is offered as a default.
10010 These stored formulas are adapted correctly when moving, inserting, or
10011 deleting columns with the corresponding commands.
10013 The formula can be any algebraic expression understood by the Calc package.
10014 For details, see the Org-mode manual.
10016 This function can also be called from Lisp programs and offers
10017 additional arguments: EQUATION can be the formula to apply. If this
10018 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10019 used to speed-up recursive calls by by-passing unnecessary aligns.
10020 SUPPRESS-CONST suppresses the interpretation of constants in the
10021 formula, assuming that this has been done already outside the function.
10022 SUPPRESS-STORE means the formula should not be stored, either because
10023 it is already stored, or because it is a modified equation that should
10024 not overwrite the stored one."
10025 (interactive "P")
10026 (org-table-check-inside-data-field)
10027 (or suppress-analysis (org-table-get-specials))
10028 (if (equal arg '(16))
10029 (let ((eq (org-table-current-field-formula)))
10030 (or eq (error "No equation active for current field"))
10031 (org-table-get-field nil eq)
10032 (org-table-align)
10033 (setq org-table-may-need-update t))
10034 (let* (fields
10035 (ndown (if (integerp arg) arg 1))
10036 (org-table-automatic-realign nil)
10037 (case-fold-search nil)
10038 (down (> ndown 1))
10039 (formula (if (and equation suppress-store)
10040 equation
10041 (org-table-get-formula equation (equal arg '(4)))))
10042 (n0 (org-table-current-column))
10043 (modes (copy-sequence org-calc-default-modes))
10044 (numbers nil) ; was a variable, now fixed default
10045 (keep-empty nil)
10046 n form form0 bw fmt x ev orig c lispp literal)
10047 ;; Parse the format string. Since we have a lot of modes, this is
10048 ;; a lot of work. However, I think calc still uses most of the time.
10049 (if (string-match ";" formula)
10050 (let ((tmp (org-split-string formula ";")))
10051 (setq formula (car tmp)
10052 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10053 (nth 1 tmp)))
10054 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
10055 (setq c (string-to-char (match-string 1 fmt))
10056 n (string-to-number (match-string 2 fmt)))
10057 (if (= c ?p)
10058 (setq modes (org-set-calc-mode 'calc-internal-prec n))
10059 (setq modes (org-set-calc-mode
10060 'calc-float-format
10061 (list (cdr (assoc c '((?n . float) (?f . fix)
10062 (?s . sci) (?e . eng))))
10063 n))))
10064 (setq fmt (replace-match "" t t fmt)))
10065 (if (string-match "[NT]" fmt)
10066 (setq numbers (equal (match-string 0 fmt) "N")
10067 fmt (replace-match "" t t fmt)))
10068 (if (string-match "L" fmt)
10069 (setq literal t
10070 fmt (replace-match "" t t fmt)))
10071 (if (string-match "E" fmt)
10072 (setq keep-empty t
10073 fmt (replace-match "" t t fmt)))
10074 (while (string-match "[DRFS]" fmt)
10075 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10076 (setq fmt (replace-match "" t t fmt)))
10077 (unless (string-match "\\S-" fmt)
10078 (setq fmt nil))))
10079 (if (and (not suppress-const) org-table-formula-use-constants)
10080 (setq formula (org-table-formula-substitute-names formula)))
10081 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10082 (while (> ndown 0)
10083 (setq fields (org-split-string
10084 (org-no-properties
10085 (buffer-substring (point-at-bol) (point-at-eol)))
10086 " *| *"))
10087 (if (eq numbers t)
10088 (setq fields (mapcar
10089 (lambda (x) (number-to-string (string-to-number x)))
10090 fields)))
10091 (setq ndown (1- ndown))
10092 (setq form (copy-sequence formula)
10093 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
10094 (if (and lispp literal) (setq lispp 'literal))
10095 ;; Check for old vertical references
10096 (setq form (org-rewrite-old-row-references form))
10097 ;; Insert complex ranges
10098 (while (string-match org-table-range-regexp form)
10099 (setq form
10100 (replace-match
10101 (save-match-data
10102 (org-table-make-reference
10103 (org-table-get-range (match-string 0 form) nil n0)
10104 keep-empty numbers lispp))
10105 t t form)))
10106 ;; Insert simple ranges
10107 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
10108 (setq form
10109 (replace-match
10110 (save-match-data
10111 (org-table-make-reference
10112 (org-sublist
10113 fields (string-to-number (match-string 1 form))
10114 (string-to-number (match-string 2 form)))
10115 keep-empty numbers lispp))
10116 t t form)))
10117 (setq form0 form)
10118 ;; Insert the references to fields in same row
10119 (while (string-match "\\$\\([0-9]+\\)" form)
10120 (setq n (string-to-number (match-string 1 form))
10121 x (nth (1- (if (= n 0) n0 n)) fields))
10122 (unless x (error "Invalid field specifier \"%s\""
10123 (match-string 0 form)))
10124 (setq form (replace-match
10125 (save-match-data
10126 (org-table-make-reference x nil numbers lispp))
10127 t t form)))
10129 (if lispp
10130 (setq ev (condition-case nil
10131 (eval (eval (read form)))
10132 (error "#ERROR"))
10133 ev (if (numberp ev) (number-to-string ev) ev))
10134 (or (fboundp 'calc-eval)
10135 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
10136 (setq ev (calc-eval (cons form modes)
10137 (if numbers 'num))))
10139 (when org-table-formula-debug
10140 (with-output-to-temp-buffer "*Substitution History*"
10141 (princ (format "Substitution history of formula
10142 Orig: %s
10143 $xyz-> %s
10144 @r$c-> %s
10145 $1-> %s\n" orig formula form0 form))
10146 (if (listp ev)
10147 (princ (format " %s^\nError: %s"
10148 (make-string (car ev) ?\-) (nth 1 ev)))
10149 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10150 ev (or fmt "NONE")
10151 (if fmt (format fmt (string-to-number ev)) ev)))))
10152 (setq bw (get-buffer-window "*Substitution History*"))
10153 (shrink-window-if-larger-than-buffer bw)
10154 (unless (and (interactive-p) (not ndown))
10155 (unless (let (inhibit-redisplay)
10156 (y-or-n-p "Debugging Formula. Continue to next? "))
10157 (org-table-align)
10158 (error "Abort"))
10159 (delete-window bw)
10160 (message "")))
10161 (if (listp ev) (setq fmt nil ev "#ERROR"))
10162 (org-table-justify-field-maybe
10163 (if fmt (format fmt (string-to-number ev)) ev))
10164 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10165 (call-interactively 'org-return)
10166 (setq ndown 0)))
10167 (and down (org-table-maybe-recalculate-line))
10168 (or suppress-align (and org-table-may-need-update
10169 (org-table-align))))))
10171 (defun org-table-put-field-property (prop value)
10172 (save-excursion
10173 (put-text-property (progn (skip-chars-backward "^|") (point))
10174 (progn (skip-chars-forward "^|") (point))
10175 prop value)))
10177 (defun org-table-get-range (desc &optional tbeg col highlight)
10178 "Get a calc vector from a column, accorting to descriptor DESC.
10179 Optional arguments TBEG and COL can give the beginning of the table and
10180 the current column, to avoid unnecessary parsing.
10181 HIGHLIGHT means, just highlight the range."
10182 (if (not (equal (string-to-char desc) ?@))
10183 (setq desc (concat "@" desc)))
10184 (save-excursion
10185 (or tbeg (setq tbeg (org-table-begin)))
10186 (or col (setq col (org-table-current-column)))
10187 (let ((thisline (org-current-line))
10188 beg end c1 c2 r1 r2 rangep tmp)
10189 (unless (string-match org-table-range-regexp desc)
10190 (error "Invalid table range specifier `%s'" desc))
10191 (setq rangep (match-end 3)
10192 r1 (and (match-end 1) (match-string 1 desc))
10193 r2 (and (match-end 4) (match-string 4 desc))
10194 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
10195 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
10197 (and c1 (setq c1 (+ (string-to-number c1)
10198 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
10199 (and c2 (setq c2 (+ (string-to-number c2)
10200 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
10201 (if (equal r1 "") (setq r1 nil))
10202 (if (equal r2 "") (setq r2 nil))
10203 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10204 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10205 ; (setq r2 (or r2 r1) c2 (or c2 c1))
10206 (if (not r1) (setq r1 thisline))
10207 (if (not r2) (setq r2 thisline))
10208 (if (not c1) (setq c1 col))
10209 (if (not c2) (setq c2 col))
10210 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10211 ;; just one field
10212 (progn
10213 (goto-line r1)
10214 (while (not (looking-at org-table-dataline-regexp))
10215 (beginning-of-line 2))
10216 (prog1 (org-trim (org-table-get-field c1))
10217 (if highlight (org-table-highlight-rectangle (point) (point)))))
10218 ;; A range, return a vector
10219 ;; First sort the numbers to get a regular ractangle
10220 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10221 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10222 (goto-line r1)
10223 (while (not (looking-at org-table-dataline-regexp))
10224 (beginning-of-line 2))
10225 (org-table-goto-column c1)
10226 (setq beg (point))
10227 (goto-line r2)
10228 (while (not (looking-at org-table-dataline-regexp))
10229 (beginning-of-line 0))
10230 (org-table-goto-column c2)
10231 (setq end (point))
10232 (if highlight
10233 (org-table-highlight-rectangle
10234 beg (progn (skip-chars-forward "^|\n") (point))))
10235 ;; return string representation of calc vector
10236 (mapcar 'org-trim
10237 (apply 'append (org-table-copy-region beg end)))))))
10239 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10240 "Analyze descriptor DESC and retrieve the corresponding line number.
10241 The cursor is currently in line CLINE, the table begins in line BLINE,
10242 and TABLE is a vector with line types."
10243 (if (string-match "^[0-9]+$" desc)
10244 (aref org-table-dlines (string-to-number desc))
10245 (setq cline (or cline (org-current-line))
10246 bline (or bline org-table-current-begin-line)
10247 table (or table org-table-current-line-types))
10248 (if (or
10249 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10250 ;; 1 2 3 4 5 6
10251 (and (not (match-end 3)) (not (match-end 6)))
10252 (and (match-end 3) (match-end 6) (not (match-end 5))))
10253 (error "invalid row descriptor `%s'" desc))
10254 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10255 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10256 (odir (and (match-end 5) (match-string 5 desc)))
10257 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10258 (i (- cline bline))
10259 (rel (and (match-end 6)
10260 (or (and (match-end 1) (not (match-end 3)))
10261 (match-end 5)))))
10262 (if (and hn (not hdir))
10263 (progn
10264 (setq i 0 hdir "+")
10265 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10266 (if (and (not hn) on (not odir))
10267 (error "should never happen");;(aref org-table-dlines on)
10268 (if (and hn (> hn 0))
10269 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10270 (if on
10271 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10272 (+ bline i)))))
10274 (defun org-find-row-type (table i type backwards relative n)
10275 (let ((l (length table)))
10276 (while (> n 0)
10277 (while (and (setq i (+ i (if backwards -1 1)))
10278 (>= i 0) (< i l)
10279 (not (eq (aref table i) type))
10280 (if (and relative (eq (aref table i) 'hline))
10281 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10282 t)))
10283 (setq n (1- n)))
10284 (if (or (< i 0) (>= i l))
10285 (error "Row descriptior leads outside table")
10286 i)))
10288 (defun org-rewrite-old-row-references (s)
10289 (if (string-match "&[-+0-9I]" s)
10290 (error "Formula contains old &row reference, please rewrite using @-syntax")
10293 (defun org-table-make-reference (elements keep-empty numbers lispp)
10294 "Convert list ELEMENTS to something appropriate to insert into formula.
10295 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10296 NUMBERS indicates that everything should be converted to numbers.
10297 LISPP means to return something appropriate for a Lisp list."
10298 (if (stringp elements) ; just a single val
10299 (if lispp
10300 (if (eq lispp 'literal)
10301 elements
10302 (prin1-to-string (if numbers (string-to-number elements) elements)))
10303 (if (equal elements "") (setq elements "0"))
10304 (if numbers (number-to-string (string-to-number elements)) elements))
10305 (unless keep-empty
10306 (setq elements
10307 (delq nil
10308 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10309 elements))))
10310 (setq elements (or elements '("0")))
10311 (if lispp
10312 (mapconcat
10313 (lambda (x)
10314 (if (eq lispp 'literal)
10316 (prin1-to-string (if numbers (string-to-number x) x))))
10317 elements " ")
10318 (concat "[" (mapconcat
10319 (lambda (x)
10320 (if numbers (number-to-string (string-to-number x)) x))
10321 elements
10322 ",") "]"))))
10324 (defun org-table-recalculate (&optional all noalign)
10325 "Recalculate the current table line by applying all stored formulas.
10326 With prefix arg ALL, do this for all lines in the table."
10327 (interactive "P")
10328 (or (memq this-command org-recalc-commands)
10329 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10330 (unless (org-at-table-p) (error "Not at a table"))
10331 (if (equal all '(16))
10332 (org-table-iterate)
10333 (org-table-get-specials)
10334 (let* ((eqlist (sort (org-table-get-stored-formulas)
10335 (lambda (a b) (string< (car a) (car b)))))
10336 (inhibit-redisplay (not debug-on-error))
10337 (line-re org-table-dataline-regexp)
10338 (thisline (org-current-line))
10339 (thiscol (org-table-current-column))
10340 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10341 ;; Insert constants in all formulas
10342 (setq eqlist
10343 (mapcar (lambda (x)
10344 (setcdr x (org-table-formula-substitute-names (cdr x)))
10346 eqlist))
10347 ;; Split the equation list
10348 (while (setq eq (pop eqlist))
10349 (if (<= (string-to-char (car eq)) ?9)
10350 (push eq eqlnum)
10351 (push eq eqlname)))
10352 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10353 (if all
10354 (progn
10355 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10356 (goto-char (setq beg (org-table-begin)))
10357 (if (re-search-forward org-table-calculate-mark-regexp end t)
10358 ;; This is a table with marked lines, compute selected lines
10359 (setq line-re org-table-recalculate-regexp)
10360 ;; Move forward to the first non-header line
10361 (if (and (re-search-forward org-table-dataline-regexp end t)
10362 (re-search-forward org-table-hline-regexp end t)
10363 (re-search-forward org-table-dataline-regexp end t))
10364 (setq beg (match-beginning 0))
10365 nil))) ;; just leave beg where it is
10366 (setq beg (point-at-bol)
10367 end (move-marker (make-marker) (1+ (point-at-eol)))))
10368 (goto-char beg)
10369 (and all (message "Re-applying formulas to full table..."))
10371 ;; First find the named fields, and mark them untouchanble
10372 (remove-text-properties beg end '(org-untouchable t))
10373 (while (setq eq (pop eqlname))
10374 (setq name (car eq)
10375 a (assoc name org-table-named-field-locations))
10376 (and (not a)
10377 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10378 (setq a (list name
10379 (aref org-table-dlines
10380 (string-to-number (match-string 1 name)))
10381 (string-to-number (match-string 2 name)))))
10382 (when (and a (or all (equal (nth 1 a) thisline)))
10383 (message "Re-applying formula to field: %s" name)
10384 (goto-line (nth 1 a))
10385 (org-table-goto-column (nth 2 a))
10386 (push (append a (list (cdr eq))) eqlname1)
10387 (org-table-put-field-property :org-untouchable t)))
10389 ;; Now evauluate the column formulas, but skip fields covered by
10390 ;; field formulas
10391 (goto-char beg)
10392 (while (re-search-forward line-re end t)
10393 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10394 ;; Unprotected line, recalculate
10395 (and all (message "Re-applying formulas to full table...(line %d)"
10396 (setq cnt (1+ cnt))))
10397 (setq org-last-recalc-line (org-current-line))
10398 (setq eql eqlnum)
10399 (while (setq entry (pop eql))
10400 (goto-line org-last-recalc-line)
10401 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10402 (unless (get-text-property (point) :org-untouchable)
10403 (org-table-eval-formula nil (cdr entry)
10404 'noalign 'nocst 'nostore 'noanalysis)))))
10406 ;; Now evaluate the field formulas
10407 (while (setq eq (pop eqlname1))
10408 (message "Re-applying formula to field: %s" (car eq))
10409 (goto-line (nth 1 eq))
10410 (org-table-goto-column (nth 2 eq))
10411 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10412 'nostore 'noanalysis))
10414 (goto-line thisline)
10415 (org-table-goto-column thiscol)
10416 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10417 (or noalign (and org-table-may-need-update (org-table-align))
10418 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10420 ;; back to initial position
10421 (message "Re-applying formulas...done")
10422 (goto-line thisline)
10423 (org-table-goto-column thiscol)
10424 (or noalign (and org-table-may-need-update (org-table-align))
10425 (and all (message "Re-applying formulas...done"))))))
10427 (defun org-table-iterate (&optional arg)
10428 "Recalculate the table until it does not change anymore."
10429 (interactive "P")
10430 (let ((imax (if arg (prefix-numeric-value arg) 10))
10431 (i 0)
10432 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10433 thistbl)
10434 (catch 'exit
10435 (while (< i imax)
10436 (setq i (1+ i))
10437 (org-table-recalculate 'all)
10438 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10439 (if (not (string= lasttbl thistbl))
10440 (setq lasttbl thistbl)
10441 (if (> i 1)
10442 (message "Convergence after %d iterations" i)
10443 (message "Table was already stable"))
10444 (throw 'exit t)))
10445 (error "No convergence after %d iterations" i))))
10447 (defun org-table-formula-substitute-names (f)
10448 "Replace $const with values in string F."
10449 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10450 ;; First, check for column names
10451 (while (setq start (string-match org-table-column-name-regexp f start))
10452 (setq start (1+ start))
10453 (setq a (assoc (match-string 1 f) org-table-column-names))
10454 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10455 ;; Parameters and constants
10456 (setq start 0)
10457 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10458 (setq start (1+ start))
10459 (if (setq a (save-match-data
10460 (org-table-get-constant (match-string 1 f))))
10461 (setq f (replace-match
10462 (concat (if pp "(") a (if pp ")")) t t f))))
10463 (if org-table-formula-debug
10464 (put-text-property 0 (length f) :orig-formula f1 f))
10467 (defun org-table-get-constant (const)
10468 "Find the value for a parameter or constant in a formula.
10469 Parameters get priority."
10470 (or (cdr (assoc const org-table-local-parameters))
10471 (cdr (assoc const org-table-formula-constants-local))
10472 (cdr (assoc const org-table-formula-constants))
10473 (and (fboundp 'constants-get) (constants-get const))
10474 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10475 (org-entry-get nil (substring const 5) 'inherit))
10476 "#UNDEFINED_NAME"))
10478 (defvar org-table-fedit-map
10479 (let ((map (make-sparse-keymap)))
10480 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10481 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10482 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10483 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10484 (org-defkey map "\C-c?" 'org-table-show-reference)
10485 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10486 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10487 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10488 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10489 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10490 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10491 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10492 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10493 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10494 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10495 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10496 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10497 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10498 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10499 map))
10501 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10502 '("Edit-Formulas"
10503 ["Finish and Install" org-table-fedit-finish t]
10504 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10505 ["Abort" org-table-fedit-abort t]
10506 "--"
10507 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10508 ["Complete Lisp Symbol" lisp-complete-symbol t]
10509 "--"
10510 "Shift Reference at Point"
10511 ["Up" org-table-fedit-ref-up t]
10512 ["Down" org-table-fedit-ref-down t]
10513 ["Left" org-table-fedit-ref-left t]
10514 ["Right" org-table-fedit-ref-right t]
10516 "Change Test Row for Column Formulas"
10517 ["Up" org-table-fedit-line-up t]
10518 ["Down" org-table-fedit-line-down t]
10519 "--"
10520 ["Scroll Table Window" org-table-fedit-scroll t]
10521 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10522 ["Show Table Grid" org-table-fedit-toggle-coordinates
10523 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10524 org-table-overlay-coordinates)]
10525 "--"
10526 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10527 :style toggle :selected org-table-buffer-is-an]))
10529 (defvar org-pos)
10531 (defun org-table-edit-formulas ()
10532 "Edit the formulas of the current table in a separate buffer."
10533 (interactive)
10534 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10535 (beginning-of-line 0))
10536 (unless (org-at-table-p) (error "Not at a table"))
10537 (org-table-get-specials)
10538 (let ((key (org-table-current-field-formula 'key 'noerror))
10539 (eql (sort (org-table-get-stored-formulas 'noerror)
10540 'org-table-formula-less-p))
10541 (pos (move-marker (make-marker) (point)))
10542 (startline 1)
10543 (wc (current-window-configuration))
10544 (titles '((column . "# Column Formulas\n")
10545 (field . "# Field Formulas\n")
10546 (named . "# Named Field Formulas\n")))
10547 entry s type title)
10548 (org-switch-to-buffer-other-window "*Edit Formulas*")
10549 (erase-buffer)
10550 ;; Keep global-font-lock-mode from turning on font-lock-mode
10551 (let ((font-lock-global-modes '(not fundamental-mode)))
10552 (fundamental-mode))
10553 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10554 (org-set-local 'org-pos pos)
10555 (org-set-local 'org-window-configuration wc)
10556 (use-local-map org-table-fedit-map)
10557 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10558 (easy-menu-add org-table-fedit-menu)
10559 (setq startline (org-current-line))
10560 (while (setq entry (pop eql))
10561 (setq type (cond
10562 ((equal (string-to-char (car entry)) ?@) 'field)
10563 ((string-match "^[0-9]" (car entry)) 'column)
10564 (t 'named)))
10565 (when (setq title (assq type titles))
10566 (or (bobp) (insert "\n"))
10567 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10568 (setq titles (delq title titles)))
10569 (if (equal key (car entry)) (setq startline (org-current-line)))
10570 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10571 (car entry) " = " (cdr entry) "\n"))
10572 (remove-text-properties 0 (length s) '(face nil) s)
10573 (insert s))
10574 (if (eq org-table-use-standard-references t)
10575 (org-table-fedit-toggle-ref-type))
10576 (goto-line startline)
10577 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10579 (defun org-table-fedit-post-command ()
10580 (when (not (memq this-command '(lisp-complete-symbol)))
10581 (let ((win (selected-window)))
10582 (save-excursion
10583 (condition-case nil
10584 (org-table-show-reference)
10585 (error nil))
10586 (select-window win)))))
10588 (defun org-table-formula-to-user (s)
10589 "Convert a formula from internal to user representation."
10590 (if (eq org-table-use-standard-references t)
10591 (org-table-convert-refs-to-an s)
10594 (defun org-table-formula-from-user (s)
10595 "Convert a formula from user to internal representation."
10596 (if org-table-use-standard-references
10597 (org-table-convert-refs-to-rc s)
10600 (defun org-table-convert-refs-to-rc (s)
10601 "Convert spreadsheet references from AB7 to @7$28.
10602 Works for single references, but also for entire formulas and even the
10603 full TBLFM line."
10604 (let ((start 0))
10605 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10606 (cond
10607 ((match-end 3)
10608 ;; format match, just advance
10609 (setq start (match-end 0)))
10610 ((and (> (match-beginning 0) 0)
10611 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10612 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10613 ;; 3.e5 or something like this.
10614 (setq start (match-end 0)))
10616 (setq start (match-beginning 0)
10617 s (replace-match
10618 (if (equal (match-string 2 s) "&")
10619 (format "$%d" (org-letters-to-number (match-string 1 s)))
10620 (format "@%d$%d"
10621 (string-to-number (match-string 2 s))
10622 (org-letters-to-number (match-string 1 s))))
10623 t t s)))))
10626 (defun org-table-convert-refs-to-an (s)
10627 "Convert spreadsheet references from to @7$28 to AB7.
10628 Works for single references, but also for entire formulas and even the
10629 full TBLFM line."
10630 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10631 (setq s (replace-match
10632 (format "%s%d"
10633 (org-number-to-letters
10634 (string-to-number (match-string 2 s)))
10635 (string-to-number (match-string 1 s)))
10636 t t s)))
10637 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10638 (setq s (replace-match (concat "\\1"
10639 (org-number-to-letters
10640 (string-to-number (match-string 2 s))) "&")
10641 t nil s)))
10644 (defun org-letters-to-number (s)
10645 "Convert a base 26 number represented by letters into an integer.
10646 For example: AB -> 28."
10647 (let ((n 0))
10648 (setq s (upcase s))
10649 (while (> (length s) 0)
10650 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10651 s (substring s 1)))
10654 (defun org-number-to-letters (n)
10655 "Convert an integer into a base 26 number represented by letters.
10656 For example: 28 -> AB."
10657 (let ((s ""))
10658 (while (> n 0)
10659 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10660 n (/ (1- n) 26)))
10663 (defun org-table-fedit-convert-buffer (function)
10664 "Convert all references in this buffer, using FUNTION."
10665 (let ((line (org-current-line)))
10666 (goto-char (point-min))
10667 (while (not (eobp))
10668 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10669 (delete-region (point) (point-at-eol))
10670 (or (eobp) (forward-char 1)))
10671 (goto-line line)))
10673 (defun org-table-fedit-toggle-ref-type ()
10674 "Convert all references in the buffer from B3 to @3$2 and back."
10675 (interactive)
10676 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10677 (org-table-fedit-convert-buffer
10678 (if org-table-buffer-is-an
10679 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10680 (message "Reference type switched to %s"
10681 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10683 (defun org-table-fedit-ref-up ()
10684 "Shift the reference at point one row/hline up."
10685 (interactive)
10686 (org-table-fedit-shift-reference 'up))
10687 (defun org-table-fedit-ref-down ()
10688 "Shift the reference at point one row/hline down."
10689 (interactive)
10690 (org-table-fedit-shift-reference 'down))
10691 (defun org-table-fedit-ref-left ()
10692 "Shift the reference at point one field to the left."
10693 (interactive)
10694 (org-table-fedit-shift-reference 'left))
10695 (defun org-table-fedit-ref-right ()
10696 "Shift the reference at point one field to the right."
10697 (interactive)
10698 (org-table-fedit-shift-reference 'right))
10700 (defun org-table-fedit-shift-reference (dir)
10701 (cond
10702 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10703 (if (memq dir '(left right))
10704 (org-rematch-and-replace 1 (eq dir 'left))
10705 (error "Cannot shift reference in this direction")))
10706 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10707 ;; A B3-like reference
10708 (if (memq dir '(up down))
10709 (org-rematch-and-replace 2 (eq dir 'up))
10710 (org-rematch-and-replace 1 (eq dir 'left))))
10711 ((org-at-regexp-p
10712 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10713 ;; An internal reference
10714 (if (memq dir '(up down))
10715 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10716 (org-rematch-and-replace 5 (eq dir 'left))))))
10718 (defun org-rematch-and-replace (n &optional decr hline)
10719 "Re-match the group N, and replace it with the shifted refrence."
10720 (or (match-end n) (error "Cannot shift reference in this direction"))
10721 (goto-char (match-beginning n))
10722 (and (looking-at (regexp-quote (match-string n)))
10723 (replace-match (org-shift-refpart (match-string 0) decr hline)
10724 t t)))
10726 (defun org-shift-refpart (ref &optional decr hline)
10727 "Shift a refrence part REF.
10728 If DECR is set, decrease the references row/column, else increase.
10729 If HLINE is set, this may be a hline reference, it certainly is not
10730 a translation reference."
10731 (save-match-data
10732 (let* ((sign (string-match "^[-+]" ref)) n)
10734 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10735 (cond
10736 ((and hline (string-match "^I+" ref))
10737 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10738 (setq n (+ n (if decr -1 1)))
10739 (if (= n 0) (setq n (+ n (if decr -1 1))))
10740 (if sign
10741 (setq sign (if (< n 0) "-" "+") n (abs n))
10742 (setq n (max 1 n)))
10743 (concat sign (make-string n ?I)))
10745 ((string-match "^[0-9]+" ref)
10746 (setq n (string-to-number (concat sign ref)))
10747 (setq n (+ n (if decr -1 1)))
10748 (if sign
10749 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10750 (number-to-string (max 1 n))))
10752 ((string-match "^[a-zA-Z]+" ref)
10753 (org-number-to-letters
10754 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10756 (t (error "Cannot shift reference"))))))
10758 (defun org-table-fedit-toggle-coordinates ()
10759 "Toggle the display of coordinates in the refrenced table."
10760 (interactive)
10761 (let ((pos (marker-position org-pos)))
10762 (with-current-buffer (marker-buffer org-pos)
10763 (save-excursion
10764 (goto-char pos)
10765 (org-table-toggle-coordinate-overlays)))))
10767 (defun org-table-fedit-finish (&optional arg)
10768 "Parse the buffer for formula definitions and install them.
10769 With prefix ARG, apply the new formulas to the table."
10770 (interactive "P")
10771 (org-table-remove-rectangle-highlight)
10772 (if org-table-use-standard-references
10773 (progn
10774 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
10775 (setq org-table-buffer-is-an nil)))
10776 (let ((pos org-pos) eql var form)
10777 (goto-char (point-min))
10778 (while (re-search-forward
10779 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
10780 nil t)
10781 (setq var (if (match-end 2) (match-string 2) (match-string 1))
10782 form (match-string 3))
10783 (setq form (org-trim form))
10784 (when (not (equal form ""))
10785 (while (string-match "[ \t]*\n[ \t]*" form)
10786 (setq form (replace-match " " t t form)))
10787 (when (assoc var eql)
10788 (error "Double formulas for %s" var))
10789 (push (cons var form) eql)))
10790 (setq org-pos nil)
10791 (set-window-configuration org-window-configuration)
10792 (select-window (get-buffer-window (marker-buffer pos)))
10793 (goto-char pos)
10794 (unless (org-at-table-p)
10795 (error "Lost table position - cannot install formulae"))
10796 (org-table-store-formulas eql)
10797 (move-marker pos nil)
10798 (kill-buffer "*Edit Formulas*")
10799 (if arg
10800 (org-table-recalculate 'all)
10801 (message "New formulas installed - press C-u C-c C-c to apply."))))
10803 (defun org-table-fedit-abort ()
10804 "Abort editing formulas, without installing the changes."
10805 (interactive)
10806 (org-table-remove-rectangle-highlight)
10807 (let ((pos org-pos))
10808 (set-window-configuration org-window-configuration)
10809 (select-window (get-buffer-window (marker-buffer pos)))
10810 (goto-char pos)
10811 (move-marker pos nil)
10812 (message "Formula editing aborted without installing changes")))
10814 (defun org-table-fedit-lisp-indent ()
10815 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
10816 (interactive)
10817 (let ((pos (point)) beg end ind)
10818 (beginning-of-line 1)
10819 (cond
10820 ((looking-at "[ \t]")
10821 (goto-char pos)
10822 (call-interactively 'lisp-indent-line))
10823 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
10824 ((not (fboundp 'pp-buffer))
10825 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
10826 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
10827 (goto-char (- (match-end 0) 2))
10828 (setq beg (point))
10829 (setq ind (make-string (current-column) ?\ ))
10830 (condition-case nil (forward-sexp 1)
10831 (error
10832 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
10833 (setq end (point))
10834 (save-restriction
10835 (narrow-to-region beg end)
10836 (if (eq last-command this-command)
10837 (progn
10838 (goto-char (point-min))
10839 (setq this-command nil)
10840 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
10841 (replace-match " ")))
10842 (pp-buffer)
10843 (untabify (point-min) (point-max))
10844 (goto-char (1+ (point-min)))
10845 (while (re-search-forward "^." nil t)
10846 (beginning-of-line 1)
10847 (insert ind))
10848 (goto-char (point-max))
10849 (backward-delete-char 1)))
10850 (goto-char beg))
10851 (t nil))))
10853 (defvar org-show-positions nil)
10855 (defun org-table-show-reference (&optional local)
10856 "Show the location/value of the $ expression at point."
10857 (interactive)
10858 (org-table-remove-rectangle-highlight)
10859 (catch 'exit
10860 (let ((pos (if local (point) org-pos))
10861 (face2 'highlight)
10862 (org-inhibit-highlight-removal t)
10863 (win (selected-window))
10864 (org-show-positions nil)
10865 var name e what match dest)
10866 (if local (org-table-get-specials))
10867 (setq what (cond
10868 ((or (org-at-regexp-p org-table-range-regexp2)
10869 (org-at-regexp-p org-table-translate-regexp)
10870 (org-at-regexp-p org-table-range-regexp))
10871 (setq match
10872 (save-match-data
10873 (org-table-convert-refs-to-rc (match-string 0))))
10874 'range)
10875 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
10876 ((org-at-regexp-p "\\$[0-9]+") 'column)
10877 ((not local) nil)
10878 (t (error "No reference at point")))
10879 match (and what (or match (match-string 0))))
10880 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
10881 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
10882 'secondary-selection))
10883 (org-add-hook 'before-change-functions
10884 'org-table-remove-rectangle-highlight)
10885 (if (eq what 'name) (setq var (substring match 1)))
10886 (when (eq what 'range)
10887 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
10888 (setq match (org-table-formula-substitute-names match)))
10889 (unless local
10890 (save-excursion
10891 (end-of-line 1)
10892 (re-search-backward "^\\S-" nil t)
10893 (beginning-of-line 1)
10894 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
10895 (setq dest
10896 (save-match-data
10897 (org-table-convert-refs-to-rc (match-string 1))))
10898 (org-table-add-rectangle-overlay
10899 (match-beginning 1) (match-end 1) face2))))
10900 (if (and (markerp pos) (marker-buffer pos))
10901 (if (get-buffer-window (marker-buffer pos))
10902 (select-window (get-buffer-window (marker-buffer pos)))
10903 (org-switch-to-buffer-other-window (get-buffer-window
10904 (marker-buffer pos)))))
10905 (goto-char pos)
10906 (org-table-force-dataline)
10907 (when dest
10908 (setq name (substring dest 1))
10909 (cond
10910 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
10911 (setq e (assoc name org-table-named-field-locations))
10912 (goto-line (nth 1 e))
10913 (org-table-goto-column (nth 2 e)))
10914 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
10915 (let ((l (string-to-number (match-string 1 dest)))
10916 (c (string-to-number (match-string 2 dest))))
10917 (goto-line (aref org-table-dlines l))
10918 (org-table-goto-column c)))
10919 (t (org-table-goto-column (string-to-number name))))
10920 (move-marker pos (point))
10921 (org-table-highlight-rectangle nil nil face2))
10922 (cond
10923 ((equal dest match))
10924 ((not match))
10925 ((eq what 'range)
10926 (condition-case nil
10927 (save-excursion
10928 (org-table-get-range match nil nil 'highlight))
10929 (error nil)))
10930 ((setq e (assoc var org-table-named-field-locations))
10931 (goto-line (nth 1 e))
10932 (org-table-goto-column (nth 2 e))
10933 (org-table-highlight-rectangle (point) (point))
10934 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
10935 ((setq e (assoc var org-table-column-names))
10936 (org-table-goto-column (string-to-number (cdr e)))
10937 (org-table-highlight-rectangle (point) (point))
10938 (goto-char (org-table-begin))
10939 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
10940 (org-table-end) t)
10941 (progn
10942 (goto-char (match-beginning 1))
10943 (org-table-highlight-rectangle)
10944 (message "Named column (column %s)" (cdr e)))
10945 (error "Column name not found")))
10946 ((eq what 'column)
10947 ;; column number
10948 (org-table-goto-column (string-to-number (substring match 1)))
10949 (org-table-highlight-rectangle (point) (point))
10950 (message "Column %s" (substring match 1)))
10951 ((setq e (assoc var org-table-local-parameters))
10952 (goto-char (org-table-begin))
10953 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
10954 (progn
10955 (goto-char (match-beginning 1))
10956 (org-table-highlight-rectangle)
10957 (message "Local parameter."))
10958 (error "Parameter not found")))
10960 (cond
10961 ((not var) (error "No reference at point"))
10962 ((setq e (assoc var org-table-formula-constants-local))
10963 (message "Local Constant: $%s=%s in #+CONSTANTS line."
10964 var (cdr e)))
10965 ((setq e (assoc var org-table-formula-constants))
10966 (message "Constant: $%s=%s in `org-table-formula-constants'."
10967 var (cdr e)))
10968 ((setq e (and (fboundp 'constants-get) (constants-get var)))
10969 (message "Constant: $%s=%s, from `constants.el'%s."
10970 var e (format " (%s units)" constants-unit-system)))
10971 (t (error "Undefined name $%s" var)))))
10972 (goto-char pos)
10973 (when (and org-show-positions
10974 (not (memq this-command '(org-table-fedit-scroll
10975 org-table-fedit-scroll-down))))
10976 (push pos org-show-positions)
10977 (push org-table-current-begin-pos org-show-positions)
10978 (let ((min (apply 'min org-show-positions))
10979 (max (apply 'max org-show-positions)))
10980 (goto-char min) (recenter 0)
10981 (goto-char max)
10982 (or (pos-visible-in-window-p max) (recenter -1))))
10983 (select-window win))))
10985 (defun org-table-force-dataline ()
10986 "Make sure the cursor is in a dataline in a table."
10987 (unless (save-excursion
10988 (beginning-of-line 1)
10989 (looking-at org-table-dataline-regexp))
10990 (let* ((re org-table-dataline-regexp)
10991 (p1 (save-excursion (re-search-forward re nil 'move)))
10992 (p2 (save-excursion (re-search-backward re nil 'move))))
10993 (cond ((and p1 p2)
10994 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
10995 p1 p2)))
10996 ((or p1 p2) (goto-char (or p1 p2)))
10997 (t (error "No table dataline around here"))))))
10999 (defun org-table-fedit-line-up ()
11000 "Move cursor one line up in the window showing the table."
11001 (interactive)
11002 (org-table-fedit-move 'previous-line))
11004 (defun org-table-fedit-line-down ()
11005 "Move cursor one line down in the window showing the table."
11006 (interactive)
11007 (org-table-fedit-move 'next-line))
11009 (defun org-table-fedit-move (command)
11010 "Move the cursor in the window shoinw the table.
11011 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
11012 (let ((org-table-allow-automatic-line-recalculation nil)
11013 (pos org-pos) (win (selected-window)) p)
11014 (select-window (get-buffer-window (marker-buffer org-pos)))
11015 (setq p (point))
11016 (call-interactively command)
11017 (while (and (org-at-table-p)
11018 (org-at-table-hline-p))
11019 (call-interactively command))
11020 (or (org-at-table-p) (goto-char p))
11021 (move-marker pos (point))
11022 (select-window win)))
11024 (defun org-table-fedit-scroll (N)
11025 (interactive "p")
11026 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
11027 (scroll-other-window N)))
11029 (defun org-table-fedit-scroll-down (N)
11030 (interactive "p")
11031 (org-table-fedit-scroll (- N)))
11033 (defvar org-table-rectangle-overlays nil)
11035 (defun org-table-add-rectangle-overlay (beg end &optional face)
11036 "Add a new overlay."
11037 (let ((ov (org-make-overlay beg end)))
11038 (org-overlay-put ov 'face (or face 'secondary-selection))
11039 (push ov org-table-rectangle-overlays)))
11041 (defun org-table-highlight-rectangle (&optional beg end face)
11042 "Highlight rectangular region in a table."
11043 (setq beg (or beg (point)) end (or end (point)))
11044 (let ((b (min beg end))
11045 (e (max beg end))
11046 l1 c1 l2 c2 tmp)
11047 (and (boundp 'org-show-positions)
11048 (setq org-show-positions (cons b (cons e org-show-positions))))
11049 (goto-char (min beg end))
11050 (setq l1 (org-current-line)
11051 c1 (org-table-current-column))
11052 (goto-char (max beg end))
11053 (setq l2 (org-current-line)
11054 c2 (org-table-current-column))
11055 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
11056 (goto-line l1)
11057 (beginning-of-line 1)
11058 (loop for line from l1 to l2 do
11059 (when (looking-at org-table-dataline-regexp)
11060 (org-table-goto-column c1)
11061 (skip-chars-backward "^|\n") (setq beg (point))
11062 (org-table-goto-column c2)
11063 (skip-chars-forward "^|\n") (setq end (point))
11064 (org-table-add-rectangle-overlay beg end face))
11065 (beginning-of-line 2))
11066 (goto-char b))
11067 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
11069 (defun org-table-remove-rectangle-highlight (&rest ignore)
11070 "Remove the rectangle overlays."
11071 (unless org-inhibit-highlight-removal
11072 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
11073 (mapc 'org-delete-overlay org-table-rectangle-overlays)
11074 (setq org-table-rectangle-overlays nil)))
11076 (defvar org-table-coordinate-overlays nil
11077 "Collects the cooordinate grid overlays, so that they can be removed.")
11078 (make-variable-buffer-local 'org-table-coordinate-overlays)
11080 (defun org-table-overlay-coordinates ()
11081 "Add overlays to the table at point, to show row/column coordinates."
11082 (interactive)
11083 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11084 (setq org-table-coordinate-overlays nil)
11085 (save-excursion
11086 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
11087 (goto-char (org-table-begin))
11088 (while (org-at-table-p)
11089 (setq eol (point-at-eol))
11090 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
11091 (push ov org-table-coordinate-overlays)
11092 (setq hline (looking-at org-table-hline-regexp))
11093 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
11094 (format "%4d" (setq id (1+ id)))))
11095 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
11096 (when hline
11097 (setq ic 0)
11098 (while (re-search-forward "[+|]\\(-+\\)" eol t)
11099 (setq beg (1+ (match-beginning 0))
11100 ic (1+ ic)
11101 s1 (concat "$" (int-to-string ic))
11102 s2 (org-number-to-letters ic)
11103 str (if (eq org-table-use-standard-references t) s2 s1))
11104 (setq ov (org-make-overlay beg (+ beg (length str))))
11105 (push ov org-table-coordinate-overlays)
11106 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
11107 (beginning-of-line 2)))))
11109 (defun org-table-toggle-coordinate-overlays ()
11110 "Toggle the display of Row/Column numbers in tables."
11111 (interactive)
11112 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
11113 (message "Row/Column number display turned %s"
11114 (if org-table-overlay-coordinates "on" "off"))
11115 (if (and (org-at-table-p) org-table-overlay-coordinates)
11116 (org-table-align))
11117 (unless org-table-overlay-coordinates
11118 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11119 (setq org-table-coordinate-overlays nil)))
11121 (defun org-table-toggle-formula-debugger ()
11122 "Toggle the formula debugger in tables."
11123 (interactive)
11124 (setq org-table-formula-debug (not org-table-formula-debug))
11125 (message "Formula debugging has been turned %s"
11126 (if org-table-formula-debug "on" "off")))
11128 ;;; The orgtbl minor mode
11130 ;; Define a minor mode which can be used in other modes in order to
11131 ;; integrate the org-mode table editor.
11133 ;; This is really a hack, because the org-mode table editor uses several
11134 ;; keys which normally belong to the major mode, for example the TAB and
11135 ;; RET keys. Here is how it works: The minor mode defines all the keys
11136 ;; necessary to operate the table editor, but wraps the commands into a
11137 ;; function which tests if the cursor is currently inside a table. If that
11138 ;; is the case, the table editor command is executed. However, when any of
11139 ;; those keys is used outside a table, the function uses `key-binding' to
11140 ;; look up if the key has an associated command in another currently active
11141 ;; keymap (minor modes, major mode, global), and executes that command.
11142 ;; There might be problems if any of the keys used by the table editor is
11143 ;; otherwise used as a prefix key.
11145 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11146 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11147 ;; addresses this by checking explicitly for both bindings.
11149 ;; The optimized version (see variable `orgtbl-optimized') takes over
11150 ;; all keys which are bound to `self-insert-command' in the *global map*.
11151 ;; Some modes bind other commands to simple characters, for example
11152 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11153 ;; active, this binding is ignored inside tables and replaced with a
11154 ;; modified self-insert.
11156 (defvar orgtbl-mode nil
11157 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11158 table editor in arbitrary modes.")
11159 (make-variable-buffer-local 'orgtbl-mode)
11161 (defvar orgtbl-mode-map (make-keymap)
11162 "Keymap for `orgtbl-mode'.")
11164 ;;;###autoload
11165 (defun turn-on-orgtbl ()
11166 "Unconditionally turn on `orgtbl-mode'."
11167 (orgtbl-mode 1))
11169 (defvar org-old-auto-fill-inhibit-regexp nil
11170 "Local variable used by `orgtbl-mode'")
11172 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
11173 "Matches a line belonging to an orgtbl.")
11175 (defconst orgtbl-extra-font-lock-keywords
11176 (list (list (concat "^" orgtbl-line-start-regexp ".*")
11177 0 (quote 'org-table) 'prepend))
11178 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
11180 ;;;###autoload
11181 (defun orgtbl-mode (&optional arg)
11182 "The `org-mode' table editor as a minor mode for use in other modes."
11183 (interactive)
11184 (if (org-mode-p)
11185 ;; Exit without error, in case some hook functions calls this
11186 ;; by accident in org-mode.
11187 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11188 (setq orgtbl-mode
11189 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11190 (if orgtbl-mode
11191 (progn
11192 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11193 ;; Make sure we are first in minor-mode-map-alist
11194 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11195 (and c (setq minor-mode-map-alist
11196 (cons c (delq c minor-mode-map-alist)))))
11197 (org-set-local (quote org-table-may-need-update) t)
11198 (org-add-hook 'before-change-functions 'org-before-change-function
11199 nil 'local)
11200 (org-set-local 'org-old-auto-fill-inhibit-regexp
11201 auto-fill-inhibit-regexp)
11202 (org-set-local 'auto-fill-inhibit-regexp
11203 (if auto-fill-inhibit-regexp
11204 (concat orgtbl-line-start-regexp "\\|"
11205 auto-fill-inhibit-regexp)
11206 orgtbl-line-start-regexp))
11207 (org-add-to-invisibility-spec '(org-cwidth))
11208 (when (fboundp 'font-lock-add-keywords)
11209 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11210 (org-restart-font-lock))
11211 (easy-menu-add orgtbl-mode-menu)
11212 (run-hooks 'orgtbl-mode-hook))
11213 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11214 (org-cleanup-narrow-column-properties)
11215 (org-remove-from-invisibility-spec '(org-cwidth))
11216 (remove-hook 'before-change-functions 'org-before-change-function t)
11217 (when (fboundp 'font-lock-remove-keywords)
11218 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11219 (org-restart-font-lock))
11220 (easy-menu-remove orgtbl-mode-menu)
11221 (force-mode-line-update 'all))))
11223 (defun org-cleanup-narrow-column-properties ()
11224 "Remove all properties related to narrow-column invisibility."
11225 (let ((s 1))
11226 (while (setq s (text-property-any s (point-max)
11227 'display org-narrow-column-arrow))
11228 (remove-text-properties s (1+ s) '(display t)))
11229 (setq s 1)
11230 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11231 (remove-text-properties s (1+ s) '(org-cwidth t)))
11232 (setq s 1)
11233 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11234 (remove-text-properties s (1+ s) '(invisible t)))))
11236 ;; Install it as a minor mode.
11237 (put 'orgtbl-mode :included t)
11238 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11239 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11241 (defun orgtbl-make-binding (fun n &rest keys)
11242 "Create a function for binding in the table minor mode.
11243 FUN is the command to call inside a table. N is used to create a unique
11244 command name. KEYS are keys that should be checked in for a command
11245 to execute outside of tables."
11246 (eval
11247 (list 'defun
11248 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11249 '(arg)
11250 (concat "In tables, run `" (symbol-name fun) "'.\n"
11251 "Outside of tables, run the binding of `"
11252 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11253 "'.")
11254 '(interactive "p")
11255 (list 'if
11256 '(org-at-table-p)
11257 (list 'call-interactively (list 'quote fun))
11258 (list 'let '(orgtbl-mode)
11259 (list 'call-interactively
11260 (append '(or)
11261 (mapcar (lambda (k)
11262 (list 'key-binding k))
11263 keys)
11264 '('orgtbl-error))))))))
11266 (defun orgtbl-error ()
11267 "Error when there is no default binding for a table key."
11268 (interactive)
11269 (error "This key has no function outside tables"))
11271 (defun orgtbl-setup ()
11272 "Setup orgtbl keymaps."
11273 (let ((nfunc 0)
11274 (bindings
11275 (list
11276 '([(meta shift left)] org-table-delete-column)
11277 '([(meta left)] org-table-move-column-left)
11278 '([(meta right)] org-table-move-column-right)
11279 '([(meta shift right)] org-table-insert-column)
11280 '([(meta shift up)] org-table-kill-row)
11281 '([(meta shift down)] org-table-insert-row)
11282 '([(meta up)] org-table-move-row-up)
11283 '([(meta down)] org-table-move-row-down)
11284 '("\C-c\C-w" org-table-cut-region)
11285 '("\C-c\M-w" org-table-copy-region)
11286 '("\C-c\C-y" org-table-paste-rectangle)
11287 '("\C-c-" org-table-insert-hline)
11288 '("\C-c}" org-table-toggle-coordinate-overlays)
11289 '("\C-c{" org-table-toggle-formula-debugger)
11290 '("\C-m" org-table-next-row)
11291 '([(shift return)] org-table-copy-down)
11292 '("\C-c\C-q" org-table-wrap-region)
11293 '("\C-c?" org-table-field-info)
11294 '("\C-c " org-table-blank-field)
11295 '("\C-c+" org-table-sum)
11296 '("\C-c=" org-table-eval-formula)
11297 '("\C-c'" org-table-edit-formulas)
11298 '("\C-c`" org-table-edit-field)
11299 '("\C-c*" org-table-recalculate)
11300 '("\C-c|" org-table-create-or-convert-from-region)
11301 '("\C-c^" org-table-sort-lines)
11302 '([(control ?#)] org-table-rotate-recalc-marks)))
11303 elt key fun cmd)
11304 (while (setq elt (pop bindings))
11305 (setq nfunc (1+ nfunc))
11306 (setq key (org-key (car elt))
11307 fun (nth 1 elt)
11308 cmd (orgtbl-make-binding fun nfunc key))
11309 (org-defkey orgtbl-mode-map key cmd))
11311 ;; Special treatment needed for TAB and RET
11312 (org-defkey orgtbl-mode-map [(return)]
11313 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11314 (org-defkey orgtbl-mode-map "\C-m"
11315 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11317 (org-defkey orgtbl-mode-map [(tab)]
11318 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11319 (org-defkey orgtbl-mode-map "\C-i"
11320 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11322 (org-defkey orgtbl-mode-map [(shift tab)]
11323 (orgtbl-make-binding 'org-table-previous-field 104
11324 [(shift tab)] [(tab)] "\C-i"))
11326 (org-defkey orgtbl-mode-map "\M-\C-m"
11327 (orgtbl-make-binding 'org-table-wrap-region 105
11328 "\M-\C-m" [(meta return)]))
11329 (org-defkey orgtbl-mode-map [(meta return)]
11330 (orgtbl-make-binding 'org-table-wrap-region 106
11331 [(meta return)] "\M-\C-m"))
11333 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11334 (when orgtbl-optimized
11335 ;; If the user wants maximum table support, we need to hijack
11336 ;; some standard editing functions
11337 (org-remap orgtbl-mode-map
11338 'self-insert-command 'orgtbl-self-insert-command
11339 'delete-char 'org-delete-char
11340 'delete-backward-char 'org-delete-backward-char)
11341 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11342 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11343 '("OrgTbl"
11344 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11345 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11346 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11347 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11348 "--"
11349 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11350 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11351 ["Copy Field from Above"
11352 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11353 "--"
11354 ("Column"
11355 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11356 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11357 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11358 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11359 ("Row"
11360 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11361 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11362 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11363 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11364 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
11365 "--"
11366 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11367 ("Rectangle"
11368 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11369 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11370 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11371 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11372 "--"
11373 ("Radio tables"
11374 ["Insert table template" orgtbl-insert-radio-table
11375 (assq major-mode orgtbl-radio-table-templates)]
11376 ["Comment/uncomment table" orgtbl-toggle-comment t])
11377 "--"
11378 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11379 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11380 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11381 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11382 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11383 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11384 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11385 ["Sum Column/Rectangle" org-table-sum
11386 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11387 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11388 ["Debug Formulas"
11389 org-table-toggle-formula-debugger :active (org-at-table-p)
11390 :keys "C-c {"
11391 :style toggle :selected org-table-formula-debug]
11392 ["Show Col/Row Numbers"
11393 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11394 :keys "C-c }"
11395 :style toggle :selected org-table-overlay-coordinates]
11399 (defun orgtbl-ctrl-c-ctrl-c (arg)
11400 "If the cursor is inside a table, realign the table.
11401 It it is a table to be sent away to a receiver, do it.
11402 With prefix arg, also recompute table."
11403 (interactive "P")
11404 (let ((pos (point)) action)
11405 (save-excursion
11406 (beginning-of-line 1)
11407 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11408 ((looking-at "[ \t]*|") pos)
11409 ((looking-at "#\\+TBLFM:") 'recalc))))
11410 (cond
11411 ((integerp action)
11412 (goto-char action)
11413 (org-table-maybe-eval-formula)
11414 (if arg
11415 (call-interactively 'org-table-recalculate)
11416 (org-table-maybe-recalculate-line))
11417 (call-interactively 'org-table-align)
11418 (orgtbl-send-table 'maybe))
11419 ((eq action 'recalc)
11420 (save-excursion
11421 (beginning-of-line 1)
11422 (skip-chars-backward " \r\n\t")
11423 (if (org-at-table-p)
11424 (org-call-with-arg 'org-table-recalculate t))))
11425 (t (let (orgtbl-mode)
11426 (call-interactively (key-binding "\C-c\C-c")))))))
11428 (defun orgtbl-tab (arg)
11429 "Justification and field motion for `orgtbl-mode'."
11430 (interactive "P")
11431 (if arg (org-table-edit-field t)
11432 (org-table-justify-field-maybe)
11433 (org-table-next-field)))
11435 (defun orgtbl-ret ()
11436 "Justification and field motion for `orgtbl-mode'."
11437 (interactive)
11438 (org-table-justify-field-maybe)
11439 (org-table-next-row))
11441 (defun orgtbl-self-insert-command (N)
11442 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11443 If the cursor is in a table looking at whitespace, the whitespace is
11444 overwritten, and the table is not marked as requiring realignment."
11445 (interactive "p")
11446 (if (and (org-at-table-p)
11448 (and org-table-auto-blank-field
11449 (member last-command
11450 '(orgtbl-hijacker-command-100
11451 orgtbl-hijacker-command-101
11452 orgtbl-hijacker-command-102
11453 orgtbl-hijacker-command-103
11454 orgtbl-hijacker-command-104
11455 orgtbl-hijacker-command-105))
11456 (org-table-blank-field))
11458 (eq N 1)
11459 (looking-at "[^|\n]* +|"))
11460 (let (org-table-may-need-update)
11461 (goto-char (1- (match-end 0)))
11462 (delete-backward-char 1)
11463 (goto-char (match-beginning 0))
11464 (self-insert-command N))
11465 (setq org-table-may-need-update t)
11466 (let (orgtbl-mode)
11467 (call-interactively (key-binding (vector last-input-event))))))
11469 (defun org-force-self-insert (N)
11470 "Needed to enforce self-insert under remapping."
11471 (interactive "p")
11472 (self-insert-command N))
11474 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11475 "Regula expression matching exponentials as produced by calc.")
11477 (defvar org-table-clean-did-remove-column nil)
11479 (defun orgtbl-export (table target)
11480 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11481 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11482 org-table-last-alignment org-table-last-column-widths
11483 maxcol column)
11484 (if (not (fboundp func))
11485 (error "Cannot export orgtbl table to %s" target))
11486 (setq lines (org-table-clean-before-export lines))
11487 (setq table
11488 (mapcar
11489 (lambda (x)
11490 (if (string-match org-table-hline-regexp x)
11491 'hline
11492 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11493 lines))
11494 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11495 table)))
11496 (loop for i from (1- maxcol) downto 0 do
11497 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11498 (setq column (delq nil column))
11499 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11500 (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))
11501 (funcall func table nil)))
11503 (defun orgtbl-send-table (&optional maybe)
11504 "Send a tranformed version of this table to the receiver position.
11505 With argument MAYBE, fail quietly if no transformation is defined for
11506 this table."
11507 (interactive)
11508 (catch 'exit
11509 (unless (org-at-table-p) (error "Not at a table"))
11510 ;; when non-interactive, we assume align has just happened.
11511 (when (interactive-p) (org-table-align))
11512 (save-excursion
11513 (goto-char (org-table-begin))
11514 (beginning-of-line 0)
11515 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11516 (if maybe
11517 (throw 'exit nil)
11518 (error "Don't know how to transform this table."))))
11519 (let* ((name (match-string 1))
11521 (transform (intern (match-string 2)))
11522 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11523 (skip (plist-get params :skip))
11524 (skipcols (plist-get params :skipcols))
11525 (txt (buffer-substring-no-properties
11526 (org-table-begin) (org-table-end)))
11527 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11528 (lines (org-table-clean-before-export lines))
11529 (i0 (if org-table-clean-did-remove-column 2 1))
11530 (table (mapcar
11531 (lambda (x)
11532 (if (string-match org-table-hline-regexp x)
11533 'hline
11534 (org-remove-by-index
11535 (org-split-string (org-trim x) "\\s-*|\\s-*")
11536 skipcols i0)))
11537 lines))
11538 (fun (if (= i0 2) 'cdr 'identity))
11539 (org-table-last-alignment
11540 (org-remove-by-index (funcall fun org-table-last-alignment)
11541 skipcols i0))
11542 (org-table-last-column-widths
11543 (org-remove-by-index (funcall fun org-table-last-column-widths)
11544 skipcols i0)))
11546 (unless (fboundp transform)
11547 (error "No such transformation function %s" transform))
11548 (setq txt (funcall transform table params))
11549 ;; Find the insertion place
11550 (save-excursion
11551 (goto-char (point-min))
11552 (unless (re-search-forward
11553 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11554 (error "Don't know where to insert translated table"))
11555 (goto-char (match-beginning 0))
11556 (beginning-of-line 2)
11557 (setq beg (point))
11558 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11559 (error "Cannot find end of insertion region"))
11560 (beginning-of-line 1)
11561 (delete-region beg (point))
11562 (goto-char beg)
11563 (insert txt "\n"))
11564 (message "Table converted and installed at receiver location"))))
11566 (defun org-remove-by-index (list indices &optional i0)
11567 "Remove the elements in LIST with indices in INDICES.
11568 First element has index 0, or I0 if given."
11569 (if (not indices)
11570 list
11571 (if (integerp indices) (setq indices (list indices)))
11572 (setq i0 (1- (or i0 0)))
11573 (delq :rm (mapcar (lambda (x)
11574 (setq i0 (1+ i0))
11575 (if (memq i0 indices) :rm x))
11576 list))))
11578 (defun orgtbl-toggle-comment ()
11579 "Comment or uncomment the orgtbl at point."
11580 (interactive)
11581 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11582 (re2 (concat "^" orgtbl-line-start-regexp))
11583 (commented (save-excursion (beginning-of-line 1)
11584 (cond ((looking-at re1) t)
11585 ((looking-at re2) nil)
11586 (t (error "Not at an org table")))))
11587 (re (if commented re1 re2))
11588 beg end)
11589 (save-excursion
11590 (beginning-of-line 1)
11591 (while (looking-at re) (beginning-of-line 0))
11592 (beginning-of-line 2)
11593 (setq beg (point))
11594 (while (looking-at re) (beginning-of-line 2))
11595 (setq end (point)))
11596 (comment-region beg end (if commented '(4) nil))))
11598 (defun orgtbl-insert-radio-table ()
11599 "Insert a radio table template appropriate for this major mode."
11600 (interactive)
11601 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11602 (txt (nth 1 e))
11603 name pos)
11604 (unless e (error "No radio table setup defined for %s" major-mode))
11605 (setq name (read-string "Table name: "))
11606 (while (string-match "%n" txt)
11607 (setq txt (replace-match name t t txt)))
11608 (or (bolp) (insert "\n"))
11609 (setq pos (point))
11610 (insert txt)
11611 (goto-char pos)))
11613 (defun org-get-param (params header i sym &optional hsym)
11614 "Get parameter value for symbol SYM.
11615 If this is a header line, actually get the value for the symbol with an
11616 additional \"h\" inserted after the colon.
11617 If the value is a protperty list, get the element for the current column.
11618 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11619 (let ((val (plist-get params sym)))
11620 (and hsym header (setq val (or (plist-get params hsym) val)))
11621 (if (consp val) (plist-get val i) val)))
11623 (defun orgtbl-to-generic (table params)
11624 "Convert the orgtbl-mode TABLE to some other format.
11625 This generic routine can be used for many standard cases.
11626 TABLE is a list, each entry either the symbol `hline' for a horizontal
11627 separator line, or a list of fields for that line.
11628 PARAMS is a property list of parameters that can influence the conversion.
11629 For the generic converter, some parameters are obligatory: You need to
11630 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11631 :splice, you must have :tstart and :tend.
11633 Valid parameters are
11635 :tstart String to start the table. Ignored when :splice is t.
11636 :tend String to end the table. Ignored when :splice is t.
11638 :splice When set to t, return only table body lines, don't wrap
11639 them into :tstart and :tend. Default is nil.
11641 :hline String to be inserted on horizontal separation lines.
11642 May be nil to ignore hlines.
11644 :lstart String to start a new table line.
11645 :lend String to end a table line
11646 :sep Separator between two fields
11647 :lfmt Format for entire line, with enough %s to capture all fields.
11648 If this is present, :lstart, :lend, and :sep are ignored.
11649 :fmt A format to be used to wrap the field, should contain
11650 %s for the original field value. For example, to wrap
11651 everything in dollars, you could use :fmt \"$%s$\".
11652 This may also be a property list with column numbers and
11653 formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11655 :hlstart :hlend :hlsep :hlfmt :hfmt
11656 Same as above, specific for the header lines in the table.
11657 All lines before the first hline are treated as header.
11658 If any of these is not present, the data line value is used.
11660 :efmt Use this format to print numbers with exponentials.
11661 The format should have %s twice for inserting mantissa
11662 and exponent, for example \"%s\\\\times10^{%s}\". This
11663 may also be a property list with column numbers and
11664 formats. :fmt will still be applied after :efmt.
11666 In addition to this, the parameters :skip and :skipcols are always handled
11667 directly by `orgtbl-send-table'. See manual."
11668 (interactive)
11669 (let* ((p params)
11670 (splicep (plist-get p :splice))
11671 (hline (plist-get p :hline))
11672 rtn line i fm efm lfmt h)
11674 ;; Do we have a header?
11675 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11676 (setq h t))
11678 ;; Put header
11679 (unless splicep
11680 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11682 ;; Now loop over all lines
11683 (while (setq line (pop table))
11684 (if (eq line 'hline)
11685 ;; A horizontal separator line
11686 (progn (if hline (push hline rtn))
11687 (setq h nil)) ; no longer in header
11688 ;; A normal line. Convert the fields, push line onto the result list
11689 (setq i 0)
11690 (setq line
11691 (mapcar
11692 (lambda (f)
11693 (setq i (1+ i)
11694 fm (org-get-param p h i :fmt :hfmt)
11695 efm (org-get-param p h i :efmt))
11696 (if (and efm (string-match orgtbl-exp-regexp f))
11697 (setq f (format
11698 efm (match-string 1 f) (match-string 2 f))))
11699 (if fm (setq f (format fm f)))
11701 line))
11702 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11703 (push (apply 'format lfmt line) rtn)
11704 (push (concat
11705 (org-get-param p h i :lstart :hlstart)
11706 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11707 (org-get-param p h i :lend :hlend))
11708 rtn))))
11710 (unless splicep
11711 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11713 (mapconcat 'identity (nreverse rtn) "\n")))
11715 (defun orgtbl-to-latex (table params)
11716 "Convert the orgtbl-mode TABLE to LaTeX.
11717 TABLE is a list, each entry either the symbol `hline' for a horizontal
11718 separator line, or a list of fields for that line.
11719 PARAMS is a property list of parameters that can influence the conversion.
11720 Supports all parameters from `orgtbl-to-generic'. Most important for
11721 LaTeX are:
11723 :splice When set to t, return only table body lines, don't wrap
11724 them into a tabular environment. Default is nil.
11726 :fmt A format to be used to wrap the field, should contain %s for the
11727 original field value. For example, to wrap everything in dollars,
11728 use :fmt \"$%s$\". This may also be a property list with column
11729 numbers and formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11731 :efmt Format for transforming numbers with exponentials. The format
11732 should have %s twice for inserting mantissa and exponent, for
11733 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11734 This may also be a property list with column numbers and formats.
11736 The general parameters :skip and :skipcols have already been applied when
11737 this function is called."
11738 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11739 org-table-last-alignment ""))
11740 (params2
11741 (list
11742 :tstart (concat "\\begin{tabular}{" alignment "}")
11743 :tend "\\end{tabular}"
11744 :lstart "" :lend " \\\\" :sep " & "
11745 :efmt "%s\\,(%s)" :hline "\\hline")))
11746 (orgtbl-to-generic table (org-combine-plists params2 params))))
11748 (defun orgtbl-to-html (table params)
11749 "Convert the orgtbl-mode TABLE to LaTeX.
11750 TABLE is a list, each entry either the symbol `hline' for a horizontal
11751 separator line, or a list of fields for that line.
11752 PARAMS is a property list of parameters that can influence the conversion.
11753 Currently this function recognizes the following parameters:
11755 :splice When set to t, return only table body lines, don't wrap
11756 them into a <table> environment. Default is nil.
11758 The general parameters :skip and :skipcols have already been applied when
11759 this function is called. The function does *not* use `orgtbl-to-generic',
11760 so you cannot specify parameters for it."
11761 (let* ((splicep (plist-get params :splice))
11762 html)
11763 ;; Just call the formatter we already have
11764 ;; We need to make text lines for it, so put the fields back together.
11765 (setq html (org-format-org-table-html
11766 (mapcar
11767 (lambda (x)
11768 (if (eq x 'hline)
11769 "|----+----|"
11770 (concat "| " (mapconcat 'identity x " | ") " |")))
11771 table)
11772 splicep))
11773 (if (string-match "\n+\\'" html)
11774 (setq html (replace-match "" t t html)))
11775 html))
11777 (defun orgtbl-to-texinfo (table params)
11778 "Convert the orgtbl-mode TABLE to TeXInfo.
11779 TABLE is a list, each entry either the symbol `hline' for a horizontal
11780 separator line, or a list of fields for that line.
11781 PARAMS is a property list of parameters that can influence the conversion.
11782 Supports all parameters from `orgtbl-to-generic'. Most important for
11783 TeXInfo are:
11785 :splice nil/t When set to t, return only table body lines, don't wrap
11786 them into a multitable environment. Default is nil.
11788 :fmt fmt A format to be used to wrap the field, should contain
11789 %s for the original field value. For example, to wrap
11790 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
11791 This may also be a property list with column numbers and
11792 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
11794 :cf \"f1 f2..\" The column fractions for the table. By default these
11795 are computed automatically from the width of the columns
11796 under org-mode.
11798 The general parameters :skip and :skipcols have already been applied when
11799 this function is called."
11800 (let* ((total (float (apply '+ org-table-last-column-widths)))
11801 (colfrac (or (plist-get params :cf)
11802 (mapconcat
11803 (lambda (x) (format "%.3f" (/ (float x) total)))
11804 org-table-last-column-widths " ")))
11805 (params2
11806 (list
11807 :tstart (concat "@multitable @columnfractions " colfrac)
11808 :tend "@end multitable"
11809 :lstart "@item " :lend "" :sep " @tab "
11810 :hlstart "@headitem ")))
11811 (orgtbl-to-generic table (org-combine-plists params2 params))))
11813 ;;;; Link Stuff
11815 ;;; Link abbreviations
11817 (defun org-link-expand-abbrev (link)
11818 "Apply replacements as defined in `org-link-abbrev-alist."
11819 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
11820 (let* ((key (match-string 1 link))
11821 (as (or (assoc key org-link-abbrev-alist-local)
11822 (assoc key org-link-abbrev-alist)))
11823 (tag (and (match-end 2) (match-string 3 link)))
11824 rpl)
11825 (if (not as)
11826 link
11827 (setq rpl (cdr as))
11828 (cond
11829 ((symbolp rpl) (funcall rpl tag))
11830 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
11831 (t (concat rpl tag)))))
11832 link))
11834 ;;; Storing and inserting links
11836 (defvar org-insert-link-history nil
11837 "Minibuffer history for links inserted with `org-insert-link'.")
11839 (defvar org-stored-links nil
11840 "Contains the links stored with `org-store-link'.")
11842 (defvar org-store-link-plist nil
11843 "Plist with info about the most recently link created with `org-store-link'.")
11845 (defvar org-link-protocols nil
11846 "Link protocols added to Org-mode using `org-add-link-type'.")
11848 (defvar org-store-link-functions nil
11849 "List of functions that are called to create and store a link.
11850 Each function will be called in turn until one returns a non-nil
11851 value. Each function should check if it is responsible for creating
11852 this link (for example by looking at the major mode).
11853 If not, it must exit and return nil.
11854 If yes, it should return a non-nil value after a calling
11855 `org-store-link-props' with a list of properties and values.
11856 Special properties are:
11858 :type The link prefix. like \"http\". This must be given.
11859 :link The link, like \"http://www.astro.uva.nl/~dominik\".
11860 This is obligatory as well.
11861 :description Optional default description for the second pair
11862 of brackets in an Org-mode link. The user can still change
11863 this when inserting this link into an Org-mode buffer.
11865 In addition to these, any additional properties can be specified
11866 and then used in remember templates.")
11868 (defun org-add-link-type (type &optional follow publish)
11869 "Add TYPE to the list of `org-link-types'.
11870 Re-compute all regular expressions depending on `org-link-types'
11871 FOLLOW and PUBLISH are two functions. Both take the link path as
11872 an argument.
11873 FOLLOW should do whatever is necessary to follow the link, for example
11874 to find a file or display a mail message.
11876 PUBLISH takes the path and retuns the string that should be used when
11877 this document is published. FIMXE: This is actually not yet implemented."
11878 (add-to-list 'org-link-types type t)
11879 (org-make-link-regexps)
11880 (add-to-list 'org-link-protocols
11881 (list type follow publish)))
11883 (defun org-add-agenda-custom-command (entry)
11884 "Replace or add a command in `org-agenda-custom-commands'.
11885 This is mostly for hacking and trying a new command - once the command
11886 works you probably want to add it to `org-agenda-custom-commands' for good."
11887 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
11888 (if ass
11889 (setcdr ass (cdr entry))
11890 (push entry org-agenda-custom-commands))))
11892 ;;;###autoload
11893 (defun org-store-link (arg)
11894 "\\<org-mode-map>Store an org-link to the current location.
11895 This link can later be inserted into an org-buffer with
11896 \\[org-insert-link].
11897 For some link types, a prefix arg is interpreted:
11898 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
11899 For file links, arg negates `org-context-in-file-links'."
11900 (interactive "P")
11901 (setq org-store-link-plist nil) ; reset
11902 (let (link cpltxt desc description search txt)
11903 (cond
11905 ((run-hook-with-args-until-success 'org-store-link-functions)
11906 (setq link (plist-get org-store-link-plist :link)
11907 desc (or (plist-get org-store-link-plist :description) link)))
11909 ((eq major-mode 'bbdb-mode)
11910 (let ((name (bbdb-record-name (bbdb-current-record)))
11911 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
11912 (setq cpltxt (concat "bbdb:" (or name company))
11913 link (org-make-link cpltxt))
11914 (org-store-link-props :type "bbdb" :name name :company company)))
11916 ((eq major-mode 'Info-mode)
11917 (setq link (org-make-link "info:"
11918 (file-name-nondirectory Info-current-file)
11919 ":" Info-current-node))
11920 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
11921 ":" Info-current-node))
11922 (org-store-link-props :type "info" :file Info-current-file
11923 :node Info-current-node))
11925 ((eq major-mode 'calendar-mode)
11926 (let ((cd (calendar-cursor-to-date)))
11927 (setq link
11928 (format-time-string
11929 (car org-time-stamp-formats)
11930 (apply 'encode-time
11931 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
11932 nil nil nil))))
11933 (org-store-link-props :type "calendar" :date cd)))
11935 ((or (eq major-mode 'vm-summary-mode)
11936 (eq major-mode 'vm-presentation-mode))
11937 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
11938 (vm-follow-summary-cursor)
11939 (save-excursion
11940 (vm-select-folder-buffer)
11941 (let* ((message (car vm-message-pointer))
11942 (folder buffer-file-name)
11943 (subject (vm-su-subject message))
11944 (to (vm-get-header-contents message "To"))
11945 (from (vm-get-header-contents message "From"))
11946 (message-id (vm-su-message-id message)))
11947 (org-store-link-props :type "vm" :from from :to to :subject subject
11948 :message-id message-id)
11949 (setq message-id (org-remove-angle-brackets message-id))
11950 (setq folder (abbreviate-file-name folder))
11951 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
11952 folder)
11953 (setq folder (replace-match "" t t folder)))
11954 (setq cpltxt (org-email-link-description))
11955 (setq link (org-make-link "vm:" folder "#" message-id)))))
11957 ((eq major-mode 'wl-summary-mode)
11958 (let* ((msgnum (wl-summary-message-number))
11959 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
11960 msgnum 'message-id))
11961 (wl-message-entity
11962 (if (fboundp 'elmo-message-entity)
11963 (elmo-message-entity
11964 wl-summary-buffer-elmo-folder msgnum)
11965 (elmo-msgdb-overview-get-entity
11966 msgnum (wl-summary-buffer-msgdb))))
11967 (from (wl-summary-line-from))
11968 (to (car (elmo-message-entity-field wl-message-entity 'to)))
11969 (subject (let (wl-thr-indent-string wl-parent-message-entity)
11970 (wl-summary-line-subject))))
11971 (org-store-link-props :type "wl" :from from :to to
11972 :subject subject :message-id message-id)
11973 (setq message-id (org-remove-angle-brackets message-id))
11974 (setq cpltxt (org-email-link-description))
11975 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
11976 "#" message-id))))
11978 ((or (equal major-mode 'mh-folder-mode)
11979 (equal major-mode 'mh-show-mode))
11980 (let ((from (org-mhe-get-header "From:"))
11981 (to (org-mhe-get-header "To:"))
11982 (message-id (org-mhe-get-header "Message-Id:"))
11983 (subject (org-mhe-get-header "Subject:")))
11984 (org-store-link-props :type "mh" :from from :to to
11985 :subject subject :message-id message-id)
11986 (setq cpltxt (org-email-link-description))
11987 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
11988 (org-remove-angle-brackets message-id)))))
11990 ((eq major-mode 'rmail-mode)
11991 (save-excursion
11992 (save-restriction
11993 (rmail-narrow-to-non-pruned-header)
11994 (let ((folder buffer-file-name)
11995 (message-id (mail-fetch-field "message-id"))
11996 (from (mail-fetch-field "from"))
11997 (to (mail-fetch-field "to"))
11998 (subject (mail-fetch-field "subject")))
11999 (org-store-link-props
12000 :type "rmail" :from from :to to
12001 :subject subject :message-id message-id)
12002 (setq message-id (org-remove-angle-brackets message-id))
12003 (setq cpltxt (org-email-link-description))
12004 (setq link (org-make-link "rmail:" folder "#" message-id))))))
12006 ((eq major-mode 'gnus-group-mode)
12007 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
12008 (gnus-group-group-name)) ; version
12009 ((fboundp 'gnus-group-name)
12010 (gnus-group-name))
12011 (t "???"))))
12012 (unless group (error "Not on a group"))
12013 (org-store-link-props :type "gnus" :group group)
12014 (setq cpltxt (concat
12015 (if (org-xor arg org-usenet-links-prefer-google)
12016 "http://groups.google.com/groups?group="
12017 "gnus:")
12018 group)
12019 link (org-make-link cpltxt))))
12021 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
12022 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
12023 (let* ((group gnus-newsgroup-name)
12024 (article (gnus-summary-article-number))
12025 (header (gnus-summary-article-header article))
12026 (from (mail-header-from header))
12027 (message-id (mail-header-id header))
12028 (date (mail-header-date header))
12029 (subject (gnus-summary-subject-string)))
12030 (org-store-link-props :type "gnus" :from from :subject subject
12031 :message-id message-id :group group)
12032 (setq cpltxt (org-email-link-description))
12033 (if (org-xor arg org-usenet-links-prefer-google)
12034 (setq link
12035 (concat
12036 cpltxt "\n "
12037 (format "http://groups.google.com/groups?as_umsgid=%s"
12038 (org-fixup-message-id-for-http message-id))))
12039 (setq link (org-make-link "gnus:" group
12040 "#" (number-to-string article))))))
12042 ((eq major-mode 'w3-mode)
12043 (setq cpltxt (url-view-url t)
12044 link (org-make-link cpltxt))
12045 (org-store-link-props :type "w3" :url (url-view-url t)))
12047 ((eq major-mode 'w3m-mode)
12048 (setq cpltxt (or w3m-current-title w3m-current-url)
12049 link (org-make-link w3m-current-url))
12050 (org-store-link-props :type "w3m" :url (url-view-url t)))
12052 ((setq search (run-hook-with-args-until-success
12053 'org-create-file-search-functions))
12054 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
12055 "::" search))
12056 (setq cpltxt (or description link)))
12058 ((eq major-mode 'image-mode)
12059 (setq cpltxt (concat "file:"
12060 (abbreviate-file-name buffer-file-name))
12061 link (org-make-link cpltxt))
12062 (org-store-link-props :type "image" :file buffer-file-name))
12064 ((eq major-mode 'dired-mode)
12065 ;; link to the file in the current line
12066 (setq cpltxt (concat "file:"
12067 (abbreviate-file-name
12068 (expand-file-name
12069 (dired-get-filename nil t))))
12070 link (org-make-link cpltxt)))
12072 ((and buffer-file-name (org-mode-p))
12073 ;; Just link to current headline
12074 (setq cpltxt (concat "file:"
12075 (abbreviate-file-name buffer-file-name)))
12076 ;; Add a context search string
12077 (when (org-xor org-context-in-file-links arg)
12078 ;; Check if we are on a target
12079 (if (org-in-regexp "<<\\(.*?\\)>>")
12080 (setq cpltxt (concat cpltxt "::" (match-string 1)))
12081 (setq txt (cond
12082 ((org-on-heading-p) nil)
12083 ((org-region-active-p)
12084 (buffer-substring (region-beginning) (region-end)))
12085 (t (buffer-substring (point-at-bol) (point-at-eol)))))
12086 (when (or (null txt) (string-match "\\S-" txt))
12087 (setq cpltxt
12088 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12089 desc "NONE"))))
12090 (if (string-match "::\\'" cpltxt)
12091 (setq cpltxt (substring cpltxt 0 -2)))
12092 (setq link (org-make-link cpltxt)))
12094 ((buffer-file-name (buffer-base-buffer))
12095 ;; Just link to this file here.
12096 (setq cpltxt (concat "file:"
12097 (abbreviate-file-name
12098 (buffer-file-name (buffer-base-buffer)))))
12099 ;; Add a context string
12100 (when (org-xor org-context-in-file-links arg)
12101 (setq txt (if (org-region-active-p)
12102 (buffer-substring (region-beginning) (region-end))
12103 (buffer-substring (point-at-bol) (point-at-eol))))
12104 ;; Only use search option if there is some text.
12105 (when (string-match "\\S-" txt)
12106 (setq cpltxt
12107 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12108 desc "NONE")))
12109 (setq link (org-make-link cpltxt)))
12111 ((interactive-p)
12112 (error "Cannot link to a buffer which is not visiting a file"))
12114 (t (setq link nil)))
12116 (if (consp link) (setq cpltxt (car link) link (cdr link)))
12117 (setq link (or link cpltxt)
12118 desc (or desc cpltxt))
12119 (if (equal desc "NONE") (setq desc nil))
12121 (if (and (interactive-p) link)
12122 (progn
12123 (setq org-stored-links
12124 (cons (list link desc) org-stored-links))
12125 (message "Stored: %s" (or desc link)))
12126 (and link (org-make-link-string link desc)))))
12128 (defun org-store-link-props (&rest plist)
12129 "Store link properties, extract names and addresses."
12130 (let (x adr)
12131 (when (setq x (plist-get plist :from))
12132 (setq adr (mail-extract-address-components x))
12133 (plist-put plist :fromname (car adr))
12134 (plist-put plist :fromaddress (nth 1 adr)))
12135 (when (setq x (plist-get plist :to))
12136 (setq adr (mail-extract-address-components x))
12137 (plist-put plist :toname (car adr))
12138 (plist-put plist :toaddress (nth 1 adr))))
12139 (let ((from (plist-get plist :from))
12140 (to (plist-get plist :to)))
12141 (when (and from to org-from-is-user-regexp)
12142 (plist-put plist :fromto
12143 (if (string-match org-from-is-user-regexp from)
12144 (concat "to %t")
12145 (concat "from %f")))))
12146 (setq org-store-link-plist plist))
12148 (defun org-email-link-description (&optional fmt)
12149 "Return the description part of an email link.
12150 This takes information from `org-store-link-plist' and formats it
12151 according to FMT (default from `org-email-link-description-format')."
12152 (setq fmt (or fmt org-email-link-description-format))
12153 (let* ((p org-store-link-plist)
12154 (to (plist-get p :toaddress))
12155 (from (plist-get p :fromaddress))
12156 (table
12157 (list
12158 (cons "%c" (plist-get p :fromto))
12159 (cons "%F" (plist-get p :from))
12160 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12161 (cons "%T" (plist-get p :to))
12162 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12163 (cons "%s" (plist-get p :subject))
12164 (cons "%m" (plist-get p :message-id)))))
12165 (when (string-match "%c" fmt)
12166 ;; Check if the user wrote this message
12167 (if (and org-from-is-user-regexp from to
12168 (save-match-data (string-match org-from-is-user-regexp from)))
12169 (setq fmt (replace-match "to %t" t t fmt))
12170 (setq fmt (replace-match "from %f" t t fmt))))
12171 (org-replace-escapes fmt table)))
12173 (defun org-make-org-heading-search-string (&optional string heading)
12174 "Make search string for STRING or current headline."
12175 (interactive)
12176 (let ((s (or string (org-get-heading))))
12177 (unless (and string (not heading))
12178 ;; We are using a headline, clean up garbage in there.
12179 (if (string-match org-todo-regexp s)
12180 (setq s (replace-match "" t t s)))
12181 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12182 (setq s (replace-match "" t t s)))
12183 (setq s (org-trim s))
12184 (if (string-match (concat "^\\(" org-quote-string "\\|"
12185 org-comment-string "\\)") s)
12186 (setq s (replace-match "" t t s)))
12187 (while (string-match org-ts-regexp s)
12188 (setq s (replace-match "" t t s))))
12189 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12190 (setq s (replace-match " " t t s)))
12191 (or string (setq s (concat "*" s))) ; Add * for headlines
12192 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12194 (defun org-make-link (&rest strings)
12195 "Concatenate STRINGS."
12196 (apply 'concat strings))
12198 (defun org-make-link-string (link &optional description)
12199 "Make a link with brackets, consisting of LINK and DESCRIPTION."
12200 (unless (string-match "\\S-" link)
12201 (error "Empty link"))
12202 (when (stringp description)
12203 ;; Remove brackets from the description, they are fatal.
12204 (while (string-match "\\[" description)
12205 (setq description (replace-match "{" t t description)))
12206 (while (string-match "\\]" description)
12207 (setq description (replace-match "}" t t description))))
12208 (when (equal (org-link-escape link) description)
12209 ;; No description needed, it is identical
12210 (setq description nil))
12211 (when (and (not description)
12212 (not (equal link (org-link-escape link))))
12213 (setq description link))
12214 (concat "[[" (org-link-escape link) "]"
12215 (if description (concat "[" description "]") "")
12216 "]"))
12218 (defconst org-link-escape-chars
12219 '((?\ . "%20")
12220 (?\[ . "%5B")
12221 (?\] . "%5D")
12222 (?\340 . "%E0") ; `a
12223 (?\342 . "%E2") ; ^a
12224 (?\347 . "%E7") ; ,c
12225 (?\350 . "%E8") ; `e
12226 (?\351 . "%E9") ; 'e
12227 (?\352 . "%EA") ; ^e
12228 (?\356 . "%EE") ; ^i
12229 (?\364 . "%F4") ; ^o
12230 (?\371 . "%F9") ; `u
12231 (?\373 . "%FB") ; ^u
12232 (?\; . "%3B")
12233 (?? . "%3F")
12234 (?= . "%3D")
12235 (?+ . "%2B")
12237 "Association list of escapes for some characters problematic in links.
12238 This is the list that is used for internal purposes.")
12240 (defconst org-link-escape-chars-browser
12241 '((?\ . "%20")) ; 32 for the SPC char
12242 "Association list of escapes for some characters problematic in links.
12243 This is the list that is used before handing over to the browser.")
12245 (defun org-link-escape (text &optional table)
12246 "Escape charaters in TEXT that are problematic for links."
12247 (setq table (or table org-link-escape-chars))
12248 (when text
12249 (let ((re (mapconcat (lambda (x) (regexp-quote
12250 (char-to-string (car x))))
12251 table "\\|")))
12252 (while (string-match re text)
12253 (setq text
12254 (replace-match
12255 (cdr (assoc (string-to-char (match-string 0 text))
12256 table))
12257 t t text)))
12258 text)))
12260 (defun org-link-unescape (text &optional table)
12261 "Reverse the action of `org-link-escape'."
12262 (setq table (or table org-link-escape-chars))
12263 (when text
12264 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12265 table "\\|")))
12266 (while (string-match re text)
12267 (setq text
12268 (replace-match
12269 (char-to-string (car (rassoc (match-string 0 text) table)))
12270 t t text)))
12271 text)))
12273 (defun org-xor (a b)
12274 "Exclusive or."
12275 (if a (not b) b))
12277 (defun org-get-header (header)
12278 "Find a header field in the current buffer."
12279 (save-excursion
12280 (goto-char (point-min))
12281 (let ((case-fold-search t) s)
12282 (cond
12283 ((eq header 'from)
12284 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12285 (setq s (match-string 1)))
12286 (while (string-match "\"" s)
12287 (setq s (replace-match "" t t s)))
12288 (if (string-match "[<(].*" s)
12289 (setq s (replace-match "" t t s))))
12290 ((eq header 'message-id)
12291 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12292 (setq s (match-string 1))))
12293 ((eq header 'subject)
12294 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12295 (setq s (match-string 1)))))
12296 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12297 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12298 s)))
12301 (defun org-fixup-message-id-for-http (s)
12302 "Replace special characters in a message id, so it can be used in an http query."
12303 (while (string-match "<" s)
12304 (setq s (replace-match "%3C" t t s)))
12305 (while (string-match ">" s)
12306 (setq s (replace-match "%3E" t t s)))
12307 (while (string-match "@" s)
12308 (setq s (replace-match "%40" t t s)))
12311 ;;;###autoload
12312 (defun org-insert-link-global ()
12313 "Insert a link like Org-mode does.
12314 This command can be called in any mode to insert a link in Org-mode syntax."
12315 (interactive)
12316 (org-run-like-in-org-mode 'org-insert-link))
12318 (defun org-insert-link (&optional complete-file)
12319 "Insert a link. At the prompt, enter the link.
12321 Completion can be used to select a link previously stored with
12322 `org-store-link'. When the empty string is entered (i.e. if you just
12323 press RET at the prompt), the link defaults to the most recently
12324 stored link. As SPC triggers completion in the minibuffer, you need to
12325 use M-SPC or C-q SPC to force the insertion of a space character.
12327 You will also be prompted for a description, and if one is given, it will
12328 be displayed in the buffer instead of the link.
12330 If there is already a link at point, this command will allow you to edit link
12331 and description parts.
12333 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12334 selected using completion. The path to the file will be relative to
12335 the current directory if the file is in the current directory or a
12336 subdirectory. Otherwise, the link will be the absolute path as
12337 completed in the minibuffer (i.e. normally ~/path/to/file).
12339 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12340 is in the current directory or below.
12341 With three \\[universal-argument] prefixes, negate the meaning of
12342 `org-keep-stored-link-after-insertion'."
12343 (interactive "P")
12344 (let* ((wcf (current-window-configuration))
12345 (region (if (org-region-active-p)
12346 (buffer-substring (region-beginning) (region-end))))
12347 (remove (and region (list (region-beginning) (region-end))))
12348 (desc region)
12349 tmphist ; byte-compile incorrectly complains about this
12350 link entry file)
12351 (cond
12352 ((org-in-regexp org-bracket-link-regexp 1)
12353 ;; We do have a link at point, and we are going to edit it.
12354 (setq remove (list (match-beginning 0) (match-end 0)))
12355 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12356 (setq link (read-string "Link: "
12357 (org-link-unescape
12358 (org-match-string-no-properties 1)))))
12359 ((or (org-in-regexp org-angle-link-re)
12360 (org-in-regexp org-plain-link-re))
12361 ;; Convert to bracket link
12362 (setq remove (list (match-beginning 0) (match-end 0))
12363 link (read-string "Link: "
12364 (org-remove-angle-brackets (match-string 0)))))
12365 ((equal complete-file '(4))
12366 ;; Completing read for file names.
12367 (setq file (read-file-name "File: "))
12368 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12369 (pwd1 (file-name-as-directory (abbreviate-file-name
12370 (expand-file-name ".")))))
12371 (cond
12372 ((equal complete-file '(16))
12373 (setq link (org-make-link
12374 "file:"
12375 (abbreviate-file-name (expand-file-name file)))))
12376 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12377 (setq link (org-make-link "file:" (match-string 1 file))))
12378 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12379 (expand-file-name file))
12380 (setq link (org-make-link
12381 "file:" (match-string 1 (expand-file-name file)))))
12382 (t (setq link (org-make-link "file:" file))))))
12384 ;; Read link, with completion for stored links.
12385 (with-output-to-temp-buffer "*Org Links*"
12386 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12387 (when org-stored-links
12388 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12389 (princ (mapconcat
12390 (lambda (x)
12391 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12392 (reverse org-stored-links) "\n"))))
12393 (let ((cw (selected-window)))
12394 (select-window (get-buffer-window "*Org Links*"))
12395 (shrink-window-if-larger-than-buffer)
12396 (setq truncate-lines t)
12397 (select-window cw))
12398 ;; Fake a link history, containing the stored links.
12399 (setq tmphist (append (mapcar 'car org-stored-links)
12400 org-insert-link-history))
12401 (unwind-protect
12402 (setq link (org-completing-read
12403 "Link: "
12404 (append
12405 (mapcar (lambda (x) (list (concat (car x) ":")))
12406 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12407 (mapcar (lambda (x) (list (concat x ":")))
12408 org-link-types))
12409 nil nil nil
12410 'tmphist
12411 (or (car (car org-stored-links)))))
12412 (set-window-configuration wcf)
12413 (kill-buffer "*Org Links*"))
12414 (setq entry (assoc link org-stored-links))
12415 (or entry (push link org-insert-link-history))
12416 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12417 (not org-keep-stored-link-after-insertion))
12418 (setq org-stored-links (delq (assoc link org-stored-links)
12419 org-stored-links)))
12420 (setq desc (or desc (nth 1 entry)))))
12422 (if (string-match org-plain-link-re link)
12423 ;; URL-like link, normalize the use of angular brackets.
12424 (setq link (org-make-link (org-remove-angle-brackets link))))
12426 ;; Check if we are linking to the current file with a search option
12427 ;; If yes, simplify the link by using only the search option.
12428 (when (and buffer-file-name
12429 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12430 (let* ((path (match-string 1 link))
12431 (case-fold-search nil)
12432 (search (match-string 2 link)))
12433 (save-match-data
12434 (if (equal (file-truename buffer-file-name) (file-truename path))
12435 ;; We are linking to this same file, with a search option
12436 (setq link search)))))
12438 ;; Check if we can/should use a relative path. If yes, simplify the link
12439 (when (string-match "\\<file:\\(.*\\)" link)
12440 (let* ((path (match-string 1 link))
12441 (origpath path)
12442 (desc-is-link (equal link desc))
12443 (case-fold-search nil))
12444 (cond
12445 ((eq org-link-file-path-type 'absolute)
12446 (setq path (abbreviate-file-name (expand-file-name path))))
12447 ((eq org-link-file-path-type 'noabbrev)
12448 (setq path (expand-file-name path)))
12449 ((eq org-link-file-path-type 'relative)
12450 (setq path (file-relative-name path)))
12452 (save-match-data
12453 (if (string-match (concat "^" (regexp-quote
12454 (file-name-as-directory
12455 (expand-file-name "."))))
12456 (expand-file-name path))
12457 ;; We are linking a file with relative path name.
12458 (setq path (substring (expand-file-name path)
12459 (match-end 0)))))))
12460 (setq link (concat "file:" path))
12461 (if (equal desc origpath)
12462 (setq desc path))))
12464 (setq desc (read-string "Description: " desc))
12465 (unless (string-match "\\S-" desc) (setq desc nil))
12466 (if remove (apply 'delete-region remove))
12467 (insert (org-make-link-string link desc))))
12469 (defun org-completing-read (&rest args)
12470 (let ((minibuffer-local-completion-map
12471 (copy-keymap minibuffer-local-completion-map)))
12472 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12473 (apply 'completing-read args)))
12475 ;;; Opening/following a link
12476 (defvar org-link-search-failed nil)
12478 (defun org-next-link ()
12479 "Move forward to the next link.
12480 If the link is in hidden text, expose it."
12481 (interactive)
12482 (when (and org-link-search-failed (eq this-command last-command))
12483 (goto-char (point-min))
12484 (message "Link search wrapped back to beginning of buffer"))
12485 (setq org-link-search-failed nil)
12486 (let* ((pos (point))
12487 (ct (org-context))
12488 (a (assoc :link ct)))
12489 (if a (goto-char (nth 2 a)))
12490 (if (re-search-forward org-any-link-re nil t)
12491 (progn
12492 (goto-char (match-beginning 0))
12493 (if (org-invisible-p) (org-show-context)))
12494 (goto-char pos)
12495 (setq org-link-search-failed t)
12496 (error "No further link found"))))
12498 (defun org-previous-link ()
12499 "Move backward to the previous link.
12500 If the link is in hidden text, expose it."
12501 (interactive)
12502 (when (and org-link-search-failed (eq this-command last-command))
12503 (goto-char (point-max))
12504 (message "Link search wrapped back to end of buffer"))
12505 (setq org-link-search-failed nil)
12506 (let* ((pos (point))
12507 (ct (org-context))
12508 (a (assoc :link ct)))
12509 (if a (goto-char (nth 1 a)))
12510 (if (re-search-backward org-any-link-re nil t)
12511 (progn
12512 (goto-char (match-beginning 0))
12513 (if (org-invisible-p) (org-show-context)))
12514 (goto-char pos)
12515 (setq org-link-search-failed t)
12516 (error "No further link found"))))
12518 (defun org-find-file-at-mouse (ev)
12519 "Open file link or URL at mouse."
12520 (interactive "e")
12521 (mouse-set-point ev)
12522 (org-open-at-point 'in-emacs))
12524 (defun org-open-at-mouse (ev)
12525 "Open file link or URL at mouse."
12526 (interactive "e")
12527 (mouse-set-point ev)
12528 (org-open-at-point))
12530 (defvar org-window-config-before-follow-link nil
12531 "The window configuration before following a link.
12532 This is saved in case the need arises to restore it.")
12534 (defvar org-open-link-marker (make-marker)
12535 "Marker pointing to the location where `org-open-at-point; was called.")
12537 ;;;###autoload
12538 (defun org-open-at-point-global ()
12539 "Follow a link like Org-mode does.
12540 This command can be called in any mode to follow a link that has
12541 Org-mode syntax."
12542 (interactive)
12543 (org-run-like-in-org-mode 'org-open-at-point))
12545 (defun org-open-at-point (&optional in-emacs)
12546 "Open link at or after point.
12547 If there is no link at point, this function will search forward up to
12548 the end of the current subtree.
12549 Normally, files will be opened by an appropriate application. If the
12550 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12551 (interactive "P")
12552 (catch 'abort
12553 (move-marker org-open-link-marker (point))
12554 (setq org-window-config-before-follow-link (current-window-configuration))
12555 (org-remove-occur-highlights nil nil t)
12556 (if (org-at-timestamp-p t)
12557 (org-follow-timestamp-link)
12558 (let (type path link line search (pos (point)))
12559 (catch 'match
12560 (save-excursion
12561 (skip-chars-forward "^]\n\r")
12562 (when (org-in-regexp org-bracket-link-regexp)
12563 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12564 (while (string-match " *\n *" link)
12565 (setq link (replace-match " " t t link)))
12566 (setq link (org-link-expand-abbrev link))
12567 (if (string-match org-link-re-with-space2 link)
12568 (setq type (match-string 1 link) path (match-string 2 link))
12569 (setq type "thisfile" path link))
12570 (throw 'match t)))
12572 (when (get-text-property (point) 'org-linked-text)
12573 (setq type "thisfile"
12574 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12575 (1+ (point)) (point))
12576 path (buffer-substring
12577 (previous-single-property-change pos 'org-linked-text)
12578 (next-single-property-change pos 'org-linked-text)))
12579 (throw 'match t))
12581 (save-excursion
12582 (when (or (org-in-regexp org-angle-link-re)
12583 (org-in-regexp org-plain-link-re))
12584 (setq type (match-string 1) path (match-string 2))
12585 (throw 'match t)))
12586 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12587 (setq type "tree-match"
12588 path (match-string 1))
12589 (throw 'match t))
12590 (save-excursion
12591 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12592 (setq type "tags"
12593 path (match-string 1))
12594 (while (string-match ":" path)
12595 (setq path (replace-match "+" t t path)))
12596 (throw 'match t))))
12597 (unless path
12598 (error "No link found"))
12599 ;; Remove any trailing spaces in path
12600 (if (string-match " +\\'" path)
12601 (setq path (replace-match "" t t path)))
12603 (cond
12605 ((assoc type org-link-protocols)
12606 (funcall (nth 1 (assoc type org-link-protocols)) path))
12608 ((equal type "mailto")
12609 (let ((cmd (car org-link-mailto-program))
12610 (args (cdr org-link-mailto-program)) args1
12611 (address path) (subject "") a)
12612 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12613 (setq address (match-string 1 path)
12614 subject (org-link-escape (match-string 2 path))))
12615 (while args
12616 (cond
12617 ((not (stringp (car args))) (push (pop args) args1))
12618 (t (setq a (pop args))
12619 (if (string-match "%a" a)
12620 (setq a (replace-match address t t a)))
12621 (if (string-match "%s" a)
12622 (setq a (replace-match subject t t a)))
12623 (push a args1))))
12624 (apply cmd (nreverse args1))))
12626 ((member type '("http" "https" "ftp" "news"))
12627 (browse-url (concat type ":" (org-link-escape
12628 path org-link-escape-chars-browser))))
12630 ((member type '("message"))
12631 (browse-url (concat type ":" path)))
12633 ((string= type "tags")
12634 (org-tags-view in-emacs path))
12635 ((string= type "thisfile")
12636 (if in-emacs
12637 (switch-to-buffer-other-window
12638 (org-get-buffer-for-internal-link (current-buffer)))
12639 (org-mark-ring-push))
12640 (let ((cmd `(org-link-search
12641 ,path
12642 ,(cond ((equal in-emacs '(4)) 'occur)
12643 ((equal in-emacs '(16)) 'org-occur)
12644 (t nil))
12645 ,pos)))
12646 (condition-case nil (eval cmd)
12647 (error (progn (widen) (eval cmd))))))
12649 ((string= type "tree-match")
12650 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12652 ((string= type "file")
12653 (if (string-match "::\\([0-9]+\\)\\'" path)
12654 (setq line (string-to-number (match-string 1 path))
12655 path (substring path 0 (match-beginning 0)))
12656 (if (string-match "::\\(.+\\)\\'" path)
12657 (setq search (match-string 1 path)
12658 path (substring path 0 (match-beginning 0)))))
12659 (if (string-match "[*?{]" (file-name-nondirectory path))
12660 (dired path)
12661 (org-open-file path in-emacs line search)))
12663 ((string= type "news")
12664 (org-follow-gnus-link path))
12666 ((string= type "bbdb")
12667 (org-follow-bbdb-link path))
12669 ((string= type "info")
12670 (org-follow-info-link path))
12672 ((string= type "gnus")
12673 (let (group article)
12674 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12675 (error "Error in Gnus link"))
12676 (setq group (match-string 1 path)
12677 article (match-string 3 path))
12678 (org-follow-gnus-link group article)))
12680 ((string= type "vm")
12681 (let (folder article)
12682 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12683 (error "Error in VM link"))
12684 (setq folder (match-string 1 path)
12685 article (match-string 3 path))
12686 ;; in-emacs is the prefix arg, will be interpreted as read-only
12687 (org-follow-vm-link folder article in-emacs)))
12689 ((string= type "wl")
12690 (let (folder article)
12691 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12692 (error "Error in Wanderlust link"))
12693 (setq folder (match-string 1 path)
12694 article (match-string 3 path))
12695 (org-follow-wl-link folder article)))
12697 ((string= type "mhe")
12698 (let (folder article)
12699 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12700 (error "Error in MHE link"))
12701 (setq folder (match-string 1 path)
12702 article (match-string 3 path))
12703 (org-follow-mhe-link folder article)))
12705 ((string= type "rmail")
12706 (let (folder article)
12707 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12708 (error "Error in RMAIL link"))
12709 (setq folder (match-string 1 path)
12710 article (match-string 3 path))
12711 (org-follow-rmail-link folder article)))
12713 ((string= type "shell")
12714 (let ((cmd path))
12715 (if (or (not org-confirm-shell-link-function)
12716 (funcall org-confirm-shell-link-function
12717 (format "Execute \"%s\" in shell? "
12718 (org-add-props cmd nil
12719 'face 'org-warning))))
12720 (progn
12721 (message "Executing %s" cmd)
12722 (shell-command cmd))
12723 (error "Abort"))))
12725 ((string= type "elisp")
12726 (let ((cmd path))
12727 (if (or (not org-confirm-elisp-link-function)
12728 (funcall org-confirm-elisp-link-function
12729 (format "Execute \"%s\" as elisp? "
12730 (org-add-props cmd nil
12731 'face 'org-warning))))
12732 (message "%s => %s" cmd (eval (read cmd)))
12733 (error "Abort"))))
12736 (browse-url-at-point)))))
12737 (move-marker org-open-link-marker nil)))
12739 ;;; File search
12741 (defvar org-create-file-search-functions nil
12742 "List of functions to construct the right search string for a file link.
12743 These functions are called in turn with point at the location to
12744 which the link should point.
12746 A function in the hook should first test if it would like to
12747 handle this file type, for example by checking the major-mode or
12748 the file extension. If it decides not to handle this file, it
12749 should just return nil to give other functions a chance. If it
12750 does handle the file, it must return the search string to be used
12751 when following the link. The search string will be part of the
12752 file link, given after a double colon, and `org-open-at-point'
12753 will automatically search for it. If special measures must be
12754 taken to make the search successful, another function should be
12755 added to the companion hook `org-execute-file-search-functions',
12756 which see.
12758 A function in this hook may also use `setq' to set the variable
12759 `description' to provide a suggestion for the descriptive text to
12760 be used for this link when it gets inserted into an Org-mode
12761 buffer with \\[org-insert-link].")
12763 (defvar org-execute-file-search-functions nil
12764 "List of functions to execute a file search triggered by a link.
12766 Functions added to this hook must accept a single argument, the
12767 search string that was part of the file link, the part after the
12768 double colon. The function must first check if it would like to
12769 handle this search, for example by checking the major-mode or the
12770 file extension. If it decides not to handle this search, it
12771 should just return nil to give other functions a chance. If it
12772 does handle the search, it must return a non-nil value to keep
12773 other functions from trying.
12775 Each function can access the current prefix argument through the
12776 variable `current-prefix-argument'. Note that a single prefix is
12777 used to force opening a link in Emacs, so it may be good to only
12778 use a numeric or double prefix to guide the search function.
12780 In case this is needed, a function in this hook can also restore
12781 the window configuration before `org-open-at-point' was called using:
12783 (set-window-configuration org-window-config-before-follow-link)")
12785 (defun org-link-search (s &optional type avoid-pos)
12786 "Search for a link search option.
12787 If S is surrounded by forward slashes, it is interpreted as a
12788 regular expression. In org-mode files, this will create an `org-occur'
12789 sparse tree. In ordinary files, `occur' will be used to list matches.
12790 If the current buffer is in `dired-mode', grep will be used to search
12791 in all files. If AVOID-POS is given, ignore matches near that position."
12792 (let ((case-fold-search t)
12793 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12794 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12795 (append '(("") (" ") ("\t") ("\n"))
12796 org-emphasis-alist)
12797 "\\|") "\\)"))
12798 (pos (point))
12799 (pre "") (post "")
12800 words re0 re1 re2 re3 re4 re5 re2a reall)
12801 (cond
12802 ;; First check if there are any special
12803 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12804 ;; Now try the builtin stuff
12805 ((save-excursion
12806 (goto-char (point-min))
12807 (and
12808 (re-search-forward
12809 (concat "<<" (regexp-quote s0) ">>") nil t)
12810 (setq pos (match-beginning 0))))
12811 ;; There is an exact target for this
12812 (goto-char pos))
12813 ((string-match "^/\\(.*\\)/$" s)
12814 ;; A regular expression
12815 (cond
12816 ((org-mode-p)
12817 (org-occur (match-string 1 s)))
12818 ;;((eq major-mode 'dired-mode)
12819 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12820 (t (org-do-occur (match-string 1 s)))))
12822 ;; A normal search strings
12823 (when (equal (string-to-char s) ?*)
12824 ;; Anchor on headlines, post may include tags.
12825 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
12826 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
12827 s (substring s 1)))
12828 (remove-text-properties
12829 0 (length s)
12830 '(face nil mouse-face nil keymap nil fontified nil) s)
12831 ;; Make a series of regular expressions to find a match
12832 (setq words (org-split-string s "[ \n\r\t]+")
12833 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
12834 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
12835 "\\)" markers)
12836 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
12837 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
12838 re1 (concat pre re2 post)
12839 re3 (concat pre re4 post)
12840 re5 (concat pre ".*" re4)
12841 re2 (concat pre re2)
12842 re2a (concat pre re2a)
12843 re4 (concat pre re4)
12844 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
12845 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
12846 re5 "\\)"
12848 (cond
12849 ((eq type 'org-occur) (org-occur reall))
12850 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
12851 (t (goto-char (point-min))
12852 (if (or (org-search-not-self 1 re0 nil t)
12853 (org-search-not-self 1 re1 nil t)
12854 (org-search-not-self 1 re2 nil t)
12855 (org-search-not-self 1 re2a nil t)
12856 (org-search-not-self 1 re3 nil t)
12857 (org-search-not-self 1 re4 nil t)
12858 (org-search-not-self 1 re5 nil t)
12860 (goto-char (match-beginning 1))
12861 (goto-char pos)
12862 (error "No match")))))
12864 ;; Normal string-search
12865 (goto-char (point-min))
12866 (if (search-forward s nil t)
12867 (goto-char (match-beginning 0))
12868 (error "No match"))))
12869 (and (org-mode-p) (org-show-context 'link-search))))
12871 (defun org-search-not-self (group &rest args)
12872 "Execute `re-search-forward', but only accept matches that do not
12873 enclose the position of `org-open-link-marker'."
12874 (let ((m org-open-link-marker))
12875 (catch 'exit
12876 (while (apply 're-search-forward args)
12877 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
12878 (goto-char (match-end group))
12879 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
12880 (> (match-beginning 0) (marker-position m))
12881 (< (match-end 0) (marker-position m)))
12882 (save-match-data
12883 (or (not (org-in-regexp
12884 org-bracket-link-analytic-regexp 1))
12885 (not (match-end 4)) ; no description
12886 (and (<= (match-beginning 4) (point))
12887 (>= (match-end 4) (point))))))
12888 (throw 'exit (point))))))))
12890 (defun org-get-buffer-for-internal-link (buffer)
12891 "Return a buffer to be used for displaying the link target of internal links."
12892 (cond
12893 ((not org-display-internal-link-with-indirect-buffer)
12894 buffer)
12895 ((string-match "(Clone)$" (buffer-name buffer))
12896 (message "Buffer is already a clone, not making another one")
12897 ;; we also do not modify visibility in this case
12898 buffer)
12899 (t ; make a new indirect buffer for displaying the link
12900 (let* ((bn (buffer-name buffer))
12901 (ibn (concat bn "(Clone)"))
12902 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
12903 (with-current-buffer ib (org-overview))
12904 ib))))
12906 (defun org-do-occur (regexp &optional cleanup)
12907 "Call the Emacs command `occur'.
12908 If CLEANUP is non-nil, remove the printout of the regular expression
12909 in the *Occur* buffer. This is useful if the regex is long and not useful
12910 to read."
12911 (occur regexp)
12912 (when cleanup
12913 (let ((cwin (selected-window)) win beg end)
12914 (when (setq win (get-buffer-window "*Occur*"))
12915 (select-window win))
12916 (goto-char (point-min))
12917 (when (re-search-forward "match[a-z]+" nil t)
12918 (setq beg (match-end 0))
12919 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
12920 (setq end (1- (match-beginning 0)))))
12921 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
12922 (goto-char (point-min))
12923 (select-window cwin))))
12925 ;;; The mark ring for links jumps
12927 (defvar org-mark-ring nil
12928 "Mark ring for positions before jumps in Org-mode.")
12929 (defvar org-mark-ring-last-goto nil
12930 "Last position in the mark ring used to go back.")
12931 ;; Fill and close the ring
12932 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
12933 (loop for i from 1 to org-mark-ring-length do
12934 (push (make-marker) org-mark-ring))
12935 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
12936 org-mark-ring)
12938 (defun org-mark-ring-push (&optional pos buffer)
12939 "Put the current position or POS into the mark ring and rotate it."
12940 (interactive)
12941 (setq pos (or pos (point)))
12942 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
12943 (move-marker (car org-mark-ring)
12944 (or pos (point))
12945 (or buffer (current-buffer)))
12946 (message "%s"
12947 (substitute-command-keys
12948 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
12950 (defun org-mark-ring-goto (&optional n)
12951 "Jump to the previous position in the mark ring.
12952 With prefix arg N, jump back that many stored positions. When
12953 called several times in succession, walk through the entire ring.
12954 Org-mode commands jumping to a different position in the current file,
12955 or to another Org-mode file, automatically push the old position
12956 onto the ring."
12957 (interactive "p")
12958 (let (p m)
12959 (if (eq last-command this-command)
12960 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
12961 (setq p org-mark-ring))
12962 (setq org-mark-ring-last-goto p)
12963 (setq m (car p))
12964 (switch-to-buffer (marker-buffer m))
12965 (goto-char m)
12966 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
12968 (defun org-remove-angle-brackets (s)
12969 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
12970 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
12972 (defun org-add-angle-brackets (s)
12973 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
12974 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
12977 ;;; Following specific links
12979 (defun org-follow-timestamp-link ()
12980 (cond
12981 ((org-at-date-range-p t)
12982 (let ((org-agenda-start-on-weekday)
12983 (t1 (match-string 1))
12984 (t2 (match-string 2)))
12985 (setq t1 (time-to-days (org-time-string-to-time t1))
12986 t2 (time-to-days (org-time-string-to-time t2)))
12987 (org-agenda-list nil t1 (1+ (- t2 t1)))))
12988 ((org-at-timestamp-p t)
12989 (org-agenda-list nil (time-to-days (org-time-string-to-time
12990 (substring (match-string 1) 0 10)))
12992 (t (error "This should not happen"))))
12995 (defun org-follow-bbdb-link (name)
12996 "Follow a BBDB link to NAME."
12997 (require 'bbdb)
12998 (let ((inhibit-redisplay (not debug-on-error))
12999 (bbdb-electric-p nil))
13000 (catch 'exit
13001 ;; Exact match on name
13002 (bbdb-name (concat "\\`" name "\\'") nil)
13003 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13004 ;; Exact match on name
13005 (bbdb-company (concat "\\`" name "\\'") nil)
13006 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13007 ;; Partial match on name
13008 (bbdb-name name nil)
13009 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13010 ;; Partial match on company
13011 (bbdb-company name nil)
13012 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13013 ;; General match including network address and notes
13014 (bbdb name nil)
13015 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
13016 (delete-window (get-buffer-window "*BBDB*"))
13017 (error "No matching BBDB record")))))
13019 (defun org-follow-info-link (name)
13020 "Follow an info file & node link to NAME."
13021 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
13022 (string-match "\\(.*\\)" name))
13023 (progn
13024 (require 'info)
13025 (if (match-string 2 name) ; If there isn't a node, choose "Top"
13026 (Info-find-node (match-string 1 name) (match-string 2 name))
13027 (Info-find-node (match-string 1 name) "Top")))
13028 (message "Could not open: %s" name)))
13030 (defun org-follow-gnus-link (&optional group article)
13031 "Follow a Gnus link to GROUP and ARTICLE."
13032 (require 'gnus)
13033 (funcall (cdr (assq 'gnus org-link-frame-setup)))
13034 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
13035 (cond ((and group article)
13036 (gnus-group-read-group 1 nil group)
13037 (gnus-summary-goto-article (string-to-number article) nil t))
13038 (group (gnus-group-jump-to-group group))))
13040 (defun org-follow-vm-link (&optional folder article readonly)
13041 "Follow a VM link to FOLDER and ARTICLE."
13042 (require 'vm)
13043 (setq article (org-add-angle-brackets article))
13044 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
13045 ;; ange-ftp or efs or tramp access
13046 (let ((user (or (match-string 1 folder) (user-login-name)))
13047 (host (match-string 2 folder))
13048 (file (match-string 3 folder)))
13049 (cond
13050 ((featurep 'tramp)
13051 ;; use tramp to access the file
13052 (if (featurep 'xemacs)
13053 (setq folder (format "[%s@%s]%s" user host file))
13054 (setq folder (format "/%s@%s:%s" user host file))))
13056 ;; use ange-ftp or efs
13057 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
13058 (setq folder (format "/%s@%s:%s" user host file))))))
13059 (when folder
13060 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
13061 (sit-for 0.1)
13062 (when article
13063 (vm-select-folder-buffer)
13064 (widen)
13065 (let ((case-fold-search t))
13066 (goto-char (point-min))
13067 (if (not (re-search-forward
13068 (concat "^" "message-id: *" (regexp-quote article))))
13069 (error "Could not find the specified message in this folder"))
13070 (vm-isearch-update)
13071 (vm-isearch-narrow)
13072 (vm-beginning-of-message)
13073 (vm-summarize)))))
13075 (defun org-follow-wl-link (folder article)
13076 "Follow a Wanderlust link to FOLDER and ARTICLE."
13077 (if (and (string= folder "%")
13078 article
13079 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
13080 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
13081 ;; Thus, we recompose folder and article ids.
13082 (setq folder (format "%s#%s" folder (match-string 1 article))
13083 article (match-string 3 article)))
13084 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
13085 (error "No such folder: %s" folder))
13086 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
13087 (and article
13088 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
13089 (wl-summary-redisplay)))
13091 (defun org-follow-rmail-link (folder article)
13092 "Follow an RMAIL link to FOLDER and ARTICLE."
13093 (setq article (org-add-angle-brackets article))
13094 (let (message-number)
13095 (save-excursion
13096 (save-window-excursion
13097 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13098 (setq message-number
13099 (save-restriction
13100 (widen)
13101 (goto-char (point-max))
13102 (if (re-search-backward
13103 (concat "^Message-ID:\\s-+" (regexp-quote
13104 (or article "")))
13105 nil t)
13106 (rmail-what-message))))))
13107 (if message-number
13108 (progn
13109 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13110 (rmail-show-message message-number)
13111 message-number)
13112 (error "Message not found"))))
13114 ;;; mh-e integration based on planner-mode
13115 (defun org-mhe-get-message-real-folder ()
13116 "Return the name of the current message real folder, so if you use
13117 sequences, it will now work."
13118 (save-excursion
13119 (let* ((folder
13120 (if (equal major-mode 'mh-folder-mode)
13121 mh-current-folder
13122 ;; Refer to the show buffer
13123 mh-show-folder-buffer))
13124 (end-index
13125 (if (boundp 'mh-index-folder)
13126 (min (length mh-index-folder) (length folder))))
13128 ;; a simple test on mh-index-data does not work, because
13129 ;; mh-index-data is always nil in a show buffer.
13130 (if (and (boundp 'mh-index-folder)
13131 (string= mh-index-folder (substring folder 0 end-index)))
13132 (if (equal major-mode 'mh-show-mode)
13133 (save-window-excursion
13134 (let (pop-up-frames)
13135 (when (buffer-live-p (get-buffer folder))
13136 (progn
13137 (pop-to-buffer folder)
13138 (org-mhe-get-message-folder-from-index)
13141 (org-mhe-get-message-folder-from-index)
13143 folder
13147 (defun org-mhe-get-message-folder-from-index ()
13148 "Returns the name of the message folder in a index folder buffer."
13149 (save-excursion
13150 (mh-index-previous-folder)
13151 (re-search-forward "^\\(+.*\\)$" nil t)
13152 (message "%s" (match-string 1))))
13154 (defun org-mhe-get-message-folder ()
13155 "Return the name of the current message folder. Be careful if you
13156 use sequences."
13157 (save-excursion
13158 (if (equal major-mode 'mh-folder-mode)
13159 mh-current-folder
13160 ;; Refer to the show buffer
13161 mh-show-folder-buffer)))
13163 (defun org-mhe-get-message-num ()
13164 "Return the number of the current message. Be careful if you
13165 use sequences."
13166 (save-excursion
13167 (if (equal major-mode 'mh-folder-mode)
13168 (mh-get-msg-num nil)
13169 ;; Refer to the show buffer
13170 (mh-show-buffer-message-number))))
13172 (defun org-mhe-get-header (header)
13173 "Return a header of the message in folder mode. This will create a
13174 show buffer for the corresponding message. If you have a more clever
13175 idea..."
13176 (let* ((folder (org-mhe-get-message-folder))
13177 (num (org-mhe-get-message-num))
13178 (buffer (get-buffer-create (concat "show-" folder)))
13179 (header-field))
13180 (with-current-buffer buffer
13181 (mh-display-msg num folder)
13182 (if (equal major-mode 'mh-folder-mode)
13183 (mh-header-display)
13184 (mh-show-header-display))
13185 (set-buffer buffer)
13186 (setq header-field (mh-get-header-field header))
13187 (if (equal major-mode 'mh-folder-mode)
13188 (mh-show)
13189 (mh-show-show))
13190 header-field)))
13192 (defun org-follow-mhe-link (folder article)
13193 "Follow an MHE link to FOLDER and ARTICLE.
13194 If ARTICLE is nil FOLDER is shown. If the configuration variable
13195 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
13196 ARTICLE is searched in all folders. Indexed searches (swish++,
13197 namazu, and others supported by MH-E) will always search in all
13198 folders."
13199 (require 'mh-e)
13200 (require 'mh-search)
13201 (require 'mh-utils)
13202 (mh-find-path)
13203 (if (not article)
13204 (mh-visit-folder (mh-normalize-folder-name folder))
13205 (setq article (org-add-angle-brackets article))
13206 (mh-search-choose)
13207 (if (equal mh-searcher 'pick)
13208 (progn
13209 (mh-search folder (list "--message-id" article))
13210 (when (and org-mhe-search-all-folders
13211 (not (org-mhe-get-message-real-folder)))
13212 (kill-this-buffer)
13213 (mh-search "+" (list "--message-id" article))))
13214 (mh-search "+" article))
13215 (if (org-mhe-get-message-real-folder)
13216 (mh-show-msg 1)
13217 (kill-this-buffer)
13218 (error "Message not found"))))
13220 ;;; BibTeX links
13222 ;; Use the custom search meachnism to construct and use search strings for
13223 ;; file links to BibTeX database entries.
13225 (defun org-create-file-search-in-bibtex ()
13226 "Create the search string and description for a BibTeX database entry."
13227 (when (eq major-mode 'bibtex-mode)
13228 ;; yes, we want to construct this search string.
13229 ;; Make a good description for this entry, using names, year and the title
13230 ;; Put it into the `description' variable which is dynamically scoped.
13231 (let ((bibtex-autokey-names 1)
13232 (bibtex-autokey-names-stretch 1)
13233 (bibtex-autokey-name-case-convert-function 'identity)
13234 (bibtex-autokey-name-separator " & ")
13235 (bibtex-autokey-additional-names " et al.")
13236 (bibtex-autokey-year-length 4)
13237 (bibtex-autokey-name-year-separator " ")
13238 (bibtex-autokey-titlewords 3)
13239 (bibtex-autokey-titleword-separator " ")
13240 (bibtex-autokey-titleword-case-convert-function 'identity)
13241 (bibtex-autokey-titleword-length 'infty)
13242 (bibtex-autokey-year-title-separator ": "))
13243 (setq description (bibtex-generate-autokey)))
13244 ;; Now parse the entry, get the key and return it.
13245 (save-excursion
13246 (bibtex-beginning-of-entry)
13247 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13249 (defun org-execute-file-search-in-bibtex (s)
13250 "Find the link search string S as a key for a database entry."
13251 (when (eq major-mode 'bibtex-mode)
13252 ;; Yes, we want to do the search in this file.
13253 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13254 (goto-char (point-min))
13255 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13256 (regexp-quote s) "[ \t\n]*,") nil t)
13257 (goto-char (match-beginning 0)))
13258 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13259 ;; Use double prefix to indicate that any web link should be browsed
13260 (let ((b (current-buffer)) (p (point)))
13261 ;; Restore the window configuration because we just use the web link
13262 (set-window-configuration org-window-config-before-follow-link)
13263 (save-excursion (set-buffer b) (goto-char p)
13264 (bibtex-url)))
13265 (recenter 0)) ; Move entry start to beginning of window
13266 ;; return t to indicate that the search is done.
13269 ;; Finally add the functions to the right hooks.
13270 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13271 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13273 ;; end of Bibtex link setup
13275 ;;; Following file links
13277 (defun org-open-file (path &optional in-emacs line search)
13278 "Open the file at PATH.
13279 First, this expands any special file name abbreviations. Then the
13280 configuration variable `org-file-apps' is checked if it contains an
13281 entry for this file type, and if yes, the corresponding command is launched.
13282 If no application is found, Emacs simply visits the file.
13283 With optional argument IN-EMACS, Emacs will visit the file.
13284 Optional LINE specifies a line to go to, optional SEARCH a string to
13285 search for. If LINE or SEARCH is given, the file will always be
13286 opened in Emacs.
13287 If the file does not exist, an error is thrown."
13288 (setq in-emacs (or in-emacs line search))
13289 (let* ((file (if (equal path "")
13290 buffer-file-name
13291 (substitute-in-file-name (expand-file-name path))))
13292 (apps (append org-file-apps (org-default-apps)))
13293 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13294 (dirp (if remp nil (file-directory-p file)))
13295 (dfile (downcase file))
13296 (old-buffer (current-buffer))
13297 (old-pos (point))
13298 (old-mode major-mode)
13299 ext cmd)
13300 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13301 (setq ext (match-string 1 dfile))
13302 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13303 (setq ext (match-string 1 dfile))))
13304 (if in-emacs
13305 (setq cmd 'emacs)
13306 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13307 (and dirp (cdr (assoc 'directory apps)))
13308 (cdr (assoc ext apps))
13309 (cdr (assoc t apps)))))
13310 (when (eq cmd 'mailcap)
13311 (require 'mailcap)
13312 (mailcap-parse-mailcaps)
13313 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13314 (command (mailcap-mime-info mime-type)))
13315 (if (stringp command)
13316 (setq cmd command)
13317 (setq cmd 'emacs))))
13318 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13319 (not (file-exists-p file))
13320 (not org-open-non-existing-files))
13321 (error "No such file: %s" file))
13322 (cond
13323 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13324 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13325 (while (string-match "['\"]%s['\"]" cmd)
13326 (setq cmd (replace-match "%s" t t cmd)))
13327 (while (string-match "%s" cmd)
13328 (setq cmd (replace-match
13329 (save-match-data (shell-quote-argument file))
13330 t t cmd)))
13331 (save-window-excursion
13332 (start-process-shell-command cmd nil cmd)))
13333 ((or (stringp cmd)
13334 (eq cmd 'emacs))
13335 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13336 (widen)
13337 (if line (goto-line line)
13338 (if search (org-link-search search))))
13339 ((consp cmd)
13340 (eval cmd))
13341 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13342 (and (org-mode-p) (eq old-mode 'org-mode)
13343 (or (not (equal old-buffer (current-buffer)))
13344 (not (equal old-pos (point))))
13345 (org-mark-ring-push old-pos old-buffer))))
13347 (defun org-default-apps ()
13348 "Return the default applications for this operating system."
13349 (cond
13350 ((eq system-type 'darwin)
13351 org-file-apps-defaults-macosx)
13352 ((eq system-type 'windows-nt)
13353 org-file-apps-defaults-windowsnt)
13354 (t org-file-apps-defaults-gnu)))
13356 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13357 (defun org-file-remote-p (file)
13358 "Test whether FILE specifies a location on a remote system.
13359 Return non-nil if the location is indeed remote.
13361 For example, the filename \"/user@host:/foo\" specifies a location
13362 on the system \"/user@host:\"."
13363 (cond ((fboundp 'file-remote-p)
13364 (file-remote-p file))
13365 ((fboundp 'tramp-handle-file-remote-p)
13366 (tramp-handle-file-remote-p file))
13367 ((and (boundp 'ange-ftp-name-format)
13368 (string-match (car ange-ftp-name-format) file))
13370 (t nil)))
13373 ;;;; Hooks for remember.el, and refiling
13375 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13376 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13378 ;;;###autoload
13379 (defun org-remember-insinuate ()
13380 "Setup remember.el for use wiht Org-mode."
13381 (require 'remember)
13382 (setq remember-annotation-functions '(org-remember-annotation))
13383 (setq remember-handler-functions '(org-remember-handler))
13384 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13386 ;;;###autoload
13387 (defun org-remember-annotation ()
13388 "Return a link to the current location as an annotation for remember.el.
13389 If you are using Org-mode files as target for data storage with
13390 remember.el, then the annotations should include a link compatible with the
13391 conventions in Org-mode. This function returns such a link."
13392 (org-store-link nil))
13394 (defconst org-remember-help
13395 "Select a destination location for the note.
13396 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13397 RET on headline -> Store as sublevel entry to current headline
13398 RET at beg-of-buf -> Append to file as level 2 headline
13399 <left>/<right> -> before/after current headline, same headings level")
13401 (defvar org-remember-previous-location nil)
13402 (defvar org-force-remember-template-char) ;; dynamically scoped
13404 (defun org-select-remember-template (&optional use-char)
13405 (when org-remember-templates
13406 (let* ((templates (mapcar (lambda (x)
13407 (if (stringp (car x))
13408 (append (list (nth 1 x) (car x)) (cddr x))
13409 (append (list (car x) "") (cdr x))))
13410 org-remember-templates))
13411 (char (or use-char
13412 (cond
13413 ((= (length templates) 1)
13414 (caar templates))
13415 ((and (boundp 'org-force-remember-template-char)
13416 org-force-remember-template-char)
13417 (if (stringp org-force-remember-template-char)
13418 (string-to-char org-force-remember-template-char)
13419 org-force-remember-template-char))
13421 (message "Select template: %s"
13422 (mapconcat
13423 (lambda (x)
13424 (cond
13425 ((not (string-match "\\S-" (nth 1 x)))
13426 (format "[%c]" (car x)))
13427 ((equal (downcase (car x))
13428 (downcase (aref (nth 1 x) 0)))
13429 (format "[%c]%s" (car x)
13430 (substring (nth 1 x) 1)))
13431 (t (format "[%c]%s" (car x) (nth 1 x)))))
13432 templates " "))
13433 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13434 (when (equal char0 ?\C-g)
13435 (jump-to-register remember-register)
13436 (kill-buffer remember-buffer))
13437 char0))))))
13438 (cddr (assoc char templates)))))
13440 (defvar x-last-selected-text)
13441 (defvar x-last-selected-text-primary)
13443 ;;;###autoload
13444 (defun org-remember-apply-template (&optional use-char skip-interactive)
13445 "Initialize *remember* buffer with template, invoke `org-mode'.
13446 This function should be placed into `remember-mode-hook' and in fact requires
13447 to be run from that hook to function properly."
13448 (if org-remember-templates
13449 (let* ((entry (org-select-remember-template use-char))
13450 (tpl (car entry))
13451 (plist-p (if org-store-link-plist t nil))
13452 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13453 (string-match "\\S-" (nth 1 entry)))
13454 (nth 1 entry)
13455 org-default-notes-file))
13456 (headline (nth 2 entry))
13457 (v-c (or (and (eq window-system 'x)
13458 (fboundp 'x-cut-buffer-or-selection-value)
13459 (x-cut-buffer-or-selection-value))
13460 (org-bound-and-true-p x-last-selected-text)
13461 (org-bound-and-true-p x-last-selected-text-primary)
13462 (and (> (length kill-ring) 0) (current-kill 0))))
13463 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13464 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13465 (v-u (concat "[" (substring v-t 1 -1) "]"))
13466 (v-U (concat "[" (substring v-T 1 -1) "]"))
13467 ;; `initial' and `annotation' are bound in `remember'
13468 (v-i (if (boundp 'initial) initial))
13469 (v-a (if (and (boundp 'annotation) annotation)
13470 (if (equal annotation "[[]]") "" annotation)
13471 ""))
13472 (v-A (if (and v-a
13473 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13474 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13475 v-a))
13476 (v-n user-full-name)
13477 (org-startup-folded nil)
13478 org-time-was-given org-end-time-was-given x
13479 prompt completions char time pos default histvar)
13480 (setq org-store-link-plist
13481 (append (list :annotation v-a :initial v-i)
13482 org-store-link-plist))
13483 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13484 (erase-buffer)
13485 (insert (substitute-command-keys
13486 (format
13487 "## Filing location: Select interactively, default, or last used:
13488 ## %s to select file and header location interactively.
13489 ## %s \"%s\" -> \"* %s\"
13490 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13491 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13492 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13493 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13494 (abbreviate-file-name (or file org-default-notes-file))
13495 (or headline "")
13496 (or (car org-remember-previous-location) "???")
13497 (or (cdr org-remember-previous-location) "???"))))
13498 (insert tpl) (goto-char (point-min))
13499 ;; Simple %-escapes
13500 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13501 (when (and initial (equal (match-string 0) "%i"))
13502 (save-match-data
13503 (let* ((lead (buffer-substring
13504 (point-at-bol) (match-beginning 0))))
13505 (setq v-i (mapconcat 'identity
13506 (org-split-string initial "\n")
13507 (concat "\n" lead))))))
13508 (replace-match
13509 (or (eval (intern (concat "v-" (match-string 1)))) "")
13510 t t))
13512 ;; %[] Insert contents of a file.
13513 (goto-char (point-min))
13514 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13515 (let ((start (match-beginning 0))
13516 (end (match-end 0))
13517 (filename (expand-file-name (match-string 1))))
13518 (goto-char start)
13519 (delete-region start end)
13520 (condition-case error
13521 (insert-file-contents filename)
13522 (error (insert (format "%%![Couldn't insert %s: %s]"
13523 filename error))))))
13524 ;; %() embedded elisp
13525 (goto-char (point-min))
13526 (while (re-search-forward "%\\((.+)\\)" nil t)
13527 (goto-char (match-beginning 0))
13528 (let ((template-start (point)))
13529 (forward-char 1)
13530 (let ((result
13531 (condition-case error
13532 (eval (read (current-buffer)))
13533 (error (format "%%![Error: %s]" error)))))
13534 (delete-region template-start (point))
13535 (insert result))))
13537 ;; From the property list
13538 (when plist-p
13539 (goto-char (point-min))
13540 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13541 (and (setq x (or (plist-get org-store-link-plist
13542 (intern (match-string 1))) ""))
13543 (replace-match x t t))))
13545 ;; Turn on org-mode in the remember buffer, set local variables
13546 (org-mode)
13547 (org-set-local 'org-finish-function 'org-remember-finalize)
13548 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13549 (org-set-local 'org-default-notes-file file))
13550 (if (and headline (stringp headline) (string-match "\\S-" headline))
13551 (org-set-local 'org-remember-default-headline headline))
13552 ;; Interactive template entries
13553 (goto-char (point-min))
13554 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGuUtT]\\)?" nil t)
13555 (setq char (if (match-end 3) (match-string 3))
13556 prompt (if (match-end 2) (match-string 2)))
13557 (goto-char (match-beginning 0))
13558 (replace-match "")
13559 (setq completions nil default nil)
13560 (when prompt
13561 (setq completions (org-split-string prompt "|")
13562 prompt (pop completions)
13563 default (car completions)
13564 histvar (intern (concat
13565 "org-remember-template-prompt-history::"
13566 (or prompt "")))
13567 completions (mapcar 'list completions)))
13568 (cond
13569 ((member char '("G" "g"))
13570 (let* ((org-last-tags-completion-table
13571 (org-global-tags-completion-table
13572 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13573 (org-add-colon-after-tag-completion t)
13574 (ins (completing-read
13575 (if prompt (concat prompt ": ") "Tags: ")
13576 'org-tags-completion-function nil nil nil
13577 'org-tags-history)))
13578 (setq ins (mapconcat 'identity
13579 (org-split-string ins (org-re "[^[:alnum:]_@]+"))
13580 ":"))
13581 (when (string-match "\\S-" ins)
13582 (or (equal (char-before) ?:) (insert ":"))
13583 (insert ins)
13584 (or (equal (char-after) ?:) (insert ":")))))
13585 (char
13586 (setq org-time-was-given (equal (upcase char) char))
13587 (setq time (org-read-date (equal (upcase char) "U") t nil
13588 prompt))
13589 (org-insert-time-stamp time org-time-was-given
13590 (member char '("u" "U"))
13591 nil nil (list org-end-time-was-given)))
13593 (insert (org-completing-read
13594 (concat (if prompt prompt "Enter string")
13595 (if default (concat " [" default "]"))
13596 ": ")
13597 completions nil nil nil histvar default)))))
13598 (goto-char (point-min))
13599 (if (re-search-forward "%\\?" nil t)
13600 (replace-match "")
13601 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13602 (org-mode)
13603 (org-set-local 'org-finish-function 'org-remember-finalize))
13604 (when (save-excursion
13605 (goto-char (point-min))
13606 (re-search-forward "%!" nil t))
13607 (replace-match "")
13608 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13610 (defun org-remember-finish-immediately ()
13611 "File remember note immediately.
13612 This should be run in `post-command-hook' and will remove itself
13613 from that hook."
13614 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13615 (when org-finish-function
13616 (funcall org-finish-function)))
13618 (defvar org-clock-marker) ; Defined below
13619 (defun org-remember-finalize ()
13620 "Finalize the remember process."
13621 (unless (fboundp 'remember-finalize)
13622 (defalias 'remember-finalize 'remember-buffer))
13623 (when (and org-clock-marker
13624 (equal (marker-buffer org-clock-marker) (current-buffer)))
13625 ;; FIXME: test this, this is w/o notetaking!
13626 (let (org-log-done) (org-clock-out)))
13627 (when buffer-file-name
13628 (save-buffer)
13629 (setq buffer-file-name nil))
13630 (remember-finalize))
13632 ;;;###autoload
13633 (defun org-remember (&optional goto org-force-remember-template-char)
13634 "Call `remember'. If this is already a remember buffer, re-apply template.
13635 If there is an active region, make sure remember uses it as initial content
13636 of the remember buffer.
13638 When called interactively with a `C-u' prefix argument GOTO, don't remember
13639 anything, just go to the file/headline where the selected template usually
13640 stores its notes. With a double prefix arg `C-u C-u', go to the last
13641 note stored by remember.
13643 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13644 associated with a template in `org-remember-templates'."
13645 (interactive "P")
13646 (cond
13647 ((equal goto '(4)) (org-go-to-remember-target))
13648 ((equal goto '(16)) (org-remember-goto-last-stored))
13650 (if (memq org-finish-function '(remember-buffer remember-finalize))
13651 (progn
13652 (when (< (length org-remember-templates) 2)
13653 (error "No other template available"))
13654 (erase-buffer)
13655 (let ((annotation (plist-get org-store-link-plist :annotation))
13656 (initial (plist-get org-store-link-plist :initial)))
13657 (org-remember-apply-template))
13658 (message "Press C-c C-c to remember data"))
13659 (if (org-region-active-p)
13660 (remember (buffer-substring (point) (mark)))
13661 (call-interactively 'remember))))))
13663 (defun org-remember-goto-last-stored ()
13664 "Go to the location where the last remember note was stored."
13665 (interactive)
13666 (bookmark-jump "org-remember-last-stored")
13667 (message "This is the last note stored by remember"))
13669 (defun org-go-to-remember-target (&optional template-key)
13670 "Go to the target location of a remember template.
13671 The user is queried for the template."
13672 (interactive)
13673 (let* ((entry (org-select-remember-template template-key))
13674 (file (nth 1 entry))
13675 (heading (nth 2 entry))
13676 visiting)
13677 (unless (and file (stringp file) (string-match "\\S-" file))
13678 (setq file org-default-notes-file))
13679 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13680 (setq heading org-remember-default-headline))
13681 (setq visiting (org-find-base-buffer-visiting file))
13682 (if (not visiting) (find-file-noselect file))
13683 (switch-to-buffer (or visiting (get-file-buffer file)))
13684 (widen)
13685 (goto-char (point-min))
13686 (if (re-search-forward
13687 (concat "^\\*+[ \t]+" (regexp-quote heading)
13688 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13689 nil t)
13690 (goto-char (match-beginning 0))
13691 (error "Target headline not found: %s" heading))))
13693 (defvar org-note-abort nil) ; dynamically scoped
13695 ;;;###autoload
13696 (defun org-remember-handler ()
13697 "Store stuff from remember.el into an org file.
13698 First prompts for an org file. If the user just presses return, the value
13699 of `org-default-notes-file' is used.
13700 Then the command offers the headings tree of the selected file in order to
13701 file the text at a specific location.
13702 You can either immediately press RET to get the note appended to the
13703 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13704 find a better place. Then press RET or <left> or <right> in insert the note.
13706 Key Cursor position Note gets inserted
13707 -----------------------------------------------------------------------------
13708 RET buffer-start as level 1 heading at end of file
13709 RET on headline as sublevel of the heading at cursor
13710 RET no heading at cursor position, level taken from context.
13711 Or use prefix arg to specify level manually.
13712 <left> on headline as same level, before current heading
13713 <right> on headline as same level, after current heading
13715 So the fastest way to store the note is to press RET RET to append it to
13716 the default file. This way your current train of thought is not
13717 interrupted, in accordance with the principles of remember.el.
13718 You can also get the fast execution without prompting by using
13719 C-u C-c C-c to exit the remember buffer. See also the variable
13720 `org-remember-store-without-prompt'.
13722 Before being stored away, the function ensures that the text has a
13723 headline, i.e. a first line that starts with a \"*\". If not, a headline
13724 is constructed from the current date and some additional data.
13726 If the variable `org-adapt-indentation' is non-nil, the entire text is
13727 also indented so that it starts in the same column as the headline
13728 \(i.e. after the stars).
13730 See also the variable `org-reverse-note-order'."
13731 (goto-char (point-min))
13732 (while (looking-at "^[ \t]*\n\\|^##.*\n")
13733 (replace-match ""))
13734 (goto-char (point-max))
13735 (beginning-of-line 1)
13736 (while (looking-at "[ \t]*$\\|##.*")
13737 (delete-region (1- (point)) (point-max))
13738 (beginning-of-line 1))
13739 (catch 'quit
13740 (if org-note-abort (throw 'quit nil))
13741 (let* ((txt (buffer-substring (point-min) (point-max)))
13742 (fastp (org-xor (equal current-prefix-arg '(4))
13743 org-remember-store-without-prompt))
13744 (file (cond
13745 (fastp org-default-notes-file)
13746 ((and (eq org-remember-interactive-interface 'refile)
13747 org-refile-targets)
13748 org-default-notes-file)
13749 ((not (and (equal current-prefix-arg '(16))
13750 org-remember-previous-location))
13751 (org-get-org-file))))
13752 (heading org-remember-default-headline)
13753 (visiting (and file (org-find-base-buffer-visiting file)))
13754 (org-startup-folded nil)
13755 (org-startup-align-all-tables nil)
13756 (org-goto-start-pos 1)
13757 spos exitcmd level indent reversed)
13758 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
13759 (setq file (car org-remember-previous-location)
13760 heading (cdr org-remember-previous-location)
13761 fastp t))
13762 (setq current-prefix-arg nil)
13763 (if (string-match "[ \t\n]+\\'" txt)
13764 (setq txt (replace-match "" t t txt)))
13765 ;; Modify text so that it becomes a nice subtree which can be inserted
13766 ;; into an org tree.
13767 (let* ((lines (split-string txt "\n"))
13768 first)
13769 (setq first (car lines) lines (cdr lines))
13770 (if (string-match "^\\*+ " first)
13771 ;; Is already a headline
13772 (setq indent nil)
13773 ;; We need to add a headline: Use time and first buffer line
13774 (setq lines (cons first lines)
13775 first (concat "* " (current-time-string)
13776 " (" (remember-buffer-desc) ")")
13777 indent " "))
13778 (if (and org-adapt-indentation indent)
13779 (setq lines (mapcar
13780 (lambda (x)
13781 (if (string-match "\\S-" x)
13782 (concat indent x) x))
13783 lines)))
13784 (setq txt (concat first "\n"
13785 (mapconcat 'identity lines "\n"))))
13786 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
13787 (setq txt (replace-match "\n\n" t t txt))
13788 (if (string-match "[ \t\n]*\\'" txt)
13789 (setq txt (replace-match "\n" t t txt))))
13790 ;; Put the modified text back into the remember buffer, for refile.
13791 (erase-buffer)
13792 (insert txt)
13793 (goto-char (point-min))
13794 (when (and (eq org-remember-interactive-interface 'refile)
13795 (not fastp))
13796 (org-refile nil (or visiting (find-file-noselect file)))
13797 (throw 'quit t))
13798 ;; Find the file
13799 (if (not visiting) (find-file-noselect file))
13800 (with-current-buffer (or visiting (get-file-buffer file))
13801 (unless (org-mode-p)
13802 (error "Target files for remember notes must be in Org-mode"))
13803 (save-excursion
13804 (save-restriction
13805 (widen)
13806 (and (goto-char (point-min))
13807 (not (re-search-forward "^\\* " nil t))
13808 (insert "\n* " (or heading "Notes") "\n"))
13809 (setq reversed (org-notes-order-reversed-p))
13811 ;; Find the default location
13812 (when (and heading (stringp heading) (string-match "\\S-" heading))
13813 (goto-char (point-min))
13814 (if (re-search-forward
13815 (concat "^\\*+[ \t]+" (regexp-quote heading)
13816 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13817 nil t)
13818 (setq org-goto-start-pos (match-beginning 0))
13819 (when fastp
13820 (goto-char (point-max))
13821 (unless (bolp) (newline))
13822 (insert "* " heading "\n")
13823 (setq org-goto-start-pos (point-at-bol 0)))))
13825 ;; Ask the User for a location, using the appropriate interface
13826 (cond
13827 (fastp (setq spos org-goto-start-pos
13828 exitcmd 'return))
13829 ((eq org-remember-interactive-interface 'outline)
13830 (setq spos (org-get-location (current-buffer)
13831 org-remember-help)
13832 exitcmd (cdr spos)
13833 spos (car spos)))
13834 ((eq org-remember-interactive-interface 'outline-path-completion)
13835 (let ((org-refile-targets '((nil . (:maxlevel . 10))))
13836 (org-refile-use-outline-path t))
13837 (setq spos (org-refile-get-location "Heading: ")
13838 exitcmd 'return
13839 spos (nth 3 spos))))
13840 (t (error "this should not hapen")))
13841 (if (not spos) (throw 'quit nil)) ; return nil to show we did
13842 ; not handle this note
13843 (goto-char spos)
13844 (cond ((org-on-heading-p t)
13845 (org-back-to-heading t)
13846 (setq level (funcall outline-level))
13847 (cond
13848 ((eq exitcmd 'return)
13849 ;; sublevel of current
13850 (setq org-remember-previous-location
13851 (cons (abbreviate-file-name file)
13852 (org-get-heading 'notags)))
13853 (if reversed
13854 (outline-next-heading)
13855 (org-end-of-subtree t)
13856 (if (not (bolp))
13857 (if (looking-at "[ \t]*\n")
13858 (beginning-of-line 2)
13859 (end-of-line 1)
13860 (insert "\n"))))
13861 (bookmark-set "org-remember-last-stored")
13862 (org-paste-subtree (org-get-legal-level level 1) txt))
13863 ((eq exitcmd 'left)
13864 ;; before current
13865 (bookmark-set "org-remember-last-stored")
13866 (org-paste-subtree level txt))
13867 ((eq exitcmd 'right)
13868 ;; after current
13869 (org-end-of-subtree t)
13870 (bookmark-set "org-remember-last-stored")
13871 (org-paste-subtree level txt))
13872 (t (error "This should not happen"))))
13874 ((and (bobp) (not reversed))
13875 ;; Put it at the end, one level below level 1
13876 (save-restriction
13877 (widen)
13878 (goto-char (point-max))
13879 (if (not (bolp)) (newline))
13880 (bookmark-set "org-remember-last-stored")
13881 (org-paste-subtree (org-get-legal-level 1 1) txt)))
13883 ((and (bobp) reversed)
13884 ;; Put it at the start, as level 1
13885 (save-restriction
13886 (widen)
13887 (goto-char (point-min))
13888 (re-search-forward "^\\*+ " nil t)
13889 (beginning-of-line 1)
13890 (bookmark-set "org-remember-last-stored")
13891 (org-paste-subtree 1 txt)))
13893 ;; Put it right there, with automatic level determined by
13894 ;; org-paste-subtree or from prefix arg
13895 (bookmark-set "org-remember-last-stored")
13896 (org-paste-subtree
13897 (if (numberp current-prefix-arg) current-prefix-arg)
13898 txt)))
13899 (when remember-save-after-remembering
13900 (save-buffer)
13901 (if (not visiting) (kill-buffer (current-buffer)))))))))
13903 t) ;; return t to indicate that we took care of this note.
13905 (defun org-get-org-file ()
13906 "Read a filename, with default directory `org-directory'."
13907 (let ((default (or org-default-notes-file remember-data-file)))
13908 (read-file-name (format "File name [%s]: " default)
13909 (file-name-as-directory org-directory)
13910 default)))
13912 (defun org-notes-order-reversed-p ()
13913 "Check if the current file should receive notes in reversed order."
13914 (cond
13915 ((not org-reverse-note-order) nil)
13916 ((eq t org-reverse-note-order) t)
13917 ((not (listp org-reverse-note-order)) nil)
13918 (t (catch 'exit
13919 (let ((all org-reverse-note-order)
13920 entry)
13921 (while (setq entry (pop all))
13922 (if (string-match (car entry) buffer-file-name)
13923 (throw 'exit (cdr entry))))
13924 nil)))))
13926 ;;; Refiling
13928 (defvar org-refile-target-table nil
13929 "The list of refile targets, created by `org-refile'.")
13931 (defvar org-agenda-new-buffers nil
13932 "Buffers created to visit agenda files.")
13934 (defun org-get-refile-targets (&optional default-buffer)
13935 "Produce a table with refile targets."
13936 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
13937 targets txt re files f desc descre)
13938 (with-current-buffer (or default-buffer (current-buffer))
13939 (while (setq entry (pop entries))
13940 (setq files (car entry) desc (cdr entry))
13941 (cond
13942 ((null files) (setq files (list (current-buffer))))
13943 ((eq files 'org-agenda-files)
13944 (setq files (org-agenda-files 'unrestricted)))
13945 ((and (symbolp files) (fboundp files))
13946 (setq files (funcall files)))
13947 ((and (symbolp files) (boundp files))
13948 (setq files (symbol-value files))))
13949 (if (stringp files) (setq files (list files)))
13950 (cond
13951 ((eq (car desc) :tag)
13952 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
13953 ((eq (car desc) :todo)
13954 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
13955 ((eq (car desc) :regexp)
13956 (setq descre (cdr desc)))
13957 ((eq (car desc) :level)
13958 (setq descre (concat "^\\*\\{" (number-to-string
13959 (if org-odd-levels-only
13960 (1- (* 2 (cdr desc)))
13961 (cdr desc)))
13962 "\\}[ \t]")))
13963 ((eq (car desc) :maxlevel)
13964 (setq descre (concat "^\\*\\{1," (number-to-string
13965 (if org-odd-levels-only
13966 (1- (* 2 (cdr desc)))
13967 (cdr desc)))
13968 "\\}[ \t]")))
13969 (t (error "Bad refiling target description %s" desc)))
13970 (while (setq f (pop files))
13971 (save-excursion
13972 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
13973 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
13974 (save-excursion
13975 (save-restriction
13976 (widen)
13977 (goto-char (point-min))
13978 (while (re-search-forward descre nil t)
13979 (goto-char (point-at-bol))
13980 (when (looking-at org-complex-heading-regexp)
13981 (setq txt (match-string 4)
13982 re (concat "^" (regexp-quote
13983 (buffer-substring (match-beginning 1)
13984 (match-end 4)))))
13985 (if (match-end 5) (setq re (concat re "[ \t]+"
13986 (regexp-quote
13987 (match-string 5)))))
13988 (setq re (concat re "[ \t]*$"))
13989 (when org-refile-use-outline-path
13990 (setq txt (mapconcat 'identity
13991 (append
13992 (if (eq org-refile-use-outline-path 'file)
13993 (list (file-name-nondirectory
13994 (buffer-file-name (buffer-base-buffer))))
13995 (if (eq org-refile-use-outline-path 'full-file-path)
13996 (list (buffer-file-name (buffer-base-buffer)))))
13997 (org-get-outline-path)
13998 (list txt))
13999 "/")))
14000 (push (list txt f re (point)) targets))
14001 (goto-char (point-at-eol))))))))
14002 (nreverse targets))))
14004 (defun org-get-outline-path ()
14005 "Return the outline path to the current entry, as a list."
14006 (let (rtn)
14007 (save-excursion
14008 (while (org-up-heading-safe)
14009 (when (looking-at org-complex-heading-regexp)
14010 (push (org-match-string-no-properties 4) rtn)))
14011 rtn)))
14013 (defvar org-refile-history nil
14014 "History for refiling operations.")
14016 (defun org-refile (&optional goto default-buffer)
14017 "Move the entry at point to another heading.
14018 The list of target headings is compiled using the information in
14019 `org-refile-targets', which see. This list is created upon first use, and
14020 you can update it by calling this command with a double prefix (`C-u C-u').
14021 FIXME: Can we find a better way of updating?
14023 At the target location, the entry is filed as a subitem of the target heading.
14024 Depending on `org-reverse-note-order', the new subitem will either be the
14025 first of the last subitem.
14027 With prefix arg GOTO, the command will only visit the target location,
14028 not actually move anything.
14029 With a double prefix `C-c C-c', go to the location where the last refiling
14030 operation has put the subtree.
14032 With a double prefix argument, the command can be used to jump to any
14033 heading in the current buffer."
14034 (interactive "P")
14035 (let* ((cbuf (current-buffer))
14036 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14037 (fname (and filename (file-truename filename)))
14038 pos it nbuf file re level reversed)
14039 (if (equal goto '(16))
14040 (org-refile-goto-last-stored)
14041 (when (setq it (org-refile-get-location
14042 (if goto "Goto: " "Refile to: ") default-buffer))
14043 (setq file (nth 1 it)
14044 re (nth 2 it)
14045 pos (nth 3 it))
14046 (setq nbuf (or (find-buffer-visiting file)
14047 (find-file-noselect file)))
14048 (if goto
14049 (progn
14050 (switch-to-buffer nbuf)
14051 (goto-char pos)
14052 (org-show-context 'org-goto))
14053 (org-copy-special)
14054 (save-excursion
14055 (set-buffer (setq nbuf (or (find-buffer-visiting file)
14056 (find-file-noselect file))))
14057 (setq reversed (org-notes-order-reversed-p))
14058 (save-excursion
14059 (save-restriction
14060 (widen)
14061 (goto-char pos)
14062 (looking-at outline-regexp)
14063 (setq level (org-get-legal-level (funcall outline-level) 1))
14064 (goto-char (or (save-excursion
14065 (if reversed
14066 (outline-next-heading)
14067 (outline-get-next-sibling)))
14068 (point-max)))
14069 (bookmark-set "org-refile-last-stored")
14070 (org-paste-subtree level))))
14071 (org-cut-special)
14072 (message "Entry refiled to \"%s\"" (car it)))))))
14074 (defun org-refile-goto-last-stored ()
14075 "Go to the location where the last refile was stored."
14076 (interactive)
14077 (bookmark-jump "org-refile-last-stored")
14078 (message "This is the location of the last refile"))
14080 (defun org-refile-get-location (&optional prompt default-buffer)
14081 "Prompt the user for a refile location, using PROMPT."
14082 (let ((org-refile-targets org-refile-targets)
14083 (org-refile-use-outline-path org-refile-use-outline-path))
14084 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
14085 (unless org-refile-target-table
14086 (error "No refile targets"))
14087 (let* ((cbuf (current-buffer))
14088 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14089 (fname (and filename (file-truename filename)))
14090 (tbl (mapcar
14091 (lambda (x)
14092 (if (not (equal fname (file-truename (nth 1 x))))
14093 (cons (concat (car x) " (" (file-name-nondirectory
14094 (nth 1 x)) ")")
14095 (cdr x))
14097 org-refile-target-table))
14098 (completion-ignore-case t)
14099 pos it nbuf file re level reversed)
14100 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
14101 tbl)))
14103 ;;;; Dynamic blocks
14105 (defun org-find-dblock (name)
14106 "Find the first dynamic block with name NAME in the buffer.
14107 If not found, stay at current position and return nil."
14108 (let (pos)
14109 (save-excursion
14110 (goto-char (point-min))
14111 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
14112 nil t)
14113 (match-beginning 0))))
14114 (if pos (goto-char pos))
14115 pos))
14117 (defconst org-dblock-start-re
14118 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
14119 "Matches the startline of a dynamic block, with parameters.")
14121 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
14122 "Matches the end of a dyhamic block.")
14124 (defun org-create-dblock (plist)
14125 "Create a dynamic block section, with parameters taken from PLIST.
14126 PLIST must containe a :name entry which is used as name of the block."
14127 (unless (bolp) (newline))
14128 (let ((name (plist-get plist :name)))
14129 (insert "#+BEGIN: " name)
14130 (while plist
14131 (if (eq (car plist) :name)
14132 (setq plist (cddr plist))
14133 (insert " " (prin1-to-string (pop plist)))))
14134 (insert "\n\n#+END:\n")
14135 (beginning-of-line -2)))
14137 (defun org-prepare-dblock ()
14138 "Prepare dynamic block for refresh.
14139 This empties the block, puts the cursor at the insert position and returns
14140 the property list including an extra property :name with the block name."
14141 (unless (looking-at org-dblock-start-re)
14142 (error "Not at a dynamic block"))
14143 (let* ((begdel (1+ (match-end 0)))
14144 (name (org-no-properties (match-string 1)))
14145 (params (append (list :name name)
14146 (read (concat "(" (match-string 3) ")")))))
14147 (unless (re-search-forward org-dblock-end-re nil t)
14148 (error "Dynamic block not terminated"))
14149 (delete-region begdel (match-beginning 0))
14150 (goto-char begdel)
14151 (open-line 1)
14152 params))
14154 (defun org-map-dblocks (&optional command)
14155 "Apply COMMAND to all dynamic blocks in the current buffer.
14156 If COMMAND is not given, use `org-update-dblock'."
14157 (let ((cmd (or command 'org-update-dblock))
14158 pos)
14159 (save-excursion
14160 (goto-char (point-min))
14161 (while (re-search-forward org-dblock-start-re nil t)
14162 (goto-char (setq pos (match-beginning 0)))
14163 (condition-case nil
14164 (funcall cmd)
14165 (error (message "Error during update of dynamic block")))
14166 (goto-char pos)
14167 (unless (re-search-forward org-dblock-end-re nil t)
14168 (error "Dynamic block not terminated"))))))
14170 (defun org-dblock-update (&optional arg)
14171 "User command for updating dynamic blocks.
14172 Update the dynamic block at point. With prefix ARG, update all dynamic
14173 blocks in the buffer."
14174 (interactive "P")
14175 (if arg
14176 (org-update-all-dblocks)
14177 (or (looking-at org-dblock-start-re)
14178 (org-beginning-of-dblock))
14179 (org-update-dblock)))
14181 (defun org-update-dblock ()
14182 "Update the dynamic block at point
14183 This means to empty the block, parse for parameters and then call
14184 the correct writing function."
14185 (save-window-excursion
14186 (let* ((pos (point))
14187 (line (org-current-line))
14188 (params (org-prepare-dblock))
14189 (name (plist-get params :name))
14190 (cmd (intern (concat "org-dblock-write:" name))))
14191 (message "Updating dynamic block `%s' at line %d..." name line)
14192 (funcall cmd params)
14193 (message "Updating dynamic block `%s' at line %d...done" name line)
14194 (goto-char pos))))
14196 (defun org-beginning-of-dblock ()
14197 "Find the beginning of the dynamic block at point.
14198 Error if there is no scuh block at point."
14199 (let ((pos (point))
14200 beg)
14201 (end-of-line 1)
14202 (if (and (re-search-backward org-dblock-start-re nil t)
14203 (setq beg (match-beginning 0))
14204 (re-search-forward org-dblock-end-re nil t)
14205 (> (match-end 0) pos))
14206 (goto-char beg)
14207 (goto-char pos)
14208 (error "Not in a dynamic block"))))
14210 (defun org-update-all-dblocks ()
14211 "Update all dynamic blocks in the buffer.
14212 This function can be used in a hook."
14213 (when (org-mode-p)
14214 (org-map-dblocks 'org-update-dblock)))
14217 ;;;; Completion
14219 (defconst org-additional-option-like-keywords
14220 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14221 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
14222 "BEGIN_EXAMPLE" "END_EXAMPLE"))
14224 (defun org-complete (&optional arg)
14225 "Perform completion on word at point.
14226 At the beginning of a headline, this completes TODO keywords as given in
14227 `org-todo-keywords'.
14228 If the current word is preceded by a backslash, completes the TeX symbols
14229 that are supported for HTML support.
14230 If the current word is preceded by \"#+\", completes special words for
14231 setting file options.
14232 In the line after \"#+STARTUP:, complete valid keywords.\"
14233 At all other locations, this simply calls the value of
14234 `org-completion-fallback-command'."
14235 (interactive "P")
14236 (org-without-partial-completion
14237 (catch 'exit
14238 (let* ((end (point))
14239 (beg1 (save-excursion
14240 (skip-chars-backward (org-re "[:alnum:]_@"))
14241 (point)))
14242 (beg (save-excursion
14243 (skip-chars-backward "a-zA-Z0-9_:$")
14244 (point)))
14245 (confirm (lambda (x) (stringp (car x))))
14246 (searchhead (equal (char-before beg) ?*))
14247 (tag (and (equal (char-before beg1) ?:)
14248 (equal (char-after (point-at-bol)) ?*)))
14249 (prop (and (equal (char-before beg1) ?:)
14250 (not (equal (char-after (point-at-bol)) ?*))))
14251 (texp (equal (char-before beg) ?\\))
14252 (link (equal (char-before beg) ?\[))
14253 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14254 beg)
14255 "#+"))
14256 (startup (string-match "^#\\+STARTUP:.*"
14257 (buffer-substring (point-at-bol) (point))))
14258 (completion-ignore-case opt)
14259 (type nil)
14260 (tbl nil)
14261 (table (cond
14262 (opt
14263 (setq type :opt)
14264 (append
14265 (mapcar
14266 (lambda (x)
14267 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14268 (cons (match-string 2 x) (match-string 1 x)))
14269 (org-split-string (org-get-current-options) "\n"))
14270 (mapcar 'list org-additional-option-like-keywords)))
14271 (startup
14272 (setq type :startup)
14273 org-startup-options)
14274 (link (append org-link-abbrev-alist-local
14275 org-link-abbrev-alist))
14276 (texp
14277 (setq type :tex)
14278 org-html-entities)
14279 ((string-match "\\`\\*+[ \t]+\\'"
14280 (buffer-substring (point-at-bol) beg))
14281 (setq type :todo)
14282 (mapcar 'list org-todo-keywords-1))
14283 (searchhead
14284 (setq type :searchhead)
14285 (save-excursion
14286 (goto-char (point-min))
14287 (while (re-search-forward org-todo-line-regexp nil t)
14288 (push (list
14289 (org-make-org-heading-search-string
14290 (match-string 3) t))
14291 tbl)))
14292 tbl)
14293 (tag (setq type :tag beg beg1)
14294 (or org-tag-alist (org-get-buffer-tags)))
14295 (prop (setq type :prop beg beg1)
14296 (mapcar 'list (org-buffer-property-keys)))
14297 (t (progn
14298 (call-interactively org-completion-fallback-command)
14299 (throw 'exit nil)))))
14300 (pattern (buffer-substring-no-properties beg end))
14301 (completion (try-completion pattern table confirm)))
14302 (cond ((eq completion t)
14303 (if (not (assoc (upcase pattern) table))
14304 (message "Already complete")
14305 (if (equal type :opt)
14306 (insert (substring (cdr (assoc (upcase pattern) table))
14307 (length pattern)))
14308 (if (memq type '(:tag :prop)) (insert ":")))))
14309 ((null completion)
14310 (message "Can't find completion for \"%s\"" pattern)
14311 (ding))
14312 ((not (string= pattern completion))
14313 (delete-region beg end)
14314 (if (string-match " +$" completion)
14315 (setq completion (replace-match "" t t completion)))
14316 (insert completion)
14317 (if (get-buffer-window "*Completions*")
14318 (delete-window (get-buffer-window "*Completions*")))
14319 (if (assoc completion table)
14320 (if (eq type :todo) (insert " ")
14321 (if (memq type '(:tag :prop)) (insert ":"))))
14322 (if (and (equal type :opt) (assoc completion table))
14323 (message "%s" (substitute-command-keys
14324 "Press \\[org-complete] again to insert example settings"))))
14326 (message "Making completion list...")
14327 (let ((list (sort (all-completions pattern table confirm)
14328 'string<)))
14329 (with-output-to-temp-buffer "*Completions*"
14330 (condition-case nil
14331 ;; Protection needed for XEmacs and emacs 21
14332 (display-completion-list list pattern)
14333 (error (display-completion-list list)))))
14334 (message "Making completion list...%s" "done")))))))
14336 ;;;; TODO, DEADLINE, Comments
14338 (defun org-toggle-comment ()
14339 "Change the COMMENT state of an entry."
14340 (interactive)
14341 (save-excursion
14342 (org-back-to-heading)
14343 (let (case-fold-search)
14344 (if (looking-at (concat outline-regexp
14345 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14346 (replace-match "" t t nil 1)
14347 (if (looking-at outline-regexp)
14348 (progn
14349 (goto-char (match-end 0))
14350 (insert org-comment-string " ")))))))
14352 (defvar org-last-todo-state-is-todo nil
14353 "This is non-nil when the last TODO state change led to a TODO state.
14354 If the last change removed the TODO tag or switched to DONE, then
14355 this is nil.")
14357 (defvar org-setting-tags nil) ; dynamically skiped
14359 ;; FIXME: better place
14360 (defun org-property-or-variable-value (var &optional inherit)
14361 "Check if there is a property fixing the value of VAR.
14362 If yes, return this value. If not, return the current value of the variable."
14363 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14364 (if (and prop (stringp prop) (string-match "\\S-" prop))
14365 (read prop)
14366 (symbol-value var))))
14368 (defun org-parse-local-options (string var)
14369 "Parse STRING for startup setting relevant for variable VAR."
14370 (let ((rtn (symbol-value var))
14371 e opts)
14372 (save-match-data
14373 (if (or (not string) (not (string-match "\\S-" string)))
14375 (setq opts (delq nil (mapcar (lambda (x)
14376 (setq e (assoc x org-startup-options))
14377 (if (eq (nth 1 e) var) e nil))
14378 (org-split-string string "[ \t]+"))))
14379 (if (not opts)
14381 (setq rtn nil)
14382 (while (setq e (pop opts))
14383 (if (not (nth 3 e))
14384 (setq rtn (nth 2 e))
14385 (if (not (listp rtn)) (setq rtn nil))
14386 (push (nth 2 e) rtn)))
14387 rtn)))))
14389 (defvar org-blocker-hook nil
14390 "Hook for functions that are allowed to block a state change.
14392 Each function gets as its single argument a property list, see
14393 `org-trigger-hook' for more information about this list.
14395 If any of the functions in this hook returns nil, the state change
14396 is blocked.")
14398 (defvar org-trigger-hook nil
14399 "Hook for functions that are triggered by a state change.
14401 Each function gets as its single argument a property list with at least
14402 the following elements:
14404 (:type type-of-change :position pos-at-entry-start
14405 :from old-state :to new-state)
14407 Depending on the type, more properties may be present.
14409 This mechanism is currently implemented for:
14411 TODO state changes
14412 ------------------
14413 :type todo-state-change
14414 :from previous state (keyword as a string), or nil
14415 :to new state (keyword as a string), or nil")
14418 (defun org-todo (&optional arg)
14419 "Change the TODO state of an item.
14420 The state of an item is given by a keyword at the start of the heading,
14421 like
14422 *** TODO Write paper
14423 *** DONE Call mom
14425 The different keywords are specified in the variable `org-todo-keywords'.
14426 By default the available states are \"TODO\" and \"DONE\".
14427 So for this example: when the item starts with TODO, it is changed to DONE.
14428 When it starts with DONE, the DONE is removed. And when neither TODO nor
14429 DONE are present, add TODO at the beginning of the heading.
14431 With C-u prefix arg, use completion to determine the new state.
14432 With numeric prefix arg, switch to that state.
14434 For calling through lisp, arg is also interpreted in the following way:
14435 'none -> empty state
14436 \"\"(empty string) -> switch to empty state
14437 'done -> switch to DONE
14438 'nextset -> switch to the next set of keywords
14439 'previousset -> switch to the previous set of keywords
14440 \"WAITING\" -> switch to the specified keyword, but only if it
14441 really is a member of `org-todo-keywords'."
14442 (interactive "P")
14443 (save-excursion
14444 (catch 'exit
14445 (org-back-to-heading)
14446 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14447 (or (looking-at (concat " +" org-todo-regexp " *"))
14448 (looking-at " *"))
14449 (let* ((match-data (match-data))
14450 (startpos (point-at-bol))
14451 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14452 (org-log-done (org-parse-local-options logging 'org-log-done))
14453 (org-log-repeat (org-parse-local-options logging 'org-log-repeat))
14454 (this (match-string 1))
14455 (hl-pos (match-beginning 0))
14456 (head (org-get-todo-sequence-head this))
14457 (ass (assoc head org-todo-kwd-alist))
14458 (interpret (nth 1 ass))
14459 (done-word (nth 3 ass))
14460 (final-done-word (nth 4 ass))
14461 (last-state (or this ""))
14462 (completion-ignore-case t)
14463 (member (member this org-todo-keywords-1))
14464 (tail (cdr member))
14465 (state (cond
14466 ((and org-todo-key-trigger
14467 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14468 (and (not arg) org-use-fast-todo-selection
14469 (not (eq org-use-fast-todo-selection 'prefix)))))
14470 ;; Use fast selection
14471 (org-fast-todo-selection))
14472 ((and (equal arg '(4))
14473 (or (not org-use-fast-todo-selection)
14474 (not org-todo-key-trigger)))
14475 ;; Read a state with completion
14476 (completing-read "State: " (mapcar (lambda(x) (list x))
14477 org-todo-keywords-1)
14478 nil t))
14479 ((eq arg 'right)
14480 (if this
14481 (if tail (car tail) nil)
14482 (car org-todo-keywords-1)))
14483 ((eq arg 'left)
14484 (if (equal member org-todo-keywords-1)
14486 (if this
14487 (nth (- (length org-todo-keywords-1) (length tail) 2)
14488 org-todo-keywords-1)
14489 (org-last org-todo-keywords-1))))
14490 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14491 (setq arg nil))) ; hack to fall back to cycling
14492 (arg
14493 ;; user or caller requests a specific state
14494 (cond
14495 ((equal arg "") nil)
14496 ((eq arg 'none) nil)
14497 ((eq arg 'done) (or done-word (car org-done-keywords)))
14498 ((eq arg 'nextset)
14499 (or (car (cdr (member head org-todo-heads)))
14500 (car org-todo-heads)))
14501 ((eq arg 'previousset)
14502 (let ((org-todo-heads (reverse org-todo-heads)))
14503 (or (car (cdr (member head org-todo-heads)))
14504 (car org-todo-heads))))
14505 ((car (member arg org-todo-keywords-1)))
14506 ((nth (1- (prefix-numeric-value arg))
14507 org-todo-keywords-1))))
14508 ((null member) (or head (car org-todo-keywords-1)))
14509 ((equal this final-done-word) nil) ;; -> make empty
14510 ((null tail) nil) ;; -> first entry
14511 ((eq interpret 'sequence)
14512 (car tail))
14513 ((memq interpret '(type priority))
14514 (if (eq this-command last-command)
14515 (car tail)
14516 (if (> (length tail) 0)
14517 (or done-word (car org-done-keywords))
14518 nil)))
14519 (t nil)))
14520 (next (if state (concat " " state " ") " "))
14521 (change-plist (list :type 'todo-state-change :from this :to state
14522 :position startpos))
14523 dostates)
14524 (when org-blocker-hook
14525 (unless (save-excursion
14526 (save-match-data
14527 (run-hook-with-args-until-failure
14528 'org-blocker-hook change-plist)))
14529 (if (interactive-p)
14530 (error "TODO state change from %s to %s blocked" this state)
14531 ;; fail silently
14532 (message "TODO state change from %s to %s blocked" this state)
14533 (throw 'exit nil))))
14534 (store-match-data match-data)
14535 (replace-match next t t)
14536 (unless (pos-visible-in-window-p hl-pos)
14537 (message "TODO state changed to %s" (org-trim next)))
14538 (unless head
14539 (setq head (org-get-todo-sequence-head state)
14540 ass (assoc head org-todo-kwd-alist)
14541 interpret (nth 1 ass)
14542 done-word (nth 3 ass)
14543 final-done-word (nth 4 ass)))
14544 (when (memq arg '(nextset previousset))
14545 (message "Keyword-Set %d/%d: %s"
14546 (- (length org-todo-sets) -1
14547 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14548 (length org-todo-sets)
14549 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14550 (setq org-last-todo-state-is-todo
14551 (not (member state org-done-keywords)))
14552 (when (and org-log-done (not (memq arg '(nextset previousset))))
14553 (setq dostates (and (listp org-log-done) (memq 'state org-log-done)
14554 (or (not org-todo-log-states)
14555 (member state org-todo-log-states))))
14557 (cond
14558 ((and state (member state org-not-done-keywords)
14559 (not (member this org-not-done-keywords)))
14560 ;; This is now a todo state and was not one before
14561 ;; Remove any CLOSED timestamp, and possibly log the state change
14562 (org-add-planning-info nil nil 'closed)
14563 (and dostates (org-add-log-maybe 'state state 'findpos)))
14564 ((and state dostates)
14565 ;; This is a non-nil state, and we need to log it
14566 (org-add-log-maybe 'state state 'findpos))
14567 ((and (member state org-done-keywords)
14568 (not (member this org-done-keywords)))
14569 ;; It is now done, and it was not done before
14570 (org-add-planning-info 'closed (org-current-time))
14571 (org-add-log-maybe 'done state 'findpos))))
14572 ;; Fixup tag positioning
14573 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14574 (run-hooks 'org-after-todo-state-change-hook)
14575 (and (member state org-done-keywords) (org-auto-repeat-maybe))
14576 (if (and arg (not (member state org-done-keywords)))
14577 (setq head (org-get-todo-sequence-head state)))
14578 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14579 ;; Fixup cursor location if close to the keyword
14580 (if (and (outline-on-heading-p)
14581 (not (bolp))
14582 (save-excursion (beginning-of-line 1)
14583 (looking-at org-todo-line-regexp))
14584 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14585 (progn
14586 (goto-char (or (match-end 2) (match-end 1)))
14587 (just-one-space)))
14588 (when org-trigger-hook
14589 (save-excursion
14590 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14592 (defun org-get-todo-sequence-head (kwd)
14593 "Return the head of the TODO sequence to which KWD belongs.
14594 If KWD is not set, check if there is a text property remembering the
14595 right sequence."
14596 (let (p)
14597 (cond
14598 ((not kwd)
14599 (or (get-text-property (point-at-bol) 'org-todo-head)
14600 (progn
14601 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14602 nil (point-at-eol)))
14603 (get-text-property p 'org-todo-head))))
14604 ((not (member kwd org-todo-keywords-1))
14605 (car org-todo-keywords-1))
14606 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14608 (defun org-fast-todo-selection ()
14609 "Fast TODO keyword selection with single keys.
14610 Returns the new TODO keyword, or nil if no state change should occur."
14611 (let* ((fulltable org-todo-key-alist)
14612 (done-keywords org-done-keywords) ;; needed for the faces.
14613 (maxlen (apply 'max (mapcar
14614 (lambda (x)
14615 (if (stringp (car x)) (string-width (car x)) 0))
14616 fulltable)))
14617 (expert nil)
14618 (fwidth (+ maxlen 3 1 3))
14619 (ncol (/ (- (window-width) 4) fwidth))
14620 tg cnt e c tbl
14621 groups ingroup)
14622 (save-window-excursion
14623 (if expert
14624 (set-buffer (get-buffer-create " *Org todo*"))
14625 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14626 (erase-buffer)
14627 (org-set-local 'org-done-keywords done-keywords)
14628 (setq tbl fulltable cnt 0)
14629 (while (setq e (pop tbl))
14630 (cond
14631 ((equal e '(:startgroup))
14632 (push '() groups) (setq ingroup t)
14633 (when (not (= cnt 0))
14634 (setq cnt 0)
14635 (insert "\n"))
14636 (insert "{ "))
14637 ((equal e '(:endgroup))
14638 (setq ingroup nil cnt 0)
14639 (insert "}\n"))
14641 (setq tg (car e) c (cdr e))
14642 (if ingroup (push tg (car groups)))
14643 (setq tg (org-add-props tg nil 'face
14644 (org-get-todo-face tg)))
14645 (if (and (= cnt 0) (not ingroup)) (insert " "))
14646 (insert "[" c "] " tg (make-string
14647 (- fwidth 4 (length tg)) ?\ ))
14648 (when (= (setq cnt (1+ cnt)) ncol)
14649 (insert "\n")
14650 (if ingroup (insert " "))
14651 (setq cnt 0)))))
14652 (insert "\n")
14653 (goto-char (point-min))
14654 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14655 (fit-window-to-buffer))
14656 (message "[a-z..]:Set [SPC]:clear")
14657 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14658 (cond
14659 ((or (= c ?\C-g)
14660 (and (= c ?q) (not (rassoc c fulltable))))
14661 (setq quit-flag t))
14662 ((= c ?\ ) nil)
14663 ((setq e (rassoc c fulltable) tg (car e))
14665 (t (setq quit-flag t))))))
14667 (defun org-get-repeat ()
14668 "Check if tere is a deadline/schedule with repeater in this entry."
14669 (save-match-data
14670 (save-excursion
14671 (org-back-to-heading t)
14672 (if (re-search-forward
14673 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
14674 (match-string 1)))))
14676 (defvar org-last-changed-timestamp)
14677 (defvar org-log-post-message)
14678 (defun org-auto-repeat-maybe ()
14679 "Check if the current headline contains a repeated deadline/schedule.
14680 If yes, set TODO state back to what it was and change the base date
14681 of repeating deadline/scheduled time stamps to new date.
14682 This function should be run in the `org-after-todo-state-change-hook'."
14683 ;; last-state is dynamically scoped into this function
14684 (let* ((repeat (org-get-repeat))
14685 (aa (assoc last-state org-todo-kwd-alist))
14686 (interpret (nth 1 aa))
14687 (head (nth 2 aa))
14688 (done-word (nth 3 aa))
14689 (whata '(("d" . day) ("m" . month) ("y" . year)))
14690 (msg "Entry repeats: ")
14691 (org-log-done)
14692 re type n what ts)
14693 (when repeat
14694 (org-todo (if (eq interpret 'type) last-state head))
14695 (when (and org-log-repeat
14696 (not (memq 'org-add-log-note
14697 (default-value 'post-command-hook))))
14698 ;; Make sure a note is taken
14699 (let ((org-log-done '(done)))
14700 (org-add-log-maybe 'done (or done-word (car org-done-keywords))
14701 'findpos)))
14702 (org-back-to-heading t)
14703 (org-add-planning-info nil nil 'closed)
14704 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
14705 org-deadline-time-regexp "\\)\\|\\("
14706 org-ts-regexp "\\)"))
14707 (while (re-search-forward
14708 re (save-excursion (outline-next-heading) (point)) t)
14709 (setq type (if (match-end 1) org-scheduled-string
14710 (if (match-end 3) org-deadline-string "Plain:"))
14711 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
14712 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
14713 (setq n (string-to-number (match-string 1 ts))
14714 what (match-string 2 ts))
14715 (if (equal what "w") (setq n (* n 7) what "d"))
14716 (org-timestamp-change n (cdr (assoc what whata)))
14717 (setq msg (concat msg type org-last-changed-timestamp " "))))
14718 (setq org-log-post-message msg)
14719 (message "%s" msg))))
14721 (defun org-show-todo-tree (arg)
14722 "Make a compact tree which shows all headlines marked with TODO.
14723 The tree will show the lines where the regexp matches, and all higher
14724 headlines above the match.
14725 With \\[universal-argument] prefix, also show the DONE entries.
14726 With a numeric prefix N, construct a sparse tree for the Nth element
14727 of `org-todo-keywords-1'."
14728 (interactive "P")
14729 (let ((case-fold-search nil)
14730 (kwd-re
14731 (cond ((null arg) org-not-done-regexp)
14732 ((equal arg '(4))
14733 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
14734 (mapcar 'list org-todo-keywords-1))))
14735 (concat "\\("
14736 (mapconcat 'identity (org-split-string kwd "|") "\\|")
14737 "\\)\\>")))
14738 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
14739 (regexp-quote (nth (1- (prefix-numeric-value arg))
14740 org-todo-keywords-1)))
14741 (t (error "Invalid prefix argument: %s" arg)))))
14742 (message "%d TODO entries found"
14743 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
14745 (defun org-deadline (&optional remove)
14746 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
14747 With argument REMOVE, remove any deadline from the item."
14748 (interactive "P")
14749 (if remove
14750 (progn
14751 (org-remove-timestamp-with-keyword org-deadline-string)
14752 (message "Item no longer has a deadline."))
14753 (org-add-planning-info 'deadline nil 'closed)))
14755 (defun org-schedule (&optional remove)
14756 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
14757 With argument REMOVE, remove any scheduling date from the item."
14758 (interactive "P")
14759 (if remove
14760 (progn
14761 (org-remove-timestamp-with-keyword org-scheduled-string)
14762 (message "Item is no longer scheduled."))
14763 (org-add-planning-info 'scheduled nil 'closed)))
14765 (defun org-remove-timestamp-with-keyword (keyword)
14766 "Remove all time stamps with KEYWORD in the current entry."
14767 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
14768 beg)
14769 (save-excursion
14770 (org-back-to-heading t)
14771 (setq beg (point))
14772 (org-end-of-subtree t t)
14773 (while (re-search-backward re beg t)
14774 (replace-match "")
14775 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
14776 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
14778 (defun org-add-planning-info (what &optional time &rest remove)
14779 "Insert new timestamp with keyword in the line directly after the headline.
14780 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
14781 If non is given, the user is prompted for a date.
14782 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
14783 be removed."
14784 (interactive)
14785 (let (org-time-was-given org-end-time-was-given)
14786 (when what (setq time (or time (org-read-date nil 'to-time))))
14787 (when (and org-insert-labeled-timestamps-at-point
14788 (member what '(scheduled deadline)))
14789 (insert
14790 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
14791 (org-insert-time-stamp time org-time-was-given
14792 nil nil nil (list org-end-time-was-given))
14793 (setq what nil))
14794 (save-excursion
14795 (save-restriction
14796 (let (col list elt ts buffer-invisibility-spec)
14797 (org-back-to-heading t)
14798 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
14799 (goto-char (match-end 1))
14800 (setq col (current-column))
14801 (goto-char (match-end 0))
14802 (if (eobp) (insert "\n") (forward-char 1))
14803 (if (and (not (looking-at outline-regexp))
14804 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
14805 "[^\r\n]*"))
14806 (not (equal (match-string 1) org-clock-string)))
14807 (narrow-to-region (match-beginning 0) (match-end 0))
14808 (insert-before-markers "\n")
14809 (backward-char 1)
14810 (narrow-to-region (point) (point))
14811 (indent-to-column col))
14812 ;; Check if we have to remove something.
14813 (setq list (cons what remove))
14814 (while list
14815 (setq elt (pop list))
14816 (goto-char (point-min))
14817 (when (or (and (eq elt 'scheduled)
14818 (re-search-forward org-scheduled-time-regexp nil t))
14819 (and (eq elt 'deadline)
14820 (re-search-forward org-deadline-time-regexp nil t))
14821 (and (eq elt 'closed)
14822 (re-search-forward org-closed-time-regexp nil t)))
14823 (replace-match "")
14824 (if (looking-at "--+<[^>]+>") (replace-match ""))
14825 (if (looking-at " +") (replace-match ""))))
14826 (goto-char (point-max))
14827 (when what
14828 (insert
14829 (if (not (equal (char-before) ?\ )) " " "")
14830 (cond ((eq what 'scheduled) org-scheduled-string)
14831 ((eq what 'deadline) org-deadline-string)
14832 ((eq what 'closed) org-closed-string))
14833 " ")
14834 (setq ts (org-insert-time-stamp
14835 time
14836 (or org-time-was-given
14837 (and (eq what 'closed) org-log-done-with-time))
14838 (eq what 'closed)
14839 nil nil (list org-end-time-was-given)))
14840 (end-of-line 1))
14841 (goto-char (point-min))
14842 (widen)
14843 (if (looking-at "[ \t]+\r?\n")
14844 (replace-match ""))
14845 ts)))))
14847 (defvar org-log-note-marker (make-marker))
14848 (defvar org-log-note-purpose nil)
14849 (defvar org-log-note-state nil)
14850 (defvar org-log-note-window-configuration nil)
14851 (defvar org-log-note-return-to (make-marker))
14852 (defvar org-log-post-message nil
14853 "Message to be displayed after a log note has been stored.
14854 The auto-repeater uses this.")
14856 (defun org-add-log-maybe (&optional purpose state findpos)
14857 "Set up the post command hook to take a note."
14858 (save-excursion
14859 (when (and (listp org-log-done)
14860 (memq purpose org-log-done))
14861 (when findpos
14862 (org-back-to-heading t)
14863 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
14864 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
14865 "[^\r\n]*\\)?"))
14866 (goto-char (match-end 0))
14867 (unless org-log-states-order-reversed
14868 (and (= (char-after) ?\n) (forward-char 1))
14869 (org-skip-over-state-notes)
14870 (skip-chars-backward " \t\n\r")))
14871 (move-marker org-log-note-marker (point))
14872 (setq org-log-note-purpose purpose)
14873 (setq org-log-note-state state)
14874 (add-hook 'post-command-hook 'org-add-log-note 'append))))
14876 (defun org-skip-over-state-notes ()
14877 "Skip past the list of State notes in an entry."
14878 (if (looking-at "\n[ \t]*- State") (forward-char 1))
14879 (while (looking-at "[ \t]*- State")
14880 (condition-case nil
14881 (org-next-item)
14882 (error (org-end-of-item)))))
14884 (defun org-add-log-note (&optional purpose)
14885 "Pop up a window for taking a note, and add this note later at point."
14886 (remove-hook 'post-command-hook 'org-add-log-note)
14887 (setq org-log-note-window-configuration (current-window-configuration))
14888 (delete-other-windows)
14889 (move-marker org-log-note-return-to (point))
14890 (switch-to-buffer (marker-buffer org-log-note-marker))
14891 (goto-char org-log-note-marker)
14892 (org-switch-to-buffer-other-window "*Org Note*")
14893 (erase-buffer)
14894 (let ((org-inhibit-startup t)) (org-mode))
14895 (insert (format "# Insert note for %s.
14896 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
14897 (cond
14898 ((eq org-log-note-purpose 'clock-out) "stopped clock")
14899 ((eq org-log-note-purpose 'done) "closed todo item")
14900 ((eq org-log-note-purpose 'state)
14901 (format "state change to \"%s\"" org-log-note-state))
14902 (t (error "This should not happen")))))
14903 (org-set-local 'org-finish-function 'org-store-log-note))
14905 (defun org-store-log-note ()
14906 "Finish taking a log note, and insert it to where it belongs."
14907 (let ((txt (buffer-string))
14908 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
14909 lines ind)
14910 (kill-buffer (current-buffer))
14911 (while (string-match "\\`#.*\n[ \t\n]*" txt)
14912 (setq txt (replace-match "" t t txt)))
14913 (if (string-match "\\s-+\\'" txt)
14914 (setq txt (replace-match "" t t txt)))
14915 (setq lines (org-split-string txt "\n"))
14916 (when (and note (string-match "\\S-" note))
14917 (setq note
14918 (org-replace-escapes
14919 note
14920 (list (cons "%u" (user-login-name))
14921 (cons "%U" user-full-name)
14922 (cons "%t" (format-time-string
14923 (org-time-stamp-format 'long 'inactive)
14924 (current-time)))
14925 (cons "%s" (if org-log-note-state
14926 (concat "\"" org-log-note-state "\"")
14927 "")))))
14928 (if lines (setq note (concat note " \\\\")))
14929 (push note lines))
14930 (when (or current-prefix-arg org-note-abort) (setq lines nil))
14931 (when lines
14932 (save-excursion
14933 (set-buffer (marker-buffer org-log-note-marker))
14934 (save-excursion
14935 (goto-char org-log-note-marker)
14936 (move-marker org-log-note-marker nil)
14937 (end-of-line 1)
14938 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
14939 (indent-relative nil)
14940 (insert "- " (pop lines))
14941 (org-indent-line-function)
14942 (beginning-of-line 1)
14943 (looking-at "[ \t]*")
14944 (setq ind (concat (match-string 0) " "))
14945 (end-of-line 1)
14946 (while lines (insert "\n" ind (pop lines)))))))
14947 (set-window-configuration org-log-note-window-configuration)
14948 (with-current-buffer (marker-buffer org-log-note-return-to)
14949 (goto-char org-log-note-return-to))
14950 (move-marker org-log-note-return-to nil)
14951 (and org-log-post-message (message "%s" org-log-post-message)))
14953 ;; FIXME: what else would be useful?
14954 ;; - priority
14955 ;; - date
14957 (defun org-sparse-tree (&optional arg)
14958 "Create a sparse tree, prompt for the details.
14959 This command can create sparse trees. You first need to select the type
14960 of match used to create the tree:
14962 t Show entries with a specific TODO keyword.
14963 T Show entries selected by a tags match.
14964 p Enter a property name and its value (both with completion on existing
14965 names/values) and show entries with that property.
14966 r Show entries matching a regular expression
14967 d Show deadlines due within `org-deadline-warning-days'."
14968 (interactive "P")
14969 (let (ans kwd value)
14970 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
14971 (setq ans (read-char-exclusive))
14972 (cond
14973 ((equal ans ?d)
14974 (call-interactively 'org-check-deadlines))
14975 ((equal ans ?b)
14976 (call-interactively 'org-check-before-date))
14977 ((equal ans ?t)
14978 (org-show-todo-tree '(4)))
14979 ((equal ans ?T)
14980 (call-interactively 'org-tags-sparse-tree))
14981 ((member ans '(?p ?P))
14982 (setq kwd (completing-read "Property: "
14983 (mapcar 'list (org-buffer-property-keys))))
14984 (setq value (completing-read "Value: "
14985 (mapcar 'list (org-property-values kwd))))
14986 (unless (string-match "\\`{.*}\\'" value)
14987 (setq value (concat "\"" value "\"")))
14988 (org-tags-sparse-tree arg (concat kwd "=" value)))
14989 ((member ans '(?r ?R ?/))
14990 (call-interactively 'org-occur))
14991 (t (error "No such sparse tree command \"%c\"" ans)))))
14993 (defvar org-occur-highlights nil)
14994 (make-variable-buffer-local 'org-occur-highlights)
14996 (defun org-occur (regexp &optional keep-previous callback)
14997 "Make a compact tree which shows all matches of REGEXP.
14998 The tree will show the lines where the regexp matches, and all higher
14999 headlines above the match. It will also show the heading after the match,
15000 to make sure editing the matching entry is easy.
15001 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
15002 call to `org-occur' will be kept, to allow stacking of calls to this
15003 command.
15004 If CALLBACK is non-nil, it is a function which is called to confirm
15005 that the match should indeed be shown."
15006 (interactive "sRegexp: \nP")
15007 (or keep-previous (org-remove-occur-highlights nil nil t))
15008 (let ((cnt 0))
15009 (save-excursion
15010 (goto-char (point-min))
15011 (if (or (not keep-previous) ; do not want to keep
15012 (not org-occur-highlights)) ; no previous matches
15013 ;; hide everything
15014 (org-overview))
15015 (while (re-search-forward regexp nil t)
15016 (when (or (not callback)
15017 (save-match-data (funcall callback)))
15018 (setq cnt (1+ cnt))
15019 (when org-highlight-sparse-tree-matches
15020 (org-highlight-new-match (match-beginning 0) (match-end 0)))
15021 (org-show-context 'occur-tree))))
15022 (when org-remove-highlights-with-change
15023 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
15024 nil 'local))
15025 (unless org-sparse-tree-open-archived-trees
15026 (org-hide-archived-subtrees (point-min) (point-max)))
15027 (run-hooks 'org-occur-hook)
15028 (if (interactive-p)
15029 (message "%d match(es) for regexp %s" cnt regexp))
15030 cnt))
15032 (defun org-show-context (&optional key)
15033 "Make sure point and context and visible.
15034 How much context is shown depends upon the variables
15035 `org-show-hierarchy-above', `org-show-following-heading'. and
15036 `org-show-siblings'."
15037 (let ((heading-p (org-on-heading-p t))
15038 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
15039 (following-p (org-get-alist-option org-show-following-heading key))
15040 (entry-p (org-get-alist-option org-show-entry-below key))
15041 (siblings-p (org-get-alist-option org-show-siblings key)))
15042 (catch 'exit
15043 ;; Show heading or entry text
15044 (if (and heading-p (not entry-p))
15045 (org-flag-heading nil) ; only show the heading
15046 (and (or entry-p (org-invisible-p) (org-invisible-p2))
15047 (org-show-hidden-entry))) ; show entire entry
15048 (when following-p
15049 ;; Show next sibling, or heading below text
15050 (save-excursion
15051 (and (if heading-p (org-goto-sibling) (outline-next-heading))
15052 (org-flag-heading nil))))
15053 (when siblings-p (org-show-siblings))
15054 (when hierarchy-p
15055 ;; show all higher headings, possibly with siblings
15056 (save-excursion
15057 (while (and (condition-case nil
15058 (progn (org-up-heading-all 1) t)
15059 (error nil))
15060 (not (bobp)))
15061 (org-flag-heading nil)
15062 (when siblings-p (org-show-siblings))))))))
15064 (defun org-reveal (&optional siblings)
15065 "Show current entry, hierarchy above it, and the following headline.
15066 This can be used to show a consistent set of context around locations
15067 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
15068 not t for the search context.
15070 With optional argument SIBLINGS, on each level of the hierarchy all
15071 siblings are shown. This repairs the tree structure to what it would
15072 look like when opened with hierarchical calls to `org-cycle'."
15073 (interactive "P")
15074 (let ((org-show-hierarchy-above t)
15075 (org-show-following-heading t)
15076 (org-show-siblings (if siblings t org-show-siblings)))
15077 (org-show-context nil)))
15079 (defun org-highlight-new-match (beg end)
15080 "Highlight from BEG to END and mark the highlight is an occur headline."
15081 (let ((ov (org-make-overlay beg end)))
15082 (org-overlay-put ov 'face 'secondary-selection)
15083 (push ov org-occur-highlights)))
15085 (defun org-remove-occur-highlights (&optional beg end noremove)
15086 "Remove the occur highlights from the buffer.
15087 BEG and END are ignored. If NOREMOVE is nil, remove this function
15088 from the `before-change-functions' in the current buffer."
15089 (interactive)
15090 (unless org-inhibit-highlight-removal
15091 (mapc 'org-delete-overlay org-occur-highlights)
15092 (setq org-occur-highlights nil)
15093 (unless noremove
15094 (remove-hook 'before-change-functions
15095 'org-remove-occur-highlights 'local))))
15097 ;;;; Priorities
15099 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
15100 "Regular expression matching the priority indicator.")
15102 (defvar org-remove-priority-next-time nil)
15104 (defun org-priority-up ()
15105 "Increase the priority of the current item."
15106 (interactive)
15107 (org-priority 'up))
15109 (defun org-priority-down ()
15110 "Decrease the priority of the current item."
15111 (interactive)
15112 (org-priority 'down))
15114 (defun org-priority (&optional action)
15115 "Change the priority of an item by ARG.
15116 ACTION can be `set', `up', `down', or a character."
15117 (interactive)
15118 (setq action (or action 'set))
15119 (let (current new news have remove)
15120 (save-excursion
15121 (org-back-to-heading)
15122 (if (looking-at org-priority-regexp)
15123 (setq current (string-to-char (match-string 2))
15124 have t)
15125 (setq current org-default-priority))
15126 (cond
15127 ((or (eq action 'set) (integerp action))
15128 (if (integerp action)
15129 (setq new action)
15130 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
15131 (setq new (read-char-exclusive)))
15132 (if (and (= (upcase org-highest-priority) org-highest-priority)
15133 (= (upcase org-lowest-priority) org-lowest-priority))
15134 (setq new (upcase new)))
15135 (cond ((equal new ?\ ) (setq remove t))
15136 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
15137 (error "Priority must be between `%c' and `%c'"
15138 org-highest-priority org-lowest-priority))))
15139 ((eq action 'up)
15140 (if (and (not have) (eq last-command this-command))
15141 (setq new org-lowest-priority)
15142 (setq new (if (and org-priority-start-cycle-with-default (not have))
15143 org-default-priority (1- current)))))
15144 ((eq action 'down)
15145 (if (and (not have) (eq last-command this-command))
15146 (setq new org-highest-priority)
15147 (setq new (if (and org-priority-start-cycle-with-default (not have))
15148 org-default-priority (1+ current)))))
15149 (t (error "Invalid action")))
15150 (if (or (< (upcase new) org-highest-priority)
15151 (> (upcase new) org-lowest-priority))
15152 (setq remove t))
15153 (setq news (format "%c" new))
15154 (if have
15155 (if remove
15156 (replace-match "" t t nil 1)
15157 (replace-match news t t nil 2))
15158 (if remove
15159 (error "No priority cookie found in line")
15160 (looking-at org-todo-line-regexp)
15161 (if (match-end 2)
15162 (progn
15163 (goto-char (match-end 2))
15164 (insert " [#" news "]"))
15165 (goto-char (match-beginning 3))
15166 (insert "[#" news "] ")))))
15167 (org-preserve-lc (org-set-tags nil 'align))
15168 (if remove
15169 (message "Priority removed")
15170 (message "Priority of current item set to %s" news))))
15173 (defun org-get-priority (s)
15174 "Find priority cookie and return priority."
15175 (save-match-data
15176 (if (not (string-match org-priority-regexp s))
15177 (* 1000 (- org-lowest-priority org-default-priority))
15178 (* 1000 (- org-lowest-priority
15179 (string-to-char (match-string 2 s)))))))
15181 ;;;; Tags
15183 (defun org-scan-tags (action matcher &optional todo-only)
15184 "Scan headline tags with inheritance and produce output ACTION.
15185 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
15186 evaluated, testing if a given set of tags qualifies a headline for
15187 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
15188 are included in the output."
15189 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
15190 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
15191 (org-re
15192 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
15193 (props (list 'face nil
15194 'done-face 'org-done
15195 'undone-face nil
15196 'mouse-face 'highlight
15197 'org-not-done-regexp org-not-done-regexp
15198 'org-todo-regexp org-todo-regexp
15199 'keymap org-agenda-keymap
15200 'help-echo
15201 (format "mouse-2 or RET jump to org file %s"
15202 (abbreviate-file-name
15203 (or (buffer-file-name (buffer-base-buffer))
15204 (buffer-name (buffer-base-buffer)))))))
15205 (case-fold-search nil)
15206 lspos
15207 tags tags-list tags-alist (llast 0) rtn level category i txt
15208 todo marker entry priority)
15209 (save-excursion
15210 (goto-char (point-min))
15211 (when (eq action 'sparse-tree)
15212 (org-overview)
15213 (org-remove-occur-highlights))
15214 (while (re-search-forward re nil t)
15215 (catch :skip
15216 (setq todo (if (match-end 1) (match-string 2))
15217 tags (if (match-end 4) (match-string 4)))
15218 (goto-char (setq lspos (1+ (match-beginning 0))))
15219 (setq level (org-reduced-level (funcall outline-level))
15220 category (org-get-category))
15221 (setq i llast llast level)
15222 ;; remove tag lists from same and sublevels
15223 (while (>= i level)
15224 (when (setq entry (assoc i tags-alist))
15225 (setq tags-alist (delete entry tags-alist)))
15226 (setq i (1- i)))
15227 ;; add the nex tags
15228 (when tags
15229 (setq tags (mapcar 'downcase (org-split-string tags ":"))
15230 tags-alist
15231 (cons (cons level tags) tags-alist)))
15232 ;; compile tags for current headline
15233 (setq tags-list
15234 (if org-use-tag-inheritance
15235 (apply 'append (mapcar 'cdr tags-alist))
15236 tags))
15237 (when (and (or (not todo-only) (member todo org-not-done-keywords))
15238 (eval matcher)
15239 (or (not org-agenda-skip-archived-trees)
15240 (not (member org-archive-tag tags-list))))
15241 (and (eq action 'agenda) (org-agenda-skip))
15242 ;; list this headline
15244 (if (eq action 'sparse-tree)
15245 (progn
15246 (and org-highlight-sparse-tree-matches
15247 (org-get-heading) (match-end 0)
15248 (org-highlight-new-match
15249 (match-beginning 0) (match-beginning 1)))
15250 (org-show-context 'tags-tree))
15251 (setq txt (org-format-agenda-item
15253 (concat
15254 (if org-tags-match-list-sublevels
15255 (make-string (1- level) ?.) "")
15256 (org-get-heading))
15257 category tags-list)
15258 priority (org-get-priority txt))
15259 (goto-char lspos)
15260 (setq marker (org-agenda-new-marker))
15261 (org-add-props txt props
15262 'org-marker marker 'org-hd-marker marker 'org-category category
15263 'priority priority 'type "tagsmatch")
15264 (push txt rtn))
15265 ;; if we are to skip sublevels, jump to end of subtree
15266 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15267 (when (and (eq action 'sparse-tree)
15268 (not org-sparse-tree-open-archived-trees))
15269 (org-hide-archived-subtrees (point-min) (point-max)))
15270 (nreverse rtn)))
15272 (defvar todo-only) ;; dynamically scoped
15274 (defun org-tags-sparse-tree (&optional todo-only match)
15275 "Create a sparse tree according to tags string MATCH.
15276 MATCH can contain positive and negative selection of tags, like
15277 \"+WORK+URGENT-WITHBOSS\".
15278 If optional argument TODO_ONLY is non-nil, only select lines that are
15279 also TODO lines."
15280 (interactive "P")
15281 (org-prepare-agenda-buffers (list (current-buffer)))
15282 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15284 (defvar org-cached-props nil)
15285 (defun org-cached-entry-get (pom property)
15286 (if (or (eq t org-use-property-inheritance)
15287 (member property org-use-property-inheritance))
15288 ;; Caching is not possible, check it directly
15289 (org-entry-get pom property 'inherit)
15290 ;; Get all properties, so that we can do complicated checks easily
15291 (cdr (assoc property (or org-cached-props
15292 (setq org-cached-props
15293 (org-entry-properties pom)))))))
15295 (defun org-global-tags-completion-table (&optional files)
15296 "Return the list of all tags in all agenda buffer/files."
15297 (save-excursion
15298 (org-uniquify
15299 (delq nil
15300 (apply 'append
15301 (mapcar
15302 (lambda (file)
15303 (set-buffer (find-file-noselect file))
15304 (append (org-get-buffer-tags)
15305 (mapcar (lambda (x) (if (stringp (car-safe x))
15306 (list (car-safe x)) nil))
15307 org-tag-alist)))
15308 (if (and files (car files))
15309 files
15310 (org-agenda-files))))))))
15312 (defun org-make-tags-matcher (match)
15313 "Create the TAGS//TODO matcher form for the selection string MATCH."
15314 ;; todo-only is scoped dynamically into this function, and the function
15315 ;; may change it it the matcher asksk for it.
15316 (unless match
15317 ;; Get a new match request, with completion
15318 (let ((org-last-tags-completion-table
15319 (org-global-tags-completion-table)))
15320 (setq match (completing-read
15321 "Match: " 'org-tags-completion-function nil nil nil
15322 'org-tags-history))))
15324 ;; Parse the string and create a lisp form
15325 (let ((match0 match)
15326 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]+\"\\)\\|[[:alnum:]_@]+\\)"))
15327 minus tag mm
15328 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15329 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15330 (if (string-match "/+" match)
15331 ;; match contains also a todo-matching request
15332 (progn
15333 (setq tagsmatch (substring match 0 (match-beginning 0))
15334 todomatch (substring match (match-end 0)))
15335 (if (string-match "^!" todomatch)
15336 (setq todo-only t todomatch (substring todomatch 1)))
15337 (if (string-match "^\\s-*$" todomatch)
15338 (setq todomatch nil)))
15339 ;; only matching tags
15340 (setq tagsmatch match todomatch nil))
15342 ;; Make the tags matcher
15343 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15344 (setq tagsmatcher t)
15345 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15346 (while (setq term (pop orterms))
15347 (while (and (equal (substring term -1) "\\") orterms)
15348 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15349 (while (string-match re term)
15350 (setq minus (and (match-end 1)
15351 (equal (match-string 1 term) "-"))
15352 tag (match-string 2 term)
15353 re-p (equal (string-to-char tag) ?{)
15354 level-p (match-end 3)
15355 prop-p (match-end 4)
15356 mm (cond
15357 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15358 (level-p `(= level ,(string-to-number
15359 (match-string 3 term))))
15360 (prop-p
15361 (setq pn (match-string 4 term)
15362 pv (match-string 5 term)
15363 cat-p (equal pn "CATEGORY")
15364 re-p (equal (string-to-char pv) ?{)
15365 pv (substring pv 1 -1))
15366 (if (equal pn "CATEGORY")
15367 (setq gv '(get-text-property (point) 'org-category))
15368 (setq gv `(org-cached-entry-get nil ,pn)))
15369 (if re-p
15370 `(string-match ,pv (or ,gv ""))
15371 `(equal ,pv ,gv)))
15372 (t `(member ,(downcase tag) tags-list)))
15373 mm (if minus (list 'not mm) mm)
15374 term (substring term (match-end 0)))
15375 (push mm tagsmatcher))
15376 (push (if (> (length tagsmatcher) 1)
15377 (cons 'and tagsmatcher)
15378 (car tagsmatcher))
15379 orlist)
15380 (setq tagsmatcher nil))
15381 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15382 (setq tagsmatcher
15383 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15385 ;; Make the todo matcher
15386 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15387 (setq todomatcher t)
15388 (setq orterms (org-split-string todomatch "|") orlist nil)
15389 (while (setq term (pop orterms))
15390 (while (string-match re term)
15391 (setq minus (and (match-end 1)
15392 (equal (match-string 1 term) "-"))
15393 kwd (match-string 2 term)
15394 re-p (equal (string-to-char kwd) ?{)
15395 term (substring term (match-end 0))
15396 mm (if re-p
15397 `(string-match ,(substring kwd 1 -1) todo)
15398 (list 'equal 'todo kwd))
15399 mm (if minus (list 'not mm) mm))
15400 (push mm todomatcher))
15401 (push (if (> (length todomatcher) 1)
15402 (cons 'and todomatcher)
15403 (car todomatcher))
15404 orlist)
15405 (setq todomatcher nil))
15406 (setq todomatcher (if (> (length orlist) 1)
15407 (cons 'or orlist) (car orlist))))
15409 ;; Return the string and lisp forms of the matcher
15410 (setq matcher (if todomatcher
15411 (list 'and tagsmatcher todomatcher)
15412 tagsmatcher))
15413 (cons match0 matcher)))
15415 (defun org-match-any-p (re list)
15416 "Does re match any element of list?"
15417 (setq list (mapcar (lambda (x) (string-match re x)) list))
15418 (delq nil list))
15420 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15421 (defvar org-tags-overlay (org-make-overlay 1 1))
15422 (org-detach-overlay org-tags-overlay)
15424 (defun org-align-tags-here (to-col)
15425 ;; Assumes that this is a headline
15426 (let ((pos (point)) (col (current-column)) tags)
15427 (beginning-of-line 1)
15428 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15429 (< pos (match-beginning 2)))
15430 (progn
15431 (setq tags (match-string 2))
15432 (goto-char (match-beginning 1))
15433 (insert " ")
15434 (delete-region (point) (1+ (match-end 0)))
15435 (backward-char 1)
15436 (move-to-column
15437 (max (1+ (current-column))
15438 (1+ col)
15439 (if (> to-col 0)
15440 to-col
15441 (- (abs to-col) (length tags))))
15443 (insert tags)
15444 (move-to-column (min (current-column) col) t))
15445 (goto-char pos))))
15447 (defun org-set-tags (&optional arg just-align)
15448 "Set the tags for the current headline.
15449 With prefix ARG, realign all tags in headings in the current buffer."
15450 (interactive "P")
15451 (let* ((re (concat "^" outline-regexp))
15452 (current (org-get-tags-string))
15453 (col (current-column))
15454 (org-setting-tags t)
15455 table current-tags inherited-tags ; computed below when needed
15456 tags p0 c0 c1 rpl)
15457 (if arg
15458 (save-excursion
15459 (goto-char (point-min))
15460 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15461 (while (re-search-forward re nil t)
15462 (org-set-tags nil t)
15463 (end-of-line 1)))
15464 (message "All tags realigned to column %d" org-tags-column))
15465 (if just-align
15466 (setq tags current)
15467 ;; Get a new set of tags from the user
15468 (save-excursion
15469 (setq table (or org-tag-alist (org-get-buffer-tags))
15470 org-last-tags-completion-table table
15471 current-tags (org-split-string current ":")
15472 inherited-tags (nreverse
15473 (nthcdr (length current-tags)
15474 (nreverse (org-get-tags-at))))
15475 tags
15476 (if (or (eq t org-use-fast-tag-selection)
15477 (and org-use-fast-tag-selection
15478 (delq nil (mapcar 'cdr table))))
15479 (org-fast-tag-selection
15480 current-tags inherited-tags table
15481 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15482 (let ((org-add-colon-after-tag-completion t))
15483 (org-trim
15484 (org-without-partial-completion
15485 (completing-read "Tags: " 'org-tags-completion-function
15486 nil nil current 'org-tags-history)))))))
15487 (while (string-match "[-+&]+" tags)
15488 ;; No boolean logic, just a list
15489 (setq tags (replace-match ":" t t tags))))
15491 (if (string-match "\\`[\t ]*\\'" tags)
15492 (setq tags "")
15493 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15494 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15496 ;; Insert new tags at the correct column
15497 (beginning-of-line 1)
15498 (cond
15499 ((and (equal current "") (equal tags "")))
15500 ((re-search-forward
15501 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15502 (point-at-eol) t)
15503 (if (equal tags "")
15504 (setq rpl "")
15505 (goto-char (match-beginning 0))
15506 (setq c0 (current-column) p0 (point)
15507 c1 (max (1+ c0) (if (> org-tags-column 0)
15508 org-tags-column
15509 (- (- org-tags-column) (length tags))))
15510 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15511 (replace-match rpl t t)
15512 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
15513 tags)
15514 (t (error "Tags alignment failed")))
15515 (move-to-column col)
15516 (unless just-align
15517 (run-hooks 'org-after-tags-change-hook)))))
15519 (defun org-change-tag-in-region (beg end tag off)
15520 "Add or remove TAG for each entry in the region.
15521 This works in the agenda, and also in an org-mode buffer."
15522 (interactive
15523 (list (region-beginning) (region-end)
15524 (let ((org-last-tags-completion-table
15525 (if (org-mode-p)
15526 (org-get-buffer-tags)
15527 (org-global-tags-completion-table))))
15528 (completing-read
15529 "Tag: " 'org-tags-completion-function nil nil nil
15530 'org-tags-history))
15531 (progn
15532 (message "[s]et or [r]emove? ")
15533 (equal (read-char-exclusive) ?r))))
15534 (if (fboundp 'deactivate-mark) (deactivate-mark))
15535 (let ((agendap (equal major-mode 'org-agenda-mode))
15536 l1 l2 m buf pos newhead (cnt 0))
15537 (goto-char end)
15538 (setq l2 (1- (org-current-line)))
15539 (goto-char beg)
15540 (setq l1 (org-current-line))
15541 (loop for l from l1 to l2 do
15542 (goto-line l)
15543 (setq m (get-text-property (point) 'org-hd-marker))
15544 (when (or (and (org-mode-p) (org-on-heading-p))
15545 (and agendap m))
15546 (setq buf (if agendap (marker-buffer m) (current-buffer))
15547 pos (if agendap m (point)))
15548 (with-current-buffer buf
15549 (save-excursion
15550 (save-restriction
15551 (goto-char pos)
15552 (setq cnt (1+ cnt))
15553 (org-toggle-tag tag (if off 'off 'on))
15554 (setq newhead (org-get-heading)))))
15555 (and agendap (org-agenda-change-all-lines newhead m))))
15556 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15558 (defun org-tags-completion-function (string predicate &optional flag)
15559 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15560 (confirm (lambda (x) (stringp (car x)))))
15561 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15562 (setq s1 (match-string 1 string)
15563 s2 (match-string 2 string))
15564 (setq s1 "" s2 string))
15565 (cond
15566 ((eq flag nil)
15567 ;; try completion
15568 (setq rtn (try-completion s2 ctable confirm))
15569 (if (stringp rtn)
15570 (setq rtn
15571 (concat s1 s2 (substring rtn (length s2))
15572 (if (and org-add-colon-after-tag-completion
15573 (assoc rtn ctable))
15574 ":" ""))))
15575 rtn)
15576 ((eq flag t)
15577 ;; all-completions
15578 (all-completions s2 ctable confirm)
15580 ((eq flag 'lambda)
15581 ;; exact match?
15582 (assoc s2 ctable)))
15585 (defun org-fast-tag-insert (kwd tags face &optional end)
15586 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15587 (insert (format "%-12s" (concat kwd ":"))
15588 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15589 (or end "")))
15591 (defun org-fast-tag-show-exit (flag)
15592 (save-excursion
15593 (goto-line 3)
15594 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15595 (replace-match ""))
15596 (when flag
15597 (end-of-line 1)
15598 (move-to-column (- (window-width) 19) t)
15599 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15601 (defun org-set-current-tags-overlay (current prefix)
15602 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15603 (if (featurep 'xemacs)
15604 (org-overlay-display org-tags-overlay (concat prefix s)
15605 'secondary-selection)
15606 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15607 (org-overlay-display org-tags-overlay (concat prefix s)))))
15609 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15610 "Fast tag selection with single keys.
15611 CURRENT is the current list of tags in the headline, INHERITED is the
15612 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15613 possibly with grouping information. TODO-TABLE is a similar table with
15614 TODO keywords, should these have keys assigned to them.
15615 If the keys are nil, a-z are automatically assigned.
15616 Returns the new tags string, or nil to not change the current settings."
15617 (let* ((fulltable (append table todo-table))
15618 (maxlen (apply 'max (mapcar
15619 (lambda (x)
15620 (if (stringp (car x)) (string-width (car x)) 0))
15621 fulltable)))
15622 (buf (current-buffer))
15623 (expert (eq org-fast-tag-selection-single-key 'expert))
15624 (buffer-tags nil)
15625 (fwidth (+ maxlen 3 1 3))
15626 (ncol (/ (- (window-width) 4) fwidth))
15627 (i-face 'org-done)
15628 (c-face 'org-todo)
15629 tg cnt e c char c1 c2 ntable tbl rtn
15630 ov-start ov-end ov-prefix
15631 (exit-after-next org-fast-tag-selection-single-key)
15632 (done-keywords org-done-keywords)
15633 groups ingroup)
15634 (save-excursion
15635 (beginning-of-line 1)
15636 (if (looking-at
15637 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15638 (setq ov-start (match-beginning 1)
15639 ov-end (match-end 1)
15640 ov-prefix "")
15641 (setq ov-start (1- (point-at-eol))
15642 ov-end (1+ ov-start))
15643 (skip-chars-forward "^\n\r")
15644 (setq ov-prefix
15645 (concat
15646 (buffer-substring (1- (point)) (point))
15647 (if (> (current-column) org-tags-column)
15649 (make-string (- org-tags-column (current-column)) ?\ ))))))
15650 (org-move-overlay org-tags-overlay ov-start ov-end)
15651 (save-window-excursion
15652 (if expert
15653 (set-buffer (get-buffer-create " *Org tags*"))
15654 (delete-other-windows)
15655 (split-window-vertically)
15656 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
15657 (erase-buffer)
15658 (org-set-local 'org-done-keywords done-keywords)
15659 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15660 (org-fast-tag-insert "Current" current c-face "\n\n")
15661 (org-fast-tag-show-exit exit-after-next)
15662 (org-set-current-tags-overlay current ov-prefix)
15663 (setq tbl fulltable char ?a cnt 0)
15664 (while (setq e (pop tbl))
15665 (cond
15666 ((equal e '(:startgroup))
15667 (push '() groups) (setq ingroup t)
15668 (when (not (= cnt 0))
15669 (setq cnt 0)
15670 (insert "\n"))
15671 (insert "{ "))
15672 ((equal e '(:endgroup))
15673 (setq ingroup nil cnt 0)
15674 (insert "}\n"))
15676 (setq tg (car e) c2 nil)
15677 (if (cdr e)
15678 (setq c (cdr e))
15679 ;; automatically assign a character.
15680 (setq c1 (string-to-char
15681 (downcase (substring
15682 tg (if (= (string-to-char tg) ?@) 1 0)))))
15683 (if (or (rassoc c1 ntable) (rassoc c1 table))
15684 (while (or (rassoc char ntable) (rassoc char table))
15685 (setq char (1+ char)))
15686 (setq c2 c1))
15687 (setq c (or c2 char)))
15688 (if ingroup (push tg (car groups)))
15689 (setq tg (org-add-props tg nil 'face
15690 (cond
15691 ((not (assoc tg table))
15692 (org-get-todo-face tg))
15693 ((member tg current) c-face)
15694 ((member tg inherited) i-face)
15695 (t nil))))
15696 (if (and (= cnt 0) (not ingroup)) (insert " "))
15697 (insert "[" c "] " tg (make-string
15698 (- fwidth 4 (length tg)) ?\ ))
15699 (push (cons tg c) ntable)
15700 (when (= (setq cnt (1+ cnt)) ncol)
15701 (insert "\n")
15702 (if ingroup (insert " "))
15703 (setq cnt 0)))))
15704 (setq ntable (nreverse ntable))
15705 (insert "\n")
15706 (goto-char (point-min))
15707 (if (and (not expert) (fboundp 'fit-window-to-buffer))
15708 (fit-window-to-buffer))
15709 (setq rtn
15710 (catch 'exit
15711 (while t
15712 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
15713 (if groups " [!] no groups" " [!]groups")
15714 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15715 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15716 (cond
15717 ((= c ?\r) (throw 'exit t))
15718 ((= c ?!)
15719 (setq groups (not groups))
15720 (goto-char (point-min))
15721 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15722 ((= c ?\C-c)
15723 (if (not expert)
15724 (org-fast-tag-show-exit
15725 (setq exit-after-next (not exit-after-next)))
15726 (setq expert nil)
15727 (delete-other-windows)
15728 (split-window-vertically)
15729 (org-switch-to-buffer-other-window " *Org tags*")
15730 (and (fboundp 'fit-window-to-buffer)
15731 (fit-window-to-buffer))))
15732 ((or (= c ?\C-g)
15733 (and (= c ?q) (not (rassoc c ntable))))
15734 (org-detach-overlay org-tags-overlay)
15735 (setq quit-flag t))
15736 ((= c ?\ )
15737 (setq current nil)
15738 (if exit-after-next (setq exit-after-next 'now)))
15739 ((= c ?\t)
15740 (condition-case nil
15741 (setq tg (completing-read
15742 "Tag: "
15743 (or buffer-tags
15744 (with-current-buffer buf
15745 (org-get-buffer-tags)))))
15746 (quit (setq tg "")))
15747 (when (string-match "\\S-" tg)
15748 (add-to-list 'buffer-tags (list tg))
15749 (if (member tg current)
15750 (setq current (delete tg current))
15751 (push tg current)))
15752 (if exit-after-next (setq exit-after-next 'now)))
15753 ((setq e (rassoc c todo-table) tg (car e))
15754 (with-current-buffer buf
15755 (save-excursion (org-todo tg)))
15756 (if exit-after-next (setq exit-after-next 'now)))
15757 ((setq e (rassoc c ntable) tg (car e))
15758 (if (member tg current)
15759 (setq current (delete tg current))
15760 (loop for g in groups do
15761 (if (member tg g)
15762 (mapc (lambda (x)
15763 (setq current (delete x current)))
15764 g)))
15765 (push tg current))
15766 (if exit-after-next (setq exit-after-next 'now))))
15768 ;; Create a sorted list
15769 (setq current
15770 (sort current
15771 (lambda (a b)
15772 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15773 (if (eq exit-after-next 'now) (throw 'exit t))
15774 (goto-char (point-min))
15775 (beginning-of-line 2)
15776 (delete-region (point) (point-at-eol))
15777 (org-fast-tag-insert "Current" current c-face)
15778 (org-set-current-tags-overlay current ov-prefix)
15779 (while (re-search-forward
15780 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
15781 (setq tg (match-string 1))
15782 (add-text-properties
15783 (match-beginning 1) (match-end 1)
15784 (list 'face
15785 (cond
15786 ((member tg current) c-face)
15787 ((member tg inherited) i-face)
15788 (t (get-text-property (match-beginning 1) 'face))))))
15789 (goto-char (point-min)))))
15790 (org-detach-overlay org-tags-overlay)
15791 (if rtn
15792 (mapconcat 'identity current ":")
15793 nil))))
15795 (defun org-get-tags-string ()
15796 "Get the TAGS string in the current headline."
15797 (unless (org-on-heading-p t)
15798 (error "Not on a heading"))
15799 (save-excursion
15800 (beginning-of-line 1)
15801 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15802 (org-match-string-no-properties 1)
15803 "")))
15805 (defun org-get-tags ()
15806 "Get the list of tags specified in the current headline."
15807 (org-split-string (org-get-tags-string) ":"))
15809 (defun org-get-buffer-tags ()
15810 "Get a table of all tags used in the buffer, for completion."
15811 (let (tags)
15812 (save-excursion
15813 (goto-char (point-min))
15814 (while (re-search-forward
15815 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
15816 (when (equal (char-after (point-at-bol 0)) ?*)
15817 (mapc (lambda (x) (add-to-list 'tags x))
15818 (org-split-string (org-match-string-no-properties 1) ":")))))
15819 (mapcar 'list tags)))
15822 ;;;; Properties
15824 ;;; Setting and retrieving properties
15826 (defconst org-special-properties
15827 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
15828 "TIMESTAMP" "TIMESTAMP_IA")
15829 "The special properties valid in Org-mode.
15831 These are properties that are not defined in the property drawer,
15832 but in some other way.")
15834 (defconst org-default-properties
15835 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
15836 "LOCATION" "LOGGING" "COLUMNS")
15837 "Some properties that are used by Org-mode for various purposes.
15838 Being in this list makes sure that they are offered for completion.")
15840 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15841 "Regular expression matching the first line of a property drawer.")
15843 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15844 "Regular expression matching the first line of a property drawer.")
15846 (defun org-property-action ()
15847 "Do an action on properties."
15848 (interactive)
15849 (let (c)
15850 (org-at-property-p)
15851 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15852 (setq c (read-char-exclusive))
15853 (cond
15854 ((equal c ?s)
15855 (call-interactively 'org-set-property))
15856 ((equal c ?d)
15857 (call-interactively 'org-delete-property))
15858 ((equal c ?D)
15859 (call-interactively 'org-delete-property-globally))
15860 ((equal c ?c)
15861 (call-interactively 'org-compute-property-at-point))
15862 (t (error "No such property action %c" c)))))
15864 (defun org-at-property-p ()
15865 "Is the cursor in a property line?"
15866 ;; FIXME: Does not check if we are actually in the drawer.
15867 ;; FIXME: also returns true on any drawers.....
15868 ;; This is used by C-c C-c for property action.
15869 (save-excursion
15870 (beginning-of-line 1)
15871 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
15873 (defmacro org-with-point-at (pom &rest body)
15874 "Move to buffer and point of point-or-marker POM for the duration of BODY."
15875 (declare (indent 1) (debug t))
15876 `(save-excursion
15877 (if (markerp pom) (set-buffer (marker-buffer pom)))
15878 (save-excursion
15879 (goto-char (or pom (point)))
15880 ,@body)))
15882 (defun org-get-property-block (&optional beg end force)
15883 "Return the (beg . end) range of the body of the property drawer.
15884 BEG and END can be beginning and end of subtree, if not given
15885 they will be found.
15886 If the drawer does not exist and FORCE is non-nil, create the drawer."
15887 (catch 'exit
15888 (save-excursion
15889 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
15890 (end (or end (progn (outline-next-heading) (point)))))
15891 (goto-char beg)
15892 (if (re-search-forward org-property-start-re end t)
15893 (setq beg (1+ (match-end 0)))
15894 (if force
15895 (save-excursion
15896 (org-insert-property-drawer)
15897 (setq end (progn (outline-next-heading) (point))))
15898 (throw 'exit nil))
15899 (goto-char beg)
15900 (if (re-search-forward org-property-start-re end t)
15901 (setq beg (1+ (match-end 0)))))
15902 (if (re-search-forward org-property-end-re end t)
15903 (setq end (match-beginning 0))
15904 (or force (throw 'exit nil))
15905 (goto-char beg)
15906 (setq end beg)
15907 (org-indent-line-function)
15908 (insert ":END:\n"))
15909 (cons beg end)))))
15911 (defun org-entry-properties (&optional pom which)
15912 "Get all properties of the entry at point-or-marker POM.
15913 This includes the TODO keyword, the tags, time strings for deadline,
15914 scheduled, and clocking, and any additional properties defined in the
15915 entry. The return value is an alist, keys may occur multiple times
15916 if the property key was used several times.
15917 POM may also be nil, in which case the current entry is used.
15918 If WHICH is nil or `all', get all properties. If WHICH is
15919 `special' or `standard', only get that subclass."
15920 (setq which (or which 'all))
15921 (org-with-point-at pom
15922 (let ((clockstr (substring org-clock-string 0 -1))
15923 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
15924 beg end range props sum-props key value string clocksum)
15925 (save-excursion
15926 (when (condition-case nil (org-back-to-heading t) (error nil))
15927 (setq beg (point))
15928 (setq sum-props (get-text-property (point) 'org-summaries))
15929 (setq clocksum (get-text-property (point) :org-clock-minutes))
15930 (outline-next-heading)
15931 (setq end (point))
15932 (when (memq which '(all special))
15933 ;; Get the special properties, like TODO and tags
15934 (goto-char beg)
15935 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15936 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15937 (when (looking-at org-priority-regexp)
15938 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15939 (when (and (setq value (org-get-tags-string))
15940 (string-match "\\S-" value))
15941 (push (cons "TAGS" value) props))
15942 (when (setq value (org-get-tags-at))
15943 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
15944 props))
15945 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15946 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
15947 string (if (equal key clockstr)
15948 (org-no-properties
15949 (org-trim
15950 (buffer-substring
15951 (match-beginning 3) (goto-char (point-at-eol)))))
15952 (substring (org-match-string-no-properties 3) 1 -1)))
15953 (unless key
15954 (if (= (char-after (match-beginning 3)) ?\[)
15955 (setq key "TIMESTAMP_IA")
15956 (setq key "TIMESTAMP")))
15957 (when (or (equal key clockstr) (not (assoc key props)))
15958 (push (cons key string) props)))
15962 (when (memq which '(all standard))
15963 ;; Get the standard properties, like :PORP: ...
15964 (setq range (org-get-property-block beg end))
15965 (when range
15966 (goto-char (car range))
15967 (while (re-search-forward
15968 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15969 (cdr range) t)
15970 (setq key (org-match-string-no-properties 1)
15971 value (org-trim (or (org-match-string-no-properties 2) "")))
15972 (unless (member key excluded)
15973 (push (cons key (or value "")) props)))))
15974 (if clocksum
15975 (push (cons "CLOCKSUM"
15976 (org-column-number-to-string (/ (float clocksum) 60.)
15977 'add_times))
15978 props))
15979 (append sum-props (nreverse props)))))))
15981 (defun org-entry-get (pom property &optional inherit)
15982 "Get value of PROPERTY for entry at point-or-marker POM.
15983 If INHERIT is non-nil and the entry does not have the property,
15984 then also check higher levels of the hierarchy.
15985 If the property is present but empty, the return value is the empty string.
15986 If the property is not present at all, nil is returned."
15987 (org-with-point-at pom
15988 (if inherit
15989 (org-entry-get-with-inheritance property)
15990 (if (member property org-special-properties)
15991 ;; We need a special property. Use brute force, get all properties.
15992 (cdr (assoc property (org-entry-properties nil 'special)))
15993 (let ((range (org-get-property-block)))
15994 (if (and range
15995 (goto-char (car range))
15996 (re-search-forward
15997 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
15998 (cdr range) t))
15999 ;; Found the property, return it.
16000 (if (match-end 1)
16001 (org-match-string-no-properties 1)
16002 "")))))))
16004 (defun org-entry-delete (pom property)
16005 "Delete the property PROPERTY from entry at point-or-marker POM."
16006 (org-with-point-at pom
16007 (if (member property org-special-properties)
16008 nil ; cannot delete these properties.
16009 (let ((range (org-get-property-block)))
16010 (if (and range
16011 (goto-char (car range))
16012 (re-search-forward
16013 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
16014 (cdr range) t))
16015 (progn
16016 (delete-region (match-beginning 0) (1+ (point-at-eol)))
16018 nil)))))
16020 ;; Multi-values properties are properties that contain multiple values
16021 ;; These values are assumed to be single words, separated by whitespace.
16022 (defun org-entry-add-to-multivalued-property (pom property value)
16023 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16024 (let* ((old (org-entry-get pom property))
16025 (values (and old (org-split-string old "[ \t]"))))
16026 (unless (member value values)
16027 (setq values (cons value values))
16028 (org-entry-put pom property
16029 (mapconcat 'identity values " ")))))
16031 (defun org-entry-remove-from-multivalued-property (pom property value)
16032 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16033 (let* ((old (org-entry-get pom property))
16034 (values (and old (org-split-string old "[ \t]"))))
16035 (when (member value values)
16036 (setq values (delete value values))
16037 (org-entry-put pom property
16038 (mapconcat 'identity values " ")))))
16040 (defun org-entry-member-in-multivalued-property (pom property value)
16041 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16042 (let* ((old (org-entry-get pom property))
16043 (values (and old (org-split-string old "[ \t]"))))
16044 (member value values)))
16046 (defvar org-entry-property-inherited-from (make-marker))
16048 (defun org-entry-get-with-inheritance (property)
16049 "Get entry property, and search higher levels if not present."
16050 (let (tmp)
16051 (save-excursion
16052 (save-restriction
16053 (widen)
16054 (catch 'ex
16055 (while t
16056 (when (setq tmp (org-entry-get nil property))
16057 (org-back-to-heading t)
16058 (move-marker org-entry-property-inherited-from (point))
16059 (throw 'ex tmp))
16060 (or (org-up-heading-safe) (throw 'ex nil)))))
16061 (or tmp (cdr (assoc property org-local-properties))
16062 (cdr (assoc property org-global-properties))))))
16064 (defun org-entry-put (pom property value)
16065 "Set PROPERTY to VALUE for entry at point-or-marker POM."
16066 (org-with-point-at pom
16067 (org-back-to-heading t)
16068 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
16069 range)
16070 (cond
16071 ((equal property "TODO")
16072 (when (and (stringp value) (string-match "\\S-" value)
16073 (not (member value org-todo-keywords-1)))
16074 (error "\"%s\" is not a valid TODO state" value))
16075 (if (or (not value)
16076 (not (string-match "\\S-" value)))
16077 (setq value 'none))
16078 (org-todo value)
16079 (org-set-tags nil 'align))
16080 ((equal property "PRIORITY")
16081 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
16082 (string-to-char value) ?\ ))
16083 (org-set-tags nil 'align))
16084 ((equal property "SCHEDULED")
16085 (if (re-search-forward org-scheduled-time-regexp end t)
16086 (cond
16087 ((eq value 'earlier) (org-timestamp-change -1 'day))
16088 ((eq value 'later) (org-timestamp-change 1 'day))
16089 (t (call-interactively 'org-schedule)))
16090 (call-interactively 'org-schedule)))
16091 ((equal property "DEADLINE")
16092 (if (re-search-forward org-deadline-time-regexp end t)
16093 (cond
16094 ((eq value 'earlier) (org-timestamp-change -1 'day))
16095 ((eq value 'later) (org-timestamp-change 1 'day))
16096 (t (call-interactively 'org-deadline)))
16097 (call-interactively 'org-deadline)))
16098 ((member property org-special-properties)
16099 (error "The %s property can not yet be set with `org-entry-put'"
16100 property))
16101 (t ; a non-special property
16102 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
16103 (setq range (org-get-property-block beg end 'force))
16104 (goto-char (car range))
16105 (if (re-search-forward
16106 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
16107 (progn
16108 (delete-region (match-beginning 1) (match-end 1))
16109 (goto-char (match-beginning 1)))
16110 (goto-char (cdr range))
16111 (insert "\n")
16112 (backward-char 1)
16113 (org-indent-line-function)
16114 (insert ":" property ":"))
16115 (and value (insert " " value))
16116 (org-indent-line-function)))))))
16118 (defun org-buffer-property-keys (&optional include-specials include-defaults)
16119 "Get all property keys in the current buffer.
16120 With INCLUDE-SPECIALS, also list the special properties that relect things
16121 like tags and TODO state.
16122 With INCLUDE-DEFAULTS, also include properties that has special meaning
16123 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING."
16124 (let (rtn range)
16125 (save-excursion
16126 (save-restriction
16127 (widen)
16128 (goto-char (point-min))
16129 (while (re-search-forward org-property-start-re nil t)
16130 (setq range (org-get-property-block))
16131 (goto-char (car range))
16132 (while (re-search-forward
16133 (org-re "^[ \t]*:\\([[:alnum:]_-]+\\):")
16134 (cdr range) t)
16135 (add-to-list 'rtn (org-match-string-no-properties 1)))
16136 (outline-next-heading))))
16138 (when include-specials
16139 (setq rtn (append org-special-properties rtn)))
16141 (when include-defaults
16142 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
16144 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
16146 (defun org-property-values (key)
16147 "Return a list of all values of property KEY."
16148 (save-excursion
16149 (save-restriction
16150 (widen)
16151 (goto-char (point-min))
16152 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
16153 values)
16154 (while (re-search-forward re nil t)
16155 (add-to-list 'values (org-trim (match-string 1))))
16156 (delete "" values)))))
16158 (defun org-insert-property-drawer ()
16159 "Insert a property drawer into the current entry."
16160 (interactive)
16161 (org-back-to-heading t)
16162 (looking-at outline-regexp)
16163 (let ((indent (- (match-end 0)(match-beginning 0)))
16164 (beg (point))
16165 (re (concat "^[ \t]*" org-keyword-time-regexp))
16166 end hiddenp)
16167 (outline-next-heading)
16168 (setq end (point))
16169 (goto-char beg)
16170 (while (re-search-forward re end t))
16171 (setq hiddenp (org-invisible-p))
16172 (end-of-line 1)
16173 (and (equal (char-after) ?\n) (forward-char 1))
16174 (org-skip-over-state-notes)
16175 (skip-chars-backward " \t\n\r")
16176 (if (eq (char-before) ?*) (forward-char 1))
16177 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
16178 (beginning-of-line 0)
16179 (indent-to-column indent)
16180 (beginning-of-line 2)
16181 (indent-to-column indent)
16182 (beginning-of-line 0)
16183 (if hiddenp
16184 (save-excursion
16185 (org-back-to-heading t)
16186 (hide-entry))
16187 (org-flag-drawer t))))
16189 (defun org-set-property (property value)
16190 "In the current entry, set PROPERTY to VALUE.
16191 When called interactively, this will prompt for a property name, offering
16192 completion on existing and default properties. And then it will prompt
16193 for a value, offering competion either on allowed values (via an inherited
16194 xxx_ALL property) or on existing values in other instances of this property
16195 in the current file."
16196 (interactive
16197 (let* ((prop (completing-read
16198 "Property: " (mapcar 'list (org-buffer-property-keys nil t))))
16199 (cur (org-entry-get nil prop))
16200 (allowed (org-property-get-allowed-values nil prop 'table))
16201 (existing (mapcar 'list (org-property-values prop)))
16202 (val (if allowed
16203 (completing-read "Value: " allowed nil 'req-match)
16204 (completing-read
16205 (concat "Value" (if (and cur (string-match "\\S-" cur))
16206 (concat "[" cur "]") "")
16207 ": ")
16208 existing nil nil "" nil cur))))
16209 (list prop (if (equal val "") cur val))))
16210 (unless (equal (org-entry-get nil property) value)
16211 (org-entry-put nil property value)))
16213 (defun org-delete-property (property)
16214 "In the current entry, delete PROPERTY."
16215 (interactive
16216 (let* ((prop (completing-read
16217 "Property: " (org-entry-properties nil 'standard))))
16218 (list prop)))
16219 (message "Property %s %s" property
16220 (if (org-entry-delete nil property)
16221 "deleted"
16222 "was not present in the entry")))
16224 (defun org-delete-property-globally (property)
16225 "Remove PROPERTY globally, from all entries."
16226 (interactive
16227 (let* ((prop (completing-read
16228 "Globally remove property: "
16229 (mapcar 'list (org-buffer-property-keys)))))
16230 (list prop)))
16231 (save-excursion
16232 (save-restriction
16233 (widen)
16234 (goto-char (point-min))
16235 (let ((cnt 0))
16236 (while (re-search-forward
16237 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16238 nil t)
16239 (setq cnt (1+ cnt))
16240 (replace-match ""))
16241 (message "Property \"%s\" removed from %d entries" property cnt)))))
16243 (defvar org-columns-current-fmt-compiled) ; defined below
16245 (defun org-compute-property-at-point ()
16246 "Compute the property at point.
16247 This looks for an enclosing column format, extracts the operator and
16248 then applies it to the proerty in the column format's scope."
16249 (interactive)
16250 (unless (org-at-property-p)
16251 (error "Not at a property"))
16252 (let ((prop (org-match-string-no-properties 2)))
16253 (org-columns-get-format-and-top-level)
16254 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16255 (error "No operator defined for property %s" prop))
16256 (org-columns-compute prop)))
16258 (defun org-property-get-allowed-values (pom property &optional table)
16259 "Get allowed values for the property PROPERTY.
16260 When TABLE is non-nil, return an alist that can directly be used for
16261 completion."
16262 (let (vals)
16263 (cond
16264 ((equal property "TODO")
16265 (setq vals (org-with-point-at pom
16266 (append org-todo-keywords-1 '("")))))
16267 ((equal property "PRIORITY")
16268 (let ((n org-lowest-priority))
16269 (while (>= n org-highest-priority)
16270 (push (char-to-string n) vals)
16271 (setq n (1- n)))))
16272 ((member property org-special-properties))
16274 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16276 (when (and vals (string-match "\\S-" vals))
16277 (setq vals (car (read-from-string (concat "(" vals ")"))))
16278 (setq vals (mapcar (lambda (x)
16279 (cond ((stringp x) x)
16280 ((numberp x) (number-to-string x))
16281 ((symbolp x) (symbol-name x))
16282 (t "???")))
16283 vals)))))
16284 (if table (mapcar 'list vals) vals)))
16286 (defun org-property-previous-allowed-value (&optional previous)
16287 "Switch to the next allowed value for this property."
16288 (interactive)
16289 (org-property-next-allowed-value t))
16291 (defun org-property-next-allowed-value (&optional previous)
16292 "Switch to the next allowed value for this property."
16293 (interactive)
16294 (unless (org-at-property-p)
16295 (error "Not at a property"))
16296 (let* ((key (match-string 2))
16297 (value (match-string 3))
16298 (allowed (or (org-property-get-allowed-values (point) key)
16299 (and (member value '("[ ]" "[-]" "[X]"))
16300 '("[ ]" "[X]"))))
16301 nval)
16302 (unless allowed
16303 (error "Allowed values for this property have not been defined"))
16304 (if previous (setq allowed (reverse allowed)))
16305 (if (member value allowed)
16306 (setq nval (car (cdr (member value allowed)))))
16307 (setq nval (or nval (car allowed)))
16308 (if (equal nval value)
16309 (error "Only one allowed value for this property"))
16310 (org-at-property-p)
16311 (replace-match (concat " :" key ": " nval) t t)
16312 (org-indent-line-function)
16313 (beginning-of-line 1)
16314 (skip-chars-forward " \t")))
16316 (defun org-find-entry-with-id (ident)
16317 "Locate the entry that contains the ID property with exact value IDENT.
16318 IDENT can be a string, a symbol or a number, this function will search for
16319 the string representation of it.
16320 Return the position where this entry starts, or nil if there is no such entry."
16321 (let ((id (cond
16322 ((stringp ident) ident)
16323 ((symbol-name ident) (symbol-name ident))
16324 ((numberp ident) (number-to-string ident))
16325 (t (error "IDENT %s must be a string, symbol or number" ident))))
16326 (case-fold-search nil))
16327 (save-excursion
16328 (save-restriction
16329 (goto-char (point-min))
16330 (when (re-search-forward
16331 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16332 nil t)
16333 (org-back-to-heading)
16334 (point))))))
16336 ;;; Column View
16338 (defvar org-columns-overlays nil
16339 "Holds the list of current column overlays.")
16341 (defvar org-columns-current-fmt nil
16342 "Local variable, holds the currently active column format.")
16343 (defvar org-columns-current-fmt-compiled nil
16344 "Local variable, holds the currently active column format.
16345 This is the compiled version of the format.")
16346 (defvar org-columns-current-widths nil
16347 "Loval variable, holds the currently widths of fields.")
16348 (defvar org-columns-current-maxwidths nil
16349 "Loval variable, holds the currently active maximum column widths.")
16350 (defvar org-columns-begin-marker (make-marker)
16351 "Points to the position where last a column creation command was called.")
16352 (defvar org-columns-top-level-marker (make-marker)
16353 "Points to the position where current columns region starts.")
16355 (defvar org-columns-map (make-sparse-keymap)
16356 "The keymap valid in column display.")
16358 (defun org-columns-content ()
16359 "Switch to contents view while in columns view."
16360 (interactive)
16361 (org-overview)
16362 (org-content))
16364 (org-defkey org-columns-map "c" 'org-columns-content)
16365 (org-defkey org-columns-map "o" 'org-overview)
16366 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16367 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16368 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16369 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16370 (org-defkey org-columns-map "v" 'org-columns-show-value)
16371 (org-defkey org-columns-map "q" 'org-columns-quit)
16372 (org-defkey org-columns-map "r" 'org-columns-redo)
16373 (org-defkey org-columns-map "g" 'org-columns-redo)
16374 (org-defkey org-columns-map [left] 'backward-char)
16375 (org-defkey org-columns-map "\M-b" 'backward-char)
16376 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16377 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16378 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16379 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16380 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16381 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16382 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16383 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16384 (org-defkey org-columns-map "<" 'org-columns-narrow)
16385 (org-defkey org-columns-map ">" 'org-columns-widen)
16386 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16387 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16388 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16389 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16391 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16392 '("Column"
16393 ["Edit property" org-columns-edit-value t]
16394 ["Next allowed value" org-columns-next-allowed-value t]
16395 ["Previous allowed value" org-columns-previous-allowed-value t]
16396 ["Show full value" org-columns-show-value t]
16397 ["Edit allowed values" org-columns-edit-allowed t]
16398 "--"
16399 ["Edit column attributes" org-columns-edit-attributes t]
16400 ["Increase column width" org-columns-widen t]
16401 ["Decrease column width" org-columns-narrow t]
16402 "--"
16403 ["Move column right" org-columns-move-right t]
16404 ["Move column left" org-columns-move-left t]
16405 ["Add column" org-columns-new t]
16406 ["Delete column" org-columns-delete t]
16407 "--"
16408 ["CONTENTS" org-columns-content t]
16409 ["OVERVIEW" org-overview t]
16410 ["Refresh columns display" org-columns-redo t]
16411 "--"
16412 ["Open link" org-columns-open-link t]
16413 "--"
16414 ["Quit" org-columns-quit t]))
16416 (defun org-columns-new-overlay (beg end &optional string face)
16417 "Create a new column overlay and add it to the list."
16418 (let ((ov (org-make-overlay beg end)))
16419 (org-overlay-put ov 'face (or face 'secondary-selection))
16420 (org-overlay-display ov string face)
16421 (push ov org-columns-overlays)
16422 ov))
16424 (defun org-columns-display-here (&optional props)
16425 "Overlay the current line with column display."
16426 (interactive)
16427 (let* ((fmt org-columns-current-fmt-compiled)
16428 (beg (point-at-bol))
16429 (level-face (save-excursion
16430 (beginning-of-line 1)
16431 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16432 (org-get-level-face 2))))
16433 (color (list :foreground
16434 (face-attribute (or level-face 'default) :foreground)))
16435 props pom property ass width f string ov column val modval)
16436 ;; Check if the entry is in another buffer.
16437 (unless props
16438 (if (eq major-mode 'org-agenda-mode)
16439 (setq pom (or (get-text-property (point) 'org-hd-marker)
16440 (get-text-property (point) 'org-marker))
16441 props (if pom (org-entry-properties pom) nil))
16442 (setq props (org-entry-properties nil))))
16443 ;; Walk the format
16444 (while (setq column (pop fmt))
16445 (setq property (car column)
16446 ass (if (equal property "ITEM")
16447 (cons "ITEM"
16448 (save-match-data
16449 (org-no-properties
16450 (org-remove-tabs
16451 (buffer-substring-no-properties
16452 (point-at-bol) (point-at-eol))))))
16453 (assoc property props))
16454 width (or (cdr (assoc property org-columns-current-maxwidths))
16455 (nth 2 column)
16456 (length property))
16457 f (format "%%-%d.%ds | " width width)
16458 val (or (cdr ass) "")
16459 modval (if (equal property "ITEM")
16460 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16461 string (format f (or modval val)))
16462 ;; Create the overlay
16463 (org-unmodified
16464 (setq ov (org-columns-new-overlay
16465 beg (setq beg (1+ beg)) string
16466 (list color 'org-column)))
16467 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16468 (org-overlay-put ov 'keymap org-columns-map)
16469 (org-overlay-put ov 'org-columns-key property)
16470 (org-overlay-put ov 'org-columns-value (cdr ass))
16471 (org-overlay-put ov 'org-columns-value-modified modval)
16472 (org-overlay-put ov 'org-columns-pom pom)
16473 (org-overlay-put ov 'org-columns-format f))
16474 (if (or (not (char-after beg))
16475 (equal (char-after beg) ?\n))
16476 (let ((inhibit-read-only t))
16477 (save-excursion
16478 (goto-char beg)
16479 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16480 ;; Make the rest of the line disappear.
16481 (org-unmodified
16482 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16483 (org-overlay-put ov 'invisible t)
16484 (org-overlay-put ov 'keymap org-columns-map)
16485 (org-overlay-put ov 'intangible t)
16486 (push ov org-columns-overlays)
16487 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16488 (org-overlay-put ov 'keymap org-columns-map)
16489 (push ov org-columns-overlays)
16490 (let ((inhibit-read-only t))
16491 (put-text-property (max (point-min) (1- (point-at-bol)))
16492 (min (point-max) (1+ (point-at-eol)))
16493 'read-only "Type `e' to edit property")))))
16495 (defvar org-previous-header-line-format nil
16496 "The header line format before column view was turned on.")
16497 (defvar org-columns-inhibit-recalculation nil
16498 "Inhibit recomputing of columns on column view startup.")
16501 (defvar header-line-format)
16502 (defun org-columns-display-here-title ()
16503 "Overlay the newline before the current line with the table title."
16504 (interactive)
16505 (let ((fmt org-columns-current-fmt-compiled)
16506 string (title "")
16507 property width f column str widths)
16508 (while (setq column (pop fmt))
16509 (setq property (car column)
16510 str (or (nth 1 column) property)
16511 width (or (cdr (assoc property org-columns-current-maxwidths))
16512 (nth 2 column)
16513 (length str))
16514 widths (push width widths)
16515 f (format "%%-%d.%ds | " width width)
16516 string (format f str)
16517 title (concat title string)))
16518 (setq title (concat
16519 (org-add-props " " nil 'display '(space :align-to 0))
16520 (org-add-props title nil 'face '(:weight bold :underline t))))
16521 (org-set-local 'org-previous-header-line-format header-line-format)
16522 (org-set-local 'org-columns-current-widths (nreverse widths))
16523 (setq header-line-format title)))
16525 (defun org-columns-remove-overlays ()
16526 "Remove all currently active column overlays."
16527 (interactive)
16528 (when (marker-buffer org-columns-begin-marker)
16529 (with-current-buffer (marker-buffer org-columns-begin-marker)
16530 (when (local-variable-p 'org-previous-header-line-format)
16531 (setq header-line-format org-previous-header-line-format)
16532 (kill-local-variable 'org-previous-header-line-format))
16533 (move-marker org-columns-begin-marker nil)
16534 (move-marker org-columns-top-level-marker nil)
16535 (org-unmodified
16536 (mapc 'org-delete-overlay org-columns-overlays)
16537 (setq org-columns-overlays nil)
16538 (let ((inhibit-read-only t))
16539 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16541 (defun org-columns-cleanup-item (item fmt)
16542 "Remove from ITEM what is a column in the format FMT."
16543 (if (not org-complex-heading-regexp)
16544 item
16545 (when (string-match org-complex-heading-regexp item)
16546 (concat
16547 (org-add-props (concat (match-string 1 item) " ") nil
16548 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16549 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16550 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16551 " " (match-string 4 item)
16552 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16554 (defun org-columns-show-value ()
16555 "Show the full value of the property."
16556 (interactive)
16557 (let ((value (get-char-property (point) 'org-columns-value)))
16558 (message "Value is: %s" (or value ""))))
16560 (defun org-columns-quit ()
16561 "Remove the column overlays and in this way exit column editing."
16562 (interactive)
16563 (org-unmodified
16564 (org-columns-remove-overlays)
16565 (let ((inhibit-read-only t))
16566 (remove-text-properties (point-min) (point-max) '(read-only t))))
16567 (when (eq major-mode 'org-agenda-mode)
16568 (message
16569 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16571 (defun org-columns-check-computed ()
16572 "Check if this column value is computed.
16573 If yes, throw an error indicating that changing it does not make sense."
16574 (let ((val (get-char-property (point) 'org-columns-value)))
16575 (when (and (stringp val)
16576 (get-char-property 0 'org-computed val))
16577 (error "This value is computed from the entry's children"))))
16579 (defun org-columns-todo (&optional arg)
16580 "Change the TODO state during column view."
16581 (interactive "P")
16582 (org-columns-edit-value "TODO"))
16584 (defun org-columns-set-tags-or-toggle (&optional arg)
16585 "Toggle checkbox at point, or set tags for current headline."
16586 (interactive "P")
16587 (if (string-match "\\`\\[[ xX-]\\]\\'"
16588 (get-char-property (point) 'org-columns-value))
16589 (org-columns-next-allowed-value)
16590 (org-columns-edit-value "TAGS")))
16592 (defun org-columns-edit-value (&optional key)
16593 "Edit the value of the property at point in column view.
16594 Where possible, use the standard interface for changing this line."
16595 (interactive)
16596 (org-columns-check-computed)
16597 (let* ((external-key key)
16598 (col (current-column))
16599 (key (or key (get-char-property (point) 'org-columns-key)))
16600 (value (get-char-property (point) 'org-columns-value))
16601 (bol (point-at-bol)) (eol (point-at-eol))
16602 (pom (or (get-text-property bol 'org-hd-marker)
16603 (point))) ; keep despite of compiler waring
16604 (line-overlays
16605 (delq nil (mapcar (lambda (x)
16606 (and (eq (overlay-buffer x) (current-buffer))
16607 (>= (overlay-start x) bol)
16608 (<= (overlay-start x) eol)
16610 org-columns-overlays)))
16611 nval eval allowed)
16612 (cond
16613 ((equal key "CLOCKSUM")
16614 (error "This special column cannot be edited"))
16615 ((equal key "ITEM")
16616 (setq eval '(org-with-point-at pom
16617 (org-edit-headline))))
16618 ((equal key "TODO")
16619 (setq eval '(org-with-point-at pom
16620 (let ((current-prefix-arg
16621 (if external-key current-prefix-arg '(4))))
16622 (call-interactively 'org-todo)))))
16623 ((equal key "PRIORITY")
16624 (setq eval '(org-with-point-at pom
16625 (call-interactively 'org-priority))))
16626 ((equal key "TAGS")
16627 (setq eval '(org-with-point-at pom
16628 (let ((org-fast-tag-selection-single-key
16629 (if (eq org-fast-tag-selection-single-key 'expert)
16630 t org-fast-tag-selection-single-key)))
16631 (call-interactively 'org-set-tags)))))
16632 ((equal key "DEADLINE")
16633 (setq eval '(org-with-point-at pom
16634 (call-interactively 'org-deadline))))
16635 ((equal key "SCHEDULED")
16636 (setq eval '(org-with-point-at pom
16637 (call-interactively 'org-schedule))))
16639 (setq allowed (org-property-get-allowed-values pom key 'table))
16640 (if allowed
16641 (setq nval (completing-read "Value: " allowed nil t))
16642 (setq nval (read-string "Edit: " value)))
16643 (setq nval (org-trim nval))
16644 (when (not (equal nval value))
16645 (setq eval '(org-entry-put pom key nval)))))
16646 (when eval
16647 (let ((inhibit-read-only t))
16648 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
16649 (unwind-protect
16650 (progn
16651 (setq org-columns-overlays
16652 (org-delete-all line-overlays org-columns-overlays))
16653 (mapc 'org-delete-overlay line-overlays)
16654 (org-columns-eval eval))
16655 (org-columns-display-here))))
16656 (move-to-column col)
16657 (if (and (org-mode-p)
16658 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16659 (org-columns-update key))))
16661 (defun org-edit-headline () ; FIXME: this is not columns specific
16662 "Edit the current headline, the part without TODO keyword, TAGS."
16663 (org-back-to-heading)
16664 (when (looking-at org-todo-line-regexp)
16665 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
16666 (txt (match-string 3))
16667 (post "")
16668 txt2)
16669 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
16670 (setq post (match-string 0 txt)
16671 txt (substring txt 0 (match-beginning 0))))
16672 (setq txt2 (read-string "Edit: " txt))
16673 (when (not (equal txt txt2))
16674 (beginning-of-line 1)
16675 (insert pre txt2 post)
16676 (delete-region (point) (point-at-eol))
16677 (org-set-tags nil t)))))
16679 (defun org-columns-edit-allowed ()
16680 "Edit the list of allowed values for the current property."
16681 (interactive)
16682 (let* ((key (get-char-property (point) 'org-columns-key))
16683 (key1 (concat key "_ALL"))
16684 (allowed (org-entry-get (point) key1 t))
16685 nval)
16686 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
16687 (setq nval (read-string "Allowed: " allowed))
16688 (org-entry-put
16689 (cond ((marker-position org-entry-property-inherited-from)
16690 org-entry-property-inherited-from)
16691 ((marker-position org-columns-top-level-marker)
16692 org-columns-top-level-marker))
16693 key1 nval)))
16695 (defmacro org-no-warnings (&rest body)
16696 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
16698 (defun org-columns-eval (form)
16699 (let (hidep)
16700 (save-excursion
16701 (beginning-of-line 1)
16702 ;; `next-line' is needed here, because it skips invisible line.
16703 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
16704 (setq hidep (org-on-heading-p 1)))
16705 (eval form)
16706 (and hidep (hide-entry))))
16708 (defun org-columns-previous-allowed-value ()
16709 "Switch to the previous allowed value for this column."
16710 (interactive)
16711 (org-columns-next-allowed-value t))
16713 (defun org-columns-next-allowed-value (&optional previous)
16714 "Switch to the next allowed value for this column."
16715 (interactive)
16716 (org-columns-check-computed)
16717 (let* ((col (current-column))
16718 (key (get-char-property (point) 'org-columns-key))
16719 (value (get-char-property (point) 'org-columns-value))
16720 (bol (point-at-bol)) (eol (point-at-eol))
16721 (pom (or (get-text-property bol 'org-hd-marker)
16722 (point))) ; keep despite of compiler waring
16723 (line-overlays
16724 (delq nil (mapcar (lambda (x)
16725 (and (eq (overlay-buffer x) (current-buffer))
16726 (>= (overlay-start x) bol)
16727 (<= (overlay-start x) eol)
16729 org-columns-overlays)))
16730 (allowed (or (org-property-get-allowed-values pom key)
16731 (and (equal
16732 (nth 4 (assoc key org-columns-current-fmt-compiled))
16733 'checkbox) '("[ ]" "[X]"))))
16734 nval)
16735 (when (equal key "ITEM")
16736 (error "Cannot edit item headline from here"))
16737 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
16738 (error "Allowed values for this property have not been defined"))
16739 (if (member key '("SCHEDULED" "DEADLINE"))
16740 (setq nval (if previous 'earlier 'later))
16741 (if previous (setq allowed (reverse allowed)))
16742 (if (member value allowed)
16743 (setq nval (car (cdr (member value allowed)))))
16744 (setq nval (or nval (car allowed)))
16745 (if (equal nval value)
16746 (error "Only one allowed value for this property")))
16747 (let ((inhibit-read-only t))
16748 (remove-text-properties (1- bol) eol '(read-only t))
16749 (unwind-protect
16750 (progn
16751 (setq org-columns-overlays
16752 (org-delete-all line-overlays org-columns-overlays))
16753 (mapc 'org-delete-overlay line-overlays)
16754 (org-columns-eval '(org-entry-put pom key nval)))
16755 (org-columns-display-here)))
16756 (move-to-column col)
16757 (if (and (org-mode-p)
16758 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16759 (org-columns-update key))))
16761 (defun org-verify-version (task)
16762 (cond
16763 ((eq task 'columns)
16764 (if (or (featurep 'xemacs)
16765 (< emacs-major-version 22))
16766 (error "Emacs 22 is required for the columns feature")))))
16768 (defun org-columns-open-link (&optional arg)
16769 (interactive "P")
16770 (let ((key (get-char-property (point) 'org-columns-key))
16771 (value (get-char-property (point) 'org-columns-value)))
16772 (org-open-link-from-string arg)))
16774 (defun org-open-link-from-string (s &optional arg)
16775 "Open a link in the string S, as if it was in Org-mode."
16776 (interactive)
16777 (with-temp-buffer
16778 (let ((org-inhibit-startup t))
16779 (org-mode)
16780 (insert s)
16781 (goto-char (point-min))
16782 (org-open-at-point arg))))
16784 (defun org-columns-get-format-and-top-level ()
16785 (let (fmt)
16786 (when (condition-case nil (org-back-to-heading) (error nil))
16787 (move-marker org-entry-property-inherited-from nil)
16788 (setq fmt (org-entry-get nil "COLUMNS" t)))
16789 (setq fmt (or fmt org-columns-default-format))
16790 (org-set-local 'org-columns-current-fmt fmt)
16791 (org-columns-compile-format fmt)
16792 (if (marker-position org-entry-property-inherited-from)
16793 (move-marker org-columns-top-level-marker
16794 org-entry-property-inherited-from)
16795 (move-marker org-columns-top-level-marker (point)))
16796 fmt))
16798 (defun org-columns ()
16799 "Turn on column view on an org-mode file."
16800 (interactive)
16801 (org-verify-version 'columns)
16802 (org-columns-remove-overlays)
16803 (move-marker org-columns-begin-marker (point))
16804 (let (beg end fmt cache maxwidths clocksump)
16805 (setq fmt (org-columns-get-format-and-top-level))
16806 (save-excursion
16807 (goto-char org-columns-top-level-marker)
16808 (setq beg (point))
16809 (unless org-columns-inhibit-recalculation
16810 (org-columns-compute-all))
16811 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
16812 (point-max)))
16813 ;; Get and cache the properties
16814 (goto-char beg)
16815 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
16816 (setq clocksump t)
16817 (save-excursion
16818 (save-restriction
16819 (narrow-to-region beg end)
16820 (org-clock-sum))))
16821 (while (re-search-forward (concat "^" outline-regexp) end t)
16822 (push (cons (org-current-line) (org-entry-properties)) cache))
16823 (when cache
16824 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16825 (org-set-local 'org-columns-current-maxwidths maxwidths)
16826 (org-columns-display-here-title)
16827 (mapc (lambda (x)
16828 (goto-line (car x))
16829 (org-columns-display-here (cdr x)))
16830 cache)))))
16832 (defun org-columns-new (&optional prop title width op fmt &rest rest)
16833 "Insert a new column, to the leeft o the current column."
16834 (interactive)
16835 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
16836 cell)
16837 (setq prop (completing-read
16838 "Property: " (mapcar 'list (org-buffer-property-keys t))
16839 nil nil prop))
16840 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
16841 (setq width (read-string "Column width: " (if width (number-to-string width))))
16842 (if (string-match "\\S-" width)
16843 (setq width (string-to-number width))
16844 (setq width nil))
16845 (setq fmt (completing-read "Summary [none]: "
16846 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox"))
16847 nil t))
16848 (if (string-match "\\S-" fmt)
16849 (setq fmt (intern fmt))
16850 (setq fmt nil))
16851 (if (eq fmt 'none) (setq fmt nil))
16852 (if editp
16853 (progn
16854 (setcar editp prop)
16855 (setcdr editp (list title width nil fmt)))
16856 (setq cell (nthcdr (1- (current-column))
16857 org-columns-current-fmt-compiled))
16858 (setcdr cell (cons (list prop title width nil fmt)
16859 (cdr cell))))
16860 (org-columns-store-format)
16861 (org-columns-redo)))
16863 (defun org-columns-delete ()
16864 "Delete the column at point from columns view."
16865 (interactive)
16866 (let* ((n (current-column))
16867 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
16868 (when (y-or-n-p
16869 (format "Are you sure you want to remove column \"%s\"? " title))
16870 (setq org-columns-current-fmt-compiled
16871 (delq (nth n org-columns-current-fmt-compiled)
16872 org-columns-current-fmt-compiled))
16873 (org-columns-store-format)
16874 (org-columns-redo)
16875 (if (>= (current-column) (length org-columns-current-fmt-compiled))
16876 (backward-char 1)))))
16878 (defun org-columns-edit-attributes ()
16879 "Edit the attributes of the current column."
16880 (interactive)
16881 (let* ((n (current-column))
16882 (info (nth n org-columns-current-fmt-compiled)))
16883 (apply 'org-columns-new info)))
16885 (defun org-columns-widen (arg)
16886 "Make the column wider by ARG characters."
16887 (interactive "p")
16888 (let* ((n (current-column))
16889 (entry (nth n org-columns-current-fmt-compiled))
16890 (width (or (nth 2 entry)
16891 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
16892 (setq width (max 1 (+ width arg)))
16893 (setcar (nthcdr 2 entry) width)
16894 (org-columns-store-format)
16895 (org-columns-redo)))
16897 (defun org-columns-narrow (arg)
16898 "Make the column nrrower by ARG characters."
16899 (interactive "p")
16900 (org-columns-widen (- arg)))
16902 (defun org-columns-move-right ()
16903 "Swap this column with the one to the right."
16904 (interactive)
16905 (let* ((n (current-column))
16906 (cell (nthcdr n org-columns-current-fmt-compiled))
16908 (when (>= n (1- (length org-columns-current-fmt-compiled)))
16909 (error "Cannot shift this column further to the right"))
16910 (setq e (car cell))
16911 (setcar cell (car (cdr cell)))
16912 (setcdr cell (cons e (cdr (cdr cell))))
16913 (org-columns-store-format)
16914 (org-columns-redo)
16915 (forward-char 1)))
16917 (defun org-columns-move-left ()
16918 "Swap this column with the one to the left."
16919 (interactive)
16920 (let* ((n (current-column)))
16921 (when (= n 0)
16922 (error "Cannot shift this column further to the left"))
16923 (backward-char 1)
16924 (org-columns-move-right)
16925 (backward-char 1)))
16927 (defun org-columns-store-format ()
16928 "Store the text version of the current columns format in appropriate place.
16929 This is either in the COLUMNS property of the node starting the current column
16930 display, or in the #+COLUMNS line of the current buffer."
16931 (let (fmt (cnt 0))
16932 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
16933 (org-set-local 'org-columns-current-fmt fmt)
16934 (if (marker-position org-columns-top-level-marker)
16935 (save-excursion
16936 (goto-char org-columns-top-level-marker)
16937 (if (and (org-at-heading-p)
16938 (org-entry-get nil "COLUMNS"))
16939 (org-entry-put nil "COLUMNS" fmt)
16940 (goto-char (point-min))
16941 ;; Overwrite all #+COLUMNS lines....
16942 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
16943 (setq cnt (1+ cnt))
16944 (replace-match (concat "#+COLUMNS: " fmt) t t))
16945 (unless (> cnt 0)
16946 (goto-char (point-min))
16947 (or (org-on-heading-p t) (outline-next-heading))
16948 (let ((inhibit-read-only t))
16949 (insert-before-markers "#+COLUMNS: " fmt "\n")))
16950 (org-set-local 'org-columns-default-format fmt))))))
16952 (defvar org-overriding-columns-format nil
16953 "When set, overrides any other definition.")
16954 (defvar org-agenda-view-columns-initially nil
16955 "When set, switch to columns view immediately after creating the agenda.")
16957 (defun org-agenda-columns ()
16958 "Turn on column view in the agenda."
16959 (interactive)
16960 (org-verify-version 'columns)
16961 (org-columns-remove-overlays)
16962 (move-marker org-columns-begin-marker (point))
16963 (let (fmt cache maxwidths m)
16964 (cond
16965 ((and (local-variable-p 'org-overriding-columns-format)
16966 org-overriding-columns-format)
16967 (setq fmt org-overriding-columns-format))
16968 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
16969 (setq fmt (org-entry-get m "COLUMNS" t)))
16970 ((and (boundp 'org-columns-current-fmt)
16971 (local-variable-p 'org-columns-current-fmt)
16972 org-columns-current-fmt)
16973 (setq fmt org-columns-current-fmt))
16974 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
16975 (setq m (get-text-property m 'org-hd-marker))
16976 (setq fmt (org-entry-get m "COLUMNS" t))))
16977 (setq fmt (or fmt org-columns-default-format))
16978 (org-set-local 'org-columns-current-fmt fmt)
16979 (org-columns-compile-format fmt)
16980 (save-excursion
16981 ;; Get and cache the properties
16982 (goto-char (point-min))
16983 (while (not (eobp))
16984 (when (setq m (or (get-text-property (point) 'org-hd-marker)
16985 (get-text-property (point) 'org-marker)))
16986 (push (cons (org-current-line) (org-entry-properties m)) cache))
16987 (beginning-of-line 2))
16988 (when cache
16989 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16990 (org-set-local 'org-columns-current-maxwidths maxwidths)
16991 (org-columns-display-here-title)
16992 (mapc (lambda (x)
16993 (goto-line (car x))
16994 (org-columns-display-here (cdr x)))
16995 cache)))))
16997 (defun org-columns-get-autowidth-alist (s cache)
16998 "Derive the maximum column widths from the format and the cache."
16999 (let ((start 0) rtn)
17000 (while (string-match (org-re "%\\([[:alpha:]]\\S-*\\)") s start)
17001 (push (cons (match-string 1 s) 1) rtn)
17002 (setq start (match-end 0)))
17003 (mapc (lambda (x)
17004 (setcdr x (apply 'max
17005 (mapcar
17006 (lambda (y)
17007 (length (or (cdr (assoc (car x) (cdr y))) " ")))
17008 cache))))
17009 rtn)
17010 rtn))
17012 (defun org-columns-compute-all ()
17013 "Compute all columns that have operators defined."
17014 (org-unmodified
17015 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
17016 (let ((columns org-columns-current-fmt-compiled) col)
17017 (while (setq col (pop columns))
17018 (when (nth 3 col)
17019 (save-excursion
17020 (org-columns-compute (car col)))))))
17022 (defun org-columns-update (property)
17023 "Recompute PROPERTY, and update the columns display for it."
17024 (org-columns-compute property)
17025 (let (fmt val pos)
17026 (save-excursion
17027 (mapc (lambda (ov)
17028 (when (equal (org-overlay-get ov 'org-columns-key) property)
17029 (setq pos (org-overlay-start ov))
17030 (goto-char pos)
17031 (when (setq val (cdr (assoc property
17032 (get-text-property
17033 (point-at-bol) 'org-summaries))))
17034 (setq fmt (org-overlay-get ov 'org-columns-format))
17035 (org-overlay-put ov 'org-columns-value val)
17036 (org-overlay-put ov 'display (format fmt val)))))
17037 org-columns-overlays))))
17039 (defun org-columns-compute (property)
17040 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
17041 (interactive)
17042 (let* ((re (concat "^" outline-regexp))
17043 (lmax 30) ; Does anyone use deeper levels???
17044 (lsum (make-vector lmax 0))
17045 (lflag (make-vector lmax nil))
17046 (level 0)
17047 (ass (assoc property org-columns-current-fmt-compiled))
17048 (format (nth 4 ass))
17049 (printf (nth 5 ass))
17050 (beg org-columns-top-level-marker)
17051 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
17052 (save-excursion
17053 ;; Find the region to compute
17054 (goto-char beg)
17055 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
17056 (goto-char end)
17057 ;; Walk the tree from the back and do the computations
17058 (while (re-search-backward re beg t)
17059 (setq sumpos (match-beginning 0)
17060 last-level level
17061 level (org-outline-level)
17062 val (org-entry-get nil property)
17063 valflag (and val (string-match "\\S-" val)))
17064 (cond
17065 ((< level last-level)
17066 ;; put the sum of lower levels here as a property
17067 (setq sum (aref lsum last-level) ; current sum
17068 flag (aref lflag last-level) ; any valid entries from children?
17069 str (org-column-number-to-string sum format printf)
17070 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
17071 useval (if flag str1 (if valflag val ""))
17072 sum-alist (get-text-property sumpos 'org-summaries))
17073 (if (assoc property sum-alist)
17074 (setcdr (assoc property sum-alist) useval)
17075 (push (cons property useval) sum-alist)
17076 (org-unmodified
17077 (add-text-properties sumpos (1+ sumpos)
17078 (list 'org-summaries sum-alist))))
17079 (when val
17080 (org-entry-put nil property (if flag str val)))
17081 ;; add current to current level accumulator
17082 (when (or flag valflag)
17083 (aset lsum level (+ (aref lsum level)
17084 (if flag sum (org-column-string-to-number
17085 (if flag str val) format))))
17086 (aset lflag level t))
17087 ;; clear accumulators for deeper levels
17088 (loop for l from (1+ level) to (1- lmax) do
17089 (aset lsum l 0)
17090 (aset lflag l nil)))
17091 ((>= level last-level)
17092 ;; add what we have here to the accumulator for this level
17093 (aset lsum level (+ (aref lsum level)
17094 (org-column-string-to-number (or val "0") format)))
17095 (and valflag (aset lflag level t)))
17096 (t (error "This should not happen")))))))
17098 (defun org-columns-redo ()
17099 "Construct the column display again."
17100 (interactive)
17101 (message "Recomputing columns...")
17102 (save-excursion
17103 (if (marker-position org-columns-begin-marker)
17104 (goto-char org-columns-begin-marker))
17105 (org-columns-remove-overlays)
17106 (if (org-mode-p)
17107 (call-interactively 'org-columns)
17108 (call-interactively 'org-agenda-columns)))
17109 (message "Recomputing columns...done"))
17111 (defun org-columns-not-in-agenda ()
17112 (if (eq major-mode 'org-agenda-mode)
17113 (error "This command is only allowed in Org-mode buffers")))
17116 (defun org-string-to-number (s)
17117 "Convert string to number, and interpret hh:mm:ss."
17118 (if (not (string-match ":" s))
17119 (string-to-number s)
17120 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17121 (while l
17122 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17123 sum)))
17125 (defun org-column-number-to-string (n fmt &optional printf)
17126 "Convert a computed column number to a string value, according to FMT."
17127 (cond
17128 ((eq fmt 'add_times)
17129 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
17130 (format "%d:%02d" h m)))
17131 ((eq fmt 'checkbox)
17132 (cond ((= n (floor n)) "[X]")
17133 ((> n 1.) "[-]")
17134 (t "[ ]")))
17135 (printf (format printf n))
17136 ((eq fmt 'currency)
17137 (format "%.2f" n))
17138 (t (number-to-string n))))
17140 (defun org-column-string-to-number (s fmt)
17141 "Convert a column value to a number that can be used for column computing."
17142 (cond
17143 ((string-match ":" s)
17144 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17145 (while l
17146 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17147 sum))
17148 ((eq fmt 'checkbox)
17149 (if (equal s "[X]") 1. 0.000001))
17150 (t (string-to-number s))))
17152 (defun org-columns-uncompile-format (cfmt)
17153 "Turn the compiled columns format back into a string representation."
17154 (let ((rtn "") e s prop title op width fmt printf)
17155 (while (setq e (pop cfmt))
17156 (setq prop (car e)
17157 title (nth 1 e)
17158 width (nth 2 e)
17159 op (nth 3 e)
17160 fmt (nth 4 e)
17161 printf (nth 5 e))
17162 (cond
17163 ((eq fmt 'add_times) (setq op ":"))
17164 ((eq fmt 'checkbox) (setq op "X"))
17165 ((eq fmt 'add_numbers) (setq op "+"))
17166 ((eq fmt 'currency) (setq op "$")))
17167 (if (and op printf) (setq op (concat op ";" printf)))
17168 (if (equal title prop) (setq title nil))
17169 (setq s (concat "%" (if width (number-to-string width))
17170 prop
17171 (if title (concat "(" title ")"))
17172 (if op (concat "{" op "}"))))
17173 (setq rtn (concat rtn " " s)))
17174 (org-trim rtn)))
17176 (defun org-columns-compile-format (fmt)
17177 "Turn a column format string into an alist of specifications.
17178 The alist has one entry for each column in the format. The elements of
17179 that list are:
17180 property the property
17181 title the title field for the columns
17182 width the column width in characters, can be nil for automatic
17183 operator the operator if any
17184 format the output format for computed results, derived from operator
17185 printf a printf format for computed values"
17186 (let ((start 0) width prop title op f printf)
17187 (setq org-columns-current-fmt-compiled nil)
17188 (while (string-match
17189 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
17190 fmt start)
17191 (setq start (match-end 0)
17192 width (match-string 1 fmt)
17193 prop (match-string 2 fmt)
17194 title (or (match-string 3 fmt) prop)
17195 op (match-string 4 fmt)
17196 f nil
17197 printf nil)
17198 (if width (setq width (string-to-number width)))
17199 (when (and op (string-match ";" op))
17200 (setq printf (substring op (match-end 0))
17201 op (substring op 0 (match-beginning 0))))
17202 (cond
17203 ((equal op "+") (setq f 'add_numbers))
17204 ((equal op "$") (setq f 'currency))
17205 ((equal op ":") (setq f 'add_times))
17206 ((equal op "X") (setq f 'checkbox)))
17207 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
17208 (setq org-columns-current-fmt-compiled
17209 (nreverse org-columns-current-fmt-compiled))))
17212 ;;; Dynamic block for Column view
17214 (defun org-columns-capture-view ()
17215 "Get the column view of the current buffer and return it as a list.
17216 The list will contains the title row and all other rows. Each row is
17217 a list of fields."
17218 (save-excursion
17219 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
17220 (n (length title)) row tbl)
17221 (goto-char (point-min))
17222 (while (re-search-forward "^\\*+ " nil t)
17223 (when (get-char-property (match-beginning 0) 'org-columns-key)
17224 (setq row nil)
17225 (loop for i from 0 to (1- n) do
17226 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
17227 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
17229 row))
17230 (setq row (nreverse row))
17231 (push row tbl)))
17232 (append (list title 'hline) (nreverse tbl)))))
17234 (defun org-dblock-write:columnview (params)
17235 "Write the column view table.
17236 PARAMS is a property list of parameters:
17238 :width enforce same column widths with <N> specifiers.
17239 :id the :ID: property of the entry where the columns view
17240 should be built, as a string. When `local', call locally.
17241 When `global' call column view with the cursor at the beginning
17242 of the buffer (usually this means that the whole buffer switches
17243 to column view).
17244 :hlines When t, insert a hline before each item. When a number, insert
17245 a hline before each level <= that number.
17246 :vlines When t, make each column a colgroup to enforce vertical lines."
17247 (let ((pos (move-marker (make-marker) (point)))
17248 (hlines (plist-get params :hlines))
17249 (vlines (plist-get params :vlines))
17250 tbl id idpos nfields tmp)
17251 (save-excursion
17252 (save-restriction
17253 (when (setq id (plist-get params :id))
17254 (cond ((not id) nil)
17255 ((eq id 'global) (goto-char (point-min)))
17256 ((eq id 'local) nil)
17257 ((setq idpos (org-find-entry-with-id id))
17258 (goto-char idpos))
17259 (t (error "Cannot find entry with :ID: %s" id))))
17260 (org-columns)
17261 (setq tbl (org-columns-capture-view))
17262 (setq nfields (length (car tbl)))
17263 (org-columns-quit)))
17264 (goto-char pos)
17265 (move-marker pos nil)
17266 (when tbl
17267 (when (plist-get params :hlines)
17268 (setq tmp nil)
17269 (while tbl
17270 (if (eq (car tbl) 'hline)
17271 (push (pop tbl) tmp)
17272 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17273 (if (and (not (eq (car tmp) 'hline))
17274 (or (eq hlines t)
17275 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17276 (push 'hline tmp)))
17277 (push (pop tbl) tmp)))
17278 (setq tbl (nreverse tmp)))
17279 (when vlines
17280 (setq tbl (mapcar (lambda (x)
17281 (if (eq 'hline x) x (cons "" x)))
17282 tbl))
17283 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17284 (setq pos (point))
17285 (insert (org-listtable-to-string tbl))
17286 (when (plist-get params :width)
17287 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17288 org-columns-current-widths "|")))
17289 (goto-char pos)
17290 (org-table-align))))
17292 (defun org-listtable-to-string (tbl)
17293 "Convert a listtable TBL to a string that contains the Org-mode table.
17294 The table still need to be alligned. The resulting string has no leading
17295 and tailing newline characters."
17296 (mapconcat
17297 (lambda (x)
17298 (cond
17299 ((listp x)
17300 (concat "|" (mapconcat 'identity x "|") "|"))
17301 ((eq x 'hline) "|-|")
17302 (t (error "Garbage in listtable: %s" x))))
17303 tbl "\n"))
17305 (defun org-insert-columns-dblock ()
17306 "Create a dynamic block capturing a column view table."
17307 (interactive)
17308 (let ((defaults '(:name "columnview" :hlines 1))
17309 (id (completing-read
17310 "Capture columns (local, global, entry with :ID: property) [local]: "
17311 (append '(("global") ("local"))
17312 (mapcar 'list (org-property-values "ID"))))))
17313 (if (equal id "") (setq id 'local))
17314 (if (equal id "global") (setq id 'global))
17315 (setq defaults (append defaults (list :id id)))
17316 (org-create-dblock defaults)
17317 (org-update-dblock)))
17319 ;;;; Timestamps
17321 (defvar org-last-changed-timestamp nil)
17322 (defvar org-time-was-given) ; dynamically scoped parameter
17323 (defvar org-end-time-was-given) ; dynamically scoped parameter
17324 (defvar org-ts-what) ; dynamically scoped parameter
17326 (defun org-time-stamp (arg)
17327 "Prompt for a date/time and insert a time stamp.
17328 If the user specifies a time like HH:MM, or if this command is called
17329 with a prefix argument, the time stamp will contain date and time.
17330 Otherwise, only the date will be included. All parts of a date not
17331 specified by the user will be filled in from the current date/time.
17332 So if you press just return without typing anything, the time stamp
17333 will represent the current date/time. If there is already a timestamp
17334 at the cursor, it will be modified."
17335 (interactive "P")
17336 (let* ((ts nil)
17337 (default-time
17338 ;; Default time is either today, or, when entering a range,
17339 ;; the range start.
17340 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17341 (save-excursion
17342 (re-search-backward
17343 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17344 (- (point) 20) t)))
17345 (apply 'encode-time (org-parse-time-string (match-string 1)))
17346 (current-time)))
17347 (default-input (and ts (org-get-compact-tod ts)))
17348 org-time-was-given org-end-time-was-given time)
17349 (cond
17350 ((and (org-at-timestamp-p)
17351 (eq last-command 'org-time-stamp)
17352 (eq this-command 'org-time-stamp))
17353 (insert "--")
17354 (setq time (let ((this-command this-command))
17355 (org-read-date arg 'totime nil nil default-time default-input)))
17356 (org-insert-time-stamp time (or org-time-was-given arg)))
17357 ((org-at-timestamp-p)
17358 (setq time (let ((this-command this-command))
17359 (org-read-date arg 'totime nil nil default-time default-input)))
17360 (when (org-at-timestamp-p) ; just to get the match data
17361 (replace-match "")
17362 (setq org-last-changed-timestamp
17363 (org-insert-time-stamp
17364 time (or org-time-was-given arg)
17365 nil nil nil (list org-end-time-was-given))))
17366 (message "Timestamp updated"))
17368 (setq time (let ((this-command this-command))
17369 (org-read-date arg 'totime nil nil default-time default-input)))
17370 (org-insert-time-stamp time (or org-time-was-given arg)
17371 nil nil nil (list org-end-time-was-given))))))
17373 ;; FIXME: can we use this for something else????
17374 ;; like computing time differences?????
17375 (defun org-get-compact-tod (s)
17376 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17377 (let* ((t1 (match-string 1 s))
17378 (h1 (string-to-number (match-string 2 s)))
17379 (m1 (string-to-number (match-string 3 s)))
17380 (t2 (and (match-end 4) (match-string 5 s)))
17381 (h2 (and t2 (string-to-number (match-string 6 s))))
17382 (m2 (and t2 (string-to-number (match-string 7 s))))
17383 dh dm)
17384 (if (not t2)
17386 (setq dh (- h2 h1) dm (- m2 m1))
17387 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17388 (concat t1 "+" (number-to-string dh)
17389 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17391 (defun org-time-stamp-inactive (&optional arg)
17392 "Insert an inactive time stamp.
17393 An inactive time stamp is enclosed in square brackets instead of angle
17394 brackets. It is inactive in the sense that it does not trigger agenda entries,
17395 does not link to the calendar and cannot be changed with the S-cursor keys.
17396 So these are more for recording a certain time/date."
17397 (interactive "P")
17398 (let (org-time-was-given org-end-time-was-given time)
17399 (setq time (org-read-date arg 'totime))
17400 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17401 nil nil (list org-end-time-was-given))))
17403 (defvar org-date-ovl (org-make-overlay 1 1))
17404 (org-overlay-put org-date-ovl 'face 'org-warning)
17405 (org-detach-overlay org-date-ovl)
17407 (defvar org-ans1) ; dynamically scoped parameter
17408 (defvar org-ans2) ; dynamically scoped parameter
17410 (defvar org-plain-time-of-day-regexp) ; defined below
17412 (defvar org-read-date-overlay nil)
17413 (defvar org-dcst nil) ; dynamically scoped
17415 (defun org-read-date (&optional with-time to-time from-string prompt
17416 default-time default-input)
17417 "Read a date, possibly a time, and make things smooth for the user.
17418 The prompt will suggest to enter an ISO date, but you can also enter anything
17419 which will at least partially be understood by `parse-time-string'.
17420 Unrecognized parts of the date will default to the current day, month, year,
17421 hour and minute. If this command is called to replace a timestamp at point,
17422 of to enter the second timestamp of a range, the default time is taken from the
17423 existing stamp. For example,
17424 3-2-5 --> 2003-02-05
17425 feb 15 --> currentyear-02-15
17426 sep 12 9 --> 2009-09-12
17427 12:45 --> today 12:45
17428 22 sept 0:34 --> currentyear-09-22 0:34
17429 12 --> currentyear-currentmonth-12
17430 Fri --> nearest Friday (today or later)
17431 etc.
17433 Furthermore you can specify a relative date by giving, as the *first* thing
17434 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17435 change in days weeks, months, years.
17436 With a single plus or minus, the date is relative to today. With a double
17437 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17438 +4d --> four days from today
17439 +4 --> same as above
17440 +2w --> two weeks from today
17441 ++5 --> five days from default date
17443 The function understands only English month and weekday abbreviations,
17444 but this can be configured with the variables `parse-time-months' and
17445 `parse-time-weekdays'.
17447 While prompting, a calendar is popped up - you can also select the
17448 date with the mouse (button 1). The calendar shows a period of three
17449 months. To scroll it to other months, use the keys `>' and `<'.
17450 If you don't like the calendar, turn it off with
17451 \(setq org-read-date-popup-calendar nil)
17453 With optional argument TO-TIME, the date will immediately be converted
17454 to an internal time.
17455 With an optional argument WITH-TIME, the prompt will suggest to also
17456 insert a time. Note that when WITH-TIME is not set, you can still
17457 enter a time, and this function will inform the calling routine about
17458 this change. The calling routine may then choose to change the format
17459 used to insert the time stamp into the buffer to include the time.
17460 With optional argument FROM-STRING, read from this string instead from
17461 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17462 the time/date that is used for everything that is not specified by the
17463 user."
17464 (require 'parse-time)
17465 (let* ((org-time-stamp-rounding-minutes
17466 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
17467 (org-dcst org-display-custom-times)
17468 (ct (org-current-time))
17469 (def (or default-time ct))
17470 (defdecode (decode-time def))
17471 (dummy (progn
17472 (when (< (nth 2 defdecode) org-extend-today-until)
17473 (setcar (nthcdr 2 defdecode) -1)
17474 (setcar (nthcdr 1 defdecode) 59)
17475 (setq def (apply 'encode-time defdecode)
17476 defdecode (decode-time def)))))
17477 (calendar-move-hook nil)
17478 (view-diary-entries-initially nil)
17479 (view-calendar-holidays-initially nil)
17480 (timestr (format-time-string
17481 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17482 (prompt (concat (if prompt (concat prompt " ") "")
17483 (format "Date+time [%s]: " timestr)))
17484 ans (org-ans0 "") org-ans1 org-ans2 final)
17486 (cond
17487 (from-string (setq ans from-string))
17488 (org-read-date-popup-calendar
17489 (save-excursion
17490 (save-window-excursion
17491 (calendar)
17492 (calendar-forward-day (- (time-to-days def)
17493 (calendar-absolute-from-gregorian
17494 (calendar-current-date))))
17495 (org-eval-in-calendar nil t)
17496 (let* ((old-map (current-local-map))
17497 (map (copy-keymap calendar-mode-map))
17498 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17499 (org-defkey map (kbd "RET") 'org-calendar-select)
17500 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17501 'org-calendar-select-mouse)
17502 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17503 'org-calendar-select-mouse)
17504 (org-defkey minibuffer-local-map [(meta shift left)]
17505 (lambda () (interactive)
17506 (org-eval-in-calendar '(calendar-backward-month 1))))
17507 (org-defkey minibuffer-local-map [(meta shift right)]
17508 (lambda () (interactive)
17509 (org-eval-in-calendar '(calendar-forward-month 1))))
17510 (org-defkey minibuffer-local-map [(meta shift up)]
17511 (lambda () (interactive)
17512 (org-eval-in-calendar '(calendar-backward-year 1))))
17513 (org-defkey minibuffer-local-map [(meta shift down)]
17514 (lambda () (interactive)
17515 (org-eval-in-calendar '(calendar-forward-year 1))))
17516 (org-defkey minibuffer-local-map [(shift up)]
17517 (lambda () (interactive)
17518 (org-eval-in-calendar '(calendar-backward-week 1))))
17519 (org-defkey minibuffer-local-map [(shift down)]
17520 (lambda () (interactive)
17521 (org-eval-in-calendar '(calendar-forward-week 1))))
17522 (org-defkey minibuffer-local-map [(shift left)]
17523 (lambda () (interactive)
17524 (org-eval-in-calendar '(calendar-backward-day 1))))
17525 (org-defkey minibuffer-local-map [(shift right)]
17526 (lambda () (interactive)
17527 (org-eval-in-calendar '(calendar-forward-day 1))))
17528 (org-defkey minibuffer-local-map ">"
17529 (lambda () (interactive)
17530 (org-eval-in-calendar '(scroll-calendar-left 1))))
17531 (org-defkey minibuffer-local-map "<"
17532 (lambda () (interactive)
17533 (org-eval-in-calendar '(scroll-calendar-right 1))))
17534 (unwind-protect
17535 (progn
17536 (use-local-map map)
17537 (add-hook 'post-command-hook 'org-read-date-display)
17538 (setq org-ans0 (read-string prompt default-input nil nil))
17539 ;; org-ans0: from prompt
17540 ;; org-ans1: from mouse click
17541 ;; org-ans2: from calendar motion
17542 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17543 (remove-hook 'post-command-hook 'org-read-date-display)
17544 (use-local-map old-map)
17545 (when org-read-date-overlay
17546 (org-delete-overlay org-read-date-overlay)
17547 (setq org-read-date-overlay nil)))))))
17549 (t ; Naked prompt only
17550 (unwind-protect
17551 (setq ans (read-string prompt default-input nil timestr))
17552 (when org-read-date-overlay
17553 (org-delete-overlay org-read-date-overlay)
17554 (setq org-read-date-overlay nil)))))
17556 (setq final (org-read-date-analyze ans def defdecode))
17558 (if to-time
17559 (apply 'encode-time final)
17560 (if (and (boundp 'org-time-was-given) org-time-was-given)
17561 (format "%04d-%02d-%02d %02d:%02d"
17562 (nth 5 final) (nth 4 final) (nth 3 final)
17563 (nth 2 final) (nth 1 final))
17564 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17565 (defvar def)
17566 (defvar defdecode)
17567 (defvar with-time)
17568 (defun org-read-date-display ()
17569 "Display the currrent date prompt interpretation in the minibuffer."
17570 (when org-read-date-display-live
17571 (when org-read-date-overlay
17572 (org-delete-overlay org-read-date-overlay))
17573 (let ((p (point)))
17574 (end-of-line 1)
17575 (while (not (equal (buffer-substring
17576 (max (point-min) (- (point) 4)) (point))
17577 " "))
17578 (insert " "))
17579 (goto-char p))
17580 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17581 " " (or org-ans1 org-ans2)))
17582 (org-end-time-was-given nil)
17583 (f (org-read-date-analyze ans def defdecode))
17584 (fmts (if org-dcst
17585 org-time-stamp-custom-formats
17586 org-time-stamp-formats))
17587 (fmt (if (or with-time
17588 (and (boundp 'org-time-was-given) org-time-was-given))
17589 (cdr fmts)
17590 (car fmts)))
17591 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
17592 (when (and org-end-time-was-given
17593 (string-match org-plain-time-of-day-regexp txt))
17594 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17595 org-end-time-was-given
17596 (substring txt (match-end 0)))))
17597 (setq org-read-date-overlay
17598 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17599 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
17601 (defun org-read-date-analyze (ans def defdecode)
17602 "Analyze the combined answer of the date prompt."
17603 ;; FIXME: cleanup and comment
17604 (let (delta deltan deltaw deltadef year month day
17605 hour minute second wday pm h2 m2 tl wday1)
17607 (when (setq delta (org-read-date-get-relative ans (current-time) def))
17608 (setq ans (replace-match "" t t ans)
17609 deltan (car delta)
17610 deltaw (nth 1 delta)
17611 deltadef (nth 2 delta)))
17613 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
17614 (when (string-match
17615 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17616 (setq year (if (match-end 2)
17617 (string-to-number (match-string 2 ans))
17618 (string-to-number (format-time-string "%Y")))
17619 month (string-to-number (match-string 3 ans))
17620 day (string-to-number (match-string 4 ans)))
17621 (if (< year 100) (setq year (+ 2000 year)))
17622 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17623 t nil ans)))
17624 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17625 ;; If there is a time with am/pm, and *no* time without it, we convert
17626 ;; so that matching will be successful.
17627 (loop for i from 1 to 2 do ; twice, for end time as well
17628 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17629 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17630 (setq hour (string-to-number (match-string 1 ans))
17631 minute (if (match-end 3)
17632 (string-to-number (match-string 3 ans))
17634 pm (equal ?p
17635 (string-to-char (downcase (match-string 4 ans)))))
17636 (if (and (= hour 12) (not pm))
17637 (setq hour 0)
17638 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17639 (setq ans (replace-match (format "%02d:%02d" hour minute)
17640 t t ans))))
17642 ;; Check if a time range is given as a duration
17643 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17644 (setq hour (string-to-number (match-string 1 ans))
17645 h2 (+ hour (string-to-number (match-string 3 ans)))
17646 minute (string-to-number (match-string 2 ans))
17647 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
17648 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17649 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
17651 ;; Check if there is a time range
17652 (when (boundp 'org-end-time-was-given)
17653 (setq org-time-was-given nil)
17654 (when (and (string-match org-plain-time-of-day-regexp ans)
17655 (match-end 8))
17656 (setq org-end-time-was-given (match-string 8 ans))
17657 (setq ans (concat (substring ans 0 (match-beginning 7))
17658 (substring ans (match-end 7))))))
17660 (setq tl (parse-time-string ans)
17661 day (or (nth 3 tl) (nth 3 defdecode))
17662 month (or (nth 4 tl)
17663 (if (and org-read-date-prefer-future
17664 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
17665 (1+ (nth 4 defdecode))
17666 (nth 4 defdecode)))
17667 year (or (nth 5 tl)
17668 (if (and org-read-date-prefer-future
17669 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
17670 (1+ (nth 5 defdecode))
17671 (nth 5 defdecode)))
17672 hour (or (nth 2 tl) (nth 2 defdecode))
17673 minute (or (nth 1 tl) (nth 1 defdecode))
17674 second (or (nth 0 tl) 0)
17675 wday (nth 6 tl))
17676 (when deltan
17677 (unless deltadef
17678 (let ((now (decode-time (current-time))))
17679 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17680 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17681 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17682 ((equal deltaw "m") (setq month (+ month deltan)))
17683 ((equal deltaw "y") (setq year (+ year deltan)))))
17684 (when (and wday (not (nth 3 tl)))
17685 ;; Weekday was given, but no day, so pick that day in the week
17686 ;; on or after the derived date.
17687 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17688 (unless (equal wday wday1)
17689 (setq day (+ day (% (- wday wday1 -7) 7)))))
17690 (if (and (boundp 'org-time-was-given)
17691 (nth 2 tl))
17692 (setq org-time-was-given t))
17693 (if (< year 100) (setq year (+ 2000 year)))
17694 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
17695 (list second minute hour day month year)))
17697 (defvar parse-time-weekdays)
17699 (defun org-read-date-get-relative (s today default)
17700 "Check string S for special relative date string.
17701 TODAY and DEFAULT are internal times, for today and for a default.
17702 Return shift list (N what def-flag)
17703 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17704 N is the number of WHATs to shift.
17705 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17706 the DEFAULT date rather than TODAY."
17707 (when (string-match
17708 (concat
17709 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
17710 "\\([0-9]+\\)?"
17711 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17712 "\\([ \t]\\|$\\)") s)
17713 (let* ((dir (if (match-end 1)
17714 (string-to-char (substring (match-string 1 s) -1))
17715 ?+))
17716 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17717 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17718 (what (if (match-end 3) (match-string 3 s) "d"))
17719 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17720 (date (if rel default today))
17721 (wday (nth 6 (decode-time date)))
17722 delta)
17723 (if wday1
17724 (progn
17725 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17726 (if (= dir ?-) (setq delta (- delta 7)))
17727 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17728 (list delta "d" rel))
17729 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17731 (defun org-eval-in-calendar (form &optional keepdate)
17732 "Eval FORM in the calendar window and return to current window.
17733 Also, store the cursor date in variable org-ans2."
17734 (let ((sw (selected-window)))
17735 (select-window (get-buffer-window "*Calendar*"))
17736 (eval form)
17737 (when (and (not keepdate) (calendar-cursor-to-date))
17738 (let* ((date (calendar-cursor-to-date))
17739 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17740 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17741 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17742 (select-window sw)))
17744 ; ;; Update the prompt to show new default date
17745 ; (save-excursion
17746 ; (goto-char (point-min))
17747 ; (when (and org-ans2
17748 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
17749 ; (get-text-property (match-end 0) 'field))
17750 ; (let ((inhibit-read-only t))
17751 ; (replace-match (concat "[" org-ans2 "]") t t)
17752 ; (add-text-properties (point-min) (1+ (match-end 0))
17753 ; (text-properties-at (1+ (point-min)))))))))
17755 (defun org-calendar-select ()
17756 "Return to `org-read-date' with the date currently selected.
17757 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17758 (interactive)
17759 (when (calendar-cursor-to-date)
17760 (let* ((date (calendar-cursor-to-date))
17761 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17762 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17763 (if (active-minibuffer-window) (exit-minibuffer))))
17765 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17766 "Insert a date stamp for the date given by the internal TIME.
17767 WITH-HM means, use the stamp format that includes the time of the day.
17768 INACTIVE means use square brackets instead of angular ones, so that the
17769 stamp will not contribute to the agenda.
17770 PRE and POST are optional strings to be inserted before and after the
17771 stamp.
17772 The command returns the inserted time stamp."
17773 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17774 stamp)
17775 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17776 (insert-before-markers (or pre ""))
17777 (insert-before-markers (setq stamp (format-time-string fmt time)))
17778 (when (listp extra)
17779 (setq extra (car extra))
17780 (if (and (stringp extra)
17781 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17782 (setq extra (format "-%02d:%02d"
17783 (string-to-number (match-string 1 extra))
17784 (string-to-number (match-string 2 extra))))
17785 (setq extra nil)))
17786 (when extra
17787 (backward-char 1)
17788 (insert-before-markers extra)
17789 (forward-char 1))
17790 (insert-before-markers (or post ""))
17791 stamp))
17793 (defun org-toggle-time-stamp-overlays ()
17794 "Toggle the use of custom time stamp formats."
17795 (interactive)
17796 (setq org-display-custom-times (not org-display-custom-times))
17797 (unless org-display-custom-times
17798 (let ((p (point-min)) (bmp (buffer-modified-p)))
17799 (while (setq p (next-single-property-change p 'display))
17800 (if (and (get-text-property p 'display)
17801 (eq (get-text-property p 'face) 'org-date))
17802 (remove-text-properties
17803 p (setq p (next-single-property-change p 'display))
17804 '(display t))))
17805 (set-buffer-modified-p bmp)))
17806 (if (featurep 'xemacs)
17807 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17808 (org-restart-font-lock)
17809 (setq org-table-may-need-update t)
17810 (if org-display-custom-times
17811 (message "Time stamps are overlayed with custom format")
17812 (message "Time stamp overlays removed")))
17814 (defun org-display-custom-time (beg end)
17815 "Overlay modified time stamp format over timestamp between BED and END."
17816 (let* ((ts (buffer-substring beg end))
17817 t1 w1 with-hm tf time str w2 (off 0))
17818 (save-match-data
17819 (setq t1 (org-parse-time-string ts t))
17820 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
17821 (setq off (- (match-end 0) (match-beginning 0)))))
17822 (setq end (- end off))
17823 (setq w1 (- end beg)
17824 with-hm (and (nth 1 t1) (nth 2 t1))
17825 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17826 time (org-fix-decoded-time t1)
17827 str (org-add-props
17828 (format-time-string
17829 (substring tf 1 -1) (apply 'encode-time time))
17830 nil 'mouse-face 'highlight)
17831 w2 (length str))
17832 (if (not (= w2 w1))
17833 (add-text-properties (1+ beg) (+ 2 beg)
17834 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17835 (if (featurep 'xemacs)
17836 (progn
17837 (put-text-property beg end 'invisible t)
17838 (put-text-property beg end 'end-glyph (make-glyph str)))
17839 (put-text-property beg end 'display str))))
17841 (defun org-translate-time (string)
17842 "Translate all timestamps in STRING to custom format.
17843 But do this only if the variable `org-display-custom-times' is set."
17844 (when org-display-custom-times
17845 (save-match-data
17846 (let* ((start 0)
17847 (re org-ts-regexp-both)
17848 t1 with-hm inactive tf time str beg end)
17849 (while (setq start (string-match re string start))
17850 (setq beg (match-beginning 0)
17851 end (match-end 0)
17852 t1 (save-match-data
17853 (org-parse-time-string (substring string beg end) t))
17854 with-hm (and (nth 1 t1) (nth 2 t1))
17855 inactive (equal (substring string beg (1+ beg)) "[")
17856 tf (funcall (if with-hm 'cdr 'car)
17857 org-time-stamp-custom-formats)
17858 time (org-fix-decoded-time t1)
17859 str (format-time-string
17860 (concat
17861 (if inactive "[" "<") (substring tf 1 -1)
17862 (if inactive "]" ">"))
17863 (apply 'encode-time time))
17864 string (replace-match str t t string)
17865 start (+ start (length str)))))))
17866 string)
17868 (defun org-fix-decoded-time (time)
17869 "Set 0 instead of nil for the first 6 elements of time.
17870 Don't touch the rest."
17871 (let ((n 0))
17872 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17874 (defun org-days-to-time (timestamp-string)
17875 "Difference between TIMESTAMP-STRING and now in days."
17876 (- (time-to-days (org-time-string-to-time timestamp-string))
17877 (time-to-days (current-time))))
17879 (defun org-deadline-close (timestamp-string &optional ndays)
17880 "Is the time in TIMESTAMP-STRING close to the current date?"
17881 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17882 (and (< (org-days-to-time timestamp-string) ndays)
17883 (not (org-entry-is-done-p))))
17885 (defun org-get-wdays (ts)
17886 "Get the deadline lead time appropriate for timestring TS."
17887 (cond
17888 ((<= org-deadline-warning-days 0)
17889 ;; 0 or negative, enforce this value no matter what
17890 (- org-deadline-warning-days))
17891 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
17892 ;; lead time is specified.
17893 (floor (* (string-to-number (match-string 1 ts))
17894 (cdr (assoc (match-string 2 ts)
17895 '(("d" . 1) ("w" . 7)
17896 ("m" . 30.4) ("y" . 365.25)))))))
17897 ;; go for the default.
17898 (t org-deadline-warning-days)))
17900 (defun org-calendar-select-mouse (ev)
17901 "Return to `org-read-date' with the date currently selected.
17902 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17903 (interactive "e")
17904 (mouse-set-point ev)
17905 (when (calendar-cursor-to-date)
17906 (let* ((date (calendar-cursor-to-date))
17907 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17908 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17909 (if (active-minibuffer-window) (exit-minibuffer))))
17911 (defun org-check-deadlines (ndays)
17912 "Check if there are any deadlines due or past due.
17913 A deadline is considered due if it happens within `org-deadline-warning-days'
17914 days from today's date. If the deadline appears in an entry marked DONE,
17915 it is not shown. The prefix arg NDAYS can be used to test that many
17916 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17917 (interactive "P")
17918 (let* ((org-warn-days
17919 (cond
17920 ((equal ndays '(4)) 100000)
17921 (ndays (prefix-numeric-value ndays))
17922 (t (abs org-deadline-warning-days))))
17923 (case-fold-search nil)
17924 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17925 (callback
17926 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17928 (message "%d deadlines past-due or due within %d days"
17929 (org-occur regexp nil callback)
17930 org-warn-days)))
17932 (defun org-check-before-date (date)
17933 "Check if there are deadlines or scheduled entries before DATE."
17934 (interactive (list (org-read-date)))
17935 (let ((case-fold-search nil)
17936 (regexp (concat "\\<\\(" org-deadline-string
17937 "\\|" org-scheduled-string
17938 "\\) *<\\([^>]+\\)>"))
17939 (callback
17940 (lambda () (time-less-p
17941 (org-time-string-to-time (match-string 2))
17942 (org-time-string-to-time date)))))
17943 (message "%d entries before %s"
17944 (org-occur regexp nil callback) date)))
17946 (defun org-evaluate-time-range (&optional to-buffer)
17947 "Evaluate a time range by computing the difference between start and end.
17948 Normally the result is just printed in the echo area, but with prefix arg
17949 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17950 If the time range is actually in a table, the result is inserted into the
17951 next column.
17952 For time difference computation, a year is assumed to be exactly 365
17953 days in order to avoid rounding problems."
17954 (interactive "P")
17956 (org-clock-update-time-maybe)
17957 (save-excursion
17958 (unless (org-at-date-range-p t)
17959 (goto-char (point-at-bol))
17960 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17961 (if (not (org-at-date-range-p t))
17962 (error "Not at a time-stamp range, and none found in current line")))
17963 (let* ((ts1 (match-string 1))
17964 (ts2 (match-string 2))
17965 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17966 (match-end (match-end 0))
17967 (time1 (org-time-string-to-time ts1))
17968 (time2 (org-time-string-to-time ts2))
17969 (t1 (time-to-seconds time1))
17970 (t2 (time-to-seconds time2))
17971 (diff (abs (- t2 t1)))
17972 (negative (< (- t2 t1) 0))
17973 ;; (ys (floor (* 365 24 60 60)))
17974 (ds (* 24 60 60))
17975 (hs (* 60 60))
17976 (fy "%dy %dd %02d:%02d")
17977 (fy1 "%dy %dd")
17978 (fd "%dd %02d:%02d")
17979 (fd1 "%dd")
17980 (fh "%02d:%02d")
17981 y d h m align)
17982 (if havetime
17983 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17985 d (floor (/ diff ds)) diff (mod diff ds)
17986 h (floor (/ diff hs)) diff (mod diff hs)
17987 m (floor (/ diff 60)))
17988 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17990 d (floor (+ (/ diff ds) 0.5))
17991 h 0 m 0))
17992 (if (not to-buffer)
17993 (message "%s" (org-make-tdiff-string y d h m))
17994 (if (org-at-table-p)
17995 (progn
17996 (goto-char match-end)
17997 (setq align t)
17998 (and (looking-at " *|") (goto-char (match-end 0))))
17999 (goto-char match-end))
18000 (if (looking-at
18001 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
18002 (replace-match ""))
18003 (if negative (insert " -"))
18004 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
18005 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
18006 (insert " " (format fh h m))))
18007 (if align (org-table-align))
18008 (message "Time difference inserted")))))
18010 (defun org-make-tdiff-string (y d h m)
18011 (let ((fmt "")
18012 (l nil))
18013 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
18014 l (push y l)))
18015 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
18016 l (push d l)))
18017 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
18018 l (push h l)))
18019 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
18020 l (push m l)))
18021 (apply 'format fmt (nreverse l))))
18023 (defun org-time-string-to-time (s)
18024 (apply 'encode-time (org-parse-time-string s)))
18026 (defun org-time-string-to-absolute (s &optional daynr prefer)
18027 "Convert a time stamp to an absolute day number.
18028 If there is a specifyer for a cyclic time stamp, get the closest date to
18029 DAYNR."
18030 (cond
18031 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
18032 (if (org-diary-sexp-entry (match-string 1 s) "" date)
18033 daynr
18034 (+ daynr 1000)))
18035 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
18036 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
18037 (time-to-days (current-time))) (match-string 0 s)
18038 prefer))
18039 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
18041 (defun org-time-from-absolute (d)
18042 "Return the time corresponding to date D.
18043 D may be an absolute day number, or a calendar-type list (month day year)."
18044 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
18045 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
18047 (defun org-calendar-holiday ()
18048 "List of holidays, for Diary display in Org-mode."
18049 (require 'holidays)
18050 (let ((hl (funcall
18051 (if (fboundp 'calendar-check-holidays)
18052 'calendar-check-holidays 'check-calendar-holidays) date)))
18053 (if hl (mapconcat 'identity hl "; "))))
18055 (defun org-diary-sexp-entry (sexp entry date)
18056 "Process a SEXP diary ENTRY for DATE."
18057 (require 'diary-lib)
18058 (let ((result (if calendar-debug-sexp
18059 (let ((stack-trace-on-error t))
18060 (eval (car (read-from-string sexp))))
18061 (condition-case nil
18062 (eval (car (read-from-string sexp)))
18063 (error
18064 (beep)
18065 (message "Bad sexp at line %d in %s: %s"
18066 (org-current-line)
18067 (buffer-file-name) sexp)
18068 (sleep-for 2))))))
18069 (cond ((stringp result) result)
18070 ((and (consp result)
18071 (stringp (cdr result))) (cdr result))
18072 (result entry)
18073 (t nil))))
18075 (defun org-diary-to-ical-string (frombuf)
18076 "Get iCalendar entries from diary entries in buffer FROMBUF.
18077 This uses the icalendar.el library."
18078 (let* ((tmpdir (if (featurep 'xemacs)
18079 (temp-directory)
18080 temporary-file-directory))
18081 (tmpfile (make-temp-name
18082 (expand-file-name "orgics" tmpdir)))
18083 buf rtn b e)
18084 (save-excursion
18085 (set-buffer frombuf)
18086 (icalendar-export-region (point-min) (point-max) tmpfile)
18087 (setq buf (find-buffer-visiting tmpfile))
18088 (set-buffer buf)
18089 (goto-char (point-min))
18090 (if (re-search-forward "^BEGIN:VEVENT" nil t)
18091 (setq b (match-beginning 0)))
18092 (goto-char (point-max))
18093 (if (re-search-backward "^END:VEVENT" nil t)
18094 (setq e (match-end 0)))
18095 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
18096 (kill-buffer buf)
18097 (kill-buffer frombuf)
18098 (delete-file tmpfile)
18099 rtn))
18101 (defun org-closest-date (start current change prefer)
18102 "Find the date closest to CURRENT that is consistent with START and CHANGE.
18103 When PREFER is `past' return a date that is either CURRENT or past.
18104 When PREFER is `future', return a date that is either CURRENT or future."
18105 ;; Make the proper lists from the dates
18106 (catch 'exit
18107 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
18108 dn dw sday cday n1 n2
18109 d m y y1 y2 date1 date2 nmonths nm ny m2)
18111 (setq start (org-date-to-gregorian start)
18112 current (org-date-to-gregorian
18113 (if org-agenda-repeating-timestamp-show-all
18114 current
18115 (time-to-days (current-time))))
18116 sday (calendar-absolute-from-gregorian start)
18117 cday (calendar-absolute-from-gregorian current))
18119 (if (<= cday sday) (throw 'exit sday))
18121 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
18122 (setq dn (string-to-number (match-string 1 change))
18123 dw (cdr (assoc (match-string 2 change) a1)))
18124 (error "Invalid change specifyer: %s" change))
18125 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
18126 (cond
18127 ((eq dw 'day)
18128 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
18129 n2 (+ n1 dn)))
18130 ((eq dw 'year)
18131 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
18132 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
18133 (setq date1 (list m d y1)
18134 n1 (calendar-absolute-from-gregorian date1)
18135 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
18136 n2 (calendar-absolute-from-gregorian date2)))
18137 ((eq dw 'month)
18138 ;; approx number of month between the tow dates
18139 (setq nmonths (floor (/ (- cday sday) 30.436875)))
18140 ;; How often does dn fit in there?
18141 (setq d (nth 1 start) m (car start) y (nth 2 start)
18142 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
18143 m (+ m nm)
18144 ny (floor (/ m 12))
18145 y (+ y ny)
18146 m (- m (* ny 12)))
18147 (while (> m 12) (setq m (- m 12) y (1+ y)))
18148 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
18149 (setq m2 (+ m dn) y2 y)
18150 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18151 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
18152 (while (< n2 cday)
18153 (setq n1 n2 m m2 y y2)
18154 (setq m2 (+ m dn) y2 y)
18155 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18156 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
18158 (if org-agenda-repeating-timestamp-show-all
18159 (cond
18160 ((eq prefer 'past) n1)
18161 ((eq prefer 'future) (if (= cday n1) n1 n2))
18162 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
18163 (cond
18164 ((eq prefer 'past) n1)
18165 ((eq prefer 'future) (if (= cday n1) n1 n2))
18166 (t (if (= cday n1) n1 n2)))))))
18168 (defun org-date-to-gregorian (date)
18169 "Turn any specification of DATE into a gregorian date for the calendar."
18170 (cond ((integerp date) (calendar-gregorian-from-absolute date))
18171 ((and (listp date) (= (length date) 3)) date)
18172 ((stringp date)
18173 (setq date (org-parse-time-string date))
18174 (list (nth 4 date) (nth 3 date) (nth 5 date)))
18175 ((listp date)
18176 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
18178 (defun org-parse-time-string (s &optional nodefault)
18179 "Parse the standard Org-mode time string.
18180 This should be a lot faster than the normal `parse-time-string'.
18181 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18182 hour and minute fields will be nil if not given."
18183 (if (string-match org-ts-regexp0 s)
18184 (list 0
18185 (if (or (match-beginning 8) (not nodefault))
18186 (string-to-number (or (match-string 8 s) "0")))
18187 (if (or (match-beginning 7) (not nodefault))
18188 (string-to-number (or (match-string 7 s) "0")))
18189 (string-to-number (match-string 4 s))
18190 (string-to-number (match-string 3 s))
18191 (string-to-number (match-string 2 s))
18192 nil nil nil)
18193 (make-list 9 0)))
18195 (defun org-timestamp-up (&optional arg)
18196 "Increase the date item at the cursor by one.
18197 If the cursor is on the year, change the year. If it is on the month or
18198 the day, change that.
18199 With prefix ARG, change by that many units."
18200 (interactive "p")
18201 (org-timestamp-change (prefix-numeric-value arg)))
18203 (defun org-timestamp-down (&optional arg)
18204 "Decrease the date item at the cursor by one.
18205 If the cursor is on the year, change the year. If it is on the month or
18206 the day, change that.
18207 With prefix ARG, change by that many units."
18208 (interactive "p")
18209 (org-timestamp-change (- (prefix-numeric-value arg))))
18211 (defun org-timestamp-up-day (&optional arg)
18212 "Increase the date in the time stamp by one day.
18213 With prefix ARG, change that many days."
18214 (interactive "p")
18215 (if (and (not (org-at-timestamp-p t))
18216 (org-on-heading-p))
18217 (org-todo 'up)
18218 (org-timestamp-change (prefix-numeric-value arg) 'day)))
18220 (defun org-timestamp-down-day (&optional arg)
18221 "Decrease the date in the time stamp by one day.
18222 With prefix ARG, change that many days."
18223 (interactive "p")
18224 (if (and (not (org-at-timestamp-p t))
18225 (org-on-heading-p))
18226 (org-todo 'down)
18227 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
18229 (defsubst org-pos-in-match-range (pos n)
18230 (and (match-beginning n)
18231 (<= (match-beginning n) pos)
18232 (>= (match-end n) pos)))
18234 (defun org-at-timestamp-p (&optional inactive-ok)
18235 "Determine if the cursor is in or at a timestamp."
18236 (interactive)
18237 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18238 (pos (point))
18239 (ans (or (looking-at tsr)
18240 (save-excursion
18241 (skip-chars-backward "^[<\n\r\t")
18242 (if (> (point) (point-min)) (backward-char 1))
18243 (and (looking-at tsr)
18244 (> (- (match-end 0) pos) -1))))))
18245 (and ans
18246 (boundp 'org-ts-what)
18247 (setq org-ts-what
18248 (cond
18249 ((= pos (match-beginning 0)) 'bracket)
18250 ((= pos (1- (match-end 0))) 'bracket)
18251 ((org-pos-in-match-range pos 2) 'year)
18252 ((org-pos-in-match-range pos 3) 'month)
18253 ((org-pos-in-match-range pos 7) 'hour)
18254 ((org-pos-in-match-range pos 8) 'minute)
18255 ((or (org-pos-in-match-range pos 4)
18256 (org-pos-in-match-range pos 5)) 'day)
18257 ((and (> pos (or (match-end 8) (match-end 5)))
18258 (< pos (match-end 0)))
18259 (- pos (or (match-end 8) (match-end 5))))
18260 (t 'day))))
18261 ans))
18263 (defun org-toggle-timestamp-type ()
18265 (interactive)
18266 (when (org-at-timestamp-p t)
18267 (save-excursion
18268 (goto-char (match-beginning 0))
18269 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18270 (goto-char (1- (match-end 0)))
18271 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18272 (message "Timestamp is now %sactive"
18273 (if (equal (char-before) ?>) "in" ""))))
18275 (defun org-timestamp-change (n &optional what)
18276 "Change the date in the time stamp at point.
18277 The date will be changed by N times WHAT. WHAT can be `day', `month',
18278 `year', `minute', `second'. If WHAT is not given, the cursor position
18279 in the timestamp determines what will be changed."
18280 (let ((pos (point))
18281 with-hm inactive
18282 org-ts-what
18283 extra
18284 ts time time0)
18285 (if (not (org-at-timestamp-p t))
18286 (error "Not at a timestamp"))
18287 (if (and (not what) (eq org-ts-what 'bracket))
18288 (org-toggle-timestamp-type)
18289 (if (and (not what) (not (eq org-ts-what 'day))
18290 org-display-custom-times
18291 (get-text-property (point) 'display)
18292 (not (get-text-property (1- (point)) 'display)))
18293 (setq org-ts-what 'day))
18294 (setq org-ts-what (or what org-ts-what)
18295 inactive (= (char-after (match-beginning 0)) ?\[)
18296 ts (match-string 0))
18297 (replace-match "")
18298 (if (string-match
18299 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
18301 (setq extra (match-string 1 ts)))
18302 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18303 (setq with-hm t))
18304 (setq time0 (org-parse-time-string ts))
18305 (setq time
18306 (encode-time (or (car time0) 0)
18307 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18308 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18309 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18310 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18311 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18312 (nthcdr 6 time0)))
18313 (when (integerp org-ts-what)
18314 (setq extra (org-modify-ts-extra extra org-ts-what n)))
18315 (if (eq what 'calendar)
18316 (let ((cal-date (org-get-date-from-calendar)))
18317 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18318 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18319 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18320 (setcar time0 (or (car time0) 0))
18321 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18322 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18323 (setq time (apply 'encode-time time0))))
18324 (setq org-last-changed-timestamp
18325 (org-insert-time-stamp time with-hm inactive nil nil extra))
18326 (org-clock-update-time-maybe)
18327 (goto-char pos)
18328 ;; Try to recenter the calendar window, if any
18329 (if (and org-calendar-follow-timestamp-change
18330 (get-buffer-window "*Calendar*" t)
18331 (memq org-ts-what '(day month year)))
18332 (org-recenter-calendar (time-to-days time))))))
18334 ;; FIXME: does not yet work for lead times
18335 (defun org-modify-ts-extra (s pos n)
18336 "Change the different parts of the lead-time and repeat fields in timestamp."
18337 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18338 ng h m new)
18339 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18340 (cond
18341 ((or (org-pos-in-match-range pos 2)
18342 (org-pos-in-match-range pos 3))
18343 (setq m (string-to-number (match-string 3 s))
18344 h (string-to-number (match-string 2 s)))
18345 (if (org-pos-in-match-range pos 2)
18346 (setq h (+ h n))
18347 (setq m (+ m n)))
18348 (if (< m 0) (setq m (+ m 60) h (1- h)))
18349 (if (> m 59) (setq m (- m 60) h (1+ h)))
18350 (setq h (min 24 (max 0 h)))
18351 (setq ng 1 new (format "-%02d:%02d" h m)))
18352 ((org-pos-in-match-range pos 6)
18353 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18354 ((org-pos-in-match-range pos 5)
18355 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
18357 (when ng
18358 (setq s (concat
18359 (substring s 0 (match-beginning ng))
18361 (substring s (match-end ng))))))
18364 (defun org-recenter-calendar (date)
18365 "If the calendar is visible, recenter it to DATE."
18366 (let* ((win (selected-window))
18367 (cwin (get-buffer-window "*Calendar*" t))
18368 (calendar-move-hook nil))
18369 (when cwin
18370 (select-window cwin)
18371 (calendar-goto-date (if (listp date) date
18372 (calendar-gregorian-from-absolute date)))
18373 (select-window win))))
18375 (defun org-goto-calendar (&optional arg)
18376 "Go to the Emacs calendar at the current date.
18377 If there is a time stamp in the current line, go to that date.
18378 A prefix ARG can be used to force the current date."
18379 (interactive "P")
18380 (let ((tsr org-ts-regexp) diff
18381 (calendar-move-hook nil)
18382 (view-calendar-holidays-initially nil)
18383 (view-diary-entries-initially nil))
18384 (if (or (org-at-timestamp-p)
18385 (save-excursion
18386 (beginning-of-line 1)
18387 (looking-at (concat ".*" tsr))))
18388 (let ((d1 (time-to-days (current-time)))
18389 (d2 (time-to-days
18390 (org-time-string-to-time (match-string 1)))))
18391 (setq diff (- d2 d1))))
18392 (calendar)
18393 (calendar-goto-today)
18394 (if (and diff (not arg)) (calendar-forward-day diff))))
18396 (defun org-get-date-from-calendar ()
18397 "Return a list (month day year) of date at point in calendar."
18398 (with-current-buffer "*Calendar*"
18399 (save-match-data
18400 (calendar-cursor-to-date))))
18402 (defun org-date-from-calendar ()
18403 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18404 If there is already a time stamp at the cursor position, update it."
18405 (interactive)
18406 (if (org-at-timestamp-p t)
18407 (org-timestamp-change 0 'calendar)
18408 (let ((cal-date (org-get-date-from-calendar)))
18409 (org-insert-time-stamp
18410 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18412 ;; Make appt aware of appointments from the agenda
18413 ;;;###autoload
18414 (defun org-agenda-to-appt (&optional filter)
18415 "Activate appointments found in `org-agenda-files'.
18416 When prefixed, prompt for a regular expression and use it as a
18417 filter: only add entries if they match this regular expression.
18419 FILTER can be a string. In this case, use this string as a
18420 regular expression to filter results.
18422 FILTER can also be an alist, with the car of each cell being
18423 either 'headline or 'category. For example:
18425 '((headline \"IMPORTANT\")
18426 (category \"Work\"))
18428 will only add headlines containing IMPORTANT or headlines
18429 belonging to the category \"Work\"."
18430 (interactive "P")
18431 (require 'calendar)
18432 (if (equal filter '(4))
18433 (setq filter (read-from-minibuffer "Regexp filter: ")))
18434 (let* ((cnt 0) ; count added events
18435 (org-agenda-new-buffers nil)
18436 (today (org-date-to-gregorian
18437 (time-to-days (current-time))))
18438 (files (org-agenda-files)) entries file)
18439 ;; Get all entries which may contain an appt
18440 (while (setq file (pop files))
18441 (setq entries
18442 (append entries
18443 (org-agenda-get-day-entries
18444 file today
18445 :timestamp :scheduled :deadline))))
18446 (setq entries (delq nil entries))
18447 ;; Map thru entries and find if they pass thru the filter
18448 (mapc
18449 (lambda(x)
18450 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18451 (cat (get-text-property 1 'org-category x))
18452 (tod (get-text-property 1 'time-of-day x))
18453 (ok (or (null filter)
18454 (and (stringp filter) (string-match filter evt))
18455 (and (listp filter)
18456 (or (string-match
18457 (cadr (assoc 'category filter)) cat)
18458 (string-match
18459 (cadr (assoc 'headline filter)) evt))))))
18460 ;; FIXME: Shall we remove text-properties for the appt text?
18461 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18462 (when (and ok tod)
18463 (setq tod (number-to-string tod)
18464 tod (when (string-match
18465 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18466 (concat (match-string 1 tod) ":"
18467 (match-string 2 tod))))
18468 (appt-add tod evt)
18469 (setq cnt (1+ cnt))))) entries)
18470 (org-release-buffers org-agenda-new-buffers)
18471 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" ""))))
18473 ;;; The clock for measuring work time.
18475 (defvar org-mode-line-string "")
18476 (put 'org-mode-line-string 'risky-local-variable t)
18478 (defvar org-mode-line-timer nil)
18479 (defvar org-clock-heading "")
18480 (defvar org-clock-start-time "")
18482 (defun org-update-mode-line ()
18483 (let* ((delta (- (time-to-seconds (current-time))
18484 (time-to-seconds org-clock-start-time)))
18485 (h (floor delta 3600))
18486 (m (floor (- delta (* 3600 h)) 60)))
18487 (setq org-mode-line-string
18488 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18489 'help-echo "Org-mode clock is running"))
18490 (force-mode-line-update)))
18492 (defvar org-clock-marker (make-marker)
18493 "Marker recording the last clock-in.")
18494 (defvar org-clock-mode-line-entry nil
18495 "Information for the modeline about the running clock.")
18497 (defun org-clock-in ()
18498 "Start the clock on the current item.
18499 If necessary, clock-out of the currently active clock."
18500 (interactive)
18501 (org-clock-out t)
18502 (let (ts)
18503 (save-excursion
18504 (org-back-to-heading t)
18505 (when (and org-clock-in-switch-to-state
18506 (not (looking-at (concat outline-regexp "[ \t]*"
18507 org-clock-in-switch-to-state
18508 "\\>"))))
18509 (org-todo org-clock-in-switch-to-state))
18510 (if (and org-clock-heading-function
18511 (functionp org-clock-heading-function))
18512 (setq org-clock-heading (funcall org-clock-heading-function))
18513 (if (looking-at org-complex-heading-regexp)
18514 (setq org-clock-heading (match-string 4))
18515 (setq org-clock-heading "???")))
18516 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18517 (org-clock-find-position)
18519 (insert "\n") (backward-char 1)
18520 (indent-relative)
18521 (insert org-clock-string " ")
18522 (setq org-clock-start-time (current-time))
18523 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18524 (move-marker org-clock-marker (point) (buffer-base-buffer))
18525 (or global-mode-string (setq global-mode-string '("")))
18526 (or (memq 'org-mode-line-string global-mode-string)
18527 (setq global-mode-string
18528 (append global-mode-string '(org-mode-line-string))))
18529 (org-update-mode-line)
18530 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18531 (message "Clock started at %s" ts))))
18533 (defun org-clock-find-position ()
18534 "Find the location where the next clock line should be inserted."
18535 (org-back-to-heading t)
18536 (catch 'exit
18537 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
18538 (re (concat "^[ \t]*" org-clock-string))
18539 (cnt 0)
18540 first last)
18541 (goto-char beg)
18542 (when (eobp) (newline) (setq end (max (point) end)))
18543 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
18544 ;; we seem to have a CLOCK drawer, so go there.
18545 (beginning-of-line 2)
18546 (throw 'exit t))
18547 ;; Lets count the CLOCK lines
18548 (goto-char beg)
18549 (while (re-search-forward re end t)
18550 (setq first (or first (match-beginning 0))
18551 last (match-beginning 0)
18552 cnt (1+ cnt)))
18553 (when (and (integerp org-clock-into-drawer)
18554 (>= (1+ cnt) org-clock-into-drawer))
18555 ;; Wrap current entries into a new drawer
18556 (goto-char last)
18557 (beginning-of-line 2)
18558 (if (org-at-item-p) (org-end-of-item))
18559 (insert ":END:\n")
18560 (beginning-of-line 0)
18561 (org-indent-line-function)
18562 (goto-char first)
18563 (insert ":CLOCK:\n")
18564 (beginning-of-line 0)
18565 (org-indent-line-function)
18566 (org-flag-drawer t)
18567 (beginning-of-line 2)
18568 (throw 'exit nil))
18570 (goto-char beg)
18571 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18572 (not (equal (match-string 1) org-clock-string)))
18573 ;; Planning info, skip to after it
18574 (beginning-of-line 2)
18575 (or (bolp) (newline)))
18576 (when (eq t org-clock-into-drawer)
18577 (insert ":CLOCK:\n:END:\n")
18578 (beginning-of-line -1)
18579 (org-indent-line-function)
18580 (org-flag-drawer t)
18581 (beginning-of-line 2)
18582 (org-indent-line-function)))))
18584 (defun org-clock-out (&optional fail-quietly)
18585 "Stop the currently running clock.
18586 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
18587 (interactive)
18588 (catch 'exit
18589 (if (not (marker-buffer org-clock-marker))
18590 (if fail-quietly (throw 'exit t) (error "No active clock")))
18591 (let (ts te s h m)
18592 (save-excursion
18593 (set-buffer (marker-buffer org-clock-marker))
18594 (goto-char org-clock-marker)
18595 (beginning-of-line 1)
18596 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18597 (equal (match-string 1) org-clock-string))
18598 (setq ts (match-string 2))
18599 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
18600 (goto-char (match-end 0))
18601 (delete-region (point) (point-at-eol))
18602 (insert "--")
18603 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18604 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
18605 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
18606 h (floor (/ s 3600))
18607 s (- s (* 3600 h))
18608 m (floor (/ s 60))
18609 s (- s (* 60 s)))
18610 (insert " => " (format "%2d:%02d" h m))
18611 (move-marker org-clock-marker nil)
18612 (let* ((logging (save-match-data (org-entry-get nil "LOGGING" t)))
18613 (org-log-done (org-parse-local-options logging 'org-log-done))
18614 (org-log-repeat (org-parse-local-options logging 'org-log-repeat)))
18615 (org-add-log-maybe 'clock-out))
18616 (when org-mode-line-timer
18617 (cancel-timer org-mode-line-timer)
18618 (setq org-mode-line-timer nil))
18619 (setq global-mode-string
18620 (delq 'org-mode-line-string global-mode-string))
18621 (force-mode-line-update)
18622 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
18624 (defun org-clock-cancel ()
18625 "Cancel the running clock be removing the start timestamp."
18626 (interactive)
18627 (if (not (marker-buffer org-clock-marker))
18628 (error "No active clock"))
18629 (save-excursion
18630 (set-buffer (marker-buffer org-clock-marker))
18631 (goto-char org-clock-marker)
18632 (delete-region (1- (point-at-bol)) (point-at-eol)))
18633 (setq global-mode-string
18634 (delq 'org-mode-line-string global-mode-string))
18635 (force-mode-line-update)
18636 (message "Clock canceled"))
18638 (defun org-clock-goto (&optional delete-windows)
18639 "Go to the currently clocked-in entry."
18640 (interactive "P")
18641 (if (not (marker-buffer org-clock-marker))
18642 (error "No active clock"))
18643 (switch-to-buffer-other-window
18644 (marker-buffer org-clock-marker))
18645 (if delete-windows (delete-other-windows))
18646 (goto-char org-clock-marker)
18647 (org-show-entry)
18648 (org-back-to-heading)
18649 (recenter))
18651 (defvar org-clock-file-total-minutes nil
18652 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
18653 (make-variable-buffer-local 'org-clock-file-total-minutes)
18655 (defun org-clock-sum (&optional tstart tend)
18656 "Sum the times for each subtree.
18657 Puts the resulting times in minutes as a text property on each headline."
18658 (interactive)
18659 (let* ((bmp (buffer-modified-p))
18660 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
18661 org-clock-string
18662 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
18663 (lmax 30)
18664 (ltimes (make-vector lmax 0))
18665 (t1 0)
18666 (level 0)
18667 ts te dt
18668 time)
18669 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
18670 (save-excursion
18671 (goto-char (point-max))
18672 (while (re-search-backward re nil t)
18673 (cond
18674 ((match-end 2)
18675 ;; Two time stamps
18676 (setq ts (match-string 2)
18677 te (match-string 3)
18678 ts (time-to-seconds
18679 (apply 'encode-time (org-parse-time-string ts)))
18680 te (time-to-seconds
18681 (apply 'encode-time (org-parse-time-string te)))
18682 ts (if tstart (max ts tstart) ts)
18683 te (if tend (min te tend) te)
18684 dt (- te ts)
18685 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
18686 ((match-end 4)
18687 ;; A naket time
18688 (setq t1 (+ t1 (string-to-number (match-string 5))
18689 (* 60 (string-to-number (match-string 4))))))
18690 (t ;; A headline
18691 (setq level (- (match-end 1) (match-beginning 1)))
18692 (when (or (> t1 0) (> (aref ltimes level) 0))
18693 (loop for l from 0 to level do
18694 (aset ltimes l (+ (aref ltimes l) t1)))
18695 (setq t1 0 time (aref ltimes level))
18696 (loop for l from level to (1- lmax) do
18697 (aset ltimes l 0))
18698 (goto-char (match-beginning 0))
18699 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
18700 (setq org-clock-file-total-minutes (aref ltimes 0)))
18701 (set-buffer-modified-p bmp)))
18703 (defun org-clock-display (&optional total-only)
18704 "Show subtree times in the entire buffer.
18705 If TOTAL-ONLY is non-nil, only show the total time for the entire file
18706 in the echo area."
18707 (interactive)
18708 (org-remove-clock-overlays)
18709 (let (time h m p)
18710 (org-clock-sum)
18711 (unless total-only
18712 (save-excursion
18713 (goto-char (point-min))
18714 (while (or (and (equal (setq p (point)) (point-min))
18715 (get-text-property p :org-clock-minutes))
18716 (setq p (next-single-property-change
18717 (point) :org-clock-minutes)))
18718 (goto-char p)
18719 (when (setq time (get-text-property p :org-clock-minutes))
18720 (org-put-clock-overlay time (funcall outline-level))))
18721 (setq h (/ org-clock-file-total-minutes 60)
18722 m (- org-clock-file-total-minutes (* 60 h)))
18723 ;; Arrange to remove the overlays upon next change.
18724 (when org-remove-highlights-with-change
18725 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
18726 nil 'local))))
18727 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
18729 (defvar org-clock-overlays nil)
18730 (make-variable-buffer-local 'org-clock-overlays)
18732 (defun org-put-clock-overlay (time &optional level)
18733 "Put an overlays on the current line, displaying TIME.
18734 If LEVEL is given, prefix time with a corresponding number of stars.
18735 This creates a new overlay and stores it in `org-clock-overlays', so that it
18736 will be easy to remove."
18737 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
18738 (l (if level (org-get-legal-level level 0) 0))
18739 (off 0)
18740 ov tx)
18741 (move-to-column c)
18742 (unless (eolp) (skip-chars-backward "^ \t"))
18743 (skip-chars-backward " \t")
18744 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
18745 tx (concat (buffer-substring (1- (point)) (point))
18746 (make-string (+ off (max 0 (- c (current-column)))) ?.)
18747 (org-add-props (format "%s %2d:%02d%s"
18748 (make-string l ?*) h m
18749 (make-string (- 10 l) ?\ ))
18750 '(face secondary-selection))
18751 ""))
18752 (if (not (featurep 'xemacs))
18753 (org-overlay-put ov 'display tx)
18754 (org-overlay-put ov 'invisible t)
18755 (org-overlay-put ov 'end-glyph (make-glyph tx)))
18756 (push ov org-clock-overlays)))
18758 (defun org-remove-clock-overlays (&optional beg end noremove)
18759 "Remove the occur highlights from the buffer.
18760 BEG and END are ignored. If NOREMOVE is nil, remove this function
18761 from the `before-change-functions' in the current buffer."
18762 (interactive)
18763 (unless org-inhibit-highlight-removal
18764 (mapc 'org-delete-overlay org-clock-overlays)
18765 (setq org-clock-overlays nil)
18766 (unless noremove
18767 (remove-hook 'before-change-functions
18768 'org-remove-clock-overlays 'local))))
18770 (defun org-clock-out-if-current ()
18771 "Clock out if the current entry contains the running clock.
18772 This is used to stop the clock after a TODO entry is marked DONE,
18773 and is only done if the variable `org-clock-out-when-done' is not nil."
18774 (when (and org-clock-out-when-done
18775 (member state org-done-keywords)
18776 (equal (marker-buffer org-clock-marker) (current-buffer))
18777 (< (point) org-clock-marker)
18778 (> (save-excursion (outline-next-heading) (point))
18779 org-clock-marker))
18780 ;; Clock out, but don't accept a logging message for this.
18781 (let ((org-log-done (if (and (listp org-log-done)
18782 (member 'clock-out org-log-done))
18783 '(done)
18784 org-log-done)))
18785 (org-clock-out))))
18787 (add-hook 'org-after-todo-state-change-hook
18788 'org-clock-out-if-current)
18790 (defun org-check-running-clock ()
18791 "Check if the current buffer contains the running clock.
18792 If yes, offer to stop it and to save the buffer with the changes."
18793 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
18794 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
18795 (buffer-name))))
18796 (org-clock-out)
18797 (when (y-or-n-p "Save changed buffer?")
18798 (save-buffer))))
18800 (defun org-clock-report (&optional arg)
18801 "Create a table containing a report about clocked time.
18802 If the cursor is inside an existing clocktable block, then the table
18803 will be updated. If not, a new clocktable will be inserted.
18804 When called with a prefix argument, move to the first clock table in the
18805 buffer and update it."
18806 (interactive "P")
18807 (org-remove-clock-overlays)
18808 (when arg (org-find-dblock "clocktable"))
18809 (if (org-in-clocktable-p)
18810 (goto-char (org-in-clocktable-p))
18811 (org-create-dblock (list :name "clocktable"
18812 :maxlevel 2 :scope 'file)))
18813 (org-update-dblock))
18815 (defun org-in-clocktable-p ()
18816 "Check if the cursor is in a clocktable."
18817 (let ((pos (point)) start)
18818 (save-excursion
18819 (end-of-line 1)
18820 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
18821 (setq start (match-beginning 0))
18822 (re-search-forward "^#\\+END:.*" nil t)
18823 (>= (match-end 0) pos)
18824 start))))
18826 (defun org-clock-update-time-maybe ()
18827 "If this is a CLOCK line, update it and return t.
18828 Otherwise, return nil."
18829 (interactive)
18830 (save-excursion
18831 (beginning-of-line 1)
18832 (skip-chars-forward " \t")
18833 (when (looking-at org-clock-string)
18834 (let ((re (concat "[ \t]*" org-clock-string
18835 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
18836 "\\([ \t]*=>.*\\)?"))
18837 ts te h m s)
18838 (if (not (looking-at re))
18840 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
18841 (end-of-line 1)
18842 (setq ts (match-string 1)
18843 te (match-string 2))
18844 (setq s (- (time-to-seconds
18845 (apply 'encode-time (org-parse-time-string te)))
18846 (time-to-seconds
18847 (apply 'encode-time (org-parse-time-string ts))))
18848 h (floor (/ s 3600))
18849 s (- s (* 3600 h))
18850 m (floor (/ s 60))
18851 s (- s (* 60 s)))
18852 (insert " => " (format "%2d:%02d" h m))
18853 t)))))
18855 (defun org-clock-special-range (key &optional time as-strings)
18856 "Return two times bordering a special time range.
18857 Key is a symbol specifying the range and can be one of `today', `yesterday',
18858 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
18859 A week starts Monday 0:00 and ends Sunday 24:00.
18860 The range is determined relative to TIME. TIME defaults to the current time.
18861 The return value is a cons cell with two internal times like the ones
18862 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
18863 the returned times will be formatted strings."
18864 (let* ((tm (decode-time (or time (current-time))))
18865 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
18866 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
18867 (dow (nth 6 tm))
18868 s1 m1 h1 d1 month1 y1 diff ts te fm)
18869 (cond
18870 ((eq key 'today)
18871 (setq h 0 m 0 h1 24 m1 0))
18872 ((eq key 'yesterday)
18873 (setq d (1- d) h 0 m 0 h1 24 m1 0))
18874 ((eq key 'thisweek)
18875 (setq diff (if (= dow 0) 6 (1- dow))
18876 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18877 ((eq key 'lastweek)
18878 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
18879 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18880 ((eq key 'thismonth)
18881 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
18882 ((eq key 'lastmonth)
18883 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
18884 ((eq key 'thisyear)
18885 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
18886 ((eq key 'lastyear)
18887 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
18888 (t (error "No such time block %s" key)))
18889 (setq ts (encode-time s m h d month y)
18890 te (encode-time (or s1 s) (or m1 m) (or h1 h)
18891 (or d1 d) (or month1 month) (or y1 y)))
18892 (setq fm (cdr org-time-stamp-formats))
18893 (if as-strings
18894 (cons (format-time-string fm ts) (format-time-string fm te))
18895 (cons ts te))))
18897 (defun org-dblock-write:clocktable (params)
18898 "Write the standard clocktable."
18899 (catch 'exit
18900 (let* ((hlchars '((1 . "*") (2 . "/")))
18901 (ins (make-marker))
18902 (total-time nil)
18903 (scope (plist-get params :scope))
18904 (tostring (plist-get params :tostring))
18905 (multifile (plist-get params :multifile))
18906 (header (plist-get params :header))
18907 (maxlevel (or (plist-get params :maxlevel) 3))
18908 (step (plist-get params :step))
18909 (emph (plist-get params :emphasize))
18910 (ts (plist-get params :tstart))
18911 (te (plist-get params :tend))
18912 (block (plist-get params :block))
18913 ipos time h m p level hlc hdl
18914 cc beg end pos tbl)
18915 (when step
18916 (org-clocktable-steps params)
18917 (throw 'exit nil))
18918 (when block
18919 (setq cc (org-clock-special-range block nil t)
18920 ts (car cc) te (cdr cc)))
18921 (if ts (setq ts (time-to-seconds
18922 (apply 'encode-time (org-parse-time-string ts)))))
18923 (if te (setq te (time-to-seconds
18924 (apply 'encode-time (org-parse-time-string te)))))
18925 (move-marker ins (point))
18926 (setq ipos (point))
18928 ;; Get the right scope
18929 (setq pos (point))
18930 (save-restriction
18931 (cond
18932 ((not scope))
18933 ((eq scope 'file) (widen))
18934 ((eq scope 'subtree) (org-narrow-to-subtree))
18935 ((eq scope 'tree)
18936 (while (org-up-heading-safe))
18937 (org-narrow-to-subtree))
18938 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
18939 (symbol-name scope)))
18940 (setq level (string-to-number (match-string 1 (symbol-name scope))))
18941 (catch 'exit
18942 (while (org-up-heading-safe)
18943 (looking-at outline-regexp)
18944 (if (<= (org-reduced-level (funcall outline-level)) level)
18945 (throw 'exit nil))))
18946 (org-narrow-to-subtree))
18947 ((or (listp scope) (eq scope 'agenda))
18948 (let* ((files (if (listp scope) scope (org-agenda-files)))
18949 (scope 'agenda)
18950 (p1 (copy-sequence params))
18951 file)
18952 (plist-put p1 :tostring t)
18953 (plist-put p1 :multifile t)
18954 (plist-put p1 :scope 'file)
18955 (org-prepare-agenda-buffers files)
18956 (while (setq file (pop files))
18957 (with-current-buffer (find-buffer-visiting file)
18958 (push (org-clocktable-add-file
18959 file (org-dblock-write:clocktable p1)) tbl)
18960 (setq total-time (+ (or total-time 0)
18961 org-clock-file-total-minutes)))))))
18962 (goto-char pos)
18964 (unless (eq scope 'agenda)
18965 (org-clock-sum ts te)
18966 (goto-char (point-min))
18967 (while (setq p (next-single-property-change (point) :org-clock-minutes))
18968 (goto-char p)
18969 (when (setq time (get-text-property p :org-clock-minutes))
18970 (save-excursion
18971 (beginning-of-line 1)
18972 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
18973 (setq level (org-reduced-level
18974 (- (match-end 1) (match-beginning 1))))
18975 (<= level maxlevel))
18976 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
18977 hdl (match-string 2)
18978 h (/ time 60)
18979 m (- time (* 60 h)))
18980 (if (and (not multifile) (= level 1)) (push "|-" tbl))
18981 (push (concat
18982 "| " (int-to-string level) "|" hlc hdl hlc " |"
18983 (make-string (1- level) ?|)
18984 hlc (format "%d:%02d" h m) hlc
18985 " |") tbl))))))
18986 (setq tbl (nreverse tbl))
18987 (if tostring
18988 (if tbl (mapconcat 'identity tbl "\n") nil)
18989 (goto-char ins)
18990 (insert-before-markers
18991 (or header
18992 (concat
18993 "Clock summary at ["
18994 (substring
18995 (format-time-string (cdr org-time-stamp-formats))
18996 1 -1)
18997 "]."
18998 (if block
18999 (format " Considered range is /%s/." block)
19001 "\n\n"))
19002 (if (eq scope 'agenda) "|File" "")
19003 "|L|Headline|Time|\n")
19004 (setq total-time (or total-time org-clock-file-total-minutes)
19005 h (/ total-time 60)
19006 m (- total-time (* 60 h)))
19007 (insert-before-markers
19008 "|-\n|"
19009 (if (eq scope 'agenda) "|" "")
19011 "*Total time*| "
19012 (format "*%d:%02d*" h m)
19013 "|\n|-\n")
19014 (setq tbl (delq nil tbl))
19015 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
19016 (equal (substring (car tbl) 0 2) "|-"))
19017 (pop tbl))
19018 (insert-before-markers (mapconcat
19019 'identity (delq nil tbl)
19020 (if (eq scope 'agenda) "\n|-\n" "\n")))
19021 (backward-delete-char 1)
19022 (goto-char ipos)
19023 (skip-chars-forward "^|")
19024 (org-table-align))))))
19026 (defun org-clocktable-steps (params)
19027 (let* ((p1 (copy-sequence params))
19028 (ts (plist-get p1 :tstart))
19029 (te (plist-get p1 :tend))
19030 (step0 (plist-get p1 :step))
19031 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
19032 (block (plist-get p1 :block))
19034 (when block
19035 (setq cc (org-clock-special-range block nil t)
19036 ts (car cc) te (cdr cc)))
19037 (if ts (setq ts (time-to-seconds
19038 (apply 'encode-time (org-parse-time-string ts)))))
19039 (if te (setq te (time-to-seconds
19040 (apply 'encode-time (org-parse-time-string te)))))
19041 (plist-put p1 :header "")
19042 (plist-put p1 :step nil)
19043 (plist-put p1 :block nil)
19044 (while (< ts te)
19045 (or (bolp) (insert "\n"))
19046 (plist-put p1 :tstart (format-time-string
19047 (car org-time-stamp-formats)
19048 (seconds-to-time ts)))
19049 (plist-put p1 :tend (format-time-string
19050 (car org-time-stamp-formats)
19051 (seconds-to-time (setq ts (+ ts step)))))
19052 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
19053 (plist-get p1 :tstart) "\n")
19054 (org-dblock-write:clocktable p1)
19055 (re-search-forward "#\\+END:")
19056 (end-of-line 0))))
19059 (defun org-clocktable-add-file (file table)
19060 (if table
19061 (let ((lines (org-split-string table "\n"))
19062 (ff (file-name-nondirectory file)))
19063 (mapconcat 'identity
19064 (mapcar (lambda (x)
19065 (if (string-match org-table-dataline-regexp x)
19066 (concat "|" ff x)
19068 lines)
19069 "\n"))))
19071 ;; FIXME: I don't think anybody uses this, ask David
19072 (defun org-collect-clock-time-entries ()
19073 "Return an internal list with clocking information.
19074 This list has one entry for each CLOCK interval.
19075 FIXME: describe the elements."
19076 (interactive)
19077 (let ((re (concat "^[ \t]*" org-clock-string
19078 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
19079 rtn beg end next cont level title total closedp leafp
19080 clockpos titlepos h m donep)
19081 (save-excursion
19082 (org-clock-sum)
19083 (goto-char (point-min))
19084 (while (re-search-forward re nil t)
19085 (setq clockpos (match-beginning 0)
19086 beg (match-string 1) end (match-string 2)
19087 cont (match-end 0))
19088 (setq beg (apply 'encode-time (org-parse-time-string beg))
19089 end (apply 'encode-time (org-parse-time-string end)))
19090 (org-back-to-heading t)
19091 (setq donep (org-entry-is-done-p))
19092 (setq titlepos (point)
19093 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
19094 h (/ total 60) m (- total (* 60 h))
19095 total (cons h m))
19096 (looking-at "\\(\\*+\\) +\\(.*\\)")
19097 (setq level (- (match-end 1) (match-beginning 1))
19098 title (org-match-string-no-properties 2))
19099 (save-excursion (outline-next-heading) (setq next (point)))
19100 (setq closedp (re-search-forward org-closed-time-regexp next t))
19101 (goto-char next)
19102 (setq leafp (and (looking-at "^\\*+ ")
19103 (<= (- (match-end 0) (point)) level)))
19104 (push (list beg end clockpos closedp donep
19105 total title titlepos level leafp)
19106 rtn)
19107 (goto-char cont)))
19108 (nreverse rtn)))
19110 ;;;; Agenda, and Diary Integration
19112 ;;; Define the Org-agenda-mode
19114 (defvar org-agenda-mode-map (make-sparse-keymap)
19115 "Keymap for `org-agenda-mode'.")
19117 (defvar org-agenda-menu) ; defined later in this file.
19118 (defvar org-agenda-follow-mode nil)
19119 (defvar org-agenda-show-log nil)
19120 (defvar org-agenda-redo-command nil)
19121 (defvar org-agenda-mode-hook nil)
19122 (defvar org-agenda-type nil)
19123 (defvar org-agenda-force-single-file nil)
19125 (defun org-agenda-mode ()
19126 "Mode for time-sorted view on action items in Org-mode files.
19128 The following commands are available:
19130 \\{org-agenda-mode-map}"
19131 (interactive)
19132 (kill-all-local-variables)
19133 (setq org-agenda-undo-list nil
19134 org-agenda-pending-undo-list nil)
19135 (setq major-mode 'org-agenda-mode)
19136 ;; Keep global-font-lock-mode from turning on font-lock-mode
19137 (org-set-local 'font-lock-global-modes (list 'not major-mode))
19138 (setq mode-name "Org-Agenda")
19139 (use-local-map org-agenda-mode-map)
19140 (easy-menu-add org-agenda-menu)
19141 (if org-startup-truncated (setq truncate-lines t))
19142 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
19143 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
19144 ;; Make sure properties are removed when copying text
19145 (when (boundp 'buffer-substring-filters)
19146 (org-set-local 'buffer-substring-filters
19147 (cons (lambda (x)
19148 (set-text-properties 0 (length x) nil x) x)
19149 buffer-substring-filters)))
19150 (unless org-agenda-keep-modes
19151 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
19152 org-agenda-show-log nil))
19153 (easy-menu-change
19154 '("Agenda") "Agenda Files"
19155 (append
19156 (list
19157 (vector
19158 (if (get 'org-agenda-files 'org-restrict)
19159 "Restricted to single file"
19160 "Edit File List")
19161 '(org-edit-agenda-file-list)
19162 (not (get 'org-agenda-files 'org-restrict)))
19163 "--")
19164 (mapcar 'org-file-menu-entry (org-agenda-files))))
19165 (org-agenda-set-mode-name)
19166 (apply
19167 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
19168 (list 'org-agenda-mode-hook)))
19170 (substitute-key-definition 'undo 'org-agenda-undo
19171 org-agenda-mode-map global-map)
19172 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
19173 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
19174 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
19175 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
19176 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
19177 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
19178 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
19179 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
19180 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
19181 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
19182 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
19183 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
19184 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
19185 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
19186 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
19187 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
19188 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
19189 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
19190 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
19191 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
19192 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
19193 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
19194 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
19195 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
19196 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
19197 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
19198 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
19199 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
19200 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
19202 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
19203 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
19204 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
19205 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
19206 (while l (org-defkey org-agenda-mode-map
19207 (int-to-string (pop l)) 'digit-argument)))
19209 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
19210 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
19211 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
19212 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
19213 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
19214 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
19215 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
19216 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
19217 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
19218 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
19219 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
19220 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
19221 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
19222 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
19223 (org-defkey org-agenda-mode-map "n" 'next-line)
19224 (org-defkey org-agenda-mode-map "p" 'previous-line)
19225 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
19226 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
19227 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
19228 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
19229 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
19230 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
19231 (eval-after-load "calendar"
19232 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
19233 'org-calendar-goto-agenda))
19234 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
19235 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
19236 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
19237 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
19238 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
19239 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
19240 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
19241 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
19242 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
19243 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
19244 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
19245 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19246 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
19247 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
19248 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
19249 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
19250 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
19251 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
19252 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
19253 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
19254 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
19255 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
19257 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
19258 "Local keymap for agenda entries from Org-mode.")
19260 (org-defkey org-agenda-keymap
19261 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
19262 (org-defkey org-agenda-keymap
19263 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
19264 (when org-agenda-mouse-1-follows-link
19265 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
19266 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
19267 '("Agenda"
19268 ("Agenda Files")
19269 "--"
19270 ["Show" org-agenda-show t]
19271 ["Go To (other window)" org-agenda-goto t]
19272 ["Go To (this window)" org-agenda-switch-to t]
19273 ["Follow Mode" org-agenda-follow-mode
19274 :style toggle :selected org-agenda-follow-mode :active t]
19275 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
19276 "--"
19277 ["Cycle TODO" org-agenda-todo t]
19278 ["Archive subtree" org-agenda-archive t]
19279 ["Delete subtree" org-agenda-kill t]
19280 "--"
19281 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
19282 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
19283 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
19284 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
19285 "--"
19286 ("Tags and Properties"
19287 ["Show all Tags" org-agenda-show-tags t]
19288 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
19289 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
19290 "--"
19291 ["Column View" org-columns t])
19292 ("Date/Schedule"
19293 ["Schedule" org-agenda-schedule t]
19294 ["Set Deadline" org-agenda-deadline t]
19295 "--"
19296 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19297 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19298 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19299 ("Clock"
19300 ["Clock in" org-agenda-clock-in t]
19301 ["Clock out" org-agenda-clock-out t]
19302 ["Clock cancel" org-agenda-clock-cancel t]
19303 ["Goto running clock" org-clock-goto t])
19304 ("Priority"
19305 ["Set Priority" org-agenda-priority t]
19306 ["Increase Priority" org-agenda-priority-up t]
19307 ["Decrease Priority" org-agenda-priority-down t]
19308 ["Show Priority" org-agenda-show-priority t])
19309 ("Calendar/Diary"
19310 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19311 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19312 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19313 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19314 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19315 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19316 "--"
19317 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19318 "--"
19319 ("View"
19320 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19321 :style radio :selected (equal org-agenda-ndays 1)]
19322 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19323 :style radio :selected (equal org-agenda-ndays 7)]
19324 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19325 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19326 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19327 :style radio :selected (member org-agenda-ndays '(365 366))]
19328 "--"
19329 ["Show Logbook entries" org-agenda-log-mode
19330 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19331 ["Include Diary" org-agenda-toggle-diary
19332 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19333 ["Use Time Grid" org-agenda-toggle-time-grid
19334 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19335 ["Write view to file" org-write-agenda t]
19336 ["Rebuild buffer" org-agenda-redo t]
19337 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19338 "--"
19339 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19340 "--"
19341 ["Quit" org-agenda-quit t]
19342 ["Exit and Release Buffers" org-agenda-exit t]
19345 ;;; Agenda undo
19347 (defvar org-agenda-allow-remote-undo t
19348 "Non-nil means, allow remote undo from the agenda buffer.")
19349 (defvar org-agenda-undo-list nil
19350 "List of undoable operations in the agenda since last refresh.")
19351 (defvar org-agenda-undo-has-started-in nil
19352 "Buffers that have already seen `undo-start' in the current undo sequence.")
19353 (defvar org-agenda-pending-undo-list nil
19354 "In a series of undo commands, this is the list of remaning undo items.")
19356 (defmacro org-if-unprotected (&rest body)
19357 "Execute BODY if there is no `org-protected' text property at point."
19358 (declare (debug t))
19359 `(unless (get-text-property (point) 'org-protected)
19360 ,@body))
19362 (defmacro org-with-remote-undo (_buffer &rest _body)
19363 "Execute BODY while recording undo information in two buffers."
19364 (declare (indent 1) (debug t))
19365 `(let ((_cline (org-current-line))
19366 (_cmd this-command)
19367 (_buf1 (current-buffer))
19368 (_buf2 ,_buffer)
19369 (_undo1 buffer-undo-list)
19370 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19371 _c1 _c2)
19372 ,@_body
19373 (when org-agenda-allow-remote-undo
19374 (setq _c1 (org-verify-change-for-undo
19375 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19376 _c2 (org-verify-change-for-undo
19377 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19378 (when (or _c1 _c2)
19379 ;; make sure there are undo boundaries
19380 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19381 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19382 ;; remember which buffer to undo
19383 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19384 org-agenda-undo-list)))))
19386 (defun org-agenda-undo ()
19387 "Undo a remote editing step in the agenda.
19388 This undoes changes both in the agenda buffer and in the remote buffer
19389 that have been changed along."
19390 (interactive)
19391 (or org-agenda-allow-remote-undo
19392 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19393 (if (not (eq this-command last-command))
19394 (setq org-agenda-undo-has-started-in nil
19395 org-agenda-pending-undo-list org-agenda-undo-list))
19396 (if (not org-agenda-pending-undo-list)
19397 (error "No further undo information"))
19398 (let* ((entry (pop org-agenda-pending-undo-list))
19399 buf line cmd rembuf)
19400 (setq cmd (pop entry) line (pop entry))
19401 (setq rembuf (nth 2 entry))
19402 (org-with-remote-undo rembuf
19403 (while (bufferp (setq buf (pop entry)))
19404 (if (pop entry)
19405 (with-current-buffer buf
19406 (let ((last-undo-buffer buf)
19407 (inhibit-read-only t))
19408 (unless (memq buf org-agenda-undo-has-started-in)
19409 (push buf org-agenda-undo-has-started-in)
19410 (make-local-variable 'pending-undo-list)
19411 (undo-start))
19412 (while (and pending-undo-list
19413 (listp pending-undo-list)
19414 (not (car pending-undo-list)))
19415 (pop pending-undo-list))
19416 (undo-more 1))))))
19417 (goto-line line)
19418 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19420 (defun org-verify-change-for-undo (l1 l2)
19421 "Verify that a real change occurred between the undo lists L1 and L2."
19422 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19423 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19424 (not (eq l1 l2)))
19426 ;;; Agenda dispatch
19428 (defvar org-agenda-restrict nil)
19429 (defvar org-agenda-restrict-begin (make-marker))
19430 (defvar org-agenda-restrict-end (make-marker))
19431 (defvar org-agenda-last-dispatch-buffer nil)
19432 (defvar org-agenda-overriding-restriction nil)
19434 ;;;###autoload
19435 (defun org-agenda (arg &optional keys restriction)
19436 "Dispatch agenda commands to collect entries to the agenda buffer.
19437 Prompts for a command to execute. Any prefix arg will be passed
19438 on to the selected command. The default selections are:
19440 a Call `org-agenda-list' to display the agenda for current day or week.
19441 t Call `org-todo-list' to display the global todo list.
19442 T Call `org-todo-list' to display the global todo list, select only
19443 entries with a specific TODO keyword (the user gets a prompt).
19444 m Call `org-tags-view' to display headlines with tags matching
19445 a condition (the user is prompted for the condition).
19446 M Like `m', but select only TODO entries, no ordinary headlines.
19447 L Create a timeline for the current buffer.
19448 e Export views to associated files.
19450 More commands can be added by configuring the variable
19451 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19452 searches can be pre-defined in this way.
19454 If the current buffer is in Org-mode and visiting a file, you can also
19455 first press `<' once to indicate that the agenda should be temporarily
19456 \(until the next use of \\[org-agenda]) restricted to the current file.
19457 Pressing `<' twice means to restrict to the current subtree or region
19458 \(if active)."
19459 (interactive "P")
19460 (catch 'exit
19461 (let* ((prefix-descriptions nil)
19462 (org-agenda-custom-commands-orig org-agenda-custom-commands)
19463 (org-agenda-custom-commands
19464 ;; normalize different versions
19465 (delq nil
19466 (mapcar
19467 (lambda (x)
19468 (cond ((stringp (cdr x))
19469 (push x prefix-descriptions)
19470 nil)
19471 ((stringp (nth 1 x)) x)
19472 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19473 (t (cons (car x) (cons "" (cdr x))))))
19474 org-agenda-custom-commands)))
19475 (buf (current-buffer))
19476 (bfn (buffer-file-name (buffer-base-buffer)))
19477 entry key type match lprops ans)
19478 ;; Turn off restriction unless there is an overriding one
19479 (unless org-agenda-overriding-restriction
19480 (put 'org-agenda-files 'org-restrict nil)
19481 (setq org-agenda-restrict nil)
19482 (move-marker org-agenda-restrict-begin nil)
19483 (move-marker org-agenda-restrict-end nil))
19484 ;; Delete old local properties
19485 (put 'org-agenda-redo-command 'org-lprops nil)
19486 ;; Remember where this call originated
19487 (setq org-agenda-last-dispatch-buffer (current-buffer))
19488 (unless keys
19489 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19490 keys (car ans)
19491 restriction (cdr ans)))
19492 ;; Estabish the restriction, if any
19493 (when (and (not org-agenda-overriding-restriction) restriction)
19494 (put 'org-agenda-files 'org-restrict (list bfn))
19495 (cond
19496 ((eq restriction 'region)
19497 (setq org-agenda-restrict t)
19498 (move-marker org-agenda-restrict-begin (region-beginning))
19499 (move-marker org-agenda-restrict-end (region-end)))
19500 ((eq restriction 'subtree)
19501 (save-excursion
19502 (setq org-agenda-restrict t)
19503 (org-back-to-heading t)
19504 (move-marker org-agenda-restrict-begin (point))
19505 (move-marker org-agenda-restrict-end
19506 (progn (org-end-of-subtree t)))))))
19508 (require 'calendar) ; FIXME: can we avoid this for some commands?
19509 ;; For example the todo list should not need it (but does...)
19510 (cond
19511 ((setq entry (assoc keys org-agenda-custom-commands))
19512 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19513 (progn
19514 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19515 (put 'org-agenda-redo-command 'org-lprops lprops)
19516 (cond
19517 ((eq type 'agenda)
19518 (org-let lprops '(org-agenda-list current-prefix-arg)))
19519 ((eq type 'alltodo)
19520 (org-let lprops '(org-todo-list current-prefix-arg)))
19521 ((eq type 'stuck)
19522 (org-let lprops '(org-agenda-list-stuck-projects
19523 current-prefix-arg)))
19524 ((eq type 'tags)
19525 (org-let lprops '(org-tags-view current-prefix-arg match)))
19526 ((eq type 'tags-todo)
19527 (org-let lprops '(org-tags-view '(4) match)))
19528 ((eq type 'todo)
19529 (org-let lprops '(org-todo-list match)))
19530 ((eq type 'tags-tree)
19531 (org-check-for-org-mode)
19532 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
19533 ((eq type 'todo-tree)
19534 (org-check-for-org-mode)
19535 (org-let lprops
19536 '(org-occur (concat "^" outline-regexp "[ \t]*"
19537 (regexp-quote match) "\\>"))))
19538 ((eq type 'occur-tree)
19539 (org-check-for-org-mode)
19540 (org-let lprops '(org-occur match)))
19541 ((functionp type)
19542 (org-let lprops '(funcall type match)))
19543 ((fboundp type)
19544 (org-let lprops '(funcall type match)))
19545 (t (error "Invalid custom agenda command type %s" type))))
19546 (org-run-agenda-series (nth 1 entry) (cddr entry))))
19547 ((equal keys "C")
19548 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
19549 (customize-variable 'org-agenda-custom-commands))
19550 ((equal keys "a") (call-interactively 'org-agenda-list))
19551 ((equal keys "t") (call-interactively 'org-todo-list))
19552 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
19553 ((equal keys "m") (call-interactively 'org-tags-view))
19554 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
19555 ((equal keys "e") (call-interactively 'org-store-agenda-views))
19556 ((equal keys "L")
19557 (unless (org-mode-p)
19558 (error "This is not an Org-mode file"))
19559 (unless restriction
19560 (put 'org-agenda-files 'org-restrict (list bfn))
19561 (org-call-with-arg 'org-timeline arg)))
19562 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
19563 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
19564 ((equal keys "!") (customize-variable 'org-stuck-projects))
19565 (t (error "Invalid agenda key"))))))
19567 (defun org-agenda-normalize-custom-commands (cmds)
19568 (delq nil
19569 (mapcar
19570 (lambda (x)
19571 (cond ((stringp (cdr x)) nil)
19572 ((stringp (nth 1 x)) x)
19573 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19574 (t (cons (car x) (cons "" (cdr x))))))
19575 cmds)))
19577 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
19578 "The user interface for selecting an agenda command."
19579 (catch 'exit
19580 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
19581 (restrict-ok (and bfn (org-mode-p)))
19582 (region-p (org-region-active-p))
19583 (custom org-agenda-custom-commands)
19584 (selstring "")
19585 restriction second-time
19586 c entry key type match prefixes rmheader header-end custom1 desc)
19587 (save-window-excursion
19588 (delete-other-windows)
19589 (org-switch-to-buffer-other-window " *Agenda Commands*")
19590 (erase-buffer)
19591 (insert (eval-when-compile
19592 (let ((header
19594 Press key for an agenda command: < Buffer,subtree/region restriction
19595 -------------------------------- > Remove restriction
19596 a Agenda for current week or day e Export agenda views
19597 t List of all TODO entries T Entries with special TODO kwd
19598 m Match a TAGS query M Like m, but only TODO entries
19599 L Timeline for current buffer # List stuck projects (!=configure)
19600 / Multi-occur C Configure custom agenda commands
19602 (start 0))
19603 (while (string-match
19604 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
19605 header start)
19606 (setq start (match-end 0))
19607 (add-text-properties (match-beginning 2) (match-end 2)
19608 '(face bold) header))
19609 header)))
19610 (setq header-end (move-marker (make-marker) (point)))
19611 (while t
19612 (setq custom1 custom)
19613 (when (eq rmheader t)
19614 (goto-line 1)
19615 (re-search-forward ":" nil t)
19616 (delete-region (match-end 0) (point-at-eol))
19617 (forward-char 1)
19618 (looking-at "-+")
19619 (delete-region (match-end 0) (point-at-eol))
19620 (move-marker header-end (match-end 0)))
19621 (goto-char header-end)
19622 (delete-region (point) (point-max))
19623 (while (setq entry (pop custom1))
19624 (setq key (car entry) desc (nth 1 entry)
19625 type (nth 2 entry) match (nth 3 entry))
19626 (if (> (length key) 1)
19627 (add-to-list 'prefixes (string-to-char key))
19628 (insert
19629 (format
19630 "\n%-4s%-14s: %s"
19631 (org-add-props (copy-sequence key)
19632 '(face bold))
19633 (cond
19634 ((string-match "\\S-" desc) desc)
19635 ((eq type 'agenda) "Agenda for current week or day")
19636 ((eq type 'alltodo) "List of all TODO entries")
19637 ((eq type 'stuck) "List of stuck projects")
19638 ((eq type 'todo) "TODO keyword")
19639 ((eq type 'tags) "Tags query")
19640 ((eq type 'tags-todo) "Tags (TODO)")
19641 ((eq type 'tags-tree) "Tags tree")
19642 ((eq type 'todo-tree) "TODO kwd tree")
19643 ((eq type 'occur-tree) "Occur tree")
19644 ((functionp type) (if (symbolp type)
19645 (symbol-name type)
19646 "Lambda expression"))
19647 (t "???"))
19648 (cond
19649 ((stringp match)
19650 (org-add-props match nil 'face 'org-warning))
19651 (match
19652 (format "set of %d commands" (length match)))
19653 (t ""))))))
19654 (when prefixes
19655 (mapc (lambda (x)
19656 (insert
19657 (format "\n%s %s"
19658 (org-add-props (char-to-string x)
19659 nil 'face 'bold)
19660 (or (cdr (assoc (concat selstring (char-to-string x))
19661 prefix-descriptions))
19662 "Prefix key"))))
19663 prefixes))
19664 (goto-char (point-min))
19665 (when (fboundp 'fit-window-to-buffer)
19666 (if second-time
19667 (if (not (pos-visible-in-window-p (point-max)))
19668 (fit-window-to-buffer))
19669 (setq second-time t)
19670 (fit-window-to-buffer)))
19671 (message "Press key for agenda command%s:"
19672 (if (or restrict-ok org-agenda-overriding-restriction)
19673 (if org-agenda-overriding-restriction
19674 " (restriction lock active)"
19675 (if restriction
19676 (format " (restricted to %s)" restriction)
19677 " (unrestricted)"))
19678 ""))
19679 (setq c (read-char-exclusive))
19680 (message "")
19681 (cond
19682 ((assoc (char-to-string c) custom)
19683 (setq selstring (concat selstring (char-to-string c)))
19684 (throw 'exit (cons selstring restriction)))
19685 ((memq c prefixes)
19686 (setq selstring (concat selstring (char-to-string c))
19687 prefixes nil
19688 rmheader (or rmheader t)
19689 custom (delq nil (mapcar
19690 (lambda (x)
19691 (if (or (= (length (car x)) 1)
19692 (/= (string-to-char (car x)) c))
19694 (cons (substring (car x) 1) (cdr x))))
19695 custom))))
19696 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
19697 (message "Restriction is only possible in Org-mode buffers")
19698 (ding) (sit-for 1))
19699 ((eq c ?1)
19700 (org-agenda-remove-restriction-lock 'noupdate)
19701 (setq restriction 'buffer))
19702 ((eq c ?0)
19703 (org-agenda-remove-restriction-lock 'noupdate)
19704 (setq restriction (if region-p 'region 'subtree)))
19705 ((eq c ?<)
19706 (org-agenda-remove-restriction-lock 'noupdate)
19707 (setq restriction
19708 (cond
19709 ((eq restriction 'buffer)
19710 (if region-p 'region 'subtree))
19711 ((memq restriction '(subtree region))
19712 nil)
19713 (t 'buffer))))
19714 ((eq c ?>)
19715 (org-agenda-remove-restriction-lock 'noupdate)
19716 (setq restriction nil))
19717 ((and (equal selstring "") (memq c '(?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
19718 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
19719 ((and (> (length selstring) 0) (eq c ?\d))
19720 (delete-window)
19721 (org-agenda-get-restriction-and-command prefix-descriptions))
19723 ((equal c ?q) (error "Abort"))
19724 (t (error "Invalid key %c" c))))))))
19726 (defun org-run-agenda-series (name series)
19727 (org-prepare-agenda name)
19728 (let* ((org-agenda-multi t)
19729 (redo (list 'org-run-agenda-series name (list 'quote series)))
19730 (cmds (car series))
19731 (gprops (nth 1 series))
19732 match ;; The byte compiler incorrectly complains about this. Keep it!
19733 cmd type lprops)
19734 (while (setq cmd (pop cmds))
19735 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
19736 (cond
19737 ((eq type 'agenda)
19738 (org-let2 gprops lprops
19739 '(call-interactively 'org-agenda-list)))
19740 ((eq type 'alltodo)
19741 (org-let2 gprops lprops
19742 '(call-interactively 'org-todo-list)))
19743 ((eq type 'stuck)
19744 (org-let2 gprops lprops
19745 '(call-interactively 'org-agenda-list-stuck-projects)))
19746 ((eq type 'tags)
19747 (org-let2 gprops lprops
19748 '(org-tags-view current-prefix-arg match)))
19749 ((eq type 'tags-todo)
19750 (org-let2 gprops lprops
19751 '(org-tags-view '(4) match)))
19752 ((eq type 'todo)
19753 (org-let2 gprops lprops
19754 '(org-todo-list match)))
19755 ((fboundp type)
19756 (org-let2 gprops lprops
19757 '(funcall type match)))
19758 (t (error "Invalid type in command series"))))
19759 (widen)
19760 (setq org-agenda-redo-command redo)
19761 (goto-char (point-min)))
19762 (org-finalize-agenda))
19764 ;;;###autoload
19765 (defmacro org-batch-agenda (cmd-key &rest parameters)
19766 "Run an agenda command in batch mode and send the result to STDOUT.
19767 If CMD-KEY is a string of length 1, it is used as a key in
19768 `org-agenda-custom-commands' and triggers this command. If it is a
19769 longer string it is used as a tags/todo match string.
19770 Paramters are alternating variable names and values that will be bound
19771 before running the agenda command."
19772 (let (pars)
19773 (while parameters
19774 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19775 (if (> (length cmd-key) 2)
19776 (eval (list 'let (nreverse pars)
19777 (list 'org-tags-view nil cmd-key)))
19778 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19779 (set-buffer org-agenda-buffer-name)
19780 (princ (org-encode-for-stdout (buffer-string)))))
19782 (defun org-encode-for-stdout (string)
19783 (if (fboundp 'encode-coding-string)
19784 (encode-coding-string string buffer-file-coding-system)
19785 string))
19787 (defvar org-agenda-info nil)
19789 ;;;###autoload
19790 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
19791 "Run an agenda command in batch mode and send the result to STDOUT.
19792 If CMD-KEY is a string of length 1, it is used as a key in
19793 `org-agenda-custom-commands' and triggers this command. If it is a
19794 longer string it is used as a tags/todo match string.
19795 Paramters are alternating variable names and values that will be bound
19796 before running the agenda command.
19798 The output gives a line for each selected agenda item. Each
19799 item is a list of comma-separated values, like this:
19801 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
19803 category The category of the item
19804 head The headline, without TODO kwd, TAGS and PRIORITY
19805 type The type of the agenda entry, can be
19806 todo selected in TODO match
19807 tagsmatch selected in tags match
19808 diary imported from diary
19809 deadline a deadline on given date
19810 scheduled scheduled on given date
19811 timestamp entry has timestamp on given date
19812 closed entry was closed on given date
19813 upcoming-deadline warning about deadline
19814 past-scheduled forwarded scheduled item
19815 block entry has date block including g. date
19816 todo The todo keyword, if any
19817 tags All tags including inherited ones, separated by colons
19818 date The relevant date, like 2007-2-14
19819 time The time, like 15:00-16:50
19820 extra Sting with extra planning info
19821 priority-l The priority letter if any was given
19822 priority-n The computed numerical priority
19823 agenda-day The day in the agenda where this is listed"
19825 (let (pars)
19826 (while parameters
19827 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19828 (push (list 'org-agenda-remove-tags t) pars)
19829 (if (> (length cmd-key) 2)
19830 (eval (list 'let (nreverse pars)
19831 (list 'org-tags-view nil cmd-key)))
19832 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19833 (set-buffer org-agenda-buffer-name)
19834 (let* ((lines (org-split-string (buffer-string) "\n"))
19835 line)
19836 (while (setq line (pop lines))
19837 (catch 'next
19838 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
19839 (setq org-agenda-info
19840 (org-fix-agenda-info (text-properties-at 0 line)))
19841 (princ
19842 (org-encode-for-stdout
19843 (mapconcat 'org-agenda-export-csv-mapper
19844 '(org-category txt type todo tags date time-of-day extra
19845 priority-letter priority agenda-day)
19846 ",")))
19847 (princ "\n"))))))
19849 (defun org-fix-agenda-info (props)
19850 "Make sure all properties on an agenda item have a canonical form,
19851 so the export commands can easily use it."
19852 (let (tmp re)
19853 (when (setq tmp (plist-get props 'tags))
19854 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
19855 (when (setq tmp (plist-get props 'date))
19856 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19857 (let ((calendar-date-display-form '(year "-" month "-" day)))
19858 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
19860 (setq tmp (calendar-date-string tmp)))
19861 (setq props (plist-put props 'date tmp)))
19862 (when (setq tmp (plist-get props 'day))
19863 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19864 (let ((calendar-date-display-form '(year "-" month "-" day)))
19865 (setq tmp (calendar-date-string tmp)))
19866 (setq props (plist-put props 'day tmp))
19867 (setq props (plist-put props 'agenda-day tmp)))
19868 (when (setq tmp (plist-get props 'txt))
19869 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
19870 (plist-put props 'priority-letter (match-string 1 tmp))
19871 (setq tmp (replace-match "" t t tmp)))
19872 (when (and (setq re (plist-get props 'org-todo-regexp))
19873 (setq re (concat "\\`\\.*" re " ?"))
19874 (string-match re tmp))
19875 (plist-put props 'todo (match-string 1 tmp))
19876 (setq tmp (replace-match "" t t tmp)))
19877 (plist-put props 'txt tmp)))
19878 props)
19880 (defun org-agenda-export-csv-mapper (prop)
19881 (let ((res (plist-get org-agenda-info prop)))
19882 (setq res
19883 (cond
19884 ((not res) "")
19885 ((stringp res) res)
19886 (t (prin1-to-string res))))
19887 (while (string-match "," res)
19888 (setq res (replace-match ";" t t res)))
19889 (org-trim res)))
19892 ;;;###autoload
19893 (defun org-store-agenda-views (&rest parameters)
19894 (interactive)
19895 (eval (list 'org-batch-store-agenda-views)))
19897 ;; FIXME, why is this a macro?????
19898 ;;;###autoload
19899 (defmacro org-batch-store-agenda-views (&rest parameters)
19900 "Run all custom agenda commands that have a file argument."
19901 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
19902 (pop-up-frames nil)
19903 (dir default-directory)
19904 pars cmd thiscmdkey files opts)
19905 (while parameters
19906 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19907 (setq pars (reverse pars))
19908 (save-window-excursion
19909 (while cmds
19910 (setq cmd (pop cmds)
19911 thiscmdkey (car cmd)
19912 opts (nth 4 cmd)
19913 files (nth 5 cmd))
19914 (if (stringp files) (setq files (list files)))
19915 (when files
19916 (eval (list 'let (append org-agenda-exporter-settings opts pars)
19917 (list 'org-agenda nil thiscmdkey)))
19918 (set-buffer org-agenda-buffer-name)
19919 (while files
19920 (eval (list 'let (append org-agenda-exporter-settings opts pars)
19921 (list 'org-write-agenda
19922 (expand-file-name (pop files) dir) t))))
19923 (and (get-buffer org-agenda-buffer-name)
19924 (kill-buffer org-agenda-buffer-name)))))))
19926 (defun org-write-agenda (file &optional nosettings)
19927 "Write the current buffer (an agenda view) as a file.
19928 Depending on the extension of the file name, plain text (.txt),
19929 HTML (.html or .htm) or Postscript (.ps) is produced.
19930 If NOSETTINGS is given, do not scope the settings of
19931 `org-agenda-exporter-settings' into the export commands. This is used when
19932 the settings have already been scoped and we do not wish to overrule other,
19933 higher priority settings."
19934 (interactive "FWrite agenda to file: ")
19935 (if (not (file-writable-p file))
19936 (error "Cannot write agenda to file %s" file))
19937 (cond
19938 ((string-match "\\.html?\\'" file) (require 'htmlize))
19939 ((string-match "\\.ps\\'" file) (require 'ps-print)))
19940 (org-let (if nosettings nil org-agenda-exporter-settings)
19941 '(save-excursion
19942 (save-window-excursion
19943 (cond
19944 ((string-match "\\.html?\\'" file)
19945 (set-buffer (htmlize-buffer (current-buffer)))
19947 (when (and org-agenda-export-html-style
19948 (string-match "<style>" org-agenda-export-html-style))
19949 ;; replace <style> section with org-agenda-export-html-style
19950 (goto-char (point-min))
19951 (kill-region (- (search-forward "<style") 6)
19952 (search-forward "</style>"))
19953 (insert org-agenda-export-html-style))
19954 (write-file file)
19955 (kill-buffer (current-buffer))
19956 (message "HTML written to %s" file))
19957 ((string-match "\\.ps\\'" file)
19958 (ps-print-buffer-with-faces file)
19959 (message "Postscript written to %s" file))
19961 (let ((bs (buffer-string)))
19962 (find-file file)
19963 (insert bs)
19964 (save-buffer 0)
19965 (kill-buffer (current-buffer))
19966 (message "Plain text written to %s" file))))))
19967 (set-buffer org-agenda-buffer-name)))
19969 (defmacro org-no-read-only (&rest body)
19970 "Inhibit read-only for BODY."
19971 `(let ((inhibit-read-only t)) ,@body))
19973 (defun org-check-for-org-mode ()
19974 "Make sure current buffer is in org-mode. Error if not."
19975 (or (org-mode-p)
19976 (error "Cannot execute org-mode agenda command on buffer in %s."
19977 major-mode)))
19979 (defun org-fit-agenda-window ()
19980 "Fit the window to the buffer size."
19981 (and (memq org-agenda-window-setup '(reorganize-frame))
19982 (fboundp 'fit-window-to-buffer)
19983 (fit-window-to-buffer
19985 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
19986 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
19988 ;;; Agenda file list
19990 (defun org-agenda-files (&optional unrestricted)
19991 "Get the list of agenda files.
19992 Optional UNRESTRICTED means return the full list even if a restriction
19993 is currently in place."
19994 (let ((files
19995 (cond
19996 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
19997 ((stringp org-agenda-files) (org-read-agenda-file-list))
19998 ((listp org-agenda-files) org-agenda-files)
19999 (t (error "Invalid value of `org-agenda-files'")))))
20000 (setq files (apply 'append
20001 (mapcar (lambda (f)
20002 (if (file-directory-p f)
20003 (directory-files f t
20004 org-agenda-file-regexp)
20005 (list f)))
20006 files)))
20007 (if org-agenda-skip-unavailable-files
20008 (delq nil
20009 (mapcar (function
20010 (lambda (file)
20011 (and (file-readable-p file) file)))
20012 files))
20013 files))) ; `org-check-agenda-file' will remove them from the list
20015 (defun org-edit-agenda-file-list ()
20016 "Edit the list of agenda files.
20017 Depending on setup, this either uses customize to edit the variable
20018 `org-agenda-files', or it visits the file that is holding the list. In the
20019 latter case, the buffer is set up in a way that saving it automatically kills
20020 the buffer and restores the previous window configuration."
20021 (interactive)
20022 (if (stringp org-agenda-files)
20023 (let ((cw (current-window-configuration)))
20024 (find-file org-agenda-files)
20025 (org-set-local 'org-window-configuration cw)
20026 (org-add-hook 'after-save-hook
20027 (lambda ()
20028 (set-window-configuration
20029 (prog1 org-window-configuration
20030 (kill-buffer (current-buffer))))
20031 (org-install-agenda-files-menu)
20032 (message "New agenda file list installed"))
20033 nil 'local)
20034 (message "%s" (substitute-command-keys
20035 "Edit list and finish with \\[save-buffer]")))
20036 (customize-variable 'org-agenda-files)))
20038 (defun org-store-new-agenda-file-list (list)
20039 "Set new value for the agenda file list and save it correcly."
20040 (if (stringp org-agenda-files)
20041 (let ((f org-agenda-files) b)
20042 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
20043 (with-temp-file f
20044 (insert (mapconcat 'identity list "\n") "\n")))
20045 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
20046 (setq org-agenda-files list)
20047 (customize-save-variable 'org-agenda-files org-agenda-files))))
20049 (defun org-read-agenda-file-list ()
20050 "Read the list of agenda files from a file."
20051 (when (stringp org-agenda-files)
20052 (with-temp-buffer
20053 (insert-file-contents org-agenda-files)
20054 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
20057 ;;;###autoload
20058 (defun org-cycle-agenda-files ()
20059 "Cycle through the files in `org-agenda-files'.
20060 If the current buffer visits an agenda file, find the next one in the list.
20061 If the current buffer does not, find the first agenda file."
20062 (interactive)
20063 (let* ((fs (org-agenda-files t))
20064 (files (append fs (list (car fs))))
20065 (tcf (if buffer-file-name (file-truename buffer-file-name)))
20066 file)
20067 (unless files (error "No agenda files"))
20068 (catch 'exit
20069 (while (setq file (pop files))
20070 (if (equal (file-truename file) tcf)
20071 (when (car files)
20072 (find-file (car files))
20073 (throw 'exit t))))
20074 (find-file (car fs)))
20075 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
20077 (defun org-agenda-file-to-front (&optional to-end)
20078 "Move/add the current file to the top of the agenda file list.
20079 If the file is not present in the list, it is added to the front. If it is
20080 present, it is moved there. With optional argument TO-END, add/move to the
20081 end of the list."
20082 (interactive "P")
20083 (let ((org-agenda-skip-unavailable-files nil)
20084 (file-alist (mapcar (lambda (x)
20085 (cons (file-truename x) x))
20086 (org-agenda-files t)))
20087 (ctf (file-truename buffer-file-name))
20088 x had)
20089 (setq x (assoc ctf file-alist) had x)
20091 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
20092 (if to-end
20093 (setq file-alist (append (delq x file-alist) (list x)))
20094 (setq file-alist (cons x (delq x file-alist))))
20095 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
20096 (org-install-agenda-files-menu)
20097 (message "File %s to %s of agenda file list"
20098 (if had "moved" "added") (if to-end "end" "front"))))
20100 (defun org-remove-file (&optional file)
20101 "Remove current file from the list of files in variable `org-agenda-files'.
20102 These are the files which are being checked for agenda entries.
20103 Optional argument FILE means, use this file instead of the current."
20104 (interactive)
20105 (let* ((org-agenda-skip-unavailable-files nil)
20106 (file (or file buffer-file-name))
20107 (true-file (file-truename file))
20108 (afile (abbreviate-file-name file))
20109 (files (delq nil (mapcar
20110 (lambda (x)
20111 (if (equal true-file
20112 (file-truename x))
20113 nil x))
20114 (org-agenda-files t)))))
20115 (if (not (= (length files) (length (org-agenda-files t))))
20116 (progn
20117 (org-store-new-agenda-file-list files)
20118 (org-install-agenda-files-menu)
20119 (message "Removed file: %s" afile))
20120 (message "File was not in list: %s (not removed)" afile))))
20122 (defun org-file-menu-entry (file)
20123 (vector file (list 'find-file file) t))
20125 (defun org-check-agenda-file (file)
20126 "Make sure FILE exists. If not, ask user what to do."
20127 (when (not (file-exists-p file))
20128 (message "non-existent file %s. [R]emove from list or [A]bort?"
20129 (abbreviate-file-name file))
20130 (let ((r (downcase (read-char-exclusive))))
20131 (cond
20132 ((equal r ?r)
20133 (org-remove-file file)
20134 (throw 'nextfile t))
20135 (t (error "Abort"))))))
20137 ;;; Agenda prepare and finalize
20139 (defvar org-agenda-multi nil) ; dynammically scoped
20140 (defvar org-agenda-buffer-name "*Org Agenda*")
20141 (defvar org-pre-agenda-window-conf nil)
20142 (defvar org-agenda-name nil)
20143 (defun org-prepare-agenda (&optional name)
20144 (setq org-todo-keywords-for-agenda nil)
20145 (setq org-done-keywords-for-agenda nil)
20146 (if org-agenda-multi
20147 (progn
20148 (setq buffer-read-only nil)
20149 (goto-char (point-max))
20150 (unless (or (bobp) org-agenda-compact-blocks)
20151 (insert "\n" (make-string (window-width) ?=) "\n"))
20152 (narrow-to-region (point) (point-max)))
20153 (org-agenda-maybe-reset-markers 'force)
20154 (org-prepare-agenda-buffers (org-agenda-files))
20155 (setq org-todo-keywords-for-agenda
20156 (org-uniquify org-todo-keywords-for-agenda))
20157 (setq org-done-keywords-for-agenda
20158 (org-uniquify org-done-keywords-for-agenda))
20159 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
20160 (awin (get-buffer-window abuf)))
20161 (cond
20162 ((equal (current-buffer) abuf) nil)
20163 (awin (select-window awin))
20164 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
20165 ((equal org-agenda-window-setup 'current-window)
20166 (switch-to-buffer abuf))
20167 ((equal org-agenda-window-setup 'other-window)
20168 (org-switch-to-buffer-other-window abuf))
20169 ((equal org-agenda-window-setup 'other-frame)
20170 (switch-to-buffer-other-frame abuf))
20171 ((equal org-agenda-window-setup 'reorganize-frame)
20172 (delete-other-windows)
20173 (org-switch-to-buffer-other-window abuf))))
20174 (setq buffer-read-only nil)
20175 (erase-buffer)
20176 (org-agenda-mode)
20177 (and name (not org-agenda-name)
20178 (org-set-local 'org-agenda-name name)))
20179 (setq buffer-read-only nil))
20181 (defun org-finalize-agenda ()
20182 "Finishing touch for the agenda buffer, called just before displaying it."
20183 (unless org-agenda-multi
20184 (save-excursion
20185 (let ((inhibit-read-only t))
20186 (goto-char (point-min))
20187 (while (org-activate-bracket-links (point-max))
20188 (add-text-properties (match-beginning 0) (match-end 0)
20189 '(face org-link)))
20190 (org-agenda-align-tags)
20191 (unless org-agenda-with-colors
20192 (remove-text-properties (point-min) (point-max) '(face nil))))
20193 (if (and (boundp 'org-overriding-columns-format)
20194 org-overriding-columns-format)
20195 (org-set-local 'org-overriding-columns-format
20196 org-overriding-columns-format))
20197 (if (and (boundp 'org-agenda-view-columns-initially)
20198 org-agenda-view-columns-initially)
20199 (org-agenda-columns))
20200 (when org-agenda-fontify-priorities
20201 (org-fontify-priorities))
20202 (run-hooks 'org-finalize-agenda-hook)
20203 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20206 (defun org-fontify-priorities ()
20207 "Make highest priority lines bold, and lowest italic."
20208 (interactive)
20209 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
20210 (org-delete-overlay o)))
20211 (org-overlays-in (point-min) (point-max)))
20212 (save-excursion
20213 (let ((inhibit-read-only t)
20214 b e p ov h l)
20215 (goto-char (point-min))
20216 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
20217 (setq h (or (get-char-property (point) 'org-highest-priority)
20218 org-highest-priority)
20219 l (or (get-char-property (point) 'org-lowest-priority)
20220 org-lowest-priority)
20221 p (string-to-char (match-string 1))
20222 b (match-beginning 0) e (point-at-eol)
20223 ov (org-make-overlay b e))
20224 (org-overlay-put
20225 ov 'face
20226 (cond ((listp org-agenda-fontify-priorities)
20227 (cdr (assoc p org-agenda-fontify-priorities)))
20228 ((equal p l) 'italic)
20229 ((equal p h) 'bold)))
20230 (org-overlay-put ov 'org-type 'org-priority)))))
20232 (defun org-prepare-agenda-buffers (files)
20233 "Create buffers for all agenda files, protect archived trees and comments."
20234 (interactive)
20235 (let ((pa '(:org-archived t))
20236 (pc '(:org-comment t))
20237 (pall '(:org-archived t :org-comment t))
20238 (inhibit-read-only t)
20239 (rea (concat ":" org-archive-tag ":"))
20240 bmp file re)
20241 (save-excursion
20242 (save-restriction
20243 (while (setq file (pop files))
20244 (if (bufferp file)
20245 (set-buffer file)
20246 (org-check-agenda-file file)
20247 (set-buffer (org-get-agenda-file-buffer file)))
20248 (widen)
20249 (setq bmp (buffer-modified-p))
20250 (org-refresh-category-properties)
20251 (setq org-todo-keywords-for-agenda
20252 (append org-todo-keywords-for-agenda org-todo-keywords-1))
20253 (setq org-done-keywords-for-agenda
20254 (append org-done-keywords-for-agenda org-done-keywords))
20255 (save-excursion
20256 (remove-text-properties (point-min) (point-max) pall)
20257 (when org-agenda-skip-archived-trees
20258 (goto-char (point-min))
20259 (while (re-search-forward rea nil t)
20260 (if (org-on-heading-p t)
20261 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
20262 (goto-char (point-min))
20263 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
20264 (while (re-search-forward re nil t)
20265 (add-text-properties
20266 (match-beginning 0) (org-end-of-subtree t) pc)))
20267 (set-buffer-modified-p bmp))))))
20269 (defvar org-agenda-skip-function nil
20270 "Function to be called at each match during agenda construction.
20271 If this function returns nil, the current match should not be skipped.
20272 Otherwise, the function must return a position from where the search
20273 should be continued.
20274 This may also be a Lisp form, it will be evaluated.
20275 Never set this variable using `setq' or so, because then it will apply
20276 to all future agenda commands. Instead, bind it with `let' to scope
20277 it dynamically into the agenda-constructing command. A good way to set
20278 it is through options in org-agenda-custom-commands.")
20280 (defun org-agenda-skip ()
20281 "Throw to `:skip' in places that should be skipped.
20282 Also moves point to the end of the skipped region, so that search can
20283 continue from there."
20284 (let ((p (point-at-bol)) to fp)
20285 (and org-agenda-skip-archived-trees
20286 (get-text-property p :org-archived)
20287 (org-end-of-subtree t)
20288 (throw :skip t))
20289 (and (get-text-property p :org-comment)
20290 (org-end-of-subtree t)
20291 (throw :skip t))
20292 (if (equal (char-after p) ?#) (throw :skip t))
20293 (when (and (or (setq fp (functionp org-agenda-skip-function))
20294 (consp org-agenda-skip-function))
20295 (setq to (save-excursion
20296 (save-match-data
20297 (if fp
20298 (funcall org-agenda-skip-function)
20299 (eval org-agenda-skip-function))))))
20300 (goto-char to)
20301 (throw :skip t))))
20303 (defvar org-agenda-markers nil
20304 "List of all currently active markers created by `org-agenda'.")
20305 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20306 "Creation time of the last agenda marker.")
20308 (defun org-agenda-new-marker (&optional pos)
20309 "Return a new agenda marker.
20310 Org-mode keeps a list of these markers and resets them when they are
20311 no longer in use."
20312 (let ((m (copy-marker (or pos (point)))))
20313 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20314 (push m org-agenda-markers)
20317 (defun org-agenda-maybe-reset-markers (&optional force)
20318 "Reset markers created by `org-agenda'. But only if they are old enough."
20319 (if (or (and force (not org-agenda-multi))
20320 (> (- (time-to-seconds (current-time))
20321 org-agenda-last-marker-time)
20323 (while org-agenda-markers
20324 (move-marker (pop org-agenda-markers) nil))))
20326 (defun org-get-agenda-file-buffer (file)
20327 "Get a buffer visiting FILE. If the buffer needs to be created, add
20328 it to the list of buffers which might be released later."
20329 (let ((buf (org-find-base-buffer-visiting file)))
20330 (if buf
20331 buf ; just return it
20332 ;; Make a new buffer and remember it
20333 (setq buf (find-file-noselect file))
20334 (if buf (push buf org-agenda-new-buffers))
20335 buf)))
20337 (defun org-release-buffers (blist)
20338 "Release all buffers in list, asking the user for confirmation when needed.
20339 When a buffer is unmodified, it is just killed. When modified, it is saved
20340 \(if the user agrees) and then killed."
20341 (let (buf file)
20342 (while (setq buf (pop blist))
20343 (setq file (buffer-file-name buf))
20344 (when (and (buffer-modified-p buf)
20345 file
20346 (y-or-n-p (format "Save file %s? " file)))
20347 (with-current-buffer buf (save-buffer)))
20348 (kill-buffer buf))))
20350 (defun org-get-category (&optional pos)
20351 "Get the category applying to position POS."
20352 (get-text-property (or pos (point)) 'org-category))
20354 ;;; Agenda timeline
20356 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20358 (defun org-timeline (&optional include-all)
20359 "Show a time-sorted view of the entries in the current org file.
20360 Only entries with a time stamp of today or later will be listed. With
20361 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20362 under the current date.
20363 If the buffer contains an active region, only check the region for
20364 dates."
20365 (interactive "P")
20366 (require 'calendar)
20367 (org-compile-prefix-format 'timeline)
20368 (org-set-sorting-strategy 'timeline)
20369 (let* ((dopast t)
20370 (dotodo include-all)
20371 (doclosed org-agenda-show-log)
20372 (entry buffer-file-name)
20373 (date (calendar-current-date))
20374 (beg (if (org-region-active-p) (region-beginning) (point-min)))
20375 (end (if (org-region-active-p) (region-end) (point-max)))
20376 (day-numbers (org-get-all-dates beg end 'no-ranges
20377 t doclosed ; always include today
20378 org-timeline-show-empty-dates))
20379 (org-deadline-warning-days 0)
20380 (org-agenda-only-exact-dates t)
20381 (today (time-to-days (current-time)))
20382 (past t)
20383 args
20384 s e rtn d emptyp)
20385 (setq org-agenda-redo-command
20386 (list 'progn
20387 (list 'org-switch-to-buffer-other-window (current-buffer))
20388 (list 'org-timeline (list 'quote include-all))))
20389 (if (not dopast)
20390 ;; Remove past dates from the list of dates.
20391 (setq day-numbers (delq nil (mapcar (lambda(x)
20392 (if (>= x today) x nil))
20393 day-numbers))))
20394 (org-prepare-agenda (concat "Timeline "
20395 (file-name-nondirectory buffer-file-name)))
20396 (if doclosed (push :closed args))
20397 (push :timestamp args)
20398 (push :deadline args)
20399 (push :scheduled args)
20400 (push :sexp args)
20401 (if dotodo (push :todo args))
20402 (while (setq d (pop day-numbers))
20403 (if (and (listp d) (eq (car d) :omitted))
20404 (progn
20405 (setq s (point))
20406 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20407 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20408 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20409 (if (and (>= d today)
20410 dopast
20411 past)
20412 (progn
20413 (setq past nil)
20414 (insert (make-string 79 ?-) "\n")))
20415 (setq date (calendar-gregorian-from-absolute d))
20416 (setq s (point))
20417 (setq rtn (and (not emptyp)
20418 (apply 'org-agenda-get-day-entries entry
20419 date args)))
20420 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20421 (progn
20422 (insert
20423 (if (stringp org-agenda-format-date)
20424 (format-time-string org-agenda-format-date
20425 (org-time-from-absolute date))
20426 (funcall org-agenda-format-date date))
20427 "\n")
20428 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20429 (put-text-property s (1- (point)) 'org-date-line t)
20430 (if (equal d today)
20431 (put-text-property s (1- (point)) 'org-today t))
20432 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20433 (put-text-property s (1- (point)) 'day d)))))
20434 (goto-char (point-min))
20435 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20436 (point-min)))
20437 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20438 (org-finalize-agenda)
20439 (setq buffer-read-only t)))
20441 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty pre-re)
20442 "Return a list of all relevant day numbers from BEG to END buffer positions.
20443 If NO-RANGES is non-nil, include only the start and end dates of a range,
20444 not every single day in the range. If FORCE-TODAY is non-nil, make
20445 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20446 inactive time stamps (those in square brackets) are included.
20447 When EMPTY is non-nil, also include days without any entries."
20448 (let ((re (concat
20449 (if pre-re pre-re "")
20450 (if inactive org-ts-regexp-both org-ts-regexp)))
20451 dates dates1 date day day1 day2 ts1 ts2)
20452 (if force-today
20453 (setq dates (list (time-to-days (current-time)))))
20454 (save-excursion
20455 (goto-char beg)
20456 (while (re-search-forward re end t)
20457 (setq day (time-to-days (org-time-string-to-time
20458 (substring (match-string 1) 0 10))))
20459 (or (memq day dates) (push day dates)))
20460 (unless no-ranges
20461 (goto-char beg)
20462 (while (re-search-forward org-tr-regexp end t)
20463 (setq ts1 (substring (match-string 1) 0 10)
20464 ts2 (substring (match-string 2) 0 10)
20465 day1 (time-to-days (org-time-string-to-time ts1))
20466 day2 (time-to-days (org-time-string-to-time ts2)))
20467 (while (< (setq day1 (1+ day1)) day2)
20468 (or (memq day1 dates) (push day1 dates)))))
20469 (setq dates (sort dates '<))
20470 (when empty
20471 (while (setq day (pop dates))
20472 (setq day2 (car dates))
20473 (push day dates1)
20474 (when (and day2 empty)
20475 (if (or (eq empty t)
20476 (and (numberp empty) (<= (- day2 day) empty)))
20477 (while (< (setq day (1+ day)) day2)
20478 (push (list day) dates1))
20479 (push (cons :omitted (- day2 day)) dates1))))
20480 (setq dates (nreverse dates1)))
20481 dates)))
20483 ;;; Agenda Daily/Weekly
20485 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
20486 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
20487 (defvar org-agenda-last-arguments nil
20488 "The arguments of the previous call to org-agenda")
20489 (defvar org-starting-day nil) ; local variable in the agenda buffer
20490 (defvar org-agenda-span nil) ; local variable in the agenda buffer
20491 (defvar org-include-all-loc nil) ; local variable
20492 (defvar org-agenda-remove-date nil) ; dynamically scoped
20494 ;;;###autoload
20495 (defun org-agenda-list (&optional include-all start-day ndays)
20496 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
20497 The view will be for the current day or week, but from the overview buffer
20498 you will be able to go to other days/weeks.
20500 With one \\[universal-argument] prefix argument INCLUDE-ALL,
20501 all unfinished TODO items will also be shown, before the agenda.
20502 This feature is considered obsolete, please use the TODO list or a block
20503 agenda instead.
20505 With a numeric prefix argument in an interactive call, the agenda will
20506 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
20507 the number of days. NDAYS defaults to `org-agenda-ndays'.
20509 START-DAY defaults to TODAY, or to the most recent match for the weekday
20510 given in `org-agenda-start-on-weekday'."
20511 (interactive "P")
20512 (if (and (integerp include-all) (> include-all 0))
20513 (setq ndays include-all include-all nil))
20514 (setq ndays (or ndays org-agenda-ndays)
20515 start-day (or start-day org-agenda-start-day))
20516 (if org-agenda-overriding-arguments
20517 (setq include-all (car org-agenda-overriding-arguments)
20518 start-day (nth 1 org-agenda-overriding-arguments)
20519 ndays (nth 2 org-agenda-overriding-arguments)))
20520 (if (stringp start-day)
20521 ;; Convert to an absolute day number
20522 (setq start-day (time-to-days (org-read-date nil t start-day))))
20523 (setq org-agenda-last-arguments (list include-all start-day ndays))
20524 (org-compile-prefix-format 'agenda)
20525 (org-set-sorting-strategy 'agenda)
20526 (require 'calendar)
20527 (let* ((org-agenda-start-on-weekday
20528 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
20529 org-agenda-start-on-weekday nil))
20530 (thefiles (org-agenda-files))
20531 (files thefiles)
20532 (today (time-to-days
20533 (time-subtract (current-time)
20534 (list 0 (* 3600 org-extend-today-until) 0))))
20535 (sd (or start-day today))
20536 (start (if (or (null org-agenda-start-on-weekday)
20537 (< org-agenda-ndays 7))
20539 (let* ((nt (calendar-day-of-week
20540 (calendar-gregorian-from-absolute sd)))
20541 (n1 org-agenda-start-on-weekday)
20542 (d (- nt n1)))
20543 (- sd (+ (if (< d 0) 7 0) d)))))
20544 (day-numbers (list start))
20545 (day-cnt 0)
20546 (inhibit-redisplay (not debug-on-error))
20547 s e rtn rtnall file date d start-pos end-pos todayp nd)
20548 (setq org-agenda-redo-command
20549 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
20550 ;; Make the list of days
20551 (setq ndays (or ndays org-agenda-ndays)
20552 nd ndays)
20553 (while (> ndays 1)
20554 (push (1+ (car day-numbers)) day-numbers)
20555 (setq ndays (1- ndays)))
20556 (setq day-numbers (nreverse day-numbers))
20557 (org-prepare-agenda "Day/Week")
20558 (org-set-local 'org-starting-day (car day-numbers))
20559 (org-set-local 'org-include-all-loc include-all)
20560 (org-set-local 'org-agenda-span
20561 (org-agenda-ndays-to-span nd))
20562 (when (and (or include-all org-agenda-include-all-todo)
20563 (member today day-numbers))
20564 (setq files thefiles
20565 rtnall nil)
20566 (while (setq file (pop files))
20567 (catch 'nextfile
20568 (org-check-agenda-file file)
20569 (setq date (calendar-gregorian-from-absolute today)
20570 rtn (org-agenda-get-day-entries
20571 file date :todo))
20572 (setq rtnall (append rtnall rtn))))
20573 (when rtnall
20574 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
20575 (add-text-properties (point-min) (1- (point))
20576 (list 'face 'org-agenda-structure))
20577 (insert (org-finalize-agenda-entries rtnall) "\n")))
20578 (unless org-agenda-compact-blocks
20579 (setq s (point))
20580 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
20581 "-agenda:\n")
20582 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
20583 'org-date-line t)))
20584 (while (setq d (pop day-numbers))
20585 (setq date (calendar-gregorian-from-absolute d)
20586 s (point))
20587 (if (or (setq todayp (= d today))
20588 (and (not start-pos) (= d sd)))
20589 (setq start-pos (point))
20590 (if (and start-pos (not end-pos))
20591 (setq end-pos (point))))
20592 (setq files thefiles
20593 rtnall nil)
20594 (while (setq file (pop files))
20595 (catch 'nextfile
20596 (org-check-agenda-file file)
20597 (if org-agenda-show-log
20598 (setq rtn (org-agenda-get-day-entries
20599 file date
20600 :deadline :scheduled :timestamp :sexp :closed))
20601 (setq rtn (org-agenda-get-day-entries
20602 file date
20603 :deadline :scheduled :sexp :timestamp)))
20604 (setq rtnall (append rtnall rtn))))
20605 (if org-agenda-include-diary
20606 (progn
20607 (require 'diary-lib)
20608 (setq rtn (org-get-entries-from-diary date))
20609 (setq rtnall (append rtnall rtn))))
20610 (if (or rtnall org-agenda-show-all-dates)
20611 (progn
20612 (setq day-cnt (1+ day-cnt))
20613 (insert
20614 (if (stringp org-agenda-format-date)
20615 (format-time-string org-agenda-format-date
20616 (org-time-from-absolute date))
20617 (funcall org-agenda-format-date date))
20618 "\n")
20619 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20620 (put-text-property s (1- (point)) 'org-date-line t)
20621 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
20622 (if todayp (put-text-property s (1- (point)) 'org-today t))
20623 (if rtnall (insert
20624 (org-finalize-agenda-entries
20625 (org-agenda-add-time-grid-maybe
20626 rtnall nd todayp))
20627 "\n"))
20628 (put-text-property s (1- (point)) 'day d)
20629 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
20630 (goto-char (point-min))
20631 (org-fit-agenda-window)
20632 (unless (and (pos-visible-in-window-p (point-min))
20633 (pos-visible-in-window-p (point-max)))
20634 (goto-char (1- (point-max)))
20635 (recenter -1)
20636 (if (not (pos-visible-in-window-p (or start-pos 1)))
20637 (progn
20638 (goto-char (or start-pos 1))
20639 (recenter 1))))
20640 (goto-char (or start-pos 1))
20641 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
20642 (org-finalize-agenda)
20643 (setq buffer-read-only t)
20644 (message "")))
20646 (defun org-agenda-ndays-to-span (n)
20647 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
20649 ;;; Agenda TODO list
20651 (defvar org-select-this-todo-keyword nil)
20652 (defvar org-last-arg nil)
20654 ;;;###autoload
20655 (defun org-todo-list (arg)
20656 "Show all TODO entries from all agenda file in a single list.
20657 The prefix arg can be used to select a specific TODO keyword and limit
20658 the list to these. When using \\[universal-argument], you will be prompted
20659 for a keyword. A numeric prefix directly selects the Nth keyword in
20660 `org-todo-keywords-1'."
20661 (interactive "P")
20662 (require 'calendar)
20663 (org-compile-prefix-format 'todo)
20664 (org-set-sorting-strategy 'todo)
20665 (org-prepare-agenda "TODO")
20666 (let* ((today (time-to-days (current-time)))
20667 (date (calendar-gregorian-from-absolute today))
20668 (kwds org-todo-keywords-for-agenda)
20669 (completion-ignore-case t)
20670 (org-select-this-todo-keyword
20671 (if (stringp arg) arg
20672 (and arg (integerp arg) (> arg 0)
20673 (nth (1- arg) kwds))))
20674 rtn rtnall files file pos)
20675 (when (equal arg '(4))
20676 (setq org-select-this-todo-keyword
20677 (completing-read "Keyword (or KWD1|K2D2|...): "
20678 (mapcar 'list kwds) nil nil)))
20679 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
20680 (org-set-local 'org-last-arg arg)
20681 (setq org-agenda-redo-command
20682 '(org-todo-list (or current-prefix-arg org-last-arg)))
20683 (setq files (org-agenda-files)
20684 rtnall nil)
20685 (while (setq file (pop files))
20686 (catch 'nextfile
20687 (org-check-agenda-file file)
20688 (setq rtn (org-agenda-get-day-entries file date :todo))
20689 (setq rtnall (append rtnall rtn))))
20690 (if org-agenda-overriding-header
20691 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20692 nil 'face 'org-agenda-structure) "\n")
20693 (insert "Global list of TODO items of type: ")
20694 (add-text-properties (point-min) (1- (point))
20695 (list 'face 'org-agenda-structure))
20696 (setq pos (point))
20697 (insert (or org-select-this-todo-keyword "ALL") "\n")
20698 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20699 (setq pos (point))
20700 (unless org-agenda-multi
20701 (insert "Available with `N r': (0)ALL")
20702 (let ((n 0) s)
20703 (mapc (lambda (x)
20704 (setq s (format "(%d)%s" (setq n (1+ n)) x))
20705 (if (> (+ (current-column) (string-width s) 1) (frame-width))
20706 (insert "\n "))
20707 (insert " " s))
20708 kwds))
20709 (insert "\n"))
20710 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20711 (when rtnall
20712 (insert (org-finalize-agenda-entries rtnall) "\n"))
20713 (goto-char (point-min))
20714 (org-fit-agenda-window)
20715 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
20716 (org-finalize-agenda)
20717 (setq buffer-read-only t)))
20719 ;;; Agenda tags match
20721 ;;;###autoload
20722 (defun org-tags-view (&optional todo-only match)
20723 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
20724 The prefix arg TODO-ONLY limits the search to TODO entries."
20725 (interactive "P")
20726 (org-compile-prefix-format 'tags)
20727 (org-set-sorting-strategy 'tags)
20728 (let* ((org-tags-match-list-sublevels
20729 (if todo-only t org-tags-match-list-sublevels))
20730 (completion-ignore-case t)
20731 rtn rtnall files file pos matcher
20732 buffer)
20733 (setq matcher (org-make-tags-matcher match)
20734 match (car matcher) matcher (cdr matcher))
20735 (org-prepare-agenda (concat "TAGS " match))
20736 (setq org-agenda-redo-command
20737 (list 'org-tags-view (list 'quote todo-only)
20738 (list 'if 'current-prefix-arg nil match)))
20739 (setq files (org-agenda-files)
20740 rtnall nil)
20741 (while (setq file (pop files))
20742 (catch 'nextfile
20743 (org-check-agenda-file file)
20744 (setq buffer (if (file-exists-p file)
20745 (org-get-agenda-file-buffer file)
20746 (error "No such file %s" file)))
20747 (if (not buffer)
20748 ;; If file does not exist, merror message to agenda
20749 (setq rtn (list
20750 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
20751 rtnall (append rtnall rtn))
20752 (with-current-buffer buffer
20753 (unless (org-mode-p)
20754 (error "Agenda file %s is not in `org-mode'" file))
20755 (save-excursion
20756 (save-restriction
20757 (if org-agenda-restrict
20758 (narrow-to-region org-agenda-restrict-begin
20759 org-agenda-restrict-end)
20760 (widen))
20761 (setq rtn (org-scan-tags 'agenda matcher todo-only))
20762 (setq rtnall (append rtnall rtn))))))))
20763 (if org-agenda-overriding-header
20764 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20765 nil 'face 'org-agenda-structure) "\n")
20766 (insert "Headlines with TAGS match: ")
20767 (add-text-properties (point-min) (1- (point))
20768 (list 'face 'org-agenda-structure))
20769 (setq pos (point))
20770 (insert match "\n")
20771 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20772 (setq pos (point))
20773 (unless org-agenda-multi
20774 (insert "Press `C-u r' to search again with new search string\n"))
20775 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20776 (when rtnall
20777 (insert (org-finalize-agenda-entries rtnall) "\n"))
20778 (goto-char (point-min))
20779 (org-fit-agenda-window)
20780 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
20781 (org-finalize-agenda)
20782 (setq buffer-read-only t)))
20784 ;;; Agenda Finding stuck projects
20786 (defvar org-agenda-skip-regexp nil
20787 "Regular expression used in skipping subtrees for the agenda.
20788 This is basically a temporary global variable that can be set and then
20789 used by user-defined selections using `org-agenda-skip-function'.")
20791 (defvar org-agenda-overriding-header nil
20792 "When this is set during todo and tags searches, will replace header.")
20794 (defun org-agenda-skip-subtree-when-regexp-matches ()
20795 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
20796 If yes, it returns the end position of this tree, causing agenda commands
20797 to skip this subtree. This is a function that can be put into
20798 `org-agenda-skip-function' for the duration of a command."
20799 (let ((end (save-excursion (org-end-of-subtree t)))
20800 skip)
20801 (save-excursion
20802 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
20803 (and skip end)))
20805 (defun org-agenda-skip-entry-if (&rest conditions)
20806 "Skip entry if any of CONDITIONS is true.
20807 See `org-agenda-skip-if' for details."
20808 (org-agenda-skip-if nil conditions))
20810 (defun org-agenda-skip-subtree-if (&rest conditions)
20811 "Skip entry if any of CONDITIONS is true.
20812 See `org-agenda-skip-if' for details."
20813 (org-agenda-skip-if t conditions))
20815 (defun org-agenda-skip-if (subtree conditions)
20816 "Checks current entity for CONDITIONS.
20817 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
20818 the entry, i.e. the text before the next heading is checked.
20820 CONDITIONS is a list of symbols, boolean OR is used to combine the results
20821 from different tests. Valid conditions are:
20823 scheduled Check if there is a scheduled cookie
20824 notscheduled Check if there is no scheduled cookie
20825 deadline Check if there is a deadline
20826 notdeadline Check if there is no deadline
20827 regexp Check if regexp matches
20828 notregexp Check if regexp does not match.
20830 The regexp is taken from the conditions list, it must come right after
20831 the `regexp' or `notregexp' element.
20833 If any of these conditions is met, this function returns the end point of
20834 the entity, causing the search to continue from there. This is a function
20835 that can be put into `org-agenda-skip-function' for the duration of a command."
20836 (let (beg end m)
20837 (org-back-to-heading t)
20838 (setq beg (point)
20839 end (if subtree
20840 (progn (org-end-of-subtree t) (point))
20841 (progn (outline-next-heading) (1- (point)))))
20842 (goto-char beg)
20843 (and
20845 (and (memq 'scheduled conditions)
20846 (re-search-forward org-scheduled-time-regexp end t))
20847 (and (memq 'notscheduled conditions)
20848 (not (re-search-forward org-scheduled-time-regexp end t)))
20849 (and (memq 'deadline conditions)
20850 (re-search-forward org-deadline-time-regexp end t))
20851 (and (memq 'notdeadline conditions)
20852 (not (re-search-forward org-deadline-time-regexp end t)))
20853 (and (setq m (memq 'regexp conditions))
20854 (stringp (nth 1 m))
20855 (re-search-forward (nth 1 m) end t))
20856 (and (setq m (memq 'notregexp conditions))
20857 (stringp (nth 1 m))
20858 (not (re-search-forward (nth 1 m) end t))))
20859 end)))
20861 ;;;###autoload
20862 (defun org-agenda-list-stuck-projects (&rest ignore)
20863 "Create agenda view for projects that are stuck.
20864 Stuck projects are project that have no next actions. For the definitions
20865 of what a project is and how to check if it stuck, customize the variable
20866 `org-stuck-projects'.
20867 MATCH is being ignored."
20868 (interactive)
20869 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
20870 ;; FIXME: we could have used org-agenda-skip-if here.
20871 (org-agenda-overriding-header "List of stuck projects: ")
20872 (matcher (nth 0 org-stuck-projects))
20873 (todo (nth 1 org-stuck-projects))
20874 (todo-wds (if (member "*" todo)
20875 (progn
20876 (org-prepare-agenda-buffers (org-agenda-files))
20877 (org-delete-all
20878 org-done-keywords-for-agenda
20879 (copy-sequence org-todo-keywords-for-agenda)))
20880 todo))
20881 (todo-re (concat "^\\*+[ \t]+\\("
20882 (mapconcat 'identity todo-wds "\\|")
20883 "\\)\\>"))
20884 (tags (nth 2 org-stuck-projects))
20885 (tags-re (if (member "*" tags)
20886 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
20887 (concat "^\\*+ .*:\\("
20888 (mapconcat 'identity tags "\\|")
20889 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
20890 (gen-re (nth 3 org-stuck-projects))
20891 (re-list
20892 (delq nil
20893 (list
20894 (if todo todo-re)
20895 (if tags tags-re)
20896 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
20897 gen-re)))))
20898 (setq org-agenda-skip-regexp
20899 (if re-list
20900 (mapconcat 'identity re-list "\\|")
20901 (error "No information how to identify unstuck projects")))
20902 (org-tags-view nil matcher)
20903 (with-current-buffer org-agenda-buffer-name
20904 (setq org-agenda-redo-command
20905 '(org-agenda-list-stuck-projects
20906 (or current-prefix-arg org-last-arg))))))
20908 ;;; Diary integration
20910 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
20912 (defun org-get-entries-from-diary (date)
20913 "Get the (Emacs Calendar) diary entries for DATE."
20914 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
20915 (diary-display-hook '(fancy-diary-display))
20916 (pop-up-frames nil)
20917 (list-diary-entries-hook
20918 (cons 'org-diary-default-entry list-diary-entries-hook))
20919 (diary-file-name-prefix-function nil) ; turn this feature off
20920 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
20921 entries
20922 (org-disable-agenda-to-diary t))
20923 (save-excursion
20924 (save-window-excursion
20925 (funcall (if (fboundp 'diary-list-entries)
20926 'diary-list-entries 'list-diary-entries)
20927 date 1)))
20928 (if (not (get-buffer fancy-diary-buffer))
20929 (setq entries nil)
20930 (with-current-buffer fancy-diary-buffer
20931 (setq buffer-read-only nil)
20932 (if (zerop (buffer-size))
20933 ;; No entries
20934 (setq entries nil)
20935 ;; Omit the date and other unnecessary stuff
20936 (org-agenda-cleanup-fancy-diary)
20937 ;; Add prefix to each line and extend the text properties
20938 (if (zerop (buffer-size))
20939 (setq entries nil)
20940 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
20941 (set-buffer-modified-p nil)
20942 (kill-buffer fancy-diary-buffer)))
20943 (when entries
20944 (setq entries (org-split-string entries "\n"))
20945 (setq entries
20946 (mapcar
20947 (lambda (x)
20948 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
20949 ;; Extend the text properties to the beginning of the line
20950 (org-add-props x (text-properties-at (1- (length x)) x)
20951 'type "diary" 'date date))
20952 entries)))))
20954 (defun org-agenda-cleanup-fancy-diary ()
20955 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
20956 This gets rid of the date, the underline under the date, and
20957 the dummy entry installed by `org-mode' to ensure non-empty diary for each
20958 date. It also removes lines that contain only whitespace."
20959 (goto-char (point-min))
20960 (if (looking-at ".*?:[ \t]*")
20961 (progn
20962 (replace-match "")
20963 (re-search-forward "\n=+$" nil t)
20964 (replace-match "")
20965 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
20966 (re-search-forward "\n=+$" nil t)
20967 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
20968 (goto-char (point-min))
20969 (while (re-search-forward "^ +\n" nil t)
20970 (replace-match ""))
20971 (goto-char (point-min))
20972 (if (re-search-forward "^Org-mode dummy\n?" nil t)
20973 (replace-match "")))
20975 ;; Make sure entries from the diary have the right text properties.
20976 (eval-after-load "diary-lib"
20977 '(if (boundp 'diary-modify-entry-list-string-function)
20978 ;; We can rely on the hook, nothing to do
20980 ;; Hook not avaiable, must use advice to make this work
20981 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
20982 "Make the position visible."
20983 (if (and org-disable-agenda-to-diary ;; called from org-agenda
20984 (stringp string)
20985 buffer-file-name)
20986 (setq string (org-modify-diary-entry-string string))))))
20988 (defun org-modify-diary-entry-string (string)
20989 "Add text properties to string, allowing org-mode to act on it."
20990 (org-add-props string nil
20991 'mouse-face 'highlight
20992 'keymap org-agenda-keymap
20993 'help-echo (if buffer-file-name
20994 (format "mouse-2 or RET jump to diary file %s"
20995 (abbreviate-file-name buffer-file-name))
20997 'org-agenda-diary-link t
20998 'org-marker (org-agenda-new-marker (point-at-bol))))
21000 (defun org-diary-default-entry ()
21001 "Add a dummy entry to the diary.
21002 Needed to avoid empty dates which mess up holiday display."
21003 ;; Catch the error if dealing with the new add-to-diary-alist
21004 (when org-disable-agenda-to-diary
21005 (condition-case nil
21006 (add-to-diary-list original-date "Org-mode dummy" "")
21007 (error
21008 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
21010 ;;;###autoload
21011 (defun org-diary (&rest args)
21012 "Return diary information from org-files.
21013 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
21014 It accesses org files and extracts information from those files to be
21015 listed in the diary. The function accepts arguments specifying what
21016 items should be listed. The following arguments are allowed:
21018 :timestamp List the headlines of items containing a date stamp or
21019 date range matching the selected date. Deadlines will
21020 also be listed, on the expiration day.
21022 :sexp List entries resulting from diary-like sexps.
21024 :deadline List any deadlines past due, or due within
21025 `org-deadline-warning-days'. The listing occurs only
21026 in the diary for *today*, not at any other date. If
21027 an entry is marked DONE, it is no longer listed.
21029 :scheduled List all items which are scheduled for the given date.
21030 The diary for *today* also contains items which were
21031 scheduled earlier and are not yet marked DONE.
21033 :todo List all TODO items from the org-file. This may be a
21034 long list - so this is not turned on by default.
21035 Like deadlines, these entries only show up in the
21036 diary for *today*, not at any other date.
21038 The call in the diary file should look like this:
21040 &%%(org-diary) ~/path/to/some/orgfile.org
21042 Use a separate line for each org file to check. Or, if you omit the file name,
21043 all files listed in `org-agenda-files' will be checked automatically:
21045 &%%(org-diary)
21047 If you don't give any arguments (as in the example above), the default
21048 arguments (:deadline :scheduled :timestamp :sexp) are used.
21049 So the example above may also be written as
21051 &%%(org-diary :deadline :timestamp :sexp :scheduled)
21053 The function expects the lisp variables `entry' and `date' to be provided
21054 by the caller, because this is how the calendar works. Don't use this
21055 function from a program - use `org-agenda-get-day-entries' instead."
21056 (org-agenda-maybe-reset-markers)
21057 (org-compile-prefix-format 'agenda)
21058 (org-set-sorting-strategy 'agenda)
21059 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21060 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
21061 (list entry)
21062 (org-agenda-files t)))
21063 file rtn results)
21064 (org-prepare-agenda-buffers files)
21065 ;; If this is called during org-agenda, don't return any entries to
21066 ;; the calendar. Org Agenda will list these entries itself.
21067 (if org-disable-agenda-to-diary (setq files nil))
21068 (while (setq file (pop files))
21069 (setq rtn (apply 'org-agenda-get-day-entries file date args))
21070 (setq results (append results rtn)))
21071 (if results
21072 (concat (org-finalize-agenda-entries results) "\n"))))
21074 ;;; Agenda entry finders
21076 (defun org-agenda-get-day-entries (file date &rest args)
21077 "Does the work for `org-diary' and `org-agenda'.
21078 FILE is the path to a file to be checked for entries. DATE is date like
21079 the one returned by `calendar-current-date'. ARGS are symbols indicating
21080 which kind of entries should be extracted. For details about these, see
21081 the documentation of `org-diary'."
21082 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21083 (let* ((org-startup-folded nil)
21084 (org-startup-align-all-tables nil)
21085 (buffer (if (file-exists-p file)
21086 (org-get-agenda-file-buffer file)
21087 (error "No such file %s" file)))
21088 arg results rtn)
21089 (if (not buffer)
21090 ;; If file does not exist, make sure an error message ends up in diary
21091 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21092 (with-current-buffer buffer
21093 (unless (org-mode-p)
21094 (error "Agenda file %s is not in `org-mode'" file))
21095 (let ((case-fold-search nil))
21096 (save-excursion
21097 (save-restriction
21098 (if org-agenda-restrict
21099 (narrow-to-region org-agenda-restrict-begin
21100 org-agenda-restrict-end)
21101 (widen))
21102 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
21103 (while (setq arg (pop args))
21104 (cond
21105 ((and (eq arg :todo)
21106 (equal date (calendar-current-date)))
21107 (setq rtn (org-agenda-get-todos))
21108 (setq results (append results rtn)))
21109 ((eq arg :timestamp)
21110 (setq rtn (org-agenda-get-blocks))
21111 (setq results (append results rtn))
21112 (setq rtn (org-agenda-get-timestamps))
21113 (setq results (append results rtn)))
21114 ((eq arg :sexp)
21115 (setq rtn (org-agenda-get-sexps))
21116 (setq results (append results rtn)))
21117 ((eq arg :scheduled)
21118 (setq rtn (org-agenda-get-scheduled))
21119 (setq results (append results rtn)))
21120 ((eq arg :closed)
21121 (setq rtn (org-agenda-get-closed))
21122 (setq results (append results rtn)))
21123 ((eq arg :deadline)
21124 (setq rtn (org-agenda-get-deadlines))
21125 (setq results (append results rtn))))))))
21126 results))))
21128 (defun org-entry-is-todo-p ()
21129 (member (org-get-todo-state) org-not-done-keywords))
21131 (defun org-entry-is-done-p ()
21132 (member (org-get-todo-state) org-done-keywords))
21134 (defun org-get-todo-state ()
21135 (save-excursion
21136 (org-back-to-heading t)
21137 (and (looking-at org-todo-line-regexp)
21138 (match-end 2)
21139 (match-string 2))))
21141 (defun org-at-date-range-p (&optional inactive-ok)
21142 "Is the cursor inside a date range?"
21143 (interactive)
21144 (save-excursion
21145 (catch 'exit
21146 (let ((pos (point)))
21147 (skip-chars-backward "^[<\r\n")
21148 (skip-chars-backward "<[")
21149 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21150 (>= (match-end 0) pos)
21151 (throw 'exit t))
21152 (skip-chars-backward "^<[\r\n")
21153 (skip-chars-backward "<[")
21154 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21155 (>= (match-end 0) pos)
21156 (throw 'exit t)))
21157 nil)))
21159 (defun org-agenda-get-todos ()
21160 "Return the TODO information for agenda display."
21161 (let* ((props (list 'face nil
21162 'done-face 'org-done
21163 'org-not-done-regexp org-not-done-regexp
21164 'org-todo-regexp org-todo-regexp
21165 'mouse-face 'highlight
21166 'keymap org-agenda-keymap
21167 'help-echo
21168 (format "mouse-2 or RET jump to org file %s"
21169 (abbreviate-file-name buffer-file-name))))
21170 ;; FIXME: get rid of the \n at some point but watch out
21171 (regexp (concat "^\\*+[ \t]+\\("
21172 (if org-select-this-todo-keyword
21173 (if (equal org-select-this-todo-keyword "*")
21174 org-todo-regexp
21175 (concat "\\<\\("
21176 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
21177 "\\)\\>"))
21178 org-not-done-regexp)
21179 "[^\n\r]*\\)"))
21180 marker priority category tags
21181 ee txt beg end)
21182 (goto-char (point-min))
21183 (while (re-search-forward regexp nil t)
21184 (catch :skip
21185 (save-match-data
21186 (beginning-of-line)
21187 (setq beg (point) end (progn (outline-next-heading) (point)))
21188 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
21189 (re-search-forward org-ts-regexp end t))
21190 (and org-agenda-todo-ignore-scheduled (goto-char beg)
21191 (re-search-forward org-scheduled-time-regexp end t))
21192 (and org-agenda-todo-ignore-deadlines (goto-char beg)
21193 (re-search-forward org-deadline-time-regexp end t)
21194 (org-deadline-close (match-string 1))))
21195 (goto-char (1+ beg))
21196 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
21197 (throw :skip nil)))
21198 (goto-char beg)
21199 (org-agenda-skip)
21200 (goto-char (match-beginning 1))
21201 (setq marker (org-agenda-new-marker (match-beginning 0))
21202 category (org-get-category)
21203 tags (org-get-tags-at (point))
21204 txt (org-format-agenda-item "" (match-string 1) category tags)
21205 priority (1+ (org-get-priority txt)))
21206 (org-add-props txt props
21207 'org-marker marker 'org-hd-marker marker
21208 'priority priority 'org-category category
21209 'type "todo")
21210 (push txt ee)
21211 (if org-agenda-todo-list-sublevels
21212 (goto-char (match-end 1))
21213 (org-end-of-subtree 'invisible))))
21214 (nreverse ee)))
21216 (defconst org-agenda-no-heading-message
21217 "No heading for this item in buffer or region.")
21219 (defun org-agenda-get-timestamps ()
21220 "Return the date stamp information for agenda display."
21221 (let* ((props (list 'face nil
21222 'org-not-done-regexp org-not-done-regexp
21223 'org-todo-regexp org-todo-regexp
21224 'mouse-face 'highlight
21225 'keymap org-agenda-keymap
21226 'help-echo
21227 (format "mouse-2 or RET jump to org file %s"
21228 (abbreviate-file-name buffer-file-name))))
21229 (d1 (calendar-absolute-from-gregorian date))
21230 (remove-re
21231 (concat
21232 (regexp-quote
21233 (format-time-string
21234 "<%Y-%m-%d"
21235 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
21236 ".*?>"))
21237 (regexp
21238 (concat
21239 (regexp-quote
21240 (substring
21241 (format-time-string
21242 (car org-time-stamp-formats)
21243 (apply 'encode-time ; DATE bound by calendar
21244 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21245 0 11))
21246 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
21247 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
21248 marker hdmarker deadlinep scheduledp donep tmp priority category
21249 ee txt timestr tags b0 b3 e3 head)
21250 (goto-char (point-min))
21251 (while (re-search-forward regexp nil t)
21252 (setq b0 (match-beginning 0)
21253 b3 (match-beginning 3) e3 (match-end 3))
21254 (catch :skip
21255 (and (org-at-date-range-p) (throw :skip nil))
21256 (org-agenda-skip)
21257 (if (and (match-end 1)
21258 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
21259 (throw :skip nil))
21260 (if (and e3
21261 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
21262 (throw :skip nil))
21263 (setq marker (org-agenda-new-marker b0)
21264 category (org-get-category b0)
21265 tmp (buffer-substring (max (point-min)
21266 (- b0 org-ds-keyword-length))
21268 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
21269 deadlinep (string-match org-deadline-regexp tmp)
21270 scheduledp (string-match org-scheduled-regexp tmp)
21271 donep (org-entry-is-done-p))
21272 (if (or scheduledp deadlinep) (throw :skip t))
21273 (if (string-match ">" timestr)
21274 ;; substring should only run to end of time stamp
21275 (setq timestr (substring timestr 0 (match-end 0))))
21276 (save-excursion
21277 (if (re-search-backward "^\\*+ " nil t)
21278 (progn
21279 (goto-char (match-beginning 0))
21280 (setq hdmarker (org-agenda-new-marker)
21281 tags (org-get-tags-at))
21282 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21283 (setq head (match-string 1))
21284 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
21285 (setq txt (org-format-agenda-item
21286 nil head category tags timestr nil
21287 remove-re)))
21288 (setq txt org-agenda-no-heading-message))
21289 (setq priority (org-get-priority txt))
21290 (org-add-props txt props
21291 'org-marker marker 'org-hd-marker hdmarker)
21292 (org-add-props txt nil 'priority priority
21293 'org-category category 'date date
21294 'type "timestamp")
21295 (push txt ee))
21296 (outline-next-heading)))
21297 (nreverse ee)))
21299 (defun org-agenda-get-sexps ()
21300 "Return the sexp information for agenda display."
21301 (require 'diary-lib)
21302 (let* ((props (list 'face nil
21303 'mouse-face 'highlight
21304 'keymap org-agenda-keymap
21305 'help-echo
21306 (format "mouse-2 or RET jump to org file %s"
21307 (abbreviate-file-name buffer-file-name))))
21308 (regexp "^&?%%(")
21309 marker category ee txt tags entry result beg b sexp sexp-entry)
21310 (goto-char (point-min))
21311 (while (re-search-forward regexp nil t)
21312 (catch :skip
21313 (org-agenda-skip)
21314 (setq beg (match-beginning 0))
21315 (goto-char (1- (match-end 0)))
21316 (setq b (point))
21317 (forward-sexp 1)
21318 (setq sexp (buffer-substring b (point)))
21319 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
21320 (org-trim (match-string 1))
21321 ""))
21322 (setq result (org-diary-sexp-entry sexp sexp-entry date))
21323 (when result
21324 (setq marker (org-agenda-new-marker beg)
21325 category (org-get-category beg))
21327 (if (string-match "\\S-" result)
21328 (setq txt result)
21329 (setq txt "SEXP entry returned empty string"))
21331 (setq txt (org-format-agenda-item
21332 "" txt category tags 'time))
21333 (org-add-props txt props 'org-marker marker)
21334 (org-add-props txt nil
21335 'org-category category 'date date
21336 'type "sexp")
21337 (push txt ee))))
21338 (nreverse ee)))
21340 (defun org-agenda-get-closed ()
21341 "Return the logged TODO entries for agenda display."
21342 (let* ((props (list 'mouse-face 'highlight
21343 'org-not-done-regexp org-not-done-regexp
21344 'org-todo-regexp org-todo-regexp
21345 'keymap org-agenda-keymap
21346 'help-echo
21347 (format "mouse-2 or RET jump to org file %s"
21348 (abbreviate-file-name buffer-file-name))))
21349 (regexp (concat
21350 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
21351 (regexp-quote
21352 (substring
21353 (format-time-string
21354 (car org-time-stamp-formats)
21355 (apply 'encode-time ; DATE bound by calendar
21356 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21357 1 11))))
21358 marker hdmarker priority category tags closedp
21359 ee txt timestr)
21360 (goto-char (point-min))
21361 (while (re-search-forward regexp nil t)
21362 (catch :skip
21363 (org-agenda-skip)
21364 (setq marker (org-agenda-new-marker (match-beginning 0))
21365 closedp (equal (match-string 1) org-closed-string)
21366 category (org-get-category (match-beginning 0))
21367 timestr (buffer-substring (match-beginning 0) (point-at-eol))
21368 ;; donep (org-entry-is-done-p)
21370 (if (string-match "\\]" timestr)
21371 ;; substring should only run to end of time stamp
21372 (setq timestr (substring timestr 0 (match-end 0))))
21373 (save-excursion
21374 (if (re-search-backward "^\\*+ " nil t)
21375 (progn
21376 (goto-char (match-beginning 0))
21377 (setq hdmarker (org-agenda-new-marker)
21378 tags (org-get-tags-at))
21379 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21380 (setq txt (org-format-agenda-item
21381 (if closedp "Closed: " "Clocked: ")
21382 (match-string 1) category tags timestr)))
21383 (setq txt org-agenda-no-heading-message))
21384 (setq priority 100000)
21385 (org-add-props txt props
21386 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
21387 'priority priority 'org-category category
21388 'type "closed" 'date date
21389 'undone-face 'org-warning 'done-face 'org-done)
21390 (push txt ee))
21391 (goto-char (point-at-eol))))
21392 ; (outline-next-heading)))
21393 (nreverse ee)))
21395 (defun org-agenda-get-deadlines ()
21396 "Return the deadline information for agenda display."
21397 (let* ((props (list 'mouse-face 'highlight
21398 'org-not-done-regexp org-not-done-regexp
21399 'org-todo-regexp org-todo-regexp
21400 'keymap org-agenda-keymap
21401 'help-echo
21402 (format "mouse-2 or RET jump to org file %s"
21403 (abbreviate-file-name buffer-file-name))))
21404 (regexp org-deadline-time-regexp)
21405 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21406 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21407 d2 diff dfrac wdays pos pos1 category tags
21408 ee txt head face s upcomingp donep timestr)
21409 (goto-char (point-min))
21410 (while (re-search-forward regexp nil t)
21411 (catch :skip
21412 (org-agenda-skip)
21413 (setq s (match-string 1)
21414 pos (1- (match-beginning 1))
21415 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21416 diff (- d2 d1)
21417 wdays (org-get-wdays s)
21418 dfrac (/ (* 1.0 (- wdays diff)) (max wdays 1))
21419 upcomingp (and todayp (> diff 0)))
21420 ;; When to show a deadline in the calendar:
21421 ;; If the expiration is within wdays warning time.
21422 ;; Past-due deadlines are only shown on the current date
21423 (if (or (and (<= diff wdays)
21424 (and todayp (not org-agenda-only-exact-dates)))
21425 (= diff 0))
21426 (save-excursion
21427 (setq category (org-get-category))
21428 (if (re-search-backward "^\\*+[ \t]+" nil t)
21429 (progn
21430 (goto-char (match-end 0))
21431 (setq pos1 (match-beginning 0))
21432 (setq tags (org-get-tags-at pos1))
21433 (setq head (buffer-substring-no-properties
21434 (point)
21435 (progn (skip-chars-forward "^\r\n")
21436 (point))))
21437 (setq donep (string-match org-looking-at-done-regexp head))
21438 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21439 (setq timestr
21440 (concat (substring s (match-beginning 1)) " "))
21441 (setq timestr 'time))
21442 (if (and donep
21443 (or org-agenda-skip-deadline-if-done
21444 (not (= diff 0))))
21445 (setq txt nil)
21446 (setq txt (org-format-agenda-item
21447 (if (= diff 0)
21448 (car org-agenda-deadline-leaders)
21449 (format (nth 1 org-agenda-deadline-leaders)
21450 diff))
21451 head category tags timestr))))
21452 (setq txt org-agenda-no-heading-message))
21453 (when txt
21454 (setq face (org-agenda-deadline-face dfrac))
21455 (org-add-props txt props
21456 'org-marker (org-agenda-new-marker pos)
21457 'org-hd-marker (org-agenda-new-marker pos1)
21458 'priority (+ (floor (* dfrac 100.))
21459 (org-get-priority txt))
21460 'org-category category
21461 'type (if upcomingp "upcoming-deadline" "deadline")
21462 'date (if upcomingp date d2)
21463 'face (if donep 'org-done face)
21464 'undone-face face 'done-face 'org-done)
21465 (push txt ee))))))
21466 (nreverse ee)))
21468 (defun org-agenda-deadline-face (fraction)
21469 "Return the face to displaying a deadline item.
21470 FRACTION is what fraction of the head-warning time has passed."
21471 (let ((faces org-agenda-deadline-faces) f)
21472 (catch 'exit
21473 (while (setq f (pop faces))
21474 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
21476 (defun org-agenda-get-scheduled ()
21477 "Return the scheduled information for agenda display."
21478 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
21479 'org-todo-regexp org-todo-regexp
21480 'done-face 'org-done
21481 'mouse-face 'highlight
21482 'keymap org-agenda-keymap
21483 'help-echo
21484 (format "mouse-2 or RET jump to org file %s"
21485 (abbreviate-file-name buffer-file-name))))
21486 (regexp org-scheduled-time-regexp)
21487 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21488 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21489 d2 diff pos pos1 category tags
21490 ee txt head pastschedp donep face timestr s)
21491 (goto-char (point-min))
21492 (while (re-search-forward regexp nil t)
21493 (catch :skip
21494 (org-agenda-skip)
21495 (setq s (match-string 1)
21496 pos (1- (match-beginning 1))
21497 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21498 ;;; is this right?
21499 ;;; do we need to do this for deadleine too????
21500 ;;; d2 (org-time-string-to-absolute (match-string 1) (if todayp nil d1))
21501 diff (- d2 d1))
21502 (setq pastschedp (and todayp (< diff 0)))
21503 ;; When to show a scheduled item in the calendar:
21504 ;; If it is on or past the date.
21505 (if (or (and (< diff 0)
21506 (and todayp (not org-agenda-only-exact-dates)))
21507 (= diff 0))
21508 (save-excursion
21509 (setq category (org-get-category))
21510 (if (re-search-backward "^\\*+[ \t]+" nil t)
21511 (progn
21512 (goto-char (match-end 0))
21513 (setq pos1 (match-beginning 0))
21514 (setq tags (org-get-tags-at))
21515 (setq head (buffer-substring-no-properties
21516 (point)
21517 (progn (skip-chars-forward "^\r\n") (point))))
21518 (setq donep (string-match org-looking-at-done-regexp head))
21519 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21520 (setq timestr
21521 (concat (substring s (match-beginning 1)) " "))
21522 (setq timestr 'time))
21523 (if (and donep
21524 (or org-agenda-skip-scheduled-if-done
21525 (not (= diff 0))))
21526 (setq txt nil)
21527 (setq txt (org-format-agenda-item
21528 (if (= diff 0)
21529 (car org-agenda-scheduled-leaders)
21530 (format (nth 1 org-agenda-scheduled-leaders)
21531 (- 1 diff)))
21532 head category tags timestr))))
21533 (setq txt org-agenda-no-heading-message))
21534 (when txt
21535 (setq face (if pastschedp
21536 'org-scheduled-previously
21537 'org-scheduled-today))
21538 (org-add-props txt props
21539 'undone-face face
21540 'face (if donep 'org-done face)
21541 'org-marker (org-agenda-new-marker pos)
21542 'org-hd-marker (org-agenda-new-marker pos1)
21543 'type (if pastschedp "past-scheduled" "scheduled")
21544 'date (if pastschedp d2 date)
21545 'priority (+ 94 (- 5 diff) (org-get-priority txt))
21546 'org-category category)
21547 (push txt ee))))))
21548 (nreverse ee)))
21550 (defun org-agenda-get-blocks ()
21551 "Return the date-range information for agenda display."
21552 (let* ((props (list 'face nil
21553 'org-not-done-regexp org-not-done-regexp
21554 'org-todo-regexp org-todo-regexp
21555 'mouse-face 'highlight
21556 'keymap org-agenda-keymap
21557 'help-echo
21558 (format "mouse-2 or RET jump to org file %s"
21559 (abbreviate-file-name buffer-file-name))))
21560 (regexp org-tr-regexp)
21561 (d0 (calendar-absolute-from-gregorian date))
21562 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
21563 donep head)
21564 (goto-char (point-min))
21565 (while (re-search-forward regexp nil t)
21566 (catch :skip
21567 (org-agenda-skip)
21568 (setq pos (point))
21569 (setq timestr (match-string 0)
21570 s1 (match-string 1)
21571 s2 (match-string 2)
21572 d1 (time-to-days (org-time-string-to-time s1))
21573 d2 (time-to-days (org-time-string-to-time s2)))
21574 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
21575 ;; Only allow days between the limits, because the normal
21576 ;; date stamps will catch the limits.
21577 (save-excursion
21578 (setq marker (org-agenda-new-marker (point)))
21579 (setq category (org-get-category))
21580 (if (re-search-backward "^\\*+ " nil t)
21581 (progn
21582 (goto-char (match-beginning 0))
21583 (setq hdmarker (org-agenda-new-marker (point)))
21584 (setq tags (org-get-tags-at))
21585 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21586 (setq head (match-string 1))
21587 (and org-agenda-skip-timestamp-if-done
21588 (org-entry-is-done-p)
21589 (throw :skip t))
21590 (setq txt (org-format-agenda-item
21591 (format (if (= d1 d2) "" "(%d/%d): ")
21592 (1+ (- d0 d1)) (1+ (- d2 d1)))
21593 head category tags
21594 (if (= d0 d1) timestr))))
21595 (setq txt org-agenda-no-heading-message))
21596 (org-add-props txt props
21597 'org-marker marker 'org-hd-marker hdmarker
21598 'type "block" 'date date
21599 'priority (org-get-priority txt) 'org-category category)
21600 (push txt ee)))
21601 (goto-char pos)))
21602 ;; Sort the entries by expiration date.
21603 (nreverse ee)))
21605 ;;; Agenda presentation and sorting
21607 (defconst org-plain-time-of-day-regexp
21608 (concat
21609 "\\(\\<[012]?[0-9]"
21610 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21611 "\\(--?"
21612 "\\(\\<[012]?[0-9]"
21613 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21614 "\\)?")
21615 "Regular expression to match a plain time or time range.
21616 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
21617 groups carry important information:
21618 0 the full match
21619 1 the first time, range or not
21620 8 the second time, if it is a range.")
21622 (defconst org-plain-time-extension-regexp
21623 (concat
21624 "\\(\\<[012]?[0-9]"
21625 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21626 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
21627 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
21628 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
21629 groups carry important information:
21630 0 the full match
21631 7 hours of duration
21632 9 minutes of duration")
21634 (defconst org-stamp-time-of-day-regexp
21635 (concat
21636 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
21637 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
21638 "\\(--?"
21639 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
21640 "Regular expression to match a timestamp time or time range.
21641 After a match, the following groups carry important information:
21642 0 the full match
21643 1 date plus weekday, for backreferencing to make sure both times on same day
21644 2 the first time, range or not
21645 4 the second time, if it is a range.")
21647 (defvar org-prefix-has-time nil
21648 "A flag, set by `org-compile-prefix-format'.
21649 The flag is set if the currently compiled format contains a `%t'.")
21650 (defvar org-prefix-has-tag nil
21651 "A flag, set by `org-compile-prefix-format'.
21652 The flag is set if the currently compiled format contains a `%T'.")
21654 (defun org-format-agenda-item (extra txt &optional category tags dotime
21655 noprefix remove-re)
21656 "Format TXT to be inserted into the agenda buffer.
21657 In particular, it adds the prefix and corresponding text properties. EXTRA
21658 must be a string and replaces the `%s' specifier in the prefix format.
21659 CATEGORY (string, symbol or nil) may be used to overrule the default
21660 category taken from local variable or file name. It will replace the `%c'
21661 specifier in the format. DOTIME, when non-nil, indicates that a
21662 time-of-day should be extracted from TXT for sorting of this entry, and for
21663 the `%t' specifier in the format. When DOTIME is a string, this string is
21664 searched for a time before TXT is. NOPREFIX is a flag and indicates that
21665 only the correctly processes TXT should be returned - this is used by
21666 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
21667 Any match of REMOVE-RE will be removed from TXT."
21668 (save-match-data
21669 ;; Diary entries sometimes have extra whitespace at the beginning
21670 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
21671 (let* ((category (or category
21672 org-category
21673 (if buffer-file-name
21674 (file-name-sans-extension
21675 (file-name-nondirectory buffer-file-name))
21676 "")))
21677 (tag (if tags (nth (1- (length tags)) tags) ""))
21678 time ; time and tag are needed for the eval of the prefix format
21679 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
21680 (time-of-day (and dotime (org-get-time-of-day ts)))
21681 stamp plain s0 s1 s2 rtn srp)
21682 (when (and dotime time-of-day org-prefix-has-time)
21683 ;; Extract starting and ending time and move them to prefix
21684 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
21685 (setq plain (string-match org-plain-time-of-day-regexp ts)))
21686 (setq s0 (match-string 0 ts)
21687 srp (and stamp (match-end 3))
21688 s1 (match-string (if plain 1 2) ts)
21689 s2 (match-string (if plain 8 (if srp 4 6)) ts))
21691 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
21692 ;; them, we might want to remove them there to avoid duplication.
21693 ;; The user can turn this off with a variable.
21694 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
21695 (string-match (concat (regexp-quote s0) " *") txt)
21696 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
21697 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
21698 (= (match-beginning 0) 0)
21700 (setq txt (replace-match "" nil nil txt))))
21701 ;; Normalize the time(s) to 24 hour
21702 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
21703 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
21705 (when (and s1 (not s2) org-agenda-default-appointment-duration
21706 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
21707 (let ((m (+ (string-to-number (match-string 2 s1))
21708 (* 60 (string-to-number (match-string 1 s1)))
21709 org-agenda-default-appointment-duration))
21711 (setq h (/ m 60) m (- m (* h 60)))
21712 (setq s2 (format "%02d:%02d" h m))))
21714 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
21715 txt)
21716 ;; Tags are in the string
21717 (if (or (eq org-agenda-remove-tags t)
21718 (and org-agenda-remove-tags
21719 org-prefix-has-tag))
21720 (setq txt (replace-match "" t t txt))
21721 (setq txt (replace-match
21722 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
21723 (match-string 2 txt))
21724 t t txt))))
21726 (when remove-re
21727 (while (string-match remove-re txt)
21728 (setq txt (replace-match "" t t txt))))
21730 ;; Create the final string
21731 (if noprefix
21732 (setq rtn txt)
21733 ;; Prepare the variables needed in the eval of the compiled format
21734 (setq time (cond (s2 (concat s1 "-" s2))
21735 (s1 (concat s1 "......"))
21736 (t ""))
21737 extra (or extra "")
21738 category (if (symbolp category) (symbol-name category) category))
21739 ;; Evaluate the compiled format
21740 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
21742 ;; And finally add the text properties
21743 (org-add-props rtn nil
21744 'org-category (downcase category) 'tags tags
21745 'org-highest-priority org-highest-priority
21746 'org-lowest-priority org-lowest-priority
21747 'prefix-length (- (length rtn) (length txt))
21748 'time-of-day time-of-day
21749 'txt txt
21750 'time time
21751 'extra extra
21752 'dotime dotime))))
21754 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
21755 (defvar org-agenda-sorting-strategy-selected nil)
21757 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
21758 (catch 'exit
21759 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
21760 ((and todayp (member 'today (car org-agenda-time-grid))))
21761 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
21762 ((member 'weekly (car org-agenda-time-grid)))
21763 (t (throw 'exit list)))
21764 (let* ((have (delq nil (mapcar
21765 (lambda (x) (get-text-property 1 'time-of-day x))
21766 list)))
21767 (string (nth 1 org-agenda-time-grid))
21768 (gridtimes (nth 2 org-agenda-time-grid))
21769 (req (car org-agenda-time-grid))
21770 (remove (member 'remove-match req))
21771 new time)
21772 (if (and (member 'require-timed req) (not have))
21773 ;; don't show empty grid
21774 (throw 'exit list))
21775 (while (setq time (pop gridtimes))
21776 (unless (and remove (member time have))
21777 (setq time (int-to-string time))
21778 (push (org-format-agenda-item
21779 nil string "" nil
21780 (concat (substring time 0 -2) ":" (substring time -2)))
21781 new)
21782 (put-text-property
21783 1 (length (car new)) 'face 'org-time-grid (car new))))
21784 (if (member 'time-up org-agenda-sorting-strategy-selected)
21785 (append new list)
21786 (append list new)))))
21788 (defun org-compile-prefix-format (key)
21789 "Compile the prefix format into a Lisp form that can be evaluated.
21790 The resulting form is returned and stored in the variable
21791 `org-prefix-format-compiled'."
21792 (setq org-prefix-has-time nil org-prefix-has-tag nil)
21793 (let ((s (cond
21794 ((stringp org-agenda-prefix-format)
21795 org-agenda-prefix-format)
21796 ((assq key org-agenda-prefix-format)
21797 (cdr (assq key org-agenda-prefix-format)))
21798 (t " %-12:c%?-12t% s")))
21799 (start 0)
21800 varform vars var e c f opt)
21801 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
21802 s start)
21803 (setq var (cdr (assoc (match-string 4 s)
21804 '(("c" . category) ("t" . time) ("s" . extra)
21805 ("T" . tag))))
21806 c (or (match-string 3 s) "")
21807 opt (match-beginning 1)
21808 start (1+ (match-beginning 0)))
21809 (if (equal var 'time) (setq org-prefix-has-time t))
21810 (if (equal var 'tag) (setq org-prefix-has-tag t))
21811 (setq f (concat "%" (match-string 2 s) "s"))
21812 (if opt
21813 (setq varform
21814 `(if (equal "" ,var)
21816 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
21817 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
21818 (setq s (replace-match "%s" t nil s))
21819 (push varform vars))
21820 (setq vars (nreverse vars))
21821 (setq org-prefix-format-compiled `(format ,s ,@vars))))
21823 (defun org-set-sorting-strategy (key)
21824 (if (symbolp (car org-agenda-sorting-strategy))
21825 ;; the old format
21826 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
21827 (setq org-agenda-sorting-strategy-selected
21828 (or (cdr (assq key org-agenda-sorting-strategy))
21829 (cdr (assq 'agenda org-agenda-sorting-strategy))
21830 '(time-up category-keep priority-down)))))
21832 (defun org-get-time-of-day (s &optional string mod24)
21833 "Check string S for a time of day.
21834 If found, return it as a military time number between 0 and 2400.
21835 If not found, return nil.
21836 The optional STRING argument forces conversion into a 5 character wide string
21837 HH:MM."
21838 (save-match-data
21839 (when
21840 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
21841 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
21842 (let* ((h (string-to-number (match-string 1 s)))
21843 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
21844 (ampm (if (match-end 4) (downcase (match-string 4 s))))
21845 (am-p (equal ampm "am"))
21846 (h1 (cond ((not ampm) h)
21847 ((= h 12) (if am-p 0 12))
21848 (t (+ h (if am-p 0 12)))))
21849 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
21850 (mod h1 24) h1))
21851 (t0 (+ (* 100 h2) m))
21852 (t1 (concat (if (>= h1 24) "+" " ")
21853 (if (< t0 100) "0" "")
21854 (if (< t0 10) "0" "")
21855 (int-to-string t0))))
21856 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
21858 (defun org-finalize-agenda-entries (list &optional nosort)
21859 "Sort and concatenate the agenda items."
21860 (setq list (mapcar 'org-agenda-highlight-todo list))
21861 (if nosort
21862 list
21863 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
21865 (defun org-agenda-highlight-todo (x)
21866 (let (re pl)
21867 (if (eq x 'line)
21868 (save-excursion
21869 (beginning-of-line 1)
21870 (setq re (get-text-property (point) 'org-todo-regexp))
21871 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
21872 (when (looking-at (concat "[ \t]*\\.*" re " +"))
21873 (add-text-properties (match-beginning 0) (match-end 0)
21874 (list 'face (org-get-todo-face 0)))
21875 (let ((s (buffer-substring (match-beginning 1) (match-end 1))))
21876 (delete-region (match-beginning 1) (1- (match-end 0)))
21877 (goto-char (match-beginning 1))
21878 (insert (format org-agenda-todo-keyword-format s)))))
21879 (setq re (concat (get-text-property 0 'org-todo-regexp x))
21880 pl (get-text-property 0 'prefix-length x))
21881 ; (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
21882 ; (add-text-properties
21883 ; (or (match-end 1) (match-end 0)) (match-end 0)
21884 ; (list 'face (org-get-todo-face (match-string 2 x)))
21885 ; x))
21886 (when (and re
21887 (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)")
21888 x (or pl 0)) pl))
21889 (add-text-properties
21890 (or (match-end 1) (match-end 0)) (match-end 0)
21891 (list 'face (org-get-todo-face (match-string 2 x)))
21893 (setq x (concat (substring x 0 (match-end 1))
21894 (format org-agenda-todo-keyword-format
21895 (match-string 2 x))
21897 (substring x (match-end 3)))))
21898 x)))
21900 (defsubst org-cmp-priority (a b)
21901 "Compare the priorities of string A and B."
21902 (let ((pa (or (get-text-property 1 'priority a) 0))
21903 (pb (or (get-text-property 1 'priority b) 0)))
21904 (cond ((> pa pb) +1)
21905 ((< pa pb) -1)
21906 (t nil))))
21908 (defsubst org-cmp-category (a b)
21909 "Compare the string values of categories of strings A and B."
21910 (let ((ca (or (get-text-property 1 'org-category a) ""))
21911 (cb (or (get-text-property 1 'org-category b) "")))
21912 (cond ((string-lessp ca cb) -1)
21913 ((string-lessp cb ca) +1)
21914 (t nil))))
21916 (defsubst org-cmp-tag (a b)
21917 "Compare the string values of categories of strings A and B."
21918 (let ((ta (car (last (get-text-property 1 'tags a))))
21919 (tb (car (last (get-text-property 1 'tags b)))))
21920 (cond ((not ta) +1)
21921 ((not tb) -1)
21922 ((string-lessp ta tb) -1)
21923 ((string-lessp tb ta) +1)
21924 (t nil))))
21926 (defsubst org-cmp-time (a b)
21927 "Compare the time-of-day values of strings A and B."
21928 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
21929 (ta (or (get-text-property 1 'time-of-day a) def))
21930 (tb (or (get-text-property 1 'time-of-day b) def)))
21931 (cond ((< ta tb) -1)
21932 ((< tb ta) +1)
21933 (t nil))))
21935 (defun org-entries-lessp (a b)
21936 "Predicate for sorting agenda entries."
21937 ;; The following variables will be used when the form is evaluated.
21938 ;; So even though the compiler complains, keep them.
21939 (let* ((time-up (org-cmp-time a b))
21940 (time-down (if time-up (- time-up) nil))
21941 (priority-up (org-cmp-priority a b))
21942 (priority-down (if priority-up (- priority-up) nil))
21943 (category-up (org-cmp-category a b))
21944 (category-down (if category-up (- category-up) nil))
21945 (category-keep (if category-up +1 nil))
21946 (tag-up (org-cmp-tag a b))
21947 (tag-down (if tag-up (- tag-up) nil)))
21948 (cdr (assoc
21949 (eval (cons 'or org-agenda-sorting-strategy-selected))
21950 '((-1 . t) (1 . nil) (nil . nil))))))
21952 ;;; Agenda restriction lock
21954 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
21955 "Overlay to mark the headline to which arenda commands are restricted.")
21956 (org-overlay-put org-agenda-restriction-lock-overlay
21957 'face 'org-agenda-restriction-lock)
21958 (org-overlay-put org-agenda-restriction-lock-overlay
21959 'help-echo "Agendas are currently limited to this subtree.")
21960 (org-detach-overlay org-agenda-restriction-lock-overlay)
21961 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
21962 "Overlay marking the agenda restriction line in speedbar.")
21963 (org-overlay-put org-speedbar-restriction-lock-overlay
21964 'face 'org-agenda-restriction-lock)
21965 (org-overlay-put org-speedbar-restriction-lock-overlay
21966 'help-echo "Agendas are currently limited to this item.")
21967 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21969 (defun org-agenda-set-restriction-lock (&optional type)
21970 "Set restriction lock for agenda, to current subtree or file.
21971 Restriction will be the file if TYPE is `file', or if type is the
21972 universal prefix '(4), or if the cursor is before the first headline
21973 in the file. Otherwise, restriction will be to the current subtree."
21974 (interactive "P")
21975 (and (equal type '(4)) (setq type 'file))
21976 (setq type (cond
21977 (type type)
21978 ((org-at-heading-p) 'subtree)
21979 ((condition-case nil (org-back-to-heading t) (error nil))
21980 'subtree)
21981 (t 'file)))
21982 (if (eq type 'subtree)
21983 (progn
21984 (setq org-agenda-restrict t)
21985 (setq org-agenda-overriding-restriction 'subtree)
21986 (put 'org-agenda-files 'org-restrict
21987 (list (buffer-file-name (buffer-base-buffer))))
21988 (org-back-to-heading t)
21989 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
21990 (move-marker org-agenda-restrict-begin (point))
21991 (move-marker org-agenda-restrict-end
21992 (save-excursion (org-end-of-subtree t)))
21993 (message "Locking agenda restriction to subtree"))
21994 (put 'org-agenda-files 'org-restrict
21995 (list (buffer-file-name (buffer-base-buffer))))
21996 (setq org-agenda-restrict nil)
21997 (setq org-agenda-overriding-restriction 'file)
21998 (move-marker org-agenda-restrict-begin nil)
21999 (move-marker org-agenda-restrict-end nil)
22000 (message "Locking agenda restriction to file"))
22001 (setq current-prefix-arg nil)
22002 (org-agenda-maybe-redo))
22004 (defun org-agenda-remove-restriction-lock (&optional noupdate)
22005 "Remove the agenda restriction lock."
22006 (interactive "P")
22007 (org-detach-overlay org-agenda-restriction-lock-overlay)
22008 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22009 (setq org-agenda-overriding-restriction nil)
22010 (setq org-agenda-restrict nil)
22011 (put 'org-agenda-files 'org-restrict nil)
22012 (move-marker org-agenda-restrict-begin nil)
22013 (move-marker org-agenda-restrict-end nil)
22014 (setq current-prefix-arg nil)
22015 (message "Agenda restriction lock removed")
22016 (or noupdate (org-agenda-maybe-redo)))
22018 (defun org-agenda-maybe-redo ()
22019 "If there is any window showing the agenda view, update it."
22020 (let ((w (get-buffer-window org-agenda-buffer-name t))
22021 (w0 (selected-window)))
22022 (when w
22023 (select-window w)
22024 (org-agenda-redo)
22025 (select-window w0)
22026 (if org-agenda-overriding-restriction
22027 (message "Agenda view shifted to new %s restriction"
22028 org-agenda-overriding-restriction)
22029 (message "Agenda restriction lock removed")))))
22031 ;;; Agenda commands
22033 (defun org-agenda-check-type (error &rest types)
22034 "Check if agenda buffer is of allowed type.
22035 If ERROR is non-nil, throw an error, otherwise just return nil."
22036 (if (memq org-agenda-type types)
22038 (if error
22039 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
22040 nil)))
22042 (defun org-agenda-quit ()
22043 "Exit agenda by removing the window or the buffer."
22044 (interactive)
22045 (let ((buf (current-buffer)))
22046 (if (not (one-window-p)) (delete-window))
22047 (kill-buffer buf)
22048 (org-agenda-maybe-reset-markers 'force)
22049 (org-columns-remove-overlays))
22050 ;; Maybe restore the pre-agenda window configuration.
22051 (and org-agenda-restore-windows-after-quit
22052 (not (eq org-agenda-window-setup 'other-frame))
22053 org-pre-agenda-window-conf
22054 (set-window-configuration org-pre-agenda-window-conf)))
22056 (defun org-agenda-exit ()
22057 "Exit agenda by removing the window or the buffer.
22058 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
22059 Org-mode buffers visited directly by the user will not be touched."
22060 (interactive)
22061 (org-release-buffers org-agenda-new-buffers)
22062 (setq org-agenda-new-buffers nil)
22063 (org-agenda-quit))
22065 (defun org-agenda-execute (arg)
22066 "Execute another agenda command, keeping same window.\\<global-map>
22067 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
22068 (interactive "P")
22069 (let ((org-agenda-window-setup 'current-window))
22070 (org-agenda arg)))
22072 (defun org-save-all-org-buffers ()
22073 "Save all Org-mode buffers without user confirmation."
22074 (interactive)
22075 (message "Saving all Org-mode buffers...")
22076 (save-some-buffers t 'org-mode-p)
22077 (message "Saving all Org-mode buffers... done"))
22079 (defun org-agenda-redo ()
22080 "Rebuild Agenda.
22081 When this is the global TODO list, a prefix argument will be interpreted."
22082 (interactive)
22083 (let* ((org-agenda-keep-modes t)
22084 (line (org-current-line))
22085 (window-line (- line (org-current-line (window-start))))
22086 (lprops (get 'org-agenda-redo-command 'org-lprops)))
22087 (message "Rebuilding agenda buffer...")
22088 (org-let lprops '(eval org-agenda-redo-command))
22089 (setq org-agenda-undo-list nil
22090 org-agenda-pending-undo-list nil)
22091 (message "Rebuilding agenda buffer...done")
22092 (goto-line line)
22093 (recenter window-line)))
22095 (defun org-agenda-goto-date (date)
22096 "Jump to DATE in agenda."
22097 (interactive (list (org-read-date)))
22098 (org-agenda-list nil date))
22100 (defun org-agenda-goto-today ()
22101 "Go to today."
22102 (interactive)
22103 (org-agenda-check-type t 'timeline 'agenda)
22104 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
22105 (cond
22106 (tdpos (goto-char tdpos))
22107 ((eq org-agenda-type 'agenda)
22108 (let* ((sd (time-to-days
22109 (time-subtract (current-time)
22110 (list 0 (* 3600 org-extend-today-until) 0))))
22111 (comp (org-agenda-compute-time-span sd org-agenda-span))
22112 (org-agenda-overriding-arguments org-agenda-last-arguments))
22113 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
22114 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
22115 (org-agenda-redo)
22116 (org-agenda-find-same-or-today-or-agenda)))
22117 (t (error "Cannot find today")))))
22119 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
22120 (goto-char
22121 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
22122 (text-property-any (point-min) (point-max) 'org-today t)
22123 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
22124 (point-min))))
22126 (defun org-agenda-later (arg)
22127 "Go forward in time by thee current span.
22128 With prefix ARG, go forward that many times the current span."
22129 (interactive "p")
22130 (org-agenda-check-type t 'agenda)
22131 (let* ((span org-agenda-span)
22132 (sd org-starting-day)
22133 (greg (calendar-gregorian-from-absolute sd))
22134 (cnt (get-text-property (point) 'org-day-cnt))
22135 greg2 nd)
22136 (cond
22137 ((eq span 'day)
22138 (setq sd (+ arg sd) nd 1))
22139 ((eq span 'week)
22140 (setq sd (+ (* 7 arg) sd) nd 7))
22141 ((eq span 'month)
22142 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
22143 sd (calendar-absolute-from-gregorian greg2))
22144 (setcar greg2 (1+ (car greg2)))
22145 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
22146 ((eq span 'year)
22147 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
22148 sd (calendar-absolute-from-gregorian greg2))
22149 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
22150 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
22151 (let ((org-agenda-overriding-arguments
22152 (list (car org-agenda-last-arguments) sd nd t)))
22153 (org-agenda-redo)
22154 (org-agenda-find-same-or-today-or-agenda cnt))))
22156 (defun org-agenda-earlier (arg)
22157 "Go backward in time by the current span.
22158 With prefix ARG, go backward that many times the current span."
22159 (interactive "p")
22160 (org-agenda-later (- arg)))
22162 (defun org-agenda-day-view ()
22163 "Switch to daily view for agenda."
22164 (interactive)
22165 (setq org-agenda-ndays 1)
22166 (org-agenda-change-time-span 'day))
22167 (defun org-agenda-week-view ()
22168 "Switch to daily view for agenda."
22169 (interactive)
22170 (setq org-agenda-ndays 7)
22171 (org-agenda-change-time-span 'week))
22172 (defun org-agenda-month-view ()
22173 "Switch to daily view for agenda."
22174 (interactive)
22175 (org-agenda-change-time-span 'month))
22176 (defun org-agenda-year-view ()
22177 "Switch to daily view for agenda."
22178 (interactive)
22179 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
22180 (org-agenda-change-time-span 'year)
22181 (error "Abort")))
22183 (defun org-agenda-change-time-span (span)
22184 "Change the agenda view to SPAN.
22185 SPAN may be `day', `week', `month', `year'."
22186 (org-agenda-check-type t 'agenda)
22187 (if (equal org-agenda-span span)
22188 (error "Viewing span is already \"%s\"" span))
22189 (let* ((sd (or (get-text-property (point) 'day)
22190 org-starting-day))
22191 (computed (org-agenda-compute-time-span sd span))
22192 (org-agenda-overriding-arguments
22193 (list (car org-agenda-last-arguments)
22194 (car computed) (cdr computed) t)))
22195 (org-agenda-redo)
22196 (org-agenda-find-same-or-today-or-agenda))
22197 (org-agenda-set-mode-name)
22198 (message "Switched to %s view" span))
22200 (defun org-agenda-compute-time-span (sd span)
22201 "Compute starting date and number of days for agenda.
22202 SPAN may be `day', `week', `month', `year'. The return value
22203 is a cons cell with the starting date and the number of days,
22204 so that the date SD will be in that range."
22205 (let* ((greg (calendar-gregorian-from-absolute sd))
22207 (cond
22208 ((eq span 'day)
22209 (setq nd 1))
22210 ((eq span 'week)
22211 (let* ((nt (calendar-day-of-week
22212 (calendar-gregorian-from-absolute sd)))
22213 (d (if org-agenda-start-on-weekday
22214 (- nt org-agenda-start-on-weekday)
22215 0)))
22216 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
22217 (setq nd 7)))
22218 ((eq span 'month)
22219 (setq sd (calendar-absolute-from-gregorian
22220 (list (car greg) 1 (nth 2 greg)))
22221 nd (- (calendar-absolute-from-gregorian
22222 (list (1+ (car greg)) 1 (nth 2 greg)))
22223 sd)))
22224 ((eq span 'year)
22225 (setq sd (calendar-absolute-from-gregorian
22226 (list 1 1 (nth 2 greg)))
22227 nd (- (calendar-absolute-from-gregorian
22228 (list 1 1 (1+ (nth 2 greg))))
22229 sd))))
22230 (cons sd nd)))
22232 ;; FIXME: does not work if user makes date format that starts with a blank
22233 (defun org-agenda-next-date-line (&optional arg)
22234 "Jump to the next line indicating a date in agenda buffer."
22235 (interactive "p")
22236 (org-agenda-check-type t 'agenda 'timeline)
22237 (beginning-of-line 1)
22238 (if (looking-at "^\\S-") (forward-char 1))
22239 (if (not (re-search-forward "^\\S-" nil t arg))
22240 (progn
22241 (backward-char 1)
22242 (error "No next date after this line in this buffer")))
22243 (goto-char (match-beginning 0)))
22245 (defun org-agenda-previous-date-line (&optional arg)
22246 "Jump to the previous line indicating a date in agenda buffer."
22247 (interactive "p")
22248 (org-agenda-check-type t 'agenda 'timeline)
22249 (beginning-of-line 1)
22250 (if (not (re-search-backward "^\\S-" nil t arg))
22251 (error "No previous date before this line in this buffer")))
22253 ;; Initialize the highlight
22254 (defvar org-hl (org-make-overlay 1 1))
22255 (org-overlay-put org-hl 'face 'highlight)
22257 (defun org-highlight (begin end &optional buffer)
22258 "Highlight a region with overlay."
22259 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
22260 org-hl begin end (or buffer (current-buffer))))
22262 (defun org-unhighlight ()
22263 "Detach overlay INDEX."
22264 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
22266 ;; FIXME this is currently not used.
22267 (defun org-highlight-until-next-command (beg end &optional buffer)
22268 (org-highlight beg end buffer)
22269 (add-hook 'pre-command-hook 'org-unhighlight-once))
22270 (defun org-unhighlight-once ()
22271 (remove-hook 'pre-command-hook 'org-unhighlight-once)
22272 (org-unhighlight))
22274 (defun org-agenda-follow-mode ()
22275 "Toggle follow mode in an agenda buffer."
22276 (interactive)
22277 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
22278 (org-agenda-set-mode-name)
22279 (message "Follow mode is %s"
22280 (if org-agenda-follow-mode "on" "off")))
22282 (defun org-agenda-log-mode ()
22283 "Toggle log mode in an agenda buffer."
22284 (interactive)
22285 (org-agenda-check-type t 'agenda 'timeline)
22286 (setq org-agenda-show-log (not org-agenda-show-log))
22287 (org-agenda-set-mode-name)
22288 (org-agenda-redo)
22289 (message "Log mode is %s"
22290 (if org-agenda-show-log "on" "off")))
22292 (defun org-agenda-toggle-diary ()
22293 "Toggle diary inclusion in an agenda buffer."
22294 (interactive)
22295 (org-agenda-check-type t 'agenda)
22296 (setq org-agenda-include-diary (not org-agenda-include-diary))
22297 (org-agenda-redo)
22298 (org-agenda-set-mode-name)
22299 (message "Diary inclusion turned %s"
22300 (if org-agenda-include-diary "on" "off")))
22302 (defun org-agenda-toggle-time-grid ()
22303 "Toggle time grid in an agenda buffer."
22304 (interactive)
22305 (org-agenda-check-type t 'agenda)
22306 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
22307 (org-agenda-redo)
22308 (org-agenda-set-mode-name)
22309 (message "Time-grid turned %s"
22310 (if org-agenda-use-time-grid "on" "off")))
22312 (defun org-agenda-set-mode-name ()
22313 "Set the mode name to indicate all the small mode settings."
22314 (setq mode-name
22315 (concat "Org-Agenda"
22316 (if (equal org-agenda-ndays 1) " Day" "")
22317 (if (equal org-agenda-ndays 7) " Week" "")
22318 (if org-agenda-follow-mode " Follow" "")
22319 (if org-agenda-include-diary " Diary" "")
22320 (if org-agenda-use-time-grid " Grid" "")
22321 (if org-agenda-show-log " Log" "")))
22322 (force-mode-line-update))
22324 (defun org-agenda-post-command-hook ()
22325 (and (eolp) (not (bolp)) (backward-char 1))
22326 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
22327 (if (and org-agenda-follow-mode
22328 (get-text-property (point) 'org-marker))
22329 (org-agenda-show)))
22331 (defun org-agenda-show-priority ()
22332 "Show the priority of the current item.
22333 This priority is composed of the main priority given with the [#A] cookies,
22334 and by additional input from the age of a schedules or deadline entry."
22335 (interactive)
22336 (let* ((pri (get-text-property (point-at-bol) 'priority)))
22337 (message "Priority is %d" (if pri pri -1000))))
22339 (defun org-agenda-show-tags ()
22340 "Show the tags applicable to the current item."
22341 (interactive)
22342 (let* ((tags (get-text-property (point-at-bol) 'tags)))
22343 (if tags
22344 (message "Tags are :%s:"
22345 (org-no-properties (mapconcat 'identity tags ":")))
22346 (message "No tags associated with this line"))))
22348 (defun org-agenda-goto (&optional highlight)
22349 "Go to the Org-mode file which contains the item at point."
22350 (interactive)
22351 (let* ((marker (or (get-text-property (point) 'org-marker)
22352 (org-agenda-error)))
22353 (buffer (marker-buffer marker))
22354 (pos (marker-position marker)))
22355 (switch-to-buffer-other-window buffer)
22356 (widen)
22357 (goto-char pos)
22358 (when (org-mode-p)
22359 (org-show-context 'agenda)
22360 (save-excursion
22361 (and (outline-next-heading)
22362 (org-flag-heading nil)))) ; show the next heading
22363 (recenter (/ (window-height) 2))
22364 (run-hooks 'org-agenda-after-show-hook)
22365 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
22367 (defvar org-agenda-after-show-hook nil
22368 "Normal hook run after an item has been shown from the agenda.
22369 Point is in the buffer where the item originated.")
22371 (defun org-agenda-kill ()
22372 "Kill the entry or subtree belonging to the current agenda entry."
22373 (interactive)
22374 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22375 (let* ((marker (or (get-text-property (point) 'org-marker)
22376 (org-agenda-error)))
22377 (buffer (marker-buffer marker))
22378 (pos (marker-position marker))
22379 (type (get-text-property (point) 'type))
22380 dbeg dend (n 0) conf)
22381 (org-with-remote-undo buffer
22382 (with-current-buffer buffer
22383 (save-excursion
22384 (goto-char pos)
22385 (if (and (org-mode-p) (not (member type '("sexp"))))
22386 (setq dbeg (progn (org-back-to-heading t) (point))
22387 dend (org-end-of-subtree t t))
22388 (setq dbeg (point-at-bol)
22389 dend (min (point-max) (1+ (point-at-eol)))))
22390 (goto-char dbeg)
22391 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
22392 (setq conf (or (eq t org-agenda-confirm-kill)
22393 (and (numberp org-agenda-confirm-kill)
22394 (> n org-agenda-confirm-kill))))
22395 (and conf
22396 (not (y-or-n-p
22397 (format "Delete entry with %d lines in buffer \"%s\"? "
22398 n (buffer-name buffer))))
22399 (error "Abort"))
22400 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
22401 (with-current-buffer buffer (delete-region dbeg dend))
22402 (message "Agenda item and source killed"))))
22404 (defun org-agenda-archive ()
22405 "Kill the entry or subtree belonging to the current agenda entry."
22406 (interactive)
22407 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22408 (let* ((marker (or (get-text-property (point) 'org-marker)
22409 (org-agenda-error)))
22410 (buffer (marker-buffer marker))
22411 (pos (marker-position marker)))
22412 (org-with-remote-undo buffer
22413 (with-current-buffer buffer
22414 (if (org-mode-p)
22415 (save-excursion
22416 (goto-char pos)
22417 (org-remove-subtree-entries-from-agenda)
22418 (org-back-to-heading t)
22419 (org-archive-subtree))
22420 (error "Archiving works only in Org-mode files"))))))
22422 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
22423 "Remove all lines in the agenda that correspond to a given subtree.
22424 The subtree is the one in buffer BUF, starting at BEG and ending at END.
22425 If this information is not given, the function uses the tree at point."
22426 (let ((buf (or buf (current-buffer))) m p)
22427 (save-excursion
22428 (unless (and beg end)
22429 (org-back-to-heading t)
22430 (setq beg (point))
22431 (org-end-of-subtree t)
22432 (setq end (point)))
22433 (set-buffer (get-buffer org-agenda-buffer-name))
22434 (save-excursion
22435 (goto-char (point-max))
22436 (beginning-of-line 1)
22437 (while (not (bobp))
22438 (when (and (setq m (get-text-property (point) 'org-marker))
22439 (equal buf (marker-buffer m))
22440 (setq p (marker-position m))
22441 (>= p beg)
22442 (<= p end))
22443 (let ((inhibit-read-only t))
22444 (delete-region (point-at-bol) (1+ (point-at-eol)))))
22445 (beginning-of-line 0))))))
22447 (defun org-agenda-open-link ()
22448 "Follow the link in the current line, if any."
22449 (interactive)
22450 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
22451 (save-excursion
22452 (save-restriction
22453 (narrow-to-region (point-at-bol) (point-at-eol))
22454 (org-open-at-point))))
22456 (defun org-agenda-copy-local-variable (var)
22457 "Get a variable from a referenced buffer and install it here."
22458 (let ((m (get-text-property (point) 'org-marker)))
22459 (when (and m (buffer-live-p (marker-buffer m)))
22460 (org-set-local var (with-current-buffer (marker-buffer m)
22461 (symbol-value var))))))
22463 (defun org-agenda-switch-to (&optional delete-other-windows)
22464 "Go to the Org-mode file which contains the item at point."
22465 (interactive)
22466 (let* ((marker (or (get-text-property (point) 'org-marker)
22467 (org-agenda-error)))
22468 (buffer (marker-buffer marker))
22469 (pos (marker-position marker)))
22470 (switch-to-buffer buffer)
22471 (and delete-other-windows (delete-other-windows))
22472 (widen)
22473 (goto-char pos)
22474 (when (org-mode-p)
22475 (org-show-context 'agenda)
22476 (save-excursion
22477 (and (outline-next-heading)
22478 (org-flag-heading nil)))))) ; show the next heading
22480 (defun org-agenda-goto-mouse (ev)
22481 "Go to the Org-mode file which contains the item at the mouse click."
22482 (interactive "e")
22483 (mouse-set-point ev)
22484 (org-agenda-goto))
22486 (defun org-agenda-show ()
22487 "Display the Org-mode file which contains the item at point."
22488 (interactive)
22489 (let ((win (selected-window)))
22490 (org-agenda-goto t)
22491 (select-window win)))
22493 (defun org-agenda-recenter (arg)
22494 "Display the Org-mode file which contains the item at point and recenter."
22495 (interactive "P")
22496 (let ((win (selected-window)))
22497 (org-agenda-goto t)
22498 (recenter arg)
22499 (select-window win)))
22501 (defun org-agenda-show-mouse (ev)
22502 "Display the Org-mode file which contains the item at the mouse click."
22503 (interactive "e")
22504 (mouse-set-point ev)
22505 (org-agenda-show))
22507 (defun org-agenda-check-no-diary ()
22508 "Check if the entry is a diary link and abort if yes."
22509 (if (get-text-property (point) 'org-agenda-diary-link)
22510 (org-agenda-error)))
22512 (defun org-agenda-error ()
22513 (error "Command not allowed in this line"))
22515 (defun org-agenda-tree-to-indirect-buffer ()
22516 "Show the subtree corresponding to the current entry in an indirect buffer.
22517 This calls the command `org-tree-to-indirect-buffer' from the original
22518 Org-mode buffer.
22519 With numerical prefix arg ARG, go up to this level and then take that tree.
22520 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
22521 dedicated frame)."
22522 (interactive)
22523 (org-agenda-check-no-diary)
22524 (let* ((marker (or (get-text-property (point) 'org-marker)
22525 (org-agenda-error)))
22526 (buffer (marker-buffer marker))
22527 (pos (marker-position marker)))
22528 (with-current-buffer buffer
22529 (save-excursion
22530 (goto-char pos)
22531 (call-interactively 'org-tree-to-indirect-buffer)))))
22533 (defvar org-last-heading-marker (make-marker)
22534 "Marker pointing to the headline that last changed its TODO state
22535 by a remote command from the agenda.")
22537 (defun org-agenda-todo-nextset ()
22538 "Switch TODO entry to next sequence."
22539 (interactive)
22540 (org-agenda-todo 'nextset))
22542 (defun org-agenda-todo-previousset ()
22543 "Switch TODO entry to previous sequence."
22544 (interactive)
22545 (org-agenda-todo 'previousset))
22547 (defun org-agenda-todo (&optional arg)
22548 "Cycle TODO state of line at point, also in Org-mode file.
22549 This changes the line at point, all other lines in the agenda referring to
22550 the same tree node, and the headline of the tree node in the Org-mode file."
22551 (interactive "P")
22552 (org-agenda-check-no-diary)
22553 (let* ((col (current-column))
22554 (marker (or (get-text-property (point) 'org-marker)
22555 (org-agenda-error)))
22556 (buffer (marker-buffer marker))
22557 (pos (marker-position marker))
22558 (hdmarker (get-text-property (point) 'org-hd-marker))
22559 (inhibit-read-only t)
22560 newhead)
22561 (org-with-remote-undo buffer
22562 (with-current-buffer buffer
22563 (widen)
22564 (goto-char pos)
22565 (org-show-context 'agenda)
22566 (save-excursion
22567 (and (outline-next-heading)
22568 (org-flag-heading nil))) ; show the next heading
22569 (org-todo arg)
22570 (and (bolp) (forward-char 1))
22571 (setq newhead (org-get-heading))
22572 (save-excursion
22573 (org-back-to-heading)
22574 (move-marker org-last-heading-marker (point))))
22575 (beginning-of-line 1)
22576 (save-excursion
22577 (org-agenda-change-all-lines newhead hdmarker 'fixface))
22578 (move-to-column col))))
22580 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
22581 "Change all lines in the agenda buffer which match HDMARKER.
22582 The new content of the line will be NEWHEAD (as modified by
22583 `org-format-agenda-item'). HDMARKER is checked with
22584 `equal' against all `org-hd-marker' text properties in the file.
22585 If FIXFACE is non-nil, the face of each item is modified acording to
22586 the new TODO state."
22587 (let* ((inhibit-read-only t)
22588 props m pl undone-face done-face finish new dotime cat tags)
22589 (save-excursion
22590 (goto-char (point-max))
22591 (beginning-of-line 1)
22592 (while (not finish)
22593 (setq finish (bobp))
22594 (when (and (setq m (get-text-property (point) 'org-hd-marker))
22595 (equal m hdmarker))
22596 (setq props (text-properties-at (point))
22597 dotime (get-text-property (point) 'dotime)
22598 cat (get-text-property (point) 'org-category)
22599 tags (get-text-property (point) 'tags)
22600 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
22601 pl (get-text-property (point) 'prefix-length)
22602 undone-face (get-text-property (point) 'undone-face)
22603 done-face (get-text-property (point) 'done-face))
22604 (move-to-column pl)
22605 (cond
22606 ((equal new "")
22607 (beginning-of-line 1)
22608 (and (looking-at ".*\n?") (replace-match "")))
22609 ((looking-at ".*")
22610 (replace-match new t t)
22611 (beginning-of-line 1)
22612 (add-text-properties (point-at-bol) (point-at-eol) props)
22613 (when fixface
22614 (add-text-properties
22615 (point-at-bol) (point-at-eol)
22616 (list 'face
22617 (if org-last-todo-state-is-todo
22618 undone-face done-face))))
22619 (org-agenda-highlight-todo 'line)
22620 (beginning-of-line 1))
22621 (t (error "Line update did not work"))))
22622 (beginning-of-line 0)))
22623 (org-finalize-agenda)))
22625 (defun org-agenda-align-tags (&optional line)
22626 "Align all tags in agenda items to `org-agenda-tags-column'."
22627 (let ((inhibit-read-only t) l c)
22628 (save-excursion
22629 (goto-char (if line (point-at-bol) (point-min)))
22630 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22631 (if line (point-at-eol) nil) t)
22632 (add-text-properties
22633 (match-beginning 2) (match-end 2)
22634 (list 'face (list 'org-tag (get-text-property
22635 (match-beginning 2) 'face))))
22636 (setq l (- (match-end 2) (match-beginning 2))
22637 c (if (< org-agenda-tags-column 0)
22638 (- (abs org-agenda-tags-column) l)
22639 org-agenda-tags-column))
22640 (delete-region (match-beginning 1) (match-end 1))
22641 (goto-char (match-beginning 1))
22642 (insert (org-add-props
22643 (make-string (max 1 (- c (current-column))) ?\ )
22644 (text-properties-at (point))))))))
22646 (defun org-agenda-priority-up ()
22647 "Increase the priority of line at point, also in Org-mode file."
22648 (interactive)
22649 (org-agenda-priority 'up))
22651 (defun org-agenda-priority-down ()
22652 "Decrease the priority of line at point, also in Org-mode file."
22653 (interactive)
22654 (org-agenda-priority 'down))
22656 (defun org-agenda-priority (&optional force-direction)
22657 "Set the priority of line at point, also in Org-mode file.
22658 This changes the line at point, all other lines in the agenda referring to
22659 the same tree node, and the headline of the tree node in the Org-mode file."
22660 (interactive)
22661 (org-agenda-check-no-diary)
22662 (let* ((marker (or (get-text-property (point) 'org-marker)
22663 (org-agenda-error)))
22664 (hdmarker (get-text-property (point) 'org-hd-marker))
22665 (buffer (marker-buffer hdmarker))
22666 (pos (marker-position hdmarker))
22667 (inhibit-read-only t)
22668 newhead)
22669 (org-with-remote-undo buffer
22670 (with-current-buffer buffer
22671 (widen)
22672 (goto-char pos)
22673 (org-show-context 'agenda)
22674 (save-excursion
22675 (and (outline-next-heading)
22676 (org-flag-heading nil))) ; show the next heading
22677 (funcall 'org-priority force-direction)
22678 (end-of-line 1)
22679 (setq newhead (org-get-heading)))
22680 (org-agenda-change-all-lines newhead hdmarker)
22681 (beginning-of-line 1))))
22683 (defun org-get-tags-at (&optional pos)
22684 "Get a list of all headline tags applicable at POS.
22685 POS defaults to point. If tags are inherited, the list contains
22686 the targets in the same sequence as the headlines appear, i.e.
22687 the tags of the current headline come last."
22688 (interactive)
22689 (let (tags lastpos)
22690 (save-excursion
22691 (save-restriction
22692 (widen)
22693 (goto-char (or pos (point)))
22694 (save-match-data
22695 (org-back-to-heading t)
22696 (condition-case nil
22697 (while (not (equal lastpos (point)))
22698 (setq lastpos (point))
22699 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
22700 (setq tags (append (org-split-string
22701 (org-match-string-no-properties 1) ":")
22702 tags)))
22703 (or org-use-tag-inheritance (error ""))
22704 (org-up-heading-all 1))
22705 (error nil))))
22706 tags)))
22708 ;; FIXME: should fix the tags property of the agenda line.
22709 (defun org-agenda-set-tags ()
22710 "Set tags for the current headline."
22711 (interactive)
22712 (org-agenda-check-no-diary)
22713 (if (and (org-region-active-p) (interactive-p))
22714 (call-interactively 'org-change-tag-in-region)
22715 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22716 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22717 (org-agenda-error)))
22718 (buffer (marker-buffer hdmarker))
22719 (pos (marker-position hdmarker))
22720 (inhibit-read-only t)
22721 newhead)
22722 (org-with-remote-undo buffer
22723 (with-current-buffer buffer
22724 (widen)
22725 (goto-char pos)
22726 (save-excursion
22727 (org-show-context 'agenda))
22728 (save-excursion
22729 (and (outline-next-heading)
22730 (org-flag-heading nil))) ; show the next heading
22731 (goto-char pos)
22732 (call-interactively 'org-set-tags)
22733 (end-of-line 1)
22734 (setq newhead (org-get-heading)))
22735 (org-agenda-change-all-lines newhead hdmarker)
22736 (beginning-of-line 1)))))
22738 (defun org-agenda-toggle-archive-tag ()
22739 "Toggle the archive tag for the current entry."
22740 (interactive)
22741 (org-agenda-check-no-diary)
22742 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22743 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22744 (org-agenda-error)))
22745 (buffer (marker-buffer hdmarker))
22746 (pos (marker-position hdmarker))
22747 (inhibit-read-only t)
22748 newhead)
22749 (org-with-remote-undo buffer
22750 (with-current-buffer buffer
22751 (widen)
22752 (goto-char pos)
22753 (org-show-context 'agenda)
22754 (save-excursion
22755 (and (outline-next-heading)
22756 (org-flag-heading nil))) ; show the next heading
22757 (call-interactively 'org-toggle-archive-tag)
22758 (end-of-line 1)
22759 (setq newhead (org-get-heading)))
22760 (org-agenda-change-all-lines newhead hdmarker)
22761 (beginning-of-line 1))))
22763 (defun org-agenda-date-later (arg &optional what)
22764 "Change the date of this item to one day later."
22765 (interactive "p")
22766 (org-agenda-check-type t 'agenda 'timeline)
22767 (org-agenda-check-no-diary)
22768 (let* ((marker (or (get-text-property (point) 'org-marker)
22769 (org-agenda-error)))
22770 (buffer (marker-buffer marker))
22771 (pos (marker-position marker)))
22772 (org-with-remote-undo buffer
22773 (with-current-buffer buffer
22774 (widen)
22775 (goto-char pos)
22776 (if (not (org-at-timestamp-p))
22777 (error "Cannot find time stamp"))
22778 (org-timestamp-change arg (or what 'day)))
22779 (org-agenda-show-new-time marker org-last-changed-timestamp))
22780 (message "Time stamp changed to %s" org-last-changed-timestamp)))
22782 (defun org-agenda-date-earlier (arg &optional what)
22783 "Change the date of this item to one day earlier."
22784 (interactive "p")
22785 (org-agenda-date-later (- arg) what))
22787 (defun org-agenda-show-new-time (marker stamp &optional prefix)
22788 "Show new date stamp via text properties."
22789 ;; We use text properties to make this undoable
22790 (let ((inhibit-read-only t))
22791 (setq stamp (concat " " prefix " => " stamp))
22792 (save-excursion
22793 (goto-char (point-max))
22794 (while (not (bobp))
22795 (when (equal marker (get-text-property (point) 'org-marker))
22796 (move-to-column (- (window-width) (length stamp)) t)
22797 (if (featurep 'xemacs)
22798 ;; Use `duplicable' property to trigger undo recording
22799 (let ((ex (make-extent nil nil))
22800 (gl (make-glyph stamp)))
22801 (set-glyph-face gl 'secondary-selection)
22802 (set-extent-properties
22803 ex (list 'invisible t 'end-glyph gl 'duplicable t))
22804 (insert-extent ex (1- (point)) (point-at-eol)))
22805 (add-text-properties
22806 (1- (point)) (point-at-eol)
22807 (list 'display (org-add-props stamp nil
22808 'face 'secondary-selection))))
22809 (beginning-of-line 1))
22810 (beginning-of-line 0)))))
22812 (defun org-agenda-date-prompt (arg)
22813 "Change the date of this item. Date is prompted for, with default today.
22814 The prefix ARG is passed to the `org-time-stamp' command and can therefore
22815 be used to request time specification in the time stamp."
22816 (interactive "P")
22817 (org-agenda-check-type t 'agenda 'timeline)
22818 (org-agenda-check-no-diary)
22819 (let* ((marker (or (get-text-property (point) 'org-marker)
22820 (org-agenda-error)))
22821 (buffer (marker-buffer marker))
22822 (pos (marker-position marker)))
22823 (org-with-remote-undo buffer
22824 (with-current-buffer buffer
22825 (widen)
22826 (goto-char pos)
22827 (if (not (org-at-timestamp-p))
22828 (error "Cannot find time stamp"))
22829 (org-time-stamp arg)
22830 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
22832 (defun org-agenda-schedule (arg)
22833 "Schedule the item at point."
22834 (interactive "P")
22835 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22836 (org-agenda-check-no-diary)
22837 (let* ((marker (or (get-text-property (point) 'org-marker)
22838 (org-agenda-error)))
22839 (buffer (marker-buffer marker))
22840 (pos (marker-position marker))
22841 (org-insert-labeled-timestamps-at-point nil)
22843 (org-with-remote-undo buffer
22844 (with-current-buffer buffer
22845 (widen)
22846 (goto-char pos)
22847 (setq ts (org-schedule arg)))
22848 (org-agenda-show-new-time marker ts "S"))
22849 (message "Item scheduled for %s" ts)))
22851 (defun org-agenda-deadline (arg)
22852 "Schedule the item at point."
22853 (interactive "P")
22854 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22855 (org-agenda-check-no-diary)
22856 (let* ((marker (or (get-text-property (point) 'org-marker)
22857 (org-agenda-error)))
22858 (buffer (marker-buffer marker))
22859 (pos (marker-position marker))
22860 (org-insert-labeled-timestamps-at-point nil)
22862 (org-with-remote-undo buffer
22863 (with-current-buffer buffer
22864 (widen)
22865 (goto-char pos)
22866 (setq ts (org-deadline arg)))
22867 (org-agenda-show-new-time marker ts "S"))
22868 (message "Deadline for this item set to %s" ts)))
22870 (defun org-get-heading (&optional no-tags)
22871 "Return the heading of the current entry, without the stars."
22872 (save-excursion
22873 (org-back-to-heading t)
22874 (if (looking-at
22875 (if no-tags
22876 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
22877 "\\*+[ \t]+\\([^\r\n]*\\)"))
22878 (match-string 1) "")))
22880 (defun org-agenda-clock-in (&optional arg)
22881 "Start the clock on the currently selected item."
22882 (interactive "P")
22883 (org-agenda-check-no-diary)
22884 (let* ((marker (or (get-text-property (point) 'org-marker)
22885 (org-agenda-error)))
22886 (pos (marker-position marker)))
22887 (org-with-remote-undo (marker-buffer marker)
22888 (with-current-buffer (marker-buffer marker)
22889 (widen)
22890 (goto-char pos)
22891 (org-clock-in)))))
22893 (defun org-agenda-clock-out (&optional arg)
22894 "Stop the currently running clock."
22895 (interactive "P")
22896 (unless (marker-buffer org-clock-marker)
22897 (error "No running clock"))
22898 (org-with-remote-undo (marker-buffer org-clock-marker)
22899 (org-clock-out)))
22901 (defun org-agenda-clock-cancel (&optional arg)
22902 "Cancel the currently running clock."
22903 (interactive "P")
22904 (unless (marker-buffer org-clock-marker)
22905 (error "No running clock"))
22906 (org-with-remote-undo (marker-buffer org-clock-marker)
22907 (org-clock-cancel)))
22909 (defun org-agenda-diary-entry ()
22910 "Make a diary entry, like the `i' command from the calendar.
22911 All the standard commands work: block, weekly etc."
22912 (interactive)
22913 (org-agenda-check-type t 'agenda 'timeline)
22914 (require 'diary-lib)
22915 (let* ((char (progn
22916 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
22917 (read-char-exclusive)))
22918 (cmd (cdr (assoc char
22919 '((?d . insert-diary-entry)
22920 (?w . insert-weekly-diary-entry)
22921 (?m . insert-monthly-diary-entry)
22922 (?y . insert-yearly-diary-entry)
22923 (?a . insert-anniversary-diary-entry)
22924 (?b . insert-block-diary-entry)
22925 (?c . insert-cyclic-diary-entry)))))
22926 (oldf (symbol-function 'calendar-cursor-to-date))
22927 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
22928 (point (point))
22929 (mark (or (mark t) (point))))
22930 (unless cmd
22931 (error "No command associated with <%c>" char))
22932 (unless (and (get-text-property point 'day)
22933 (or (not (equal ?b char))
22934 (get-text-property mark 'day)))
22935 (error "Don't know which date to use for diary entry"))
22936 ;; We implement this by hacking the `calendar-cursor-to-date' function
22937 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
22938 (let ((calendar-mark-ring
22939 (list (calendar-gregorian-from-absolute
22940 (or (get-text-property mark 'day)
22941 (get-text-property point 'day))))))
22942 (unwind-protect
22943 (progn
22944 (fset 'calendar-cursor-to-date
22945 (lambda (&optional error)
22946 (calendar-gregorian-from-absolute
22947 (get-text-property point 'day))))
22948 (call-interactively cmd))
22949 (fset 'calendar-cursor-to-date oldf)))))
22952 (defun org-agenda-execute-calendar-command (cmd)
22953 "Execute a calendar command from the agenda, with the date associated to
22954 the cursor position."
22955 (org-agenda-check-type t 'agenda 'timeline)
22956 (require 'diary-lib)
22957 (unless (get-text-property (point) 'day)
22958 (error "Don't know which date to use for calendar command"))
22959 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
22960 (point (point))
22961 (date (calendar-gregorian-from-absolute
22962 (get-text-property point 'day)))
22963 ;; the following 3 vars are needed in the calendar
22964 (displayed-day (extract-calendar-day date))
22965 (displayed-month (extract-calendar-month date))
22966 (displayed-year (extract-calendar-year date)))
22967 (unwind-protect
22968 (progn
22969 (fset 'calendar-cursor-to-date
22970 (lambda (&optional error)
22971 (calendar-gregorian-from-absolute
22972 (get-text-property point 'day))))
22973 (call-interactively cmd))
22974 (fset 'calendar-cursor-to-date oldf))))
22976 (defun org-agenda-phases-of-moon ()
22977 "Display the phases of the moon for the 3 months around the cursor date."
22978 (interactive)
22979 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
22981 (defun org-agenda-holidays ()
22982 "Display the holidays for the 3 months around the cursor date."
22983 (interactive)
22984 (org-agenda-execute-calendar-command 'list-calendar-holidays))
22986 (defun org-agenda-sunrise-sunset (arg)
22987 "Display sunrise and sunset for the cursor date.
22988 Latitude and longitude can be specified with the variables
22989 `calendar-latitude' and `calendar-longitude'. When called with prefix
22990 argument, latitude and longitude will be prompted for."
22991 (interactive "P")
22992 (let ((calendar-longitude (if arg nil calendar-longitude))
22993 (calendar-latitude (if arg nil calendar-latitude))
22994 (calendar-location-name
22995 (if arg "the given coordinates" calendar-location-name)))
22996 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
22998 (defun org-agenda-goto-calendar ()
22999 "Open the Emacs calendar with the date at the cursor."
23000 (interactive)
23001 (org-agenda-check-type t 'agenda 'timeline)
23002 (let* ((day (or (get-text-property (point) 'day)
23003 (error "Don't know which date to open in calendar")))
23004 (date (calendar-gregorian-from-absolute day))
23005 (calendar-move-hook nil)
23006 (view-calendar-holidays-initially nil)
23007 (view-diary-entries-initially nil))
23008 (calendar)
23009 (calendar-goto-date date)))
23011 (defun org-calendar-goto-agenda ()
23012 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
23013 This is a command that has to be installed in `calendar-mode-map'."
23014 (interactive)
23015 (org-agenda-list nil (calendar-absolute-from-gregorian
23016 (calendar-cursor-to-date))
23017 nil))
23019 (defun org-agenda-convert-date ()
23020 (interactive)
23021 (org-agenda-check-type t 'agenda 'timeline)
23022 (let ((day (get-text-property (point) 'day))
23023 date s)
23024 (unless day
23025 (error "Don't know which date to convert"))
23026 (setq date (calendar-gregorian-from-absolute day))
23027 (setq s (concat
23028 "Gregorian: " (calendar-date-string date) "\n"
23029 "ISO: " (calendar-iso-date-string date) "\n"
23030 "Day of Yr: " (calendar-day-of-year-string date) "\n"
23031 "Julian: " (calendar-julian-date-string date) "\n"
23032 "Astron. JD: " (calendar-astro-date-string date)
23033 " (Julian date number at noon UTC)\n"
23034 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
23035 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
23036 "French: " (calendar-french-date-string date) "\n"
23037 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
23038 "Mayan: " (calendar-mayan-date-string date) "\n"
23039 "Coptic: " (calendar-coptic-date-string date) "\n"
23040 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
23041 "Persian: " (calendar-persian-date-string date) "\n"
23042 "Chinese: " (calendar-chinese-date-string date) "\n"))
23043 (with-output-to-temp-buffer "*Dates*"
23044 (princ s))
23045 (if (fboundp 'fit-window-to-buffer)
23046 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
23049 ;;;; Embedded LaTeX
23051 (defvar org-cdlatex-mode-map (make-sparse-keymap)
23052 "Keymap for the minor `org-cdlatex-mode'.")
23054 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
23055 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
23056 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
23057 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
23058 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
23060 (defvar org-cdlatex-texmathp-advice-is-done nil
23061 "Flag remembering if we have applied the advice to texmathp already.")
23063 (define-minor-mode org-cdlatex-mode
23064 "Toggle the minor `org-cdlatex-mode'.
23065 This mode supports entering LaTeX environment and math in LaTeX fragments
23066 in Org-mode.
23067 \\{org-cdlatex-mode-map}"
23068 nil " OCDL" nil
23069 (when org-cdlatex-mode (require 'cdlatex))
23070 (unless org-cdlatex-texmathp-advice-is-done
23071 (setq org-cdlatex-texmathp-advice-is-done t)
23072 (defadvice texmathp (around org-math-always-on activate)
23073 "Always return t in org-mode buffers.
23074 This is because we want to insert math symbols without dollars even outside
23075 the LaTeX math segments. If Orgmode thinks that point is actually inside
23076 en embedded LaTeX fragement, let texmathp do its job.
23077 \\[org-cdlatex-mode-map]"
23078 (interactive)
23079 (let (p)
23080 (cond
23081 ((not (org-mode-p)) ad-do-it)
23082 ((eq this-command 'cdlatex-math-symbol)
23083 (setq ad-return-value t
23084 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
23086 (let ((p (org-inside-LaTeX-fragment-p)))
23087 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
23088 (setq ad-return-value t
23089 texmathp-why '("Org-mode embedded math" . 0))
23090 (if p ad-do-it)))))))))
23092 (defun turn-on-org-cdlatex ()
23093 "Unconditionally turn on `org-cdlatex-mode'."
23094 (org-cdlatex-mode 1))
23096 (defun org-inside-LaTeX-fragment-p ()
23097 "Test if point is inside a LaTeX fragment.
23098 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
23099 sequence appearing also before point.
23100 Even though the matchers for math are configurable, this function assumes
23101 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
23102 delimiters are skipped when they have been removed by customization.
23103 The return value is nil, or a cons cell with the delimiter and
23104 and the position of this delimiter.
23106 This function does a reasonably good job, but can locally be fooled by
23107 for example currency specifications. For example it will assume being in
23108 inline math after \"$22.34\". The LaTeX fragment formatter will only format
23109 fragments that are properly closed, but during editing, we have to live
23110 with the uncertainty caused by missing closing delimiters. This function
23111 looks only before point, not after."
23112 (catch 'exit
23113 (let ((pos (point))
23114 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
23115 (lim (progn
23116 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
23117 (point)))
23118 dd-on str (start 0) m re)
23119 (goto-char pos)
23120 (when dodollar
23121 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
23122 re (nth 1 (assoc "$" org-latex-regexps)))
23123 (while (string-match re str start)
23124 (cond
23125 ((= (match-end 0) (length str))
23126 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
23127 ((= (match-end 0) (- (length str) 5))
23128 (throw 'exit nil))
23129 (t (setq start (match-end 0))))))
23130 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
23131 (goto-char pos)
23132 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
23133 (and (match-beginning 2) (throw 'exit nil))
23134 ;; count $$
23135 (while (re-search-backward "\\$\\$" lim t)
23136 (setq dd-on (not dd-on)))
23137 (goto-char pos)
23138 (if dd-on (cons "$$" m))))))
23141 (defun org-try-cdlatex-tab ()
23142 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
23143 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
23144 - inside a LaTeX fragment, or
23145 - after the first word in a line, where an abbreviation expansion could
23146 insert a LaTeX environment."
23147 (when org-cdlatex-mode
23148 (cond
23149 ((save-excursion
23150 (skip-chars-backward "a-zA-Z0-9*")
23151 (skip-chars-backward " \t")
23152 (bolp))
23153 (cdlatex-tab) t)
23154 ((org-inside-LaTeX-fragment-p)
23155 (cdlatex-tab) t)
23156 (t nil))))
23158 (defun org-cdlatex-underscore-caret (&optional arg)
23159 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
23160 Revert to the normal definition outside of these fragments."
23161 (interactive "P")
23162 (if (org-inside-LaTeX-fragment-p)
23163 (call-interactively 'cdlatex-sub-superscript)
23164 (let (org-cdlatex-mode)
23165 (call-interactively (key-binding (vector last-input-event))))))
23167 (defun org-cdlatex-math-modify (&optional arg)
23168 "Execute `cdlatex-math-modify' in LaTeX fragments.
23169 Revert to the normal definition outside of these fragments."
23170 (interactive "P")
23171 (if (org-inside-LaTeX-fragment-p)
23172 (call-interactively 'cdlatex-math-modify)
23173 (let (org-cdlatex-mode)
23174 (call-interactively (key-binding (vector last-input-event))))))
23176 (defvar org-latex-fragment-image-overlays nil
23177 "List of overlays carrying the images of latex fragments.")
23178 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
23180 (defun org-remove-latex-fragment-image-overlays ()
23181 "Remove all overlays with LaTeX fragment images in current buffer."
23182 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
23183 (setq org-latex-fragment-image-overlays nil))
23185 (defun org-preview-latex-fragment (&optional subtree)
23186 "Preview the LaTeX fragment at point, or all locally or globally.
23187 If the cursor is in a LaTeX fragment, create the image and overlay
23188 it over the source code. If there is no fragment at point, display
23189 all fragments in the current text, from one headline to the next. With
23190 prefix SUBTREE, display all fragments in the current subtree. With a
23191 double prefix `C-u C-u', or when the cursor is before the first headline,
23192 display all fragments in the buffer.
23193 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
23194 (interactive "P")
23195 (org-remove-latex-fragment-image-overlays)
23196 (save-excursion
23197 (save-restriction
23198 (let (beg end at msg)
23199 (cond
23200 ((or (equal subtree '(16))
23201 (not (save-excursion
23202 (re-search-backward (concat "^" outline-regexp) nil t))))
23203 (setq beg (point-min) end (point-max)
23204 msg "Creating images for buffer...%s"))
23205 ((equal subtree '(4))
23206 (org-back-to-heading)
23207 (setq beg (point) end (org-end-of-subtree t)
23208 msg "Creating images for subtree...%s"))
23210 (if (setq at (org-inside-LaTeX-fragment-p))
23211 (goto-char (max (point-min) (- (cdr at) 2)))
23212 (org-back-to-heading))
23213 (setq beg (point) end (progn (outline-next-heading) (point))
23214 msg (if at "Creating image...%s"
23215 "Creating images for entry...%s"))))
23216 (message msg "")
23217 (narrow-to-region beg end)
23218 (goto-char beg)
23219 (org-format-latex
23220 (concat "ltxpng/" (file-name-sans-extension
23221 (file-name-nondirectory
23222 buffer-file-name)))
23223 default-directory 'overlays msg at 'forbuffer)
23224 (message msg "done. Use `C-c C-c' to remove images.")))))
23226 (defvar org-latex-regexps
23227 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
23228 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
23229 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
23230 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
23231 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
23232 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
23233 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
23234 "Regular expressions for matching embedded LaTeX.")
23236 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
23237 "Replace LaTeX fragments with links to an image, and produce images."
23238 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
23239 (let* ((prefixnodir (file-name-nondirectory prefix))
23240 (absprefix (expand-file-name prefix dir))
23241 (todir (file-name-directory absprefix))
23242 (opt org-format-latex-options)
23243 (matchers (plist-get opt :matchers))
23244 (re-list org-latex-regexps)
23245 (cnt 0) txt link beg end re e checkdir
23246 m n block linkfile movefile ov)
23247 ;; Check if there are old images files with this prefix, and remove them
23248 (when (file-directory-p todir)
23249 (mapc 'delete-file
23250 (directory-files
23251 todir 'full
23252 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
23253 ;; Check the different regular expressions
23254 (while (setq e (pop re-list))
23255 (setq m (car e) re (nth 1 e) n (nth 2 e)
23256 block (if (nth 3 e) "\n\n" ""))
23257 (when (member m matchers)
23258 (goto-char (point-min))
23259 (while (re-search-forward re nil t)
23260 (when (or (not at) (equal (cdr at) (match-beginning n)))
23261 (setq txt (match-string n)
23262 beg (match-beginning n) end (match-end n)
23263 cnt (1+ cnt)
23264 linkfile (format "%s_%04d.png" prefix cnt)
23265 movefile (format "%s_%04d.png" absprefix cnt)
23266 link (concat block "[[file:" linkfile "]]" block))
23267 (if msg (message msg cnt))
23268 (goto-char beg)
23269 (unless checkdir ; make sure the directory exists
23270 (setq checkdir t)
23271 (or (file-directory-p todir) (make-directory todir)))
23272 (org-create-formula-image
23273 txt movefile opt forbuffer)
23274 (if overlays
23275 (progn
23276 (setq ov (org-make-overlay beg end))
23277 (if (featurep 'xemacs)
23278 (progn
23279 (org-overlay-put ov 'invisible t)
23280 (org-overlay-put
23281 ov 'end-glyph
23282 (make-glyph (vector 'png :file movefile))))
23283 (org-overlay-put
23284 ov 'display
23285 (list 'image :type 'png :file movefile :ascent 'center)))
23286 (push ov org-latex-fragment-image-overlays)
23287 (goto-char end))
23288 (delete-region beg end)
23289 (insert link))))))))
23291 ;; This function borrows from Ganesh Swami's latex2png.el
23292 (defun org-create-formula-image (string tofile options buffer)
23293 (let* ((tmpdir (if (featurep 'xemacs)
23294 (temp-directory)
23295 temporary-file-directory))
23296 (texfilebase (make-temp-name
23297 (expand-file-name "orgtex" tmpdir)))
23298 (texfile (concat texfilebase ".tex"))
23299 (dvifile (concat texfilebase ".dvi"))
23300 (pngfile (concat texfilebase ".png"))
23301 (fnh (face-attribute 'default :height nil))
23302 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
23303 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
23304 (fg (or (plist-get options (if buffer :foreground :html-foreground))
23305 "Black"))
23306 (bg (or (plist-get options (if buffer :background :html-background))
23307 "Transparent")))
23308 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
23309 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
23310 (with-temp-file texfile
23311 (insert org-format-latex-header
23312 "\n\\begin{document}\n" string "\n\\end{document}\n"))
23313 (let ((dir default-directory))
23314 (condition-case nil
23315 (progn
23316 (cd tmpdir)
23317 (call-process "latex" nil nil nil texfile))
23318 (error nil))
23319 (cd dir))
23320 (if (not (file-exists-p dvifile))
23321 (progn (message "Failed to create dvi file from %s" texfile) nil)
23322 (call-process "dvipng" nil nil nil
23323 "-E" "-fg" fg "-bg" bg
23324 "-D" dpi
23325 ;;"-x" scale "-y" scale
23326 "-T" "tight"
23327 "-o" pngfile
23328 dvifile)
23329 (if (not (file-exists-p pngfile))
23330 (progn (message "Failed to create png file from %s" texfile) nil)
23331 ;; Use the requested file name and clean up
23332 (copy-file pngfile tofile 'replace)
23333 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
23334 (delete-file (concat texfilebase e)))
23335 pngfile))))
23337 (defun org-dvipng-color (attr)
23338 "Return an rgb color specification for dvipng."
23339 (apply 'format "rgb %s %s %s"
23340 (mapcar 'org-normalize-color
23341 (color-values (face-attribute 'default attr nil)))))
23343 (defun org-normalize-color (value)
23344 "Return string to be used as color value for an RGB component."
23345 (format "%g" (/ value 65535.0)))
23347 ;;;; Exporting
23349 ;;; Variables, constants, and parameter plists
23351 (defconst org-level-max 20)
23353 (defvar org-export-html-preamble nil
23354 "Preamble, to be inserted just after <body>. Set by publishing functions.")
23355 (defvar org-export-html-postamble nil
23356 "Preamble, to be inserted just before </body>. Set by publishing functions.")
23357 (defvar org-export-html-auto-preamble t
23358 "Should default preamble be inserted? Set by publishing functions.")
23359 (defvar org-export-html-auto-postamble t
23360 "Should default postamble be inserted? Set by publishing functions.")
23361 (defvar org-current-export-file nil) ; dynamically scoped parameter
23362 (defvar org-current-export-dir nil) ; dynamically scoped parameter
23365 (defconst org-export-plist-vars
23366 '((:language . org-export-default-language)
23367 (:customtime . org-display-custom-times)
23368 (:headline-levels . org-export-headline-levels)
23369 (:section-numbers . org-export-with-section-numbers)
23370 (:table-of-contents . org-export-with-toc)
23371 (:preserve-breaks . org-export-preserve-breaks)
23372 (:archived-trees . org-export-with-archived-trees)
23373 (:emphasize . org-export-with-emphasize)
23374 (:sub-superscript . org-export-with-sub-superscripts)
23375 (:special-strings . org-export-with-special-strings)
23376 (:footnotes . org-export-with-footnotes)
23377 (:drawers . org-export-with-drawers)
23378 (:tags . org-export-with-tags)
23379 (:TeX-macros . org-export-with-TeX-macros)
23380 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
23381 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
23382 (:fixed-width . org-export-with-fixed-width)
23383 (:timestamps . org-export-with-timestamps)
23384 (:author-info . org-export-author-info)
23385 (:time-stamp-file . org-export-time-stamp-file)
23386 (:tables . org-export-with-tables)
23387 (:table-auto-headline . org-export-highlight-first-table-line)
23388 (:style . org-export-html-style)
23389 (:agenda-style . org-agenda-export-html-style)
23390 (:convert-org-links . org-export-html-link-org-files-as-html)
23391 (:inline-images . org-export-html-inline-images)
23392 (:html-extension . org-export-html-extension)
23393 (:html-table-tag . org-export-html-table-tag)
23394 (:expand-quoted-html . org-export-html-expand)
23395 (:timestamp . org-export-html-with-timestamp)
23396 (:publishing-directory . org-export-publishing-directory)
23397 (:preamble . org-export-html-preamble)
23398 (:postamble . org-export-html-postamble)
23399 (:auto-preamble . org-export-html-auto-preamble)
23400 (:auto-postamble . org-export-html-auto-postamble)
23401 (:author . user-full-name)
23402 (:email . user-mail-address)))
23404 (defun org-default-export-plist ()
23405 "Return the property list with default settings for the export variables."
23406 (let ((l org-export-plist-vars) rtn e)
23407 (while (setq e (pop l))
23408 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
23409 rtn))
23411 (defun org-infile-export-plist ()
23412 "Return the property list with file-local settings for export."
23413 (save-excursion
23414 (save-restriction
23415 (widen)
23416 (goto-char 0)
23417 (let ((re (org-make-options-regexp
23418 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
23419 p key val text options)
23420 (while (re-search-forward re nil t)
23421 (setq key (org-match-string-no-properties 1)
23422 val (org-match-string-no-properties 2))
23423 (cond
23424 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
23425 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
23426 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
23427 ((string-equal key "DATE") (setq p (plist-put p :date val)))
23428 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
23429 ((string-equal key "TEXT")
23430 (setq text (if text (concat text "\n" val) val)))
23431 ((string-equal key "OPTIONS") (setq options val))))
23432 (setq p (plist-put p :text text))
23433 (when options
23434 (let ((op '(("H" . :headline-levels)
23435 ("num" . :section-numbers)
23436 ("toc" . :table-of-contents)
23437 ("\\n" . :preserve-breaks)
23438 ("@" . :expand-quoted-html)
23439 (":" . :fixed-width)
23440 ("|" . :tables)
23441 ("^" . :sub-superscript)
23442 ("-" . :special-strings)
23443 ("f" . :footnotes)
23444 ("d" . :drawers)
23445 ("tags" . :tags)
23446 ("*" . :emphasize)
23447 ("TeX" . :TeX-macros)
23448 ("LaTeX" . :LaTeX-fragments)
23449 ("skip" . :skip-before-1st-heading)
23450 ("author" . :author-info)
23451 ("timestamp" . :time-stamp-file)))
23453 (while (setq o (pop op))
23454 (if (string-match (concat (regexp-quote (car o))
23455 ":\\([^ \t\n\r;,.]*\\)")
23456 options)
23457 (setq p (plist-put p (cdr o)
23458 (car (read-from-string
23459 (match-string 1 options)))))))))
23460 p))))
23462 (defun org-export-directory (type plist)
23463 (let* ((val (plist-get plist :publishing-directory))
23464 (dir (if (listp val)
23465 (or (cdr (assoc type val)) ".")
23466 val)))
23467 dir))
23469 (defun org-skip-comments (lines)
23470 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
23471 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
23472 (re2 "^\\(\\*+\\)[ \t\n\r]")
23473 (case-fold-search nil)
23474 rtn line level)
23475 (while (setq line (pop lines))
23476 (cond
23477 ((and (string-match re1 line)
23478 (setq level (- (match-end 1) (match-beginning 1))))
23479 ;; Beginning of a COMMENT subtree. Skip it.
23480 (while (and (setq line (pop lines))
23481 (or (not (string-match re2 line))
23482 (> (- (match-end 1) (match-beginning 1)) level))))
23483 (setq lines (cons line lines)))
23484 ((string-match "^#" line)
23485 ;; an ordinary comment line
23487 ((and org-export-table-remove-special-lines
23488 (string-match "^[ \t]*|" line)
23489 (or (string-match "^[ \t]*| *[!_^] *|" line)
23490 (and (string-match "| *<[0-9]+> *|" line)
23491 (not (string-match "| *[^ <|]" line)))))
23492 ;; a special table line that should be removed
23494 (t (setq rtn (cons line rtn)))))
23495 (nreverse rtn)))
23497 (defun org-export (&optional arg)
23498 (interactive)
23499 (let ((help "[t] insert the export option template
23500 \[v] limit export to visible part of outline tree
23502 \[a] export as ASCII
23504 \[h] export as HTML
23505 \[H] export as HTML to temporary buffer
23506 \[R] export region as HTML
23507 \[b] export as HTML and browse immediately
23508 \[x] export as XOXO
23510 \[l] export as LaTeX
23511 \[L] export as LaTeX to temporary buffer
23513 \[i] export current file as iCalendar file
23514 \[I] export all agenda files as iCalendar files
23515 \[c] export agenda files into combined iCalendar file
23517 \[F] publish current file
23518 \[P] publish current project
23519 \[X] publish... (project will be prompted for)
23520 \[A] publish all projects")
23521 (cmds
23522 '((?t . org-insert-export-options-template)
23523 (?v . org-export-visible)
23524 (?a . org-export-as-ascii)
23525 (?h . org-export-as-html)
23526 (?b . org-export-as-html-and-open)
23527 (?H . org-export-as-html-to-buffer)
23528 (?R . org-export-region-as-html)
23529 (?x . org-export-as-xoxo)
23530 (?l . org-export-as-latex)
23531 (?L . org-export-as-latex-to-buffer)
23532 (?i . org-export-icalendar-this-file)
23533 (?I . org-export-icalendar-all-agenda-files)
23534 (?c . org-export-icalendar-combine-agenda-files)
23535 (?F . org-publish-current-file)
23536 (?P . org-publish-current-project)
23537 (?X . org-publish)
23538 (?A . org-publish-all)))
23539 r1 r2 ass)
23540 (save-window-excursion
23541 (delete-other-windows)
23542 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
23543 (princ help))
23544 (message "Select command: ")
23545 (setq r1 (read-char-exclusive)))
23546 (setq r2 (if (< r1 27) (+ r1 96) r1))
23547 (if (setq ass (assq r2 cmds))
23548 (call-interactively (cdr ass))
23549 (error "No command associated with key %c" r1))))
23551 (defconst org-html-entities
23552 '(("nbsp")
23553 ("iexcl")
23554 ("cent")
23555 ("pound")
23556 ("curren")
23557 ("yen")
23558 ("brvbar")
23559 ("vert" . "&#124;")
23560 ("sect")
23561 ("uml")
23562 ("copy")
23563 ("ordf")
23564 ("laquo")
23565 ("not")
23566 ("shy")
23567 ("reg")
23568 ("macr")
23569 ("deg")
23570 ("plusmn")
23571 ("sup2")
23572 ("sup3")
23573 ("acute")
23574 ("micro")
23575 ("para")
23576 ("middot")
23577 ("odot"."o")
23578 ("star"."*")
23579 ("cedil")
23580 ("sup1")
23581 ("ordm")
23582 ("raquo")
23583 ("frac14")
23584 ("frac12")
23585 ("frac34")
23586 ("iquest")
23587 ("Agrave")
23588 ("Aacute")
23589 ("Acirc")
23590 ("Atilde")
23591 ("Auml")
23592 ("Aring") ("AA"."&Aring;")
23593 ("AElig")
23594 ("Ccedil")
23595 ("Egrave")
23596 ("Eacute")
23597 ("Ecirc")
23598 ("Euml")
23599 ("Igrave")
23600 ("Iacute")
23601 ("Icirc")
23602 ("Iuml")
23603 ("ETH")
23604 ("Ntilde")
23605 ("Ograve")
23606 ("Oacute")
23607 ("Ocirc")
23608 ("Otilde")
23609 ("Ouml")
23610 ("times")
23611 ("Oslash")
23612 ("Ugrave")
23613 ("Uacute")
23614 ("Ucirc")
23615 ("Uuml")
23616 ("Yacute")
23617 ("THORN")
23618 ("szlig")
23619 ("agrave")
23620 ("aacute")
23621 ("acirc")
23622 ("atilde")
23623 ("auml")
23624 ("aring")
23625 ("aelig")
23626 ("ccedil")
23627 ("egrave")
23628 ("eacute")
23629 ("ecirc")
23630 ("euml")
23631 ("igrave")
23632 ("iacute")
23633 ("icirc")
23634 ("iuml")
23635 ("eth")
23636 ("ntilde")
23637 ("ograve")
23638 ("oacute")
23639 ("ocirc")
23640 ("otilde")
23641 ("ouml")
23642 ("divide")
23643 ("oslash")
23644 ("ugrave")
23645 ("uacute")
23646 ("ucirc")
23647 ("uuml")
23648 ("yacute")
23649 ("thorn")
23650 ("yuml")
23651 ("fnof")
23652 ("Alpha")
23653 ("Beta")
23654 ("Gamma")
23655 ("Delta")
23656 ("Epsilon")
23657 ("Zeta")
23658 ("Eta")
23659 ("Theta")
23660 ("Iota")
23661 ("Kappa")
23662 ("Lambda")
23663 ("Mu")
23664 ("Nu")
23665 ("Xi")
23666 ("Omicron")
23667 ("Pi")
23668 ("Rho")
23669 ("Sigma")
23670 ("Tau")
23671 ("Upsilon")
23672 ("Phi")
23673 ("Chi")
23674 ("Psi")
23675 ("Omega")
23676 ("alpha")
23677 ("beta")
23678 ("gamma")
23679 ("delta")
23680 ("epsilon")
23681 ("varepsilon"."&epsilon;")
23682 ("zeta")
23683 ("eta")
23684 ("theta")
23685 ("iota")
23686 ("kappa")
23687 ("lambda")
23688 ("mu")
23689 ("nu")
23690 ("xi")
23691 ("omicron")
23692 ("pi")
23693 ("rho")
23694 ("sigmaf") ("varsigma"."&sigmaf;")
23695 ("sigma")
23696 ("tau")
23697 ("upsilon")
23698 ("phi")
23699 ("chi")
23700 ("psi")
23701 ("omega")
23702 ("thetasym") ("vartheta"."&thetasym;")
23703 ("upsih")
23704 ("piv")
23705 ("bull") ("bullet"."&bull;")
23706 ("hellip") ("dots"."&hellip;")
23707 ("prime")
23708 ("Prime")
23709 ("oline")
23710 ("frasl")
23711 ("weierp")
23712 ("image")
23713 ("real")
23714 ("trade")
23715 ("alefsym")
23716 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
23717 ("uarr") ("uparrow"."&uarr;")
23718 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
23719 ("darr")("downarrow"."&darr;")
23720 ("harr") ("leftrightarrow"."&harr;")
23721 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
23722 ("lArr") ("Leftarrow"."&lArr;")
23723 ("uArr") ("Uparrow"."&uArr;")
23724 ("rArr") ("Rightarrow"."&rArr;")
23725 ("dArr") ("Downarrow"."&dArr;")
23726 ("hArr") ("Leftrightarrow"."&hArr;")
23727 ("forall")
23728 ("part") ("partial"."&part;")
23729 ("exist") ("exists"."&exist;")
23730 ("empty") ("emptyset"."&empty;")
23731 ("nabla")
23732 ("isin") ("in"."&isin;")
23733 ("notin")
23734 ("ni")
23735 ("prod")
23736 ("sum")
23737 ("minus")
23738 ("lowast") ("ast"."&lowast;")
23739 ("radic")
23740 ("prop") ("proptp"."&prop;")
23741 ("infin") ("infty"."&infin;")
23742 ("ang") ("angle"."&ang;")
23743 ("and") ("wedge"."&and;")
23744 ("or") ("vee"."&or;")
23745 ("cap")
23746 ("cup")
23747 ("int")
23748 ("there4")
23749 ("sim")
23750 ("cong") ("simeq"."&cong;")
23751 ("asymp")("approx"."&asymp;")
23752 ("ne") ("neq"."&ne;")
23753 ("equiv")
23754 ("le")
23755 ("ge")
23756 ("sub") ("subset"."&sub;")
23757 ("sup") ("supset"."&sup;")
23758 ("nsub")
23759 ("sube")
23760 ("supe")
23761 ("oplus")
23762 ("otimes")
23763 ("perp")
23764 ("sdot") ("cdot"."&sdot;")
23765 ("lceil")
23766 ("rceil")
23767 ("lfloor")
23768 ("rfloor")
23769 ("lang")
23770 ("rang")
23771 ("loz") ("Diamond"."&loz;")
23772 ("spades") ("spadesuit"."&spades;")
23773 ("clubs") ("clubsuit"."&clubs;")
23774 ("hearts") ("diamondsuit"."&hearts;")
23775 ("diams") ("diamondsuit"."&diams;")
23776 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
23777 ("quot")
23778 ("amp")
23779 ("lt")
23780 ("gt")
23781 ("OElig")
23782 ("oelig")
23783 ("Scaron")
23784 ("scaron")
23785 ("Yuml")
23786 ("circ")
23787 ("tilde")
23788 ("ensp")
23789 ("emsp")
23790 ("thinsp")
23791 ("zwnj")
23792 ("zwj")
23793 ("lrm")
23794 ("rlm")
23795 ("ndash")
23796 ("mdash")
23797 ("lsquo")
23798 ("rsquo")
23799 ("sbquo")
23800 ("ldquo")
23801 ("rdquo")
23802 ("bdquo")
23803 ("dagger")
23804 ("Dagger")
23805 ("permil")
23806 ("lsaquo")
23807 ("rsaquo")
23808 ("euro")
23810 ("arccos"."arccos")
23811 ("arcsin"."arcsin")
23812 ("arctan"."arctan")
23813 ("arg"."arg")
23814 ("cos"."cos")
23815 ("cosh"."cosh")
23816 ("cot"."cot")
23817 ("coth"."coth")
23818 ("csc"."csc")
23819 ("deg"."deg")
23820 ("det"."det")
23821 ("dim"."dim")
23822 ("exp"."exp")
23823 ("gcd"."gcd")
23824 ("hom"."hom")
23825 ("inf"."inf")
23826 ("ker"."ker")
23827 ("lg"."lg")
23828 ("lim"."lim")
23829 ("liminf"."liminf")
23830 ("limsup"."limsup")
23831 ("ln"."ln")
23832 ("log"."log")
23833 ("max"."max")
23834 ("min"."min")
23835 ("Pr"."Pr")
23836 ("sec"."sec")
23837 ("sin"."sin")
23838 ("sinh"."sinh")
23839 ("sup"."sup")
23840 ("tan"."tan")
23841 ("tanh"."tanh")
23843 "Entities for TeX->HTML translation.
23844 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
23845 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
23846 In that case, \"\\ent\" will be translated to \"&other;\".
23847 The list contains HTML entities for Latin-1, Greek and other symbols.
23848 It is supplemented by a number of commonly used TeX macros with appropriate
23849 translations. There is currently no way for users to extend this.")
23851 ;;; General functions for all backends
23853 (defun org-cleaned-string-for-export (string &rest parameters)
23854 "Cleanup a buffer STRING so that links can be created safely."
23855 (interactive)
23856 (let* ((re-radio (and org-target-link-regexp
23857 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
23858 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
23859 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
23860 (re-archive (concat ":" org-archive-tag ":"))
23861 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
23862 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
23863 (htmlp (plist-get parameters :for-html))
23864 (asciip (plist-get parameters :for-ascii))
23865 (latexp (plist-get parameters :for-LaTeX))
23866 (commentsp (plist-get parameters :comments))
23867 (archived-trees (plist-get parameters :archived-trees))
23868 (inhibit-read-only t)
23869 (drawers org-drawers)
23870 (exp-drawers (plist-get parameters :drawers))
23871 (outline-regexp "\\*+ ")
23872 a b xx
23873 rtn p)
23874 (with-current-buffer (get-buffer-create " org-mode-tmp")
23875 (erase-buffer)
23876 (insert string)
23877 ;; Remove license-to-kill stuff
23878 (while (setq p (text-property-any (point-min) (point-max)
23879 :org-license-to-kill t))
23880 (delete-region p (next-single-property-change p :org-license-to-kill)))
23882 (let ((org-inhibit-startup t)) (org-mode))
23883 (untabify (point-min) (point-max))
23885 ;; Get the correct stuff before the first headline
23886 (when (plist-get parameters :skip-before-1st-heading)
23887 (goto-char (point-min))
23888 (when (re-search-forward "^\\*+[ \t]" nil t)
23889 (delete-region (point-min) (match-beginning 0))
23890 (goto-char (point-min))
23891 (insert "\n")))
23892 (when (plist-get parameters :add-text)
23893 (goto-char (point-min))
23894 (insert (plist-get parameters :add-text) "\n"))
23896 ;; Get rid of archived trees
23897 (when (not (eq archived-trees t))
23898 (goto-char (point-min))
23899 (while (re-search-forward re-archive nil t)
23900 (if (not (org-on-heading-p t))
23901 (org-end-of-subtree t)
23902 (beginning-of-line 1)
23903 (setq a (if archived-trees
23904 (1+ (point-at-eol)) (point))
23905 b (org-end-of-subtree t))
23906 (if (> b a) (delete-region a b)))))
23908 ;; Get rid of drawers
23909 (unless (eq t exp-drawers)
23910 (goto-char (point-min))
23911 (let ((re (concat "^[ \t]*:\\("
23912 (mapconcat
23913 'identity
23914 (org-delete-all exp-drawers
23915 (copy-sequence drawers))
23916 "\\|")
23917 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
23918 (while (re-search-forward re nil t)
23919 (replace-match ""))))
23921 ;; Find targets in comments and move them out of comments,
23922 ;; but mark them as targets that should be invisible
23923 (goto-char (point-min))
23924 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
23925 (replace-match "\\1(INVISIBLE)"))
23927 ;; Protect backend specific stuff, throw away the others.
23928 (let ((formatters
23929 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
23930 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
23931 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
23932 fmt)
23933 (goto-char (point-min))
23934 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
23935 (goto-char (match-end 0))
23936 (while (not (looking-at "#\\+END_EXAMPLE"))
23937 (insert ": ")
23938 (beginning-of-line 2)))
23939 (goto-char (point-min))
23940 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
23941 (add-text-properties (match-beginning 0) (match-end 0)
23942 '(org-protected t)))
23943 (while formatters
23944 (setq fmt (pop formatters))
23945 (when (car fmt)
23946 (goto-char (point-min))
23947 (while (re-search-forward (concat "^#\\+" (cadr fmt)
23948 ":[ \t]*\\(.*\\)") nil t)
23949 (replace-match "\\1" t)
23950 (add-text-properties
23951 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
23952 '(org-protected t))))
23953 (goto-char (point-min))
23954 (while (re-search-forward
23955 (concat "^#\\+"
23956 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
23957 (cadddr fmt) "\\>.*\n?") nil t)
23958 (if (car fmt)
23959 (add-text-properties (match-beginning 1) (1+ (match-end 1))
23960 '(org-protected t))
23961 (delete-region (match-beginning 0) (match-end 0))))))
23963 ;; Protect quoted subtrees
23964 (goto-char (point-min))
23965 (while (re-search-forward re-quote nil t)
23966 (goto-char (match-beginning 0))
23967 (end-of-line 1)
23968 (add-text-properties (point) (org-end-of-subtree t)
23969 '(org-protected t)))
23971 ;; Protect verbatim elements
23972 (goto-char (point-min))
23973 (while (re-search-forward org-verbatim-re nil t)
23974 (add-text-properties (match-beginning 4) (match-end 4)
23975 '(org-protected t))
23976 (goto-char (1+ (match-end 4))))
23978 ;; Remove subtrees that are commented
23979 (goto-char (point-min))
23980 (while (re-search-forward re-commented nil t)
23981 (goto-char (match-beginning 0))
23982 (delete-region (point) (org-end-of-subtree t)))
23984 ;; Remove special table lines
23985 (when org-export-table-remove-special-lines
23986 (goto-char (point-min))
23987 (while (re-search-forward "^[ \t]*|" nil t)
23988 (beginning-of-line 1)
23989 (if (or (looking-at "[ \t]*| *[!_^] *|")
23990 (and (looking-at ".*?| *<[0-9]+> *|")
23991 (not (looking-at ".*?| *[^ <|]"))))
23992 (delete-region (max (point-min) (1- (point-at-bol)))
23993 (point-at-eol))
23994 (end-of-line 1))))
23996 ;; Specific LaTeX stuff
23997 (when latexp
23998 (require 'org-export-latex nil)
23999 (org-export-latex-cleaned-string))
24001 (when asciip
24002 (org-export-ascii-clean-string))
24004 ;; Specific HTML stuff
24005 (when htmlp
24006 ;; Convert LaTeX fragments to images
24007 (when (plist-get parameters :LaTeX-fragments)
24008 (org-format-latex
24009 (concat "ltxpng/" (file-name-sans-extension
24010 (file-name-nondirectory
24011 org-current-export-file)))
24012 org-current-export-dir nil "Creating LaTeX image %s"))
24013 (message "Exporting..."))
24015 ;; Remove or replace comments
24016 (goto-char (point-min))
24017 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
24018 (if commentsp
24019 (progn (add-text-properties
24020 (match-beginning 0) (match-end 0) '(org-protected t))
24021 (replace-match (format commentsp (match-string 1)) t t))
24022 (replace-match "")))
24024 ;; Find matches for radio targets and turn them into internal links
24025 (goto-char (point-min))
24026 (when re-radio
24027 (while (re-search-forward re-radio nil t)
24028 (org-if-unprotected
24029 (replace-match "\\1[[\\2]]"))))
24031 ;; Find all links that contain a newline and put them into a single line
24032 (goto-char (point-min))
24033 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
24034 (org-if-unprotected
24035 (replace-match "\\1 \\3")
24036 (goto-char (match-beginning 0))))
24039 ;; Normalize links: Convert angle and plain links into bracket links
24040 ;; Expand link abbreviations
24041 (goto-char (point-min))
24042 (while (re-search-forward re-plain-link nil t)
24043 (goto-char (1- (match-end 0)))
24044 (org-if-unprotected
24045 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24046 ":" (match-string 3) "]]")))
24047 ;; added 'org-link face to links
24048 (put-text-property 0 (length s) 'face 'org-link s)
24049 (replace-match s t t))))
24050 (goto-char (point-min))
24051 (while (re-search-forward re-angle-link nil t)
24052 (goto-char (1- (match-end 0)))
24053 (org-if-unprotected
24054 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24055 ":" (match-string 3) "]]")))
24056 (put-text-property 0 (length s) 'face 'org-link s)
24057 (replace-match s t t))))
24058 (goto-char (point-min))
24059 (while (re-search-forward org-bracket-link-regexp nil t)
24060 (org-if-unprotected
24061 (let* ((s (concat "[[" (setq xx (save-match-data
24062 (org-link-expand-abbrev (match-string 1))))
24064 (if (match-end 3)
24065 (match-string 2)
24066 (concat "[" xx "]"))
24067 "]")))
24068 (put-text-property 0 (length s) 'face 'org-link s)
24069 (replace-match s t t))))
24071 ;; Find multiline emphasis and put them into single line
24072 (when (plist-get parameters :emph-multiline)
24073 (goto-char (point-min))
24074 (while (re-search-forward org-emph-re nil t)
24075 (if (not (= (char-after (match-beginning 3))
24076 (char-after (match-beginning 4))))
24077 (org-if-unprotected
24078 (subst-char-in-region (match-beginning 0) (match-end 0)
24079 ?\n ?\ t)
24080 (goto-char (1- (match-end 0))))
24081 (goto-char (1+ (match-beginning 0))))))
24083 (setq rtn (buffer-string)))
24084 (kill-buffer " org-mode-tmp")
24085 rtn))
24087 (defun org-export-grab-title-from-buffer ()
24088 "Get a title for the current document, from looking at the buffer."
24089 (let ((inhibit-read-only t))
24090 (save-excursion
24091 (goto-char (point-min))
24092 (let ((end (save-excursion (outline-next-heading) (point))))
24093 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
24094 ;; Mark the line so that it will not be exported as normal text.
24095 (org-unmodified
24096 (add-text-properties (match-beginning 0) (match-end 0)
24097 (list :org-license-to-kill t)))
24098 ;; Return the title string
24099 (org-trim (match-string 0)))))))
24101 (defun org-export-get-title-from-subtree ()
24102 "Return subtree title and exclude it from export."
24103 (let (title (m (mark)))
24104 (save-excursion
24105 (goto-char (region-beginning))
24106 (when (and (org-at-heading-p)
24107 (>= (org-end-of-subtree t t) (region-end)))
24108 ;; This is a subtree, we take the title from the first heading
24109 (goto-char (region-beginning))
24110 (looking-at org-todo-line-regexp)
24111 (setq title (match-string 3))
24112 (org-unmodified
24113 (add-text-properties (point) (1+ (point-at-eol))
24114 (list :org-license-to-kill t)))))
24115 title))
24117 (defun org-solidify-link-text (s &optional alist)
24118 "Take link text and make a safe target out of it."
24119 (save-match-data
24120 (let* ((rtn
24121 (mapconcat
24122 'identity
24123 (org-split-string s "[ \t\r\n]+") "--"))
24124 (a (assoc rtn alist)))
24125 (or (cdr a) rtn))))
24127 (defun org-get-min-level (lines)
24128 "Get the minimum level in LINES."
24129 (let ((re "^\\(\\*+\\) ") l min)
24130 (catch 'exit
24131 (while (setq l (pop lines))
24132 (if (string-match re l)
24133 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24134 1)))
24136 ;; Variable holding the vector with section numbers
24137 (defvar org-section-numbers (make-vector org-level-max 0))
24139 (defun org-init-section-numbers ()
24140 "Initialize the vector for the section numbers."
24141 (let* ((level -1)
24142 (numbers (nreverse (org-split-string "" "\\.")))
24143 (depth (1- (length org-section-numbers)))
24144 (i depth) number-string)
24145 (while (>= i 0)
24146 (if (> i level)
24147 (aset org-section-numbers i 0)
24148 (setq number-string (or (car numbers) "0"))
24149 (if (string-match "\\`[A-Z]\\'" number-string)
24150 (aset org-section-numbers i
24151 (- (string-to-char number-string) ?A -1))
24152 (aset org-section-numbers i (string-to-number number-string)))
24153 (pop numbers))
24154 (setq i (1- i)))))
24156 (defun org-section-number (&optional level)
24157 "Return a string with the current section number.
24158 When LEVEL is non-nil, increase section numbers on that level."
24159 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
24160 (when level
24161 (when (> level -1)
24162 (aset org-section-numbers
24163 level (1+ (aref org-section-numbers level))))
24164 (setq idx (1+ level))
24165 (while (<= idx depth)
24166 (if (not (= idx 1))
24167 (aset org-section-numbers idx 0))
24168 (setq idx (1+ idx))))
24169 (setq idx 0)
24170 (while (<= idx depth)
24171 (setq n (aref org-section-numbers idx))
24172 (setq string (concat string (if (not (string= string "")) "." "")
24173 (int-to-string n)))
24174 (setq idx (1+ idx)))
24175 (save-match-data
24176 (if (string-match "\\`\\([@0]\\.\\)+" string)
24177 (setq string (replace-match "" t nil string)))
24178 (if (string-match "\\(\\.0\\)+\\'" string)
24179 (setq string (replace-match "" t nil string))))
24180 string))
24182 ;;; ASCII export
24184 (defvar org-last-level nil) ; dynamically scoped variable
24185 (defvar org-min-level nil) ; dynamically scoped variable
24186 (defvar org-levels-open nil) ; dynamically scoped parameter
24187 (defvar org-ascii-current-indentation nil) ; For communication
24189 (defun org-export-as-ascii (arg)
24190 "Export the outline as a pretty ASCII file.
24191 If there is an active region, export only the region.
24192 The prefix ARG specifies how many levels of the outline should become
24193 underlined headlines. The default is 3."
24194 (interactive "P")
24195 (setq-default org-todo-line-regexp org-todo-line-regexp)
24196 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24197 (org-infile-export-plist)))
24198 (region-p (org-region-active-p))
24199 (subtree-p
24200 (when region-p
24201 (save-excursion
24202 (goto-char (region-beginning))
24203 (and (org-at-heading-p)
24204 (>= (org-end-of-subtree t t) (region-end))))))
24205 (custom-times org-display-custom-times)
24206 (org-ascii-current-indentation '(0 . 0))
24207 (level 0) line txt
24208 (umax nil)
24209 (umax-toc nil)
24210 (case-fold-search nil)
24211 (filename (concat (file-name-as-directory
24212 (org-export-directory :ascii opt-plist))
24213 (file-name-sans-extension
24214 (or (and subtree-p
24215 (org-entry-get (region-beginning)
24216 "EXPORT_FILE_NAME" t))
24217 (file-name-nondirectory buffer-file-name)))
24218 ".txt"))
24219 (filename (if (equal (file-truename filename)
24220 (file-truename buffer-file-name))
24221 (concat filename ".txt")
24222 filename))
24223 (buffer (find-file-noselect filename))
24224 (org-levels-open (make-vector org-level-max nil))
24225 (odd org-odd-levels-only)
24226 (date (plist-get opt-plist :date))
24227 (author (plist-get opt-plist :author))
24228 (title (or (and subtree-p (org-export-get-title-from-subtree))
24229 (plist-get opt-plist :title)
24230 (and (not
24231 (plist-get opt-plist :skip-before-1st-heading))
24232 (org-export-grab-title-from-buffer))
24233 (file-name-sans-extension
24234 (file-name-nondirectory buffer-file-name))))
24235 (email (plist-get opt-plist :email))
24236 (language (plist-get opt-plist :language))
24237 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24238 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
24239 (todo nil)
24240 (lang-words nil)
24241 (region
24242 (buffer-substring
24243 (if (org-region-active-p) (region-beginning) (point-min))
24244 (if (org-region-active-p) (region-end) (point-max))))
24245 (lines (org-split-string
24246 (org-cleaned-string-for-export
24247 region
24248 :for-ascii t
24249 :skip-before-1st-heading
24250 (plist-get opt-plist :skip-before-1st-heading)
24251 :drawers (plist-get opt-plist :drawers)
24252 :verbatim-multiline t
24253 :archived-trees
24254 (plist-get opt-plist :archived-trees)
24255 :add-text (plist-get opt-plist :text))
24256 "\n"))
24257 thetoc have-headings first-heading-pos
24258 table-open table-buffer)
24260 (let ((inhibit-read-only t))
24261 (org-unmodified
24262 (remove-text-properties (point-min) (point-max)
24263 '(:org-license-to-kill t))))
24265 (setq org-min-level (org-get-min-level lines))
24266 (setq org-last-level org-min-level)
24267 (org-init-section-numbers)
24269 (find-file-noselect filename)
24271 (setq lang-words (or (assoc language org-export-language-setup)
24272 (assoc "en" org-export-language-setup)))
24273 (switch-to-buffer-other-window buffer)
24274 (erase-buffer)
24275 (fundamental-mode)
24276 ;; create local variables for all options, to make sure all called
24277 ;; functions get the correct information
24278 (mapc (lambda (x)
24279 (set (make-local-variable (cdr x))
24280 (plist-get opt-plist (car x))))
24281 org-export-plist-vars)
24282 (org-set-local 'org-odd-levels-only odd)
24283 (setq umax (if arg (prefix-numeric-value arg)
24284 org-export-headline-levels))
24285 (setq umax-toc (if (integerp org-export-with-toc)
24286 (min org-export-with-toc umax)
24287 umax))
24289 ;; File header
24290 (if title (org-insert-centered title ?=))
24291 (insert "\n")
24292 (if (and (or author email)
24293 org-export-author-info)
24294 (insert (concat (nth 1 lang-words) ": " (or author "")
24295 (if email (concat " <" email ">") "")
24296 "\n")))
24298 (cond
24299 ((and date (string-match "%" date))
24300 (setq date (format-time-string date (current-time))))
24301 (date)
24302 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24304 (if (and date org-export-time-stamp-file)
24305 (insert (concat (nth 2 lang-words) ": " date"\n")))
24307 (insert "\n\n")
24309 (if org-export-with-toc
24310 (progn
24311 (push (concat (nth 3 lang-words) "\n") thetoc)
24312 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
24313 (mapc '(lambda (line)
24314 (if (string-match org-todo-line-regexp
24315 line)
24316 ;; This is a headline
24317 (progn
24318 (setq have-headings t)
24319 (setq level (- (match-end 1) (match-beginning 1))
24320 level (org-tr-level level)
24321 txt (match-string 3 line)
24322 todo
24323 (or (and org-export-mark-todo-in-toc
24324 (match-beginning 2)
24325 (not (member (match-string 2 line)
24326 org-done-keywords)))
24327 ; TODO, not DONE
24328 (and org-export-mark-todo-in-toc
24329 (= level umax-toc)
24330 (org-search-todo-below
24331 line lines level))))
24332 (setq txt (org-html-expand-for-ascii txt))
24334 (while (string-match org-bracket-link-regexp txt)
24335 (setq txt
24336 (replace-match
24337 (match-string (if (match-end 2) 3 1) txt)
24338 t t txt)))
24340 (if (and (memq org-export-with-tags '(not-in-toc nil))
24341 (string-match
24342 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
24343 txt))
24344 (setq txt (replace-match "" t t txt)))
24345 (if (string-match quote-re0 txt)
24346 (setq txt (replace-match "" t t txt)))
24348 (if org-export-with-section-numbers
24349 (setq txt (concat (org-section-number level)
24350 " " txt)))
24351 (if (<= level umax-toc)
24352 (progn
24353 (push
24354 (concat
24355 (make-string
24356 (* (max 0 (- level org-min-level)) 4) ?\ )
24357 (format (if todo "%s (*)\n" "%s\n") txt))
24358 thetoc)
24359 (setq org-last-level level))
24360 ))))
24361 lines)
24362 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24364 (org-init-section-numbers)
24365 (while (setq line (pop lines))
24366 ;; Remove the quoted HTML tags.
24367 (setq line (org-html-expand-for-ascii line))
24368 ;; Remove targets
24369 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
24370 (setq line (replace-match "" t t line)))
24371 ;; Replace internal links
24372 (while (string-match org-bracket-link-regexp line)
24373 (setq line (replace-match
24374 (if (match-end 3) "[\\3]" "[\\1]")
24375 t nil line)))
24376 (when custom-times
24377 (setq line (org-translate-time line)))
24378 (cond
24379 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24380 ;; a Headline
24381 (setq first-heading-pos (or first-heading-pos (point)))
24382 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24383 txt (match-string 2 line))
24384 (org-ascii-level-start level txt umax lines))
24386 ((and org-export-with-tables
24387 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24388 (if (not table-open)
24389 ;; New table starts
24390 (setq table-open t table-buffer nil))
24391 ;; Accumulate lines
24392 (setq table-buffer (cons line table-buffer))
24393 (when (or (not lines)
24394 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24395 (car lines))))
24396 (setq table-open nil
24397 table-buffer (nreverse table-buffer))
24398 (insert (mapconcat
24399 (lambda (x)
24400 (org-fix-indentation x org-ascii-current-indentation))
24401 (org-format-table-ascii table-buffer)
24402 "\n") "\n")))
24404 (setq line (org-fix-indentation line org-ascii-current-indentation))
24405 (if (and org-export-with-fixed-width
24406 (string-match "^\\([ \t]*\\)\\(:\\)" line))
24407 (setq line (replace-match "\\1" nil nil line)))
24408 (insert line "\n"))))
24410 (normal-mode)
24412 ;; insert the table of contents
24413 (when thetoc
24414 (goto-char (point-min))
24415 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
24416 (progn
24417 (goto-char (match-beginning 0))
24418 (replace-match ""))
24419 (goto-char first-heading-pos))
24420 (mapc 'insert thetoc)
24421 (or (looking-at "[ \t]*\n[ \t]*\n")
24422 (insert "\n\n")))
24424 ;; Convert whitespace place holders
24425 (goto-char (point-min))
24426 (let (beg end)
24427 (while (setq beg (next-single-property-change (point) 'org-whitespace))
24428 (setq end (next-single-property-change beg 'org-whitespace))
24429 (goto-char beg)
24430 (delete-region beg end)
24431 (insert (make-string (- end beg) ?\ ))))
24433 (save-buffer)
24434 ;; remove display and invisible chars
24435 (let (beg end)
24436 (goto-char (point-min))
24437 (while (setq beg (next-single-property-change (point) 'display))
24438 (setq end (next-single-property-change beg 'display))
24439 (delete-region beg end)
24440 (goto-char beg)
24441 (insert "=>"))
24442 (goto-char (point-min))
24443 (while (setq beg (next-single-property-change (point) 'org-cwidth))
24444 (setq end (next-single-property-change beg 'org-cwidth))
24445 (delete-region beg end)
24446 (goto-char beg)))
24447 (goto-char (point-min))))
24449 (defun org-export-ascii-clean-string ()
24450 "Do extra work for ASCII export"
24451 (goto-char (point-min))
24452 (while (re-search-forward org-verbatim-re nil t)
24453 (goto-char (match-end 2))
24454 (backward-delete-char 1) (insert "'")
24455 (goto-char (match-beginning 2))
24456 (delete-char 1) (insert "`")
24457 (goto-char (match-end 2))))
24459 (defun org-search-todo-below (line lines level)
24460 "Search the subtree below LINE for any TODO entries."
24461 (let ((rest (cdr (memq line lines)))
24462 (re org-todo-line-regexp)
24463 line lv todo)
24464 (catch 'exit
24465 (while (setq line (pop rest))
24466 (if (string-match re line)
24467 (progn
24468 (setq lv (- (match-end 1) (match-beginning 1))
24469 todo (and (match-beginning 2)
24470 (not (member (match-string 2 line)
24471 org-done-keywords))))
24472 ; TODO, not DONE
24473 (if (<= lv level) (throw 'exit nil))
24474 (if todo (throw 'exit t))))))))
24476 (defun org-html-expand-for-ascii (line)
24477 "Handle quoted HTML for ASCII export."
24478 (if org-export-html-expand
24479 (while (string-match "@<[^<>\n]*>" line)
24480 ;; We just remove the tags for now.
24481 (setq line (replace-match "" nil nil line))))
24482 line)
24484 (defun org-insert-centered (s &optional underline)
24485 "Insert the string S centered and underline it with character UNDERLINE."
24486 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
24487 (insert (make-string ind ?\ ) s "\n")
24488 (if underline
24489 (insert (make-string ind ?\ )
24490 (make-string (string-width s) underline)
24491 "\n"))))
24493 (defun org-ascii-level-start (level title umax &optional lines)
24494 "Insert a new level in ASCII export."
24495 (let (char (n (- level umax 1)) (ind 0))
24496 (if (> level umax)
24497 (progn
24498 (insert (make-string (* 2 n) ?\ )
24499 (char-to-string (nth (% n (length org-export-ascii-bullets))
24500 org-export-ascii-bullets))
24501 " " title "\n")
24502 ;; find the indentation of the next non-empty line
24503 (catch 'stop
24504 (while lines
24505 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
24506 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
24507 (throw 'stop (setq ind (org-get-indentation (car lines)))))
24508 (pop lines)))
24509 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
24510 (if (or (not (equal (char-before) ?\n))
24511 (not (equal (char-before (1- (point))) ?\n)))
24512 (insert "\n"))
24513 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
24514 (unless org-export-with-tags
24515 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
24516 (setq title (replace-match "" t t title))))
24517 (if org-export-with-section-numbers
24518 (setq title (concat (org-section-number level) " " title)))
24519 (insert title "\n" (make-string (string-width title) char) "\n")
24520 (setq org-ascii-current-indentation '(0 . 0)))))
24522 (defun org-export-visible (type arg)
24523 "Create a copy of the visible part of the current buffer, and export it.
24524 The copy is created in a temporary buffer and removed after use.
24525 TYPE is the final key (as a string) that also select the export command in
24526 the `C-c C-e' export dispatcher.
24527 As a special case, if the you type SPC at the prompt, the temporary
24528 org-mode file will not be removed but presented to you so that you can
24529 continue to use it. The prefix arg ARG is passed through to the exporting
24530 command."
24531 (interactive
24532 (list (progn
24533 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
24534 (read-char-exclusive))
24535 current-prefix-arg))
24536 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
24537 (error "Invalid export key"))
24538 (let* ((binding (cdr (assoc type
24539 '((?a . org-export-as-ascii)
24540 (?\C-a . org-export-as-ascii)
24541 (?b . org-export-as-html-and-open)
24542 (?\C-b . org-export-as-html-and-open)
24543 (?h . org-export-as-html)
24544 (?H . org-export-as-html-to-buffer)
24545 (?R . org-export-region-as-html)
24546 (?x . org-export-as-xoxo)))))
24547 (keepp (equal type ?\ ))
24548 (file buffer-file-name)
24549 (buffer (get-buffer-create "*Org Export Visible*"))
24550 s e)
24551 ;; Need to hack the drawers here.
24552 (save-excursion
24553 (goto-char (point-min))
24554 (while (re-search-forward org-drawer-regexp nil t)
24555 (goto-char (match-beginning 1))
24556 (or (org-invisible-p) (org-flag-drawer nil))))
24557 (with-current-buffer buffer (erase-buffer))
24558 (save-excursion
24559 (setq s (goto-char (point-min)))
24560 (while (not (= (point) (point-max)))
24561 (goto-char (org-find-invisible))
24562 (append-to-buffer buffer s (point))
24563 (setq s (goto-char (org-find-visible))))
24564 (org-cycle-hide-drawers 'all)
24565 (goto-char (point-min))
24566 (unless keepp
24567 ;; Copy all comment lines to the end, to make sure #+ settings are
24568 ;; still available for the second export step. Kind of a hack, but
24569 ;; does do the trick.
24570 (if (looking-at "#[^\r\n]*")
24571 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
24572 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
24573 (append-to-buffer buffer (1+ (match-beginning 0))
24574 (min (point-max) (1+ (match-end 0))))))
24575 (set-buffer buffer)
24576 (let ((buffer-file-name file)
24577 (org-inhibit-startup t))
24578 (org-mode)
24579 (show-all)
24580 (unless keepp (funcall binding arg))))
24581 (if (not keepp)
24582 (kill-buffer buffer)
24583 (switch-to-buffer-other-window buffer)
24584 (goto-char (point-min)))))
24586 (defun org-find-visible ()
24587 (let ((s (point)))
24588 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24589 (get-char-property s 'invisible)))
24591 (defun org-find-invisible ()
24592 (let ((s (point)))
24593 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24594 (not (get-char-property s 'invisible))))
24597 ;;; HTML export
24599 (defun org-get-current-options ()
24600 "Return a string with current options as keyword options.
24601 Does include HTML export options as well as TODO and CATEGORY stuff."
24602 (format
24603 "#+TITLE: %s
24604 #+AUTHOR: %s
24605 #+EMAIL: %s
24606 #+LANGUAGE: %s
24607 #+TEXT: Some descriptive text to be emitted. Several lines OK.
24608 #+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
24609 #+CATEGORY: %s
24610 #+SEQ_TODO: %s
24611 #+TYP_TODO: %s
24612 #+PRIORITIES: %c %c %c
24613 #+DRAWERS: %s
24614 #+STARTUP: %s %s %s %s %s
24615 #+TAGS: %s
24616 #+ARCHIVE: %s
24617 #+LINK: %s
24619 (buffer-name) (user-full-name) user-mail-address org-export-default-language
24620 org-export-headline-levels
24621 org-export-with-section-numbers
24622 org-export-with-toc
24623 org-export-preserve-breaks
24624 org-export-html-expand
24625 org-export-with-fixed-width
24626 org-export-with-tables
24627 org-export-with-sub-superscripts
24628 org-export-with-special-strings
24629 org-export-with-footnotes
24630 org-export-with-emphasize
24631 org-export-with-TeX-macros
24632 org-export-with-LaTeX-fragments
24633 org-export-skip-text-before-1st-heading
24634 org-export-with-drawers
24635 org-export-with-tags
24636 (file-name-nondirectory buffer-file-name)
24637 "TODO FEEDBACK VERIFY DONE"
24638 "Me Jason Marie DONE"
24639 org-highest-priority org-lowest-priority org-default-priority
24640 (mapconcat 'identity org-drawers " ")
24641 (cdr (assoc org-startup-folded
24642 '((nil . "showall") (t . "overview") (content . "content"))))
24643 (if org-odd-levels-only "odd" "oddeven")
24644 (if org-hide-leading-stars "hidestars" "showstars")
24645 (if org-startup-align-all-tables "align" "noalign")
24646 (cond ((eq t org-log-done) "logdone")
24647 ((not org-log-done) "nologging")
24648 ((listp org-log-done)
24649 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
24650 org-log-done " ")))
24651 (or (mapconcat (lambda (x)
24652 (cond
24653 ((equal '(:startgroup) x) "{")
24654 ((equal '(:endgroup) x) "}")
24655 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
24656 (t (car x))))
24657 (or org-tag-alist (org-get-buffer-tags)) " ") "")
24658 org-archive-location
24659 "org file:~/org/%s.org"
24662 (defun org-insert-export-options-template ()
24663 "Insert into the buffer a template with information for exporting."
24664 (interactive)
24665 (if (not (bolp)) (newline))
24666 (let ((s (org-get-current-options)))
24667 (and (string-match "#\\+CATEGORY" s)
24668 (setq s (substring s 0 (match-beginning 0))))
24669 (insert s)))
24671 (defun org-toggle-fixed-width-section (arg)
24672 "Toggle the fixed-width export.
24673 If there is no active region, the QUOTE keyword at the current headline is
24674 inserted or removed. When present, it causes the text between this headline
24675 and the next to be exported as fixed-width text, and unmodified.
24676 If there is an active region, this command adds or removes a colon as the
24677 first character of this line. If the first character of a line is a colon,
24678 this line is also exported in fixed-width font."
24679 (interactive "P")
24680 (let* ((cc 0)
24681 (regionp (org-region-active-p))
24682 (beg (if regionp (region-beginning) (point)))
24683 (end (if regionp (region-end)))
24684 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
24685 (case-fold-search nil)
24686 (re "[ \t]*\\(:\\)")
24687 off)
24688 (if regionp
24689 (save-excursion
24690 (goto-char beg)
24691 (setq cc (current-column))
24692 (beginning-of-line 1)
24693 (setq off (looking-at re))
24694 (while (> nlines 0)
24695 (setq nlines (1- nlines))
24696 (beginning-of-line 1)
24697 (cond
24698 (arg
24699 (move-to-column cc t)
24700 (insert ":\n")
24701 (forward-line -1))
24702 ((and off (looking-at re))
24703 (replace-match "" t t nil 1))
24704 ((not off) (move-to-column cc t) (insert ":")))
24705 (forward-line 1)))
24706 (save-excursion
24707 (org-back-to-heading)
24708 (if (looking-at (concat outline-regexp
24709 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
24710 (replace-match "" t t nil 1)
24711 (if (looking-at outline-regexp)
24712 (progn
24713 (goto-char (match-end 0))
24714 (insert org-quote-string " "))))))))
24716 (defun org-export-as-html-and-open (arg)
24717 "Export the outline as HTML and immediately open it with a browser.
24718 If there is an active region, export only the region.
24719 The prefix ARG specifies how many levels of the outline should become
24720 headlines. The default is 3. Lower levels will become bulleted lists."
24721 (interactive "P")
24722 (org-export-as-html arg 'hidden)
24723 (org-open-file buffer-file-name))
24725 (defun org-export-as-html-batch ()
24726 "Call `org-export-as-html', may be used in batch processing as
24727 emacs --batch
24728 --load=$HOME/lib/emacs/org.el
24729 --eval \"(setq org-export-headline-levels 2)\"
24730 --visit=MyFile --funcall org-export-as-html-batch"
24731 (org-export-as-html org-export-headline-levels 'hidden))
24733 (defun org-export-as-html-to-buffer (arg)
24734 "Call `org-exort-as-html` with output to a temporary buffer.
24735 No file is created. The prefix ARG is passed through to `org-export-as-html'."
24736 (interactive "P")
24737 (org-export-as-html arg nil nil "*Org HTML Export*")
24738 (switch-to-buffer-other-window "*Org HTML Export*"))
24740 (defun org-replace-region-by-html (beg end)
24741 "Assume the current region has org-mode syntax, and convert it to HTML.
24742 This can be used in any buffer. For example, you could write an
24743 itemized list in org-mode syntax in an HTML buffer and then use this
24744 command to convert it."
24745 (interactive "r")
24746 (let (reg html buf pop-up-frames)
24747 (save-window-excursion
24748 (if (org-mode-p)
24749 (setq html (org-export-region-as-html
24750 beg end t 'string))
24751 (setq reg (buffer-substring beg end)
24752 buf (get-buffer-create "*Org tmp*"))
24753 (with-current-buffer buf
24754 (erase-buffer)
24755 (insert reg)
24756 (org-mode)
24757 (setq html (org-export-region-as-html
24758 (point-min) (point-max) t 'string)))
24759 (kill-buffer buf)))
24760 (delete-region beg end)
24761 (insert html)))
24763 (defun org-export-region-as-html (beg end &optional body-only buffer)
24764 "Convert region from BEG to END in org-mode buffer to HTML.
24765 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
24766 contents, and only produce the region of converted text, useful for
24767 cut-and-paste operations.
24768 If BUFFER is a buffer or a string, use/create that buffer as a target
24769 of the converted HTML. If BUFFER is the symbol `string', return the
24770 produced HTML as a string and leave not buffer behind. For example,
24771 a Lisp program could call this function in the following way:
24773 (setq html (org-export-region-as-html beg end t 'string))
24775 When called interactively, the output buffer is selected, and shown
24776 in a window. A non-interactive call will only retunr the buffer."
24777 (interactive "r\nP")
24778 (when (interactive-p)
24779 (setq buffer "*Org HTML Export*"))
24780 (let ((transient-mark-mode t) (zmacs-regions t)
24781 rtn)
24782 (goto-char end)
24783 (set-mark (point)) ;; to activate the region
24784 (goto-char beg)
24785 (setq rtn (org-export-as-html
24786 nil nil nil
24787 buffer body-only))
24788 (if (fboundp 'deactivate-mark) (deactivate-mark))
24789 (if (and (interactive-p) (bufferp rtn))
24790 (switch-to-buffer-other-window rtn)
24791 rtn)))
24793 (defvar html-table-tag nil) ; dynamically scoped into this.
24794 (defun org-export-as-html (arg &optional hidden ext-plist
24795 to-buffer body-only)
24796 "Export the outline as a pretty HTML file.
24797 If there is an active region, export only the region. The prefix
24798 ARG specifies how many levels of the outline should become
24799 headlines. The default is 3. Lower levels will become bulleted
24800 lists. When HIDDEN is non-nil, don't display the HTML buffer.
24801 EXT-PLIST is a property list with external parameters overriding
24802 org-mode's default settings, but still inferior to file-local
24803 settings. When TO-BUFFER is non-nil, create a buffer with that
24804 name and export to that buffer. If TO-BUFFER is the symbol `string',
24805 don't leave any buffer behind but just return the resulting HTML as
24806 a string. When BODY-ONLY is set, don't produce the file header and footer,
24807 simply return the content of <body>...</body>, without even
24808 the body tags themselves."
24809 (interactive "P")
24811 ;; Make sure we have a file name when we need it.
24812 (when (and (not (or to-buffer body-only))
24813 (not buffer-file-name))
24814 (if (buffer-base-buffer)
24815 (org-set-local 'buffer-file-name
24816 (with-current-buffer (buffer-base-buffer)
24817 buffer-file-name))
24818 (error "Need a file name to be able to export.")))
24820 (message "Exporting...")
24821 (setq-default org-todo-line-regexp org-todo-line-regexp)
24822 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
24823 (setq-default org-done-keywords org-done-keywords)
24824 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
24825 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24826 ext-plist
24827 (org-infile-export-plist)))
24829 (style (plist-get opt-plist :style))
24830 (link-validate (plist-get opt-plist :link-validation-function))
24831 valid thetoc have-headings first-heading-pos
24832 (odd org-odd-levels-only)
24833 (region-p (org-region-active-p))
24834 (subtree-p
24835 (when region-p
24836 (save-excursion
24837 (goto-char (region-beginning))
24838 (and (org-at-heading-p)
24839 (>= (org-end-of-subtree t t) (region-end))))))
24840 ;; The following two are dynamically scoped into other
24841 ;; routines below.
24842 (org-current-export-dir (org-export-directory :html opt-plist))
24843 (org-current-export-file buffer-file-name)
24844 (level 0) (line "") (origline "") txt todo
24845 (umax nil)
24846 (umax-toc nil)
24847 (filename (if to-buffer nil
24848 (expand-file-name
24849 (concat
24850 (file-name-sans-extension
24851 (or (and subtree-p
24852 (org-entry-get (region-beginning)
24853 "EXPORT_FILE_NAME" t))
24854 (file-name-nondirectory buffer-file-name)))
24855 "." org-export-html-extension)
24856 (file-name-as-directory
24857 (org-export-directory :html opt-plist)))))
24858 (current-dir (if buffer-file-name
24859 (file-name-directory buffer-file-name)
24860 default-directory))
24861 (buffer (if to-buffer
24862 (cond
24863 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
24864 (t (get-buffer-create to-buffer)))
24865 (find-file-noselect filename)))
24866 (org-levels-open (make-vector org-level-max nil))
24867 (date (plist-get opt-plist :date))
24868 (author (plist-get opt-plist :author))
24869 (title (or (and subtree-p (org-export-get-title-from-subtree))
24870 (plist-get opt-plist :title)
24871 (and (not
24872 (plist-get opt-plist :skip-before-1st-heading))
24873 (org-export-grab-title-from-buffer))
24874 (and buffer-file-name
24875 (file-name-sans-extension
24876 (file-name-nondirectory buffer-file-name)))
24877 "UNTITLED"))
24878 (html-table-tag (plist-get opt-plist :html-table-tag))
24879 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24880 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
24881 (inquote nil)
24882 (infixed nil)
24883 (in-local-list nil)
24884 (local-list-num nil)
24885 (local-list-indent nil)
24886 (llt org-plain-list-ordered-item-terminator)
24887 (email (plist-get opt-plist :email))
24888 (language (plist-get opt-plist :language))
24889 (lang-words nil)
24890 (target-alist nil) tg
24891 (head-count 0) cnt
24892 (start 0)
24893 (coding-system (and (boundp 'buffer-file-coding-system)
24894 buffer-file-coding-system))
24895 (coding-system-for-write (or org-export-html-coding-system
24896 coding-system))
24897 (save-buffer-coding-system (or org-export-html-coding-system
24898 coding-system))
24899 (charset (and coding-system-for-write
24900 (fboundp 'coding-system-get)
24901 (coding-system-get coding-system-for-write
24902 'mime-charset)))
24903 (region
24904 (buffer-substring
24905 (if region-p (region-beginning) (point-min))
24906 (if region-p (region-end) (point-max))))
24907 (lines
24908 (org-split-string
24909 (org-cleaned-string-for-export
24910 region
24911 :emph-multiline t
24912 :for-html t
24913 :skip-before-1st-heading
24914 (plist-get opt-plist :skip-before-1st-heading)
24915 :drawers (plist-get opt-plist :drawers)
24916 :archived-trees
24917 (plist-get opt-plist :archived-trees)
24918 :add-text
24919 (plist-get opt-plist :text)
24920 :LaTeX-fragments
24921 (plist-get opt-plist :LaTeX-fragments))
24922 "[\r\n]"))
24923 table-open type
24924 table-buffer table-orig-buffer
24925 ind start-is-num starter didclose
24926 rpl path desc descp desc1 desc2 link
24929 (let ((inhibit-read-only t))
24930 (org-unmodified
24931 (remove-text-properties (point-min) (point-max)
24932 '(:org-license-to-kill t))))
24934 (message "Exporting...")
24936 (setq org-min-level (org-get-min-level lines))
24937 (setq org-last-level org-min-level)
24938 (org-init-section-numbers)
24940 (cond
24941 ((and date (string-match "%" date))
24942 (setq date (format-time-string date (current-time))))
24943 (date)
24944 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24946 ;; Get the language-dependent settings
24947 (setq lang-words (or (assoc language org-export-language-setup)
24948 (assoc "en" org-export-language-setup)))
24950 ;; Switch to the output buffer
24951 (set-buffer buffer)
24952 (let ((inhibit-read-only t)) (erase-buffer))
24953 (fundamental-mode)
24955 (and (fboundp 'set-buffer-file-coding-system)
24956 (set-buffer-file-coding-system coding-system-for-write))
24958 (let ((case-fold-search nil)
24959 (org-odd-levels-only odd))
24960 ;; create local variables for all options, to make sure all called
24961 ;; functions get the correct information
24962 (mapc (lambda (x)
24963 (set (make-local-variable (cdr x))
24964 (plist-get opt-plist (car x))))
24965 org-export-plist-vars)
24966 (setq umax (if arg (prefix-numeric-value arg)
24967 org-export-headline-levels))
24968 (setq umax-toc (if (integerp org-export-with-toc)
24969 (min org-export-with-toc umax)
24970 umax))
24971 (unless body-only
24972 ;; File header
24973 (insert (format
24974 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
24975 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
24976 <html xmlns=\"http://www.w3.org/1999/xhtml\"
24977 lang=\"%s\" xml:lang=\"%s\">
24978 <head>
24979 <title>%s</title>
24980 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
24981 <meta name=\"generator\" content=\"Org-mode\"/>
24982 <meta name=\"generated\" content=\"%s\"/>
24983 <meta name=\"author\" content=\"%s\"/>
24985 </head><body>
24987 language language (org-html-expand title)
24988 (or charset "iso-8859-1") date author style))
24990 (insert (or (plist-get opt-plist :preamble) ""))
24992 (when (plist-get opt-plist :auto-preamble)
24993 (if title (insert (format org-export-html-title-format
24994 (org-html-expand title))))))
24996 (if (and org-export-with-toc (not body-only))
24997 (progn
24998 (push (format "<h%d>%s</h%d>\n"
24999 org-export-html-toplevel-hlevel
25000 (nth 3 lang-words)
25001 org-export-html-toplevel-hlevel)
25002 thetoc)
25003 (push "<ul>\n<li>" thetoc)
25004 (setq lines
25005 (mapcar '(lambda (line)
25006 (if (string-match org-todo-line-regexp line)
25007 ;; This is a headline
25008 (progn
25009 (setq have-headings t)
25010 (setq level (- (match-end 1) (match-beginning 1))
25011 level (org-tr-level level)
25012 txt (save-match-data
25013 (org-html-expand
25014 (org-export-cleanup-toc-line
25015 (match-string 3 line))))
25016 todo
25017 (or (and org-export-mark-todo-in-toc
25018 (match-beginning 2)
25019 (not (member (match-string 2 line)
25020 org-done-keywords)))
25021 ; TODO, not DONE
25022 (and org-export-mark-todo-in-toc
25023 (= level umax-toc)
25024 (org-search-todo-below
25025 line lines level))))
25026 (if (string-match
25027 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
25028 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
25029 (if (string-match quote-re0 txt)
25030 (setq txt (replace-match "" t t txt)))
25031 (if org-export-with-section-numbers
25032 (setq txt (concat (org-section-number level)
25033 " " txt)))
25034 (if (<= level (max umax umax-toc))
25035 (setq head-count (+ head-count 1)))
25036 (if (<= level umax-toc)
25037 (progn
25038 (if (> level org-last-level)
25039 (progn
25040 (setq cnt (- level org-last-level))
25041 (while (>= (setq cnt (1- cnt)) 0)
25042 (push "\n<ul>\n<li>" thetoc))
25043 (push "\n" thetoc)))
25044 (if (< level org-last-level)
25045 (progn
25046 (setq cnt (- org-last-level level))
25047 (while (>= (setq cnt (1- cnt)) 0)
25048 (push "</li>\n</ul>" thetoc))
25049 (push "\n" thetoc)))
25050 ;; Check for targets
25051 (while (string-match org-target-regexp line)
25052 (setq tg (match-string 1 line)
25053 line (replace-match
25054 (concat "@<span class=\"target\">" tg "@</span> ")
25055 t t line))
25056 (push (cons (org-solidify-link-text tg)
25057 (format "sec-%d" head-count))
25058 target-alist))
25059 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
25060 (setq txt (replace-match "" t t txt)))
25061 (push
25062 (format
25063 (if todo
25064 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
25065 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
25066 head-count txt) thetoc)
25068 (setq org-last-level level))
25070 line)
25071 lines))
25072 (while (> org-last-level (1- org-min-level))
25073 (setq org-last-level (1- org-last-level))
25074 (push "</li>\n</ul>\n" thetoc))
25075 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25077 (setq head-count 0)
25078 (org-init-section-numbers)
25080 (while (setq line (pop lines) origline line)
25081 (catch 'nextline
25083 ;; end of quote section?
25084 (when (and inquote (string-match "^\\*+ " line))
25085 (insert "</pre>\n")
25086 (setq inquote nil))
25087 ;; inside a quote section?
25088 (when inquote
25089 (insert (org-html-protect line) "\n")
25090 (throw 'nextline nil))
25092 ;; verbatim lines
25093 (when (and org-export-with-fixed-width
25094 (string-match "^[ \t]*:\\(.*\\)" line))
25095 (when (not infixed)
25096 (setq infixed t)
25097 (insert "<pre>\n"))
25098 (insert (org-html-protect (match-string 1 line)) "\n")
25099 (when (and lines
25100 (not (string-match "^[ \t]*\\(:.*\\)"
25101 (car lines))))
25102 (setq infixed nil)
25103 (insert "</pre>\n"))
25104 (throw 'nextline nil))
25106 ;; Protected HTML
25107 (when (get-text-property 0 'org-protected line)
25108 (let (par)
25109 (when (re-search-backward
25110 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
25111 (setq par (match-string 1))
25112 (replace-match "\\2\n"))
25113 (insert line "\n")
25114 (while (and lines
25115 (or (= (length (car lines)) 0)
25116 (get-text-property 0 'org-protected (car lines))))
25117 (insert (pop lines) "\n"))
25118 (and par (insert "<p>\n")))
25119 (throw 'nextline nil))
25121 ;; Horizontal line
25122 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
25123 (insert "\n<hr/>\n")
25124 (throw 'nextline nil))
25126 ;; make targets to anchors
25127 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
25128 (cond
25129 ((match-end 2)
25130 (setq line (replace-match
25131 (concat "@<a name=\""
25132 (org-solidify-link-text (match-string 1 line))
25133 "\">\\nbsp@</a>")
25134 t t line)))
25135 ((and org-export-with-toc (equal (string-to-char line) ?*))
25136 (setq line (replace-match
25137 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
25138 ; (concat "@<i>" (match-string 1 line) "@</i> ")
25139 t t line)))
25141 (setq line (replace-match
25142 (concat "@<a name=\""
25143 (org-solidify-link-text (match-string 1 line))
25144 "\" class=\"target\">" (match-string 1 line) "@</a> ")
25145 t t line)))))
25147 (setq line (org-html-handle-time-stamps line))
25149 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
25150 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
25151 ;; Also handle sub_superscripts and checkboxes
25152 (or (string-match org-table-hline-regexp line)
25153 (setq line (org-html-expand line)))
25155 ;; Format the links
25156 (setq start 0)
25157 (while (string-match org-bracket-link-analytic-regexp line start)
25158 (setq start (match-beginning 0))
25159 (setq type (if (match-end 2) (match-string 2 line) "internal"))
25160 (setq path (match-string 3 line))
25161 (setq desc1 (if (match-end 5) (match-string 5 line))
25162 desc2 (if (match-end 2) (concat type ":" path) path)
25163 descp (and desc1 (not (equal desc1 desc2)))
25164 desc (or desc1 desc2))
25165 ;; Make an image out of the description if that is so wanted
25166 (when (and descp (org-file-image-p desc))
25167 (save-match-data
25168 (if (string-match "^file:" desc)
25169 (setq desc (substring desc (match-end 0)))))
25170 (setq desc (concat "<img src=\"" desc "\"/>")))
25171 ;; FIXME: do we need to unescape here somewhere?
25172 (cond
25173 ((equal type "internal")
25174 (setq rpl
25175 (concat
25176 "<a href=\"#"
25177 (org-solidify-link-text
25178 (save-match-data (org-link-unescape path)) target-alist)
25179 "\">" desc "</a>")))
25180 ((member type '("http" "https"))
25181 ;; standard URL, just check if we need to inline an image
25182 (if (and (or (eq t org-export-html-inline-images)
25183 (and org-export-html-inline-images (not descp)))
25184 (org-file-image-p path))
25185 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
25186 (setq link (concat type ":" path))
25187 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
25188 ((member type '("ftp" "mailto" "news"))
25189 ;; standard URL
25190 (setq link (concat type ":" path))
25191 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
25192 ((string= type "file")
25193 ;; FILE link
25194 (let* ((filename path)
25195 (abs-p (file-name-absolute-p filename))
25196 thefile file-is-image-p search)
25197 (save-match-data
25198 (if (string-match "::\\(.*\\)" filename)
25199 (setq search (match-string 1 filename)
25200 filename (replace-match "" t nil filename)))
25201 (setq valid
25202 (if (functionp link-validate)
25203 (funcall link-validate filename current-dir)
25205 (setq file-is-image-p (org-file-image-p filename))
25206 (setq thefile (if abs-p (expand-file-name filename) filename))
25207 (when (and org-export-html-link-org-files-as-html
25208 (string-match "\\.org$" thefile))
25209 (setq thefile (concat (substring thefile 0
25210 (match-beginning 0))
25211 "." org-export-html-extension))
25212 (if (and search
25213 ;; make sure this is can be used as target search
25214 (not (string-match "^[0-9]*$" search))
25215 (not (string-match "^\\*" search))
25216 (not (string-match "^/.*/$" search)))
25217 (setq thefile (concat thefile "#"
25218 (org-solidify-link-text
25219 (org-link-unescape search)))))
25220 (when (string-match "^file:" desc)
25221 (setq desc (replace-match "" t t desc))
25222 (if (string-match "\\.org$" desc)
25223 (setq desc (replace-match "" t t desc))))))
25224 (setq rpl (if (and file-is-image-p
25225 (or (eq t org-export-html-inline-images)
25226 (and org-export-html-inline-images
25227 (not descp))))
25228 (concat "<img src=\"" thefile "\"/>")
25229 (concat "<a href=\"" thefile "\">" desc "</a>")))
25230 (if (not valid) (setq rpl desc))))
25231 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
25232 (setq rpl (concat "<i>&lt;" type ":"
25233 (save-match-data (org-link-unescape path))
25234 "&gt;</i>"))))
25235 (setq line (replace-match rpl t t line)
25236 start (+ start (length rpl))))
25238 ;; TODO items
25239 (if (and (string-match org-todo-line-regexp line)
25240 (match-beginning 2))
25242 (setq line
25243 (concat (substring line 0 (match-beginning 2))
25244 "<span class=\""
25245 (if (member (match-string 2 line)
25246 org-done-keywords)
25247 "done" "todo")
25248 "\">" (match-string 2 line)
25249 "</span>" (substring line (match-end 2)))))
25251 ;; Does this contain a reference to a footnote?
25252 (when org-export-with-footnotes
25253 (setq start 0)
25254 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
25255 (if (get-text-property (match-beginning 2) 'org-protected line)
25256 (setq start (match-end 2))
25257 (let ((n (match-string 2 line)))
25258 (setq line
25259 (replace-match
25260 (format
25261 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
25262 (match-string 1 line) n n n)
25263 t t line))))))
25265 (cond
25266 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25267 ;; This is a headline
25268 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25269 txt (match-string 2 line))
25270 (if (string-match quote-re0 txt)
25271 (setq txt (replace-match "" t t txt)))
25272 (if (<= level (max umax umax-toc))
25273 (setq head-count (+ head-count 1)))
25274 (when in-local-list
25275 ;; Close any local lists before inserting a new header line
25276 (while local-list-num
25277 (org-close-li)
25278 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25279 (pop local-list-num))
25280 (setq local-list-indent nil
25281 in-local-list nil))
25282 (setq first-heading-pos (or first-heading-pos (point)))
25283 (org-html-level-start level txt umax
25284 (and org-export-with-toc (<= level umax))
25285 head-count)
25286 ;; QUOTES
25287 (when (string-match quote-re line)
25288 (insert "<pre>")
25289 (setq inquote t)))
25291 ((and org-export-with-tables
25292 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25293 (if (not table-open)
25294 ;; New table starts
25295 (setq table-open t table-buffer nil table-orig-buffer nil))
25296 ;; Accumulate lines
25297 (setq table-buffer (cons line table-buffer)
25298 table-orig-buffer (cons origline table-orig-buffer))
25299 (when (or (not lines)
25300 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25301 (car lines))))
25302 (setq table-open nil
25303 table-buffer (nreverse table-buffer)
25304 table-orig-buffer (nreverse table-orig-buffer))
25305 (org-close-par-maybe)
25306 (insert (org-format-table-html table-buffer table-orig-buffer))))
25308 ;; Normal lines
25309 (when (string-match
25310 (cond
25311 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25312 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25313 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25314 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
25315 line)
25316 (setq ind (org-get-string-indentation line)
25317 start-is-num (match-beginning 4)
25318 starter (if (match-beginning 2)
25319 (substring (match-string 2 line) 0 -1))
25320 line (substring line (match-beginning 5)))
25321 (unless (string-match "[^ \t]" line)
25322 ;; empty line. Pretend indentation is large.
25323 (setq ind (if org-empty-line-terminates-plain-lists
25325 (1+ (or (car local-list-indent) 1)))))
25326 (setq didclose nil)
25327 (while (and in-local-list
25328 (or (and (= ind (car local-list-indent))
25329 (not starter))
25330 (< ind (car local-list-indent))))
25331 (setq didclose t)
25332 (org-close-li)
25333 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25334 (pop local-list-num) (pop local-list-indent)
25335 (setq in-local-list local-list-indent))
25336 (cond
25337 ((and starter
25338 (or (not in-local-list)
25339 (> ind (car local-list-indent))))
25340 ;; Start new (level of) list
25341 (org-close-par-maybe)
25342 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
25343 (push start-is-num local-list-num)
25344 (push ind local-list-indent)
25345 (setq in-local-list t))
25346 (starter
25347 ;; continue current list
25348 (org-close-li)
25349 (insert "<li>\n"))
25350 (didclose
25351 ;; we did close a list, normal text follows: need <p>
25352 (org-open-par)))
25353 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
25354 (setq line
25355 (replace-match
25356 (if (equal (match-string 1 line) "X")
25357 "<b>[X]</b>"
25358 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
25359 t t line))))
25361 ;; Empty lines start a new paragraph. If hand-formatted lists
25362 ;; are not fully interpreted, lines starting with "-", "+", "*"
25363 ;; also start a new paragraph.
25364 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
25366 ;; Is this the start of a footnote?
25367 (when org-export-with-footnotes
25368 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
25369 (org-close-par-maybe)
25370 (let ((n (match-string 1 line)))
25371 (setq line (replace-match
25372 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
25374 ;; Check if the line break needs to be conserved
25375 (cond
25376 ((string-match "\\\\\\\\[ \t]*$" line)
25377 (setq line (replace-match "<br/>" t t line)))
25378 (org-export-preserve-breaks
25379 (setq line (concat line "<br/>"))))
25381 (insert line "\n")))))
25383 ;; Properly close all local lists and other lists
25384 (when inquote (insert "</pre>\n"))
25385 (when in-local-list
25386 ;; Close any local lists before inserting a new header line
25387 (while local-list-num
25388 (org-close-li)
25389 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
25390 (pop local-list-num))
25391 (setq local-list-indent nil
25392 in-local-list nil))
25393 (org-html-level-start 1 nil umax
25394 (and org-export-with-toc (<= level umax))
25395 head-count)
25397 (unless body-only
25398 (when (plist-get opt-plist :auto-postamble)
25399 (insert "<div id=\"postamble\">")
25400 (when (and org-export-author-info author)
25401 (insert "<p class=\"author\"> "
25402 (nth 1 lang-words) ": " author "\n")
25403 (when email
25404 (if (listp (split-string email ",+ *"))
25405 (mapc (lambda(e)
25406 (insert "<a href=\"mailto:" e "\">&lt;"
25407 e "&gt;</a>\n"))
25408 (split-string email ",+ *"))
25409 (insert "<a href=\"mailto:" email "\">&lt;"
25410 email "&gt;</a>\n")))
25411 (insert "</p>\n"))
25412 (when (and date org-export-time-stamp-file)
25413 (insert "<p class=\"date\"> "
25414 (nth 2 lang-words) ": "
25415 date "</p>\n"))
25416 (insert "</div>"))
25418 (if org-export-html-with-timestamp
25419 (insert org-export-html-html-helper-timestamp))
25420 (insert (or (plist-get opt-plist :postamble) ""))
25421 (insert "</body>\n</html>\n"))
25423 (normal-mode)
25424 (if (eq major-mode default-major-mode) (html-mode))
25426 ;; insert the table of contents
25427 (goto-char (point-min))
25428 (when thetoc
25429 (if (or (re-search-forward
25430 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
25431 (re-search-forward
25432 "\\[TABLE-OF-CONTENTS\\]" nil t))
25433 (progn
25434 (goto-char (match-beginning 0))
25435 (replace-match ""))
25436 (goto-char first-heading-pos)
25437 (when (looking-at "\\s-*</p>")
25438 (goto-char (match-end 0))
25439 (insert "\n")))
25440 (insert "<div id=\"table-of-contents\">\n")
25441 (mapc 'insert thetoc)
25442 (insert "</div>\n"))
25443 ;; remove empty paragraphs and lists
25444 (goto-char (point-min))
25445 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
25446 (replace-match ""))
25447 (goto-char (point-min))
25448 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
25449 (replace-match ""))
25450 ;; Convert whitespace place holders
25451 (goto-char (point-min))
25452 (let (beg end n)
25453 (while (setq beg (next-single-property-change (point) 'org-whitespace))
25454 (setq n (get-text-property beg 'org-whitespace)
25455 end (next-single-property-change beg 'org-whitespace))
25456 (goto-char beg)
25457 (delete-region beg end)
25458 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
25459 (make-string n ?x)))))
25461 (or to-buffer (save-buffer))
25462 (goto-char (point-min))
25463 (message "Exporting... done")
25464 (if (eq to-buffer 'string)
25465 (prog1 (buffer-substring (point-min) (point-max))
25466 (kill-buffer (current-buffer)))
25467 (current-buffer)))))
25469 (defvar org-table-colgroup-info nil)
25470 (defun org-format-table-ascii (lines)
25471 "Format a table for ascii export."
25472 (if (stringp lines)
25473 (setq lines (org-split-string lines "\n")))
25474 (if (not (string-match "^[ \t]*|" (car lines)))
25475 ;; Table made by table.el - test for spanning
25476 lines
25478 ;; A normal org table
25479 ;; Get rid of hlines at beginning and end
25480 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25481 (setq lines (nreverse lines))
25482 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25483 (setq lines (nreverse lines))
25484 (when org-export-table-remove-special-lines
25485 ;; Check if the table has a marking column. If yes remove the
25486 ;; column and the special lines
25487 (setq lines (org-table-clean-before-export lines)))
25488 ;; Get rid of the vertical lines except for grouping
25489 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
25490 rtn line vl1 start)
25491 (while (setq line (pop lines))
25492 (if (string-match org-table-hline-regexp line)
25493 (and (string-match "|\\(.*\\)|" line)
25494 (setq line (replace-match " \\1" t nil line)))
25495 (setq start 0 vl1 vl)
25496 (while (string-match "|" line start)
25497 (setq start (match-end 0))
25498 (or (pop vl1) (setq line (replace-match " " t t line)))))
25499 (push line rtn))
25500 (nreverse rtn))))
25502 (defun org-colgroup-info-to-vline-list (info)
25503 (let (vl new last)
25504 (while info
25505 (setq last new new (pop info))
25506 (if (or (memq last '(:end :startend))
25507 (memq new '(:start :startend)))
25508 (push t vl)
25509 (push nil vl)))
25510 (setq vl (nreverse vl))
25511 (and vl (setcar vl nil))
25512 vl))
25514 (defun org-format-table-html (lines olines)
25515 "Find out which HTML converter to use and return the HTML code."
25516 (if (stringp lines)
25517 (setq lines (org-split-string lines "\n")))
25518 (if (string-match "^[ \t]*|" (car lines))
25519 ;; A normal org table
25520 (org-format-org-table-html lines)
25521 ;; Table made by table.el - test for spanning
25522 (let* ((hlines (delq nil (mapcar
25523 (lambda (x)
25524 (if (string-match "^[ \t]*\\+-" x) x
25525 nil))
25526 lines)))
25527 (first (car hlines))
25528 (ll (and (string-match "\\S-+" first)
25529 (match-string 0 first)))
25530 (re (concat "^[ \t]*" (regexp-quote ll)))
25531 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
25532 hlines))))
25533 (if (and (not spanning)
25534 (not org-export-prefer-native-exporter-for-tables))
25535 ;; We can use my own converter with HTML conversions
25536 (org-format-table-table-html lines)
25537 ;; Need to use the code generator in table.el, with the original text.
25538 (org-format-table-table-html-using-table-generate-source olines)))))
25540 (defun org-format-org-table-html (lines &optional splice)
25541 "Format a table into HTML."
25542 ;; Get rid of hlines at beginning and end
25543 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25544 (setq lines (nreverse lines))
25545 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25546 (setq lines (nreverse lines))
25547 (when org-export-table-remove-special-lines
25548 ;; Check if the table has a marking column. If yes remove the
25549 ;; column and the special lines
25550 (setq lines (org-table-clean-before-export lines)))
25552 (let ((head (and org-export-highlight-first-table-line
25553 (delq nil (mapcar
25554 (lambda (x) (string-match "^[ \t]*|-" x))
25555 (cdr lines)))))
25556 (nlines 0) fnum i
25557 tbopen line fields html gr colgropen)
25558 (if splice (setq head nil))
25559 (unless splice (push (if head "<thead>" "<tbody>") html))
25560 (setq tbopen t)
25561 (while (setq line (pop lines))
25562 (catch 'next-line
25563 (if (string-match "^[ \t]*|-" line)
25564 (progn
25565 (unless splice
25566 (push (if head "</thead>" "</tbody>") html)
25567 (if lines (push "<tbody>" html) (setq tbopen nil)))
25568 (setq head nil) ;; head ends here, first time around
25569 ;; ignore this line
25570 (throw 'next-line t)))
25571 ;; Break the line into fields
25572 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25573 (unless fnum (setq fnum (make-vector (length fields) 0)))
25574 (setq nlines (1+ nlines) i -1)
25575 (push (concat "<tr>"
25576 (mapconcat
25577 (lambda (x)
25578 (setq i (1+ i))
25579 (if (and (< i nlines)
25580 (string-match org-table-number-regexp x))
25581 (incf (aref fnum i)))
25582 (if head
25583 (concat (car org-export-table-header-tags) x
25584 (cdr org-export-table-header-tags))
25585 (concat (car org-export-table-data-tags) x
25586 (cdr org-export-table-data-tags))))
25587 fields "")
25588 "</tr>")
25589 html)))
25590 (unless splice (if tbopen (push "</tbody>" html)))
25591 (unless splice (push "</table>\n" html))
25592 (setq html (nreverse html))
25593 (unless splice
25594 ;; Put in col tags with the alignment (unfortuntely often ignored...)
25595 (push (mapconcat
25596 (lambda (x)
25597 (setq gr (pop org-table-colgroup-info))
25598 (format "%s<col align=\"%s\"></col>%s"
25599 (if (memq gr '(:start :startend))
25600 (prog1
25601 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
25602 (setq colgropen t))
25604 (if (> (/ (float x) nlines) org-table-number-fraction)
25605 "right" "left")
25606 (if (memq gr '(:end :startend))
25607 (progn (setq colgropen nil) "</colgroup>")
25608 "")))
25609 fnum "")
25610 html)
25611 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
25612 (push html-table-tag html))
25613 (concat (mapconcat 'identity html "\n") "\n")))
25615 (defun org-table-clean-before-export (lines)
25616 "Check if the table has a marking column.
25617 If yes remove the column and the special lines."
25618 (setq org-table-colgroup-info nil)
25619 (if (memq nil
25620 (mapcar
25621 (lambda (x) (or (string-match "^[ \t]*|-" x)
25622 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
25623 lines))
25624 (progn
25625 (setq org-table-clean-did-remove-column nil)
25626 (delq nil
25627 (mapcar
25628 (lambda (x)
25629 (cond
25630 ((string-match "^[ \t]*| */ *|" x)
25631 (setq org-table-colgroup-info
25632 (mapcar (lambda (x)
25633 (cond ((member x '("<" "&lt;")) :start)
25634 ((member x '(">" "&gt;")) :end)
25635 ((member x '("<>" "&lt;&gt;")) :startend)
25636 (t nil)))
25637 (org-split-string x "[ \t]*|[ \t]*")))
25638 nil)
25639 (t x)))
25640 lines)))
25641 (setq org-table-clean-did-remove-column t)
25642 (delq nil
25643 (mapcar
25644 (lambda (x)
25645 (cond
25646 ((string-match "^[ \t]*| */ *|" x)
25647 (setq org-table-colgroup-info
25648 (mapcar (lambda (x)
25649 (cond ((member x '("<" "&lt;")) :start)
25650 ((member x '(">" "&gt;")) :end)
25651 ((member x '("<>" "&lt;&gt;")) :startend)
25652 (t nil)))
25653 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
25654 nil)
25655 ((string-match "^[ \t]*| *[!_^/] *|" x)
25656 nil) ; ignore this line
25657 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
25658 (string-match "^\\([ \t]*\\)|[^|]*|" x))
25659 ;; remove the first column
25660 (replace-match "\\1|" t nil x))))
25661 lines))))
25663 (defun org-format-table-table-html (lines)
25664 "Format a table generated by table.el into HTML.
25665 This conversion does *not* use `table-generate-source' from table.el.
25666 This has the advantage that Org-mode's HTML conversions can be used.
25667 But it has the disadvantage, that no cell- or row-spanning is allowed."
25668 (let (line field-buffer
25669 (head org-export-highlight-first-table-line)
25670 fields html empty)
25671 (setq html (concat html-table-tag "\n"))
25672 (while (setq line (pop lines))
25673 (setq empty "&nbsp;")
25674 (catch 'next-line
25675 (if (string-match "^[ \t]*\\+-" line)
25676 (progn
25677 (if field-buffer
25678 (progn
25679 (setq
25680 html
25681 (concat
25682 html
25683 "<tr>"
25684 (mapconcat
25685 (lambda (x)
25686 (if (equal x "") (setq x empty))
25687 (if head
25688 (concat (car org-export-table-header-tags) x
25689 (cdr org-export-table-header-tags))
25690 (concat (car org-export-table-data-tags) x
25691 (cdr org-export-table-data-tags))))
25692 field-buffer "\n")
25693 "</tr>\n"))
25694 (setq head nil)
25695 (setq field-buffer nil)))
25696 ;; Ignore this line
25697 (throw 'next-line t)))
25698 ;; Break the line into fields and store the fields
25699 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25700 (if field-buffer
25701 (setq field-buffer (mapcar
25702 (lambda (x)
25703 (concat x "<br/>" (pop fields)))
25704 field-buffer))
25705 (setq field-buffer fields))))
25706 (setq html (concat html "</table>\n"))
25707 html))
25709 (defun org-format-table-table-html-using-table-generate-source (lines)
25710 "Format a table into html, using `table-generate-source' from table.el.
25711 This has the advantage that cell- or row-spanning is allowed.
25712 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
25713 (require 'table)
25714 (with-current-buffer (get-buffer-create " org-tmp1 ")
25715 (erase-buffer)
25716 (insert (mapconcat 'identity lines "\n"))
25717 (goto-char (point-min))
25718 (if (not (re-search-forward "|[^+]" nil t))
25719 (error "Error processing table"))
25720 (table-recognize-table)
25721 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
25722 (table-generate-source 'html " org-tmp2 ")
25723 (set-buffer " org-tmp2 ")
25724 (buffer-substring (point-min) (point-max))))
25726 (defun org-html-handle-time-stamps (s)
25727 "Format time stamps in string S, or remove them."
25728 (catch 'exit
25729 (let (r b)
25730 (while (string-match org-maybe-keyword-time-regexp s)
25731 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
25732 ;; never export CLOCK
25733 (throw 'exit ""))
25734 (or b (setq b (substring s 0 (match-beginning 0))))
25735 (if (not org-export-with-timestamps)
25736 (setq r (concat r (substring s 0 (match-beginning 0)))
25737 s (substring s (match-end 0)))
25738 (setq r (concat
25739 r (substring s 0 (match-beginning 0))
25740 (if (match-end 1)
25741 (format "@<span class=\"timestamp-kwd\">%s @</span>"
25742 (match-string 1 s)))
25743 (format " @<span class=\"timestamp\">%s@</span>"
25744 (substring
25745 (org-translate-time (match-string 3 s)) 1 -1)))
25746 s (substring s (match-end 0)))))
25747 ;; Line break if line started and ended with time stamp stuff
25748 (if (not r)
25750 (setq r (concat r s))
25751 (unless (string-match "\\S-" (concat b s))
25752 (setq r (concat r "@<br/>")))
25753 r))))
25755 (defun org-html-protect (s)
25756 ;; convert & to &amp;, < to &lt; and > to &gt;
25757 (let ((start 0))
25758 (while (string-match "&" s start)
25759 (setq s (replace-match "&amp;" t t s)
25760 start (1+ (match-beginning 0))))
25761 (while (string-match "<" s)
25762 (setq s (replace-match "&lt;" t t s)))
25763 (while (string-match ">" s)
25764 (setq s (replace-match "&gt;" t t s))))
25767 (defun org-export-cleanup-toc-line (s)
25768 "Remove tags and time staps from lines going into the toc."
25769 (when (memq org-export-with-tags '(not-in-toc nil))
25770 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
25771 (setq s (replace-match "" t t s))))
25772 (when org-export-remove-timestamps-from-toc
25773 (while (string-match org-maybe-keyword-time-regexp s)
25774 (setq s (replace-match "" t t s))))
25775 (while (string-match org-bracket-link-regexp s)
25776 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
25777 t t s)))
25780 (defun org-html-expand (string)
25781 "Prepare STRING for HTML export. Applies all active conversions.
25782 If there are links in the string, don't modify these."
25783 (let* ((re (concat org-bracket-link-regexp "\\|"
25784 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
25785 m s l res)
25786 (while (setq m (string-match re string))
25787 (setq s (substring string 0 m)
25788 l (match-string 0 string)
25789 string (substring string (match-end 0)))
25790 (push (org-html-do-expand s) res)
25791 (push l res))
25792 (push (org-html-do-expand string) res)
25793 (apply 'concat (nreverse res))))
25795 (defun org-html-do-expand (s)
25796 "Apply all active conversions to translate special ASCII to HTML."
25797 (setq s (org-html-protect s))
25798 (if org-export-html-expand
25799 (let ((start 0))
25800 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
25801 (setq s (replace-match "<\\1>" t nil s)))))
25802 (if org-export-with-emphasize
25803 (setq s (org-export-html-convert-emphasize s)))
25804 (if org-export-with-special-strings
25805 (setq s (org-export-html-convert-special-strings s)))
25806 (if org-export-with-sub-superscripts
25807 (setq s (org-export-html-convert-sub-super s)))
25808 (if org-export-with-TeX-macros
25809 (let ((start 0) wd ass)
25810 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
25811 (if (get-text-property (match-beginning 0) 'org-protected s)
25812 (setq start (match-end 0))
25813 (setq wd (match-string 1 s))
25814 (if (setq ass (assoc wd org-html-entities))
25815 (setq s (replace-match (or (cdr ass)
25816 (concat "&" (car ass) ";"))
25817 t t s))
25818 (setq start (+ start (length wd))))))))
25821 (defun org-create-multibrace-regexp (left right n)
25822 "Create a regular expression which will match a balanced sexp.
25823 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
25824 as single character strings.
25825 The regexp returned will match the entire expression including the
25826 delimiters. It will also define a single group which contains the
25827 match except for the outermost delimiters. The maximum depth of
25828 stacked delimiters is N. Escaping delimiters is not possible."
25829 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
25830 (or "\\|")
25831 (re nothing)
25832 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
25833 (while (> n 1)
25834 (setq n (1- n)
25835 re (concat re or next)
25836 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
25837 (concat left "\\(" re "\\)" right)))
25839 (defvar org-match-substring-regexp
25840 (concat
25841 "\\([^\\]\\)\\([_^]\\)\\("
25842 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
25843 "\\|"
25844 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
25845 "\\|"
25846 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
25847 "The regular expression matching a sub- or superscript.")
25849 (defvar org-match-substring-with-braces-regexp
25850 (concat
25851 "\\([^\\]\\)\\([_^]\\)\\("
25852 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
25853 "\\)")
25854 "The regular expression matching a sub- or superscript, forcing braces.")
25856 (defconst org-export-html-special-string-regexps
25857 '(("\\\\-" . "&shy;")
25858 ("---\\([^-]\\)" . "&mdash;\\1")
25859 ("--\\([^-]\\)" . "&ndash;\\1")
25860 ("\\.\\.\\." . "&hellip;"))
25861 "Regular expressions for special string conversion.")
25863 (defun org-export-html-convert-special-strings (string)
25864 "Convert special characters in STRING to HTML."
25865 (let ((all org-export-html-special-string-regexps)
25866 e a re rpl start)
25867 (while (setq a (pop all))
25868 (setq re (car a) rpl (cdr a) start 0)
25869 (while (string-match re string start)
25870 (if (get-text-property (match-beginning 0) 'org-protected string)
25871 (setq start (match-end 0))
25872 (setq string (replace-match rpl t nil string)))))
25873 string))
25875 (defun org-export-html-convert-sub-super (string)
25876 "Convert sub- and superscripts in STRING to HTML."
25877 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
25878 (while (string-match org-match-substring-regexp string s)
25879 (cond
25880 ((and requireb (match-end 8)) (setq s (match-end 2)))
25881 ((get-text-property (match-beginning 2) 'org-protected string)
25882 (setq s (match-end 2)))
25884 (setq s (match-end 1)
25885 key (if (string= (match-string 2 string) "_") "sub" "sup")
25886 c (or (match-string 8 string)
25887 (match-string 6 string)
25888 (match-string 5 string))
25889 string (replace-match
25890 (concat (match-string 1 string)
25891 "<" key ">" c "</" key ">")
25892 t t string)))))
25893 (while (string-match "\\\\\\([_^]\\)" string)
25894 (setq string (replace-match (match-string 1 string) t t string)))
25895 string))
25897 (defun org-export-html-convert-emphasize (string)
25898 "Apply emphasis."
25899 (let ((s 0) rpl)
25900 (while (string-match org-emph-re string s)
25901 (if (not (equal
25902 (substring string (match-beginning 3) (1+ (match-beginning 3)))
25903 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
25904 (setq s (match-beginning 0)
25906 (concat
25907 (match-string 1 string)
25908 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
25909 (match-string 4 string)
25910 (nth 3 (assoc (match-string 3 string)
25911 org-emphasis-alist))
25912 (match-string 5 string))
25913 string (replace-match rpl t t string)
25914 s (+ s (- (length rpl) 2)))
25915 (setq s (1+ s))))
25916 string))
25918 (defvar org-par-open nil)
25919 (defun org-open-par ()
25920 "Insert <p>, but first close previous paragraph if any."
25921 (org-close-par-maybe)
25922 (insert "\n<p>")
25923 (setq org-par-open t))
25924 (defun org-close-par-maybe ()
25925 "Close paragraph if there is one open."
25926 (when org-par-open
25927 (insert "</p>")
25928 (setq org-par-open nil)))
25929 (defun org-close-li ()
25930 "Close <li> if necessary."
25931 (org-close-par-maybe)
25932 (insert "</li>\n"))
25934 (defvar body-only) ; dynamically scoped into this.
25935 (defun org-html-level-start (level title umax with-toc head-count)
25936 "Insert a new level in HTML export.
25937 When TITLE is nil, just close all open levels."
25938 (org-close-par-maybe)
25939 (let ((l org-level-max))
25940 (while (>= l level)
25941 (if (aref org-levels-open (1- l))
25942 (progn
25943 (org-html-level-close l umax)
25944 (aset org-levels-open (1- l) nil)))
25945 (setq l (1- l)))
25946 (when title
25947 ;; If title is nil, this means this function is called to close
25948 ;; all levels, so the rest is done only if title is given
25949 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
25950 (setq title (replace-match
25951 (if org-export-with-tags
25952 (save-match-data
25953 (concat
25954 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
25955 (mapconcat 'identity (org-split-string
25956 (match-string 1 title) ":")
25957 "&nbsp;")
25958 "</span>"))
25960 t t title)))
25961 (if (> level umax)
25962 (progn
25963 (if (aref org-levels-open (1- level))
25964 (progn
25965 (org-close-li)
25966 (insert "<li>" title "<br/>\n"))
25967 (aset org-levels-open (1- level) t)
25968 (org-close-par-maybe)
25969 (insert "<ul>\n<li>" title "<br/>\n")))
25970 (aset org-levels-open (1- level) t)
25971 (if (and org-export-with-section-numbers (not body-only))
25972 (setq title (concat (org-section-number level) " " title)))
25973 (setq level (+ level org-export-html-toplevel-hlevel -1))
25974 (if with-toc
25975 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
25976 level level head-count title level))
25977 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
25978 (org-open-par)))))
25980 (defun org-html-level-close (level max-outline-level)
25981 "Terminate one level in HTML export."
25982 (if (<= level max-outline-level)
25983 (insert "</div>\n")
25984 (org-close-li)
25985 (insert "</ul>\n")))
25987 ;;; iCalendar export
25989 ;;;###autoload
25990 (defun org-export-icalendar-this-file ()
25991 "Export current file as an iCalendar file.
25992 The iCalendar file will be located in the same directory as the Org-mode
25993 file, but with extension `.ics'."
25994 (interactive)
25995 (org-export-icalendar nil buffer-file-name))
25997 ;;;###autoload
25998 (defun org-export-icalendar-all-agenda-files ()
25999 "Export all files in `org-agenda-files' to iCalendar .ics files.
26000 Each iCalendar file will be located in the same directory as the Org-mode
26001 file, but with extension `.ics'."
26002 (interactive)
26003 (apply 'org-export-icalendar nil (org-agenda-files t)))
26005 ;;;###autoload
26006 (defun org-export-icalendar-combine-agenda-files ()
26007 "Export all files in `org-agenda-files' to a single combined iCalendar file.
26008 The file is stored under the name `org-combined-agenda-icalendar-file'."
26009 (interactive)
26010 (apply 'org-export-icalendar t (org-agenda-files t)))
26012 (defun org-export-icalendar (combine &rest files)
26013 "Create iCalendar files for all elements of FILES.
26014 If COMBINE is non-nil, combine all calendar entries into a single large
26015 file and store it under the name `org-combined-agenda-icalendar-file'."
26016 (save-excursion
26017 (org-prepare-agenda-buffers files)
26018 (let* ((dir (org-export-directory
26019 :ical (list :publishing-directory
26020 org-export-publishing-directory)))
26021 file ical-file ical-buffer category started org-agenda-new-buffers)
26023 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
26024 (when combine
26025 (setq ical-file
26026 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
26027 org-combined-agenda-icalendar-file
26028 (expand-file-name org-combined-agenda-icalendar-file dir))
26029 ical-buffer (org-get-agenda-file-buffer ical-file))
26030 (set-buffer ical-buffer) (erase-buffer))
26031 (while (setq file (pop files))
26032 (catch 'nextfile
26033 (org-check-agenda-file file)
26034 (set-buffer (org-get-agenda-file-buffer file))
26035 (unless combine
26036 (setq ical-file (concat (file-name-as-directory dir)
26037 (file-name-sans-extension
26038 (file-name-nondirectory buffer-file-name))
26039 ".ics"))
26040 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
26041 (with-current-buffer ical-buffer (erase-buffer)))
26042 (setq category (or org-category
26043 (file-name-sans-extension
26044 (file-name-nondirectory buffer-file-name))))
26045 (if (symbolp category) (setq category (symbol-name category)))
26046 (let ((standard-output ical-buffer))
26047 (if combine
26048 (and (not started) (setq started t)
26049 (org-start-icalendar-file org-icalendar-combined-name))
26050 (org-start-icalendar-file category))
26051 (org-print-icalendar-entries combine)
26052 (when (or (and combine (not files)) (not combine))
26053 (org-finish-icalendar-file)
26054 (set-buffer ical-buffer)
26055 (save-buffer)
26056 (run-hooks 'org-after-save-iCalendar-file-hook)))))
26057 (org-release-buffers org-agenda-new-buffers))))
26059 (defvar org-after-save-iCalendar-file-hook nil
26060 "Hook run after an iCalendar file has been saved.
26061 The iCalendar buffer is still current when this hook is run.
26062 A good way to use this is to tell a desktop calenndar application to re-read
26063 the iCalendar file.")
26065 (defun org-print-icalendar-entries (&optional combine)
26066 "Print iCalendar entries for the current Org-mode file to `standard-output'.
26067 When COMBINE is non nil, add the category to each line."
26068 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
26069 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
26070 (dts (org-ical-ts-to-string
26071 (format-time-string (cdr org-time-stamp-formats) (current-time))
26072 "DTSTART"))
26073 hd ts ts2 state status (inc t) pos b sexp rrule
26074 scheduledp deadlinep tmp pri category entry location summary desc
26075 (sexp-buffer (get-buffer-create "*ical-tmp*")))
26076 (org-refresh-category-properties)
26077 (save-excursion
26078 (goto-char (point-min))
26079 (while (re-search-forward re1 nil t)
26080 (catch :skip
26081 (org-agenda-skip)
26082 (setq pos (match-beginning 0)
26083 ts (match-string 0)
26084 inc t
26085 hd (org-get-heading)
26086 summary (org-icalendar-cleanup-string
26087 (org-entry-get nil "SUMMARY"))
26088 desc (org-icalendar-cleanup-string
26089 (or (org-entry-get nil "DESCRIPTION")
26090 (and org-icalendar-include-body (org-get-entry)))
26091 t org-icalendar-include-body)
26092 location (org-icalendar-cleanup-string
26093 (org-entry-get nil "LOCATION"))
26094 category (org-get-category))
26095 (if (looking-at re2)
26096 (progn
26097 (goto-char (match-end 0))
26098 (setq ts2 (match-string 1) inc nil))
26099 (setq tmp (buffer-substring (max (point-min)
26100 (- pos org-ds-keyword-length))
26101 pos)
26102 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
26103 (progn
26104 (setq inc nil)
26105 (replace-match "\\1" t nil ts))
26107 deadlinep (string-match org-deadline-regexp tmp)
26108 scheduledp (string-match org-scheduled-regexp tmp)
26109 ;; donep (org-entry-is-done-p)
26111 (if (or (string-match org-tr-regexp hd)
26112 (string-match org-ts-regexp hd))
26113 (setq hd (replace-match "" t t hd)))
26114 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
26115 (setq rrule
26116 (concat "\nRRULE:FREQ="
26117 (cdr (assoc
26118 (match-string 2 ts)
26119 '(("d" . "DAILY")("w" . "WEEKLY")
26120 ("m" . "MONTHLY")("y" . "YEARLY"))))
26121 ";INTERVAL=" (match-string 1 ts)))
26122 (setq rrule ""))
26123 (setq summary (or summary hd))
26124 (if (string-match org-bracket-link-regexp summary)
26125 (setq summary
26126 (replace-match (if (match-end 3)
26127 (match-string 3 summary)
26128 (match-string 1 summary))
26129 t t summary)))
26130 (if deadlinep (setq summary (concat "DL: " summary)))
26131 (if scheduledp (setq summary (concat "S: " summary)))
26132 (if (string-match "\\`<%%" ts)
26133 (with-current-buffer sexp-buffer
26134 (insert (substring ts 1 -1) " " summary "\n"))
26135 (princ (format "BEGIN:VEVENT
26137 %s%s
26138 SUMMARY:%s%s%s
26139 CATEGORIES:%s
26140 END:VEVENT\n"
26141 (org-ical-ts-to-string ts "DTSTART")
26142 (org-ical-ts-to-string ts2 "DTEND" inc)
26143 rrule summary
26144 (if (and desc (string-match "\\S-" desc))
26145 (concat "\nDESCRIPTION: " desc) "")
26146 (if (and location (string-match "\\S-" location))
26147 (concat "\nLOCATION: " location) "")
26148 category)))))
26150 (when (and org-icalendar-include-sexps
26151 (condition-case nil (require 'icalendar) (error nil))
26152 (fboundp 'icalendar-export-region))
26153 ;; Get all the literal sexps
26154 (goto-char (point-min))
26155 (while (re-search-forward "^&?%%(" nil t)
26156 (catch :skip
26157 (org-agenda-skip)
26158 (setq b (match-beginning 0))
26159 (goto-char (1- (match-end 0)))
26160 (forward-sexp 1)
26161 (end-of-line 1)
26162 (setq sexp (buffer-substring b (point)))
26163 (with-current-buffer sexp-buffer
26164 (insert sexp "\n"))
26165 (princ (org-diary-to-ical-string sexp-buffer)))))
26167 (when org-icalendar-include-todo
26168 (goto-char (point-min))
26169 (while (re-search-forward org-todo-line-regexp nil t)
26170 (catch :skip
26171 (org-agenda-skip)
26172 (setq state (match-string 2))
26173 (setq status (if (member state org-done-keywords)
26174 "COMPLETED" "NEEDS-ACTION"))
26175 (when (and state
26176 (or (not (member state org-done-keywords))
26177 (eq org-icalendar-include-todo 'all))
26178 (not (member org-archive-tag (org-get-tags-at)))
26180 (setq hd (match-string 3)
26181 summary (org-icalendar-cleanup-string
26182 (org-entry-get nil "SUMMARY"))
26183 desc (org-icalendar-cleanup-string
26184 (or (org-entry-get nil "DESCRIPTION")
26185 (and org-icalendar-include-body (org-get-entry)))
26186 t org-icalendar-include-body)
26187 location (org-icalendar-cleanup-string
26188 (org-entry-get nil "LOCATION")))
26189 (if (string-match org-bracket-link-regexp hd)
26190 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
26191 (match-string 1 hd))
26192 t t hd)))
26193 (if (string-match org-priority-regexp hd)
26194 (setq pri (string-to-char (match-string 2 hd))
26195 hd (concat (substring hd 0 (match-beginning 1))
26196 (substring hd (match-end 1))))
26197 (setq pri org-default-priority))
26198 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
26199 (- org-lowest-priority org-highest-priority))))))
26201 (princ (format "BEGIN:VTODO
26203 SUMMARY:%s%s%s
26204 CATEGORIES:%s
26205 SEQUENCE:1
26206 PRIORITY:%d
26207 STATUS:%s
26208 END:VTODO\n"
26210 (or summary hd)
26211 (if (and location (string-match "\\S-" location))
26212 (concat "\nLOCATION: " location) "")
26213 (if (and desc (string-match "\\S-" desc))
26214 (concat "\nDESCRIPTION: " desc) "")
26215 category pri status)))))))))
26217 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
26218 "Take out stuff and quote what needs to be quoted.
26219 When IS-BODY is non-nil, assume that this is the body of an item, clean up
26220 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
26221 characters."
26222 (if (not s)
26224 (when is-body
26225 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
26226 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
26227 (while (string-match re s) (setq s (replace-match "" t t s)))
26228 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
26229 (let ((start 0))
26230 (while (string-match "\\([,;\\]\\)" s start)
26231 (setq start (+ (match-beginning 0) 2)
26232 s (replace-match "\\\\\\1" nil nil s))))
26233 (when is-body
26234 (while (string-match "[ \t]*\n[ \t]*" s)
26235 (setq s (replace-match "\\n" t t s))))
26236 (setq s (org-trim s))
26237 (if is-body
26238 (if maxlength
26239 (if (and (numberp maxlength)
26240 (> (length s) maxlength))
26241 (setq s (substring s 0 maxlength)))))
26244 (defun org-get-entry ()
26245 "Clean-up description string."
26246 (save-excursion
26247 (org-back-to-heading t)
26248 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
26250 (defun org-start-icalendar-file (name)
26251 "Start an iCalendar file by inserting the header."
26252 (let ((user user-full-name)
26253 (name (or name "unknown"))
26254 (timezone (cadr (current-time-zone))))
26255 (princ
26256 (format "BEGIN:VCALENDAR
26257 VERSION:2.0
26258 X-WR-CALNAME:%s
26259 PRODID:-//%s//Emacs with Org-mode//EN
26260 X-WR-TIMEZONE:%s
26261 CALSCALE:GREGORIAN\n" name user timezone))))
26263 (defun org-finish-icalendar-file ()
26264 "Finish an iCalendar file by inserting the END statement."
26265 (princ "END:VCALENDAR\n"))
26267 (defun org-ical-ts-to-string (s keyword &optional inc)
26268 "Take a time string S and convert it to iCalendar format.
26269 KEYWORD is added in front, to make a complete line like DTSTART....
26270 When INC is non-nil, increase the hour by two (if time string contains
26271 a time), or the day by one (if it does not contain a time)."
26272 (let ((t1 (org-parse-time-string s 'nodefault))
26273 t2 fmt have-time time)
26274 (if (and (car t1) (nth 1 t1) (nth 2 t1))
26275 (setq t2 t1 have-time t)
26276 (setq t2 (org-parse-time-string s)))
26277 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
26278 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
26279 (when inc
26280 (if have-time
26281 (if org-agenda-default-appointment-duration
26282 (setq mi (+ org-agenda-default-appointment-duration mi))
26283 (setq h (+ 2 h)))
26284 (setq d (1+ d))))
26285 (setq time (encode-time s mi h d m y)))
26286 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
26287 (concat keyword (format-time-string fmt time))))
26289 ;;; XOXO export
26291 (defun org-export-as-xoxo-insert-into (buffer &rest output)
26292 (with-current-buffer buffer
26293 (apply 'insert output)))
26294 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
26296 (defun org-export-as-xoxo (&optional buffer)
26297 "Export the org buffer as XOXO.
26298 The XOXO buffer is named *xoxo-<source buffer name>*"
26299 (interactive (list (current-buffer)))
26300 ;; A quickie abstraction
26302 ;; Output everything as XOXO
26303 (with-current-buffer (get-buffer buffer)
26304 (let* ((pos (point))
26305 (opt-plist (org-combine-plists (org-default-export-plist)
26306 (org-infile-export-plist)))
26307 (filename (concat (file-name-as-directory
26308 (org-export-directory :xoxo opt-plist))
26309 (file-name-sans-extension
26310 (file-name-nondirectory buffer-file-name))
26311 ".html"))
26312 (out (find-file-noselect filename))
26313 (last-level 1)
26314 (hanging-li nil))
26315 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
26316 ;; Check the output buffer is empty.
26317 (with-current-buffer out (erase-buffer))
26318 ;; Kick off the output
26319 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
26320 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
26321 (let* ((hd (match-string-no-properties 1))
26322 (level (length hd))
26323 (text (concat
26324 (match-string-no-properties 2)
26325 (save-excursion
26326 (goto-char (match-end 0))
26327 (let ((str ""))
26328 (catch 'loop
26329 (while 't
26330 (forward-line)
26331 (if (looking-at "^[ \t]\\(.*\\)")
26332 (setq str (concat str (match-string-no-properties 1)))
26333 (throw 'loop str)))))))))
26335 ;; Handle level rendering
26336 (cond
26337 ((> level last-level)
26338 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
26340 ((< level last-level)
26341 (dotimes (- (- last-level level) 1)
26342 (if hanging-li
26343 (org-export-as-xoxo-insert-into out "</li>\n"))
26344 (org-export-as-xoxo-insert-into out "</ol>\n"))
26345 (when hanging-li
26346 (org-export-as-xoxo-insert-into out "</li>\n")
26347 (setq hanging-li nil)))
26349 ((equal level last-level)
26350 (if hanging-li
26351 (org-export-as-xoxo-insert-into out "</li>\n")))
26354 (setq last-level level)
26356 ;; And output the new li
26357 (setq hanging-li 't)
26358 (if (equal ?+ (elt text 0))
26359 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
26360 (org-export-as-xoxo-insert-into out "<li>" text))))
26362 ;; Finally finish off the ol
26363 (dotimes (- last-level 1)
26364 (if hanging-li
26365 (org-export-as-xoxo-insert-into out "</li>\n"))
26366 (org-export-as-xoxo-insert-into out "</ol>\n"))
26368 (goto-char pos)
26369 ;; Finish the buffer off and clean it up.
26370 (switch-to-buffer-other-window out)
26371 (indent-region (point-min) (point-max) nil)
26372 (save-buffer)
26373 (goto-char (point-min))
26377 ;;;; Key bindings
26379 ;; Make `C-c C-x' a prefix key
26380 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
26382 ;; TAB key with modifiers
26383 (org-defkey org-mode-map "\C-i" 'org-cycle)
26384 (org-defkey org-mode-map [(tab)] 'org-cycle)
26385 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
26386 (org-defkey org-mode-map [(meta tab)] 'org-complete)
26387 (org-defkey org-mode-map "\M-\t" 'org-complete)
26388 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
26389 ;; The following line is necessary under Suse GNU/Linux
26390 (unless (featurep 'xemacs)
26391 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
26392 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
26393 (define-key org-mode-map [backtab] 'org-shifttab)
26395 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
26396 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
26397 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
26399 ;; Cursor keys with modifiers
26400 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
26401 (org-defkey org-mode-map [(meta right)] 'org-metaright)
26402 (org-defkey org-mode-map [(meta up)] 'org-metaup)
26403 (org-defkey org-mode-map [(meta down)] 'org-metadown)
26405 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
26406 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
26407 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
26408 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
26410 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
26411 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
26412 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
26413 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
26415 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
26416 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
26418 ;;; Extra keys for tty access.
26419 ;; We only set them when really needed because otherwise the
26420 ;; menus don't show the simple keys
26422 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
26423 (not window-system))
26424 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
26425 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
26426 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
26427 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
26428 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
26429 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
26430 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
26431 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
26432 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
26433 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
26434 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
26435 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
26436 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
26437 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
26438 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
26439 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
26440 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
26441 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
26442 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
26443 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
26444 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
26445 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
26447 ;; All the other keys
26449 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
26450 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
26451 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
26452 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
26453 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
26454 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
26455 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
26456 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
26457 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
26458 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
26459 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
26460 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
26461 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
26462 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
26463 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
26464 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
26465 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
26466 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
26467 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
26468 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
26469 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
26470 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
26471 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
26472 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
26473 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
26474 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
26475 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
26476 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
26477 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
26478 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
26479 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
26480 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
26481 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
26482 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
26483 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
26484 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
26485 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
26486 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
26487 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
26488 (org-defkey org-mode-map "\C-c^" 'org-sort)
26489 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
26490 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
26491 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
26492 (org-defkey org-mode-map "\C-m" 'org-return)
26493 (org-defkey org-mode-map "\C-j" 'org-return-indent)
26494 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
26495 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
26496 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
26497 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
26498 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
26499 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
26500 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
26501 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
26502 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
26503 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
26504 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
26505 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
26506 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
26507 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
26508 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
26509 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
26511 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
26512 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
26513 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
26514 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
26516 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
26517 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
26518 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
26519 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
26520 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
26521 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
26522 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
26523 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
26524 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
26525 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
26526 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
26527 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
26529 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
26531 (when (featurep 'xemacs)
26532 (org-defkey org-mode-map 'button3 'popup-mode-menu))
26534 (defsubst org-table-p () (org-at-table-p))
26536 (defun org-self-insert-command (N)
26537 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
26538 If the cursor is in a table looking at whitespace, the whitespace is
26539 overwritten, and the table is not marked as requiring realignment."
26540 (interactive "p")
26541 (if (and (org-table-p)
26542 (progn
26543 ;; check if we blank the field, and if that triggers align
26544 (and org-table-auto-blank-field
26545 (member last-command
26546 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
26547 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
26548 ;; got extra space, this field does not determine column width
26549 (let (org-table-may-need-update) (org-table-blank-field))
26550 ;; no extra space, this field may determine column width
26551 (org-table-blank-field)))
26553 (eq N 1)
26554 (looking-at "[^|\n]* |"))
26555 (let (org-table-may-need-update)
26556 (goto-char (1- (match-end 0)))
26557 (delete-backward-char 1)
26558 (goto-char (match-beginning 0))
26559 (self-insert-command N))
26560 (setq org-table-may-need-update t)
26561 (self-insert-command N)
26562 (org-fix-tags-on-the-fly)))
26564 (defun org-fix-tags-on-the-fly ()
26565 (when (and (equal (char-after (point-at-bol)) ?*)
26566 (org-on-heading-p))
26567 (org-align-tags-here org-tags-column)))
26569 (defun org-delete-backward-char (N)
26570 "Like `delete-backward-char', insert whitespace at field end in tables.
26571 When deleting backwards, in tables this function will insert whitespace in
26572 front of the next \"|\" separator, to keep the table aligned. The table will
26573 still be marked for re-alignment if the field did fill the entire column,
26574 because, in this case the deletion might narrow the column."
26575 (interactive "p")
26576 (if (and (org-table-p)
26577 (eq N 1)
26578 (string-match "|" (buffer-substring (point-at-bol) (point)))
26579 (looking-at ".*?|"))
26580 (let ((pos (point))
26581 (noalign (looking-at "[^|\n\r]* |"))
26582 (c org-table-may-need-update))
26583 (backward-delete-char N)
26584 (skip-chars-forward "^|")
26585 (insert " ")
26586 (goto-char (1- pos))
26587 ;; noalign: if there were two spaces at the end, this field
26588 ;; does not determine the width of the column.
26589 (if noalign (setq org-table-may-need-update c)))
26590 (backward-delete-char N)
26591 (org-fix-tags-on-the-fly)))
26593 (defun org-delete-char (N)
26594 "Like `delete-char', but insert whitespace at field end in tables.
26595 When deleting characters, in tables this function will insert whitespace in
26596 front of the next \"|\" separator, to keep the table aligned. The table will
26597 still be marked for re-alignment if the field did fill the entire column,
26598 because, in this case the deletion might narrow the column."
26599 (interactive "p")
26600 (if (and (org-table-p)
26601 (not (bolp))
26602 (not (= (char-after) ?|))
26603 (eq N 1))
26604 (if (looking-at ".*?|")
26605 (let ((pos (point))
26606 (noalign (looking-at "[^|\n\r]* |"))
26607 (c org-table-may-need-update))
26608 (replace-match (concat
26609 (substring (match-string 0) 1 -1)
26610 " |"))
26611 (goto-char pos)
26612 ;; noalign: if there were two spaces at the end, this field
26613 ;; does not determine the width of the column.
26614 (if noalign (setq org-table-may-need-update c)))
26615 (delete-char N))
26616 (delete-char N)
26617 (org-fix-tags-on-the-fly)))
26619 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
26620 (put 'org-self-insert-command 'delete-selection t)
26621 (put 'orgtbl-self-insert-command 'delete-selection t)
26622 (put 'org-delete-char 'delete-selection 'supersede)
26623 (put 'org-delete-backward-char 'delete-selection 'supersede)
26625 ;; Make `flyspell-mode' delay after some commands
26626 (put 'org-self-insert-command 'flyspell-delayed t)
26627 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
26628 (put 'org-delete-char 'flyspell-delayed t)
26629 (put 'org-delete-backward-char 'flyspell-delayed t)
26631 ;; Make pabbrev-mode expand after org-mode commands
26632 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
26633 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
26635 ;; How to do this: Measure non-white length of current string
26636 ;; If equal to column width, we should realign.
26638 (defun org-remap (map &rest commands)
26639 "In MAP, remap the functions given in COMMANDS.
26640 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
26641 (let (new old)
26642 (while commands
26643 (setq old (pop commands) new (pop commands))
26644 (if (fboundp 'command-remapping)
26645 (org-defkey map (vector 'remap old) new)
26646 (substitute-key-definition old new map global-map)))))
26648 (when (eq org-enable-table-editor 'optimized)
26649 ;; If the user wants maximum table support, we need to hijack
26650 ;; some standard editing functions
26651 (org-remap org-mode-map
26652 'self-insert-command 'org-self-insert-command
26653 'delete-char 'org-delete-char
26654 'delete-backward-char 'org-delete-backward-char)
26655 (org-defkey org-mode-map "|" 'org-force-self-insert))
26657 (defun org-shiftcursor-error ()
26658 "Throw an error because Shift-Cursor command was applied in wrong context."
26659 (error "This command is active in special context like tables, headlines or timestamps"))
26661 (defun org-shifttab (&optional arg)
26662 "Global visibility cycling or move to previous table field.
26663 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
26664 on context.
26665 See the individual commands for more information."
26666 (interactive "P")
26667 (cond
26668 ((org-at-table-p) (call-interactively 'org-table-previous-field))
26669 (arg (message "Content view to level: ")
26670 (org-content (prefix-numeric-value arg))
26671 (setq org-cycle-global-status 'overview))
26672 (t (call-interactively 'org-global-cycle))))
26674 (defun org-shiftmetaleft ()
26675 "Promote subtree or delete table column.
26676 Calls `org-promote-subtree', `org-outdent-item',
26677 or `org-table-delete-column', depending on context.
26678 See the individual commands for more information."
26679 (interactive)
26680 (cond
26681 ((org-at-table-p) (call-interactively 'org-table-delete-column))
26682 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
26683 ((org-at-item-p) (call-interactively 'org-outdent-item))
26684 (t (org-shiftcursor-error))))
26686 (defun org-shiftmetaright ()
26687 "Demote subtree or insert table column.
26688 Calls `org-demote-subtree', `org-indent-item',
26689 or `org-table-insert-column', depending on context.
26690 See the individual commands for more information."
26691 (interactive)
26692 (cond
26693 ((org-at-table-p) (call-interactively 'org-table-insert-column))
26694 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
26695 ((org-at-item-p) (call-interactively 'org-indent-item))
26696 (t (org-shiftcursor-error))))
26698 (defun org-shiftmetaup (&optional arg)
26699 "Move subtree up or kill table row.
26700 Calls `org-move-subtree-up' or `org-table-kill-row' or
26701 `org-move-item-up' depending on context. See the individual commands
26702 for more information."
26703 (interactive "P")
26704 (cond
26705 ((org-at-table-p) (call-interactively 'org-table-kill-row))
26706 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26707 ((org-at-item-p) (call-interactively 'org-move-item-up))
26708 (t (org-shiftcursor-error))))
26709 (defun org-shiftmetadown (&optional arg)
26710 "Move subtree down or insert table row.
26711 Calls `org-move-subtree-down' or `org-table-insert-row' or
26712 `org-move-item-down', depending on context. See the individual
26713 commands for more information."
26714 (interactive "P")
26715 (cond
26716 ((org-at-table-p) (call-interactively 'org-table-insert-row))
26717 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26718 ((org-at-item-p) (call-interactively 'org-move-item-down))
26719 (t (org-shiftcursor-error))))
26721 (defun org-metaleft (&optional arg)
26722 "Promote heading or move table column to left.
26723 Calls `org-do-promote' or `org-table-move-column', depending on context.
26724 With no specific context, calls the Emacs default `backward-word'.
26725 See the individual commands for more information."
26726 (interactive "P")
26727 (cond
26728 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
26729 ((or (org-on-heading-p) (org-region-active-p))
26730 (call-interactively 'org-do-promote))
26731 ((org-at-item-p) (call-interactively 'org-outdent-item))
26732 (t (call-interactively 'backward-word))))
26734 (defun org-metaright (&optional arg)
26735 "Demote subtree or move table column to right.
26736 Calls `org-do-demote' or `org-table-move-column', depending on context.
26737 With no specific context, calls the Emacs default `forward-word'.
26738 See the individual commands for more information."
26739 (interactive "P")
26740 (cond
26741 ((org-at-table-p) (call-interactively 'org-table-move-column))
26742 ((or (org-on-heading-p) (org-region-active-p))
26743 (call-interactively 'org-do-demote))
26744 ((org-at-item-p) (call-interactively 'org-indent-item))
26745 (t (call-interactively 'forward-word))))
26747 (defun org-metaup (&optional arg)
26748 "Move subtree up or move table row up.
26749 Calls `org-move-subtree-up' or `org-table-move-row' or
26750 `org-move-item-up', depending on context. See the individual commands
26751 for more information."
26752 (interactive "P")
26753 (cond
26754 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
26755 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26756 ((org-at-item-p) (call-interactively 'org-move-item-up))
26757 (t (transpose-lines 1) (beginning-of-line -1))))
26759 (defun org-metadown (&optional arg)
26760 "Move subtree down or move table row down.
26761 Calls `org-move-subtree-down' or `org-table-move-row' or
26762 `org-move-item-down', depending on context. See the individual
26763 commands for more information."
26764 (interactive "P")
26765 (cond
26766 ((org-at-table-p) (call-interactively 'org-table-move-row))
26767 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26768 ((org-at-item-p) (call-interactively 'org-move-item-down))
26769 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
26771 (defun org-shiftup (&optional arg)
26772 "Increase item in timestamp or increase priority of current headline.
26773 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
26774 depending on context. See the individual commands for more information."
26775 (interactive "P")
26776 (cond
26777 ((org-at-timestamp-p t)
26778 (call-interactively (if org-edit-timestamp-down-means-later
26779 'org-timestamp-down 'org-timestamp-up)))
26780 ((org-on-heading-p) (call-interactively 'org-priority-up))
26781 ((org-at-item-p) (call-interactively 'org-previous-item))
26782 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
26784 (defun org-shiftdown (&optional arg)
26785 "Decrease item in timestamp or decrease priority of current headline.
26786 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
26787 depending on context. See the individual commands for more information."
26788 (interactive "P")
26789 (cond
26790 ((org-at-timestamp-p t)
26791 (call-interactively (if org-edit-timestamp-down-means-later
26792 'org-timestamp-up 'org-timestamp-down)))
26793 ((org-on-heading-p) (call-interactively 'org-priority-down))
26794 (t (call-interactively 'org-next-item))))
26796 (defun org-shiftright ()
26797 "Next TODO keyword or timestamp one day later, depending on context."
26798 (interactive)
26799 (cond
26800 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
26801 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
26802 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
26803 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
26804 (t (org-shiftcursor-error))))
26806 (defun org-shiftleft ()
26807 "Previous TODO keyword or timestamp one day earlier, depending on context."
26808 (interactive)
26809 (cond
26810 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
26811 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
26812 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
26813 ((org-at-property-p)
26814 (call-interactively 'org-property-previous-allowed-value))
26815 (t (org-shiftcursor-error))))
26817 (defun org-shiftcontrolright ()
26818 "Switch to next TODO set."
26819 (interactive)
26820 (cond
26821 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
26822 (t (org-shiftcursor-error))))
26824 (defun org-shiftcontrolleft ()
26825 "Switch to previous TODO set."
26826 (interactive)
26827 (cond
26828 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
26829 (t (org-shiftcursor-error))))
26831 (defun org-ctrl-c-ret ()
26832 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
26833 (interactive)
26834 (cond
26835 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
26836 (t (call-interactively 'org-insert-heading))))
26838 (defun org-copy-special ()
26839 "Copy region in table or copy current subtree.
26840 Calls `org-table-copy' or `org-copy-subtree', depending on context.
26841 See the individual commands for more information."
26842 (interactive)
26843 (call-interactively
26844 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
26846 (defun org-cut-special ()
26847 "Cut region in table or cut current subtree.
26848 Calls `org-table-copy' or `org-cut-subtree', depending on context.
26849 See the individual commands for more information."
26850 (interactive)
26851 (call-interactively
26852 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
26854 (defun org-paste-special (arg)
26855 "Paste rectangular region into table, or past subtree relative to level.
26856 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
26857 See the individual commands for more information."
26858 (interactive "P")
26859 (if (org-at-table-p)
26860 (org-table-paste-rectangle)
26861 (org-paste-subtree arg)))
26863 (defun org-ctrl-c-ctrl-c (&optional arg)
26864 "Set tags in headline, or update according to changed information at point.
26866 This command does many different things, depending on context:
26868 - If the cursor is in a headline, prompt for tags and insert them
26869 into the current line, aligned to `org-tags-column'. When called
26870 with prefix arg, realign all tags in the current buffer.
26872 - If the cursor is in one of the special #+KEYWORD lines, this
26873 triggers scanning the buffer for these lines and updating the
26874 information.
26876 - If the cursor is inside a table, realign the table. This command
26877 works even if the automatic table editor has been turned off.
26879 - If the cursor is on a #+TBLFM line, re-apply the formulas to
26880 the entire table.
26882 - If the cursor is a the beginning of a dynamic block, update it.
26884 - If the cursor is inside a table created by the table.el package,
26885 activate that table.
26887 - If the current buffer is a remember buffer, close note and file it.
26888 with a prefix argument, file it without further interaction to the default
26889 location.
26891 - If the cursor is on a <<<target>>>, update radio targets and corresponding
26892 links in this buffer.
26894 - If the cursor is on a numbered item in a plain list, renumber the
26895 ordered list.
26897 - If the cursor is on a checkbox, toggle it."
26898 (interactive "P")
26899 (let ((org-enable-table-editor t))
26900 (cond
26901 ((or org-clock-overlays
26902 org-occur-highlights
26903 org-latex-fragment-image-overlays)
26904 (org-remove-clock-overlays)
26905 (org-remove-occur-highlights)
26906 (org-remove-latex-fragment-image-overlays)
26907 (message "Temporary highlights/overlays removed from current buffer"))
26908 ((and (local-variable-p 'org-finish-function (current-buffer))
26909 (fboundp org-finish-function))
26910 (funcall org-finish-function))
26911 ((org-at-property-p)
26912 (call-interactively 'org-property-action))
26913 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
26914 ((org-on-heading-p) (call-interactively 'org-set-tags))
26915 ((org-at-table.el-p)
26916 (require 'table)
26917 (beginning-of-line 1)
26918 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
26919 (call-interactively 'table-recognize-table))
26920 ((org-at-table-p)
26921 (org-table-maybe-eval-formula)
26922 (if arg
26923 (call-interactively 'org-table-recalculate)
26924 (org-table-maybe-recalculate-line))
26925 (call-interactively 'org-table-align))
26926 ((org-at-item-checkbox-p)
26927 (call-interactively 'org-toggle-checkbox))
26928 ((org-at-item-p)
26929 (call-interactively 'org-maybe-renumber-ordered-list))
26930 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
26931 ;; Dynamic block
26932 (beginning-of-line 1)
26933 (org-update-dblock))
26934 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
26935 (cond
26936 ((equal (match-string 1) "TBLFM")
26937 ;; Recalculate the table before this line
26938 (save-excursion
26939 (beginning-of-line 1)
26940 (skip-chars-backward " \r\n\t")
26941 (if (org-at-table-p)
26942 (org-call-with-arg 'org-table-recalculate t))))
26944 (call-interactively 'org-mode-restart))))
26945 (t (error "C-c C-c can do nothing useful at this location.")))))
26947 (defun org-mode-restart ()
26948 "Restart Org-mode, to scan again for special lines.
26949 Also updates the keyword regular expressions."
26950 (interactive)
26951 (let ((org-inhibit-startup t)) (org-mode))
26952 (message "Org-mode restarted to refresh keyword and special line setup"))
26954 (defun org-kill-note-or-show-branches ()
26955 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
26956 (interactive)
26957 (if (not org-finish-function)
26958 (call-interactively 'show-branches)
26959 (let ((org-note-abort t))
26960 (funcall org-finish-function))))
26962 (defun org-return (&optional indent)
26963 "Goto next table row or insert a newline.
26964 Calls `org-table-next-row' or `newline', depending on context.
26965 See the individual commands for more information."
26966 (interactive)
26967 (cond
26968 ((bobp) (if indent (newline-and-indent) (newline)))
26969 ((org-at-table-p)
26970 (org-table-justify-field-maybe)
26971 (call-interactively 'org-table-next-row))
26972 (t (if indent (newline-and-indent) (newline)))))
26974 (defun org-return-indent ()
26975 (interactive)
26976 "Goto next table row or insert a newline and indent.
26977 Calls `org-table-next-row' or `newline-and-indent', depending on
26978 context. See the individual commands for more information."
26979 (org-return t))
26981 (defun org-ctrl-c-minus ()
26982 "Insert separator line in table or modify bullet type in list.
26983 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
26984 depending on context."
26985 (interactive)
26986 (cond
26987 ((org-at-table-p)
26988 (call-interactively 'org-table-insert-hline))
26989 ((org-on-heading-p)
26990 ;; Convert to item
26991 (save-excursion
26992 (beginning-of-line 1)
26993 (if (looking-at "\\*+ ")
26994 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
26995 ((org-in-item-p)
26996 (call-interactively 'org-cycle-list-bullet))
26997 (t (error "`C-c -' does have no function here."))))
26999 (defun org-meta-return (&optional arg)
27000 "Insert a new heading or wrap a region in a table.
27001 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
27002 See the individual commands for more information."
27003 (interactive "P")
27004 (cond
27005 ((org-at-table-p)
27006 (call-interactively 'org-table-wrap-region))
27007 (t (call-interactively 'org-insert-heading))))
27009 ;;; Menu entries
27011 ;; Define the Org-mode menus
27012 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
27013 '("Tbl"
27014 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
27015 ["Next Field" org-cycle (org-at-table-p)]
27016 ["Previous Field" org-shifttab (org-at-table-p)]
27017 ["Next Row" org-return (org-at-table-p)]
27018 "--"
27019 ["Blank Field" org-table-blank-field (org-at-table-p)]
27020 ["Edit Field" org-table-edit-field (org-at-table-p)]
27021 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
27022 "--"
27023 ("Column"
27024 ["Move Column Left" org-metaleft (org-at-table-p)]
27025 ["Move Column Right" org-metaright (org-at-table-p)]
27026 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
27027 ["Insert Column" org-shiftmetaright (org-at-table-p)])
27028 ("Row"
27029 ["Move Row Up" org-metaup (org-at-table-p)]
27030 ["Move Row Down" org-metadown (org-at-table-p)]
27031 ["Delete Row" org-shiftmetaup (org-at-table-p)]
27032 ["Insert Row" org-shiftmetadown (org-at-table-p)]
27033 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
27034 "--"
27035 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
27036 ("Rectangle"
27037 ["Copy Rectangle" org-copy-special (org-at-table-p)]
27038 ["Cut Rectangle" org-cut-special (org-at-table-p)]
27039 ["Paste Rectangle" org-paste-special (org-at-table-p)]
27040 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
27041 "--"
27042 ("Calculate"
27043 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
27044 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
27045 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
27046 "--"
27047 ["Recalculate line" org-table-recalculate (org-at-table-p)]
27048 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
27049 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
27050 "--"
27051 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
27052 "--"
27053 ["Sum Column/Rectangle" org-table-sum
27054 (or (org-at-table-p) (org-region-active-p))]
27055 ["Which Column?" org-table-current-column (org-at-table-p)])
27056 ["Debug Formulas"
27057 org-table-toggle-formula-debugger
27058 :style toggle :selected org-table-formula-debug]
27059 ["Show Col/Row Numbers"
27060 org-table-toggle-coordinate-overlays
27061 :style toggle :selected org-table-overlay-coordinates]
27062 "--"
27063 ["Create" org-table-create (and (not (org-at-table-p))
27064 org-enable-table-editor)]
27065 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
27066 ["Import from File" org-table-import (not (org-at-table-p))]
27067 ["Export to File" org-table-export (org-at-table-p)]
27068 "--"
27069 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
27071 (easy-menu-define org-org-menu org-mode-map "Org menu"
27072 '("Org"
27073 ("Show/Hide"
27074 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
27075 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
27076 ["Sparse Tree" org-occur t]
27077 ["Reveal Context" org-reveal t]
27078 ["Show All" show-all t]
27079 "--"
27080 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
27081 "--"
27082 ["New Heading" org-insert-heading t]
27083 ("Navigate Headings"
27084 ["Up" outline-up-heading t]
27085 ["Next" outline-next-visible-heading t]
27086 ["Previous" outline-previous-visible-heading t]
27087 ["Next Same Level" outline-forward-same-level t]
27088 ["Previous Same Level" outline-backward-same-level t]
27089 "--"
27090 ["Jump" org-goto t])
27091 ("Edit Structure"
27092 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
27093 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
27094 "--"
27095 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
27096 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
27097 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
27098 "--"
27099 ["Promote Heading" org-metaleft (not (org-at-table-p))]
27100 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
27101 ["Demote Heading" org-metaright (not (org-at-table-p))]
27102 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
27103 "--"
27104 ["Sort Region/Children" org-sort (not (org-at-table-p))]
27105 "--"
27106 ["Convert to odd levels" org-convert-to-odd-levels t]
27107 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
27108 ("Editing"
27109 ["Emphasis..." org-emphasize t])
27110 ("Archive"
27111 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
27112 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
27113 ; :active t :keys "C-u C-c C-x C-a"]
27114 ["Sparse trees open ARCHIVE trees"
27115 (setq org-sparse-tree-open-archived-trees
27116 (not org-sparse-tree-open-archived-trees))
27117 :style toggle :selected org-sparse-tree-open-archived-trees]
27118 ["Cycling opens ARCHIVE trees"
27119 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
27120 :style toggle :selected org-cycle-open-archived-trees]
27121 ["Agenda includes ARCHIVE trees"
27122 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
27123 :style toggle :selected (not org-agenda-skip-archived-trees)]
27124 "--"
27125 ["Move Subtree to Archive" org-advertized-archive-subtree t]
27126 ; ["Check and Move Children" (org-archive-subtree '(4))
27127 ; :active t :keys "C-u C-c C-x C-s"]
27129 "--"
27130 ("TODO Lists"
27131 ["TODO/DONE/-" org-todo t]
27132 ("Select keyword"
27133 ["Next keyword" org-shiftright (org-on-heading-p)]
27134 ["Previous keyword" org-shiftleft (org-on-heading-p)]
27135 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
27136 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
27137 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
27138 ["Show TODO Tree" org-show-todo-tree t]
27139 ["Global TODO list" org-todo-list t]
27140 "--"
27141 ["Set Priority" org-priority t]
27142 ["Priority Up" org-shiftup t]
27143 ["Priority Down" org-shiftdown t])
27144 ("TAGS and Properties"
27145 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
27146 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
27147 "--"
27148 ["Set property" 'org-set-property t]
27149 ["Column view of properties" org-columns t]
27150 ["Insert Column View DBlock" org-insert-columns-dblock t])
27151 ("Dates and Scheduling"
27152 ["Timestamp" org-time-stamp t]
27153 ["Timestamp (inactive)" org-time-stamp-inactive t]
27154 ("Change Date"
27155 ["1 Day Later" org-shiftright t]
27156 ["1 Day Earlier" org-shiftleft t]
27157 ["1 ... Later" org-shiftup t]
27158 ["1 ... Earlier" org-shiftdown t])
27159 ["Compute Time Range" org-evaluate-time-range t]
27160 ["Schedule Item" org-schedule t]
27161 ["Deadline" org-deadline t]
27162 "--"
27163 ["Custom time format" org-toggle-time-stamp-overlays
27164 :style radio :selected org-display-custom-times]
27165 "--"
27166 ["Goto Calendar" org-goto-calendar t]
27167 ["Date from Calendar" org-date-from-calendar t])
27168 ("Logging work"
27169 ["Clock in" org-clock-in t]
27170 ["Clock out" org-clock-out t]
27171 ["Clock cancel" org-clock-cancel t]
27172 ["Goto running clock" org-clock-goto t]
27173 ["Display times" org-clock-display t]
27174 ["Create clock table" org-clock-report t]
27175 "--"
27176 ["Record DONE time"
27177 (progn (setq org-log-done (not org-log-done))
27178 (message "Switching to %s will %s record a timestamp"
27179 (car org-done-keywords)
27180 (if org-log-done "automatically" "not")))
27181 :style toggle :selected org-log-done])
27182 "--"
27183 ["Agenda Command..." org-agenda t]
27184 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
27185 ("File List for Agenda")
27186 ("Special views current file"
27187 ["TODO Tree" org-show-todo-tree t]
27188 ["Check Deadlines" org-check-deadlines t]
27189 ["Timeline" org-timeline t]
27190 ["Tags Tree" org-tags-sparse-tree t])
27191 "--"
27192 ("Hyperlinks"
27193 ["Store Link (Global)" org-store-link t]
27194 ["Insert Link" org-insert-link t]
27195 ["Follow Link" org-open-at-point t]
27196 "--"
27197 ["Next link" org-next-link t]
27198 ["Previous link" org-previous-link t]
27199 "--"
27200 ["Descriptive Links"
27201 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
27202 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
27203 ["Literal Links"
27204 (progn
27205 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
27206 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
27207 "--"
27208 ["Export/Publish..." org-export t]
27209 ("LaTeX"
27210 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
27211 :selected org-cdlatex-mode]
27212 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
27213 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
27214 ["Modify math symbol" org-cdlatex-math-modify
27215 (org-inside-LaTeX-fragment-p)]
27216 ["Export LaTeX fragments as images"
27217 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
27218 :style toggle :selected org-export-with-LaTeX-fragments])
27219 "--"
27220 ("Documentation"
27221 ["Show Version" org-version t]
27222 ["Info Documentation" org-info t])
27223 ("Customize"
27224 ["Browse Org Group" org-customize t]
27225 "--"
27226 ["Expand This Menu" org-create-customize-menu
27227 (fboundp 'customize-menu-create)])
27228 "--"
27229 ["Refresh setup" org-mode-restart t]
27232 (defun org-info (&optional node)
27233 "Read documentation for Org-mode in the info system.
27234 With optional NODE, go directly to that node."
27235 (interactive)
27236 (require 'info)
27237 (Info-goto-node (format "(org)%s" (or node ""))))
27239 (defun org-install-agenda-files-menu ()
27240 (let ((bl (buffer-list)))
27241 (save-excursion
27242 (while bl
27243 (set-buffer (pop bl))
27244 (if (org-mode-p) (setq bl nil)))
27245 (when (org-mode-p)
27246 (easy-menu-change
27247 '("Org") "File List for Agenda"
27248 (append
27249 (list
27250 ["Edit File List" (org-edit-agenda-file-list) t]
27251 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
27252 ["Remove Current File from List" org-remove-file t]
27253 ["Cycle through agenda files" org-cycle-agenda-files t]
27254 ["Occur in all agenda files" org-occur-in-agenda-files t]
27255 "--")
27256 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
27258 ;;;; Documentation
27260 (defun org-customize ()
27261 "Call the customize function with org as argument."
27262 (interactive)
27263 (customize-browse 'org))
27265 (defun org-create-customize-menu ()
27266 "Create a full customization menu for Org-mode, insert it into the menu."
27267 (interactive)
27268 (if (fboundp 'customize-menu-create)
27269 (progn
27270 (easy-menu-change
27271 '("Org") "Customize"
27272 `(["Browse Org group" org-customize t]
27273 "--"
27274 ,(customize-menu-create 'org)
27275 ["Set" Custom-set t]
27276 ["Save" Custom-save t]
27277 ["Reset to Current" Custom-reset-current t]
27278 ["Reset to Saved" Custom-reset-saved t]
27279 ["Reset to Standard Settings" Custom-reset-standard t]))
27280 (message "\"Org\"-menu now contains full customization menu"))
27281 (error "Cannot expand menu (outdated version of cus-edit.el)")))
27283 ;;;; Miscellaneous stuff
27286 ;;; Generally useful functions
27288 (defun org-context ()
27289 "Return a list of contexts of the current cursor position.
27290 If several contexts apply, all are returned.
27291 Each context entry is a list with a symbol naming the context, and
27292 two positions indicating start and end of the context. Possible
27293 contexts are:
27295 :headline anywhere in a headline
27296 :headline-stars on the leading stars in a headline
27297 :todo-keyword on a TODO keyword (including DONE) in a headline
27298 :tags on the TAGS in a headline
27299 :priority on the priority cookie in a headline
27300 :item on the first line of a plain list item
27301 :item-bullet on the bullet/number of a plain list item
27302 :checkbox on the checkbox in a plain list item
27303 :table in an org-mode table
27304 :table-special on a special filed in a table
27305 :table-table in a table.el table
27306 :link on a hyperlink
27307 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
27308 :target on a <<target>>
27309 :radio-target on a <<<radio-target>>>
27310 :latex-fragment on a LaTeX fragment
27311 :latex-preview on a LaTeX fragment with overlayed preview image
27313 This function expects the position to be visible because it uses font-lock
27314 faces as a help to recognize the following contexts: :table-special, :link,
27315 and :keyword."
27316 (let* ((f (get-text-property (point) 'face))
27317 (faces (if (listp f) f (list f)))
27318 (p (point)) clist o)
27319 ;; First the large context
27320 (cond
27321 ((org-on-heading-p t)
27322 (push (list :headline (point-at-bol) (point-at-eol)) clist)
27323 (when (progn
27324 (beginning-of-line 1)
27325 (looking-at org-todo-line-tags-regexp))
27326 (push (org-point-in-group p 1 :headline-stars) clist)
27327 (push (org-point-in-group p 2 :todo-keyword) clist)
27328 (push (org-point-in-group p 4 :tags) clist))
27329 (goto-char p)
27330 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
27331 (if (looking-at "\\[#[A-Z0-9]\\]")
27332 (push (org-point-in-group p 0 :priority) clist)))
27334 ((org-at-item-p)
27335 (push (org-point-in-group p 2 :item-bullet) clist)
27336 (push (list :item (point-at-bol)
27337 (save-excursion (org-end-of-item) (point)))
27338 clist)
27339 (and (org-at-item-checkbox-p)
27340 (push (org-point-in-group p 0 :checkbox) clist)))
27342 ((org-at-table-p)
27343 (push (list :table (org-table-begin) (org-table-end)) clist)
27344 (if (memq 'org-formula faces)
27345 (push (list :table-special
27346 (previous-single-property-change p 'face)
27347 (next-single-property-change p 'face)) clist)))
27348 ((org-at-table-p 'any)
27349 (push (list :table-table) clist)))
27350 (goto-char p)
27352 ;; Now the small context
27353 (cond
27354 ((org-at-timestamp-p)
27355 (push (org-point-in-group p 0 :timestamp) clist))
27356 ((memq 'org-link faces)
27357 (push (list :link
27358 (previous-single-property-change p 'face)
27359 (next-single-property-change p 'face)) clist))
27360 ((memq 'org-special-keyword faces)
27361 (push (list :keyword
27362 (previous-single-property-change p 'face)
27363 (next-single-property-change p 'face)) clist))
27364 ((org-on-target-p)
27365 (push (org-point-in-group p 0 :target) clist)
27366 (goto-char (1- (match-beginning 0)))
27367 (if (looking-at org-radio-target-regexp)
27368 (push (org-point-in-group p 0 :radio-target) clist))
27369 (goto-char p))
27370 ((setq o (car (delq nil
27371 (mapcar
27372 (lambda (x)
27373 (if (memq x org-latex-fragment-image-overlays) x))
27374 (org-overlays-at (point))))))
27375 (push (list :latex-fragment
27376 (org-overlay-start o) (org-overlay-end o)) clist)
27377 (push (list :latex-preview
27378 (org-overlay-start o) (org-overlay-end o)) clist))
27379 ((org-inside-LaTeX-fragment-p)
27380 ;; FIXME: positions wrong.
27381 (push (list :latex-fragment (point) (point)) clist)))
27383 (setq clist (nreverse (delq nil clist)))
27384 clist))
27386 ;; FIXME: Compare with at-regexp-p Do we need both?
27387 (defun org-in-regexp (re &optional nlines visually)
27388 "Check if point is inside a match of regexp.
27389 Normally only the current line is checked, but you can include NLINES extra
27390 lines both before and after point into the search.
27391 If VISUALLY is set, require that the cursor is not after the match but
27392 really on, so that the block visually is on the match."
27393 (catch 'exit
27394 (let ((pos (point))
27395 (eol (point-at-eol (+ 1 (or nlines 0))))
27396 (inc (if visually 1 0)))
27397 (save-excursion
27398 (beginning-of-line (- 1 (or nlines 0)))
27399 (while (re-search-forward re eol t)
27400 (if (and (<= (match-beginning 0) pos)
27401 (>= (+ inc (match-end 0)) pos))
27402 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
27404 (defun org-at-regexp-p (regexp)
27405 "Is point inside a match of REGEXP in the current line?"
27406 (catch 'exit
27407 (save-excursion
27408 (let ((pos (point)) (end (point-at-eol)))
27409 (beginning-of-line 1)
27410 (while (re-search-forward regexp end t)
27411 (if (and (<= (match-beginning 0) pos)
27412 (>= (match-end 0) pos))
27413 (throw 'exit t)))
27414 nil))))
27416 (defun org-occur-in-agenda-files (regexp &optional nlines)
27417 "Call `multi-occur' with buffers for all agenda files."
27418 (interactive "sOrg-files matching: \np")
27419 (let* ((files (org-agenda-files))
27420 (tnames (mapcar 'file-truename files))
27421 (extra org-agenda-multi-occur-extra-files)
27423 (while (setq f (pop extra))
27424 (unless (member (file-truename f) tnames)
27425 (add-to-list 'files f 'append)
27426 (add-to-list 'tnames (file-truename f) 'append)))
27427 (multi-occur
27428 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
27429 regexp)))
27431 (if (boundp 'occur-mode-find-occurrence-hook)
27432 ;; Emacs 23
27433 (add-hook 'occur-mode-find-occurrence-hook
27434 (lambda ()
27435 (when (org-mode-p)
27436 (org-reveal))))
27437 ;; Emacs 22
27438 (defadvice occur-mode-goto-occurrence
27439 (after org-occur-reveal activate)
27440 (and (org-mode-p) (org-reveal)))
27441 (defadvice occur-mode-goto-occurrence-other-window
27442 (after org-occur-reveal activate)
27443 (and (org-mode-p) (org-reveal)))
27444 (defadvice occur-mode-display-occurrence
27445 (after org-occur-reveal activate)
27446 (when (org-mode-p)
27447 (let ((pos (occur-mode-find-occurrence)))
27448 (with-current-buffer (marker-buffer pos)
27449 (save-excursion
27450 (goto-char pos)
27451 (org-reveal)))))))
27453 (defun org-uniquify (list)
27454 "Remove duplicate elements from LIST."
27455 (let (res)
27456 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
27457 res))
27459 (defun org-delete-all (elts list)
27460 "Remove all elements in ELTS from LIST."
27461 (while elts
27462 (setq list (delete (pop elts) list)))
27463 list)
27465 (defun org-back-over-empty-lines ()
27466 "Move backwards over witespace, to the beginning of the first empty line.
27467 Returns the number o empty lines passed."
27468 (let ((pos (point)))
27469 (skip-chars-backward " \t\n\r")
27470 (beginning-of-line 2)
27471 (goto-char (min (point) pos))
27472 (count-lines (point) pos)))
27474 (defun org-skip-whitespace ()
27475 (skip-chars-forward " \t\n\r"))
27477 (defun org-point-in-group (point group &optional context)
27478 "Check if POINT is in match-group GROUP.
27479 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
27480 match. If the match group does ot exist or point is not inside it,
27481 return nil."
27482 (and (match-beginning group)
27483 (>= point (match-beginning group))
27484 (<= point (match-end group))
27485 (if context
27486 (list context (match-beginning group) (match-end group))
27487 t)))
27489 (defun org-switch-to-buffer-other-window (&rest args)
27490 "Switch to buffer in a second window on the current frame.
27491 In particular, do not allow pop-up frames."
27492 (let (pop-up-frames special-display-buffer-names special-display-regexps
27493 special-display-function)
27494 (apply 'switch-to-buffer-other-window args)))
27496 (defun org-combine-plists (&rest plists)
27497 "Create a single property list from all plists in PLISTS.
27498 The process starts by copying the first list, and then setting properties
27499 from the other lists. Settings in the last list are the most significant
27500 ones and overrule settings in the other lists."
27501 (let ((rtn (copy-sequence (pop plists)))
27502 p v ls)
27503 (while plists
27504 (setq ls (pop plists))
27505 (while ls
27506 (setq p (pop ls) v (pop ls))
27507 (setq rtn (plist-put rtn p v))))
27508 rtn))
27510 (defun org-move-line-down (arg)
27511 "Move the current line down. With prefix argument, move it past ARG lines."
27512 (interactive "p")
27513 (let ((col (current-column))
27514 beg end pos)
27515 (beginning-of-line 1) (setq beg (point))
27516 (beginning-of-line 2) (setq end (point))
27517 (beginning-of-line (+ 1 arg))
27518 (setq pos (move-marker (make-marker) (point)))
27519 (insert (delete-and-extract-region beg end))
27520 (goto-char pos)
27521 (move-to-column col)))
27523 (defun org-move-line-up (arg)
27524 "Move the current line up. With prefix argument, move it past ARG lines."
27525 (interactive "p")
27526 (let ((col (current-column))
27527 beg end pos)
27528 (beginning-of-line 1) (setq beg (point))
27529 (beginning-of-line 2) (setq end (point))
27530 (beginning-of-line (- arg))
27531 (setq pos (move-marker (make-marker) (point)))
27532 (insert (delete-and-extract-region beg end))
27533 (goto-char pos)
27534 (move-to-column col)))
27536 (defun org-replace-escapes (string table)
27537 "Replace %-escapes in STRING with values in TABLE.
27538 TABLE is an association list with keys like \"%a\" and string values.
27539 The sequences in STRING may contain normal field width and padding information,
27540 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
27541 so values can contain further %-escapes if they are define later in TABLE."
27542 (let ((case-fold-search nil)
27543 e re rpl)
27544 (while (setq e (pop table))
27545 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
27546 (while (string-match re string)
27547 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
27548 (cdr e)))
27549 (setq string (replace-match rpl t t string))))
27550 string))
27553 (defun org-sublist (list start end)
27554 "Return a section of LIST, from START to END.
27555 Counting starts at 1."
27556 (let (rtn (c start))
27557 (setq list (nthcdr (1- start) list))
27558 (while (and list (<= c end))
27559 (push (pop list) rtn)
27560 (setq c (1+ c)))
27561 (nreverse rtn)))
27563 (defun org-find-base-buffer-visiting (file)
27564 "Like `find-buffer-visiting' but alway return the base buffer and
27565 not an indirect buffer"
27566 (let ((buf (find-buffer-visiting file)))
27567 (if buf
27568 (or (buffer-base-buffer buf) buf)
27569 nil)))
27571 (defun org-image-file-name-regexp ()
27572 "Return regexp matching the file names of images."
27573 (if (fboundp 'image-file-name-regexp)
27574 (image-file-name-regexp)
27575 (let ((image-file-name-extensions
27576 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
27577 "xbm" "xpm" "pbm" "pgm" "ppm")))
27578 (concat "\\."
27579 (regexp-opt (nconc (mapcar 'upcase
27580 image-file-name-extensions)
27581 image-file-name-extensions)
27583 "\\'"))))
27585 (defun org-file-image-p (file)
27586 "Return non-nil if FILE is an image."
27587 (save-match-data
27588 (string-match (org-image-file-name-regexp) file)))
27590 ;;; Paragraph filling stuff.
27591 ;; We want this to be just right, so use the full arsenal.
27593 (defun org-indent-line-function ()
27594 "Indent line like previous, but further if previous was headline or item."
27595 (interactive)
27596 (let* ((pos (point))
27597 (itemp (org-at-item-p))
27598 column bpos bcol tpos tcol bullet btype bullet-type)
27599 ;; Find the previous relevant line
27600 (beginning-of-line 1)
27601 (cond
27602 ((looking-at "#") (setq column 0))
27603 ((looking-at "\\*+ ") (setq column 0))
27605 (beginning-of-line 0)
27606 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
27607 (beginning-of-line 0))
27608 (cond
27609 ((looking-at "\\*+[ \t]+")
27610 (goto-char (match-end 0))
27611 (setq column (current-column)))
27612 ((org-in-item-p)
27613 (org-beginning-of-item)
27614 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
27615 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
27616 (setq bpos (match-beginning 1) tpos (match-end 0)
27617 bcol (progn (goto-char bpos) (current-column))
27618 tcol (progn (goto-char tpos) (current-column))
27619 bullet (match-string 1)
27620 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
27621 (if (not itemp)
27622 (setq column tcol)
27623 (goto-char pos)
27624 (beginning-of-line 1)
27625 (if (looking-at "\\S-")
27626 (progn
27627 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
27628 (setq bullet (match-string 1)
27629 btype (if (string-match "[0-9]" bullet) "n" bullet))
27630 (setq column (if (equal btype bullet-type) bcol tcol)))
27631 (setq column (org-get-indentation)))))
27632 (t (setq column (org-get-indentation))))))
27633 (goto-char pos)
27634 (if (<= (current-column) (current-indentation))
27635 (indent-line-to column)
27636 (save-excursion (indent-line-to column)))
27637 (setq column (current-column))
27638 (beginning-of-line 1)
27639 (if (looking-at
27640 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
27641 (replace-match (concat "\\1" (format org-property-format
27642 (match-string 2) (match-string 3)))
27643 t nil))
27644 (move-to-column column)))
27646 (defun org-set-autofill-regexps ()
27647 (interactive)
27648 ;; In the paragraph separator we include headlines, because filling
27649 ;; text in a line directly attached to a headline would otherwise
27650 ;; fill the headline as well.
27651 (org-set-local 'comment-start-skip "^#+[ \t]*")
27652 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
27653 ;; The paragraph starter includes hand-formatted lists.
27654 (org-set-local 'paragraph-start
27655 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
27656 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
27657 ;; But only if the user has not turned off tables or fixed-width regions
27658 (org-set-local
27659 'auto-fill-inhibit-regexp
27660 (concat "\\*+ \\|#\\+"
27661 "\\|[ \t]*" org-keyword-time-regexp
27662 (if (or org-enable-table-editor org-enable-fixed-width-editor)
27663 (concat
27664 "\\|[ \t]*["
27665 (if org-enable-table-editor "|" "")
27666 (if org-enable-fixed-width-editor ":" "")
27667 "]"))))
27668 ;; We use our own fill-paragraph function, to make sure that tables
27669 ;; and fixed-width regions are not wrapped. That function will pass
27670 ;; through to `fill-paragraph' when appropriate.
27671 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
27672 ; Adaptive filling: To get full control, first make sure that
27673 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
27674 (org-set-local 'adaptive-fill-regexp "\000")
27675 (org-set-local 'adaptive-fill-function
27676 'org-adaptive-fill-function)
27677 (org-set-local
27678 'align-mode-rules-list
27679 '((org-in-buffer-settings
27680 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
27681 (modes . '(org-mode))))))
27683 (defun org-fill-paragraph (&optional justify)
27684 "Re-align a table, pass through to fill-paragraph if no table."
27685 (let ((table-p (org-at-table-p))
27686 (table.el-p (org-at-table.el-p)))
27687 (cond ((and (equal (char-after (point-at-bol)) ?*)
27688 (save-excursion (goto-char (point-at-bol))
27689 (looking-at outline-regexp)))
27690 t) ; skip headlines
27691 (table.el-p t) ; skip table.el tables
27692 (table-p (org-table-align) t) ; align org-mode tables
27693 (t nil)))) ; call paragraph-fill
27695 ;; For reference, this is the default value of adaptive-fill-regexp
27696 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
27698 (defun org-adaptive-fill-function ()
27699 "Return a fill prefix for org-mode files.
27700 In particular, this makes sure hanging paragraphs for hand-formatted lists
27701 work correctly."
27702 (cond ((looking-at "#[ \t]+")
27703 (match-string 0))
27704 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
27705 (save-excursion
27706 (goto-char (match-end 0))
27707 (make-string (current-column) ?\ )))
27708 (t nil)))
27710 ;;;; Functions extending outline functionality
27713 (defun org-beginning-of-line (&optional arg)
27714 "Go to the beginning of the current line. If that is invisible, continue
27715 to a visible line beginning. This makes the function of C-a more intuitive.
27716 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27717 first attempt, and only move to after the tags when the cursor is already
27718 beyond the end of the headline."
27719 (interactive "P")
27720 (let ((pos (point)))
27721 (beginning-of-line 1)
27722 (if (bobp)
27724 (backward-char 1)
27725 (if (org-invisible-p)
27726 (while (and (not (bobp)) (org-invisible-p))
27727 (backward-char 1)
27728 (beginning-of-line 1))
27729 (forward-char 1)))
27730 (when org-special-ctrl-a/e
27731 (cond
27732 ((and (looking-at org-todo-line-regexp)
27733 (= (char-after (match-end 1)) ?\ ))
27734 (goto-char
27735 (if (eq org-special-ctrl-a/e t)
27736 (cond ((> pos (match-beginning 3)) (match-beginning 3))
27737 ((= pos (point)) (match-beginning 3))
27738 (t (point)))
27739 (cond ((> pos (point)) (point))
27740 ((not (eq last-command this-command)) (point))
27741 (t (match-beginning 3))))))
27742 ((org-at-item-p)
27743 (goto-char
27744 (if (eq org-special-ctrl-a/e t)
27745 (cond ((> pos (match-end 4)) (match-end 4))
27746 ((= pos (point)) (match-end 4))
27747 (t (point)))
27748 (cond ((> pos (point)) (point))
27749 ((not (eq last-command this-command)) (point))
27750 (t (match-end 4))))))))))
27752 (defun org-end-of-line (&optional arg)
27753 "Go to the end of the line.
27754 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27755 first attempt, and only move to after the tags when the cursor is already
27756 beyond the end of the headline."
27757 (interactive "P")
27758 (if (or (not org-special-ctrl-a/e)
27759 (not (org-on-heading-p)))
27760 (end-of-line arg)
27761 (let ((pos (point)))
27762 (beginning-of-line 1)
27763 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
27764 (if (eq org-special-ctrl-a/e t)
27765 (if (or (< pos (match-beginning 1))
27766 (= pos (match-end 0)))
27767 (goto-char (match-beginning 1))
27768 (goto-char (match-end 0)))
27769 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
27770 (goto-char (match-end 0))
27771 (goto-char (match-beginning 1))))
27772 (end-of-line arg)))))
27774 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
27775 (define-key org-mode-map "\C-e" 'org-end-of-line)
27777 (defun org-kill-line (&optional arg)
27778 "Kill line, to tags or end of line."
27779 (interactive "P")
27780 (cond
27781 ((or (not org-special-ctrl-k)
27782 (bolp)
27783 (not (org-on-heading-p)))
27784 (call-interactively 'kill-line))
27785 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
27786 (kill-region (point) (match-beginning 1))
27787 (org-set-tags nil t))
27788 (t (kill-region (point) (point-at-eol)))))
27790 (define-key org-mode-map "\C-k" 'org-kill-line)
27792 (defun org-invisible-p ()
27793 "Check if point is at a character currently not visible."
27794 ;; Early versions of noutline don't have `outline-invisible-p'.
27795 (if (fboundp 'outline-invisible-p)
27796 (outline-invisible-p)
27797 (get-char-property (point) 'invisible)))
27799 (defun org-invisible-p2 ()
27800 "Check if point is at a character currently not visible."
27801 (save-excursion
27802 (if (and (eolp) (not (bobp))) (backward-char 1))
27803 ;; Early versions of noutline don't have `outline-invisible-p'.
27804 (if (fboundp 'outline-invisible-p)
27805 (outline-invisible-p)
27806 (get-char-property (point) 'invisible))))
27808 (defalias 'org-back-to-heading 'outline-back-to-heading)
27809 (defalias 'org-on-heading-p 'outline-on-heading-p)
27810 (defalias 'org-at-heading-p 'outline-on-heading-p)
27811 (defun org-at-heading-or-item-p ()
27812 (or (org-on-heading-p) (org-at-item-p)))
27814 (defun org-on-target-p ()
27815 (or (org-in-regexp org-radio-target-regexp)
27816 (org-in-regexp org-target-regexp)))
27818 (defun org-up-heading-all (arg)
27819 "Move to the heading line of which the present line is a subheading.
27820 This function considers both visible and invisible heading lines.
27821 With argument, move up ARG levels."
27822 (if (fboundp 'outline-up-heading-all)
27823 (outline-up-heading-all arg) ; emacs 21 version of outline.el
27824 (outline-up-heading arg t))) ; emacs 22 version of outline.el
27826 (defun org-up-heading-safe ()
27827 "Move to the heading line of which the present line is a subheading.
27828 This version will not throw an error. It will return the level of the
27829 headline found, or nil if no higher level is found."
27830 (let ((pos (point)) start-level level
27831 (re (concat "^" outline-regexp)))
27832 (catch 'exit
27833 (outline-back-to-heading t)
27834 (setq start-level (funcall outline-level))
27835 (if (equal start-level 1) (throw 'exit nil))
27836 (while (re-search-backward re nil t)
27837 (setq level (funcall outline-level))
27838 (if (< level start-level) (throw 'exit level)))
27839 nil)))
27841 (defun org-first-sibling-p ()
27842 "Is this heading the first child of its parents?"
27843 (interactive)
27844 (let ((re (concat "^" outline-regexp))
27845 level l)
27846 (unless (org-at-heading-p t)
27847 (error "Not at a heading"))
27848 (setq level (funcall outline-level))
27849 (save-excursion
27850 (if (not (re-search-backward re nil t))
27852 (setq l (funcall outline-level))
27853 (< l level)))))
27855 (defun org-goto-sibling (&optional previous)
27856 "Goto the next sibling, even if it is invisible.
27857 When PREVIOUS is set, go to the previous sibling instead. Returns t
27858 when a sibling was found. When none is found, return nil and don't
27859 move point."
27860 (let ((fun (if previous 're-search-backward 're-search-forward))
27861 (pos (point))
27862 (re (concat "^" outline-regexp))
27863 level l)
27864 (when (condition-case nil (org-back-to-heading t) (error nil))
27865 (setq level (funcall outline-level))
27866 (catch 'exit
27867 (or previous (forward-char 1))
27868 (while (funcall fun re nil t)
27869 (setq l (funcall outline-level))
27870 (when (< l level) (goto-char pos) (throw 'exit nil))
27871 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
27872 (goto-char pos)
27873 nil))))
27875 (defun org-show-siblings ()
27876 "Show all siblings of the current headline."
27877 (save-excursion
27878 (while (org-goto-sibling) (org-flag-heading nil)))
27879 (save-excursion
27880 (while (org-goto-sibling 'previous)
27881 (org-flag-heading nil))))
27883 (defun org-show-hidden-entry ()
27884 "Show an entry where even the heading is hidden."
27885 (save-excursion
27886 (org-show-entry)))
27888 (defun org-flag-heading (flag &optional entry)
27889 "Flag the current heading. FLAG non-nil means make invisible.
27890 When ENTRY is non-nil, show the entire entry."
27891 (save-excursion
27892 (org-back-to-heading t)
27893 ;; Check if we should show the entire entry
27894 (if entry
27895 (progn
27896 (org-show-entry)
27897 (save-excursion
27898 (and (outline-next-heading)
27899 (org-flag-heading nil))))
27900 (outline-flag-region (max (point-min) (1- (point)))
27901 (save-excursion (outline-end-of-heading) (point))
27902 flag))))
27904 (defun org-end-of-subtree (&optional invisible-OK to-heading)
27905 ;; This is an exact copy of the original function, but it uses
27906 ;; `org-back-to-heading', to make it work also in invisible
27907 ;; trees. And is uses an invisible-OK argument.
27908 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
27909 (org-back-to-heading invisible-OK)
27910 (let ((first t)
27911 (level (funcall outline-level)))
27912 (while (and (not (eobp))
27913 (or first (> (funcall outline-level) level)))
27914 (setq first nil)
27915 (outline-next-heading))
27916 (unless to-heading
27917 (if (memq (preceding-char) '(?\n ?\^M))
27918 (progn
27919 ;; Go to end of line before heading
27920 (forward-char -1)
27921 (if (memq (preceding-char) '(?\n ?\^M))
27922 ;; leave blank line before heading
27923 (forward-char -1))))))
27924 (point))
27926 (defun org-show-subtree ()
27927 "Show everything after this heading at deeper levels."
27928 (outline-flag-region
27929 (point)
27930 (save-excursion
27931 (outline-end-of-subtree) (outline-next-heading) (point))
27932 nil))
27934 (defun org-show-entry ()
27935 "Show the body directly following this heading.
27936 Show the heading too, if it is currently invisible."
27937 (interactive)
27938 (save-excursion
27939 (condition-case nil
27940 (progn
27941 (org-back-to-heading t)
27942 (outline-flag-region
27943 (max (point-min) (1- (point)))
27944 (save-excursion
27945 (re-search-forward
27946 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
27947 (or (match-beginning 1) (point-max)))
27948 nil))
27949 (error nil))))
27951 (defun org-make-options-regexp (kwds)
27952 "Make a regular expression for keyword lines."
27953 (concat
27955 "#?[ \t]*\\+\\("
27956 (mapconcat 'regexp-quote kwds "\\|")
27957 "\\):[ \t]*"
27958 "\\(.+\\)"))
27960 ;; Make isearch reveal the necessary context
27961 (defun org-isearch-end ()
27962 "Reveal context after isearch exits."
27963 (when isearch-success ; only if search was successful
27964 (if (featurep 'xemacs)
27965 ;; Under XEmacs, the hook is run in the correct place,
27966 ;; we directly show the context.
27967 (org-show-context 'isearch)
27968 ;; In Emacs the hook runs *before* restoring the overlays.
27969 ;; So we have to use a one-time post-command-hook to do this.
27970 ;; (Emacs 22 has a special variable, see function `org-mode')
27971 (unless (and (boundp 'isearch-mode-end-hook-quit)
27972 isearch-mode-end-hook-quit)
27973 ;; Only when the isearch was not quitted.
27974 (org-add-hook 'post-command-hook 'org-isearch-post-command
27975 'append 'local)))))
27977 (defun org-isearch-post-command ()
27978 "Remove self from hook, and show context."
27979 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
27980 (org-show-context 'isearch))
27983 ;;;; Integration with and fixes for other packages
27985 ;;; Imenu support
27987 (defvar org-imenu-markers nil
27988 "All markers currently used by Imenu.")
27989 (make-variable-buffer-local 'org-imenu-markers)
27991 (defun org-imenu-new-marker (&optional pos)
27992 "Return a new marker for use by Imenu, and remember the marker."
27993 (let ((m (make-marker)))
27994 (move-marker m (or pos (point)))
27995 (push m org-imenu-markers)
27998 (defun org-imenu-get-tree ()
27999 "Produce the index for Imenu."
28000 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
28001 (setq org-imenu-markers nil)
28002 (let* ((n org-imenu-depth)
28003 (re (concat "^" outline-regexp))
28004 (subs (make-vector (1+ n) nil))
28005 (last-level 0)
28006 m tree level head)
28007 (save-excursion
28008 (save-restriction
28009 (widen)
28010 (goto-char (point-max))
28011 (while (re-search-backward re nil t)
28012 (setq level (org-reduced-level (funcall outline-level)))
28013 (when (<= level n)
28014 (looking-at org-complex-heading-regexp)
28015 (setq head (org-match-string-no-properties 4)
28016 m (org-imenu-new-marker))
28017 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
28018 (if (>= level last-level)
28019 (push (cons head m) (aref subs level))
28020 (push (cons head (aref subs (1+ level))) (aref subs level))
28021 (loop for i from (1+ level) to n do (aset subs i nil)))
28022 (setq last-level level)))))
28023 (aref subs 1)))
28025 (eval-after-load "imenu"
28026 '(progn
28027 (add-hook 'imenu-after-jump-hook
28028 (lambda () (org-show-context 'org-goto)))))
28030 ;; Speedbar support
28032 (defun org-speedbar-set-agenda-restriction ()
28033 "Restrict future agenda commands to the location at point in speedbar.
28034 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
28035 (interactive)
28036 (let (p m tp np dir txt w)
28037 (cond
28038 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28039 'org-imenu t))
28040 (setq m (get-text-property p 'org-imenu-marker))
28041 (save-excursion
28042 (save-restriction
28043 (set-buffer (marker-buffer m))
28044 (goto-char m)
28045 (org-agenda-set-restriction-lock 'subtree))))
28046 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28047 'speedbar-function 'speedbar-find-file))
28048 (setq tp (previous-single-property-change
28049 (1+ p) 'speedbar-function)
28050 np (next-single-property-change
28051 tp 'speedbar-function)
28052 dir (speedbar-line-directory)
28053 txt (buffer-substring-no-properties (or tp (point-min))
28054 (or np (point-max))))
28055 (save-excursion
28056 (save-restriction
28057 (set-buffer (find-file-noselect
28058 (let ((default-directory dir))
28059 (expand-file-name txt))))
28060 (unless (org-mode-p)
28061 (error "Cannot restrict to non-Org-mode file"))
28062 (org-agenda-set-restriction-lock 'file))))
28063 (t (error "Don't know how to restrict Org-mode's agenda")))
28064 (org-move-overlay org-speedbar-restriction-lock-overlay
28065 (point-at-bol) (point-at-eol))
28066 (setq current-prefix-arg nil)
28067 (org-agenda-maybe-redo)))
28069 (eval-after-load "speedbar"
28070 '(progn
28071 (speedbar-add-supported-extension ".org")
28072 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
28073 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
28074 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
28075 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
28076 (add-hook 'speedbar-visiting-tag-hook
28077 (lambda () (org-show-context 'org-goto)))))
28080 ;;; Fixes and Hacks
28082 ;; Make flyspell not check words in links, to not mess up our keymap
28083 (defun org-mode-flyspell-verify ()
28084 "Don't let flyspell put overlays at active buttons."
28085 (not (get-text-property (point) 'keymap)))
28087 ;; Make `bookmark-jump' show the jump location if it was hidden.
28088 (eval-after-load "bookmark"
28089 '(if (boundp 'bookmark-after-jump-hook)
28090 ;; We can use the hook
28091 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
28092 ;; Hook not available, use advice
28093 (defadvice bookmark-jump (after org-make-visible activate)
28094 "Make the position visible."
28095 (org-bookmark-jump-unhide))))
28097 (defun org-bookmark-jump-unhide ()
28098 "Unhide the current position, to show the bookmark location."
28099 (and (org-mode-p)
28100 (or (org-invisible-p)
28101 (save-excursion (goto-char (max (point-min) (1- (point))))
28102 (org-invisible-p)))
28103 (org-show-context 'bookmark-jump)))
28105 ;; Fix a bug in htmlize where there are text properties (face nil)
28106 (eval-after-load "htmlize"
28107 '(progn
28108 (defadvice htmlize-faces-in-buffer (after org-no-nil-faces activate)
28109 "Make sure there are no nil faces"
28110 (setq ad-return-value (delq nil ad-return-value)))))
28112 ;; Make session.el ignore our circular variable
28113 (eval-after-load "session"
28114 '(add-to-list 'session-globals-exclude 'org-mark-ring))
28116 ;;;; Experimental code
28118 (defun org-closed-in-range ()
28119 "Sparse tree of items closed in a certain time range.
28120 Still experimental, may disappear in the future."
28121 (interactive)
28122 ;; Get the time interval from the user.
28123 (let* ((time1 (time-to-seconds
28124 (org-read-date nil 'to-time nil "Starting date: ")))
28125 (time2 (time-to-seconds
28126 (org-read-date nil 'to-time nil "End date:")))
28127 ;; callback function
28128 (callback (lambda ()
28129 (let ((time
28130 (time-to-seconds
28131 (apply 'encode-time
28132 (org-parse-time-string
28133 (match-string 1))))))
28134 ;; check if time in interval
28135 (and (>= time time1) (<= time time2))))))
28136 ;; make tree, check each match with the callback
28137 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
28139 ;;;; Finish up
28141 (provide 'org)
28143 (run-hooks 'org-load-hook)
28145 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
28146 ;;; org.el ends here