Make sure properties mentioned in COLUMNS will be offered for completion.
[org-mode.git] / org.el
blobf4cffdcd34a53ed32113dd9e0e60b1145fddff38
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;; Version: 5.21
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 3, or (at your option)
15 ;; any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;;; Commentary:
30 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
31 ;; project planning with a fast and effective plain-text system.
33 ;; Org-mode develops organizational tasks around NOTES files that contain
34 ;; information about projects as plain text. Org-mode is implemented on
35 ;; top of outline-mode, which makes it possible to keep the content of
36 ;; large files well structured. Visibility cycling and structure editing
37 ;; help to work with the tree. Tables are easily created with a built-in
38 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
39 ;; and scheduling. It dynamically compiles entries into an agenda that
40 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
41 ;; Plain text URL-like links connect to websites, emails, Usenet
42 ;; messages, BBDB entries, and any files related to the projects. For
43 ;; printing and sharing of notes, an Org-mode file can be exported as a
44 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
45 ;; iCalendar file. It can also serve as a publishing tool for a set of
46 ;; linked webpages.
48 ;; Installation and Activation
49 ;; ---------------------------
50 ;; See the corresponding sections in the manual at
52 ;; http://orgmode.org/org.html#Installation
54 ;; Documentation
55 ;; -------------
56 ;; The documentation of Org-mode can be found in the TeXInfo file. The
57 ;; distribution also contains a PDF version of it. At the homepage of
58 ;; Org-mode, you can read the same text online as HTML. There is also an
59 ;; excellent reference card made by Philip Rooke. This card can be found
60 ;; in the etc/ directory of Emacs 22.
62 ;; A list of recent changes can be found at
63 ;; http://orgmode.org/Changes.html
65 ;;; Code:
67 ;;;; Require other packages
69 (eval-when-compile
70 (require 'cl)
71 (require 'gnus-sum)
72 (require 'calendar))
73 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
74 ;; the file noutline.el being loaded.
75 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
76 ;; We require noutline, which might be provided in outline.el
77 (require 'outline) (require 'noutline)
78 ;; Other stuff we need.
79 (require 'time-date)
80 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
81 (require 'easymenu)
83 ;;;; Customization variables
85 ;;; Version
87 (defconst org-version "5.21"
88 "The version number of the file org.el.")
90 (defun org-version (&optional here)
91 "Show the org-mode version in the echo area.
92 With prefix arg HERE, insert it at point."
93 (interactive "P")
94 (let ((version (format "Org-mode version %s" org-version)))
95 (message version)
96 (if here
97 (insert version))))
99 ;;; Compatibility constants
100 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
101 (defconst org-format-transports-properties-p
102 (let ((x "a"))
103 (add-text-properties 0 1 '(test t) x)
104 (get-text-property 0 'test (format "%s" x)))
105 "Does format transport text properties?")
107 (defmacro org-bound-and-true-p (var)
108 "Return the value of symbol VAR if it is bound, else nil."
109 `(and (boundp (quote ,var)) ,var))
111 (defmacro org-unmodified (&rest body)
112 "Execute body without changing `buffer-modified-p'."
113 `(set-buffer-modified-p
114 (prog1 (buffer-modified-p) ,@body)))
116 (defmacro org-re (s)
117 "Replace posix classes in regular expression."
118 (if (featurep 'xemacs)
119 (let ((ss s))
120 (save-match-data
121 (while (string-match "\\[:alnum:\\]" ss)
122 (setq ss (replace-match "a-zA-Z0-9" t t ss)))
123 (while (string-match "\\[:alpha:\\]" ss)
124 (setq ss (replace-match "a-zA-Z" t t ss)))
125 ss))
128 (defmacro org-preserve-lc (&rest body)
129 `(let ((_line (org-current-line))
130 (_col (current-column)))
131 (unwind-protect
132 (progn ,@body)
133 (goto-line _line)
134 (move-to-column _col))))
136 (defmacro org-without-partial-completion (&rest body)
137 `(let ((pc-mode (and (boundp 'partial-completion-mode)
138 partial-completion-mode)))
139 (unwind-protect
140 (progn
141 (if pc-mode (partial-completion-mode -1))
142 ,@body)
143 (if pc-mode (partial-completion-mode 1)))))
145 ;;; The custom variables
147 (defgroup org nil
148 "Outline-based notes management and organizer."
149 :tag "Org"
150 :group 'outlines
151 :group 'hypermedia
152 :group 'calendar)
154 ;; FIXME: Needs a separate group...
155 (defcustom org-completion-fallback-command 'hippie-expand
156 "The expansion command called by \\[org-complete] in normal context.
157 Normal means, no org-mode-specific context."
158 :group 'org
159 :type 'function)
161 (defgroup org-startup nil
162 "Options concerning startup of Org-mode."
163 :tag "Org Startup"
164 :group 'org)
166 (defcustom org-startup-folded t
167 "Non-nil means, entering Org-mode will switch to OVERVIEW.
168 This can also be configured on a per-file basis by adding one of
169 the following lines anywhere in the buffer:
171 #+STARTUP: fold
172 #+STARTUP: nofold
173 #+STARTUP: content"
174 :group 'org-startup
175 :type '(choice
176 (const :tag "nofold: show all" nil)
177 (const :tag "fold: overview" t)
178 (const :tag "content: all headlines" content)))
180 (defcustom org-startup-truncated t
181 "Non-nil means, entering Org-mode will set `truncate-lines'.
182 This is useful since some lines containing links can be very long and
183 uninteresting. Also tables look terrible when wrapped."
184 :group 'org-startup
185 :type 'boolean)
187 (defcustom org-startup-align-all-tables nil
188 "Non-nil means, align all tables when visiting a file.
189 This is useful when the column width in tables is forced with <N> cookies
190 in table fields. Such tables will look correct only after the first re-align.
191 This can also be configured on a per-file basis by adding one of
192 the following lines anywhere in the buffer:
193 #+STARTUP: align
194 #+STARTUP: noalign"
195 :group 'org-startup
196 :type 'boolean)
198 (defcustom org-insert-mode-line-in-empty-file nil
199 "Non-nil means insert the first line setting Org-mode in empty files.
200 When the function `org-mode' is called interactively in an empty file, this
201 normally means that the file name does not automatically trigger Org-mode.
202 To ensure that the file will always be in Org-mode in the future, a
203 line enforcing Org-mode will be inserted into the buffer, if this option
204 has been set."
205 :group 'org-startup
206 :type 'boolean)
208 (defcustom org-replace-disputed-keys nil
209 "Non-nil means use alternative key bindings for some keys.
210 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
211 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
212 If you want to use Org-mode together with one of these other modes,
213 or more generally if you would like to move some Org-mode commands to
214 other keys, set this variable and configure the keys with the variable
215 `org-disputed-keys'.
217 This option is only relevant at load-time of Org-mode, and must be set
218 *before* org.el is loaded. Changing it requires a restart of Emacs to
219 become effective."
220 :group 'org-startup
221 :type 'boolean)
223 (if (fboundp 'defvaralias)
224 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
226 (defcustom org-disputed-keys
227 '(([(shift up)] . [(meta p)])
228 ([(shift down)] . [(meta n)])
229 ([(shift left)] . [(meta -)])
230 ([(shift right)] . [(meta +)])
231 ([(control shift right)] . [(meta shift +)])
232 ([(control shift left)] . [(meta shift -)]))
233 "Keys for which Org-mode and other modes compete.
234 This is an alist, cars are the default keys, second element specifies
235 the alternative to use when `org-replace-disputed-keys' is t.
237 Keys can be specified in any syntax supported by `define-key'.
238 The value of this option takes effect only at Org-mode's startup,
239 therefore you'll have to restart Emacs to apply it after changing."
240 :group 'org-startup
241 :type 'alist)
243 (defun org-key (key)
244 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
245 Or return the original if not disputed."
246 (if org-replace-disputed-keys
247 (let* ((nkey (key-description key))
248 (x (org-find-if (lambda (x)
249 (equal (key-description (car x)) nkey))
250 org-disputed-keys)))
251 (if x (cdr x) key))
252 key))
254 (defun org-find-if (predicate seq)
255 (catch 'exit
256 (while seq
257 (if (funcall predicate (car seq))
258 (throw 'exit (car seq))
259 (pop seq)))))
261 (defun org-defkey (keymap key def)
262 "Define a key, possibly translated, as returned by `org-key'."
263 (define-key keymap (org-key key) def))
265 (defcustom org-ellipsis nil
266 "The ellipsis to use in the Org-mode outline.
267 When nil, just use the standard three dots. When a string, use that instead,
268 When a face, use the standart 3 dots, but with the specified face.
269 The change affects only Org-mode (which will then use its own display table).
270 Changing this requires executing `M-x org-mode' in a buffer to become
271 effective."
272 :group 'org-startup
273 :type '(choice (const :tag "Default" nil)
274 (face :tag "Face" :value org-warning)
275 (string :tag "String" :value "...#")))
277 (defvar org-display-table nil
278 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
280 (defgroup org-keywords nil
281 "Keywords in Org-mode."
282 :tag "Org Keywords"
283 :group 'org)
285 (defcustom org-deadline-string "DEADLINE:"
286 "String to mark deadline entries.
287 A deadline is this string, followed by a time stamp. Should be a word,
288 terminated by a colon. You can insert a schedule keyword and
289 a timestamp with \\[org-deadline].
290 Changes become only effective after restarting Emacs."
291 :group 'org-keywords
292 :type 'string)
294 (defcustom org-scheduled-string "SCHEDULED:"
295 "String to mark scheduled TODO entries.
296 A schedule is this string, followed by a time stamp. Should be a word,
297 terminated by a colon. You can insert a schedule keyword and
298 a timestamp with \\[org-schedule].
299 Changes become only effective after restarting Emacs."
300 :group 'org-keywords
301 :type 'string)
303 (defcustom org-closed-string "CLOSED:"
304 "String used as the prefix for timestamps logging closing a TODO entry."
305 :group 'org-keywords
306 :type 'string)
308 (defcustom org-clock-string "CLOCK:"
309 "String used as prefix for timestamps clocking work hours on an item."
310 :group 'org-keywords
311 :type 'string)
313 (defcustom org-comment-string "COMMENT"
314 "Entries starting with this keyword will never be exported.
315 An entry can be toggled between COMMENT and normal with
316 \\[org-toggle-comment].
317 Changes become only effective after restarting Emacs."
318 :group 'org-keywords
319 :type 'string)
321 (defcustom org-quote-string "QUOTE"
322 "Entries starting with this keyword will be exported in fixed-width font.
323 Quoting applies only to the text in the entry following the headline, and does
324 not extend beyond the next headline, even if that is lower level.
325 An entry can be toggled between QUOTE and normal with
326 \\[org-toggle-fixed-width-section]."
327 :group 'org-keywords
328 :type 'string)
330 (defconst org-repeat-re
331 ; (concat "\\(?:\\<\\(?:" org-scheduled-string "\\|" org-deadline-string "\\)"
332 ; " +<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\)\\(\\+[0-9]+[dwmy]\\)")
333 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\(\\+[0-9]+[dwmy]\\)"
334 "Regular expression for specifying repeated events.
335 After a match, group 1 contains the repeat expression.")
337 (defgroup org-structure nil
338 "Options concerning the general structure of Org-mode files."
339 :tag "Org Structure"
340 :group 'org)
342 (defgroup org-reveal-location nil
343 "Options about how to make context of a location visible."
344 :tag "Org Reveal Location"
345 :group 'org-structure)
347 (defconst org-context-choice
348 '(choice
349 (const :tag "Always" t)
350 (const :tag "Never" nil)
351 (repeat :greedy t :tag "Individual contexts"
352 (cons
353 (choice :tag "Context"
354 (const agenda)
355 (const org-goto)
356 (const occur-tree)
357 (const tags-tree)
358 (const link-search)
359 (const mark-goto)
360 (const bookmark-jump)
361 (const isearch)
362 (const default))
363 (boolean))))
364 "Contexts for the reveal options.")
366 (defcustom org-show-hierarchy-above '((default . t))
367 "Non-nil means, show full hierarchy when revealing a location.
368 Org-mode often shows locations in an org-mode file which might have
369 been invisible before. When this is set, the hierarchy of headings
370 above the exposed location is shown.
371 Turning this off for example for sparse trees makes them very compact.
372 Instead of t, this can also be an alist specifying this option for different
373 contexts. Valid contexts are
374 agenda when exposing an entry from the agenda
375 org-goto when using the command `org-goto' on key C-c C-j
376 occur-tree when using the command `org-occur' on key C-c /
377 tags-tree when constructing a sparse tree based on tags matches
378 link-search when exposing search matches associated with a link
379 mark-goto when exposing the jump goal of a mark
380 bookmark-jump when exposing a bookmark location
381 isearch when exiting from an incremental search
382 default default for all contexts not set explicitly"
383 :group 'org-reveal-location
384 :type org-context-choice)
386 (defcustom org-show-following-heading '((default . nil))
387 "Non-nil means, show following heading when revealing a location.
388 Org-mode often shows locations in an org-mode file which might have
389 been invisible before. When this is set, the heading following the
390 match is shown.
391 Turning this off for example for sparse trees makes them very compact,
392 but makes it harder to edit the location of the match. In such a case,
393 use the command \\[org-reveal] to show more context.
394 Instead of t, this can also be an alist specifying this option for different
395 contexts. See `org-show-hierarchy-above' for valid contexts."
396 :group 'org-reveal-location
397 :type org-context-choice)
399 (defcustom org-show-siblings '((default . nil) (isearch t))
400 "Non-nil means, show all sibling heading when revealing a location.
401 Org-mode often shows locations in an org-mode file which might have
402 been invisible before. When this is set, the sibling of the current entry
403 heading are all made visible. If `org-show-hierarchy-above' is t,
404 the same happens on each level of the hierarchy above the current entry.
406 By default this is on for the isearch context, off for all other contexts.
407 Turning this off for example for sparse trees makes them very compact,
408 but makes it harder to edit the location of the match. In such a case,
409 use the command \\[org-reveal] to show more context.
410 Instead of t, this can also be an alist specifying this option for different
411 contexts. See `org-show-hierarchy-above' for valid contexts."
412 :group 'org-reveal-location
413 :type org-context-choice)
415 (defcustom org-show-entry-below '((default . nil))
416 "Non-nil means, show the entry below a headline when revealing a location.
417 Org-mode often shows locations in an org-mode file which might have
418 been invisible before. When this is set, the text below the headline that is
419 exposed is also shown.
421 By default this is off for all contexts.
422 Instead of t, this can also be an alist specifying this option for different
423 contexts. See `org-show-hierarchy-above' for valid contexts."
424 :group 'org-reveal-location
425 :type org-context-choice)
427 (defgroup org-cycle nil
428 "Options concerning visibility cycling in Org-mode."
429 :tag "Org Cycle"
430 :group 'org-structure)
432 (defcustom org-drawers '("PROPERTIES" "CLOCK")
433 "Names of drawers. Drawers are not opened by cycling on the headline above.
434 Drawers only open with a TAB on the drawer line itself. A drawer looks like
435 this:
436 :DRAWERNAME:
437 .....
438 :END:
439 The drawer \"PROPERTIES\" is special for capturing properties through
440 the property API.
442 Drawers can be defined on the per-file basis with a line like:
444 #+DRAWERS: HIDDEN STATE PROPERTIES"
445 :group 'org-structure
446 :type '(repeat (string :tag "Drawer Name")))
448 (defcustom org-cycle-global-at-bob nil
449 "Cycle globally if cursor is at beginning of buffer and not at a headline.
450 This makes it possible to do global cycling without having to use S-TAB or
451 C-u TAB. For this special case to work, the first line of the buffer
452 must not be a headline - it may be empty ot some other text. When used in
453 this way, `org-cycle-hook' is disables temporarily, to make sure the
454 cursor stays at the beginning of the buffer.
455 When this option is nil, don't do anything special at the beginning
456 of the buffer."
457 :group 'org-cycle
458 :type 'boolean)
460 (defcustom org-cycle-emulate-tab t
461 "Where should `org-cycle' emulate TAB.
462 nil Never
463 white Only in completely white lines
464 whitestart Only at the beginning of lines, before the first non-white char
465 t Everywhere except in headlines
466 exc-hl-bol Everywhere except at the start of a headline
467 If TAB is used in a place where it does not emulate TAB, the current subtree
468 visibility is cycled."
469 :group 'org-cycle
470 :type '(choice (const :tag "Never" nil)
471 (const :tag "Only in completely white lines" white)
472 (const :tag "Before first char in a line" whitestart)
473 (const :tag "Everywhere except in headlines" t)
474 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
477 (defcustom org-cycle-separator-lines 2
478 "Number of empty lines needed to keep an empty line between collapsed trees.
479 If you leave an empty line between the end of a subtree and the following
480 headline, this empty line is hidden when the subtree is folded.
481 Org-mode will leave (exactly) one empty line visible if the number of
482 empty lines is equal or larger to the number given in this variable.
483 So the default 2 means, at least 2 empty lines after the end of a subtree
484 are needed to produce free space between a collapsed subtree and the
485 following headline.
487 Special case: when 0, never leave empty lines in collapsed view."
488 :group 'org-cycle
489 :type 'integer)
491 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
492 org-cycle-hide-drawers
493 org-cycle-show-empty-lines
494 org-optimize-window-after-visibility-change)
495 "Hook that is run after `org-cycle' has changed the buffer visibility.
496 The function(s) in this hook must accept a single argument which indicates
497 the new state that was set by the most recent `org-cycle' command. The
498 argument is a symbol. After a global state change, it can have the values
499 `overview', `content', or `all'. After a local state change, it can have
500 the values `folded', `children', or `subtree'."
501 :group 'org-cycle
502 :type 'hook)
504 (defgroup org-edit-structure nil
505 "Options concerning structure editing in Org-mode."
506 :tag "Org Edit Structure"
507 :group 'org-structure)
509 (defcustom org-special-ctrl-a/e nil
510 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
511 When t, `C-a' will bring back the cursor to the beginning of the
512 headline text, i.e. after the stars and after a possible TODO keyword.
513 In an item, this will be the position after the bullet.
514 When the cursor is already at that position, another `C-a' will bring
515 it to the beginning of the line.
516 `C-e' will jump to the end of the headline, ignoring the presence of tags
517 in the headline. A second `C-e' will then jump to the true end of the
518 line, after any tags.
519 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
520 and only a directly following, identical keypress will bring the cursor
521 to the special positions."
522 :group 'org-edit-structure
523 :type '(choice
524 (const :tag "off" nil)
525 (const :tag "after bullet first" t)
526 (const :tag "border first" reversed)))
528 (if (fboundp 'defvaralias)
529 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
531 (defcustom org-special-ctrl-k nil
532 "Non-nil means `C-k' will behave specially in headlines.
533 When nil, `C-k' will call the default `kill-line' command.
534 When t, the following will happen while the cursor is in the headline:
536 - When the cursor is at the beginning of a headline, kill the entire
537 line and possible the folded subtree below the line.
538 - When in the middle of the headline text, kill the headline up to the tags.
539 - When after the headline text, kill the tags."
540 :group 'org-edit-structure
541 :type 'boolean)
543 (defcustom org-odd-levels-only nil
544 "Non-nil means, skip even levels and only use odd levels for the outline.
545 This has the effect that two stars are being added/taken away in
546 promotion/demotion commands. It also influences how levels are
547 handled by the exporters.
548 Changing it requires restart of `font-lock-mode' to become effective
549 for fontification also in regions already fontified.
550 You may also set this on a per-file basis by adding one of the following
551 lines to the buffer:
553 #+STARTUP: odd
554 #+STARTUP: oddeven"
555 :group 'org-edit-structure
556 :group 'org-font-lock
557 :type 'boolean)
559 (defcustom org-adapt-indentation t
560 "Non-nil means, adapt indentation when promoting and demoting.
561 When this is set and the *entire* text in an entry is indented, the
562 indentation is increased by one space in a demotion command, and
563 decreased by one in a promotion command. If any line in the entry
564 body starts at column 0, indentation is not changed at all."
565 :group 'org-edit-structure
566 :type 'boolean)
568 (defcustom org-blank-before-new-entry '((heading . nil)
569 (plain-list-item . nil))
570 "Should `org-insert-heading' leave a blank line before new heading/item?
571 The value is an alist, with `heading' and `plain-list-item' as car,
572 and a boolean flag as cdr."
573 :group 'org-edit-structure
574 :type '(list
575 (cons (const heading) (boolean))
576 (cons (const plain-list-item) (boolean))))
578 (defcustom org-insert-heading-hook nil
579 "Hook being run after inserting a new heading."
580 :group 'org-edit-structure
581 :type 'hook)
583 (defcustom org-enable-fixed-width-editor t
584 "Non-nil means, lines starting with \":\" are treated as fixed-width.
585 This currently only means, they are never auto-wrapped.
586 When nil, such lines will be treated like ordinary lines.
587 See also the QUOTE keyword."
588 :group 'org-edit-structure
589 :type 'boolean)
591 (defcustom org-goto-auto-isearch t
592 "Non-nil means, typing characters in org-goto starts incremental search."
593 :group 'org-edit-structure
594 :type 'boolean)
596 (defgroup org-sparse-trees nil
597 "Options concerning sparse trees in Org-mode."
598 :tag "Org Sparse Trees"
599 :group 'org-structure)
601 (defcustom org-highlight-sparse-tree-matches t
602 "Non-nil means, highlight all matches that define a sparse tree.
603 The highlights will automatically disappear the next time the buffer is
604 changed by an edit command."
605 :group 'org-sparse-trees
606 :type 'boolean)
608 (defcustom org-remove-highlights-with-change t
609 "Non-nil means, any change to the buffer will remove temporary highlights.
610 Such highlights are created by `org-occur' and `org-clock-display'.
611 When nil, `C-c C-c needs to be used to get rid of the highlights.
612 The highlights created by `org-preview-latex-fragment' always need
613 `C-c C-c' to be removed."
614 :group 'org-sparse-trees
615 :group 'org-time
616 :type 'boolean)
619 (defcustom org-occur-hook '(org-first-headline-recenter)
620 "Hook that is run after `org-occur' has constructed a sparse tree.
621 This can be used to recenter the window to show as much of the structure
622 as possible."
623 :group 'org-sparse-trees
624 :type 'hook)
626 (defgroup org-plain-lists nil
627 "Options concerning plain lists in Org-mode."
628 :tag "Org Plain lists"
629 :group 'org-structure)
631 (defcustom org-cycle-include-plain-lists nil
632 "Non-nil means, include plain lists into visibility cycling.
633 This means that during cycling, plain list items will *temporarily* be
634 interpreted as outline headlines with a level given by 1000+i where i is the
635 indentation of the bullet. In all other operations, plain list items are
636 not seen as headlines. For example, you cannot assign a TODO keyword to
637 such an item."
638 :group 'org-plain-lists
639 :type 'boolean)
641 (defcustom org-plain-list-ordered-item-terminator t
642 "The character that makes a line with leading number an ordered list item.
643 Valid values are ?. and ?\). To get both terminators, use t. While
644 ?. may look nicer, it creates the danger that a line with leading
645 number may be incorrectly interpreted as an item. ?\) therefore is
646 the safe choice."
647 :group 'org-plain-lists
648 :type '(choice (const :tag "dot like in \"2.\"" ?.)
649 (const :tag "paren like in \"2)\"" ?\))
650 (const :tab "both" t)))
652 (defcustom org-auto-renumber-ordered-lists t
653 "Non-nil means, automatically renumber ordered plain lists.
654 Renumbering happens when the sequence have been changed with
655 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
656 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
657 :group 'org-plain-lists
658 :type 'boolean)
660 (defcustom org-provide-checkbox-statistics t
661 "Non-nil means, update checkbox statistics after insert and toggle.
662 When this is set, checkbox statistics is updated each time you either insert
663 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
664 with \\[org-ctrl-c-ctrl-c\\]."
665 :group 'org-plain-lists
666 :type 'boolean)
668 (defgroup org-archive nil
669 "Options concerning archiving in Org-mode."
670 :tag "Org Archive"
671 :group 'org-structure)
673 (defcustom org-archive-tag "ARCHIVE"
674 "The tag that marks a subtree as archived.
675 An archived subtree does not open during visibility cycling, and does
676 not contribute to the agenda listings.
677 After changing this, font-lock must be restarted in the relevant buffers to
678 get the proper fontification."
679 :group 'org-archive
680 :group 'org-keywords
681 :type 'string)
683 (defcustom org-agenda-skip-archived-trees t
684 "Non-nil means, the agenda will skip any items located in archived trees.
685 An archived tree is a tree marked with the tag ARCHIVE."
686 :group 'org-archive
687 :group 'org-agenda-skip
688 :type 'boolean)
690 (defcustom org-cycle-open-archived-trees nil
691 "Non-nil means, `org-cycle' will open archived trees.
692 An archived tree is a tree marked with the tag ARCHIVE.
693 When nil, archived trees will stay folded. You can still open them with
694 normal outline commands like `show-all', but not with the cycling commands."
695 :group 'org-archive
696 :group 'org-cycle
697 :type 'boolean)
699 (defcustom org-sparse-tree-open-archived-trees nil
700 "Non-nil means sparse tree construction shows matches in archived trees.
701 When nil, matches in these trees are highlighted, but the trees are kept in
702 collapsed state."
703 :group 'org-archive
704 :group 'org-sparse-trees
705 :type 'boolean)
707 (defcustom org-archive-location "%s_archive::"
708 "The location where subtrees should be archived.
709 This string consists of two parts, separated by a double-colon.
711 The first part is a file name - when omitted, archiving happens in the same
712 file. %s will be replaced by the current file name (without directory part).
713 Archiving to a different file is useful to keep archived entries from
714 contributing to the Org-mode Agenda.
716 The part after the double colon is a headline. The archived entries will be
717 filed under that headline. When omitted, the subtrees are simply filed away
718 at the end of the file, as top-level entries.
720 Here are a few examples:
721 \"%s_archive::\"
722 If the current file is Projects.org, archive in file
723 Projects.org_archive, as top-level trees. This is the default.
725 \"::* Archived Tasks\"
726 Archive in the current file, under the top-level headline
727 \"* Archived Tasks\".
729 \"~/org/archive.org::\"
730 Archive in file ~/org/archive.org (absolute path), as top-level trees.
732 \"basement::** Finished Tasks\"
733 Archive in file ./basement (relative path), as level 3 trees
734 below the level 2 heading \"** Finished Tasks\".
736 You may set this option on a per-file basis by adding to the buffer a
737 line like
739 #+ARCHIVE: basement::** Finished Tasks"
740 :group 'org-archive
741 :type 'string)
743 (defcustom org-archive-mark-done t
744 "Non-nil means, mark entries as DONE when they are moved to the archive file.
745 This can be a string to set the keyword to use. When t, Org-mode will
746 use the first keyword in its list that means done."
747 :group 'org-archive
748 :type '(choice
749 (const :tag "No" nil)
750 (const :tag "Yes" t)
751 (string :tag "Use this keyword")))
753 (defcustom org-archive-stamp-time t
754 "Non-nil means, add a time stamp to entries moved to an archive file.
755 This variable is obsolete and has no effect anymore, instead add ot remove
756 `time' from the variablle `org-archive-save-context-info'."
757 :group 'org-archive
758 :type 'boolean)
760 (defcustom org-archive-save-context-info '(time file olpath category todo itags)
761 "Parts of context info that should be stored as properties when archiving.
762 When a subtree is moved to an archive file, it looses information given by
763 context, like inherited tags, the category, and possibly also the TODO
764 state (depending on the variable `org-archive-mark-done').
765 This variable can be a list of any of the following symbols:
767 time The time of archiving.
768 file The file where the entry originates.
769 itags The local tags, in the headline of the subtree.
770 ltags The tags the subtree inherits from further up the hierarchy.
771 todo The pre-archive TODO state.
772 category The category, taken from file name or #+CATEGORY lines.
773 olpath The outline path to the item. These are all headlines above
774 the current item, separated by /, like a file path.
776 For each symbol present in the list, a property will be created in
777 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
778 information."
779 :group 'org-archive
780 :type '(set :greedy t
781 (const :tag "Time" time)
782 (const :tag "File" file)
783 (const :tag "Category" category)
784 (const :tag "TODO state" todo)
785 (const :tag "TODO state" priority)
786 (const :tag "Inherited tags" itags)
787 (const :tag "Outline path" olpath)
788 (const :tag "Local tags" ltags)))
790 (defgroup org-imenu-and-speedbar nil
791 "Options concerning imenu and speedbar in Org-mode."
792 :tag "Org Imenu and Speedbar"
793 :group 'org-structure)
795 (defcustom org-imenu-depth 2
796 "The maximum level for Imenu access to Org-mode headlines.
797 This also applied for speedbar access."
798 :group 'org-imenu-and-speedbar
799 :type 'number)
801 (defgroup org-table nil
802 "Options concerning tables in Org-mode."
803 :tag "Org Table"
804 :group 'org)
806 (defcustom org-enable-table-editor 'optimized
807 "Non-nil means, lines starting with \"|\" are handled by the table editor.
808 When nil, such lines will be treated like ordinary lines.
810 When equal to the symbol `optimized', the table editor will be optimized to
811 do the following:
812 - Automatic overwrite mode in front of whitespace in table fields.
813 This makes the structure of the table stay in tact as long as the edited
814 field does not exceed the column width.
815 - Minimize the number of realigns. Normally, the table is aligned each time
816 TAB or RET are pressed to move to another field. With optimization this
817 happens only if changes to a field might have changed the column width.
818 Optimization requires replacing the functions `self-insert-command',
819 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
820 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
821 very good at guessing when a re-align will be necessary, but you can always
822 force one with \\[org-ctrl-c-ctrl-c].
824 If you would like to use the optimized version in Org-mode, but the
825 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
827 This variable can be used to turn on and off the table editor during a session,
828 but in order to toggle optimization, a restart is required.
830 See also the variable `org-table-auto-blank-field'."
831 :group 'org-table
832 :type '(choice
833 (const :tag "off" nil)
834 (const :tag "on" t)
835 (const :tag "on, optimized" optimized)))
837 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
838 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
839 In the optimized version, the table editor takes over all simple keys that
840 normally just insert a character. In tables, the characters are inserted
841 in a way to minimize disturbing the table structure (i.e. in overwrite mode
842 for empty fields). Outside tables, the correct binding of the keys is
843 restored.
845 The default for this option is t if the optimized version is also used in
846 Org-mode. See the variable `org-enable-table-editor' for details. Changing
847 this variable requires a restart of Emacs to become effective."
848 :group 'org-table
849 :type 'boolean)
851 (defcustom orgtbl-radio-table-templates
852 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
853 % END RECEIVE ORGTBL %n
854 \\begin{comment}
855 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
856 | | |
857 \\end{comment}\n")
858 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
859 @c END RECEIVE ORGTBL %n
860 @ignore
861 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
862 | | |
863 @end ignore\n")
864 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
865 <!-- END RECEIVE ORGTBL %n -->
866 <!--
867 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
868 | | |
869 -->\n"))
870 "Templates for radio tables in different major modes.
871 All occurrences of %n in a template will be replaced with the name of the
872 table, obtained by prompting the user."
873 :group 'org-table
874 :type '(repeat
875 (list (symbol :tag "Major mode")
876 (string :tag "Format"))))
878 (defgroup org-table-settings nil
879 "Settings for tables in Org-mode."
880 :tag "Org Table Settings"
881 :group 'org-table)
883 (defcustom org-table-default-size "5x2"
884 "The default size for newly created tables, Columns x Rows."
885 :group 'org-table-settings
886 :type 'string)
888 (defcustom org-table-number-regexp
889 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
890 "Regular expression for recognizing numbers in table columns.
891 If a table column contains mostly numbers, it will be aligned to the
892 right. If not, it will be aligned to the left.
894 The default value of this option is a regular expression which allows
895 anything which looks remotely like a number as used in scientific
896 context. For example, all of the following will be considered a
897 number:
898 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
900 Other options offered by the customize interface are more restrictive."
901 :group 'org-table-settings
902 :type '(choice
903 (const :tag "Positive Integers"
904 "^[0-9]+$")
905 (const :tag "Integers"
906 "^[-+]?[0-9]+$")
907 (const :tag "Floating Point Numbers"
908 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
909 (const :tag "Floating Point Number or Integer"
910 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
911 (const :tag "Exponential, Floating point, Integer"
912 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
913 (const :tag "Very General Number-Like, including hex"
914 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
915 (string :tag "Regexp:")))
917 (defcustom org-table-number-fraction 0.5
918 "Fraction of numbers in a column required to make the column align right.
919 In a column all non-white fields are considered. If at least this
920 fraction of fields is matched by `org-table-number-fraction',
921 alignment to the right border applies."
922 :group 'org-table-settings
923 :type 'number)
925 (defgroup org-table-editing nil
926 "Behavior of tables during editing in Org-mode."
927 :tag "Org Table Editing"
928 :group 'org-table)
930 (defcustom org-table-automatic-realign t
931 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
932 When nil, aligning is only done with \\[org-table-align], or after column
933 removal/insertion."
934 :group 'org-table-editing
935 :type 'boolean)
937 (defcustom org-table-auto-blank-field t
938 "Non-nil means, automatically blank table field when starting to type into it.
939 This only happens when typing immediately after a field motion
940 command (TAB, S-TAB or RET).
941 Only relevant when `org-enable-table-editor' is equal to `optimized'."
942 :group 'org-table-editing
943 :type 'boolean)
945 (defcustom org-table-tab-jumps-over-hlines t
946 "Non-nil means, tab in the last column of a table with jump over a hline.
947 If a horizontal separator line is following the current line,
948 `org-table-next-field' can either create a new row before that line, or jump
949 over the line. When this option is nil, a new line will be created before
950 this line."
951 :group 'org-table-editing
952 :type 'boolean)
954 (defcustom org-table-tab-recognizes-table.el t
955 "Non-nil means, TAB will automatically notice a table.el table.
956 When it sees such a table, it moves point into it and - if necessary -
957 calls `table-recognize-table'."
958 :group 'org-table-editing
959 :type 'boolean)
961 (defgroup org-table-calculation nil
962 "Options concerning tables in Org-mode."
963 :tag "Org Table Calculation"
964 :group 'org-table)
966 (defcustom org-table-use-standard-references t
967 "Should org-mode work with table refrences like B3 instead of @3$2?
968 Possible values are:
969 nil never use them
970 from accept as input, do not present for editing
971 t: accept as input and present for editing"
972 :group 'org-table-calculation
973 :type '(choice
974 (const :tag "Never, don't even check unser input for them" nil)
975 (const :tag "Always, both as user input, and when editing" t)
976 (const :tag "Convert user input, don't offer during editing" 'from)))
978 (defcustom org-table-copy-increment t
979 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
980 :group 'org-table-calculation
981 :type 'boolean)
983 (defcustom org-calc-default-modes
984 '(calc-internal-prec 12
985 calc-float-format (float 5)
986 calc-angle-mode deg
987 calc-prefer-frac nil
988 calc-symbolic-mode nil
989 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
990 calc-display-working-message t
992 "List with Calc mode settings for use in calc-eval for table formulas.
993 The list must contain alternating symbols (Calc modes variables and values).
994 Don't remove any of the default settings, just change the values. Org-mode
995 relies on the variables to be present in the list."
996 :group 'org-table-calculation
997 :type 'plist)
999 (defcustom org-table-formula-evaluate-inline t
1000 "Non-nil means, TAB and RET evaluate a formula in current table field.
1001 If the current field starts with an equal sign, it is assumed to be a formula
1002 which should be evaluated as described in the manual and in the documentation
1003 string of the command `org-table-eval-formula'. This feature requires the
1004 Emacs calc package.
1005 When this variable is nil, formula calculation is only available through
1006 the command \\[org-table-eval-formula]."
1007 :group 'org-table-calculation
1008 :type 'boolean)
1010 (defcustom org-table-formula-use-constants t
1011 "Non-nil means, interpret constants in formulas in tables.
1012 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1013 by the value given in `org-table-formula-constants', or by a value obtained
1014 from the `constants.el' package."
1015 :group 'org-table-calculation
1016 :type 'boolean)
1018 (defcustom org-table-formula-constants nil
1019 "Alist with constant names and values, for use in table formulas.
1020 The car of each element is a name of a constant, without the `$' before it.
1021 The cdr is the value as a string. For example, if you'd like to use the
1022 speed of light in a formula, you would configure
1024 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1026 and then use it in an equation like `$1*$c'.
1028 Constants can also be defined on a per-file basis using a line like
1030 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
1031 :group 'org-table-calculation
1032 :type '(repeat
1033 (cons (string :tag "name")
1034 (string :tag "value"))))
1036 (defvar org-table-formula-constants-local nil
1037 "Local version of `org-table-formula-constants'.")
1038 (make-variable-buffer-local 'org-table-formula-constants-local)
1040 (defcustom org-table-allow-automatic-line-recalculation t
1041 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1042 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1043 :group 'org-table-calculation
1044 :type 'boolean)
1046 (defgroup org-link nil
1047 "Options concerning links in Org-mode."
1048 :tag "Org Link"
1049 :group 'org)
1051 (defvar org-link-abbrev-alist-local nil
1052 "Buffer-local version of `org-link-abbrev-alist', which see.
1053 The value of this is taken from the #+LINK lines.")
1054 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1056 (defcustom org-link-abbrev-alist nil
1057 "Alist of link abbreviations.
1058 The car of each element is a string, to be replaced at the start of a link.
1059 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1060 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1062 [[linkkey:tag][description]]
1064 If REPLACE is a string, the tag will simply be appended to create the link.
1065 If the string contains \"%s\", the tag will be inserted there.
1067 REPLACE may also be a function that will be called with the tag as the
1068 only argument to create the link, which should be returned as a string.
1070 See the manual for examples."
1071 :group 'org-link
1072 :type 'alist)
1074 (defcustom org-descriptive-links t
1075 "Non-nil means, hide link part and only show description of bracket links.
1076 Bracket links are like [[link][descritpion]]. This variable sets the initial
1077 state in new org-mode buffers. The setting can then be toggled on a
1078 per-buffer basis from the Org->Hyperlinks menu."
1079 :group 'org-link
1080 :type 'boolean)
1082 (defcustom org-link-file-path-type 'adaptive
1083 "How the path name in file links should be stored.
1084 Valid values are:
1086 relative Relative to the current directory, i.e. the directory of the file
1087 into which the link is being inserted.
1088 absolute Absolute path, if possible with ~ for home directory.
1089 noabbrev Absolute path, no abbreviation of home directory.
1090 adaptive Use relative path for files in the current directory and sub-
1091 directories of it. For other files, use an absolute path."
1092 :group 'org-link
1093 :type '(choice
1094 (const relative)
1095 (const absolute)
1096 (const noabbrev)
1097 (const adaptive)))
1099 (defcustom org-activate-links '(bracket angle plain radio tag date)
1100 "Types of links that should be activated in Org-mode files.
1101 This is a list of symbols, each leading to the activation of a certain link
1102 type. In principle, it does not hurt to turn on most link types - there may
1103 be a small gain when turning off unused link types. The types are:
1105 bracket The recommended [[link][description]] or [[link]] links with hiding.
1106 angular Links in angular brackes that may contain whitespace like
1107 <bbdb:Carsten Dominik>.
1108 plain Plain links in normal text, no whitespace, like http://google.com.
1109 radio Text that is matched by a radio target, see manual for details.
1110 tag Tag settings in a headline (link to tag search).
1111 date Time stamps (link to calendar).
1113 Changing this variable requires a restart of Emacs to become effective."
1114 :group 'org-link
1115 :type '(set (const :tag "Double bracket links (new style)" bracket)
1116 (const :tag "Angular bracket links (old style)" angular)
1117 (const :tag "plain text links" plain)
1118 (const :tag "Radio target matches" radio)
1119 (const :tag "Tags" tag)
1120 (const :tag "Tags" target)
1121 (const :tag "Timestamps" date)))
1123 (defgroup org-link-store nil
1124 "Options concerning storing links in Org-mode"
1125 :tag "Org Store Link"
1126 :group 'org-link)
1128 (defcustom org-email-link-description-format "Email %c: %.30s"
1129 "Format of the description part of a link to an email or usenet message.
1130 The following %-excapes will be replaced by corresponding information:
1132 %F full \"From\" field
1133 %f name, taken from \"From\" field, address if no name
1134 %T full \"To\" field
1135 %t first name in \"To\" field, address if no name
1136 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1137 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1138 %s subject
1139 %m message-id.
1141 You may use normal field width specification between the % and the letter.
1142 This is for example useful to limit the length of the subject.
1144 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1145 :group 'org-link-store
1146 :type 'string)
1148 (defcustom org-from-is-user-regexp
1149 (let (r1 r2)
1150 (when (and user-mail-address (not (string= user-mail-address "")))
1151 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1152 (when (and user-full-name (not (string= user-full-name "")))
1153 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1154 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1155 "Regexp mached against the \"From:\" header of an email or usenet message.
1156 It should match if the message is from the user him/herself."
1157 :group 'org-link-store
1158 :type 'regexp)
1160 (defcustom org-context-in-file-links t
1161 "Non-nil means, file links from `org-store-link' contain context.
1162 A search string will be added to the file name with :: as separator and
1163 used to find the context when the link is activated by the command
1164 `org-open-at-point'.
1165 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1166 negates this setting for the duration of the command."
1167 :group 'org-link-store
1168 :type 'boolean)
1170 (defcustom org-keep-stored-link-after-insertion nil
1171 "Non-nil means, keep link in list for entire session.
1173 The command `org-store-link' adds a link pointing to the current
1174 location to an internal list. These links accumulate during a session.
1175 The command `org-insert-link' can be used to insert links into any
1176 Org-mode file (offering completion for all stored links). When this
1177 option is nil, every link which has been inserted once using \\[org-insert-link]
1178 will be removed from the list, to make completing the unused links
1179 more efficient."
1180 :group 'org-link-store
1181 :type 'boolean)
1183 (defcustom org-usenet-links-prefer-google nil
1184 "Non-nil means, `org-store-link' will create web links to Google groups.
1185 When nil, Gnus will be used for such links.
1186 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1187 negates this setting for the duration of the command."
1188 :group 'org-link-store
1189 :type 'boolean)
1191 (defgroup org-link-follow nil
1192 "Options concerning following links in Org-mode"
1193 :tag "Org Follow Link"
1194 :group 'org-link)
1196 (defcustom org-tab-follows-link nil
1197 "Non-nil means, on links TAB will follow the link.
1198 Needs to be set before org.el is loaded."
1199 :group 'org-link-follow
1200 :type 'boolean)
1202 (defcustom org-return-follows-link nil
1203 "Non-nil means, on links RET will follow the link.
1204 Needs to be set before org.el is loaded."
1205 :group 'org-link-follow
1206 :type 'boolean)
1208 (defcustom org-mouse-1-follows-link t
1209 "Non-nil means, mouse-1 on a link will follow the link.
1210 A longer mouse click will still set point. Does not wortk on XEmacs.
1211 Needs to be set before org.el is loaded."
1212 :group 'org-link-follow
1213 :type 'boolean)
1215 (defcustom org-mark-ring-length 4
1216 "Number of different positions to be recorded in the ring
1217 Changing this requires a restart of Emacs to work correctly."
1218 :group 'org-link-follow
1219 :type 'interger)
1221 (defcustom org-link-frame-setup
1222 '((vm . vm-visit-folder-other-frame)
1223 (gnus . gnus-other-frame)
1224 (file . find-file-other-window))
1225 "Setup the frame configuration for following links.
1226 When following a link with Emacs, it may often be useful to display
1227 this link in another window or frame. This variable can be used to
1228 set this up for the different types of links.
1229 For VM, use any of
1230 `vm-visit-folder'
1231 `vm-visit-folder-other-frame'
1232 For Gnus, use any of
1233 `gnus'
1234 `gnus-other-frame'
1235 For FILE, use any of
1236 `find-file'
1237 `find-file-other-window'
1238 `find-file-other-frame'
1239 For the calendar, use the variable `calendar-setup'.
1240 For BBDB, it is currently only possible to display the matches in
1241 another window."
1242 :group 'org-link-follow
1243 :type '(list
1244 (cons (const vm)
1245 (choice
1246 (const vm-visit-folder)
1247 (const vm-visit-folder-other-window)
1248 (const vm-visit-folder-other-frame)))
1249 (cons (const gnus)
1250 (choice
1251 (const gnus)
1252 (const gnus-other-frame)))
1253 (cons (const file)
1254 (choice
1255 (const find-file)
1256 (const find-file-other-window)
1257 (const find-file-other-frame)))))
1259 (defcustom org-display-internal-link-with-indirect-buffer nil
1260 "Non-nil means, use indirect buffer to display infile links.
1261 Activating internal links (from one location in a file to another location
1262 in the same file) normally just jumps to the location. When the link is
1263 activated with a C-u prefix (or with mouse-3), the link is displayed in
1264 another window. When this option is set, the other window actually displays
1265 an indirect buffer clone of the current buffer, to avoid any visibility
1266 changes to the current buffer."
1267 :group 'org-link-follow
1268 :type 'boolean)
1270 (defcustom org-open-non-existing-files nil
1271 "Non-nil means, `org-open-file' will open non-existing files.
1272 When nil, an error will be generated."
1273 :group 'org-link-follow
1274 :type 'boolean)
1276 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1277 "Function and arguments to call for following mailto links.
1278 This is a list with the first element being a lisp function, and the
1279 remaining elements being arguments to the function. In string arguments,
1280 %a will be replaced by the address, and %s will be replaced by the subject
1281 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1282 :group 'org-link-follow
1283 :type '(choice
1284 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1285 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1286 (const :tag "message-mail" (message-mail "%a" "%s"))
1287 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1289 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1290 "Non-nil means, ask for confirmation before executing shell links.
1291 Shell links can be dangerous: just think about a link
1293 [[shell:rm -rf ~/*][Google Search]]
1295 This link would show up in your Org-mode document as \"Google Search\",
1296 but really it would remove your entire home directory.
1297 Therefore we advise against setting this variable to nil.
1298 Just change it to `y-or-n-p' of you want to confirm with a
1299 single keystroke rather than having to type \"yes\"."
1300 :group 'org-link-follow
1301 :type '(choice
1302 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1303 (const :tag "with y-or-n (faster)" y-or-n-p)
1304 (const :tag "no confirmation (dangerous)" nil)))
1306 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1307 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1308 Elisp links can be dangerous: just think about a link
1310 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1312 This link would show up in your Org-mode document as \"Google Search\",
1313 but really it would remove your entire home directory.
1314 Therefore we advise against setting this variable to nil.
1315 Just change it to `y-or-n-p' of you want to confirm with a
1316 single keystroke rather than having to type \"yes\"."
1317 :group 'org-link-follow
1318 :type '(choice
1319 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1320 (const :tag "with y-or-n (faster)" y-or-n-p)
1321 (const :tag "no confirmation (dangerous)" nil)))
1323 (defconst org-file-apps-defaults-gnu
1324 '((remote . emacs)
1325 (t . mailcap))
1326 "Default file applications on a UNIX or GNU/Linux system.
1327 See `org-file-apps'.")
1329 (defconst org-file-apps-defaults-macosx
1330 '((remote . emacs)
1331 (t . "open %s")
1332 ("ps" . "gv %s")
1333 ("ps.gz" . "gv %s")
1334 ("eps" . "gv %s")
1335 ("eps.gz" . "gv %s")
1336 ("dvi" . "xdvi %s")
1337 ("fig" . "xfig %s"))
1338 "Default file applications on a MacOS X system.
1339 The system \"open\" is known as a default, but we use X11 applications
1340 for some files for which the OS does not have a good default.
1341 See `org-file-apps'.")
1343 (defconst org-file-apps-defaults-windowsnt
1344 (list
1345 '(remote . emacs)
1346 (cons t
1347 (list (if (featurep 'xemacs)
1348 'mswindows-shell-execute
1349 'w32-shell-execute)
1350 "open" 'file)))
1351 "Default file applications on a Windows NT system.
1352 The system \"open\" is used for most files.
1353 See `org-file-apps'.")
1355 (defcustom org-file-apps
1357 ("txt" . emacs)
1358 ("tex" . emacs)
1359 ("ltx" . emacs)
1360 ("org" . emacs)
1361 ("el" . emacs)
1362 ("bib" . emacs)
1364 "External applications for opening `file:path' items in a document.
1365 Org-mode uses system defaults for different file types, but
1366 you can use this variable to set the application for a given file
1367 extension. The entries in this list are cons cells where the car identifies
1368 files and the cdr the corresponding command. Possible values for the
1369 file identifier are
1370 \"ext\" A string identifying an extension
1371 `directory' Matches a directory
1372 `remote' Matches a remote file, accessible through tramp or efs.
1373 Remote files most likely should be visited through Emacs
1374 because external applications cannot handle such paths.
1375 t Default for all remaining files
1377 Possible values for the command are:
1378 `emacs' The file will be visited by the current Emacs process.
1379 `default' Use the default application for this file type.
1380 string A command to be executed by a shell; %s will be replaced
1381 by the path to the file.
1382 sexp A Lisp form which will be evaluated. The file path will
1383 be available in the Lisp variable `file'.
1384 For more examples, see the system specific constants
1385 `org-file-apps-defaults-macosx'
1386 `org-file-apps-defaults-windowsnt'
1387 `org-file-apps-defaults-gnu'."
1388 :group 'org-link-follow
1389 :type '(repeat
1390 (cons (choice :value ""
1391 (string :tag "Extension")
1392 (const :tag "Default for unrecognized files" t)
1393 (const :tag "Remote file" remote)
1394 (const :tag "Links to a directory" directory))
1395 (choice :value ""
1396 (const :tag "Visit with Emacs" emacs)
1397 (const :tag "Use system default" default)
1398 (string :tag "Command")
1399 (sexp :tag "Lisp form")))))
1401 (defcustom org-mhe-search-all-folders nil
1402 "Non-nil means, that the search for the mh-message will be extended to
1403 all folders if the message cannot be found in the folder given in the link.
1404 Searching all folders is very efficient with one of the search engines
1405 supported by MH-E, but will be slow with pick."
1406 :group 'org-link-follow
1407 :type 'boolean)
1409 (defgroup org-remember nil
1410 "Options concerning interaction with remember.el."
1411 :tag "Org Remember"
1412 :group 'org)
1414 (defcustom org-directory "~/org"
1415 "Directory with org files.
1416 This directory will be used as default to prompt for org files.
1417 Used by the hooks for remember.el."
1418 :group 'org-remember
1419 :type 'directory)
1421 (defcustom org-default-notes-file "~/.notes"
1422 "Default target for storing notes.
1423 Used by the hooks for remember.el. This can be a string, or nil to mean
1424 the value of `remember-data-file'.
1425 You can set this on a per-template basis with the variable
1426 `org-remember-templates'."
1427 :group 'org-remember
1428 :type '(choice
1429 (const :tag "Default from remember-data-file" nil)
1430 file))
1432 (defcustom org-remember-store-without-prompt t
1433 "Non-nil means, `C-c C-c' stores remember note without further promts.
1434 In this case, you need `C-u C-c C-c' to get the prompts for
1435 note file and headline.
1436 When this variable is nil, `C-c C-c' give you the prompts, and
1437 `C-u C-c C-c' trigger the fasttrack."
1438 :group 'org-remember
1439 :type 'boolean)
1441 (defcustom org-remember-interactive-interface 'refile
1442 "The interface to be used for interactive filing of remember notes.
1443 This is only used when the interactive mode for selecting a filing
1444 location is used (see the variable `org-remember-store-without-prompt').
1445 Allowed vaues are:
1446 outline The interface shows an outline of the relevant file
1447 and the correct heading is found by moving through
1448 the outline or by searching with incremental search.
1449 outline-path-completion Headlines in the current buffer are offered via
1450 completion.
1451 refile Use the refile interface, and offer headlines,
1452 possibly from different buffers."
1453 :group 'org-remember
1454 :type '(choice
1455 (const :tag "Refile" refile)
1456 (const :tag "Outline" outline)
1457 (const :tag "Outline-path-completion" outline-path-completion)))
1459 (defcustom org-goto-interface 'outline
1460 "The default interface to be used for `org-goto'.
1461 Allowed vaues are:
1462 outline The interface shows an outline of the relevant file
1463 and the correct heading is found by moving through
1464 the outline or by searching with incremental search.
1465 outline-path-completion Headlines in the current buffer are offered via
1466 completion."
1467 :group 'org-remember ; FIXME: different group for org-goto and org-refile
1468 :type '(choice
1469 (const :tag "Outline" outline)
1470 (const :tag "Outline-path-completion" outline-path-completion)))
1472 (defcustom org-remember-default-headline ""
1473 "The headline that should be the default location in the notes file.
1474 When filing remember notes, the cursor will start at that position.
1475 You can set this on a per-template basis with the variable
1476 `org-remember-templates'."
1477 :group 'org-remember
1478 :type 'string)
1480 (defcustom org-remember-templates nil
1481 "Templates for the creation of remember buffers.
1482 When nil, just let remember make the buffer.
1483 When not nil, this is a list of 5-element lists. In each entry, the first
1484 element is the name of the template, which should be a single short word.
1485 The second element is a character, a unique key to select this template.
1486 The third element is the template. The fourth element is optional and can
1487 specify a destination file for remember items created with this template.
1488 The default file is given by `org-default-notes-file'. An optional fifth
1489 element can specify the headline in that file that should be offered
1490 first when the user is asked to file the entry. The default headline is
1491 given in the variable `org-remember-default-headline'.
1493 The template specifies the structure of the remember buffer. It should have
1494 a first line starting with a star, to act as the org-mode headline.
1495 Furthermore, the following %-escapes will be replaced with content:
1497 %^{prompt} Prompt the user for a string and replace this sequence with it.
1498 A default value and a completion table ca be specified like this:
1499 %^{prompt|default|completion2|completion3|...}
1500 %t time stamp, date only
1501 %T time stamp with date and time
1502 %u, %U like the above, but inactive time stamps
1503 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1504 You may define a prompt like %^{Please specify birthday}t
1505 %n user name (taken from `user-full-name')
1506 %a annotation, normally the link created with org-store-link
1507 %i initial content, the region active. If %i is indented,
1508 the entire inserted text will be indented as well.
1509 %c content of the clipboard, or current kill ring head
1510 %^g prompt for tags, with completion on tags in target file
1511 %^G prompt for tags, with completion all tags in all agenda files
1512 %:keyword specific information for certain link types, see below
1513 %[pathname] insert the contents of the file given by `pathname'
1514 %(sexp) evaluate elisp `(sexp)' and replace with the result
1515 %! Store this note immediately after filling the template
1517 %? After completing the template, position cursor here.
1519 Apart from these general escapes, you can access information specific to the
1520 link type that is created. For example, calling `remember' in emails or gnus
1521 will record the author and the subject of the message, which you can access
1522 with %:author and %:subject, respectively. Here is a complete list of what
1523 is recorded for each link type.
1525 Link type | Available information
1526 -------------------+------------------------------------------------------
1527 bbdb | %:type %:name %:company
1528 vm, wl, mh, rmail | %:type %:subject %:message-id
1529 | %:from %:fromname %:fromaddress
1530 | %:to %:toname %:toaddress
1531 | %:fromto (either \"to NAME\" or \"from NAME\")
1532 gnus | %:group, for messages also all email fields
1533 w3, w3m | %:type %:url
1534 info | %:type %:file %:node
1535 calendar | %:type %:date"
1536 :group 'org-remember
1537 :get (lambda (var) ; Make sure all entries have 5 elements
1538 (mapcar (lambda (x)
1539 (if (not (stringp (car x))) (setq x (cons "" x)))
1540 (cond ((= (length x) 4) (append x '("")))
1541 ((= (length x) 3) (append x '("" "")))
1542 (t x)))
1543 (default-value var)))
1544 :type '(repeat
1545 :tag "enabled"
1546 (list :value ("" ?a "\n" nil nil)
1547 (string :tag "Name")
1548 (character :tag "Selection Key")
1549 (string :tag "Template")
1550 (choice
1551 (file :tag "Destination file")
1552 (const :tag "Prompt for file" nil))
1553 (choice
1554 (string :tag "Destination headline")
1555 (const :tag "Selection interface for heading")))))
1557 (defcustom org-reverse-note-order nil
1558 "Non-nil means, store new notes at the beginning of a file or entry.
1559 When nil, new notes will be filed to the end of a file or entry.
1560 This can also be a list with cons cells of regular expressions that
1561 are matched against file names, and values."
1562 :group 'org-remember
1563 :type '(choice
1564 (const :tag "Reverse always" t)
1565 (const :tag "Reverse never" nil)
1566 (repeat :tag "By file name regexp"
1567 (cons regexp boolean))))
1569 (defcustom org-refile-targets nil
1570 "Targets for refiling entries with \\[org-refile].
1571 This is list of cons cells. Each cell contains:
1572 - a specification of the files to be considered, either a list of files,
1573 or a symbol whose function or value fields will be used to retrieve
1574 a file name or a list of file names. Nil means, refile to a different
1575 heading in the current buffer.
1576 - A specification of how to find candidate refile targets. This may be
1577 any of
1578 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1579 This tag has to be present in all target headlines, inheritance will
1580 not be considered.
1581 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1582 todo keyword.
1583 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1584 headlines that are refiling targets.
1585 - a cons cell (:level . N). Any headline of level N is considered a target.
1586 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1587 ;; FIXME: what if there are a var and func with same name???
1588 :group 'org-remember
1589 :type '(repeat
1590 (cons
1591 (choice :value org-agenda-files
1592 (const :tag "All agenda files" org-agenda-files)
1593 (const :tag "Current buffer" nil)
1594 (function) (variable) (file))
1595 (choice :tag "Identify target headline by"
1596 (cons :tag "Specific tag" (const :tag) (string))
1597 (cons :tag "TODO keyword" (const :todo) (string))
1598 (cons :tag "Regular expression" (const :regexp) (regexp))
1599 (cons :tag "Level number" (const :level) (integer))
1600 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1602 (defcustom org-refile-use-outline-path nil
1603 "Non-nil means, provide refile targets as paths.
1604 So a level 3 headline will be available as level1/level2/level3.
1605 When the value is `file', also include the file name (without directory)
1606 into the path. When `full-file-path', include the full file path."
1607 :group 'org-remember
1608 :type '(choice
1609 (const :tag "Not" nil)
1610 (const :tag "Yes" t)
1611 (const :tag "Start with file name" file)
1612 (const :tag "Start with full file path" full-file-path)))
1614 (defgroup org-todo nil
1615 "Options concerning TODO items in Org-mode."
1616 :tag "Org TODO"
1617 :group 'org)
1619 (defgroup org-progress nil
1620 "Options concerning Progress logging in Org-mode."
1621 :tag "Org Progress"
1622 :group 'org-time)
1624 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1625 "List of TODO entry keyword sequences and their interpretation.
1626 \\<org-mode-map>This is a list of sequences.
1628 Each sequence starts with a symbol, either `sequence' or `type',
1629 indicating if the keywords should be interpreted as a sequence of
1630 action steps, or as different types of TODO items. The first
1631 keywords are states requiring action - these states will select a headline
1632 for inclusion into the global TODO list Org-mode produces. If one of
1633 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1634 signify that no further action is necessary. If \"|\" is not found,
1635 the last keyword is treated as the only DONE state of the sequence.
1637 The command \\[org-todo] cycles an entry through these states, and one
1638 additional state where no keyword is present. For details about this
1639 cycling, see the manual.
1641 TODO keywords and interpretation can also be set on a per-file basis with
1642 the special #+SEQ_TODO and #+TYP_TODO lines.
1644 For backward compatibility, this variable may also be just a list
1645 of keywords - in this case the interptetation (sequence or type) will be
1646 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1647 :group 'org-todo
1648 :group 'org-keywords
1649 :type '(choice
1650 (repeat :tag "Old syntax, just keywords"
1651 (string :tag "Keyword"))
1652 (repeat :tag "New syntax"
1653 (cons
1654 (choice
1655 :tag "Interpretation"
1656 (const :tag "Sequence (cycling hits every state)" sequence)
1657 (const :tag "Type (cycling directly to DONE)" type))
1658 (repeat
1659 (string :tag "Keyword"))))))
1661 (defvar org-todo-keywords-1 nil)
1662 (make-variable-buffer-local 'org-todo-keywords-1)
1663 (defvar org-todo-keywords-for-agenda nil)
1664 (defvar org-done-keywords-for-agenda nil)
1665 (defvar org-not-done-keywords nil)
1666 (make-variable-buffer-local 'org-not-done-keywords)
1667 (defvar org-done-keywords nil)
1668 (make-variable-buffer-local 'org-done-keywords)
1669 (defvar org-todo-heads nil)
1670 (make-variable-buffer-local 'org-todo-heads)
1671 (defvar org-todo-sets nil)
1672 (make-variable-buffer-local 'org-todo-sets)
1673 (defvar org-todo-log-states nil)
1674 (make-variable-buffer-local 'org-todo-log-states)
1675 (defvar org-todo-kwd-alist nil)
1676 (make-variable-buffer-local 'org-todo-kwd-alist)
1677 (defvar org-todo-key-alist nil)
1678 (make-variable-buffer-local 'org-todo-key-alist)
1679 (defvar org-todo-key-trigger nil)
1680 (make-variable-buffer-local 'org-todo-key-trigger)
1682 (defcustom org-todo-interpretation 'sequence
1683 "Controls how TODO keywords are interpreted.
1684 This variable is in principle obsolete and is only used for
1685 backward compatibility, if the interpretation of todo keywords is
1686 not given already in `org-todo-keywords'. See that variable for
1687 more information."
1688 :group 'org-todo
1689 :group 'org-keywords
1690 :type '(choice (const sequence)
1691 (const type)))
1693 (defcustom org-use-fast-todo-selection 'prefix
1694 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1695 This variable describes if and under what circumstances the cycling
1696 mechanism for TODO keywords will be replaced by a single-key, direct
1697 selection scheme.
1699 When nil, fast selection is never used.
1701 When the symbol `prefix', it will be used when `org-todo' is called with
1702 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1703 in an agenda buffer.
1705 When t, fast selection is used by default. In this case, the prefix
1706 argument forces cycling instead.
1708 In all cases, the special interface is only used if access keys have actually
1709 been assigned by the user, i.e. if keywords in the configuration are followed
1710 by a letter in parenthesis, like TODO(t)."
1711 :group 'org-todo
1712 :type '(choice
1713 (const :tag "Never" nil)
1714 (const :tag "By default" t)
1715 (const :tag "Only with C-u C-c C-t" prefix)))
1717 (defcustom org-after-todo-state-change-hook nil
1718 "Hook which is run after the state of a TODO item was changed.
1719 The new state (a string with a TODO keyword, or nil) is available in the
1720 Lisp variable `state'."
1721 :group 'org-todo
1722 :type 'hook)
1724 (defcustom org-log-done nil
1725 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1726 When the state of an entry is changed from nothing or a DONE state to
1727 a not-done TODO state, remove a previous closing date.
1729 This can also be a list of symbols indicating under which conditions
1730 the time stamp recording the action should be annotated with a short note.
1731 Valid members of this list are
1733 done Offer to record a note when marking entries done
1734 state Offer to record a note whenever changing the TODO state
1735 of an item. This is only relevant if TODO keywords are
1736 interpreted as sequence, see variable `org-todo-interpretation'.
1737 When `state' is set, this includes tracking `done'.
1738 clock-out Offer to record a note when clocking out of an item.
1740 A separate window will then pop up and allow you to type a note.
1741 After finishing with C-c C-c, the note will be added directly after the
1742 timestamp, as a plain list item. See also the variable
1743 `org-log-note-headings'.
1745 Logging can also be configured on a per-file basis by adding one of
1746 the following lines anywhere in the buffer:
1748 #+STARTUP: logdone
1749 #+STARTUP: nologging
1750 #+STARTUP: lognotedone
1751 #+STARTUP: lognotestate
1752 #+STARTUP: lognoteclock-out
1754 You can have local logging settings for a subtree by setting the LOGGING
1755 property to one or more of these keywords."
1756 :group 'org-todo
1757 :group 'org-progress
1758 :type '(choice
1759 (const :tag "off" nil)
1760 (const :tag "on" t)
1761 (set :tag "on, with notes, detailed control" :greedy t :value (done)
1762 (const :tag "when item is marked DONE" done)
1763 (const :tag "when TODO state changes" state)
1764 (const :tag "when clocking out" clock-out))))
1766 (defcustom org-log-done-with-time t
1767 "Non-nil means, the CLOSED time stamp will contain date and time.
1768 When nil, only the date will be recorded."
1769 :group 'org-progress
1770 :type 'boolean)
1772 (defcustom org-log-note-headings
1773 '((done . "CLOSING NOTE %t")
1774 (state . "State %-12s %t")
1775 (clock-out . ""))
1776 "Headings for notes added when clocking out or closing TODO items.
1777 The value is an alist, with the car being a symbol indicating the note
1778 context, and the cdr is the heading to be used. The heading may also be the
1779 empty string.
1780 %t in the heading will be replaced by a time stamp.
1781 %s will be replaced by the new TODO state, in double quotes.
1782 %u will be replaced by the user name.
1783 %U will be replaced by the full user name."
1784 :group 'org-todo
1785 :group 'org-progress
1786 :type '(list :greedy t
1787 (cons (const :tag "Heading when closing an item" done) string)
1788 (cons (const :tag
1789 "Heading when changing todo state (todo sequence only)"
1790 state) string)
1791 (cons (const :tag "Heading when clocking out" clock-out) string)))
1793 (defcustom org-log-states-order-reversed t
1794 "Non-nil means, the latest state change note will be directly after heading.
1795 When nil, the notes will be orderer according to time."
1796 :group 'org-todo
1797 :group 'org-progress
1798 :type 'boolean)
1800 (defcustom org-log-repeat t
1801 "Non-nil means, prompt for a note when REPEAT is resetting a TODO entry.
1802 When nil, no note will be taken.
1803 This option can also be set with on a per-file-basis with
1805 #+STARTUP: logrepeat
1806 #+STARTUP: nologrepeat
1808 You can have local logging settings for a subtree by setting the LOGGING
1809 property to one or more of these keywords."
1810 :group 'org-todo
1811 :group 'org-progress
1812 :type 'boolean)
1814 (defcustom org-clock-into-drawer 2
1815 "Should clocking info be wrapped into a drawer?
1816 When t, clocking info will always be inserted into a :CLOCK: drawer.
1817 If necessary, the drawer will be created.
1818 When nil, the drawer will not be created, but used when present.
1819 When an integer and the number of clocking entries in an item
1820 reaches or exceeds this number, a drawer will be created."
1821 :group 'org-todo
1822 :group 'org-progress
1823 :type '(choice
1824 (const :tag "Always" t)
1825 (const :tag "Only when drawer exists" nil)
1826 (integer :tag "When at least N clock entries")))
1828 (defcustom org-clock-out-when-done t
1829 "When t, the clock will be stopped when the relevant entry is marked DONE.
1830 Nil means, clock will keep running until stopped explicitly with
1831 `C-c C-x C-o', or until the clock is started in a different item."
1832 :group 'org-progress
1833 :type 'boolean)
1835 (defcustom org-clock-in-switch-to-state nil
1836 "Set task to a special todo state while clocking it.
1837 The value should be the state to which the entry should be switched."
1838 :group 'org-progress
1839 :group 'org-todo
1840 :type '(choice
1841 (const :tag "Don't force a state" nil)
1842 (string :tag "State")))
1844 (defgroup org-priorities nil
1845 "Priorities in Org-mode."
1846 :tag "Org Priorities"
1847 :group 'org-todo)
1849 (defcustom org-highest-priority ?A
1850 "The highest priority of TODO items. A character like ?A, ?B etc.
1851 Must have a smaller ASCII number than `org-lowest-priority'."
1852 :group 'org-priorities
1853 :type 'character)
1855 (defcustom org-lowest-priority ?C
1856 "The lowest priority of TODO items. A character like ?A, ?B etc.
1857 Must have a larger ASCII number than `org-highest-priority'."
1858 :group 'org-priorities
1859 :type 'character)
1861 (defcustom org-default-priority ?B
1862 "The default priority of TODO items.
1863 This is the priority an item get if no explicit priority is given."
1864 :group 'org-priorities
1865 :type 'character)
1867 (defcustom org-priority-start-cycle-with-default t
1868 "Non-nil means, start with default priority when starting to cycle.
1869 When this is nil, the first step in the cycle will be (depending on the
1870 command used) one higher or lower that the default priority."
1871 :group 'org-priorities
1872 :type 'boolean)
1874 (defgroup org-time nil
1875 "Options concerning time stamps and deadlines in Org-mode."
1876 :tag "Org Time"
1877 :group 'org)
1879 (defcustom org-insert-labeled-timestamps-at-point nil
1880 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1881 When nil, these labeled time stamps are forces into the second line of an
1882 entry, just after the headline. When scheduling from the global TODO list,
1883 the time stamp will always be forced into the second line."
1884 :group 'org-time
1885 :type 'boolean)
1887 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1888 "Formats for `format-time-string' which are used for time stamps.
1889 It is not recommended to change this constant.")
1891 (defcustom org-time-stamp-rounding-minutes 0
1892 "Number of minutes to round time stamps to upon insertion.
1893 When zero, insert the time unmodified. Useful rounding numbers
1894 should be factors of 60, so for example 5, 10, 15.
1895 When this is not zero, you can still force an exact time-stamp by using
1896 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1897 :group 'org-time
1898 :type 'integer)
1900 (defcustom org-display-custom-times nil
1901 "Non-nil means, overlay custom formats over all time stamps.
1902 The formats are defined through the variable `org-time-stamp-custom-formats'.
1903 To turn this on on a per-file basis, insert anywhere in the file:
1904 #+STARTUP: customtime"
1905 :group 'org-time
1906 :set 'set-default
1907 :type 'sexp)
1908 (make-variable-buffer-local 'org-display-custom-times)
1910 (defcustom org-time-stamp-custom-formats
1911 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1912 "Custom formats for time stamps. See `format-time-string' for the syntax.
1913 These are overlayed over the default ISO format if the variable
1914 `org-display-custom-times' is set. Time like %H:%M should be at the
1915 end of the second format."
1916 :group 'org-time
1917 :type 'sexp)
1919 (defun org-time-stamp-format (&optional long inactive)
1920 "Get the right format for a time string."
1921 (let ((f (if long (cdr org-time-stamp-formats)
1922 (car org-time-stamp-formats))))
1923 (if inactive
1924 (concat "[" (substring f 1 -1) "]")
1925 f)))
1927 (defcustom org-read-date-prefer-future t
1928 "Non-nil means, assume future for incomplete date input from user.
1929 This affects the following situations:
1930 1. The user gives a day, but no month.
1931 For example, if today is the 15th, and you enter \"3\", Org-mode will
1932 read this as the third of *next* month. However, if you enter \"17\",
1933 it will be considered as *this* month.
1934 2. The user gives a month but not a year.
1935 For example, if it is april and you enter \"feb 2\", this will be read
1936 as feb 2, *next* year. \"May 5\", however, will be this year.
1938 When this option is nil, the current month and year will always be used
1939 as defaults."
1940 :group 'org-time
1941 :type 'boolean)
1943 (defcustom org-read-date-display-live t
1944 "Non-nil means, display current interpretation of date prompt live.
1945 This display will be in an overlay, in the minibuffer."
1946 :group 'org-time
1947 :type 'boolean)
1949 (defcustom org-read-date-popup-calendar t
1950 "Non-nil means, pop up a calendar when prompting for a date.
1951 In the calendar, the date can be selected with mouse-1. However, the
1952 minibuffer will also be active, and you can simply enter the date as well.
1953 When nil, only the minibuffer will be available."
1954 :group 'org-time
1955 :type 'boolean)
1956 (if (fboundp 'defvaralias)
1957 (defvaralias 'org-popup-calendar-for-date-prompt
1958 'org-read-date-popup-calendar))
1960 (defcustom org-extend-today-until 0
1961 "The hour when your day really ends.
1962 This has influence for the following applications:
1963 - When switching the agenda to \"today\". It it is still earlier than
1964 the time given here, the day recognized as TODAY is actually yesterday.
1965 - When a date is read from the user and it is still before the time given
1966 here, the current date and time will be assumed to be yesterday, 23:59.
1968 FIXME:
1969 IMPORTANT: This is still a very experimental feature, it may disappear
1970 again or it may be extended to mean more things."
1971 :group 'org-time
1972 :type 'number)
1974 (defcustom org-edit-timestamp-down-means-later nil
1975 "Non-nil means, S-down will increase the time in a time stamp.
1976 When nil, S-up will increase."
1977 :group 'org-time
1978 :type 'boolean)
1980 (defcustom org-calendar-follow-timestamp-change t
1981 "Non-nil means, make the calendar window follow timestamp changes.
1982 When a timestamp is modified and the calendar window is visible, it will be
1983 moved to the new date."
1984 :group 'org-time
1985 :type 'boolean)
1987 (defcustom org-clock-heading-function nil
1988 "When non-nil, should be a function to create `org-clock-heading'.
1989 This is the string shown in the mode line when a clock is running.
1990 The function is called with point at the beginning of the headline."
1991 :group 'org-time ; FIXME: Should we have a separate group????
1992 :type 'function)
1994 (defgroup org-tags nil
1995 "Options concerning tags in Org-mode."
1996 :tag "Org Tags"
1997 :group 'org)
1999 (defcustom org-tag-alist nil
2000 "List of tags allowed in Org-mode files.
2001 When this list is nil, Org-mode will base TAG input on what is already in the
2002 buffer.
2003 The value of this variable is an alist, the car of each entry must be a
2004 keyword as a string, the cdr may be a character that is used to select
2005 that tag through the fast-tag-selection interface.
2006 See the manual for details."
2007 :group 'org-tags
2008 :type '(repeat
2009 (choice
2010 (cons (string :tag "Tag name")
2011 (character :tag "Access char"))
2012 (const :tag "Start radio group" (:startgroup))
2013 (const :tag "End radio group" (:endgroup)))))
2015 (defcustom org-use-fast-tag-selection 'auto
2016 "Non-nil means, use fast tag selection scheme.
2017 This is a special interface to select and deselect tags with single keys.
2018 When nil, fast selection is never used.
2019 When the symbol `auto', fast selection is used if and only if selection
2020 characters for tags have been configured, either through the variable
2021 `org-tag-alist' or through a #+TAGS line in the buffer.
2022 When t, fast selection is always used and selection keys are assigned
2023 automatically if necessary."
2024 :group 'org-tags
2025 :type '(choice
2026 (const :tag "Always" t)
2027 (const :tag "Never" nil)
2028 (const :tag "When selection characters are configured" 'auto)))
2030 (defcustom org-fast-tag-selection-single-key nil
2031 "Non-nil means, fast tag selection exits after first change.
2032 When nil, you have to press RET to exit it.
2033 During fast tag selection, you can toggle this flag with `C-c'.
2034 This variable can also have the value `expert'. In this case, the window
2035 displaying the tags menu is not even shown, until you press C-c again."
2036 :group 'org-tags
2037 :type '(choice
2038 (const :tag "No" nil)
2039 (const :tag "Yes" t)
2040 (const :tag "Expert" expert)))
2042 (defvar org-fast-tag-selection-include-todo nil
2043 "Non-nil means, fast tags selection interface will also offer TODO states.
2044 This is an undocumented feature, you should not rely on it.")
2046 (defcustom org-tags-column -80
2047 "The column to which tags should be indented in a headline.
2048 If this number is positive, it specifies the column. If it is negative,
2049 it means that the tags should be flushright to that column. For example,
2050 -80 works well for a normal 80 character screen."
2051 :group 'org-tags
2052 :type 'integer)
2054 (defcustom org-auto-align-tags t
2055 "Non-nil means, realign tags after pro/demotion of TODO state change.
2056 These operations change the length of a headline and therefore shift
2057 the tags around. With this options turned on, after each such operation
2058 the tags are again aligned to `org-tags-column'."
2059 :group 'org-tags
2060 :type 'boolean)
2062 (defcustom org-use-tag-inheritance t
2063 "Non-nil means, tags in levels apply also for sublevels.
2064 When nil, only the tags directly given in a specific line apply there.
2065 If you turn off this option, you very likely want to turn on the
2066 companion option `org-tags-match-list-sublevels'."
2067 :group 'org-tags
2068 :type 'boolean)
2070 (defcustom org-tags-match-list-sublevels nil
2071 "Non-nil means list also sublevels of headlines matching tag search.
2072 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2073 the sublevels of a headline matching a tag search often also match
2074 the same search. Listing all of them can create very long lists.
2075 Setting this variable to nil causes subtrees of a match to be skipped.
2076 This option is off by default, because inheritance in on. If you turn
2077 inheritance off, you very likely want to turn this option on.
2079 As a special case, if the tag search is restricted to TODO items, the
2080 value of this variable is ignored and sublevels are always checked, to
2081 make sure all corresponding TODO items find their way into the list."
2082 :group 'org-tags
2083 :type 'boolean)
2085 (defvar org-tags-history nil
2086 "History of minibuffer reads for tags.")
2087 (defvar org-last-tags-completion-table nil
2088 "The last used completion table for tags.")
2089 (defvar org-after-tags-change-hook nil
2090 "Hook that is run after the tags in a line have changed.")
2092 (defgroup org-properties nil
2093 "Options concerning properties in Org-mode."
2094 :tag "Org Properties"
2095 :group 'org)
2097 (defcustom org-property-format "%-10s %s"
2098 "How property key/value pairs should be formatted by `indent-line'.
2099 When `indent-line' hits a property definition, it will format the line
2100 according to this format, mainly to make sure that the values are
2101 lined-up with respect to each other."
2102 :group 'org-properties
2103 :type 'string)
2105 (defcustom org-use-property-inheritance nil
2106 "Non-nil means, properties apply also for sublevels.
2107 This setting is only relevant during property searches, not when querying
2108 an entry with `org-entry-get'. To retrieve a property with inheritance,
2109 you need to call `org-entry-get' with the inheritance flag.
2110 Turning this on can cause significant overhead when doing a search, so
2111 this is turned off by default.
2112 When nil, only the properties directly given in the current entry count.
2113 The value may also be a list of properties that shouldhave inheritance.
2115 However, note that some special properties use inheritance under special
2116 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2117 and the properties ending in \"_ALL\" when they are used as descriptor
2118 for valid values of a property."
2119 :group 'org-properties
2120 :type '(choice
2121 (const :tag "Not" nil)
2122 (const :tag "Always" nil)
2123 (repeat :tag "Specific properties" (string :tag "Property"))))
2125 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2126 "The default column format, if no other format has been defined.
2127 This variable can be set on the per-file basis by inserting a line
2129 #+COLUMNS: %25ITEM ....."
2130 :group 'org-properties
2131 :type 'string)
2133 (defcustom org-global-properties nil
2134 "List of property/value pairs that can be inherited by any entry.
2135 You can set buffer-local values for this by adding lines like
2137 #+PROPERTY: NAME VALUE"
2138 :group 'org-properties
2139 :type '(repeat
2140 (cons (string :tag "Property")
2141 (string :tag "Value"))))
2143 (defvar org-local-properties nil
2144 "List of property/value pairs that can be inherited by any entry.
2145 Valid for the current buffer.
2146 This variable is populated from #+PROPERTY lines.")
2148 (defgroup org-agenda nil
2149 "Options concerning agenda views in Org-mode."
2150 :tag "Org Agenda"
2151 :group 'org)
2153 (defvar org-category nil
2154 "Variable used by org files to set a category for agenda display.
2155 Such files should use a file variable to set it, for example
2157 # -*- mode: org; org-category: \"ELisp\"
2159 or contain a special line
2161 #+CATEGORY: ELisp
2163 If the file does not specify a category, then file's base name
2164 is used instead.")
2165 (make-variable-buffer-local 'org-category)
2167 (defcustom org-agenda-files nil
2168 "The files to be used for agenda display.
2169 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2170 \\[org-remove-file]. You can also use customize to edit the list.
2172 If an entry is a directory, all files in that directory that are matched by
2173 `org-agenda-file-regexp' will be part of the file list.
2175 If the value of the variable is not a list but a single file name, then
2176 the list of agenda files is actually stored and maintained in that file, one
2177 agenda file per line."
2178 :group 'org-agenda
2179 :type '(choice
2180 (repeat :tag "List of files and directories" file)
2181 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2183 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2184 "Regular expression to match files for `org-agenda-files'.
2185 If any element in the list in that variable contains a directory instead
2186 of a normal file, all files in that directory that are matched by this
2187 regular expression will be included."
2188 :group 'org-agenda
2189 :type 'regexp)
2191 (defcustom org-agenda-skip-unavailable-files nil
2192 "t means to just skip non-reachable files in `org-agenda-files'.
2193 Nil means to remove them, after a query, from the list."
2194 :group 'org-agenda
2195 :type 'boolean)
2197 (defcustom org-agenda-multi-occur-extra-files nil
2198 "List of extra files to be searched by `org-occur-in-agenda-files'.
2199 The files in `org-agenda-files' are always searched."
2200 :group 'org-agenda
2201 :type '(repeat file))
2203 (defcustom org-agenda-confirm-kill 1
2204 "When set, remote killing from the agenda buffer needs confirmation.
2205 When t, a confirmation is always needed. When a number N, confirmation is
2206 only needed when the text to be killed contains more than N non-white lines."
2207 :group 'org-agenda
2208 :type '(choice
2209 (const :tag "Never" nil)
2210 (const :tag "Always" t)
2211 (number :tag "When more than N lines")))
2213 (defcustom org-calendar-to-agenda-key [?c]
2214 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2215 The command `org-calendar-goto-agenda' will be bound to this key. The
2216 default is the character `c' because then `c' can be used to switch back and
2217 forth between agenda and calendar."
2218 :group 'org-agenda
2219 :type 'sexp)
2221 (defcustom org-agenda-compact-blocks nil
2222 "Non-nil means, make the block agenda more compact.
2223 This is done by leaving out unnecessary lines."
2224 :group 'org-agenda
2225 :type nil)
2227 (defgroup org-agenda-export nil
2228 "Options concerning exporting agenda views in Org-mode."
2229 :tag "Org Agenda Export"
2230 :group 'org-agenda)
2232 (defcustom org-agenda-with-colors t
2233 "Non-nil means, use colors in agenda views."
2234 :group 'org-agenda-export
2235 :type 'boolean)
2237 (defcustom org-agenda-exporter-settings nil
2238 "Alist of variable/value pairs that should be active during agenda export.
2239 This is a good place to set uptions for ps-print and for htmlize."
2240 :group 'org-agenda-export
2241 :type '(repeat
2242 (list
2243 (variable)
2244 (sexp :tag "Value"))))
2246 (defcustom org-agenda-export-html-style ""
2247 "The style specification for exported HTML Agenda files.
2248 If this variable contains a string, it will replace the default <style>
2249 section as produced by `htmlize'.
2250 Since there are different ways of setting style information, this variable
2251 needs to contain the full HTML structure to provide a style, including the
2252 surrounding HTML tags. The style specifications should include definitions
2253 the fonts used by the agenda, here is an example:
2255 <style type=\"text/css\">
2256 p { font-weight: normal; color: gray; }
2257 .org-agenda-structure {
2258 font-size: 110%;
2259 color: #003399;
2260 font-weight: 600;
2262 .org-todo {
2263 color: #cc6666;Week-agenda:
2264 font-weight: bold;
2266 .org-done {
2267 color: #339933;
2269 .title { text-align: center; }
2270 .todo, .deadline { color: red; }
2271 .done { color: green; }
2272 </style>
2274 or, if you want to keep the style in a file,
2276 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2278 As the value of this option simply gets inserted into the HTML <head> header,
2279 you can \"misuse\" it to also add other text to the header. However,
2280 <style>...</style> is required, if not present the variable will be ignored."
2281 :group 'org-agenda-export
2282 :group 'org-export-html
2283 :type 'string)
2285 (defgroup org-agenda-custom-commands nil
2286 "Options concerning agenda views in Org-mode."
2287 :tag "Org Agenda Custom Commands"
2288 :group 'org-agenda)
2290 (defcustom org-agenda-custom-commands nil
2291 "Custom commands for the agenda.
2292 These commands will be offered on the splash screen displayed by the
2293 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2295 (key desc type match options files)
2297 key The key (one or more characters as a string) to be associated
2298 with the command.
2299 desc A description of the commend, when omitted or nil, a default
2300 description is built using MATCH.
2301 type The command type, any of the following symbols:
2302 todo Entries with a specific TODO keyword, in all agenda files.
2303 tags Tags match in all agenda files.
2304 tags-todo Tags match in all agenda files, TODO entries only.
2305 todo-tree Sparse tree of specific TODO keyword in *current* file.
2306 tags-tree Sparse tree with all tags matches in *current* file.
2307 occur-tree Occur sparse tree for *current* file.
2308 ... A user-defined function.
2309 match What to search for:
2310 - a single keyword for TODO keyword searches
2311 - a tags match expression for tags searches
2312 - a regular expression for occur searches
2313 options A list of option settings, similar to that in a let form, so like
2314 this: ((opt1 val1) (opt2 val2) ...)
2315 files A list of files file to write the produced agenda buffer to
2316 with the command `org-store-agenda-views'.
2317 If a file name ends in \".html\", an HTML version of the buffer
2318 is written out. If it ends in \".ps\", a postscript version is
2319 produced. Otherwide, only the plain text is written to the file.
2321 You can also define a set of commands, to create a composite agenda buffer.
2322 In this case, an entry looks like this:
2324 (key desc (cmd1 cmd2 ...) general-options file)
2326 where
2328 desc A description string to be displayed in the dispatcher menu.
2329 cmd An agenda command, similar to the above. However, tree commands
2330 are no allowed, but instead you can get agenda and global todo list.
2331 So valid commands for a set are:
2332 (agenda)
2333 (alltodo)
2334 (stuck)
2335 (todo \"match\" options files)
2336 (tags \"match\" options files)
2337 (tags-todo \"match\" options files)
2339 Each command can carry a list of options, and another set of options can be
2340 given for the whole set of commands. Individual command options take
2341 precedence over the general options.
2343 When using several characters as key to a command, the first characters
2344 are prefix commands. For the dispatcher to display useful information, you
2345 should provide a description for the prefix, like
2347 (setq org-agenda-custom-commands
2348 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2349 (\"hl\" tags \"+HOME+Lisa\")
2350 (\"hp\" tags \"+HOME+Peter\")
2351 (\"hk\" tags \"+HOME+Kim\")))"
2352 :group 'org-agenda-custom-commands
2353 :type '(repeat
2354 (choice :value ("a" "" tags "" nil)
2355 (list :tag "Single command"
2356 (string :tag "Access Key(s) ")
2357 (option (string :tag "Description"))
2358 (choice
2359 (const :tag "Agenda" agenda)
2360 (const :tag "TODO list" alltodo)
2361 (const :tag "Stuck projects" stuck)
2362 (const :tag "Tags search (all agenda files)" tags)
2363 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2364 (const :tag "TODO keyword search (all agenda files)" todo)
2365 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2366 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2367 (const :tag "Occur tree (current buffer)" occur-tree)
2368 (sexp :tag "Other, user-defined function"))
2369 (string :tag "Match")
2370 (repeat :tag "Local options"
2371 (list (variable :tag "Option") (sexp :tag "Value")))
2372 (option (repeat :tag "Export" (file :tag "Export to"))))
2373 (list :tag "Command series, all agenda files"
2374 (string :tag "Access Key(s)")
2375 (string :tag "Description ")
2376 (repeat
2377 (choice
2378 (const :tag "Agenda" (agenda))
2379 (const :tag "TODO list" (alltodo))
2380 (const :tag "Stuck projects" (stuck))
2381 (list :tag "Tags search"
2382 (const :format "" tags)
2383 (string :tag "Match")
2384 (repeat :tag "Local options"
2385 (list (variable :tag "Option")
2386 (sexp :tag "Value"))))
2388 (list :tag "Tags search, TODO entries only"
2389 (const :format "" tags-todo)
2390 (string :tag "Match")
2391 (repeat :tag "Local options"
2392 (list (variable :tag "Option")
2393 (sexp :tag "Value"))))
2395 (list :tag "TODO keyword search"
2396 (const :format "" todo)
2397 (string :tag "Match")
2398 (repeat :tag "Local options"
2399 (list (variable :tag "Option")
2400 (sexp :tag "Value"))))
2402 (list :tag "Other, user-defined function"
2403 (symbol :tag "function")
2404 (string :tag "Match")
2405 (repeat :tag "Local options"
2406 (list (variable :tag "Option")
2407 (sexp :tag "Value"))))))
2409 (repeat :tag "General options"
2410 (list (variable :tag "Option")
2411 (sexp :tag "Value")))
2412 (option (repeat :tag "Export" (file :tag "Export to"))))
2413 (cons :tag "Prefix key documentation"
2414 (string :tag "Access Key(s)")
2415 (string :tag "Description ")))))
2417 (defcustom org-stuck-projects
2418 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2419 "How to identify stuck projects.
2420 This is a list of four items:
2421 1. A tags/todo matcher string that is used to identify a project.
2422 The entire tree below a headline matched by this is considered one project.
2423 2. A list of TODO keywords identifying non-stuck projects.
2424 If the project subtree contains any headline with one of these todo
2425 keywords, the project is considered to be not stuck. If you specify
2426 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2427 3. A list of tags identifying non-stuck projects.
2428 If the project subtree contains any headline with one of these tags,
2429 the project is considered to be not stuck. If you specify \"*\" as
2430 a tag, any tag will mark the project unstuck.
2431 4. An arbitrary regular expression matching non-stuck projects.
2433 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2434 or `C-c a #' to produce the list."
2435 :group 'org-agenda-custom-commands
2436 :type '(list
2437 (string :tag "Tags/TODO match to identify a project")
2438 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2439 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2440 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2443 (defgroup org-agenda-skip nil
2444 "Options concerning skipping parts of agenda files."
2445 :tag "Org Agenda Skip"
2446 :group 'org-agenda)
2448 (defcustom org-agenda-todo-list-sublevels t
2449 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2450 When nil, the sublevels of a TODO entry are not checked, resulting in
2451 potentially much shorter TODO lists."
2452 :group 'org-agenda-skip
2453 :group 'org-todo
2454 :type 'boolean)
2456 (defcustom org-agenda-todo-ignore-with-date nil
2457 "Non-nil means, don't show entries with a date in the global todo list.
2458 You can use this if you prefer to mark mere appointments with a TODO keyword,
2459 but don't want them to show up in the TODO list.
2460 When this is set, it also covers deadlines and scheduled items, the settings
2461 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2462 will be ignored."
2463 :group 'org-agenda-skip
2464 :group 'org-todo
2465 :type 'boolean)
2467 (defcustom org-agenda-todo-ignore-scheduled nil
2468 "Non-nil means, don't show scheduled entries in the global todo list.
2469 The idea behind this is that by scheduling it, you have already taken care
2470 of this item.
2471 See also `org-agenda-todo-ignore-with-date'."
2472 :group 'org-agenda-skip
2473 :group 'org-todo
2474 :type 'boolean)
2476 (defcustom org-agenda-todo-ignore-deadlines nil
2477 "Non-nil means, don't show near deadline entries in the global todo list.
2478 Near means closer than `org-deadline-warning-days' days.
2479 The idea behind this is that such items will appear in the agenda anyway.
2480 See also `org-agenda-todo-ignore-with-date'."
2481 :group 'org-agenda-skip
2482 :group 'org-todo
2483 :type 'boolean)
2485 (defcustom org-agenda-skip-scheduled-if-done nil
2486 "Non-nil means don't show scheduled items in agenda when they are done.
2487 This is relevant for the daily/weekly agenda, not for the TODO list. And
2488 it applies only to the actual date of the scheduling. Warnings about
2489 an item with a past scheduling dates are always turned off when the item
2490 is DONE."
2491 :group 'org-agenda-skip
2492 :type 'boolean)
2494 (defcustom org-agenda-skip-deadline-if-done nil
2495 "Non-nil means don't show deadines when the corresponding item is done.
2496 When nil, the deadline is still shown and should give you a happy feeling.
2497 This is relevant for the daily/weekly agenda. And it applied only to the
2498 actualy date of the deadline. Warnings about approching and past-due
2499 deadlines are always turned off when the item is DONE."
2500 :group 'org-agenda-skip
2501 :type 'boolean)
2503 (defcustom org-agenda-skip-timestamp-if-done nil
2504 "Non-nil means don't select item by timestamp or -range if it is DONE."
2505 :group 'org-agenda-skip
2506 :type 'boolean)
2508 (defcustom org-timeline-show-empty-dates 3
2509 "Non-nil means, `org-timeline' also shows dates without an entry.
2510 When nil, only the days which actually have entries are shown.
2511 When t, all days between the first and the last date are shown.
2512 When an integer, show also empty dates, but if there is a gap of more than
2513 N days, just insert a special line indicating the size of the gap."
2514 :group 'org-agenda-skip
2515 :type '(choice
2516 (const :tag "None" nil)
2517 (const :tag "All" t)
2518 (number :tag "at most")))
2521 (defgroup org-agenda-startup nil
2522 "Options concerning initial settings in the Agenda in Org Mode."
2523 :tag "Org Agenda Startup"
2524 :group 'org-agenda)
2526 (defcustom org-finalize-agenda-hook nil
2527 "Hook run just before displaying an agenda buffer."
2528 :group 'org-agenda-startup
2529 :type 'hook)
2531 (defcustom org-agenda-mouse-1-follows-link nil
2532 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2533 A longer mouse click will still set point. Does not wortk on XEmacs.
2534 Needs to be set before org.el is loaded."
2535 :group 'org-agenda-startup
2536 :type 'boolean)
2538 (defcustom org-agenda-start-with-follow-mode nil
2539 "The initial value of follow-mode in a newly created agenda window."
2540 :group 'org-agenda-startup
2541 :type 'boolean)
2543 (defgroup org-agenda-windows nil
2544 "Options concerning the windows used by the Agenda in Org Mode."
2545 :tag "Org Agenda Windows"
2546 :group 'org-agenda)
2548 (defcustom org-agenda-window-setup 'reorganize-frame
2549 "How the agenda buffer should be displayed.
2550 Possible values for this option are:
2552 current-window Show agenda in the current window, keeping all other windows.
2553 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2554 other-window Use `switch-to-buffer-other-window' to display agenda.
2555 reorganize-frame Show only two windows on the current frame, the current
2556 window and the agenda.
2557 See also the variable `org-agenda-restore-windows-after-quit'."
2558 :group 'org-agenda-windows
2559 :type '(choice
2560 (const current-window)
2561 (const other-frame)
2562 (const other-window)
2563 (const reorganize-frame)))
2565 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2566 "The min and max height of the agenda window as a fraction of frame height.
2567 The value of the variable is a cons cell with two numbers between 0 and 1.
2568 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2569 :group 'org-agenda-windows
2570 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2572 (defcustom org-agenda-restore-windows-after-quit nil
2573 "Non-nil means, restore window configuration open exiting agenda.
2574 Before the window configuration is changed for displaying the agenda,
2575 the current status is recorded. When the agenda is exited with
2576 `q' or `x' and this option is set, the old state is restored. If
2577 `org-agenda-window-setup' is `other-frame', the value of this
2578 option will be ignored.."
2579 :group 'org-agenda-windows
2580 :type 'boolean)
2582 (defcustom org-indirect-buffer-display 'other-window
2583 "How should indirect tree buffers be displayed?
2584 This applies to indirect buffers created with the commands
2585 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2586 Valid values are:
2587 current-window Display in the current window
2588 other-window Just display in another window.
2589 dedicated-frame Create one new frame, and re-use it each time.
2590 new-frame Make a new frame each time. Note that in this case
2591 previously-made indirect buffers are kept, and you need to
2592 kill these buffers yourself."
2593 :group 'org-structure
2594 :group 'org-agenda-windows
2595 :type '(choice
2596 (const :tag "In current window" current-window)
2597 (const :tag "In current frame, other window" other-window)
2598 (const :tag "Each time a new frame" new-frame)
2599 (const :tag "One dedicated frame" dedicated-frame)))
2601 (defgroup org-agenda-daily/weekly nil
2602 "Options concerning the daily/weekly agenda."
2603 :tag "Org Agenda Daily/Weekly"
2604 :group 'org-agenda)
2606 (defcustom org-agenda-ndays 7
2607 "Number of days to include in overview display.
2608 Should be 1 or 7."
2609 :group 'org-agenda-daily/weekly
2610 :type 'number)
2612 (defcustom org-agenda-start-on-weekday 1
2613 "Non-nil means, start the overview always on the specified weekday.
2614 0 denotes Sunday, 1 denotes Monday etc.
2615 When nil, always start on the current day."
2616 :group 'org-agenda-daily/weekly
2617 :type '(choice (const :tag "Today" nil)
2618 (number :tag "Weekday No.")))
2620 (defcustom org-agenda-show-all-dates t
2621 "Non-nil means, `org-agenda' shows every day in the selected range.
2622 When nil, only the days which actually have entries are shown."
2623 :group 'org-agenda-daily/weekly
2624 :type 'boolean)
2626 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2627 "Format string for displaying dates in the agenda.
2628 Used by the daily/weekly agenda and by the timeline. This should be
2629 a format string understood by `format-time-string', or a function returning
2630 the formatted date as a string. The function must take a single argument,
2631 a calendar-style date list like (month day year)."
2632 :group 'org-agenda-daily/weekly
2633 :type '(choice
2634 (string :tag "Format string")
2635 (function :tag "Function")))
2637 (defun org-agenda-format-date-aligned (date)
2638 "Format a date string for display in the daily/weekly agenda, or timeline.
2639 This function makes sure that dates are aligned for easy reading."
2640 (format "%-9s %2d %s %4d"
2641 (calendar-day-name date)
2642 (extract-calendar-day date)
2643 (calendar-month-name (extract-calendar-month date))
2644 (extract-calendar-year date)))
2646 (defcustom org-agenda-include-diary nil
2647 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2648 :group 'org-agenda-daily/weekly
2649 :type 'boolean)
2651 (defcustom org-agenda-include-all-todo nil
2652 "Set means weekly/daily agenda will always contain all TODO entries.
2653 The TODO entries will be listed at the top of the agenda, before
2654 the entries for specific days."
2655 :group 'org-agenda-daily/weekly
2656 :type 'boolean)
2658 (defcustom org-agenda-repeating-timestamp-show-all t
2659 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2660 When nil, only one occurence is shown, either today or the
2661 nearest into the future."
2662 :group 'org-agenda-daily/weekly
2663 :type 'boolean)
2665 (defcustom org-deadline-warning-days 14
2666 "No. of days before expiration during which a deadline becomes active.
2667 This variable governs the display in sparse trees and in the agenda.
2668 When negative, it means use this number (the absolute value of it)
2669 even if a deadline has a different individual lead time specified."
2670 :group 'org-time
2671 :group 'org-agenda-daily/weekly
2672 :type 'number)
2674 (defcustom org-scheduled-past-days 10000
2675 "No. of days to continue listing scheduled items that are not marked DONE.
2676 When an item is scheduled on a date, it shows up in the agenda on this
2677 day and will be listed until it is marked done for the number of days
2678 given here."
2679 :group 'org-agenda-daily/weekly
2680 :type 'number)
2682 (defgroup org-agenda-time-grid nil
2683 "Options concerning the time grid in the Org-mode Agenda."
2684 :tag "Org Agenda Time Grid"
2685 :group 'org-agenda)
2687 (defcustom org-agenda-use-time-grid t
2688 "Non-nil means, show a time grid in the agenda schedule.
2689 A time grid is a set of lines for specific times (like every two hours between
2690 8:00 and 20:00). The items scheduled for a day at specific times are
2691 sorted in between these lines.
2692 For details about when the grid will be shown, and what it will look like, see
2693 the variable `org-agenda-time-grid'."
2694 :group 'org-agenda-time-grid
2695 :type 'boolean)
2697 (defcustom org-agenda-time-grid
2698 '((daily today require-timed)
2699 "----------------"
2700 (800 1000 1200 1400 1600 1800 2000))
2702 "The settings for time grid for agenda display.
2703 This is a list of three items. The first item is again a list. It contains
2704 symbols specifying conditions when the grid should be displayed:
2706 daily if the agenda shows a single day
2707 weekly if the agenda shows an entire week
2708 today show grid on current date, independent of daily/weekly display
2709 require-timed show grid only if at least one item has a time specification
2711 The second item is a string which will be places behing the grid time.
2713 The third item is a list of integers, indicating the times that should have
2714 a grid line."
2715 :group 'org-agenda-time-grid
2716 :type
2717 '(list
2718 (set :greedy t :tag "Grid Display Options"
2719 (const :tag "Show grid in single day agenda display" daily)
2720 (const :tag "Show grid in weekly agenda display" weekly)
2721 (const :tag "Always show grid for today" today)
2722 (const :tag "Show grid only if any timed entries are present"
2723 require-timed)
2724 (const :tag "Skip grid times already present in an entry"
2725 remove-match))
2726 (string :tag "Grid String")
2727 (repeat :tag "Grid Times" (integer :tag "Time"))))
2729 (defgroup org-agenda-sorting nil
2730 "Options concerning sorting in the Org-mode Agenda."
2731 :tag "Org Agenda Sorting"
2732 :group 'org-agenda)
2734 (defconst org-sorting-choice
2735 '(choice
2736 (const time-up) (const time-down)
2737 (const category-keep) (const category-up) (const category-down)
2738 (const tag-down) (const tag-up)
2739 (const priority-up) (const priority-down))
2740 "Sorting choices.")
2742 (defcustom org-agenda-sorting-strategy
2743 '((agenda time-up category-keep priority-down)
2744 (todo category-keep priority-down)
2745 (tags category-keep priority-down))
2746 "Sorting structure for the agenda items of a single day.
2747 This is a list of symbols which will be used in sequence to determine
2748 if an entry should be listed before another entry. The following
2749 symbols are recognized:
2751 time-up Put entries with time-of-day indications first, early first
2752 time-down Put entries with time-of-day indications first, late first
2753 category-keep Keep the default order of categories, corresponding to the
2754 sequence in `org-agenda-files'.
2755 category-up Sort alphabetically by category, A-Z.
2756 category-down Sort alphabetically by category, Z-A.
2757 tag-up Sort alphabetically by last tag, A-Z.
2758 tag-down Sort alphabetically by last tag, Z-A.
2759 priority-up Sort numerically by priority, high priority last.
2760 priority-down Sort numerically by priority, high priority first.
2762 The different possibilities will be tried in sequence, and testing stops
2763 if one comparison returns a \"not-equal\". For example, the default
2764 '(time-up category-keep priority-down)
2765 means: Pull out all entries having a specified time of day and sort them,
2766 in order to make a time schedule for the current day the first thing in the
2767 agenda listing for the day. Of the entries without a time indication, keep
2768 the grouped in categories, don't sort the categories, but keep them in
2769 the sequence given in `org-agenda-files'. Within each category sort by
2770 priority.
2772 Leaving out `category-keep' would mean that items will be sorted across
2773 categories by priority.
2775 Instead of a single list, this can also be a set of list for specific
2776 contents, with a context symbol in the car of the list, any of
2777 `agenda', `todo', `tags' for the corresponding agenda views."
2778 :group 'org-agenda-sorting
2779 :type `(choice
2780 (repeat :tag "General" ,org-sorting-choice)
2781 (list :tag "Individually"
2782 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2783 (repeat ,org-sorting-choice))
2784 (cons (const :tag "Strategy for TODO lists" todo)
2785 (repeat ,org-sorting-choice))
2786 (cons (const :tag "Strategy for Tags matches" tags)
2787 (repeat ,org-sorting-choice)))))
2789 (defcustom org-sort-agenda-notime-is-late t
2790 "Non-nil means, items without time are considered late.
2791 This is only relevant for sorting. When t, items which have no explicit
2792 time like 15:30 will be considered as 99:01, i.e. later than any items which
2793 do have a time. When nil, the default time is before 0:00. You can use this
2794 option to decide if the schedule for today should come before or after timeless
2795 agenda entries."
2796 :group 'org-agenda-sorting
2797 :type 'boolean)
2799 (defgroup org-agenda-line-format nil
2800 "Options concerning the entry prefix in the Org-mode agenda display."
2801 :tag "Org Agenda Line Format"
2802 :group 'org-agenda)
2804 (defcustom org-agenda-prefix-format
2805 '((agenda . " %-12:c%?-12t% s")
2806 (timeline . " % s")
2807 (todo . " %-12:c")
2808 (tags . " %-12:c"))
2809 "Format specifications for the prefix of items in the agenda views.
2810 An alist with four entries, for the different agenda types. The keys to the
2811 sublists are `agenda', `timeline', `todo', and `tags'. The values
2812 are format strings.
2813 This format works similar to a printf format, with the following meaning:
2815 %c the category of the item, \"Diary\" for entries from the diary, or
2816 as given by the CATEGORY keyword or derived from the file name.
2817 %T the *last* tag of the item. Last because inherited tags come
2818 first in the list.
2819 %t the time-of-day specification if one applies to the entry, in the
2820 format HH:MM
2821 %s Scheduling/Deadline information, a short string
2823 All specifiers work basically like the standard `%s' of printf, but may
2824 contain two additional characters: A question mark just after the `%' and
2825 a whitespace/punctuation character just before the final letter.
2827 If the first character after `%' is a question mark, the entire field
2828 will only be included if the corresponding value applies to the
2829 current entry. This is useful for fields which should have fixed
2830 width when present, but zero width when absent. For example,
2831 \"%?-12t\" will result in a 12 character time field if a time of the
2832 day is specified, but will completely disappear in entries which do
2833 not contain a time.
2835 If there is punctuation or whitespace character just before the final
2836 format letter, this character will be appended to the field value if
2837 the value is not empty. For example, the format \"%-12:c\" leads to
2838 \"Diary: \" if the category is \"Diary\". If the category were be
2839 empty, no additional colon would be interted.
2841 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2842 - Indent the line with two space characters
2843 - Give the category in a 12 chars wide field, padded with whitespace on
2844 the right (because of `-'). Append a colon if there is a category
2845 (because of `:').
2846 - If there is a time-of-day, put it into a 12 chars wide field. If no
2847 time, don't put in an empty field, just skip it (because of '?').
2848 - Finally, put the scheduling information and append a whitespace.
2850 As another example, if you don't want the time-of-day of entries in
2851 the prefix, you could use:
2853 (setq org-agenda-prefix-format \" %-11:c% s\")
2855 See also the variables `org-agenda-remove-times-when-in-prefix' and
2856 `org-agenda-remove-tags'."
2857 :type '(choice
2858 (string :tag "General format")
2859 (list :greedy t :tag "View dependent"
2860 (cons (const agenda) (string :tag "Format"))
2861 (cons (const timeline) (string :tag "Format"))
2862 (cons (const todo) (string :tag "Format"))
2863 (cons (const tags) (string :tag "Format"))))
2864 :group 'org-agenda-line-format)
2866 (defvar org-prefix-format-compiled nil
2867 "The compiled version of the most recently used prefix format.
2868 See the variable `org-agenda-prefix-format'.")
2870 (defcustom org-agenda-todo-keyword-format "%-1s"
2871 "Format for the TODO keyword in agenda lines.
2872 Set this to something like \"%-12s\" if you want all TODO keywords
2873 to occupy a fixed space in the agenda display."
2874 :group 'org-agenda-line-format
2875 :type 'string)
2877 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
2878 "Text preceeding scheduled items in the agenda view.
2879 This is a list with two strings. The first applies when the item is
2880 scheduled on the current day. The second applies when it has been scheduled
2881 previously, it may contain a %d to capture how many days ago the item was
2882 scheduled."
2883 :group 'org-agenda-line-format
2884 :type '(list
2885 (string :tag "Scheduled today ")
2886 (string :tag "Scheduled previously")))
2888 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
2889 "Text preceeding deadline items in the agenda view.
2890 This is a list with two strings. The first applies when the item has its
2891 deadline on the current day. The second applies when it is in the past or
2892 in the future, it may contain %d to capture how many days away the deadline
2893 is (was)."
2894 :group 'org-agenda-line-format
2895 :type '(list
2896 (string :tag "Deadline today ")
2897 (string :tag "Deadline relative")))
2899 (defcustom org-agenda-remove-times-when-in-prefix t
2900 "Non-nil means, remove duplicate time specifications in agenda items.
2901 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2902 time-of-day specification in a headline or diary entry is extracted and
2903 placed into the prefix. If this option is non-nil, the original specification
2904 \(a timestamp or -range, or just a plain time(range) specification like
2905 11:30-4pm) will be removed for agenda display. This makes the agenda less
2906 cluttered.
2907 The option can be t or nil. It may also be the symbol `beg', indicating
2908 that the time should only be removed what it is located at the beginning of
2909 the headline/diary entry."
2910 :group 'org-agenda-line-format
2911 :type '(choice
2912 (const :tag "Always" t)
2913 (const :tag "Never" nil)
2914 (const :tag "When at beginning of entry" beg)))
2917 (defcustom org-agenda-default-appointment-duration nil
2918 "Default duration for appointments that only have a starting time.
2919 When nil, no duration is specified in such cases.
2920 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
2921 :group 'org-agenda-line-format
2922 :type '(choice
2923 (integer :tag "Minutes")
2924 (const :tag "No default duration")))
2927 (defcustom org-agenda-remove-tags nil
2928 "Non-nil means, remove the tags from the headline copy in the agenda.
2929 When this is the symbol `prefix', only remove tags when
2930 `org-agenda-prefix-format' contains a `%T' specifier."
2931 :group 'org-agenda-line-format
2932 :type '(choice
2933 (const :tag "Always" t)
2934 (const :tag "Never" nil)
2935 (const :tag "When prefix format contains %T" prefix)))
2937 (if (fboundp 'defvaralias)
2938 (defvaralias 'org-agenda-remove-tags-when-in-prefix
2939 'org-agenda-remove-tags))
2941 (defcustom org-agenda-tags-column -80
2942 "Shift tags in agenda items to this column.
2943 If this number is positive, it specifies the column. If it is negative,
2944 it means that the tags should be flushright to that column. For example,
2945 -80 works well for a normal 80 character screen."
2946 :group 'org-agenda-line-format
2947 :type 'integer)
2949 (if (fboundp 'defvaralias)
2950 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
2952 (defcustom org-agenda-fontify-priorities t
2953 "Non-nil means, highlight low and high priorities in agenda.
2954 When t, the highest priority entries are bold, lowest priority italic.
2955 This may also be an association list of priority faces. The face may be
2956 a names face, or a list like `(:background \"Red\")'."
2957 :group 'org-agenda-line-format
2958 :type '(choice
2959 (const :tag "Never" nil)
2960 (const :tag "Defaults" t)
2961 (repeat :tag "Specify"
2962 (list (character :tag "Priority" :value ?A)
2963 (sexp :tag "face")))))
2965 (defgroup org-latex nil
2966 "Options for embedding LaTeX code into Org-mode"
2967 :tag "Org LaTeX"
2968 :group 'org)
2970 (defcustom org-format-latex-options
2971 '(:foreground default :background default :scale 1.0
2972 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2973 :matchers ("begin" "$" "$$" "\\(" "\\["))
2974 "Options for creating images from LaTeX fragments.
2975 This is a property list with the following properties:
2976 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
2977 `default' means use the forground of the default face.
2978 :background the background color, or \"Transparent\".
2979 `default' means use the background of the default face.
2980 :scale a scaling factor for the size of the images
2981 :html-foreground, :html-background, :html-scale
2982 The same numbers for HTML export.
2983 :matchers a list indicating which matchers should be used to
2984 find LaTeX fragments. Valid members of this list are:
2985 \"begin\" find environments
2986 \"$\" find math expressions surrounded by $...$
2987 \"$$\" find math expressions surrounded by $$....$$
2988 \"\\(\" find math expressions surrounded by \\(...\\)
2989 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2990 :group 'org-latex
2991 :type 'plist)
2993 (defcustom org-format-latex-header "\\documentclass{article}
2994 \\usepackage{fullpage} % do not remove
2995 \\usepackage{amssymb}
2996 \\usepackage[usenames]{color}
2997 \\usepackage{amsmath}
2998 \\usepackage{latexsym}
2999 \\usepackage[mathscr]{eucal}
3000 \\pagestyle{empty} % do not remove"
3001 "The document header used for processing LaTeX fragments."
3002 :group 'org-latex
3003 :type 'string)
3005 (defgroup org-export nil
3006 "Options for exporting org-listings."
3007 :tag "Org Export"
3008 :group 'org)
3010 (defgroup org-export-general nil
3011 "General options for exporting Org-mode files."
3012 :tag "Org Export General"
3013 :group 'org-export)
3015 ;; FIXME
3016 (defvar org-export-publishing-directory nil)
3018 (defcustom org-export-with-special-strings t
3019 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3020 When this option is turned on, these strings will be exported as:
3022 Org HTML LaTeX
3023 -----+----------+--------
3024 \\- &shy; \\-
3025 -- &ndash; --
3026 --- &mdash; ---
3027 ... &hellip; \ldots
3029 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3030 :group 'org-export-translation
3031 :type 'boolean)
3033 (defcustom org-export-language-setup
3034 '(("en" "Author" "Date" "Table of Contents")
3035 ("cs" "Autor" "Datum" "Obsah")
3036 ("da" "Ophavsmand" "Dato" "Indhold")
3037 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
3038 ("es" "Autor" "Fecha" "\xcdndice")
3039 ("fr" "Auteur" "Date" "Table des mati\xe8res")
3040 ("it" "Autore" "Data" "Indice")
3041 ("nl" "Auteur" "Datum" "Inhoudsopgave")
3042 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
3043 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
3044 "Terms used in export text, translated to different languages.
3045 Use the variable `org-export-default-language' to set the language,
3046 or use the +OPTION lines for a per-file setting."
3047 :group 'org-export-general
3048 :type '(repeat
3049 (list
3050 (string :tag "HTML language tag")
3051 (string :tag "Author")
3052 (string :tag "Date")
3053 (string :tag "Table of Contents"))))
3055 (defcustom org-export-default-language "en"
3056 "The default language of HTML export, as a string.
3057 This should have an association in `org-export-language-setup'."
3058 :group 'org-export-general
3059 :type 'string)
3061 (defcustom org-export-skip-text-before-1st-heading t
3062 "Non-nil means, skip all text before the first headline when exporting.
3063 When nil, that text is exported as well."
3064 :group 'org-export-general
3065 :type 'boolean)
3067 (defcustom org-export-headline-levels 3
3068 "The last level which is still exported as a headline.
3069 Inferior levels will produce itemize lists when exported.
3070 Note that a numeric prefix argument to an exporter function overrides
3071 this setting.
3073 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
3074 :group 'org-export-general
3075 :type 'number)
3077 (defcustom org-export-with-section-numbers t
3078 "Non-nil means, add section numbers to headlines when exporting.
3080 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
3081 :group 'org-export-general
3082 :type 'boolean)
3084 (defcustom org-export-with-toc t
3085 "Non-nil means, create a table of contents in exported files.
3086 The TOC contains headlines with levels up to`org-export-headline-levels'.
3087 When an integer, include levels up to N in the toc, this may then be
3088 different from `org-export-headline-levels', but it will not be allowed
3089 to be larger than the number of headline levels.
3090 When nil, no table of contents is made.
3092 Headlines which contain any TODO items will be marked with \"(*)\" in
3093 ASCII export, and with red color in HTML output, if the option
3094 `org-export-mark-todo-in-toc' is set.
3096 In HTML output, the TOC will be clickable.
3098 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
3099 or \"toc:3\"."
3100 :group 'org-export-general
3101 :type '(choice
3102 (const :tag "No Table of Contents" nil)
3103 (const :tag "Full Table of Contents" t)
3104 (integer :tag "TOC to level")))
3106 (defcustom org-export-mark-todo-in-toc nil
3107 "Non-nil means, mark TOC lines that contain any open TODO items."
3108 :group 'org-export-general
3109 :type 'boolean)
3111 (defcustom org-export-preserve-breaks nil
3112 "Non-nil means, preserve all line breaks when exporting.
3113 Normally, in HTML output paragraphs will be reformatted. In ASCII
3114 export, line breaks will always be preserved, regardless of this variable.
3116 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3117 :group 'org-export-general
3118 :type 'boolean)
3120 (defcustom org-export-with-archived-trees 'headline
3121 "Whether subtrees with the ARCHIVE tag should be exported.
3122 This can have three different values
3123 nil Do not export, pretend this tree is not present
3124 t Do export the entire tree
3125 headline Only export the headline, but skip the tree below it."
3126 :group 'org-export-general
3127 :group 'org-archive
3128 :type '(choice
3129 (const :tag "not at all" nil)
3130 (const :tag "headline only" 'headline)
3131 (const :tag "entirely" t)))
3133 (defcustom org-export-author-info t
3134 "Non-nil means, insert author name and email into the exported file.
3136 This option can also be set with the +OPTIONS line,
3137 e.g. \"author-info:nil\"."
3138 :group 'org-export-general
3139 :type 'boolean)
3141 (defcustom org-export-time-stamp-file t
3142 "Non-nil means, insert a time stamp into the exported file.
3143 The time stamp shows when the file was created.
3145 This option can also be set with the +OPTIONS line,
3146 e.g. \"timestamp:nil\"."
3147 :group 'org-export-general
3148 :type 'boolean)
3150 (defcustom org-export-with-timestamps t
3151 "If nil, do not export time stamps and associated keywords."
3152 :group 'org-export-general
3153 :type 'boolean)
3155 (defcustom org-export-remove-timestamps-from-toc t
3156 "If nil, remove timestamps from the table of contents entries."
3157 :group 'org-export-general
3158 :type 'boolean)
3160 (defcustom org-export-with-tags 'not-in-toc
3161 "If nil, do not export tags, just remove them from headlines.
3162 If this is the symbol `not-in-toc', tags will be removed from table of
3163 contents entries, but still be shown in the headlines of the document.
3165 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3166 :group 'org-export-general
3167 :type '(choice
3168 (const :tag "Off" nil)
3169 (const :tag "Not in TOC" not-in-toc)
3170 (const :tag "On" t)))
3172 (defcustom org-export-with-drawers nil
3173 "Non-nil means, export with drawers like the property drawer.
3174 When t, all drawers are exported. This may also be a list of
3175 drawer names to export."
3176 :group 'org-export-general
3177 :type '(choice
3178 (const :tag "All drawers" t)
3179 (const :tag "None" nil)
3180 (repeat :tag "Selected drawers"
3181 (string :tag "Drawer name"))))
3183 (defgroup org-export-translation nil
3184 "Options for translating special ascii sequences for the export backends."
3185 :tag "Org Export Translation"
3186 :group 'org-export)
3188 (defcustom org-export-with-emphasize t
3189 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3190 If the export target supports emphasizing text, the word will be
3191 typeset in bold, italic, or underlined, respectively. Works only for
3192 single words, but you can say: I *really* *mean* *this*.
3193 Not all export backends support this.
3195 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3196 :group 'org-export-translation
3197 :type 'boolean)
3199 (defcustom org-export-with-footnotes t
3200 "If nil, export [1] as a footnote marker.
3201 Lines starting with [1] will be formatted as footnotes.
3203 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3204 :group 'org-export-translation
3205 :type 'boolean)
3207 (defcustom org-export-with-sub-superscripts t
3208 "Non-nil means, interpret \"_\" and \"^\" for export.
3209 When this option is turned on, you can use TeX-like syntax for sub- and
3210 superscripts. Several characters after \"_\" or \"^\" will be
3211 considered as a single item - so grouping with {} is normally not
3212 needed. For example, the following things will be parsed as single
3213 sub- or superscripts.
3215 10^24 or 10^tau several digits will be considered 1 item.
3216 10^-12 or 10^-tau a leading sign with digits or a word
3217 x^2-y^3 will be read as x^2 - y^3, because items are
3218 terminated by almost any nonword/nondigit char.
3219 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3221 Still, ambiguity is possible - so when in doubt use {} to enclose the
3222 sub/superscript. If you set this variable to the symbol `{}',
3223 the braces are *required* in order to trigger interpretations as
3224 sub/superscript. This can be helpful in documents that need \"_\"
3225 frequently in plain text.
3227 Not all export backends support this, but HTML does.
3229 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3230 :group 'org-export-translation
3231 :type '(choice
3232 (const :tag "Always interpret" t)
3233 (const :tag "Only with braces" {})
3234 (const :tag "Never interpret" nil)))
3236 (defcustom org-export-with-special-strings t
3237 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3238 When this option is turned on, these strings will be exported as:
3240 \\- : &shy;
3241 -- : &ndash;
3242 --- : &mdash;
3244 Not all export backends support this, but HTML does.
3246 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3247 :group 'org-export-translation
3248 :type 'boolean)
3250 (defcustom org-export-with-TeX-macros t
3251 "Non-nil means, interpret simple TeX-like macros when exporting.
3252 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3253 No only real TeX macros will work here, but the standard HTML entities
3254 for math can be used as macro names as well. For a list of supported
3255 names in HTML export, see the constant `org-html-entities'.
3256 Not all export backends support this.
3258 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3259 :group 'org-export-translation
3260 :group 'org-export-latex
3261 :type 'boolean)
3263 (defcustom org-export-with-LaTeX-fragments nil
3264 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3265 When set, the exporter will find LaTeX environments if the \\begin line is
3266 the first non-white thing on a line. It will also find the math delimiters
3267 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3268 display math.
3270 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3271 :group 'org-export-translation
3272 :group 'org-export-latex
3273 :type 'boolean)
3275 (defcustom org-export-with-fixed-width t
3276 "Non-nil means, lines starting with \":\" will be in fixed width font.
3277 This can be used to have pre-formatted text, fragments of code etc. For
3278 example:
3279 : ;; Some Lisp examples
3280 : (while (defc cnt)
3281 : (ding))
3282 will be looking just like this in also HTML. See also the QUOTE keyword.
3283 Not all export backends support this.
3285 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3286 :group 'org-export-translation
3287 :type 'boolean)
3289 (defcustom org-match-sexp-depth 3
3290 "Number of stacked braces for sub/superscript matching.
3291 This has to be set before loading org.el to be effective."
3292 :group 'org-export-translation
3293 :type 'integer)
3295 (defgroup org-export-tables nil
3296 "Options for exporting tables in Org-mode."
3297 :tag "Org Export Tables"
3298 :group 'org-export)
3300 (defcustom org-export-with-tables t
3301 "If non-nil, lines starting with \"|\" define a table.
3302 For example:
3304 | Name | Address | Birthday |
3305 |-------------+----------+-----------|
3306 | Arthur Dent | England | 29.2.2100 |
3308 Not all export backends support this.
3310 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3311 :group 'org-export-tables
3312 :type 'boolean)
3314 (defcustom org-export-highlight-first-table-line t
3315 "Non-nil means, highlight the first table line.
3316 In HTML export, this means use <th> instead of <td>.
3317 In tables created with table.el, this applies to the first table line.
3318 In Org-mode tables, all lines before the first horizontal separator
3319 line will be formatted with <th> tags."
3320 :group 'org-export-tables
3321 :type 'boolean)
3323 (defcustom org-export-table-remove-special-lines t
3324 "Remove special lines and marking characters in calculating tables.
3325 This removes the special marking character column from tables that are set
3326 up for spreadsheet calculations. It also removes the entire lines
3327 marked with `!', `_', or `^'. The lines with `$' are kept, because
3328 the values of constants may be useful to have."
3329 :group 'org-export-tables
3330 :type 'boolean)
3332 (defcustom org-export-prefer-native-exporter-for-tables nil
3333 "Non-nil means, always export tables created with table.el natively.
3334 Natively means, use the HTML code generator in table.el.
3335 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3336 the table does not use row- or column-spanning). This has the
3337 advantage, that the automatic HTML conversions for math symbols and
3338 sub/superscripts can be applied. Org-mode's HTML generator is also
3339 much faster."
3340 :group 'org-export-tables
3341 :type 'boolean)
3343 (defgroup org-export-ascii nil
3344 "Options specific for ASCII export of Org-mode files."
3345 :tag "Org Export ASCII"
3346 :group 'org-export)
3348 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3349 "Characters for underlining headings in ASCII export.
3350 In the given sequence, these characters will be used for level 1, 2, ..."
3351 :group 'org-export-ascii
3352 :type '(repeat character))
3354 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3355 "Bullet characters for headlines converted to lists in ASCII export.
3356 The first character is used for the first lest level generated in this
3357 way, and so on. If there are more levels than characters given here,
3358 the list will be repeated.
3359 Note that plain lists will keep the same bullets as the have in the
3360 Org-mode file."
3361 :group 'org-export-ascii
3362 :type '(repeat character))
3364 (defgroup org-export-xml nil
3365 "Options specific for XML export of Org-mode files."
3366 :tag "Org Export XML"
3367 :group 'org-export)
3369 (defgroup org-export-html nil
3370 "Options specific for HTML export of Org-mode files."
3371 :tag "Org Export HTML"
3372 :group 'org-export)
3374 (defcustom org-export-html-coding-system nil
3376 :group 'org-export-html
3377 :type 'coding-system)
3379 (defcustom org-export-html-extension "html"
3380 "The extension for exported HTML files."
3381 :group 'org-export-html
3382 :type 'string)
3384 (defcustom org-export-html-style
3385 "<style type=\"text/css\">
3386 html {
3387 font-family: Times, serif;
3388 font-size: 12pt;
3390 .title { text-align: center; }
3391 .todo { color: red; }
3392 .done { color: green; }
3393 .timestamp { color: grey }
3394 .timestamp-kwd { color: CadetBlue }
3395 .tag { background-color:lightblue; font-weight:normal }
3396 .target { background-color: lavender; }
3397 pre {
3398 border: 1pt solid #AEBDCC;
3399 background-color: #F3F5F7;
3400 padding: 5pt;
3401 font-family: courier, monospace;
3403 table { border-collapse: collapse; }
3404 td, th {
3405 vertical-align: top;
3406 <!--border: 1pt solid #ADB9CC;-->
3408 </style>"
3409 "The default style specification for exported HTML files.
3410 Since there are different ways of setting style information, this variable
3411 needs to contain the full HTML structure to provide a style, including the
3412 surrounding HTML tags. The style specifications should include definitions
3413 for new classes todo, done, title, and deadline. For example, legal values
3414 would be:
3416 <style type=\"text/css\">
3417 p { font-weight: normal; color: gray; }
3418 h1 { color: black; }
3419 .title { text-align: center; }
3420 .todo, .deadline { color: red; }
3421 .done { color: green; }
3422 </style>
3424 or, if you want to keep the style in a file,
3426 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3428 As the value of this option simply gets inserted into the HTML <head> header,
3429 you can \"misuse\" it to add arbitrary text to the header."
3430 :group 'org-export-html
3431 :type 'string)
3434 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3435 "Format for typesetting the document title in HTML export."
3436 :group 'org-export-html
3437 :type 'string)
3439 (defcustom org-export-html-toplevel-hlevel 2
3440 "The <H> level for level 1 headings in HTML export."
3441 :group 'org-export-html
3442 :type 'string)
3444 (defcustom org-export-html-link-org-files-as-html t
3445 "Non-nil means, make file links to `file.org' point to `file.html'.
3446 When org-mode is exporting an org-mode file to HTML, links to
3447 non-html files are directly put into a href tag in HTML.
3448 However, links to other Org-mode files (recognized by the
3449 extension `.org.) should become links to the corresponding html
3450 file, assuming that the linked org-mode file will also be
3451 converted to HTML.
3452 When nil, the links still point to the plain `.org' file."
3453 :group 'org-export-html
3454 :type 'boolean)
3456 (defcustom org-export-html-inline-images 'maybe
3457 "Non-nil means, inline images into exported HTML pages.
3458 This is done using an <img> tag. When nil, an anchor with href is used to
3459 link to the image. If this option is `maybe', then images in links with
3460 an empty description will be inlined, while images with a description will
3461 be linked only."
3462 :group 'org-export-html
3463 :type '(choice (const :tag "Never" nil)
3464 (const :tag "Always" t)
3465 (const :tag "When there is no description" maybe)))
3467 ;; FIXME: rename
3468 (defcustom org-export-html-expand t
3469 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3470 When nil, these tags will be exported as plain text and therefore
3471 not be interpreted by a browser.
3473 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3474 :group 'org-export-html
3475 :type 'boolean)
3477 (defcustom org-export-html-table-tag
3478 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3479 "The HTML tag that is used to start a table.
3480 This must be a <table> tag, but you may change the options like
3481 borders and spacing."
3482 :group 'org-export-html
3483 :type 'string)
3485 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3486 "The opening tag for table header fields.
3487 This is customizable so that alignment options can be specified."
3488 :group 'org-export-tables
3489 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3491 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3492 "The opening tag for table data fields.
3493 This is customizable so that alignment options can be specified."
3494 :group 'org-export-tables
3495 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3497 (defcustom org-export-html-with-timestamp nil
3498 "If non-nil, write `org-export-html-html-helper-timestamp'
3499 into the exported HTML text. Otherwise, the buffer will just be saved
3500 to a file."
3501 :group 'org-export-html
3502 :type 'boolean)
3504 (defcustom org-export-html-html-helper-timestamp
3505 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3506 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3507 :group 'org-export-html
3508 :type 'string)
3510 (defgroup org-export-icalendar nil
3511 "Options specific for iCalendar export of Org-mode files."
3512 :tag "Org Export iCalendar"
3513 :group 'org-export)
3515 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3516 "The file name for the iCalendar file covering all agenda files.
3517 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3518 The file name should be absolute, the file will be overwritten without warning."
3519 :group 'org-export-icalendar
3520 :type 'file)
3522 (defcustom org-icalendar-include-todo nil
3523 "Non-nil means, export to iCalendar files should also cover TODO items."
3524 :group 'org-export-icalendar
3525 :type '(choice
3526 (const :tag "None" nil)
3527 (const :tag "Unfinished" t)
3528 (const :tag "All" all)))
3530 (defcustom org-icalendar-include-sexps t
3531 "Non-nil means, export to iCalendar files should also cover sexp entries.
3532 These are entries like in the diary, but directly in an Org-mode file."
3533 :group 'org-export-icalendar
3534 :type 'boolean)
3536 (defcustom org-icalendar-include-body 100
3537 "Amount of text below headline to be included in iCalendar export.
3538 This is a number of characters that should maximally be included.
3539 Properties, scheduling and clocking lines will always be removed.
3540 The text will be inserted into the DESCRIPTION field."
3541 :group 'org-export-icalendar
3542 :type '(choice
3543 (const :tag "Nothing" nil)
3544 (const :tag "Everything" t)
3545 (integer :tag "Max characters")))
3547 (defcustom org-icalendar-combined-name "OrgMode"
3548 "Calendar name for the combined iCalendar representing all agenda files."
3549 :group 'org-export-icalendar
3550 :type 'string)
3552 (defgroup org-font-lock nil
3553 "Font-lock settings for highlighting in Org-mode."
3554 :tag "Org Font Lock"
3555 :group 'org)
3557 (defcustom org-level-color-stars-only nil
3558 "Non-nil means fontify only the stars in each headline.
3559 When nil, the entire headline is fontified.
3560 Changing it requires restart of `font-lock-mode' to become effective
3561 also in regions already fontified."
3562 :group 'org-font-lock
3563 :type 'boolean)
3565 (defcustom org-hide-leading-stars nil
3566 "Non-nil means, hide the first N-1 stars in a headline.
3567 This works by using the face `org-hide' for these stars. This
3568 face is white for a light background, and black for a dark
3569 background. You may have to customize the face `org-hide' to
3570 make this work.
3571 Changing it requires restart of `font-lock-mode' to become effective
3572 also in regions already fontified.
3573 You may also set this on a per-file basis by adding one of the following
3574 lines to the buffer:
3576 #+STARTUP: hidestars
3577 #+STARTUP: showstars"
3578 :group 'org-font-lock
3579 :type 'boolean)
3581 (defcustom org-fontify-done-headline nil
3582 "Non-nil means, change the face of a headline if it is marked DONE.
3583 Normally, only the TODO/DONE keyword indicates the state of a headline.
3584 When this is non-nil, the headline after the keyword is set to the
3585 `org-headline-done' as an additional indication."
3586 :group 'org-font-lock
3587 :type 'boolean)
3589 (defcustom org-fontify-emphasized-text t
3590 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3591 Changing this variable requires a restart of Emacs to take effect."
3592 :group 'org-font-lock
3593 :type 'boolean)
3595 (defcustom org-highlight-latex-fragments-and-specials nil
3596 "Non-nil means, fontify what is treated specially by the exporters."
3597 :group 'org-font-lock
3598 :type 'boolean)
3600 (defcustom org-hide-emphasis-markers nil
3601 "Non-nil mean font-lock should hide the emphasis marker characters."
3602 :group 'org-font-lock
3603 :type 'boolean)
3605 (defvar org-emph-re nil
3606 "Regular expression for matching emphasis.")
3607 (defvar org-verbatim-re nil
3608 "Regular expression for matching verbatim text.")
3609 (defvar org-emphasis-regexp-components) ; defined just below
3610 (defvar org-emphasis-alist) ; defined just below
3611 (defun org-set-emph-re (var val)
3612 "Set variable and compute the emphasis regular expression."
3613 (set var val)
3614 (when (and (boundp 'org-emphasis-alist)
3615 (boundp 'org-emphasis-regexp-components)
3616 org-emphasis-alist org-emphasis-regexp-components)
3617 (let* ((e org-emphasis-regexp-components)
3618 (pre (car e))
3619 (post (nth 1 e))
3620 (border (nth 2 e))
3621 (body (nth 3 e))
3622 (nl (nth 4 e))
3623 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3624 (body1 (concat body "*?"))
3625 (markers (mapconcat 'car org-emphasis-alist ""))
3626 (vmarkers (mapconcat
3627 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3628 org-emphasis-alist "")))
3629 ;; make sure special characters appear at the right position in the class
3630 (if (string-match "\\^" markers)
3631 (setq markers (concat (replace-match "" t t markers) "^")))
3632 (if (string-match "-" markers)
3633 (setq markers (concat (replace-match "" t t markers) "-")))
3634 (if (string-match "\\^" vmarkers)
3635 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3636 (if (string-match "-" vmarkers)
3637 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3638 (if (> nl 0)
3639 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3640 (int-to-string nl) "\\}")))
3641 ;; Make the regexp
3642 (setq org-emph-re
3643 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3644 "\\("
3645 "\\([" markers "]\\)"
3646 "\\("
3647 "[^" border "]\\|"
3648 "[^" border (if (and nil stacked) markers) "]"
3649 body1
3650 "[^" border (if (and nil stacked) markers) "]"
3651 "\\)"
3652 "\\3\\)"
3653 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3654 (setq org-verbatim-re
3655 (concat "\\([" pre "]\\|^\\)"
3656 "\\("
3657 "\\([" vmarkers "]\\)"
3658 "\\("
3659 "[^" border "]\\|"
3660 "[^" border "]"
3661 body1
3662 "[^" border "]"
3663 "\\)"
3664 "\\3\\)"
3665 "\\([" post "]\\|$\\)")))))
3667 (defcustom org-emphasis-regexp-components
3668 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3669 "Components used to build the regular expression for emphasis.
3670 This is a list with 6 entries. Terminology: In an emphasis string
3671 like \" *strong word* \", we call the initial space PREMATCH, the final
3672 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3673 and \"trong wor\" is the body. The different components in this variable
3674 specify what is allowed/forbidden in each part:
3676 pre Chars allowed as prematch. Beginning of line will be allowed too.
3677 post Chars allowed as postmatch. End of line will be allowed too.
3678 border The chars *forbidden* as border characters.
3679 body-regexp A regexp like \".\" to match a body character. Don't use
3680 non-shy groups here, and don't allow newline here.
3681 newline The maximum number of newlines allowed in an emphasis exp.
3683 Use customize to modify this, or restart Emacs after changing it."
3684 :group 'org-font-lock
3685 :set 'org-set-emph-re
3686 :type '(list
3687 (sexp :tag "Allowed chars in pre ")
3688 (sexp :tag "Allowed chars in post ")
3689 (sexp :tag "Forbidden chars in border ")
3690 (sexp :tag "Regexp for body ")
3691 (integer :tag "number of newlines allowed")
3692 (option (boolean :tag "Stacking (DISABLED) "))))
3694 (defcustom org-emphasis-alist
3695 '(("*" bold "<b>" "</b>")
3696 ("/" italic "<i>" "</i>")
3697 ("_" underline "<u>" "</u>")
3698 ("=" org-code "<code>" "</code>" verbatim)
3699 ("~" org-verbatim "" "" verbatim)
3700 ("+" (:strike-through t) "<del>" "</del>")
3702 "Special syntax for emphasized text.
3703 Text starting and ending with a special character will be emphasized, for
3704 example *bold*, _underlined_ and /italic/. This variable sets the marker
3705 characters, the face to be used by font-lock for highlighting in Org-mode
3706 Emacs buffers, and the HTML tags to be used for this.
3707 Use customize to modify this, or restart Emacs after changing it."
3708 :group 'org-font-lock
3709 :set 'org-set-emph-re
3710 :type '(repeat
3711 (list
3712 (string :tag "Marker character")
3713 (choice
3714 (face :tag "Font-lock-face")
3715 (plist :tag "Face property list"))
3716 (string :tag "HTML start tag")
3717 (string :tag "HTML end tag")
3718 (option (const verbatim)))))
3720 ;;; The faces
3722 (defgroup org-faces nil
3723 "Faces in Org-mode."
3724 :tag "Org Faces"
3725 :group 'org-font-lock)
3727 (defun org-compatible-face (inherits specs)
3728 "Make a compatible face specification.
3729 If INHERITS is an existing face and if the Emacs version supports it,
3730 just inherit the face. If not, use SPECS to define the face.
3731 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3732 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3733 to the top of the list. The `min-colors' attribute will be removed from
3734 any other entries, and any resulting duplicates will be removed entirely."
3735 (cond
3736 ((and inherits (facep inherits)
3737 (not (featurep 'xemacs)) (> emacs-major-version 22))
3738 ;; In Emacs 23, we use inheritance where possible.
3739 ;; We only do this in Emacs 23, because only there the outline
3740 ;; faces have been changed to the original org-mode-level-faces.
3741 (list (list t :inherit inherits)))
3742 ((or (featurep 'xemacs) (< emacs-major-version 22))
3743 ;; These do not understand the `min-colors' attribute.
3744 (let (r e a)
3745 (while (setq e (pop specs))
3746 (cond
3747 ((memq (car e) '(t default)) (push e r))
3748 ((setq a (member '(min-colors 8) (car e)))
3749 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3750 (cdr e)))))
3751 ((setq a (assq 'min-colors (car e)))
3752 (setq e (cons (delq a (car e)) (cdr e)))
3753 (or (assoc (car e) r) (push e r)))
3754 (t (or (assoc (car e) r) (push e r)))))
3755 (nreverse r)))
3756 (t specs)))
3757 (put 'org-compatible-face 'lisp-indent-function 1)
3759 (defface org-hide
3760 '((((background light)) (:foreground "white"))
3761 (((background dark)) (:foreground "black")))
3762 "Face used to hide leading stars in headlines.
3763 The forground color of this face should be equal to the background
3764 color of the frame."
3765 :group 'org-faces)
3767 (defface org-level-1 ;; font-lock-function-name-face
3768 (org-compatible-face 'outline-1
3769 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3770 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3771 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3772 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3773 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3774 (t (:bold t))))
3775 "Face used for level 1 headlines."
3776 :group 'org-faces)
3778 (defface org-level-2 ;; font-lock-variable-name-face
3779 (org-compatible-face 'outline-2
3780 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3781 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3782 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3783 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3784 (t (:bold t))))
3785 "Face used for level 2 headlines."
3786 :group 'org-faces)
3788 (defface org-level-3 ;; font-lock-keyword-face
3789 (org-compatible-face 'outline-3
3790 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3791 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3792 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3793 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3794 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3795 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3796 (t (:bold t))))
3797 "Face used for level 3 headlines."
3798 :group 'org-faces)
3800 (defface org-level-4 ;; font-lock-comment-face
3801 (org-compatible-face 'outline-4
3802 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3803 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3804 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3805 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3806 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3807 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3808 (t (:bold t))))
3809 "Face used for level 4 headlines."
3810 :group 'org-faces)
3812 (defface org-level-5 ;; font-lock-type-face
3813 (org-compatible-face 'outline-5
3814 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3815 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3816 (((class color) (min-colors 8)) (:foreground "green"))))
3817 "Face used for level 5 headlines."
3818 :group 'org-faces)
3820 (defface org-level-6 ;; font-lock-constant-face
3821 (org-compatible-face 'outline-6
3822 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3823 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3824 (((class color) (min-colors 8)) (:foreground "magenta"))))
3825 "Face used for level 6 headlines."
3826 :group 'org-faces)
3828 (defface org-level-7 ;; font-lock-builtin-face
3829 (org-compatible-face 'outline-7
3830 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3831 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3832 (((class color) (min-colors 8)) (:foreground "blue"))))
3833 "Face used for level 7 headlines."
3834 :group 'org-faces)
3836 (defface org-level-8 ;; font-lock-string-face
3837 (org-compatible-face 'outline-8
3838 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3839 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3840 (((class color) (min-colors 8)) (:foreground "green"))))
3841 "Face used for level 8 headlines."
3842 :group 'org-faces)
3844 (defface org-special-keyword ;; font-lock-string-face
3845 (org-compatible-face nil
3846 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3847 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3848 (t (:italic t))))
3849 "Face used for special keywords."
3850 :group 'org-faces)
3852 (defface org-drawer ;; font-lock-function-name-face
3853 (org-compatible-face nil
3854 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3855 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3856 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3857 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3858 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3859 (t (:bold t))))
3860 "Face used for drawers."
3861 :group 'org-faces)
3863 (defface org-property-value nil
3864 "Face used for the value of a property."
3865 :group 'org-faces)
3867 (defface org-column
3868 (org-compatible-face nil
3869 '((((class color) (min-colors 16) (background light))
3870 (:background "grey90"))
3871 (((class color) (min-colors 16) (background dark))
3872 (:background "grey30"))
3873 (((class color) (min-colors 8))
3874 (:background "cyan" :foreground "black"))
3875 (t (:inverse-video t))))
3876 "Face for column display of entry properties."
3877 :group 'org-faces)
3879 (when (fboundp 'set-face-attribute)
3880 ;; Make sure that a fixed-width face is used when we have a column table.
3881 (set-face-attribute 'org-column nil
3882 :height (face-attribute 'default :height)
3883 :family (face-attribute 'default :family)))
3885 (defface org-warning
3886 (org-compatible-face 'font-lock-warning-face
3887 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3888 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3889 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3890 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3891 (t (:bold t))))
3892 "Face for deadlines and TODO keywords."
3893 :group 'org-faces)
3895 (defface org-archived ; similar to shadow
3896 (org-compatible-face 'shadow
3897 '((((class color grayscale) (min-colors 88) (background light))
3898 (:foreground "grey50"))
3899 (((class color grayscale) (min-colors 88) (background dark))
3900 (:foreground "grey70"))
3901 (((class color) (min-colors 8) (background light))
3902 (:foreground "green"))
3903 (((class color) (min-colors 8) (background dark))
3904 (:foreground "yellow"))))
3905 "Face for headline with the ARCHIVE tag."
3906 :group 'org-faces)
3908 (defface org-link
3909 '((((class color) (background light)) (:foreground "Purple" :underline t))
3910 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3911 (t (:underline t)))
3912 "Face for links."
3913 :group 'org-faces)
3915 (defface org-ellipsis
3916 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
3917 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
3918 (t (:strike-through t)))
3919 "Face for the ellipsis in folded text."
3920 :group 'org-faces)
3922 (defface org-target
3923 '((((class color) (background light)) (:underline t))
3924 (((class color) (background dark)) (:underline t))
3925 (t (:underline t)))
3926 "Face for links."
3927 :group 'org-faces)
3929 (defface org-date
3930 '((((class color) (background light)) (:foreground "Purple" :underline t))
3931 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3932 (t (:underline t)))
3933 "Face for links."
3934 :group 'org-faces)
3936 (defface org-sexp-date
3937 '((((class color) (background light)) (:foreground "Purple"))
3938 (((class color) (background dark)) (:foreground "Cyan"))
3939 (t (:underline t)))
3940 "Face for links."
3941 :group 'org-faces)
3943 (defface org-tag
3944 '((t (:bold t)))
3945 "Face for tags."
3946 :group 'org-faces)
3948 (defface org-todo ; font-lock-warning-face
3949 (org-compatible-face nil
3950 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3951 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3952 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3953 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3954 (t (:inverse-video t :bold t))))
3955 "Face for TODO keywords."
3956 :group 'org-faces)
3958 (defface org-done ;; font-lock-type-face
3959 (org-compatible-face nil
3960 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
3961 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
3962 (((class color) (min-colors 8)) (:foreground "green"))
3963 (t (:bold t))))
3964 "Face used for todo keywords that indicate DONE items."
3965 :group 'org-faces)
3967 (defface org-headline-done ;; font-lock-string-face
3968 (org-compatible-face nil
3969 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3970 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3971 (((class color) (min-colors 8) (background light)) (:bold nil))))
3972 "Face used to indicate that a headline is DONE.
3973 This face is only used if `org-fontify-done-headline' is set. If applies
3974 to the part of the headline after the DONE keyword."
3975 :group 'org-faces)
3977 (defcustom org-todo-keyword-faces nil
3978 "Faces for specific TODO keywords.
3979 This is a list of cons cells, with TODO keywords in the car
3980 and faces in the cdr. The face can be a symbol, or a property
3981 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
3982 :group 'org-faces
3983 :group 'org-todo
3984 :type '(repeat
3985 (cons
3986 (string :tag "keyword")
3987 (sexp :tag "face"))))
3989 (defface org-table ;; font-lock-function-name-face
3990 (org-compatible-face nil
3991 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3992 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3993 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3994 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3995 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
3996 (((class color) (min-colors 8) (background dark)))))
3997 "Face used for tables."
3998 :group 'org-faces)
4000 (defface org-formula
4001 (org-compatible-face nil
4002 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4003 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4004 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4005 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
4006 (t (:bold t :italic t))))
4007 "Face for formulas."
4008 :group 'org-faces)
4010 (defface org-code
4011 (org-compatible-face nil
4012 '((((class color grayscale) (min-colors 88) (background light))
4013 (:foreground "grey50"))
4014 (((class color grayscale) (min-colors 88) (background dark))
4015 (:foreground "grey70"))
4016 (((class color) (min-colors 8) (background light))
4017 (:foreground "green"))
4018 (((class color) (min-colors 8) (background dark))
4019 (:foreground "yellow"))))
4020 "Face for fixed-with text like code snippets."
4021 :group 'org-faces
4022 :version "22.1")
4024 (defface org-verbatim
4025 (org-compatible-face nil
4026 '((((class color grayscale) (min-colors 88) (background light))
4027 (:foreground "grey50" :underline t))
4028 (((class color grayscale) (min-colors 88) (background dark))
4029 (:foreground "grey70" :underline t))
4030 (((class color) (min-colors 8) (background light))
4031 (:foreground "green" :underline t))
4032 (((class color) (min-colors 8) (background dark))
4033 (:foreground "yellow" :underline t))))
4034 "Face for fixed-with text like code snippets."
4035 :group 'org-faces
4036 :version "22.1")
4038 (defface org-agenda-structure ;; font-lock-function-name-face
4039 (org-compatible-face nil
4040 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4041 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4042 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4043 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4044 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4045 (t (:bold t))))
4046 "Face used in agenda for captions and dates."
4047 :group 'org-faces)
4049 (defface org-scheduled-today
4050 (org-compatible-face nil
4051 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
4052 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
4053 (((class color) (min-colors 8)) (:foreground "green"))
4054 (t (:bold t :italic t))))
4055 "Face for items scheduled for a certain day."
4056 :group 'org-faces)
4058 (defface org-scheduled-previously
4059 (org-compatible-face nil
4060 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4061 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4062 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4063 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4064 (t (:bold t))))
4065 "Face for items scheduled previously, and not yet done."
4066 :group 'org-faces)
4068 (defface org-upcoming-deadline
4069 (org-compatible-face nil
4070 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4071 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4072 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4073 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4074 (t (:bold t))))
4075 "Face for items scheduled previously, and not yet done."
4076 :group 'org-faces)
4078 (defcustom org-agenda-deadline-faces
4079 '((1.0 . org-warning)
4080 (0.5 . org-upcoming-deadline)
4081 (0.0 . default))
4082 "Faces for showing deadlines in the agenda.
4083 This is a list of cons cells. The cdr of each cell is a face to be used,
4084 and it can also just be like '(:foreground \"yellow\").
4085 Each car is a fraction of the head-warning time that must have passed for
4086 this the face in the cdr to be used for display. The numbers must be
4087 given in descending order. The head-warning time is normally taken
4088 from `org-deadline-warning-days', but can also be specified in the deadline
4089 timestamp itself, like this:
4091 DEADLINE: <2007-08-13 Mon -8d>
4093 You may use d for days, w for weeks, m for months and y for years. Months
4094 and years will only be treated in an approximate fashion (30.4 days for a
4095 month and 365.24 days for a year)."
4096 :group 'org-faces
4097 :group 'org-agenda-daily/weekly
4098 :type '(repeat
4099 (cons
4100 (number :tag "Fraction of head-warning time passed")
4101 (sexp :tag "Face"))))
4103 ;; FIXME: this is not a good face yet.
4104 (defface org-agenda-restriction-lock
4105 (org-compatible-face nil
4106 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
4107 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
4108 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
4109 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
4110 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
4111 (t (:inverse-video t))))
4112 "Face for showing the agenda restriction lock."
4113 :group 'org-faces)
4115 (defface org-time-grid ;; font-lock-variable-name-face
4116 (org-compatible-face nil
4117 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4118 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4119 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4120 "Face used for time grids."
4121 :group 'org-faces)
4123 (defconst org-level-faces
4124 '(org-level-1 org-level-2 org-level-3 org-level-4
4125 org-level-5 org-level-6 org-level-7 org-level-8
4128 (defcustom org-n-level-faces (length org-level-faces)
4129 "The number different faces to be used for headlines.
4130 Org-mode defines 8 different headline faces, so this can be at most 8.
4131 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4132 :type 'number
4133 :group 'org-faces)
4135 ;;; Functions and variables from ther packages
4136 ;; Declared here to avoid compiler warnings
4138 (eval-and-compile
4139 (unless (fboundp 'declare-function)
4140 (defmacro declare-function (fn file &optional arglist fileonly))))
4142 ;; XEmacs only
4143 (defvar outline-mode-menu-heading)
4144 (defvar outline-mode-menu-show)
4145 (defvar outline-mode-menu-hide)
4146 (defvar zmacs-regions) ; XEmacs regions
4148 ;; Emacs only
4149 (defvar mark-active)
4151 ;; Various packages
4152 ;; FIXME: get the argument lists for the UNKNOWN stuff
4153 (declare-function add-to-diary-list "diary-lib"
4154 (date string specifier &optional marker globcolor literal))
4155 (declare-function table--at-cell-p "table" (position &optional object at-column))
4156 (declare-function Info-find-node "info" (filename nodename &optional no-going-back))
4157 (declare-function Info-goto-node "info" (nodename &optional fork))
4158 (declare-function bbdb "ext:bbdb-com" (string elidep))
4159 (declare-function bbdb-company "ext:bbdb-com" (string elidep))
4160 (declare-function bbdb-current-record "ext:bbdb-com" (&optional planning-on-modifying))
4161 (declare-function bbdb-name "ext:bbdb-com" (string elidep))
4162 (declare-function bbdb-record-getprop "ext:bbdb" (record property))
4163 (declare-function bbdb-record-name "ext:bbdb" (record))
4164 (declare-function bibtex-beginning-of-entry "bibtex" ())
4165 (declare-function bibtex-generate-autokey "bibtex" ())
4166 (declare-function bibtex-parse-entry "bibtex" (&optional content))
4167 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
4168 (defvar calc-embedded-close-formula)
4169 (defvar calc-embedded-open-formula)
4170 (declare-function calendar-astro-date-string "cal-julian" (&optional date))
4171 (declare-function calendar-bahai-date-string "cal-bahai" (&optional date))
4172 (declare-function calendar-check-holidays "holidays" (date))
4173 (declare-function calendar-chinese-date-string "cal-china" (&optional date))
4174 (declare-function calendar-coptic-date-string "cal-coptic" (&optional date))
4175 (declare-function calendar-ethiopic-date-string "cal-coptic" (&optional date))
4176 (declare-function calendar-forward-day "cal-move" (arg))
4177 (declare-function calendar-french-date-string "cal-french" (&optional date))
4178 (declare-function calendar-goto-date "cal-move" (date))
4179 (declare-function calendar-goto-today "cal-move" ())
4180 (declare-function calendar-hebrew-date-string "cal-hebrew" (&optional date))
4181 (declare-function calendar-islamic-date-string "cal-islam" (&optional date))
4182 (declare-function calendar-iso-date-string "cal-iso" (&optional date))
4183 (declare-function calendar-julian-date-string "cal-julian" (&optional date))
4184 (declare-function calendar-mayan-date-string "cal-mayan" (&optional date))
4185 (declare-function calendar-persian-date-string "cal-persia" (&optional date))
4186 (defvar calendar-mode-map)
4187 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4188 (declare-function cdlatex-tab "ext:cdlatex" ())
4189 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4190 (declare-function elmo-folder-exists-p "ext:elmo" (folder) t)
4191 (declare-function elmo-message-entity-field "ext:elmo-msgdb" (entity field &optional type))
4192 (declare-function elmo-message-field "ext:elmo" (folder number field &optional type) t)
4193 (declare-function elmo-msgdb-overview-get-entity "ext:elmo" (&rest unknown) t)
4194 (defvar font-lock-unfontify-region-function)
4195 (declare-function gnus-article-show-summary "gnus-art" ())
4196 (declare-function gnus-summary-last-subject "gnus-sum" ())
4197 (defvar gnus-other-frame-object)
4198 (defvar gnus-group-name)
4199 (defvar gnus-article-current)
4200 (defvar Info-current-file)
4201 (defvar Info-current-node)
4202 (declare-function mh-display-msg "mh-show" (msg-num folder-name))
4203 (declare-function mh-find-path "mh-utils" ())
4204 (declare-function mh-get-header-field "mh-utils" (field))
4205 (declare-function mh-get-msg-num "mh-utils" (error-if-no-message))
4206 (declare-function mh-header-display "mh-show" ())
4207 (declare-function mh-index-previous-folder "mh-search" ())
4208 (declare-function mh-normalize-folder-name "mh-utils" (folder &optional empty-string-okay dont-remove-trailing-slash return-nil-if-folder-empty))
4209 (declare-function mh-search "mh-search" (folder search-regexp &optional redo-search-flag window-config))
4210 (declare-function mh-search-choose "mh-search" (&optional searcher))
4211 (declare-function mh-show "mh-show" (&optional message redisplay-flag))
4212 (declare-function mh-show-buffer-message-number "mh-comp" (&optional buffer))
4213 (declare-function mh-show-header-display "mh-show" t t)
4214 (declare-function mh-show-msg "mh-show" (msg))
4215 (declare-function mh-show-show "mh-show" t t)
4216 (declare-function mh-visit-folder "mh-folder" (folder &optional range index-data))
4217 (defvar mh-progs)
4218 (defvar mh-current-folder)
4219 (defvar mh-show-folder-buffer)
4220 (defvar mh-index-folder)
4221 (defvar mh-searcher)
4222 (declare-function org-export-latex-cleaned-string "org-export-latex" ())
4223 (declare-function parse-time-string "parse-time" (string))
4224 (declare-function remember "remember" (&optional initial))
4225 (declare-function remember-buffer-desc "remember" ())
4226 (declare-function remember-finalize "remember" ())
4227 (defvar remember-save-after-remembering)
4228 (defvar remember-data-file)
4229 (defvar remember-register)
4230 (defvar remember-buffer)
4231 (defvar remember-handler-functions)
4232 (defvar remember-annotation-functions)
4233 (declare-function rmail-narrow-to-non-pruned-header "rmail" ())
4234 (declare-function rmail-show-message "rmail" (&optional n no-summary))
4235 (declare-function rmail-what-message "rmail" ())
4236 (defvar texmathp-why)
4237 (declare-function vm-beginning-of-message "ext:vm-page" ())
4238 (declare-function vm-follow-summary-cursor "ext:vm-motion" ())
4239 (declare-function vm-get-header-contents "ext:vm-summary" (message header-name-regexp &optional clump-sep))
4240 (declare-function vm-isearch-narrow "ext:vm-search" ())
4241 (declare-function vm-isearch-update "ext:vm-search" ())
4242 (declare-function vm-select-folder-buffer "ext:vm-macro" ())
4243 (declare-function vm-su-message-id "ext:vm-summary" (m))
4244 (declare-function vm-su-subject "ext:vm-summary" (m))
4245 (declare-function vm-summarize "ext:vm-summary" (&optional display raise))
4246 (defvar vm-message-pointer)
4247 (defvar vm-folder-directory)
4248 (defvar w3m-current-url)
4249 (defvar w3m-current-title)
4250 ;; backward compatibility to old version of wl
4251 (declare-function wl-summary-buffer-msgdb "ext:wl-folder" (&rest unknown) t)
4252 (declare-function wl-folder-get-elmo-folder "ext:wl-folder" (entity &optional no-cache))
4253 (declare-function wl-summary-goto-folder-subr "ext:wl-summary" (&optional name scan-type other-window sticky interactive scoring force-exit))
4254 (declare-function wl-summary-jump-to-msg-by-message-id "ext:wl-summary" (&optional id))
4255 (declare-function wl-summary-line-from "ext:wl-summary" ())
4256 (declare-function wl-summary-line-subject "ext:wl-summary" ())
4257 (declare-function wl-summary-message-number "ext:wl-summary" ())
4258 (declare-function wl-summary-redisplay "ext:wl-summary" (&optional arg))
4259 (defvar wl-summary-buffer-elmo-folder)
4260 (defvar wl-summary-buffer-folder-name)
4261 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4263 (defvar org-latex-regexps)
4264 (defvar constants-unit-system)
4266 ;;; Variables for pre-computed regular expressions, all buffer local
4268 (defvar org-drawer-regexp nil
4269 "Matches first line of a hidden block.")
4270 (make-variable-buffer-local 'org-drawer-regexp)
4271 (defvar org-todo-regexp nil
4272 "Matches any of the TODO state keywords.")
4273 (make-variable-buffer-local 'org-todo-regexp)
4274 (defvar org-not-done-regexp nil
4275 "Matches any of the TODO state keywords except the last one.")
4276 (make-variable-buffer-local 'org-not-done-regexp)
4277 (defvar org-todo-line-regexp nil
4278 "Matches a headline and puts TODO state into group 2 if present.")
4279 (make-variable-buffer-local 'org-todo-line-regexp)
4280 (defvar org-complex-heading-regexp nil
4281 "Matches a headline and puts everything into groups:
4282 group 1: the stars
4283 group 2: The todo keyword, maybe
4284 group 3: Priority cookie
4285 group 4: True headline
4286 group 5: Tags")
4287 (make-variable-buffer-local 'org-complex-heading-regexp)
4288 (defvar org-todo-line-tags-regexp nil
4289 "Matches a headline and puts TODO state into group 2 if present.
4290 Also put tags into group 4 if tags are present.")
4291 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4292 (defvar org-nl-done-regexp nil
4293 "Matches newline followed by a headline with the DONE keyword.")
4294 (make-variable-buffer-local 'org-nl-done-regexp)
4295 (defvar org-looking-at-done-regexp nil
4296 "Matches the DONE keyword a point.")
4297 (make-variable-buffer-local 'org-looking-at-done-regexp)
4298 (defvar org-ds-keyword-length 12
4299 "Maximum length of the Deadline and SCHEDULED keywords.")
4300 (make-variable-buffer-local 'org-ds-keyword-length)
4301 (defvar org-deadline-regexp nil
4302 "Matches the DEADLINE keyword.")
4303 (make-variable-buffer-local 'org-deadline-regexp)
4304 (defvar org-deadline-time-regexp nil
4305 "Matches the DEADLINE keyword together with a time stamp.")
4306 (make-variable-buffer-local 'org-deadline-time-regexp)
4307 (defvar org-deadline-line-regexp nil
4308 "Matches the DEADLINE keyword and the rest of the line.")
4309 (make-variable-buffer-local 'org-deadline-line-regexp)
4310 (defvar org-scheduled-regexp nil
4311 "Matches the SCHEDULED keyword.")
4312 (make-variable-buffer-local 'org-scheduled-regexp)
4313 (defvar org-scheduled-time-regexp nil
4314 "Matches the SCHEDULED keyword together with a time stamp.")
4315 (make-variable-buffer-local 'org-scheduled-time-regexp)
4316 (defvar org-closed-time-regexp nil
4317 "Matches the CLOSED keyword together with a time stamp.")
4318 (make-variable-buffer-local 'org-closed-time-regexp)
4320 (defvar org-keyword-time-regexp nil
4321 "Matches any of the 4 keywords, together with the time stamp.")
4322 (make-variable-buffer-local 'org-keyword-time-regexp)
4323 (defvar org-keyword-time-not-clock-regexp nil
4324 "Matches any of the 3 keywords, together with the time stamp.")
4325 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4326 (defvar org-maybe-keyword-time-regexp nil
4327 "Matches a timestamp, possibly preceeded by a keyword.")
4328 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4329 (defvar org-planning-or-clock-line-re nil
4330 "Matches a line with planning or clock info.")
4331 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4333 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4334 rear-nonsticky t mouse-map t fontified t)
4335 "Properties to remove when a string without properties is wanted.")
4337 (defsubst org-match-string-no-properties (num &optional string)
4338 (if (featurep 'xemacs)
4339 (let ((s (match-string num string)))
4340 (remove-text-properties 0 (length s) org-rm-props s)
4342 (match-string-no-properties num string)))
4344 (defsubst org-no-properties (s)
4345 (if (fboundp 'set-text-properties)
4346 (set-text-properties 0 (length s) nil s)
4347 (remove-text-properties 0 (length s) org-rm-props s))
4350 (defsubst org-get-alist-option (option key)
4351 (cond ((eq key t) t)
4352 ((eq option t) t)
4353 ((assoc key option) (cdr (assoc key option)))
4354 (t (cdr (assq 'default option)))))
4356 (defsubst org-inhibit-invisibility ()
4357 "Modified `buffer-invisibility-spec' for Emacs 21.
4358 Some ops with invisible text do not work correctly on Emacs 21. For these
4359 we turn off invisibility temporarily. Use this in a `let' form."
4360 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4362 (defsubst org-set-local (var value)
4363 "Make VAR local in current buffer and set it to VALUE."
4364 (set (make-variable-buffer-local var) value))
4366 (defsubst org-mode-p ()
4367 "Check if the current buffer is in Org-mode."
4368 (eq major-mode 'org-mode))
4370 (defsubst org-last (list)
4371 "Return the last element of LIST."
4372 (car (last list)))
4374 (defun org-let (list &rest body)
4375 (eval (cons 'let (cons list body))))
4376 (put 'org-let 'lisp-indent-function 1)
4378 (defun org-let2 (list1 list2 &rest body)
4379 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4380 (put 'org-let2 'lisp-indent-function 2)
4381 (defconst org-startup-options
4382 '(("fold" org-startup-folded t)
4383 ("overview" org-startup-folded t)
4384 ("nofold" org-startup-folded nil)
4385 ("showall" org-startup-folded nil)
4386 ("content" org-startup-folded content)
4387 ("hidestars" org-hide-leading-stars t)
4388 ("showstars" org-hide-leading-stars nil)
4389 ("odd" org-odd-levels-only t)
4390 ("oddeven" org-odd-levels-only nil)
4391 ("align" org-startup-align-all-tables t)
4392 ("noalign" org-startup-align-all-tables nil)
4393 ("customtime" org-display-custom-times t)
4394 ("logging" org-log-done t)
4395 ("logdone" org-log-done t)
4396 ("nologging" org-log-done nil)
4397 ("lognotedone" org-log-done done push)
4398 ("lognotestate" org-log-done state push)
4399 ("lognoteclock-out" org-log-done clock-out push)
4400 ("logrepeat" org-log-repeat t)
4401 ("nologrepeat" org-log-repeat nil)
4402 ("constcgs" constants-unit-system cgs)
4403 ("constSI" constants-unit-system SI))
4404 "Variable associated with STARTUP options for org-mode.
4405 Each element is a list of three items: The startup options as written
4406 in the #+STARTUP line, the corresponding variable, and the value to
4407 set this variable to if the option is found. An optional forth element PUSH
4408 means to push this value onto the list in the variable.")
4410 (defun org-set-regexps-and-options ()
4411 "Precompute regular expressions for current buffer."
4412 (when (org-mode-p)
4413 (org-set-local 'org-todo-kwd-alist nil)
4414 (org-set-local 'org-todo-key-alist nil)
4415 (org-set-local 'org-todo-key-trigger nil)
4416 (org-set-local 'org-todo-keywords-1 nil)
4417 (org-set-local 'org-done-keywords nil)
4418 (org-set-local 'org-todo-heads nil)
4419 (org-set-local 'org-todo-sets nil)
4420 (org-set-local 'org-todo-log-states nil)
4421 (let ((re (org-make-options-regexp
4422 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4423 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4424 "CONSTANTS" "PROPERTY" "DRAWERS")))
4425 (splitre "[ \t]+")
4426 kwds kws0 kwsa key value cat arch tags const links hw dws
4427 tail sep kws1 prio props drawers
4428 ex log)
4429 (save-excursion
4430 (save-restriction
4431 (widen)
4432 (goto-char (point-min))
4433 (while (re-search-forward re nil t)
4434 (setq key (match-string 1) value (org-match-string-no-properties 2))
4435 (cond
4436 ((equal key "CATEGORY")
4437 (if (string-match "[ \t]+$" value)
4438 (setq value (replace-match "" t t value)))
4439 (setq cat value))
4440 ((member key '("SEQ_TODO" "TODO"))
4441 (push (cons 'sequence (org-split-string value splitre)) kwds))
4442 ((equal key "TYP_TODO")
4443 (push (cons 'type (org-split-string value splitre)) kwds))
4444 ((equal key "TAGS")
4445 (setq tags (append tags (org-split-string value splitre))))
4446 ((equal key "COLUMNS")
4447 (org-set-local 'org-columns-default-format value))
4448 ((equal key "LINK")
4449 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4450 (push (cons (match-string 1 value)
4451 (org-trim (match-string 2 value)))
4452 links)))
4453 ((equal key "PRIORITIES")
4454 (setq prio (org-split-string value " +")))
4455 ((equal key "PROPERTY")
4456 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4457 (push (cons (match-string 1 value) (match-string 2 value))
4458 props)))
4459 ((equal key "DRAWERS")
4460 (setq drawers (org-split-string value splitre)))
4461 ((equal key "CONSTANTS")
4462 (setq const (append const (org-split-string value splitre))))
4463 ((equal key "STARTUP")
4464 (let ((opts (org-split-string value splitre))
4465 l var val)
4466 (while (setq l (pop opts))
4467 (when (setq l (assoc l org-startup-options))
4468 (setq var (nth 1 l) val (nth 2 l))
4469 (if (not (nth 3 l))
4470 (set (make-local-variable var) val)
4471 (if (not (listp (symbol-value var)))
4472 (set (make-local-variable var) nil))
4473 (set (make-local-variable var) (symbol-value var))
4474 (add-to-list var val))))))
4475 ((equal key "ARCHIVE")
4476 (string-match " *$" value)
4477 (setq arch (replace-match "" t t value))
4478 (remove-text-properties 0 (length arch)
4479 '(face t fontified t) arch)))
4481 (when cat
4482 (org-set-local 'org-category (intern cat))
4483 (push (cons "CATEGORY" cat) props))
4484 (when prio
4485 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4486 (setq prio (mapcar 'string-to-char prio))
4487 (org-set-local 'org-highest-priority (nth 0 prio))
4488 (org-set-local 'org-lowest-priority (nth 1 prio))
4489 (org-set-local 'org-default-priority (nth 2 prio)))
4490 (and props (org-set-local 'org-local-properties (nreverse props)))
4491 (and drawers (org-set-local 'org-drawers drawers))
4492 (and arch (org-set-local 'org-archive-location arch))
4493 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4494 ;; Process the TODO keywords
4495 (unless kwds
4496 ;; Use the global values as if they had been given locally.
4497 (setq kwds (default-value 'org-todo-keywords))
4498 (if (stringp (car kwds))
4499 (setq kwds (list (cons org-todo-interpretation
4500 (default-value 'org-todo-keywords)))))
4501 (setq kwds (reverse kwds)))
4502 (setq kwds (nreverse kwds))
4503 (let (inter kws kw)
4504 (while (setq kws (pop kwds))
4505 (setq inter (pop kws) sep (member "|" kws)
4506 kws0 (delete "|" (copy-sequence kws))
4507 kwsa nil
4508 kws1 (mapcar
4509 (lambda (x)
4510 (if (string-match "^\\(.*?\\)\\(?:(\\(..?\\))\\)?$" x)
4511 (progn
4512 (setq kw (match-string 1 x)
4513 ex (and (match-end 2) (match-string 2 x))
4514 log (and ex (string-match "@" ex))
4515 key (and ex (substring ex 0 1)))
4516 (if (equal key "@") (setq key nil))
4517 (push (cons kw (and key (string-to-char key))) kwsa)
4518 (and log (push kw org-todo-log-states))
4520 (error "Invalid TODO keyword %s" x)))
4521 kws0)
4522 kwsa (if kwsa (append '((:startgroup))
4523 (nreverse kwsa)
4524 '((:endgroup))))
4525 hw (car kws1)
4526 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4527 tail (list inter hw (car dws) (org-last dws)))
4528 (add-to-list 'org-todo-heads hw 'append)
4529 (push kws1 org-todo-sets)
4530 (setq org-done-keywords (append org-done-keywords dws nil))
4531 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4532 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4533 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4534 (setq org-todo-sets (nreverse org-todo-sets)
4535 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4536 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4537 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4538 ;; Process the constants
4539 (when const
4540 (let (e cst)
4541 (while (setq e (pop const))
4542 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4543 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4544 (setq org-table-formula-constants-local cst)))
4546 ;; Process the tags.
4547 (when tags
4548 (let (e tgs)
4549 (while (setq e (pop tags))
4550 (cond
4551 ((equal e "{") (push '(:startgroup) tgs))
4552 ((equal e "}") (push '(:endgroup) tgs))
4553 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4554 (push (cons (match-string 1 e)
4555 (string-to-char (match-string 2 e)))
4556 tgs))
4557 (t (push (list e) tgs))))
4558 (org-set-local 'org-tag-alist nil)
4559 (while (setq e (pop tgs))
4560 (or (and (stringp (car e))
4561 (assoc (car e) org-tag-alist))
4562 (push e org-tag-alist))))))
4564 ;; Compute the regular expressions and other local variables
4565 (if (not org-done-keywords)
4566 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4567 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4568 (length org-scheduled-string)))
4569 org-drawer-regexp
4570 (concat "^[ \t]*:\\("
4571 (mapconcat 'regexp-quote org-drawers "\\|")
4572 "\\):[ \t]*$")
4573 org-not-done-keywords
4574 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4575 org-todo-regexp
4576 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4577 "\\|") "\\)\\>")
4578 org-not-done-regexp
4579 (concat "\\<\\("
4580 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4581 "\\)\\>")
4582 org-todo-line-regexp
4583 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4584 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4585 "\\)\\>\\)?[ \t]*\\(.*\\)")
4586 org-complex-heading-regexp
4587 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4588 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4589 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4590 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4591 org-nl-done-regexp
4592 (concat "\n\\*+[ \t]+"
4593 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4594 "\\)" "\\>")
4595 org-todo-line-tags-regexp
4596 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4597 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4598 (org-re
4599 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4600 org-looking-at-done-regexp
4601 (concat "^" "\\(?:"
4602 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4603 "\\>")
4604 org-deadline-regexp (concat "\\<" org-deadline-string)
4605 org-deadline-time-regexp
4606 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4607 org-deadline-line-regexp
4608 (concat "\\<\\(" org-deadline-string "\\).*")
4609 org-scheduled-regexp
4610 (concat "\\<" org-scheduled-string)
4611 org-scheduled-time-regexp
4612 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4613 org-closed-time-regexp
4614 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4615 org-keyword-time-regexp
4616 (concat "\\<\\(" org-scheduled-string
4617 "\\|" org-deadline-string
4618 "\\|" org-closed-string
4619 "\\|" org-clock-string "\\)"
4620 " *[[<]\\([^]>]+\\)[]>]")
4621 org-keyword-time-not-clock-regexp
4622 (concat "\\<\\(" org-scheduled-string
4623 "\\|" org-deadline-string
4624 "\\|" org-closed-string
4625 "\\)"
4626 " *[[<]\\([^]>]+\\)[]>]")
4627 org-maybe-keyword-time-regexp
4628 (concat "\\(\\<\\(" org-scheduled-string
4629 "\\|" org-deadline-string
4630 "\\|" org-closed-string
4631 "\\|" org-clock-string "\\)\\)?"
4632 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4633 org-planning-or-clock-line-re
4634 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4635 "\\|" org-deadline-string
4636 "\\|" org-closed-string "\\|" org-clock-string
4637 "\\)\\>\\)")
4639 (org-compute-latex-and-specials-regexp)
4640 (org-set-font-lock-defaults)))
4642 (defun org-remove-keyword-keys (list)
4643 (mapcar (lambda (x)
4644 (if (string-match "(..?)$" x)
4645 (substring x 0 (match-beginning 0))
4647 list))
4649 ;; FIXME: this could be done much better, using second characters etc.
4650 (defun org-assign-fast-keys (alist)
4651 "Assign fast keys to a keyword-key alist.
4652 Respect keys that are already there."
4653 (let (new e k c c1 c2 (char ?a))
4654 (while (setq e (pop alist))
4655 (cond
4656 ((equal e '(:startgroup)) (push e new))
4657 ((equal e '(:endgroup)) (push e new))
4659 (setq k (car e) c2 nil)
4660 (if (cdr e)
4661 (setq c (cdr e))
4662 ;; automatically assign a character.
4663 (setq c1 (string-to-char
4664 (downcase (substring
4665 k (if (= (string-to-char k) ?@) 1 0)))))
4666 (if (or (rassoc c1 new) (rassoc c1 alist))
4667 (while (or (rassoc char new) (rassoc char alist))
4668 (setq char (1+ char)))
4669 (setq c2 c1))
4670 (setq c (or c2 char)))
4671 (push (cons k c) new))))
4672 (nreverse new)))
4674 ;;; Some variables ujsed in various places
4676 (defvar org-window-configuration nil
4677 "Used in various places to store a window configuration.")
4678 (defvar org-finish-function nil
4679 "Function to be called when `C-c C-c' is used.
4680 This is for getting out of special buffers like remember.")
4683 ;; FIXME: Occasionally check by commenting these, to make sure
4684 ;; no other functions uses these, forgetting to let-bind them.
4685 (defvar entry)
4686 (defvar state)
4687 (defvar last-state)
4688 (defvar date)
4689 (defvar description)
4691 ;; Defined somewhere in this file, but used before definition.
4692 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4693 (defvar org-agenda-buffer-name)
4694 (defvar org-agenda-undo-list)
4695 (defvar org-agenda-pending-undo-list)
4696 (defvar org-agenda-overriding-header)
4697 (defvar orgtbl-mode)
4698 (defvar org-html-entities)
4699 (defvar org-struct-menu)
4700 (defvar org-org-menu)
4701 (defvar org-tbl-menu)
4702 (defvar org-agenda-keymap)
4704 ;;;; Emacs/XEmacs compatibility
4706 ;; Overlay compatibility functions
4707 (defun org-make-overlay (beg end &optional buffer)
4708 (if (featurep 'xemacs)
4709 (make-extent beg end buffer)
4710 (make-overlay beg end buffer)))
4711 (defun org-delete-overlay (ovl)
4712 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4713 (defun org-detach-overlay (ovl)
4714 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4715 (defun org-move-overlay (ovl beg end &optional buffer)
4716 (if (featurep 'xemacs)
4717 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4718 (move-overlay ovl beg end buffer)))
4719 (defun org-overlay-put (ovl prop value)
4720 (if (featurep 'xemacs)
4721 (set-extent-property ovl prop value)
4722 (overlay-put ovl prop value)))
4723 (defun org-overlay-display (ovl text &optional face evap)
4724 "Make overlay OVL display TEXT with face FACE."
4725 (if (featurep 'xemacs)
4726 (let ((gl (make-glyph text)))
4727 (and face (set-glyph-face gl face))
4728 (set-extent-property ovl 'invisible t)
4729 (set-extent-property ovl 'end-glyph gl))
4730 (overlay-put ovl 'display text)
4731 (if face (overlay-put ovl 'face face))
4732 (if evap (overlay-put ovl 'evaporate t))))
4733 (defun org-overlay-before-string (ovl text &optional face evap)
4734 "Make overlay OVL display TEXT with face FACE."
4735 (if (featurep 'xemacs)
4736 (let ((gl (make-glyph text)))
4737 (and face (set-glyph-face gl face))
4738 (set-extent-property ovl 'begin-glyph gl))
4739 (if face (org-add-props text nil 'face face))
4740 (overlay-put ovl 'before-string text)
4741 (if evap (overlay-put ovl 'evaporate t))))
4742 (defun org-overlay-get (ovl prop)
4743 (if (featurep 'xemacs)
4744 (extent-property ovl prop)
4745 (overlay-get ovl prop)))
4746 (defun org-overlays-at (pos)
4747 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4748 (defun org-overlays-in (&optional start end)
4749 (if (featurep 'xemacs)
4750 (extent-list nil start end)
4751 (overlays-in start end)))
4752 (defun org-overlay-start (o)
4753 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4754 (defun org-overlay-end (o)
4755 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4756 (defun org-find-overlays (prop &optional pos delete)
4757 "Find all overlays specifying PROP at POS or point.
4758 If DELETE is non-nil, delete all those overlays."
4759 (let ((overlays (org-overlays-at (or pos (point))))
4760 ov found)
4761 (while (setq ov (pop overlays))
4762 (if (org-overlay-get ov prop)
4763 (if delete (org-delete-overlay ov) (push ov found))))
4764 found))
4766 ;; Region compatibility
4768 (defun org-add-hook (hook function &optional append local)
4769 "Add-hook, compatible with both Emacsen."
4770 (if (and local (featurep 'xemacs))
4771 (add-local-hook hook function append)
4772 (add-hook hook function append local)))
4774 (defvar org-ignore-region nil
4775 "To temporarily disable the active region.")
4777 (defun org-region-active-p ()
4778 "Is `transient-mark-mode' on and the region active?
4779 Works on both Emacs and XEmacs."
4780 (if org-ignore-region
4782 (if (featurep 'xemacs)
4783 (and zmacs-regions (region-active-p))
4784 (if (fboundp 'use-region-p)
4785 (use-region-p)
4786 (and transient-mark-mode mark-active))))) ; Emacs 22 and before
4788 ;; Invisibility compatibility
4790 (defun org-add-to-invisibility-spec (arg)
4791 "Add elements to `buffer-invisibility-spec'.
4792 See documentation for `buffer-invisibility-spec' for the kind of elements
4793 that can be added."
4794 (cond
4795 ((fboundp 'add-to-invisibility-spec)
4796 (add-to-invisibility-spec arg))
4797 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4798 (setq buffer-invisibility-spec (list arg)))
4800 (setq buffer-invisibility-spec
4801 (cons arg buffer-invisibility-spec)))))
4803 (defun org-remove-from-invisibility-spec (arg)
4804 "Remove elements from `buffer-invisibility-spec'."
4805 (if (fboundp 'remove-from-invisibility-spec)
4806 (remove-from-invisibility-spec arg)
4807 (if (consp buffer-invisibility-spec)
4808 (setq buffer-invisibility-spec
4809 (delete arg buffer-invisibility-spec)))))
4811 (defun org-in-invisibility-spec-p (arg)
4812 "Is ARG a member of `buffer-invisibility-spec'?"
4813 (if (consp buffer-invisibility-spec)
4814 (member arg buffer-invisibility-spec)
4815 nil))
4817 ;;;; Define the Org-mode
4819 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4820 (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."))
4823 ;; We use a before-change function to check if a table might need
4824 ;; an update.
4825 (defvar org-table-may-need-update t
4826 "Indicates that a table might need an update.
4827 This variable is set by `org-before-change-function'.
4828 `org-table-align' sets it back to nil.")
4829 (defvar org-mode-map)
4830 (defvar org-mode-hook nil)
4831 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4832 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4833 (defvar org-table-buffer-is-an nil)
4834 (defconst org-outline-regexp "\\*+ ")
4836 ;;;###autoload
4837 (define-derived-mode org-mode outline-mode "Org"
4838 "Outline-based notes management and organizer, alias
4839 \"Carsten's outline-mode for keeping track of everything.\"
4841 Org-mode develops organizational tasks around a NOTES file which
4842 contains information about projects as plain text. Org-mode is
4843 implemented on top of outline-mode, which is ideal to keep the content
4844 of large files well structured. It supports ToDo items, deadlines and
4845 time stamps, which magically appear in the diary listing of the Emacs
4846 calendar. Tables are easily created with a built-in table editor.
4847 Plain text URL-like links connect to websites, emails (VM), Usenet
4848 messages (Gnus), BBDB entries, and any files related to the project.
4849 For printing and sharing of notes, an Org-mode file (or a part of it)
4850 can be exported as a structured ASCII or HTML file.
4852 The following commands are available:
4854 \\{org-mode-map}"
4856 ;; Get rid of Outline menus, they are not needed
4857 ;; Need to do this here because define-derived-mode sets up
4858 ;; the keymap so late. Still, it is a waste to call this each time
4859 ;; we switch another buffer into org-mode.
4860 (if (featurep 'xemacs)
4861 (when (boundp 'outline-mode-menu-heading)
4862 ;; Assume this is Greg's port, it used easymenu
4863 (easy-menu-remove outline-mode-menu-heading)
4864 (easy-menu-remove outline-mode-menu-show)
4865 (easy-menu-remove outline-mode-menu-hide))
4866 (define-key org-mode-map [menu-bar headings] 'undefined)
4867 (define-key org-mode-map [menu-bar hide] 'undefined)
4868 (define-key org-mode-map [menu-bar show] 'undefined))
4870 (easy-menu-add org-org-menu)
4871 (easy-menu-add org-tbl-menu)
4872 (org-install-agenda-files-menu)
4873 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4874 (org-add-to-invisibility-spec '(org-cwidth))
4875 (when (featurep 'xemacs)
4876 (org-set-local 'line-move-ignore-invisible t))
4877 (org-set-local 'outline-regexp org-outline-regexp)
4878 (org-set-local 'outline-level 'org-outline-level)
4879 (when (and org-ellipsis
4880 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4881 (fboundp 'make-glyph-code))
4882 (unless org-display-table
4883 (setq org-display-table (make-display-table)))
4884 (set-display-table-slot
4885 org-display-table 4
4886 (vconcat (mapcar
4887 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4888 org-ellipsis)))
4889 (if (stringp org-ellipsis) org-ellipsis "..."))))
4890 (setq buffer-display-table org-display-table))
4891 (org-set-regexps-and-options)
4892 ;; Calc embedded
4893 (org-set-local 'calc-embedded-open-mode "# ")
4894 (modify-syntax-entry ?# "<")
4895 (modify-syntax-entry ?@ "w")
4896 (if org-startup-truncated (setq truncate-lines t))
4897 (org-set-local 'font-lock-unfontify-region-function
4898 'org-unfontify-region)
4899 ;; Activate before-change-function
4900 (org-set-local 'org-table-may-need-update t)
4901 (org-add-hook 'before-change-functions 'org-before-change-function nil
4902 'local)
4903 ;; Check for running clock before killing a buffer
4904 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4905 ;; Paragraphs and auto-filling
4906 (org-set-autofill-regexps)
4907 (setq indent-line-function 'org-indent-line-function)
4908 (org-update-radio-target-regexp)
4910 ;; Comment characters
4911 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4912 (org-set-local 'comment-padding " ")
4914 ;; Align options lines
4915 (org-set-local
4916 'align-mode-rules-list
4917 '((org-in-buffer-settings
4918 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4919 (modes . '(org-mode)))))
4921 ;; Imenu
4922 (org-set-local 'imenu-create-index-function
4923 'org-imenu-get-tree)
4925 ;; Make isearch reveal context
4926 (if (or (featurep 'xemacs)
4927 (not (boundp 'outline-isearch-open-invisible-function)))
4928 ;; Emacs 21 and XEmacs make use of the hook
4929 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4930 ;; Emacs 22 deals with this through a special variable
4931 (org-set-local 'outline-isearch-open-invisible-function
4932 (lambda (&rest ignore) (org-show-context 'isearch))))
4934 ;; If empty file that did not turn on org-mode automatically, make it to.
4935 (if (and org-insert-mode-line-in-empty-file
4936 (interactive-p)
4937 (= (point-min) (point-max)))
4938 (insert "# -*- mode: org -*-\n\n"))
4940 (unless org-inhibit-startup
4941 (when org-startup-align-all-tables
4942 (let ((bmp (buffer-modified-p)))
4943 (org-table-map-tables 'org-table-align)
4944 (set-buffer-modified-p bmp)))
4945 (org-cycle-hide-drawers 'all)
4946 (cond
4947 ((eq org-startup-folded t)
4948 (org-cycle '(4)))
4949 ((eq org-startup-folded 'content)
4950 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4951 (org-cycle '(4)) (org-cycle '(4)))))))
4953 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4955 (defsubst org-call-with-arg (command arg)
4956 "Call COMMAND interactively, but pretend prefix are was ARG."
4957 (let ((current-prefix-arg arg)) (call-interactively command)))
4959 (defsubst org-current-line (&optional pos)
4960 (save-excursion
4961 (and pos (goto-char pos))
4962 ;; works also in narrowed buffer, because we start at 1, not point-min
4963 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
4965 (defun org-current-time ()
4966 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4967 (if (> org-time-stamp-rounding-minutes 0)
4968 (let ((r org-time-stamp-rounding-minutes)
4969 (time (decode-time)))
4970 (apply 'encode-time
4971 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4972 (nthcdr 2 time))))
4973 (current-time)))
4975 (defun org-add-props (string plist &rest props)
4976 "Add text properties to entire string, from beginning to end.
4977 PLIST may be a list of properties, PROPS are individual properties and values
4978 that will be added to PLIST. Returns the string that was modified."
4979 (add-text-properties
4980 0 (length string) (if props (append plist props) plist) string)
4981 string)
4982 (put 'org-add-props 'lisp-indent-function 2)
4985 ;;;; Font-Lock stuff, including the activators
4987 (defvar org-mouse-map (make-sparse-keymap))
4988 (org-defkey org-mouse-map
4989 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4990 (org-defkey org-mouse-map
4991 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4992 (when org-mouse-1-follows-link
4993 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4994 (when org-tab-follows-link
4995 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4996 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4997 (when org-return-follows-link
4998 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
4999 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
5001 (require 'font-lock)
5003 (defconst org-non-link-chars "]\t\n\r<>")
5004 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
5005 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp" "message"))
5006 (defvar org-link-re-with-space nil
5007 "Matches a link with spaces, optional angular brackets around it.")
5008 (defvar org-link-re-with-space2 nil
5009 "Matches a link with spaces, optional angular brackets around it.")
5010 (defvar org-angle-link-re nil
5011 "Matches link with angular brackets, spaces are allowed.")
5012 (defvar org-plain-link-re nil
5013 "Matches plain link, without spaces.")
5014 (defvar org-bracket-link-regexp nil
5015 "Matches a link in double brackets.")
5016 (defvar org-bracket-link-analytic-regexp nil
5017 "Regular expression used to analyze links.
5018 Here is what the match groups contain after a match:
5019 1: http:
5020 2: http
5021 3: path
5022 4: [desc]
5023 5: desc")
5024 (defvar org-any-link-re nil
5025 "Regular expression matching any link.")
5027 (defun org-make-link-regexps ()
5028 "Update the link regular expressions.
5029 This should be called after the variable `org-link-types' has changed."
5030 (setq org-link-re-with-space
5031 (concat
5032 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5033 "\\([^" org-non-link-chars " ]"
5034 "[^" org-non-link-chars "]*"
5035 "[^" org-non-link-chars " ]\\)>?")
5036 org-link-re-with-space2
5037 (concat
5038 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5039 "\\([^" org-non-link-chars " ]"
5040 "[^]\t\n\r]*"
5041 "[^" org-non-link-chars " ]\\)>?")
5042 org-angle-link-re
5043 (concat
5044 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5045 "\\([^" org-non-link-chars " ]"
5046 "[^" org-non-link-chars "]*"
5047 "\\)>")
5048 org-plain-link-re
5049 (concat
5050 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5051 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5052 org-bracket-link-regexp
5053 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5054 org-bracket-link-analytic-regexp
5055 (concat
5056 "\\[\\["
5057 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
5058 "\\([^]]+\\)"
5059 "\\]"
5060 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5061 "\\]")
5062 org-any-link-re
5063 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5064 org-angle-link-re "\\)\\|\\("
5065 org-plain-link-re "\\)")))
5067 (org-make-link-regexps)
5069 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5070 "Regular expression for fast time stamp matching.")
5071 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
5072 "Regular expression for fast time stamp matching.")
5073 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5074 "Regular expression matching time strings for analysis.
5075 This one does not require the space after the date.")
5076 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5077 "Regular expression matching time strings for analysis.")
5078 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5079 "Regular expression matching time stamps, with groups.")
5080 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5081 "Regular expression matching time stamps (also [..]), with groups.")
5082 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5083 "Regular expression matching a time stamp range.")
5084 (defconst org-tr-regexp-both
5085 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5086 "Regular expression matching a time stamp range.")
5087 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5088 org-ts-regexp "\\)?")
5089 "Regular expression matching a time stamp or time stamp range.")
5090 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5091 org-ts-regexp-both "\\)?")
5092 "Regular expression matching a time stamp or time stamp range.
5093 The time stamps may be either active or inactive.")
5095 (defvar org-emph-face nil)
5097 (defun org-do-emphasis-faces (limit)
5098 "Run through the buffer and add overlays to links."
5099 (let (rtn)
5100 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5101 (if (not (= (char-after (match-beginning 3))
5102 (char-after (match-beginning 4))))
5103 (progn
5104 (setq rtn t)
5105 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5106 'face
5107 (nth 1 (assoc (match-string 3)
5108 org-emphasis-alist)))
5109 (add-text-properties (match-beginning 2) (match-end 2)
5110 '(font-lock-multiline t))
5111 (when org-hide-emphasis-markers
5112 (add-text-properties (match-end 4) (match-beginning 5)
5113 '(invisible org-link))
5114 (add-text-properties (match-beginning 3) (match-end 3)
5115 '(invisible org-link)))))
5116 (backward-char 1))
5117 rtn))
5119 (defun org-emphasize (&optional char)
5120 "Insert or change an emphasis, i.e. a font like bold or italic.
5121 If there is an active region, change that region to a new emphasis.
5122 If there is no region, just insert the marker characters and position
5123 the cursor between them.
5124 CHAR should be either the marker character, or the first character of the
5125 HTML tag associated with that emphasis. If CHAR is a space, the means
5126 to remove the emphasis of the selected region.
5127 If char is not given (for example in an interactive call) it
5128 will be prompted for."
5129 (interactive)
5130 (let ((eal org-emphasis-alist) e det
5131 (erc org-emphasis-regexp-components)
5132 (prompt "")
5133 (string "") beg end move tag c s)
5134 (if (org-region-active-p)
5135 (setq beg (region-beginning) end (region-end)
5136 string (buffer-substring beg end))
5137 (setq move t))
5139 (while (setq e (pop eal))
5140 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5141 c (aref tag 0))
5142 (push (cons c (string-to-char (car e))) det)
5143 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5144 (substring tag 1)))))
5145 (unless char
5146 (message "%s" (concat "Emphasis marker or tag:" prompt))
5147 (setq char (read-char-exclusive)))
5148 (setq char (or (cdr (assoc char det)) char))
5149 (if (equal char ?\ )
5150 (setq s "" move nil)
5151 (unless (assoc (char-to-string char) org-emphasis-alist)
5152 (error "No such emphasis marker: \"%c\"" char))
5153 (setq s (char-to-string char)))
5154 (while (and (> (length string) 1)
5155 (equal (substring string 0 1) (substring string -1))
5156 (assoc (substring string 0 1) org-emphasis-alist))
5157 (setq string (substring string 1 -1)))
5158 (setq string (concat s string s))
5159 (if beg (delete-region beg end))
5160 (unless (or (bolp)
5161 (string-match (concat "[" (nth 0 erc) "\n]")
5162 (char-to-string (char-before (point)))))
5163 (insert " "))
5164 (unless (string-match (concat "[" (nth 1 erc) "\n]")
5165 (char-to-string (char-after (point))))
5166 (insert " ") (backward-char 1))
5167 (insert string)
5168 (and move (backward-char 1))))
5170 (defconst org-nonsticky-props
5171 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5174 (defun org-activate-plain-links (limit)
5175 "Run through the buffer and add overlays to links."
5176 (catch 'exit
5177 (let (f)
5178 (while (re-search-forward org-plain-link-re limit t)
5179 (setq f (get-text-property (match-beginning 0) 'face))
5180 (if (or (eq f 'org-tag)
5181 (and (listp f) (memq 'org-tag f)))
5183 (add-text-properties (match-beginning 0) (match-end 0)
5184 (list 'mouse-face 'highlight
5185 'rear-nonsticky org-nonsticky-props
5186 'keymap org-mouse-map
5188 (throw 'exit t))))))
5190 (defun org-activate-code (limit)
5191 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
5192 (unless (get-text-property (match-beginning 1) 'face)
5193 (remove-text-properties (match-beginning 0) (match-end 0)
5194 '(display t invisible t intangible t))
5195 t)))
5197 (defun org-activate-angle-links (limit)
5198 "Run through the buffer and add overlays to links."
5199 (if (re-search-forward org-angle-link-re limit t)
5200 (progn
5201 (add-text-properties (match-beginning 0) (match-end 0)
5202 (list 'mouse-face 'highlight
5203 'rear-nonsticky org-nonsticky-props
5204 'keymap org-mouse-map
5206 t)))
5208 (defmacro org-maybe-intangible (props)
5209 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
5210 In emacs 21, invisible text is not avoided by the command loop, so the
5211 intangible property is needed to make sure point skips this text.
5212 In Emacs 22, this is not necessary. The intangible text property has
5213 led to problems with flyspell. These problems are fixed in flyspell.el,
5214 but we still avoid setting the property in Emacs 22 and later.
5215 We use a macro so that the test can happen at compilation time."
5216 (if (< emacs-major-version 22)
5217 `(append '(intangible t) ,props)
5218 props))
5220 (defun org-activate-bracket-links (limit)
5221 "Run through the buffer and add overlays to bracketed links."
5222 (if (re-search-forward org-bracket-link-regexp limit t)
5223 (let* ((help (concat "LINK: "
5224 (org-match-string-no-properties 1)))
5225 ;; FIXME: above we should remove the escapes.
5226 ;; but that requires another match, protecting match data,
5227 ;; a lot of overhead for font-lock.
5228 (ip (org-maybe-intangible
5229 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5230 'keymap org-mouse-map 'mouse-face 'highlight
5231 'font-lock-multiline t 'help-echo help)))
5232 (vp (list 'rear-nonsticky org-nonsticky-props
5233 'keymap org-mouse-map 'mouse-face 'highlight
5234 ' font-lock-multiline t 'help-echo help)))
5235 ;; We need to remove the invisible property here. Table narrowing
5236 ;; may have made some of this invisible.
5237 (remove-text-properties (match-beginning 0) (match-end 0)
5238 '(invisible nil))
5239 (if (match-end 3)
5240 (progn
5241 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5242 (add-text-properties (match-beginning 3) (match-end 3) vp)
5243 (add-text-properties (match-end 3) (match-end 0) ip))
5244 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5245 (add-text-properties (match-beginning 1) (match-end 1) vp)
5246 (add-text-properties (match-end 1) (match-end 0) ip))
5247 t)))
5249 (defun org-activate-dates (limit)
5250 "Run through the buffer and add overlays to dates."
5251 (if (re-search-forward org-tsr-regexp-both limit t)
5252 (progn
5253 (add-text-properties (match-beginning 0) (match-end 0)
5254 (list 'mouse-face 'highlight
5255 'rear-nonsticky org-nonsticky-props
5256 'keymap org-mouse-map))
5257 (when org-display-custom-times
5258 (if (match-end 3)
5259 (org-display-custom-time (match-beginning 3) (match-end 3)))
5260 (org-display-custom-time (match-beginning 1) (match-end 1)))
5261 t)))
5263 (defvar org-target-link-regexp nil
5264 "Regular expression matching radio targets in plain text.")
5265 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5266 "Regular expression matching a link target.")
5267 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5268 "Regular expression matching a radio target.")
5269 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5270 "Regular expression matching any target.")
5272 (defun org-activate-target-links (limit)
5273 "Run through the buffer and add overlays to target matches."
5274 (when org-target-link-regexp
5275 (let ((case-fold-search t))
5276 (if (re-search-forward org-target-link-regexp limit t)
5277 (progn
5278 (add-text-properties (match-beginning 0) (match-end 0)
5279 (list 'mouse-face 'highlight
5280 'rear-nonsticky org-nonsticky-props
5281 'keymap org-mouse-map
5282 'help-echo "Radio target link"
5283 'org-linked-text t))
5284 t)))))
5286 (defun org-update-radio-target-regexp ()
5287 "Find all radio targets in this file and update the regular expression."
5288 (interactive)
5289 (when (memq 'radio org-activate-links)
5290 (setq org-target-link-regexp
5291 (org-make-target-link-regexp (org-all-targets 'radio)))
5292 (org-restart-font-lock)))
5294 (defun org-hide-wide-columns (limit)
5295 (let (s e)
5296 (setq s (text-property-any (point) (or limit (point-max))
5297 'org-cwidth t))
5298 (when s
5299 (setq e (next-single-property-change s 'org-cwidth))
5300 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5301 (goto-char e)
5302 t)))
5304 (defvar org-latex-and-specials-regexp nil
5305 "Regular expression for highlighting export special stuff.")
5306 (defvar org-match-substring-regexp)
5307 (defvar org-match-substring-with-braces-regexp)
5308 (defvar org-export-html-special-string-regexps)
5310 (defun org-compute-latex-and-specials-regexp ()
5311 "Compute regular expression for stuff treated specially by exporters."
5312 (if (not org-highlight-latex-fragments-and-specials)
5313 (org-set-local 'org-latex-and-specials-regexp nil)
5314 (let*
5315 ((matchers (plist-get org-format-latex-options :matchers))
5316 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5317 org-latex-regexps)))
5318 (options (org-combine-plists (org-default-export-plist)
5319 (org-infile-export-plist)))
5320 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5321 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5322 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5323 (org-export-html-expand (plist-get options :expand-quoted-html))
5324 (org-export-with-special-strings (plist-get options :special-strings))
5325 (re-sub
5326 (cond
5327 ((equal org-export-with-sub-superscripts '{})
5328 (list org-match-substring-with-braces-regexp))
5329 (org-export-with-sub-superscripts
5330 (list org-match-substring-regexp))
5331 (t nil)))
5332 (re-latex
5333 (if org-export-with-LaTeX-fragments
5334 (mapcar (lambda (x) (nth 1 x)) latexs)))
5335 (re-macros
5336 (if org-export-with-TeX-macros
5337 (list (concat "\\\\"
5338 (regexp-opt
5339 (append (mapcar 'car org-html-entities)
5340 (if (boundp 'org-latex-entities)
5341 org-latex-entities nil))
5342 'words))) ; FIXME
5344 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5345 (re-special (if org-export-with-special-strings
5346 (mapcar (lambda (x) (car x))
5347 org-export-html-special-string-regexps)))
5348 (re-rest
5349 (delq nil
5350 (list
5351 (if org-export-html-expand "@<[^>\n]+>")
5352 ))))
5353 (org-set-local
5354 'org-latex-and-specials-regexp
5355 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5356 re-rest) "\\|")))))
5358 (defface org-latex-and-export-specials
5359 (let ((font (cond ((assq :inherit custom-face-attributes)
5360 '(:inherit underline))
5361 (t '(:underline t)))))
5362 `((((class grayscale) (background light))
5363 (:foreground "DimGray" ,@font))
5364 (((class grayscale) (background dark))
5365 (:foreground "LightGray" ,@font))
5366 (((class color) (background light))
5367 (:foreground "SaddleBrown"))
5368 (((class color) (background dark))
5369 (:foreground "burlywood"))
5370 (t (,@font))))
5371 "Face used to highlight math latex and other special exporter stuff."
5372 :group 'org-faces)
5374 (defun org-do-latex-and-special-faces (limit)
5375 "Run through the buffer and add overlays to links."
5376 (when org-latex-and-specials-regexp
5377 (let (rtn d)
5378 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5379 limit t))
5380 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5381 'face))
5382 '(org-code org-verbatim underline)))
5383 (progn
5384 (setq rtn t
5385 d (cond ((member (char-after (1+ (match-beginning 0)))
5386 '(?_ ?^)) 1)
5387 (t 0)))
5388 (font-lock-prepend-text-property
5389 (+ d (match-beginning 0)) (match-end 0)
5390 'face 'org-latex-and-export-specials)
5391 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5392 '(font-lock-multiline t)))))
5393 rtn)))
5395 (defun org-restart-font-lock ()
5396 "Restart font-lock-mode, to force refontification."
5397 (when (and (boundp 'font-lock-mode) font-lock-mode)
5398 (font-lock-mode -1)
5399 (font-lock-mode 1)))
5401 (defun org-all-targets (&optional radio)
5402 "Return a list of all targets in this file.
5403 With optional argument RADIO, only find radio targets."
5404 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5405 rtn)
5406 (save-excursion
5407 (goto-char (point-min))
5408 (while (re-search-forward re nil t)
5409 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5410 rtn)))
5412 (defun org-make-target-link-regexp (targets)
5413 "Make regular expression matching all strings in TARGETS.
5414 The regular expression finds the targets also if there is a line break
5415 between words."
5416 (and targets
5417 (concat
5418 "\\<\\("
5419 (mapconcat
5420 (lambda (x)
5421 (while (string-match " +" x)
5422 (setq x (replace-match "\\s-+" t t x)))
5424 targets
5425 "\\|")
5426 "\\)\\>")))
5428 (defun org-activate-tags (limit)
5429 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5430 (progn
5431 (add-text-properties (match-beginning 1) (match-end 1)
5432 (list 'mouse-face 'highlight
5433 'rear-nonsticky org-nonsticky-props
5434 'keymap org-mouse-map))
5435 t)))
5437 (defun org-outline-level ()
5438 (save-excursion
5439 (looking-at outline-regexp)
5440 (if (match-beginning 1)
5441 (+ (org-get-string-indentation (match-string 1)) 1000)
5442 (1- (- (match-end 0) (match-beginning 0))))))
5444 (defvar org-font-lock-keywords nil)
5446 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5447 "Regular expression matching a property line.")
5449 (defun org-set-font-lock-defaults ()
5450 (let* ((em org-fontify-emphasized-text)
5451 (lk org-activate-links)
5452 (org-font-lock-extra-keywords
5453 (list
5454 ;; Headlines
5455 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5456 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5457 ;; Table lines
5458 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5459 (1 'org-table t))
5460 ;; Table internals
5461 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5462 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5463 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5464 ;; Drawers
5465 (list org-drawer-regexp '(0 'org-special-keyword t))
5466 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5467 ;; Properties
5468 (list org-property-re
5469 '(1 'org-special-keyword t)
5470 '(3 'org-property-value t))
5471 (if org-format-transports-properties-p
5472 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5473 ;; Links
5474 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5475 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5476 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5477 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5478 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5479 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5480 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5481 '(org-hide-wide-columns (0 nil append))
5482 ;; TODO lines
5483 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5484 '(1 (org-get-todo-face 1) t))
5485 ;; DONE
5486 (if org-fontify-done-headline
5487 (list (concat "^[*]+ +\\<\\("
5488 (mapconcat 'regexp-quote org-done-keywords "\\|")
5489 "\\)\\(.*\\)")
5490 '(2 'org-headline-done t))
5491 nil)
5492 ;; Priorities
5493 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5494 ;; Special keywords
5495 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5496 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5497 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5498 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5499 ;; Emphasis
5500 (if em
5501 (if (featurep 'xemacs)
5502 '(org-do-emphasis-faces (0 nil append))
5503 '(org-do-emphasis-faces)))
5504 ;; Checkboxes
5505 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5506 2 'bold prepend)
5507 (if org-provide-checkbox-statistics
5508 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5509 (0 (org-get-checkbox-statistics-face) t)))
5510 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5511 '(1 'org-archived prepend))
5512 ;; Specials
5513 '(org-do-latex-and-special-faces)
5514 ;; Code
5515 '(org-activate-code (1 'org-code t))
5516 ;; COMMENT
5517 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5518 "\\|" org-quote-string "\\)\\>")
5519 '(1 'org-special-keyword t))
5520 '("^#.*" (0 'font-lock-comment-face t))
5522 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5523 ;; Now set the full font-lock-keywords
5524 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5525 (org-set-local 'font-lock-defaults
5526 '(org-font-lock-keywords t nil nil backward-paragraph))
5527 (kill-local-variable 'font-lock-keywords) nil))
5529 (defvar org-m nil)
5530 (defvar org-l nil)
5531 (defvar org-f nil)
5532 (defun org-get-level-face (n)
5533 "Get the right face for match N in font-lock matching of healdines."
5534 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5535 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5536 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5537 (cond
5538 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5539 ((eq n 2) org-f)
5540 (t (if org-level-color-stars-only nil org-f))))
5542 (defun org-get-todo-face (kwd)
5543 "Get the right face for a TODO keyword KWD.
5544 If KWD is a number, get the corresponding match group."
5545 (if (numberp kwd) (setq kwd (match-string kwd)))
5546 (or (cdr (assoc kwd org-todo-keyword-faces))
5547 (and (member kwd org-done-keywords) 'org-done)
5548 'org-todo))
5550 (defun org-unfontify-region (beg end &optional maybe_loudly)
5551 "Remove fontification and activation overlays from links."
5552 (font-lock-default-unfontify-region beg end)
5553 (let* ((buffer-undo-list t)
5554 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5555 (inhibit-modification-hooks t)
5556 deactivate-mark buffer-file-name buffer-file-truename)
5557 (remove-text-properties beg end
5558 '(mouse-face t keymap t org-linked-text t
5559 invisible t intangible t))))
5561 ;;;; Visibility cycling, including org-goto and indirect buffer
5563 ;;; Cycling
5565 (defvar org-cycle-global-status nil)
5566 (make-variable-buffer-local 'org-cycle-global-status)
5567 (defvar org-cycle-subtree-status nil)
5568 (make-variable-buffer-local 'org-cycle-subtree-status)
5570 ;;;###autoload
5571 (defun org-cycle (&optional arg)
5572 "Visibility cycling for Org-mode.
5574 - When this function is called with a prefix argument, rotate the entire
5575 buffer through 3 states (global cycling)
5576 1. OVERVIEW: Show only top-level headlines.
5577 2. CONTENTS: Show all headlines of all levels, but no body text.
5578 3. SHOW ALL: Show everything.
5580 - When point is at the beginning of a headline, rotate the subtree started
5581 by this line through 3 different states (local cycling)
5582 1. FOLDED: Only the main headline is shown.
5583 2. CHILDREN: The main headline and the direct children are shown.
5584 From this state, you can move to one of the children
5585 and zoom in further.
5586 3. SUBTREE: Show the entire subtree, including body text.
5588 - When there is a numeric prefix, go up to a heading with level ARG, do
5589 a `show-subtree' and return to the previous cursor position. If ARG
5590 is negative, go up that many levels.
5592 - When point is not at the beginning of a headline, execute
5593 `indent-relative', like TAB normally does. See the option
5594 `org-cycle-emulate-tab' for details.
5596 - Special case: if point is at the beginning of the buffer and there is
5597 no headline in line 1, this function will act as if called with prefix arg.
5598 But only if also the variable `org-cycle-global-at-bob' is t."
5599 (interactive "P")
5600 (let* ((outline-regexp
5601 (if (and (org-mode-p) org-cycle-include-plain-lists)
5602 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5603 outline-regexp))
5604 (bob-special (and org-cycle-global-at-bob (bobp)
5605 (not (looking-at outline-regexp))))
5606 (org-cycle-hook
5607 (if bob-special
5608 (delq 'org-optimize-window-after-visibility-change
5609 (copy-sequence org-cycle-hook))
5610 org-cycle-hook))
5611 (pos (point)))
5613 (if (or bob-special (equal arg '(4)))
5614 ;; special case: use global cycling
5615 (setq arg t))
5617 (cond
5619 ((org-at-table-p 'any)
5620 ;; Enter the table or move to the next field in the table
5621 (or (org-table-recognize-table.el)
5622 (progn
5623 (if arg (org-table-edit-field t)
5624 (org-table-justify-field-maybe)
5625 (call-interactively 'org-table-next-field)))))
5627 ((eq arg t) ;; Global cycling
5629 (cond
5630 ((and (eq last-command this-command)
5631 (eq org-cycle-global-status 'overview))
5632 ;; We just created the overview - now do table of contents
5633 ;; This can be slow in very large buffers, so indicate action
5634 (message "CONTENTS...")
5635 (org-content)
5636 (message "CONTENTS...done")
5637 (setq org-cycle-global-status 'contents)
5638 (run-hook-with-args 'org-cycle-hook 'contents))
5640 ((and (eq last-command this-command)
5641 (eq org-cycle-global-status 'contents))
5642 ;; We just showed the table of contents - now show everything
5643 (show-all)
5644 (message "SHOW ALL")
5645 (setq org-cycle-global-status 'all)
5646 (run-hook-with-args 'org-cycle-hook 'all))
5649 ;; Default action: go to overview
5650 (org-overview)
5651 (message "OVERVIEW")
5652 (setq org-cycle-global-status 'overview)
5653 (run-hook-with-args 'org-cycle-hook 'overview))))
5655 ((and org-drawers org-drawer-regexp
5656 (save-excursion
5657 (beginning-of-line 1)
5658 (looking-at org-drawer-regexp)))
5659 ;; Toggle block visibility
5660 (org-flag-drawer
5661 (not (get-char-property (match-end 0) 'invisible))))
5663 ((integerp arg)
5664 ;; Show-subtree, ARG levels up from here.
5665 (save-excursion
5666 (org-back-to-heading)
5667 (outline-up-heading (if (< arg 0) (- arg)
5668 (- (funcall outline-level) arg)))
5669 (org-show-subtree)))
5671 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5672 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5673 ;; At a heading: rotate between three different views
5674 (org-back-to-heading)
5675 (let ((goal-column 0) eoh eol eos)
5676 ;; First, some boundaries
5677 (save-excursion
5678 (org-back-to-heading)
5679 (save-excursion
5680 (beginning-of-line 2)
5681 (while (and (not (eobp)) ;; this is like `next-line'
5682 (get-char-property (1- (point)) 'invisible))
5683 (beginning-of-line 2)) (setq eol (point)))
5684 (outline-end-of-heading) (setq eoh (point))
5685 (org-end-of-subtree t)
5686 (unless (eobp)
5687 (skip-chars-forward " \t\n")
5688 (beginning-of-line 1) ; in case this is an item
5690 (setq eos (1- (point))))
5691 ;; Find out what to do next and set `this-command'
5692 (cond
5693 ((= eos eoh)
5694 ;; Nothing is hidden behind this heading
5695 (message "EMPTY ENTRY")
5696 (setq org-cycle-subtree-status nil)
5697 (save-excursion
5698 (goto-char eos)
5699 (outline-next-heading)
5700 (if (org-invisible-p) (org-flag-heading nil))))
5701 ((or (>= eol eos)
5702 (not (string-match "\\S-" (buffer-substring eol eos))))
5703 ;; Entire subtree is hidden in one line: open it
5704 (org-show-entry)
5705 (show-children)
5706 (message "CHILDREN")
5707 (save-excursion
5708 (goto-char eos)
5709 (outline-next-heading)
5710 (if (org-invisible-p) (org-flag-heading nil)))
5711 (setq org-cycle-subtree-status 'children)
5712 (run-hook-with-args 'org-cycle-hook 'children))
5713 ((and (eq last-command this-command)
5714 (eq org-cycle-subtree-status 'children))
5715 ;; We just showed the children, now show everything.
5716 (org-show-subtree)
5717 (message "SUBTREE")
5718 (setq org-cycle-subtree-status 'subtree)
5719 (run-hook-with-args 'org-cycle-hook 'subtree))
5721 ;; Default action: hide the subtree.
5722 (hide-subtree)
5723 (message "FOLDED")
5724 (setq org-cycle-subtree-status 'folded)
5725 (run-hook-with-args 'org-cycle-hook 'folded)))))
5727 ;; TAB emulation
5728 (buffer-read-only (org-back-to-heading))
5730 ((org-try-cdlatex-tab))
5732 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5733 (or (not (bolp))
5734 (not (looking-at outline-regexp))))
5735 (call-interactively (global-key-binding "\t")))
5737 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5738 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5739 (or (and (eq org-cycle-emulate-tab 'white)
5740 (= (match-end 0) (point-at-eol)))
5741 (and (eq org-cycle-emulate-tab 'whitestart)
5742 (>= (match-end 0) pos))))
5744 (eq org-cycle-emulate-tab t))
5745 ; (if (and (looking-at "[ \n\r\t]")
5746 ; (string-match "^[ \t]*$" (buffer-substring
5747 ; (point-at-bol) (point))))
5748 ; (progn
5749 ; (beginning-of-line 1)
5750 ; (and (looking-at "[ \t]+") (replace-match ""))))
5751 (call-interactively (global-key-binding "\t")))
5753 (t (save-excursion
5754 (org-back-to-heading)
5755 (org-cycle))))))
5757 ;;;###autoload
5758 (defun org-global-cycle (&optional arg)
5759 "Cycle the global visibility. For details see `org-cycle'."
5760 (interactive "P")
5761 (let ((org-cycle-include-plain-lists
5762 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5763 (if (integerp arg)
5764 (progn
5765 (show-all)
5766 (hide-sublevels arg)
5767 (setq org-cycle-global-status 'contents))
5768 (org-cycle '(4)))))
5770 (defun org-overview ()
5771 "Switch to overview mode, shoing only top-level headlines.
5772 Really, this shows all headlines with level equal or greater than the level
5773 of the first headline in the buffer. This is important, because if the
5774 first headline is not level one, then (hide-sublevels 1) gives confusing
5775 results."
5776 (interactive)
5777 (let ((level (save-excursion
5778 (goto-char (point-min))
5779 (if (re-search-forward (concat "^" outline-regexp) nil t)
5780 (progn
5781 (goto-char (match-beginning 0))
5782 (funcall outline-level))))))
5783 (and level (hide-sublevels level))))
5785 (defun org-content (&optional arg)
5786 "Show all headlines in the buffer, like a table of contents.
5787 With numerical argument N, show content up to level N."
5788 (interactive "P")
5789 (save-excursion
5790 ;; Visit all headings and show their offspring
5791 (and (integerp arg) (org-overview))
5792 (goto-char (point-max))
5793 (catch 'exit
5794 (while (and (progn (condition-case nil
5795 (outline-previous-visible-heading 1)
5796 (error (goto-char (point-min))))
5798 (looking-at outline-regexp))
5799 (if (integerp arg)
5800 (show-children (1- arg))
5801 (show-branches))
5802 (if (bobp) (throw 'exit nil))))))
5805 (defun org-optimize-window-after-visibility-change (state)
5806 "Adjust the window after a change in outline visibility.
5807 This function is the default value of the hook `org-cycle-hook'."
5808 (when (get-buffer-window (current-buffer))
5809 (cond
5810 ; ((eq state 'overview) (org-first-headline-recenter 1))
5811 ; ((eq state 'overview) (org-beginning-of-line))
5812 ((eq state 'content) nil)
5813 ((eq state 'all) nil)
5814 ((eq state 'folded) nil)
5815 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5816 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5818 (defun org-compact-display-after-subtree-move ()
5819 (let (beg end)
5820 (save-excursion
5821 (if (org-up-heading-safe)
5822 (progn
5823 (hide-subtree)
5824 (show-entry)
5825 (show-children)
5826 (org-cycle-show-empty-lines 'children)
5827 (org-cycle-hide-drawers 'children))
5828 (org-overview)))))
5830 (defun org-cycle-show-empty-lines (state)
5831 "Show empty lines above all visible headlines.
5832 The region to be covered depends on STATE when called through
5833 `org-cycle-hook'. Lisp program can use t for STATE to get the
5834 entire buffer covered. Note that an empty line is only shown if there
5835 are at least `org-cycle-separator-lines' empty lines before the headeline."
5836 (when (> org-cycle-separator-lines 0)
5837 (save-excursion
5838 (let* ((n org-cycle-separator-lines)
5839 (re (cond
5840 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5841 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5842 (t (let ((ns (number-to-string (- n 2))))
5843 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5844 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5845 beg end)
5846 (cond
5847 ((memq state '(overview contents t))
5848 (setq beg (point-min) end (point-max)))
5849 ((memq state '(children folded))
5850 (setq beg (point) end (progn (org-end-of-subtree t t)
5851 (beginning-of-line 2)
5852 (point)))))
5853 (when beg
5854 (goto-char beg)
5855 (while (re-search-forward re end t)
5856 (if (not (get-char-property (match-end 1) 'invisible))
5857 (outline-flag-region
5858 (match-beginning 1) (match-end 1) nil)))))))
5859 ;; Never hide empty lines at the end of the file.
5860 (save-excursion
5861 (goto-char (point-max))
5862 (outline-previous-heading)
5863 (outline-end-of-heading)
5864 (if (and (looking-at "[ \t\n]+")
5865 (= (match-end 0) (point-max)))
5866 (outline-flag-region (point) (match-end 0) nil))))
5868 (defun org-subtree-end-visible-p ()
5869 "Is the end of the current subtree visible?"
5870 (pos-visible-in-window-p
5871 (save-excursion (org-end-of-subtree t) (point))))
5873 (defun org-first-headline-recenter (&optional N)
5874 "Move cursor to the first headline and recenter the headline.
5875 Optional argument N means, put the headline into the Nth line of the window."
5876 (goto-char (point-min))
5877 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5878 (beginning-of-line)
5879 (recenter (prefix-numeric-value N))))
5881 ;;; Org-goto
5883 (defvar org-goto-window-configuration nil)
5884 (defvar org-goto-marker nil)
5885 (defvar org-goto-map
5886 (let ((map (make-sparse-keymap)))
5887 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5888 (while (setq cmd (pop cmds))
5889 (substitute-key-definition cmd cmd map global-map)))
5890 (suppress-keymap map)
5891 (org-defkey map "\C-m" 'org-goto-ret)
5892 (org-defkey map [(return)] 'org-goto-ret)
5893 (org-defkey map [(left)] 'org-goto-left)
5894 (org-defkey map [(right)] 'org-goto-right)
5895 (org-defkey map [(control ?g)] 'org-goto-quit)
5896 (org-defkey map "\C-i" 'org-cycle)
5897 (org-defkey map [(tab)] 'org-cycle)
5898 (org-defkey map [(down)] 'outline-next-visible-heading)
5899 (org-defkey map [(up)] 'outline-previous-visible-heading)
5900 (if org-goto-auto-isearch
5901 (if (fboundp 'define-key-after)
5902 (define-key-after map [t] 'org-goto-local-auto-isearch)
5903 nil)
5904 (org-defkey map "q" 'org-goto-quit)
5905 (org-defkey map "n" 'outline-next-visible-heading)
5906 (org-defkey map "p" 'outline-previous-visible-heading)
5907 (org-defkey map "f" 'outline-forward-same-level)
5908 (org-defkey map "b" 'outline-backward-same-level)
5909 (org-defkey map "u" 'outline-up-heading))
5910 (org-defkey map "/" 'org-occur)
5911 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5912 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5913 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5914 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5915 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5916 map))
5918 (defconst org-goto-help
5919 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5920 RET=jump to location [Q]uit and return to previous location
5921 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5923 (defvar org-goto-start-pos) ; dynamically scoped parameter
5925 (defun org-goto (&optional alternative-interface)
5926 "Look up a different location in the current file, keeping current visibility.
5928 When you want look-up or go to a different location in a document, the
5929 fastest way is often to fold the entire buffer and then dive into the tree.
5930 This method has the disadvantage, that the previous location will be folded,
5931 which may not be what you want.
5933 This command works around this by showing a copy of the current buffer
5934 in an indirect buffer, in overview mode. You can dive into the tree in
5935 that copy, use org-occur and incremental search to find a location.
5936 When pressing RET or `Q', the command returns to the original buffer in
5937 which the visibility is still unchanged. After RET is will also jump to
5938 the location selected in the indirect buffer and expose the
5939 the headline hierarchy above."
5940 (interactive "P")
5941 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
5942 (org-refile-use-outline-path t)
5943 (interface
5944 (if (not alternative-interface)
5945 org-goto-interface
5946 (if (eq org-goto-interface 'outline)
5947 'outline-path-completion
5948 'outline)))
5949 (org-goto-start-pos (point))
5950 (selected-point
5951 (if (eq interface 'outline)
5952 (car (org-get-location (current-buffer) org-goto-help))
5953 (nth 3 (org-refile-get-location "Goto: ")))))
5954 (if selected-point
5955 (progn
5956 (org-mark-ring-push org-goto-start-pos)
5957 (goto-char selected-point)
5958 (if (or (org-invisible-p) (org-invisible-p2))
5959 (org-show-context 'org-goto)))
5960 (message "Quit"))))
5962 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5963 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5964 (defvar org-goto-local-auto-isearch-map) ; defined below
5966 (defun org-get-location (buf help)
5967 "Let the user select a location in the Org-mode buffer BUF.
5968 This function uses a recursive edit. It returns the selected position
5969 or nil."
5970 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5971 (isearch-hide-immediately nil)
5972 (isearch-search-fun-function
5973 (lambda () 'org-goto-local-search-forward-headings))
5974 (org-goto-selected-point org-goto-exit-command))
5975 (save-excursion
5976 (save-window-excursion
5977 (delete-other-windows)
5978 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5979 (switch-to-buffer
5980 (condition-case nil
5981 (make-indirect-buffer (current-buffer) "*org-goto*")
5982 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5983 (with-output-to-temp-buffer "*Help*"
5984 (princ help))
5985 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
5986 (setq buffer-read-only nil)
5987 (let ((org-startup-truncated t)
5988 (org-startup-folded nil)
5989 (org-startup-align-all-tables nil))
5990 (org-mode)
5991 (org-overview))
5992 (setq buffer-read-only t)
5993 (if (and (boundp 'org-goto-start-pos)
5994 (integer-or-marker-p org-goto-start-pos))
5995 (let ((org-show-hierarchy-above t)
5996 (org-show-siblings t)
5997 (org-show-following-heading t))
5998 (goto-char org-goto-start-pos)
5999 (and (org-invisible-p) (org-show-context)))
6000 (goto-char (point-min)))
6001 (org-beginning-of-line)
6002 (message "Select location and press RET")
6003 (use-local-map org-goto-map)
6004 (recursive-edit)
6006 (kill-buffer "*org-goto*")
6007 (cons org-goto-selected-point org-goto-exit-command)))
6009 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6010 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6011 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6012 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6014 (defun org-goto-local-search-forward-headings (string bound noerror)
6015 "Search and make sure that anu matches are in headlines."
6016 (catch 'return
6017 (while (search-forward string bound noerror)
6018 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6019 (and (member :headline context)
6020 (not (member :tags context))))
6021 (throw 'return (point))))))
6023 (defun org-goto-local-auto-isearch ()
6024 "Start isearch."
6025 (interactive)
6026 (goto-char (point-min))
6027 (let ((keys (this-command-keys)))
6028 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6029 (isearch-mode t)
6030 (isearch-process-search-char (string-to-char keys)))))
6032 (defun org-goto-ret (&optional arg)
6033 "Finish `org-goto' by going to the new location."
6034 (interactive "P")
6035 (setq org-goto-selected-point (point)
6036 org-goto-exit-command 'return)
6037 (throw 'exit nil))
6039 (defun org-goto-left ()
6040 "Finish `org-goto' by going to the new location."
6041 (interactive)
6042 (if (org-on-heading-p)
6043 (progn
6044 (beginning-of-line 1)
6045 (setq org-goto-selected-point (point)
6046 org-goto-exit-command 'left)
6047 (throw 'exit nil))
6048 (error "Not on a heading")))
6050 (defun org-goto-right ()
6051 "Finish `org-goto' by going to the new location."
6052 (interactive)
6053 (if (org-on-heading-p)
6054 (progn
6055 (setq org-goto-selected-point (point)
6056 org-goto-exit-command 'right)
6057 (throw 'exit nil))
6058 (error "Not on a heading")))
6060 (defun org-goto-quit ()
6061 "Finish `org-goto' without cursor motion."
6062 (interactive)
6063 (setq org-goto-selected-point nil)
6064 (setq org-goto-exit-command 'quit)
6065 (throw 'exit nil))
6067 ;;; Indirect buffer display of subtrees
6069 (defvar org-indirect-dedicated-frame nil
6070 "This is the frame being used for indirect tree display.")
6071 (defvar org-last-indirect-buffer nil)
6073 (defun org-tree-to-indirect-buffer (&optional arg)
6074 "Create indirect buffer and narrow it to current subtree.
6075 With numerical prefix ARG, go up to this level and then take that tree.
6076 If ARG is negative, go up that many levels.
6077 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6078 indirect buffer previously made with this command, to avoid proliferation of
6079 indirect buffers. However, when you call the command with a `C-u' prefix, or
6080 when `org-indirect-buffer-display' is `new-frame', the last buffer
6081 is kept so that you can work with several indirect buffers at the same time.
6082 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6083 requests that a new frame be made for the new buffer, so that the dedicated
6084 frame is not changed."
6085 (interactive "P")
6086 (let ((cbuf (current-buffer))
6087 (cwin (selected-window))
6088 (pos (point))
6089 beg end level heading ibuf)
6090 (save-excursion
6091 (org-back-to-heading t)
6092 (when (numberp arg)
6093 (setq level (org-outline-level))
6094 (if (< arg 0) (setq arg (+ level arg)))
6095 (while (> (setq level (org-outline-level)) arg)
6096 (outline-up-heading 1 t)))
6097 (setq beg (point)
6098 heading (org-get-heading))
6099 (org-end-of-subtree t) (setq end (point)))
6100 (if (and (buffer-live-p org-last-indirect-buffer)
6101 (not (eq org-indirect-buffer-display 'new-frame))
6102 (not arg))
6103 (kill-buffer org-last-indirect-buffer))
6104 (setq ibuf (org-get-indirect-buffer cbuf)
6105 org-last-indirect-buffer ibuf)
6106 (cond
6107 ((or (eq org-indirect-buffer-display 'new-frame)
6108 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6109 (select-frame (make-frame))
6110 (delete-other-windows)
6111 (switch-to-buffer ibuf)
6112 (org-set-frame-title heading))
6113 ((eq org-indirect-buffer-display 'dedicated-frame)
6114 (raise-frame
6115 (select-frame (or (and org-indirect-dedicated-frame
6116 (frame-live-p org-indirect-dedicated-frame)
6117 org-indirect-dedicated-frame)
6118 (setq org-indirect-dedicated-frame (make-frame)))))
6119 (delete-other-windows)
6120 (switch-to-buffer ibuf)
6121 (org-set-frame-title (concat "Indirect: " heading)))
6122 ((eq org-indirect-buffer-display 'current-window)
6123 (switch-to-buffer ibuf))
6124 ((eq org-indirect-buffer-display 'other-window)
6125 (pop-to-buffer ibuf))
6126 (t (error "Invalid value.")))
6127 (if (featurep 'xemacs)
6128 (save-excursion (org-mode) (turn-on-font-lock)))
6129 (narrow-to-region beg end)
6130 (show-all)
6131 (goto-char pos)
6132 (and (window-live-p cwin) (select-window cwin))))
6134 (defun org-get-indirect-buffer (&optional buffer)
6135 (setq buffer (or buffer (current-buffer)))
6136 (let ((n 1) (base (buffer-name buffer)) bname)
6137 (while (buffer-live-p
6138 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6139 (setq n (1+ n)))
6140 (condition-case nil
6141 (make-indirect-buffer buffer bname 'clone)
6142 (error (make-indirect-buffer buffer bname)))))
6144 (defun org-set-frame-title (title)
6145 "Set the title of the current frame to the string TITLE."
6146 ;; FIXME: how to name a single frame in XEmacs???
6147 (unless (featurep 'xemacs)
6148 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6150 ;;;; Structure editing
6152 ;;; Inserting headlines
6154 (defun org-insert-heading (&optional force-heading)
6155 "Insert a new heading or item with same depth at point.
6156 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6157 If point is at the beginning of a headline, insert a sibling before the
6158 current headline. If point is not at the beginning, do not split the line,
6159 but create the new hedline after the current line."
6160 (interactive "P")
6161 (if (= (buffer-size) 0)
6162 (insert "\n* ")
6163 (when (or force-heading (not (org-insert-item)))
6164 (let* ((head (save-excursion
6165 (condition-case nil
6166 (progn
6167 (org-back-to-heading)
6168 (match-string 0))
6169 (error "*"))))
6170 (blank (cdr (assq 'heading org-blank-before-new-entry)))
6171 pos)
6172 (cond
6173 ((and (org-on-heading-p) (bolp)
6174 (or (bobp)
6175 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6176 ;; insert before the current line
6177 (open-line (if blank 2 1)))
6178 ((and (bolp)
6179 (or (bobp)
6180 (save-excursion
6181 (backward-char 1) (not (org-invisible-p)))))
6182 ;; insert right here
6183 nil)
6185 ;; in the middle of the line
6186 (org-show-entry)
6187 (end-of-line 1)
6188 (newline (if blank 2 1))))
6189 (insert head) (just-one-space)
6190 (setq pos (point))
6191 (end-of-line 1)
6192 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6193 (run-hooks 'org-insert-heading-hook)))))
6195 (defun org-insert-heading-after-current ()
6196 "Insert a new heading with same level as current, after current subtree."
6197 (interactive)
6198 (org-back-to-heading)
6199 (org-insert-heading)
6200 (org-move-subtree-down)
6201 (end-of-line 1))
6203 (defun org-insert-todo-heading (arg)
6204 "Insert a new heading with the same level and TODO state as current heading.
6205 If the heading has no TODO state, or if the state is DONE, use the first
6206 state (TODO by default). Also with prefix arg, force first state."
6207 (interactive "P")
6208 (when (not (org-insert-item 'checkbox))
6209 (org-insert-heading)
6210 (save-excursion
6211 (org-back-to-heading)
6212 (outline-previous-heading)
6213 (looking-at org-todo-line-regexp))
6214 (if (or arg
6215 (not (match-beginning 2))
6216 (member (match-string 2) org-done-keywords))
6217 (insert (car org-todo-keywords-1) " ")
6218 (insert (match-string 2) " "))))
6220 (defun org-insert-subheading (arg)
6221 "Insert a new subheading and demote it.
6222 Works for outline headings and for plain lists alike."
6223 (interactive "P")
6224 (org-insert-heading arg)
6225 (cond
6226 ((org-on-heading-p) (org-do-demote))
6227 ((org-at-item-p) (org-indent-item 1))))
6229 (defun org-insert-todo-subheading (arg)
6230 "Insert a new subheading with TODO keyword or checkbox and demote it.
6231 Works for outline headings and for plain lists alike."
6232 (interactive "P")
6233 (org-insert-todo-heading arg)
6234 (cond
6235 ((org-on-heading-p) (org-do-demote))
6236 ((org-at-item-p) (org-indent-item 1))))
6238 ;;; Promotion and Demotion
6240 (defun org-promote-subtree ()
6241 "Promote the entire subtree.
6242 See also `org-promote'."
6243 (interactive)
6244 (save-excursion
6245 (org-map-tree 'org-promote))
6246 (org-fix-position-after-promote))
6248 (defun org-demote-subtree ()
6249 "Demote the entire subtree. See `org-demote'.
6250 See also `org-promote'."
6251 (interactive)
6252 (save-excursion
6253 (org-map-tree 'org-demote))
6254 (org-fix-position-after-promote))
6257 (defun org-do-promote ()
6258 "Promote the current heading higher up the tree.
6259 If the region is active in `transient-mark-mode', promote all headings
6260 in the region."
6261 (interactive)
6262 (save-excursion
6263 (if (org-region-active-p)
6264 (org-map-region 'org-promote (region-beginning) (region-end))
6265 (org-promote)))
6266 (org-fix-position-after-promote))
6268 (defun org-do-demote ()
6269 "Demote the current heading lower down the tree.
6270 If the region is active in `transient-mark-mode', demote all headings
6271 in the region."
6272 (interactive)
6273 (save-excursion
6274 (if (org-region-active-p)
6275 (org-map-region 'org-demote (region-beginning) (region-end))
6276 (org-demote)))
6277 (org-fix-position-after-promote))
6279 (defun org-fix-position-after-promote ()
6280 "Make sure that after pro/demotion cursor position is right."
6281 (let ((pos (point)))
6282 (when (save-excursion
6283 (beginning-of-line 1)
6284 (looking-at org-todo-line-regexp)
6285 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6286 (cond ((eobp) (insert " "))
6287 ((eolp) (insert " "))
6288 ((equal (char-after) ?\ ) (forward-char 1))))))
6290 (defun org-reduced-level (l)
6291 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6293 (defun org-get-legal-level (level &optional change)
6294 "Rectify a level change under the influence of `org-odd-levels-only'
6295 LEVEL is a current level, CHANGE is by how much the level should be
6296 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6297 even level numbers will become the next higher odd number."
6298 (if org-odd-levels-only
6299 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6300 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6301 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6302 (max 1 (+ level change))))
6304 (defun org-promote ()
6305 "Promote the current heading higher up the tree.
6306 If the region is active in `transient-mark-mode', promote all headings
6307 in the region."
6308 (org-back-to-heading t)
6309 (let* ((level (save-match-data (funcall outline-level)))
6310 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
6311 (diff (abs (- level (length up-head) -1))))
6312 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6313 (replace-match up-head nil t)
6314 ;; Fixup tag positioning
6315 (and org-auto-align-tags (org-set-tags nil t))
6316 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
6318 (defun org-demote ()
6319 "Demote the current heading lower down the tree.
6320 If the region is active in `transient-mark-mode', demote all headings
6321 in the region."
6322 (org-back-to-heading t)
6323 (let* ((level (save-match-data (funcall outline-level)))
6324 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
6325 (diff (abs (- level (length down-head) -1))))
6326 (replace-match down-head nil t)
6327 ;; Fixup tag positioning
6328 (and org-auto-align-tags (org-set-tags nil t))
6329 (if org-adapt-indentation (org-fixup-indentation diff))))
6331 (defun org-map-tree (fun)
6332 "Call FUN for every heading underneath the current one."
6333 (org-back-to-heading)
6334 (let ((level (funcall outline-level)))
6335 (save-excursion
6336 (funcall fun)
6337 (while (and (progn
6338 (outline-next-heading)
6339 (> (funcall outline-level) level))
6340 (not (eobp)))
6341 (funcall fun)))))
6343 (defun org-map-region (fun beg end)
6344 "Call FUN for every heading between BEG and END."
6345 (let ((org-ignore-region t))
6346 (save-excursion
6347 (setq end (copy-marker end))
6348 (goto-char beg)
6349 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6350 (< (point) end))
6351 (funcall fun))
6352 (while (and (progn
6353 (outline-next-heading)
6354 (< (point) end))
6355 (not (eobp)))
6356 (funcall fun)))))
6358 (defun org-fixup-indentation (diff)
6359 "Change the indentation in the current entry by DIFF
6360 However, if any line in the current entry has no indentation, or if it
6361 would end up with no indentation after the change, nothing at all is done."
6362 (save-excursion
6363 (let ((end (save-excursion (outline-next-heading)
6364 (point-marker)))
6365 (prohibit (if (> diff 0)
6366 "^\\S-"
6367 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6368 col)
6369 (unless (save-excursion (end-of-line 1)
6370 (re-search-forward prohibit end t))
6371 (while (and (< (point) end)
6372 (re-search-forward "^[ \t]+" end t))
6373 (goto-char (match-end 0))
6374 (setq col (current-column))
6375 (if (< diff 0) (replace-match ""))
6376 (indent-to (+ diff col))))
6377 (move-marker end nil))))
6379 (defun org-convert-to-odd-levels ()
6380 "Convert an org-mode file with all levels allowed to one with odd levels.
6381 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6382 level 5 etc."
6383 (interactive)
6384 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6385 (let ((org-odd-levels-only nil) n)
6386 (save-excursion
6387 (goto-char (point-min))
6388 (while (re-search-forward "^\\*\\*+ " nil t)
6389 (setq n (- (length (match-string 0)) 2))
6390 (while (>= (setq n (1- n)) 0)
6391 (org-demote))
6392 (end-of-line 1))))))
6395 (defun org-convert-to-oddeven-levels ()
6396 "Convert an org-mode file with only odd levels to one with odd and even levels.
6397 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6398 section with an even level, conversion would destroy the structure of the file. An error
6399 is signaled in this case."
6400 (interactive)
6401 (goto-char (point-min))
6402 ;; First check if there are no even levels
6403 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6404 (org-show-context t)
6405 (error "Not all levels are odd in this file. Conversion not possible."))
6406 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6407 (let ((org-odd-levels-only nil) n)
6408 (save-excursion
6409 (goto-char (point-min))
6410 (while (re-search-forward "^\\*\\*+ " nil t)
6411 (setq n (/ (1- (length (match-string 0))) 2))
6412 (while (>= (setq n (1- n)) 0)
6413 (org-promote))
6414 (end-of-line 1))))))
6416 (defun org-tr-level (n)
6417 "Make N odd if required."
6418 (if org-odd-levels-only (1+ (/ n 2)) n))
6420 ;;; Vertical tree motion, cutting and pasting of subtrees
6422 (defun org-move-subtree-up (&optional arg)
6423 "Move the current subtree up past ARG headlines of the same level."
6424 (interactive "p")
6425 (org-move-subtree-down (- (prefix-numeric-value arg))))
6427 (defun org-move-subtree-down (&optional arg)
6428 "Move the current subtree down past ARG headlines of the same level."
6429 (interactive "p")
6430 (setq arg (prefix-numeric-value arg))
6431 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6432 'outline-get-last-sibling))
6433 (ins-point (make-marker))
6434 (cnt (abs arg))
6435 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6436 ;; Select the tree
6437 (org-back-to-heading)
6438 (setq beg0 (point))
6439 (save-excursion
6440 (setq ne-beg (org-back-over-empty-lines))
6441 (setq beg (point)))
6442 (save-match-data
6443 (save-excursion (outline-end-of-heading)
6444 (setq folded (org-invisible-p)))
6445 (outline-end-of-subtree))
6446 (outline-next-heading)
6447 (setq ne-end (org-back-over-empty-lines))
6448 (setq end (point))
6449 (goto-char beg0)
6450 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6451 ;; include less whitespace
6452 (save-excursion
6453 (goto-char beg)
6454 (forward-line (- ne-beg ne-end))
6455 (setq beg (point))))
6456 ;; Find insertion point, with error handling
6457 (while (> cnt 0)
6458 (or (and (funcall movfunc) (looking-at outline-regexp))
6459 (progn (goto-char beg0)
6460 (error "Cannot move past superior level or buffer limit")))
6461 (setq cnt (1- cnt)))
6462 (if (> arg 0)
6463 ;; Moving forward - still need to move over subtree
6464 (progn (org-end-of-subtree t t)
6465 (save-excursion
6466 (org-back-over-empty-lines)
6467 (or (bolp) (newline)))))
6468 (setq ne-ins (org-back-over-empty-lines))
6469 (move-marker ins-point (point))
6470 (setq txt (buffer-substring beg end))
6471 (delete-region beg end)
6472 (outline-flag-region (1- beg) beg nil)
6473 (outline-flag-region (1- (point)) (point) nil)
6474 (insert txt)
6475 (or (bolp) (insert "\n"))
6476 (setq ins-end (point))
6477 (goto-char ins-point)
6478 (org-skip-whitespace)
6479 (when (and (< arg 0)
6480 (org-first-sibling-p)
6481 (> ne-ins ne-beg))
6482 ;; Move whitespace back to beginning
6483 (save-excursion
6484 (goto-char ins-end)
6485 (let ((kill-whole-line t))
6486 (kill-line (- ne-ins ne-beg)) (point)))
6487 (insert (make-string (- ne-ins ne-beg) ?\n)))
6488 (move-marker ins-point nil)
6489 (org-compact-display-after-subtree-move)
6490 (unless folded
6491 (org-show-entry)
6492 (show-children)
6493 (org-cycle-hide-drawers 'children))))
6495 (defvar org-subtree-clip ""
6496 "Clipboard for cut and paste of subtrees.
6497 This is actually only a copy of the kill, because we use the normal kill
6498 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6500 (defvar org-subtree-clip-folded nil
6501 "Was the last copied subtree folded?
6502 This is used to fold the tree back after pasting.")
6504 (defun org-cut-subtree (&optional n)
6505 "Cut the current subtree into the clipboard.
6506 With prefix arg N, cut this many sequential subtrees.
6507 This is a short-hand for marking the subtree and then cutting it."
6508 (interactive "p")
6509 (org-copy-subtree n 'cut))
6511 (defun org-copy-subtree (&optional n cut)
6512 "Cut the current subtree into the clipboard.
6513 With prefix arg N, cut this many sequential subtrees.
6514 This is a short-hand for marking the subtree and then copying it.
6515 If CUT is non-nil, actually cut the subtree."
6516 (interactive "p")
6517 (let (beg end folded (beg0 (point)))
6518 (if (interactive-p)
6519 (org-back-to-heading nil) ; take what looks like a subtree
6520 (org-back-to-heading t)) ; take what is really there
6521 (org-back-over-empty-lines)
6522 (setq beg (point))
6523 (skip-chars-forward " \t\r\n")
6524 (save-match-data
6525 (save-excursion (outline-end-of-heading)
6526 (setq folded (org-invisible-p)))
6527 (condition-case nil
6528 (outline-forward-same-level (1- n))
6529 (error nil))
6530 (org-end-of-subtree t t))
6531 (org-back-over-empty-lines)
6532 (setq end (point))
6533 (goto-char beg0)
6534 (when (> end beg)
6535 (setq org-subtree-clip-folded folded)
6536 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6537 (setq org-subtree-clip (current-kill 0))
6538 (message "%s: Subtree(s) with %d characters"
6539 (if cut "Cut" "Copied")
6540 (length org-subtree-clip)))))
6542 (defun org-paste-subtree (&optional level tree)
6543 "Paste the clipboard as a subtree, with modification of headline level.
6544 The entire subtree is promoted or demoted in order to match a new headline
6545 level. By default, the new level is derived from the visible headings
6546 before and after the insertion point, and taken to be the inferior headline
6547 level of the two. So if the previous visible heading is level 3 and the
6548 next is level 4 (or vice versa), level 4 will be used for insertion.
6549 This makes sure that the subtree remains an independent subtree and does
6550 not swallow low level entries.
6552 You can also force a different level, either by using a numeric prefix
6553 argument, or by inserting the heading marker by hand. For example, if the
6554 cursor is after \"*****\", then the tree will be shifted to level 5.
6556 If you want to insert the tree as is, just use \\[yank].
6558 If optional TREE is given, use this text instead of the kill ring."
6559 (interactive "P")
6560 (unless (org-kill-is-subtree-p tree)
6561 (error "%s"
6562 (substitute-command-keys
6563 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6564 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6565 (^re (concat "^\\(" outline-regexp "\\)"))
6566 (re (concat "\\(" outline-regexp "\\)"))
6567 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6569 (old-level (if (string-match ^re txt)
6570 (- (match-end 0) (match-beginning 0) 1)
6571 -1))
6572 (force-level (cond (level (prefix-numeric-value level))
6573 ((string-match
6574 ^re_ (buffer-substring (point-at-bol) (point)))
6575 (- (match-end 1) (match-beginning 1)))
6576 (t nil)))
6577 (previous-level (save-excursion
6578 (condition-case nil
6579 (progn
6580 (outline-previous-visible-heading 1)
6581 (if (looking-at re)
6582 (- (match-end 0) (match-beginning 0) 1)
6584 (error 1))))
6585 (next-level (save-excursion
6586 (condition-case nil
6587 (progn
6588 (or (looking-at outline-regexp)
6589 (outline-next-visible-heading 1))
6590 (if (looking-at re)
6591 (- (match-end 0) (match-beginning 0) 1)
6593 (error 1))))
6594 (new-level (or force-level (max previous-level next-level)))
6595 (shift (if (or (= old-level -1)
6596 (= new-level -1)
6597 (= old-level new-level))
6599 (- new-level old-level)))
6600 (delta (if (> shift 0) -1 1))
6601 (func (if (> shift 0) 'org-demote 'org-promote))
6602 (org-odd-levels-only nil)
6603 beg end)
6604 ;; Remove the forced level indicator
6605 (if force-level
6606 (delete-region (point-at-bol) (point)))
6607 ;; Paste
6608 (beginning-of-line 1)
6609 (org-back-over-empty-lines) ;; FIXME: correct fix????
6610 (setq beg (point))
6611 (insert-before-markers txt) ;; FIXME: correct fix????
6612 (unless (string-match "\n\\'" txt) (insert "\n"))
6613 (setq end (point))
6614 (goto-char beg)
6615 (skip-chars-forward " \t\n\r")
6616 (setq beg (point))
6617 ;; Shift if necessary
6618 (unless (= shift 0)
6619 (save-restriction
6620 (narrow-to-region beg end)
6621 (while (not (= shift 0))
6622 (org-map-region func (point-min) (point-max))
6623 (setq shift (+ delta shift)))
6624 (goto-char (point-min))))
6625 (when (interactive-p)
6626 (message "Clipboard pasted as level %d subtree" new-level))
6627 (if (and kill-ring
6628 (eq org-subtree-clip (current-kill 0))
6629 org-subtree-clip-folded)
6630 ;; The tree was folded before it was killed/copied
6631 (hide-subtree))))
6633 (defun org-kill-is-subtree-p (&optional txt)
6634 "Check if the current kill is an outline subtree, or a set of trees.
6635 Returns nil if kill does not start with a headline, or if the first
6636 headline level is not the largest headline level in the tree.
6637 So this will actually accept several entries of equal levels as well,
6638 which is OK for `org-paste-subtree'.
6639 If optional TXT is given, check this string instead of the current kill."
6640 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6641 (start-level (and kill
6642 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6643 org-outline-regexp "\\)")
6644 kill)
6645 (- (match-end 2) (match-beginning 2) 1)))
6646 (re (concat "^" org-outline-regexp))
6647 (start (1+ (match-beginning 2))))
6648 (if (not start-level)
6649 (progn
6650 nil) ;; does not even start with a heading
6651 (catch 'exit
6652 (while (setq start (string-match re kill (1+ start)))
6653 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6654 (throw 'exit nil)))
6655 t))))
6657 (defun org-narrow-to-subtree ()
6658 "Narrow buffer to the current subtree."
6659 (interactive)
6660 (save-excursion
6661 (narrow-to-region
6662 (progn (org-back-to-heading) (point))
6663 (progn (org-end-of-subtree t t) (point)))))
6666 ;;; Outline Sorting
6668 (defun org-sort (with-case)
6669 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6670 Optional argument WITH-CASE means sort case-sensitively."
6671 (interactive "P")
6672 (if (org-at-table-p)
6673 (org-call-with-arg 'org-table-sort-lines with-case)
6674 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6676 (defvar org-priority-regexp) ; defined later in the file
6678 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6679 "Sort entries on a certain level of an outline tree.
6680 If there is an active region, the entries in the region are sorted.
6681 Else, if the cursor is before the first entry, sort the top-level items.
6682 Else, the children of the entry at point are sorted.
6684 Sorting can be alphabetically, numerically, and by date/time as given by
6685 the first time stamp in the entry. The command prompts for the sorting
6686 type unless it has been given to the function through the SORTING-TYPE
6687 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6688 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6689 called with point at the beginning of the record. It must return either
6690 a string or a number that should serve as the sorting key for that record.
6692 Comparing entries ignores case by default. However, with an optional argument
6693 WITH-CASE, the sorting considers case as well."
6694 (interactive "P")
6695 (let ((case-func (if with-case 'identity 'downcase))
6696 start beg end stars re re2
6697 txt what tmp plain-list-p)
6698 ;; Find beginning and end of region to sort
6699 (cond
6700 ((org-region-active-p)
6701 ;; we will sort the region
6702 (setq end (region-end)
6703 what "region")
6704 (goto-char (region-beginning))
6705 (if (not (org-on-heading-p)) (outline-next-heading))
6706 (setq start (point)))
6707 ((org-at-item-p)
6708 ;; we will sort this plain list
6709 (org-beginning-of-item-list) (setq start (point))
6710 (org-end-of-item-list) (setq end (point))
6711 (goto-char start)
6712 (setq plain-list-p t
6713 what "plain list"))
6714 ((or (org-on-heading-p)
6715 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6716 ;; we will sort the children of the current headline
6717 (org-back-to-heading)
6718 (setq start (point)
6719 end (progn (org-end-of-subtree t t)
6720 (org-back-over-empty-lines)
6721 (point))
6722 what "children")
6723 (goto-char start)
6724 (show-subtree)
6725 (outline-next-heading))
6727 ;; we will sort the top-level entries in this file
6728 (goto-char (point-min))
6729 (or (org-on-heading-p) (outline-next-heading))
6730 (setq start (point) end (point-max) what "top-level")
6731 (goto-char start)
6732 (show-all)))
6734 (setq beg (point))
6735 (if (>= beg end) (error "Nothing to sort"))
6737 (unless plain-list-p
6738 (looking-at "\\(\\*+\\)")
6739 (setq stars (match-string 1)
6740 re (concat "^" (regexp-quote stars) " +")
6741 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6742 txt (buffer-substring beg end))
6743 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6744 (if (and (not (equal stars "*")) (string-match re2 txt))
6745 (error "Region to sort contains a level above the first entry")))
6747 (unless sorting-type
6748 (message
6749 (if plain-list-p
6750 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6751 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
6752 what)
6753 (setq sorting-type (read-char-exclusive))
6755 (and (= (downcase sorting-type) ?f)
6756 (setq getkey-func
6757 (completing-read "Sort using function: "
6758 obarray 'fboundp t nil nil))
6759 (setq getkey-func (intern getkey-func)))
6761 (and (= (downcase sorting-type) ?r)
6762 (setq property
6763 (completing-read "Property: "
6764 (mapcar 'list (org-buffer-property-keys t))
6765 nil t))))
6767 (message "Sorting entries...")
6769 (save-restriction
6770 (narrow-to-region start end)
6772 (let ((dcst (downcase sorting-type))
6773 (now (current-time)))
6774 (sort-subr
6775 (/= dcst sorting-type)
6776 ;; This function moves to the beginning character of the "record" to
6777 ;; be sorted.
6778 (if plain-list-p
6779 (lambda nil
6780 (if (org-at-item-p) t (goto-char (point-max))))
6781 (lambda nil
6782 (if (re-search-forward re nil t)
6783 (goto-char (match-beginning 0))
6784 (goto-char (point-max)))))
6785 ;; This function moves to the last character of the "record" being
6786 ;; sorted.
6787 (if plain-list-p
6788 'org-end-of-item
6789 (lambda nil
6790 (save-match-data
6791 (condition-case nil
6792 (outline-forward-same-level 1)
6793 (error
6794 (goto-char (point-max)))))))
6796 ;; This function returns the value that gets sorted against.
6797 (if plain-list-p
6798 (lambda nil
6799 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6800 (cond
6801 ((= dcst ?n)
6802 (string-to-number (buffer-substring (match-end 0)
6803 (point-at-eol))))
6804 ((= dcst ?a)
6805 (buffer-substring (match-end 0) (point-at-eol)))
6806 ((= dcst ?t)
6807 (if (re-search-forward org-ts-regexp
6808 (point-at-eol) t)
6809 (org-time-string-to-time (match-string 0))
6810 now))
6811 ((= dcst ?f)
6812 (if getkey-func
6813 (progn
6814 (setq tmp (funcall getkey-func))
6815 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6816 tmp)
6817 (error "Invalid key function `%s'" getkey-func)))
6818 (t (error "Invalid sorting type `%c'" sorting-type)))))
6819 (lambda nil
6820 (cond
6821 ((= dcst ?n)
6822 (if (looking-at outline-regexp)
6823 (string-to-number (buffer-substring (match-end 0)
6824 (point-at-eol)))
6825 nil))
6826 ((= dcst ?a)
6827 (funcall case-func (buffer-substring (point-at-bol)
6828 (point-at-eol))))
6829 ((= dcst ?t)
6830 (if (re-search-forward org-ts-regexp
6831 (save-excursion
6832 (forward-line 2)
6833 (point)) t)
6834 (org-time-string-to-time (match-string 0))
6835 now))
6836 ((= dcst ?p)
6837 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6838 (string-to-char (match-string 2))
6839 org-default-priority))
6840 ((= dcst ?r)
6841 (or (org-entry-get nil property) ""))
6842 ((= dcst ?f)
6843 (if getkey-func
6844 (progn
6845 (setq tmp (funcall getkey-func))
6846 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6847 tmp)
6848 (error "Invalid key function `%s'" getkey-func)))
6849 (t (error "Invalid sorting type `%c'" sorting-type)))))
6851 (cond
6852 ((= dcst ?a) 'string<)
6853 ((= dcst ?t) 'time-less-p)
6854 (t nil)))))
6855 (message "Sorting entries...done")))
6857 (defun org-do-sort (table what &optional with-case sorting-type)
6858 "Sort TABLE of WHAT according to SORTING-TYPE.
6859 The user will be prompted for the SORTING-TYPE if the call to this
6860 function does not specify it. WHAT is only for the prompt, to indicate
6861 what is being sorted. The sorting key will be extracted from
6862 the car of the elements of the table.
6863 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6864 (unless sorting-type
6865 (message
6866 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6867 what)
6868 (setq sorting-type (read-char-exclusive)))
6869 (let ((dcst (downcase sorting-type))
6870 extractfun comparefun)
6871 ;; Define the appropriate functions
6872 (cond
6873 ((= dcst ?n)
6874 (setq extractfun 'string-to-number
6875 comparefun (if (= dcst sorting-type) '< '>)))
6876 ((= dcst ?a)
6877 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6878 (lambda(x) (downcase (org-sort-remove-invisible x))))
6879 comparefun (if (= dcst sorting-type)
6880 'string<
6881 (lambda (a b) (and (not (string< a b))
6882 (not (string= a b)))))))
6883 ((= dcst ?t)
6884 (setq extractfun
6885 (lambda (x)
6886 (if (string-match org-ts-regexp x)
6887 (time-to-seconds
6888 (org-time-string-to-time (match-string 0 x)))
6890 comparefun (if (= dcst sorting-type) '< '>)))
6891 (t (error "Invalid sorting type `%c'" sorting-type)))
6893 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6894 table)
6895 (lambda (a b) (funcall comparefun (car a) (car b))))))
6897 ;;;; Plain list items, including checkboxes
6899 ;;; Plain list items
6901 (defun org-at-item-p ()
6902 "Is point in a line starting a hand-formatted item?"
6903 (let ((llt org-plain-list-ordered-item-terminator))
6904 (save-excursion
6905 (goto-char (point-at-bol))
6906 (looking-at
6907 (cond
6908 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6909 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6910 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6911 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
6913 (defun org-in-item-p ()
6914 "It the cursor inside a plain list item.
6915 Does not have to be the first line."
6916 (save-excursion
6917 (condition-case nil
6918 (progn
6919 (org-beginning-of-item)
6920 (org-at-item-p)
6922 (error nil))))
6924 (defun org-insert-item (&optional checkbox)
6925 "Insert a new item at the current level.
6926 Return t when things worked, nil when we are not in an item."
6927 (when (save-excursion
6928 (condition-case nil
6929 (progn
6930 (org-beginning-of-item)
6931 (org-at-item-p)
6932 (if (org-invisible-p) (error "Invisible item"))
6934 (error nil)))
6935 (let* ((bul (match-string 0))
6936 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
6937 (match-end 0)))
6938 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
6939 pos)
6940 (cond
6941 ((and (org-at-item-p) (<= (point) eow))
6942 ;; before the bullet
6943 (beginning-of-line 1)
6944 (open-line (if blank 2 1)))
6945 ((<= (point) eow)
6946 (beginning-of-line 1))
6947 (t (newline (if blank 2 1))))
6948 (insert bul (if checkbox "[ ]" ""))
6949 (just-one-space)
6950 (setq pos (point))
6951 (end-of-line 1)
6952 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
6953 (org-maybe-renumber-ordered-list)
6954 (and checkbox (org-update-checkbox-count-maybe))
6957 ;;; Checkboxes
6959 (defun org-at-item-checkbox-p ()
6960 "Is point at a line starting a plain-list item with a checklet?"
6961 (and (org-at-item-p)
6962 (save-excursion
6963 (goto-char (match-end 0))
6964 (skip-chars-forward " \t")
6965 (looking-at "\\[[- X]\\]"))))
6967 (defun org-toggle-checkbox (&optional arg)
6968 "Toggle the checkbox in the current line."
6969 (interactive "P")
6970 (catch 'exit
6971 (let (beg end status (firstnew 'unknown))
6972 (cond
6973 ((org-region-active-p)
6974 (setq beg (region-beginning) end (region-end)))
6975 ((org-on-heading-p)
6976 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
6977 ((org-at-item-checkbox-p)
6978 (let ((pos (point)))
6979 (replace-match
6980 (cond (arg "[-]")
6981 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
6982 (t "[ ]"))
6983 t t)
6984 (goto-char pos))
6985 (throw 'exit t))
6986 (t (error "Not at a checkbox or heading, and no active region")))
6987 (save-excursion
6988 (goto-char beg)
6989 (while (< (point) end)
6990 (when (org-at-item-checkbox-p)
6991 (setq status (equal (match-string 0) "[X]"))
6992 (when (eq firstnew 'unknown)
6993 (setq firstnew (not status)))
6994 (replace-match
6995 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
6996 (beginning-of-line 2)))))
6997 (org-update-checkbox-count-maybe))
6999 (defun org-update-checkbox-count-maybe ()
7000 "Update checkbox statistics unless turned off by user."
7001 (when org-provide-checkbox-statistics
7002 (org-update-checkbox-count)))
7004 (defun org-update-checkbox-count (&optional all)
7005 "Update the checkbox statistics in the current section.
7006 This will find all statistic cookies like [57%] and [6/12] and update them
7007 with the current numbers. With optional prefix argument ALL, do this for
7008 the whole buffer."
7009 (interactive "P")
7010 (save-excursion
7011 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
7012 (beg (condition-case nil
7013 (progn (outline-back-to-heading) (point))
7014 (error (point-min))))
7015 (end (move-marker (make-marker)
7016 (progn (outline-next-heading) (point))))
7017 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
7018 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
7019 (re-find (concat re "\\|" re-box))
7020 beg-cookie end-cookie is-percent c-on c-off lim
7021 eline curr-ind next-ind continue-from startsearch
7022 (cstat 0)
7024 (when all
7025 (goto-char (point-min))
7026 (outline-next-heading)
7027 (setq beg (point) end (point-max)))
7028 (goto-char end)
7029 ;; find each statistic cookie
7030 (while (re-search-backward re-find beg t)
7031 (setq beg-cookie (match-beginning 1)
7032 end-cookie (match-end 1)
7033 cstat (+ cstat (if end-cookie 1 0))
7034 startsearch (point-at-eol)
7035 continue-from (point-at-bol)
7036 is-percent (match-beginning 2)
7037 lim (cond
7038 ((org-on-heading-p) (outline-next-heading) (point))
7039 ((org-at-item-p) (org-end-of-item) (point))
7040 (t nil))
7041 c-on 0
7042 c-off 0)
7043 (when lim
7044 ;; find first checkbox for this cookie and gather
7045 ;; statistics from all that are at this indentation level
7046 (goto-char startsearch)
7047 (if (re-search-forward re-box lim t)
7048 (progn
7049 (org-beginning-of-item)
7050 (setq curr-ind (org-get-indentation))
7051 (setq next-ind curr-ind)
7052 (while (= curr-ind next-ind)
7053 (save-excursion (end-of-line) (setq eline (point)))
7054 (if (re-search-forward re-box eline t)
7055 (if (member (match-string 2) '("[ ]" "[-]"))
7056 (setq c-off (1+ c-off))
7057 (setq c-on (1+ c-on))
7060 (org-end-of-item)
7061 (setq next-ind (org-get-indentation))
7063 (goto-char continue-from)
7064 ;; update cookie
7065 (when end-cookie
7066 (delete-region beg-cookie end-cookie)
7067 (goto-char beg-cookie)
7068 (insert
7069 (if is-percent
7070 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
7071 (format "[%d/%d]" c-on (+ c-on c-off)))))
7072 ;; update items checkbox if it has one
7073 (when (org-at-item-p)
7074 (org-beginning-of-item)
7075 (when (and (> (+ c-on c-off) 0)
7076 (re-search-forward re-box (point-at-eol) t))
7077 (setq beg-cookie (match-beginning 2)
7078 end-cookie (match-end 2))
7079 (delete-region beg-cookie end-cookie)
7080 (goto-char beg-cookie)
7081 (cond ((= c-off 0) (insert "[X]"))
7082 ((= c-on 0) (insert "[ ]"))
7083 (t (insert "[-]")))
7085 (goto-char continue-from))
7086 (when (interactive-p)
7087 (message "Checkbox satistics updated %s (%d places)"
7088 (if all "in entire file" "in current outline entry") cstat)))))
7090 (defun org-get-checkbox-statistics-face ()
7091 "Select the face for checkbox statistics.
7092 The face will be `org-done' when all relevant boxes are checked. Otherwise
7093 it will be `org-todo'."
7094 (if (match-end 1)
7095 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
7096 (if (and (> (match-end 2) (match-beginning 2))
7097 (equal (match-string 2) (match-string 3)))
7098 'org-done
7099 'org-todo)))
7101 (defun org-get-indentation (&optional line)
7102 "Get the indentation of the current line, interpreting tabs.
7103 When LINE is given, assume it represents a line and compute its indentation."
7104 (if line
7105 (if (string-match "^ *" (org-remove-tabs line))
7106 (match-end 0))
7107 (save-excursion
7108 (beginning-of-line 1)
7109 (skip-chars-forward " \t")
7110 (current-column))))
7112 (defun org-remove-tabs (s &optional width)
7113 "Replace tabulators in S with spaces.
7114 Assumes that s is a single line, starting in column 0."
7115 (setq width (or width tab-width))
7116 (while (string-match "\t" s)
7117 (setq s (replace-match
7118 (make-string
7119 (- (* width (/ (+ (match-beginning 0) width) width))
7120 (match-beginning 0)) ?\ )
7121 t t s)))
7124 (defun org-fix-indentation (line ind)
7125 "Fix indentation in LINE.
7126 IND is a cons cell with target and minimum indentation.
7127 If the current indenation in LINE is smaller than the minimum,
7128 leave it alone. If it is larger than ind, set it to the target."
7129 (let* ((l (org-remove-tabs line))
7130 (i (org-get-indentation l))
7131 (i1 (car ind)) (i2 (cdr ind)))
7132 (if (>= i i2) (setq l (substring line i2)))
7133 (if (> i1 0)
7134 (concat (make-string i1 ?\ ) l)
7135 l)))
7137 (defcustom org-empty-line-terminates-plain-lists nil
7138 "Non-nil means, an empty line ends all plain list levels.
7139 When nil, empty lines are part of the preceeding item."
7140 :group 'org-plain-lists
7141 :type 'boolean)
7143 (defun org-beginning-of-item ()
7144 "Go to the beginning of the current hand-formatted item.
7145 If the cursor is not in an item, throw an error."
7146 (interactive)
7147 (let ((pos (point))
7148 (limit (save-excursion
7149 (condition-case nil
7150 (progn
7151 (org-back-to-heading)
7152 (beginning-of-line 2) (point))
7153 (error (point-min)))))
7154 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7155 ind ind1)
7156 (if (org-at-item-p)
7157 (beginning-of-line 1)
7158 (beginning-of-line 1)
7159 (skip-chars-forward " \t")
7160 (setq ind (current-column))
7161 (if (catch 'exit
7162 (while t
7163 (beginning-of-line 0)
7164 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
7166 (if (looking-at "[ \t]*$")
7167 (setq ind1 ind-empty)
7168 (skip-chars-forward " \t")
7169 (setq ind1 (current-column)))
7170 (if (< ind1 ind)
7171 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
7173 (goto-char pos)
7174 (error "Not in an item")))))
7176 (defun org-end-of-item ()
7177 "Go to the end of the current hand-formatted item.
7178 If the cursor is not in an item, throw an error."
7179 (interactive)
7180 (let* ((pos (point))
7181 ind1
7182 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7183 (limit (save-excursion (outline-next-heading) (point)))
7184 (ind (save-excursion
7185 (org-beginning-of-item)
7186 (skip-chars-forward " \t")
7187 (current-column)))
7188 (end (catch 'exit
7189 (while t
7190 (beginning-of-line 2)
7191 (if (eobp) (throw 'exit (point)))
7192 (if (>= (point) limit) (throw 'exit (point-at-bol)))
7193 (if (looking-at "[ \t]*$")
7194 (setq ind1 ind-empty)
7195 (skip-chars-forward " \t")
7196 (setq ind1 (current-column)))
7197 (if (<= ind1 ind)
7198 (throw 'exit (point-at-bol)))))))
7199 (if end
7200 (goto-char end)
7201 (goto-char pos)
7202 (error "Not in an item"))))
7204 (defun org-next-item ()
7205 "Move to the beginning of the next item in the current plain list.
7206 Error if not at a plain list, or if this is the last item in the list."
7207 (interactive)
7208 (let (ind ind1 (pos (point)))
7209 (org-beginning-of-item)
7210 (setq ind (org-get-indentation))
7211 (org-end-of-item)
7212 (setq ind1 (org-get-indentation))
7213 (unless (and (org-at-item-p) (= ind ind1))
7214 (goto-char pos)
7215 (error "On last item"))))
7217 (defun org-previous-item ()
7218 "Move to the beginning of the previous item in the current plain list.
7219 Error if not at a plain list, or if this is the first item in the list."
7220 (interactive)
7221 (let (beg ind ind1 (pos (point)))
7222 (org-beginning-of-item)
7223 (setq beg (point))
7224 (setq ind (org-get-indentation))
7225 (goto-char beg)
7226 (catch 'exit
7227 (while t
7228 (beginning-of-line 0)
7229 (if (looking-at "[ \t]*$")
7231 (if (<= (setq ind1 (org-get-indentation)) ind)
7232 (throw 'exit t)))))
7233 (condition-case nil
7234 (if (or (not (org-at-item-p))
7235 (< ind1 (1- ind)))
7236 (error "")
7237 (org-beginning-of-item))
7238 (error (goto-char pos)
7239 (error "On first item")))))
7241 (defun org-first-list-item-p ()
7242 "Is this heading the item in a plain list?"
7243 (unless (org-at-item-p)
7244 (error "Not at a plain list item"))
7245 (org-beginning-of-item)
7246 (= (point) (save-excursion (org-beginning-of-item-list))))
7248 (defun org-move-item-down ()
7249 "Move the plain list item at point down, i.e. swap with following item.
7250 Subitems (items with larger indentation) are considered part of the item,
7251 so this really moves item trees."
7252 (interactive)
7253 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
7254 (org-beginning-of-item)
7255 (setq beg0 (point))
7256 (save-excursion
7257 (setq ne-beg (org-back-over-empty-lines))
7258 (setq beg (point)))
7259 (goto-char beg0)
7260 (setq ind (org-get-indentation))
7261 (org-end-of-item)
7262 (setq end0 (point))
7263 (setq ind1 (org-get-indentation))
7264 (setq ne-end (org-back-over-empty-lines))
7265 (setq end (point))
7266 (goto-char beg0)
7267 (when (and (org-first-list-item-p) (< ne-end ne-beg))
7268 ;; include less whitespace
7269 (save-excursion
7270 (goto-char beg)
7271 (forward-line (- ne-beg ne-end))
7272 (setq beg (point))))
7273 (goto-char end0)
7274 (if (and (org-at-item-p) (= ind ind1))
7275 (progn
7276 (org-end-of-item)
7277 (org-back-over-empty-lines)
7278 (setq txt (buffer-substring beg end))
7279 (save-excursion
7280 (delete-region beg end))
7281 (setq pos (point))
7282 (insert txt)
7283 (goto-char pos) (org-skip-whitespace)
7284 (org-maybe-renumber-ordered-list))
7285 (goto-char pos)
7286 (error "Cannot move this item further down"))))
7288 (defun org-move-item-up (arg)
7289 "Move the plain list item at point up, i.e. swap with previous item.
7290 Subitems (items with larger indentation) are considered part of the item,
7291 so this really moves item trees."
7292 (interactive "p")
7293 (let (beg beg0 end end0 ind ind1 (pos (point)) txt
7294 ne-beg ne-end ne-ins ins-end)
7295 (org-beginning-of-item)
7296 (setq beg0 (point))
7297 (setq ind (org-get-indentation))
7298 (save-excursion
7299 (setq ne-beg (org-back-over-empty-lines))
7300 (setq beg (point)))
7301 (goto-char beg0)
7302 (org-end-of-item)
7303 (setq ne-end (org-back-over-empty-lines))
7304 (setq end (point))
7305 (goto-char beg0)
7306 (catch 'exit
7307 (while t
7308 (beginning-of-line 0)
7309 (if (looking-at "[ \t]*$")
7310 (if org-empty-line-terminates-plain-lists
7311 (progn
7312 (goto-char pos)
7313 (error "Cannot move this item further up"))
7314 nil)
7315 (if (<= (setq ind1 (org-get-indentation)) ind)
7316 (throw 'exit t)))))
7317 (condition-case nil
7318 (org-beginning-of-item)
7319 (error (goto-char beg)
7320 (error "Cannot move this item further up")))
7321 (setq ind1 (org-get-indentation))
7322 (if (and (org-at-item-p) (= ind ind1))
7323 (progn
7324 (setq ne-ins (org-back-over-empty-lines))
7325 (setq txt (buffer-substring beg end))
7326 (save-excursion
7327 (delete-region beg end))
7328 (setq pos (point))
7329 (insert txt)
7330 (setq ins-end (point))
7331 (goto-char pos) (org-skip-whitespace)
7333 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
7334 ;; Move whitespace back to beginning
7335 (save-excursion
7336 (goto-char ins-end)
7337 (let ((kill-whole-line t))
7338 (kill-line (- ne-ins ne-beg)) (point)))
7339 (insert (make-string (- ne-ins ne-beg) ?\n)))
7341 (org-maybe-renumber-ordered-list))
7342 (goto-char pos)
7343 (error "Cannot move this item further up"))))
7345 (defun org-maybe-renumber-ordered-list ()
7346 "Renumber the ordered list at point if setup allows it.
7347 This tests the user option `org-auto-renumber-ordered-lists' before
7348 doing the renumbering."
7349 (interactive)
7350 (when (and org-auto-renumber-ordered-lists
7351 (org-at-item-p))
7352 (if (match-beginning 3)
7353 (org-renumber-ordered-list 1)
7354 (org-fix-bullet-type))))
7356 (defun org-maybe-renumber-ordered-list-safe ()
7357 (condition-case nil
7358 (save-excursion
7359 (org-maybe-renumber-ordered-list))
7360 (error nil)))
7362 (defun org-cycle-list-bullet (&optional which)
7363 "Cycle through the different itemize/enumerate bullets.
7364 This cycle the entire list level through the sequence:
7366 `-' -> `+' -> `*' -> `1.' -> `1)'
7368 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7369 0 meand `-', 1 means `+' etc."
7370 (interactive "P")
7371 (org-preserve-lc
7372 (org-beginning-of-item-list)
7373 (org-at-item-p)
7374 (beginning-of-line 1)
7375 (let ((current (match-string 0))
7376 (prevp (eq which 'previous))
7377 new)
7378 (setq new (cond
7379 ((and (numberp which)
7380 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7381 ((string-match "-" current) (if prevp "1)" "+"))
7382 ((string-match "\\+" current)
7383 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7384 ((string-match "\\*" current) (if prevp "+" "1."))
7385 ((string-match "\\." current) (if prevp "*" "1)"))
7386 ((string-match ")" current) (if prevp "1." "-"))
7387 (t (error "This should not happen"))))
7388 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7389 (org-fix-bullet-type)
7390 (org-maybe-renumber-ordered-list))))
7392 (defun org-get-string-indentation (s)
7393 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7394 (let ((n -1) (i 0) (w tab-width) c)
7395 (catch 'exit
7396 (while (< (setq n (1+ n)) (length s))
7397 (setq c (aref s n))
7398 (cond ((= c ?\ ) (setq i (1+ i)))
7399 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7400 (t (throw 'exit t)))))
7403 (defun org-renumber-ordered-list (arg)
7404 "Renumber an ordered plain list.
7405 Cursor needs to be in the first line of an item, the line that starts
7406 with something like \"1.\" or \"2)\"."
7407 (interactive "p")
7408 (unless (and (org-at-item-p)
7409 (match-beginning 3))
7410 (error "This is not an ordered list"))
7411 (let ((line (org-current-line))
7412 (col (current-column))
7413 (ind (org-get-string-indentation
7414 (buffer-substring (point-at-bol) (match-beginning 3))))
7415 ;; (term (substring (match-string 3) -1))
7416 ind1 (n (1- arg))
7417 fmt)
7418 ;; find where this list begins
7419 (org-beginning-of-item-list)
7420 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7421 (setq fmt (concat "%d" (match-string 1)))
7422 (beginning-of-line 0)
7423 ;; walk forward and replace these numbers
7424 (catch 'exit
7425 (while t
7426 (catch 'next
7427 (beginning-of-line 2)
7428 (if (eobp) (throw 'exit nil))
7429 (if (looking-at "[ \t]*$") (throw 'next nil))
7430 (skip-chars-forward " \t") (setq ind1 (current-column))
7431 (if (> ind1 ind) (throw 'next t))
7432 (if (< ind1 ind) (throw 'exit t))
7433 (if (not (org-at-item-p)) (throw 'exit nil))
7434 (delete-region (match-beginning 2) (match-end 2))
7435 (goto-char (match-beginning 2))
7436 (insert (format fmt (setq n (1+ n)))))))
7437 (goto-line line)
7438 (move-to-column col)))
7440 (defun org-fix-bullet-type ()
7441 "Make sure all items in this list have the same bullet as the firsst item."
7442 (interactive)
7443 (unless (org-at-item-p) (error "This is not a list"))
7444 (let ((line (org-current-line))
7445 (col (current-column))
7446 (ind (current-indentation))
7447 ind1 bullet)
7448 ;; find where this list begins
7449 (org-beginning-of-item-list)
7450 (beginning-of-line 1)
7451 ;; find out what the bullet type is
7452 (looking-at "[ \t]*\\(\\S-+\\)")
7453 (setq bullet (match-string 1))
7454 ;; walk forward and replace these numbers
7455 (beginning-of-line 0)
7456 (catch 'exit
7457 (while t
7458 (catch 'next
7459 (beginning-of-line 2)
7460 (if (eobp) (throw 'exit nil))
7461 (if (looking-at "[ \t]*$") (throw 'next nil))
7462 (skip-chars-forward " \t") (setq ind1 (current-column))
7463 (if (> ind1 ind) (throw 'next t))
7464 (if (< ind1 ind) (throw 'exit t))
7465 (if (not (org-at-item-p)) (throw 'exit nil))
7466 (skip-chars-forward " \t")
7467 (looking-at "\\S-+")
7468 (replace-match bullet))))
7469 (goto-line line)
7470 (move-to-column col)
7471 (if (string-match "[0-9]" bullet)
7472 (org-renumber-ordered-list 1))))
7474 (defun org-beginning-of-item-list ()
7475 "Go to the beginning of the current item list.
7476 I.e. to the first item in this list."
7477 (interactive)
7478 (org-beginning-of-item)
7479 (let ((pos (point-at-bol))
7480 (ind (org-get-indentation))
7481 ind1)
7482 ;; find where this list begins
7483 (catch 'exit
7484 (while t
7485 (catch 'next
7486 (beginning-of-line 0)
7487 (if (looking-at "[ \t]*$")
7488 (throw (if (bobp) 'exit 'next) t))
7489 (skip-chars-forward " \t") (setq ind1 (current-column))
7490 (if (or (< ind1 ind)
7491 (and (= ind1 ind)
7492 (not (org-at-item-p)))
7493 (bobp))
7494 (throw 'exit t)
7495 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7496 (goto-char pos)))
7499 (defun org-end-of-item-list ()
7500 "Go to the end of the current item list.
7501 I.e. to the text after the last item."
7502 (interactive)
7503 (org-beginning-of-item)
7504 (let ((pos (point-at-bol))
7505 (ind (org-get-indentation))
7506 ind1)
7507 ;; find where this list begins
7508 (catch 'exit
7509 (while t
7510 (catch 'next
7511 (beginning-of-line 2)
7512 (if (looking-at "[ \t]*$")
7513 (throw (if (eobp) 'exit 'next) t))
7514 (skip-chars-forward " \t") (setq ind1 (current-column))
7515 (if (or (< ind1 ind)
7516 (and (= ind1 ind)
7517 (not (org-at-item-p)))
7518 (eobp))
7519 (progn
7520 (setq pos (point-at-bol))
7521 (throw 'exit t))))))
7522 (goto-char pos)))
7525 (defvar org-last-indent-begin-marker (make-marker))
7526 (defvar org-last-indent-end-marker (make-marker))
7528 (defun org-outdent-item (arg)
7529 "Outdent a local list item."
7530 (interactive "p")
7531 (org-indent-item (- arg)))
7533 (defun org-indent-item (arg)
7534 "Indent a local list item."
7535 (interactive "p")
7536 (unless (org-at-item-p)
7537 (error "Not on an item"))
7538 (save-excursion
7539 (let (beg end ind ind1 tmp delta ind-down ind-up)
7540 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7541 (setq beg org-last-indent-begin-marker
7542 end org-last-indent-end-marker)
7543 (org-beginning-of-item)
7544 (setq beg (move-marker org-last-indent-begin-marker (point)))
7545 (org-end-of-item)
7546 (setq end (move-marker org-last-indent-end-marker (point))))
7547 (goto-char beg)
7548 (setq tmp (org-item-indent-positions)
7549 ind (car tmp)
7550 ind-down (nth 2 tmp)
7551 ind-up (nth 1 tmp)
7552 delta (if (> arg 0)
7553 (if ind-down (- ind-down ind) 2)
7554 (if ind-up (- ind-up ind) -2)))
7555 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7556 (while (< (point) end)
7557 (beginning-of-line 1)
7558 (skip-chars-forward " \t") (setq ind1 (current-column))
7559 (delete-region (point-at-bol) (point))
7560 (or (eolp) (indent-to-column (+ ind1 delta)))
7561 (beginning-of-line 2))))
7562 (org-fix-bullet-type)
7563 (org-maybe-renumber-ordered-list-safe)
7564 (save-excursion
7565 (beginning-of-line 0)
7566 (condition-case nil (org-beginning-of-item) (error nil))
7567 (org-maybe-renumber-ordered-list-safe)))
7569 (defun org-item-indent-positions ()
7570 "Return indentation for plain list items.
7571 This returns a list with three values: The current indentation, the
7572 parent indentation and the indentation a child should habe.
7573 Assumes cursor in item line."
7574 (let* ((bolpos (point-at-bol))
7575 (ind (org-get-indentation))
7576 ind-down ind-up pos)
7577 (save-excursion
7578 (org-beginning-of-item-list)
7579 (skip-chars-backward "\n\r \t")
7580 (when (org-in-item-p)
7581 (org-beginning-of-item)
7582 (setq ind-up (org-get-indentation))))
7583 (setq pos (point))
7584 (save-excursion
7585 (cond
7586 ((and (condition-case nil (progn (org-previous-item) t)
7587 (error nil))
7588 (or (forward-char 1) t)
7589 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7590 (setq ind-down (org-get-indentation)))
7591 ((and (goto-char pos)
7592 (org-at-item-p))
7593 (goto-char (match-end 0))
7594 (skip-chars-forward " \t")
7595 (setq ind-down (current-column)))))
7596 (list ind ind-up ind-down)))
7598 ;;; The orgstruct minor mode
7600 ;; Define a minor mode which can be used in other modes in order to
7601 ;; integrate the org-mode structure editing commands.
7603 ;; This is really a hack, because the org-mode structure commands use
7604 ;; keys which normally belong to the major mode. Here is how it
7605 ;; works: The minor mode defines all the keys necessary to operate the
7606 ;; structure commands, but wraps the commands into a function which
7607 ;; tests if the cursor is currently at a headline or a plain list
7608 ;; item. If that is the case, the structure command is used,
7609 ;; temporarily setting many Org-mode variables like regular
7610 ;; expressions for filling etc. However, when any of those keys is
7611 ;; used at a different location, function uses `key-binding' to look
7612 ;; up if the key has an associated command in another currently active
7613 ;; keymap (minor modes, major mode, global), and executes that
7614 ;; command. There might be problems if any of the keys is otherwise
7615 ;; used as a prefix key.
7617 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7618 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7619 ;; addresses this by checking explicitly for both bindings.
7621 (defvar orgstruct-mode-map (make-sparse-keymap)
7622 "Keymap for the minor `orgstruct-mode'.")
7624 (defvar org-local-vars nil
7625 "List of local variables, for use by `orgstruct-mode'")
7627 ;;;###autoload
7628 (define-minor-mode orgstruct-mode
7629 "Toggle the minor more `orgstruct-mode'.
7630 This mode is for using Org-mode structure commands in other modes.
7631 The following key behave as if Org-mode was active, if the cursor
7632 is on a headline, or on a plain list item (both in the definition
7633 of Org-mode).
7635 M-up Move entry/item up
7636 M-down Move entry/item down
7637 M-left Promote
7638 M-right Demote
7639 M-S-up Move entry/item up
7640 M-S-down Move entry/item down
7641 M-S-left Promote subtree
7642 M-S-right Demote subtree
7643 M-q Fill paragraph and items like in Org-mode
7644 C-c ^ Sort entries
7645 C-c - Cycle list bullet
7646 TAB Cycle item visibility
7647 M-RET Insert new heading/item
7648 S-M-RET Insert new TODO heading / Chekbox item
7649 C-c C-c Set tags / toggle checkbox"
7650 nil " OrgStruct" nil
7651 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7653 ;;;###autoload
7654 (defun turn-on-orgstruct ()
7655 "Unconditionally turn on `orgstruct-mode'."
7656 (orgstruct-mode 1))
7658 ;;;###autoload
7659 (defun turn-on-orgstruct++ ()
7660 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7661 In addition to setting orgstruct-mode, this also exports all indentation and
7662 autofilling variables from org-mode into the buffer. Note that turning
7663 off orgstruct-mode will *not* remove these additional settings."
7664 (orgstruct-mode 1)
7665 (let (var val)
7666 (mapc
7667 (lambda (x)
7668 (when (string-match
7669 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7670 (symbol-name (car x)))
7671 (setq var (car x) val (nth 1 x))
7672 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7673 org-local-vars)))
7675 (defun orgstruct-error ()
7676 "Error when there is no default binding for a structure key."
7677 (interactive)
7678 (error "This key has no function outside structure elements"))
7680 (defun orgstruct-setup ()
7681 "Setup orgstruct keymaps."
7682 (let ((nfunc 0)
7683 (bindings
7684 (list
7685 '([(meta up)] org-metaup)
7686 '([(meta down)] org-metadown)
7687 '([(meta left)] org-metaleft)
7688 '([(meta right)] org-metaright)
7689 '([(meta shift up)] org-shiftmetaup)
7690 '([(meta shift down)] org-shiftmetadown)
7691 '([(meta shift left)] org-shiftmetaleft)
7692 '([(meta shift right)] org-shiftmetaright)
7693 '([(shift up)] org-shiftup)
7694 '([(shift down)] org-shiftdown)
7695 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7696 '("\M-q" fill-paragraph)
7697 '("\C-c^" org-sort)
7698 '("\C-c-" org-cycle-list-bullet)))
7699 elt key fun cmd)
7700 (while (setq elt (pop bindings))
7701 (setq nfunc (1+ nfunc))
7702 (setq key (org-key (car elt))
7703 fun (nth 1 elt)
7704 cmd (orgstruct-make-binding fun nfunc key))
7705 (org-defkey orgstruct-mode-map key cmd))
7707 ;; Special treatment needed for TAB and RET
7708 (org-defkey orgstruct-mode-map [(tab)]
7709 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7710 (org-defkey orgstruct-mode-map "\C-i"
7711 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7713 (org-defkey orgstruct-mode-map "\M-\C-m"
7714 (orgstruct-make-binding 'org-insert-heading 105
7715 "\M-\C-m" [(meta return)]))
7716 (org-defkey orgstruct-mode-map [(meta return)]
7717 (orgstruct-make-binding 'org-insert-heading 106
7718 [(meta return)] "\M-\C-m"))
7720 (org-defkey orgstruct-mode-map [(shift meta return)]
7721 (orgstruct-make-binding 'org-insert-todo-heading 107
7722 [(meta return)] "\M-\C-m"))
7724 (unless org-local-vars
7725 (setq org-local-vars (org-get-local-variables)))
7729 (defun orgstruct-make-binding (fun n &rest keys)
7730 "Create a function for binding in the structure minor mode.
7731 FUN is the command to call inside a table. N is used to create a unique
7732 command name. KEYS are keys that should be checked in for a command
7733 to execute outside of tables."
7734 (eval
7735 (list 'defun
7736 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7737 '(arg)
7738 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7739 "Outside of structure, run the binding of `"
7740 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7741 "'.")
7742 '(interactive "p")
7743 (list 'if
7744 '(org-context-p 'headline 'item)
7745 (list 'org-run-like-in-org-mode (list 'quote fun))
7746 (list 'let '(orgstruct-mode)
7747 (list 'call-interactively
7748 (append '(or)
7749 (mapcar (lambda (k)
7750 (list 'key-binding k))
7751 keys)
7752 '('orgstruct-error))))))))
7754 (defun org-context-p (&rest contexts)
7755 "Check if local context is and of CONTEXTS.
7756 Possible values in the list of contexts are `table', `headline', and `item'."
7757 (let ((pos (point)))
7758 (goto-char (point-at-bol))
7759 (prog1 (or (and (memq 'table contexts)
7760 (looking-at "[ \t]*|"))
7761 (and (memq 'headline contexts)
7762 (looking-at "\\*+"))
7763 (and (memq 'item contexts)
7764 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
7765 (goto-char pos))))
7767 (defun org-get-local-variables ()
7768 "Return a list of all local variables in an org-mode buffer."
7769 (let (varlist)
7770 (with-current-buffer (get-buffer-create "*Org tmp*")
7771 (erase-buffer)
7772 (org-mode)
7773 (setq varlist (buffer-local-variables)))
7774 (kill-buffer "*Org tmp*")
7775 (delq nil
7776 (mapcar
7777 (lambda (x)
7778 (setq x
7779 (if (symbolp x)
7780 (list x)
7781 (list (car x) (list 'quote (cdr x)))))
7782 (if (string-match
7783 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7784 (symbol-name (car x)))
7785 x nil))
7786 varlist))))
7788 ;;;###autoload
7789 (defun org-run-like-in-org-mode (cmd)
7790 (unless org-local-vars
7791 (setq org-local-vars (org-get-local-variables)))
7792 (eval (list 'let org-local-vars
7793 (list 'call-interactively (list 'quote cmd)))))
7795 ;;;; Archiving
7797 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
7799 (defun org-archive-subtree (&optional find-done)
7800 "Move the current subtree to the archive.
7801 The archive can be a certain top-level heading in the current file, or in
7802 a different file. The tree will be moved to that location, the subtree
7803 heading be marked DONE, and the current time will be added.
7805 When called with prefix argument FIND-DONE, find whole trees without any
7806 open TODO items and archive them (after getting confirmation from the user).
7807 If the cursor is not at a headline when this comand is called, try all level
7808 1 trees. If the cursor is on a headline, only try the direct children of
7809 this heading."
7810 (interactive "P")
7811 (if find-done
7812 (org-archive-all-done)
7813 ;; Save all relevant TODO keyword-relatex variables
7815 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
7816 (tr-org-todo-keywords-1 org-todo-keywords-1)
7817 (tr-org-todo-kwd-alist org-todo-kwd-alist)
7818 (tr-org-done-keywords org-done-keywords)
7819 (tr-org-todo-regexp org-todo-regexp)
7820 (tr-org-todo-line-regexp org-todo-line-regexp)
7821 (tr-org-odd-levels-only org-odd-levels-only)
7822 (this-buffer (current-buffer))
7823 (org-archive-location org-archive-location)
7824 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
7825 ;; start of variables that will be used for saving context
7826 ;; The compiler complains about them - keep them anyway!
7827 (file (abbreviate-file-name (buffer-file-name)))
7828 (olpath (mapconcat 'identity (org-get-outline-path) "/"))
7829 (time (format-time-string
7830 (substring (cdr org-time-stamp-formats) 1 -1)
7831 (current-time)))
7832 afile heading buffer level newfile-p
7833 category todo priority
7834 ;; start of variables that will be used for savind context
7835 ltags itags prop)
7837 ;; Try to find a local archive location
7838 (save-excursion
7839 (save-restriction
7840 (widen)
7841 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
7842 (if (and prop (string-match "\\S-" prop))
7843 (setq org-archive-location prop)
7844 (if (or (re-search-backward re nil t)
7845 (re-search-forward re nil t))
7846 (setq org-archive-location (match-string 1))))))
7848 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
7849 (progn
7850 (setq afile (format (match-string 1 org-archive-location)
7851 (file-name-nondirectory buffer-file-name))
7852 heading (match-string 2 org-archive-location)))
7853 (error "Invalid `org-archive-location'"))
7854 (if (> (length afile) 0)
7855 (setq newfile-p (not (file-exists-p afile))
7856 buffer (find-file-noselect afile))
7857 (setq buffer (current-buffer)))
7858 (unless buffer
7859 (error "Cannot access file \"%s\"" afile))
7860 (if (and (> (length heading) 0)
7861 (string-match "^\\*+" heading))
7862 (setq level (match-end 0))
7863 (setq heading nil level 0))
7864 (save-excursion
7865 (org-back-to-heading t)
7866 ;; Get context information that will be lost by moving the tree
7867 (org-refresh-category-properties)
7868 (setq category (org-get-category)
7869 todo (and (looking-at org-todo-line-regexp)
7870 (match-string 2))
7871 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
7872 ltags (org-get-tags)
7873 itags (org-delete-all ltags (org-get-tags-at)))
7874 (setq ltags (mapconcat 'identity ltags " ")
7875 itags (mapconcat 'identity itags " "))
7876 ;; We first only copy, in case something goes wrong
7877 ;; we need to protect this-command, to avoid kill-region sets it,
7878 ;; which would lead to duplication of subtrees
7879 (let (this-command) (org-copy-subtree))
7880 (set-buffer buffer)
7881 ;; Enforce org-mode for the archive buffer
7882 (if (not (org-mode-p))
7883 ;; Force the mode for future visits.
7884 (let ((org-insert-mode-line-in-empty-file t)
7885 (org-inhibit-startup t))
7886 (call-interactively 'org-mode)))
7887 (when newfile-p
7888 (goto-char (point-max))
7889 (insert (format "\nArchived entries from file %s\n\n"
7890 (buffer-file-name this-buffer))))
7891 ;; Force the TODO keywords of the original buffer
7892 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
7893 (org-todo-keywords-1 tr-org-todo-keywords-1)
7894 (org-todo-kwd-alist tr-org-todo-kwd-alist)
7895 (org-done-keywords tr-org-done-keywords)
7896 (org-todo-regexp tr-org-todo-regexp)
7897 (org-todo-line-regexp tr-org-todo-line-regexp)
7898 (org-odd-levels-only
7899 (if (local-variable-p 'org-odd-levels-only (current-buffer))
7900 org-odd-levels-only
7901 tr-org-odd-levels-only)))
7902 (goto-char (point-min))
7903 (if heading
7904 (progn
7905 (if (re-search-forward
7906 (concat "^" (regexp-quote heading)
7907 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
7908 nil t)
7909 (goto-char (match-end 0))
7910 ;; Heading not found, just insert it at the end
7911 (goto-char (point-max))
7912 (or (bolp) (insert "\n"))
7913 (insert "\n" heading "\n")
7914 (end-of-line 0))
7915 ;; Make the subtree visible
7916 (show-subtree)
7917 (org-end-of-subtree t)
7918 (skip-chars-backward " \t\r\n")
7919 (and (looking-at "[ \t\r\n]*")
7920 (replace-match "\n\n")))
7921 ;; No specific heading, just go to end of file.
7922 (goto-char (point-max)) (insert "\n"))
7923 ;; Paste
7924 (org-paste-subtree (org-get-legal-level level 1))
7926 ;; Mark the entry as done
7927 (when (and org-archive-mark-done
7928 (looking-at org-todo-line-regexp)
7929 (or (not (match-end 2))
7930 (not (member (match-string 2) org-done-keywords))))
7931 (let (org-log-done)
7932 (org-todo
7933 (car (or (member org-archive-mark-done org-done-keywords)
7934 org-done-keywords)))))
7936 ;; Add the context info
7937 (when org-archive-save-context-info
7938 (let ((l org-archive-save-context-info) e n v)
7939 (while (setq e (pop l))
7940 (when (and (setq v (symbol-value e))
7941 (stringp v) (string-match "\\S-" v))
7942 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
7943 (org-entry-put (point) n v)))))
7945 ;; Save the buffer, if it is not the same buffer.
7946 (if (not (eq this-buffer buffer)) (save-buffer))))
7947 ;; Here we are back in the original buffer. Everything seems to have
7948 ;; worked. So now cut the tree and finish up.
7949 (let (this-command) (org-cut-subtree))
7950 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
7951 (message "Subtree archived %s"
7952 (if (eq this-buffer buffer)
7953 (concat "under heading: " heading)
7954 (concat "in file: " (abbreviate-file-name afile)))))))
7956 (defun org-refresh-category-properties ()
7957 "Refresh category text properties in teh buffer."
7958 (let ((def-cat (cond
7959 ((null org-category)
7960 (if buffer-file-name
7961 (file-name-sans-extension
7962 (file-name-nondirectory buffer-file-name))
7963 "???"))
7964 ((symbolp org-category) (symbol-name org-category))
7965 (t org-category)))
7966 beg end cat pos optionp)
7967 (org-unmodified
7968 (save-excursion
7969 (save-restriction
7970 (widen)
7971 (goto-char (point-min))
7972 (put-text-property (point) (point-max) 'org-category def-cat)
7973 (while (re-search-forward
7974 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7975 (setq pos (match-end 0)
7976 optionp (equal (char-after (match-beginning 0)) ?#)
7977 cat (org-trim (match-string 2)))
7978 (if optionp
7979 (setq beg (point-at-bol) end (point-max))
7980 (org-back-to-heading t)
7981 (setq beg (point) end (org-end-of-subtree t t)))
7982 (put-text-property beg end 'org-category cat)
7983 (goto-char pos)))))))
7985 (defun org-archive-all-done (&optional tag)
7986 "Archive sublevels of the current tree without open TODO items.
7987 If the cursor is not on a headline, try all level 1 trees. If
7988 it is on a headline, try all direct children.
7989 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
7990 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
7991 (rea (concat ".*:" org-archive-tag ":"))
7992 (begm (make-marker))
7993 (endm (make-marker))
7994 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
7995 "Move subtree to archive (no open TODO items)? "))
7996 beg end (cntarch 0))
7997 (if (org-on-heading-p)
7998 (progn
7999 (setq re1 (concat "^" (regexp-quote
8000 (make-string
8001 (1+ (- (match-end 0) (match-beginning 0) 1))
8002 ?*))
8003 " "))
8004 (move-marker begm (point))
8005 (move-marker endm (org-end-of-subtree t)))
8006 (setq re1 "^* ")
8007 (move-marker begm (point-min))
8008 (move-marker endm (point-max)))
8009 (save-excursion
8010 (goto-char begm)
8011 (while (re-search-forward re1 endm t)
8012 (setq beg (match-beginning 0)
8013 end (save-excursion (org-end-of-subtree t) (point)))
8014 (goto-char beg)
8015 (if (re-search-forward re end t)
8016 (goto-char end)
8017 (goto-char beg)
8018 (if (and (or (not tag) (not (looking-at rea)))
8019 (y-or-n-p question))
8020 (progn
8021 (if tag
8022 (org-toggle-tag org-archive-tag 'on)
8023 (org-archive-subtree))
8024 (setq cntarch (1+ cntarch)))
8025 (goto-char end)))))
8026 (message "%d trees archived" cntarch)))
8028 (defun org-cycle-hide-drawers (state)
8029 "Re-hide all drawers after a visibility state change."
8030 (when (and (org-mode-p)
8031 (not (memq state '(overview folded))))
8032 (save-excursion
8033 (let* ((globalp (memq state '(contents all)))
8034 (beg (if globalp (point-min) (point)))
8035 (end (if globalp (point-max) (org-end-of-subtree t))))
8036 (goto-char beg)
8037 (while (re-search-forward org-drawer-regexp end t)
8038 (org-flag-drawer t))))))
8040 (defun org-flag-drawer (flag)
8041 (save-excursion
8042 (beginning-of-line 1)
8043 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
8044 (let ((b (match-end 0))
8045 (outline-regexp org-outline-regexp))
8046 (if (re-search-forward
8047 "^[ \t]*:END:"
8048 (save-excursion (outline-next-heading) (point)) t)
8049 (outline-flag-region b (point-at-eol) flag)
8050 (error ":END: line missing"))))))
8052 (defun org-cycle-hide-archived-subtrees (state)
8053 "Re-hide all archived subtrees after a visibility state change."
8054 (when (and (not org-cycle-open-archived-trees)
8055 (not (memq state '(overview folded))))
8056 (save-excursion
8057 (let* ((globalp (memq state '(contents all)))
8058 (beg (if globalp (point-min) (point)))
8059 (end (if globalp (point-max) (org-end-of-subtree t))))
8060 (org-hide-archived-subtrees beg end)
8061 (goto-char beg)
8062 (if (looking-at (concat ".*:" org-archive-tag ":"))
8063 (message "%s" (substitute-command-keys
8064 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
8066 (defun org-force-cycle-archived ()
8067 "Cycle subtree even if it is archived."
8068 (interactive)
8069 (setq this-command 'org-cycle)
8070 (let ((org-cycle-open-archived-trees t))
8071 (call-interactively 'org-cycle)))
8073 (defun org-hide-archived-subtrees (beg end)
8074 "Re-hide all archived subtrees after a visibility state change."
8075 (save-excursion
8076 (let* ((re (concat ":" org-archive-tag ":")))
8077 (goto-char beg)
8078 (while (re-search-forward re end t)
8079 (and (org-on-heading-p) (hide-subtree))
8080 (org-end-of-subtree t)))))
8082 (defun org-toggle-tag (tag &optional onoff)
8083 "Toggle the tag TAG for the current line.
8084 If ONOFF is `on' or `off', don't toggle but set to this state."
8085 (unless (org-on-heading-p t) (error "Not on headling"))
8086 (let (res current)
8087 (save-excursion
8088 (beginning-of-line)
8089 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8090 (point-at-eol) t)
8091 (progn
8092 (setq current (match-string 1))
8093 (replace-match ""))
8094 (setq current ""))
8095 (setq current (nreverse (org-split-string current ":")))
8096 (cond
8097 ((eq onoff 'on)
8098 (setq res t)
8099 (or (member tag current) (push tag current)))
8100 ((eq onoff 'off)
8101 (or (not (member tag current)) (setq current (delete tag current))))
8102 (t (if (member tag current)
8103 (setq current (delete tag current))
8104 (setq res t)
8105 (push tag current))))
8106 (end-of-line 1)
8107 (if current
8108 (progn
8109 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8110 (org-set-tags nil t))
8111 (delete-horizontal-space))
8112 (run-hooks 'org-after-tags-change-hook))
8113 res))
8115 (defun org-toggle-archive-tag (&optional arg)
8116 "Toggle the archive tag for the current headline.
8117 With prefix ARG, check all children of current headline and offer tagging
8118 the children that do not contain any open TODO items."
8119 (interactive "P")
8120 (if arg
8121 (org-archive-all-done 'tag)
8122 (let (set)
8123 (save-excursion
8124 (org-back-to-heading t)
8125 (setq set (org-toggle-tag org-archive-tag))
8126 (when set (hide-subtree)))
8127 (and set (beginning-of-line 1))
8128 (message "Subtree %s" (if set "archived" "unarchived")))))
8131 ;;;; Tables
8133 ;;; The table editor
8135 ;; Watch out: Here we are talking about two different kind of tables.
8136 ;; Most of the code is for the tables created with the Org-mode table editor.
8137 ;; Sometimes, we talk about tables created and edited with the table.el
8138 ;; Emacs package. We call the former org-type tables, and the latter
8139 ;; table.el-type tables.
8141 (defun org-before-change-function (beg end)
8142 "Every change indicates that a table might need an update."
8143 (setq org-table-may-need-update t))
8145 (defconst org-table-line-regexp "^[ \t]*|"
8146 "Detects an org-type table line.")
8147 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8148 "Detects an org-type table line.")
8149 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8150 "Detects a table line marked for automatic recalculation.")
8151 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8152 "Detects a table line marked for automatic recalculation.")
8153 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8154 "Detects a table line marked for automatic recalculation.")
8155 (defconst org-table-hline-regexp "^[ \t]*|-"
8156 "Detects an org-type table hline.")
8157 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8158 "Detects a table-type table hline.")
8159 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8160 "Detects an org-type or table-type table.")
8161 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8162 "Searching from within a table (any type) this finds the first line
8163 outside the table.")
8164 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8165 "Searching from within a table (any type) this finds the first line
8166 outside the table.")
8168 (defvar org-table-last-highlighted-reference nil)
8169 (defvar org-table-formula-history nil)
8171 (defvar org-table-column-names nil
8172 "Alist with column names, derived from the `!' line.")
8173 (defvar org-table-column-name-regexp nil
8174 "Regular expression matching the current column names.")
8175 (defvar org-table-local-parameters nil
8176 "Alist with parameter names, derived from the `$' line.")
8177 (defvar org-table-named-field-locations nil
8178 "Alist with locations of named fields.")
8180 (defvar org-table-current-line-types nil
8181 "Table row types, non-nil only for the duration of a comand.")
8182 (defvar org-table-current-begin-line nil
8183 "Table begin line, non-nil only for the duration of a comand.")
8184 (defvar org-table-current-begin-pos nil
8185 "Table begin position, non-nil only for the duration of a comand.")
8186 (defvar org-table-dlines nil
8187 "Vector of data line line numbers in the current table.")
8188 (defvar org-table-hlines nil
8189 "Vector of hline line numbers in the current table.")
8191 (defconst org-table-range-regexp
8192 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
8193 ;; 1 2 3 4 5
8194 "Regular expression for matching ranges in formulas.")
8196 (defconst org-table-range-regexp2
8197 (concat
8198 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
8199 "\\.\\."
8200 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8201 "Match a range for reference display.")
8203 (defconst org-table-translate-regexp
8204 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8205 "Match a reference that needs translation, for reference display.")
8207 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8209 (defun org-table-create-with-table.el ()
8210 "Use the table.el package to insert a new table.
8211 If there is already a table at point, convert between Org-mode tables
8212 and table.el tables."
8213 (interactive)
8214 (require 'table)
8215 (cond
8216 ((org-at-table.el-p)
8217 (if (y-or-n-p "Convert table to Org-mode table? ")
8218 (org-table-convert)))
8219 ((org-at-table-p)
8220 (if (y-or-n-p "Convert table to table.el table? ")
8221 (org-table-convert)))
8222 (t (call-interactively 'table-insert))))
8224 (defun org-table-create-or-convert-from-region (arg)
8225 "Convert region to table, or create an empty table.
8226 If there is an active region, convert it to a table, using the function
8227 `org-table-convert-region'. See the documentation of that function
8228 to learn how the prefix argument is interpreted to determine the field
8229 separator.
8230 If there is no such region, create an empty table with `org-table-create'."
8231 (interactive "P")
8232 (if (org-region-active-p)
8233 (org-table-convert-region (region-beginning) (region-end) arg)
8234 (org-table-create arg)))
8236 (defun org-table-create (&optional size)
8237 "Query for a size and insert a table skeleton.
8238 SIZE is a string Columns x Rows like for example \"3x2\"."
8239 (interactive "P")
8240 (unless size
8241 (setq size (read-string
8242 (concat "Table size Columns x Rows [e.g. "
8243 org-table-default-size "]: ")
8244 "" nil org-table-default-size)))
8246 (let* ((pos (point))
8247 (indent (make-string (current-column) ?\ ))
8248 (split (org-split-string size " *x *"))
8249 (rows (string-to-number (nth 1 split)))
8250 (columns (string-to-number (car split)))
8251 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8252 "\n")))
8253 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8254 (point-at-bol) (point)))
8255 (beginning-of-line 1)
8256 (newline))
8257 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8258 (dotimes (i rows) (insert line))
8259 (goto-char pos)
8260 (if (> rows 1)
8261 ;; Insert a hline after the first row.
8262 (progn
8263 (end-of-line 1)
8264 (insert "\n|-")
8265 (goto-char pos)))
8266 (org-table-align)))
8268 (defun org-table-convert-region (beg0 end0 &optional separator)
8269 "Convert region to a table.
8270 The region goes from BEG0 to END0, but these borders will be moved
8271 slightly, to make sure a beginning of line in the first line is included.
8273 SEPARATOR specifies the field separator in the lines. It can have the
8274 following values:
8276 '(4) Use the comma as a field separator
8277 '(16) Use a TAB as field separator
8278 integer When a number, use that many spaces as field separator
8279 nil When nil, the command tries to be smart and figure out the
8280 separator in the following way:
8281 - when each line contains a TAB, assume TAB-separated material
8282 - when each line contains a comme, assume CSV material
8283 - else, assume one or more SPACE charcters as separator."
8284 (interactive "rP")
8285 (let* ((beg (min beg0 end0))
8286 (end (max beg0 end0))
8288 (goto-char beg)
8289 (beginning-of-line 1)
8290 (setq beg (move-marker (make-marker) (point)))
8291 (goto-char end)
8292 (if (bolp) (backward-char 1) (end-of-line 1))
8293 (setq end (move-marker (make-marker) (point)))
8294 ;; Get the right field separator
8295 (unless separator
8296 (goto-char beg)
8297 (setq separator
8298 (cond
8299 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8300 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8301 (t 1))))
8302 (setq re (cond
8303 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8304 ((equal separator '(16)) "^\\|\t")
8305 ((integerp separator)
8306 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8307 (t (error "This should not happen"))))
8308 (goto-char beg)
8309 (while (re-search-forward re end t)
8310 (replace-match "| " t t))
8311 (goto-char beg)
8312 (insert " ")
8313 (org-table-align)))
8315 (defun org-table-import (file arg)
8316 "Import FILE as a table.
8317 The file is assumed to be tab-separated. Such files can be produced by most
8318 spreadsheet and database applications. If no tabs (at least one per line)
8319 are found, lines will be split on whitespace into fields."
8320 (interactive "f\nP")
8321 (or (bolp) (newline))
8322 (let ((beg (point))
8323 (pm (point-max)))
8324 (insert-file-contents file)
8325 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8327 (defun org-table-export ()
8328 "Export table as a tab-separated file.
8329 Such a file can be imported into a spreadsheet program like Excel."
8330 (interactive)
8331 (let* ((beg (org-table-begin))
8332 (end (org-table-end))
8333 (table (buffer-substring beg end))
8334 (file (read-file-name "Export table to: "))
8335 buf)
8336 (unless (or (not (file-exists-p file))
8337 (y-or-n-p (format "Overwrite file %s? " file)))
8338 (error "Abort"))
8339 (with-current-buffer (find-file-noselect file)
8340 (setq buf (current-buffer))
8341 (erase-buffer)
8342 (fundamental-mode)
8343 (insert table)
8344 (goto-char (point-min))
8345 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8346 (replace-match "" t t)
8347 (end-of-line 1))
8348 (goto-char (point-min))
8349 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8350 (replace-match "" t t)
8351 (goto-char (min (1+ (point)) (point-max))))
8352 (goto-char (point-min))
8353 (while (re-search-forward "^-[-+]*$" nil t)
8354 (replace-match "")
8355 (if (looking-at "\n")
8356 (delete-char 1)))
8357 (goto-char (point-min))
8358 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8359 (replace-match "\t" t t))
8360 (save-buffer))
8361 (kill-buffer buf)))
8363 (defvar org-table-aligned-begin-marker (make-marker)
8364 "Marker at the beginning of the table last aligned.
8365 Used to check if cursor still is in that table, to minimize realignment.")
8366 (defvar org-table-aligned-end-marker (make-marker)
8367 "Marker at the end of the table last aligned.
8368 Used to check if cursor still is in that table, to minimize realignment.")
8369 (defvar org-table-last-alignment nil
8370 "List of flags for flushright alignment, from the last re-alignment.
8371 This is being used to correctly align a single field after TAB or RET.")
8372 (defvar org-table-last-column-widths nil
8373 "List of max width of fields in each column.
8374 This is being used to correctly align a single field after TAB or RET.")
8375 (defvar org-table-overlay-coordinates nil
8376 "Overlay coordinates after each align of a table.")
8377 (make-variable-buffer-local 'org-table-overlay-coordinates)
8379 (defvar org-last-recalc-line nil)
8380 (defconst org-narrow-column-arrow "=>"
8381 "Used as display property in narrowed table columns.")
8383 (defun org-table-align ()
8384 "Align the table at point by aligning all vertical bars."
8385 (interactive)
8386 (let* (
8387 ;; Limits of table
8388 (beg (org-table-begin))
8389 (end (org-table-end))
8390 ;; Current cursor position
8391 (linepos (org-current-line))
8392 (colpos (org-table-current-column))
8393 (winstart (window-start))
8394 (winstartline (org-current-line (min winstart (1- (point-max)))))
8395 lines (new "") lengths l typenums ty fields maxfields i
8396 column
8397 (indent "") cnt frac
8398 rfmt hfmt
8399 (spaces '(1 . 1))
8400 (sp1 (car spaces))
8401 (sp2 (cdr spaces))
8402 (rfmt1 (concat
8403 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8404 (hfmt1 (concat
8405 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8406 emptystrings links dates emph narrow fmax f1 len c e)
8407 (untabify beg end)
8408 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8409 ;; Check if we have links or dates
8410 (goto-char beg)
8411 (setq links (re-search-forward org-bracket-link-regexp end t))
8412 (goto-char beg)
8413 (setq emph (and org-hide-emphasis-markers
8414 (re-search-forward org-emph-re end t)))
8415 (goto-char beg)
8416 (setq dates (and org-display-custom-times
8417 (re-search-forward org-ts-regexp-both end t)))
8418 ;; Make sure the link properties are right
8419 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8420 ;; Make sure the date properties are right
8421 (when dates (goto-char beg) (while (org-activate-dates end)))
8422 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8424 ;; Check if we are narrowing any columns
8425 (goto-char beg)
8426 (setq narrow (and org-format-transports-properties-p
8427 (re-search-forward "<[0-9]+>" end t)))
8428 ;; Get the rows
8429 (setq lines (org-split-string
8430 (buffer-substring beg end) "\n"))
8431 ;; Store the indentation of the first line
8432 (if (string-match "^ *" (car lines))
8433 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8434 ;; Mark the hlines by setting the corresponding element to nil
8435 ;; At the same time, we remove trailing space.
8436 (setq lines (mapcar (lambda (l)
8437 (if (string-match "^ *|-" l)
8439 (if (string-match "[ \t]+$" l)
8440 (substring l 0 (match-beginning 0))
8441 l)))
8442 lines))
8443 ;; Get the data fields by splitting the lines.
8444 (setq fields (mapcar
8445 (lambda (l)
8446 (org-split-string l " *| *"))
8447 (delq nil (copy-sequence lines))))
8448 ;; How many fields in the longest line?
8449 (condition-case nil
8450 (setq maxfields (apply 'max (mapcar 'length fields)))
8451 (error
8452 (kill-region beg end)
8453 (org-table-create org-table-default-size)
8454 (error "Empty table - created default table")))
8455 ;; A list of empty strings to fill any short rows on output
8456 (setq emptystrings (make-list maxfields ""))
8457 ;; Check for special formatting.
8458 (setq i -1)
8459 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8460 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8461 ;; Check if there is an explicit width specified
8462 (when narrow
8463 (setq c column fmax nil)
8464 (while c
8465 (setq e (pop c))
8466 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8467 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8468 ;; Find fields that are wider than fmax, and shorten them
8469 (when fmax
8470 (loop for xx in column do
8471 (when (and (stringp xx)
8472 (> (org-string-width xx) fmax))
8473 (org-add-props xx nil
8474 'help-echo
8475 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8476 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8477 (unless (> f1 1)
8478 (error "Cannot narrow field starting with wide link \"%s\""
8479 (match-string 0 xx)))
8480 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8481 (add-text-properties (- f1 2) f1
8482 (list 'display org-narrow-column-arrow)
8483 xx)))))
8484 ;; Get the maximum width for each column
8485 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8486 ;; Get the fraction of numbers, to decide about alignment of the column
8487 (setq cnt 0 frac 0.0)
8488 (loop for x in column do
8489 (if (equal x "")
8491 (setq frac ( / (+ (* frac cnt)
8492 (if (string-match org-table-number-regexp x) 1 0))
8493 (setq cnt (1+ cnt))))))
8494 (push (>= frac org-table-number-fraction) typenums))
8495 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8497 ;; Store the alignment of this table, for later editing of single fields
8498 (setq org-table-last-alignment typenums
8499 org-table-last-column-widths lengths)
8501 ;; With invisible characters, `format' does not get the field width right
8502 ;; So we need to make these fields wide by hand.
8503 (when (or links emph)
8504 (loop for i from 0 upto (1- maxfields) do
8505 (setq len (nth i lengths))
8506 (loop for j from 0 upto (1- (length fields)) do
8507 (setq c (nthcdr i (car (nthcdr j fields))))
8508 (if (and (stringp (car c))
8509 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8510 ; (string-match org-bracket-link-regexp (car c))
8511 (< (org-string-width (car c)) len))
8512 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8514 ;; Compute the formats needed for output of the table
8515 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8516 (while (setq l (pop lengths))
8517 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8518 (setq rfmt (concat rfmt (format rfmt1 ty l))
8519 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8520 (setq rfmt (concat rfmt "\n")
8521 hfmt (concat (substring hfmt 0 -1) "|\n"))
8523 (setq new (mapconcat
8524 (lambda (l)
8525 (if l (apply 'format rfmt
8526 (append (pop fields) emptystrings))
8527 hfmt))
8528 lines ""))
8529 ;; Replace the old one
8530 (delete-region beg end)
8531 (move-marker end nil)
8532 (move-marker org-table-aligned-begin-marker (point))
8533 (insert new)
8534 (move-marker org-table-aligned-end-marker (point))
8535 (when (and orgtbl-mode (not (org-mode-p)))
8536 (goto-char org-table-aligned-begin-marker)
8537 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8538 ;; Try to move to the old location
8539 (goto-line winstartline)
8540 (setq winstart (point-at-bol))
8541 (goto-line linepos)
8542 (set-window-start (selected-window) winstart 'noforce)
8543 (org-table-goto-column colpos)
8544 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8545 (setq org-table-may-need-update nil)
8548 (defun org-string-width (s)
8549 "Compute width of string, ignoring invisible characters.
8550 This ignores character with invisibility property `org-link', and also
8551 characters with property `org-cwidth', because these will become invisible
8552 upon the next fontification round."
8553 (let (b l)
8554 (when (or (eq t buffer-invisibility-spec)
8555 (assq 'org-link buffer-invisibility-spec))
8556 (while (setq b (text-property-any 0 (length s)
8557 'invisible 'org-link s))
8558 (setq s (concat (substring s 0 b)
8559 (substring s (or (next-single-property-change
8560 b 'invisible s) (length s)))))))
8561 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8562 (setq s (concat (substring s 0 b)
8563 (substring s (or (next-single-property-change
8564 b 'org-cwidth s) (length s))))))
8565 (setq l (string-width s) b -1)
8566 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8567 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8570 (defun org-table-begin (&optional table-type)
8571 "Find the beginning of the table and return its position.
8572 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8573 (save-excursion
8574 (if (not (re-search-backward
8575 (if table-type org-table-any-border-regexp
8576 org-table-border-regexp)
8577 nil t))
8578 (progn (goto-char (point-min)) (point))
8579 (goto-char (match-beginning 0))
8580 (beginning-of-line 2)
8581 (point))))
8583 (defun org-table-end (&optional table-type)
8584 "Find the end of the table and return its position.
8585 With argument TABLE-TYPE, go to the end of a table.el-type table."
8586 (save-excursion
8587 (if (not (re-search-forward
8588 (if table-type org-table-any-border-regexp
8589 org-table-border-regexp)
8590 nil t))
8591 (goto-char (point-max))
8592 (goto-char (match-beginning 0)))
8593 (point-marker)))
8595 (defun org-table-justify-field-maybe (&optional new)
8596 "Justify the current field, text to left, number to right.
8597 Optional argument NEW may specify text to replace the current field content."
8598 (cond
8599 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8600 ((org-at-table-hline-p))
8601 ((and (not new)
8602 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8603 (current-buffer)))
8604 (< (point) org-table-aligned-begin-marker)
8605 (>= (point) org-table-aligned-end-marker)))
8606 ;; This is not the same table, force a full re-align
8607 (setq org-table-may-need-update t))
8608 (t ;; realign the current field, based on previous full realign
8609 (let* ((pos (point)) s
8610 (col (org-table-current-column))
8611 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8612 l f n o e)
8613 (when (> col 0)
8614 (skip-chars-backward "^|\n")
8615 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8616 (progn
8617 (setq s (match-string 1)
8618 o (match-string 0)
8619 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8620 e (not (= (match-beginning 2) (match-end 2))))
8621 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8622 l (if e "|" (setq org-table-may-need-update t) ""))
8623 n (format f s))
8624 (if new
8625 (if (<= (length new) l) ;; FIXME: length -> str-width?
8626 (setq n (format f new))
8627 (setq n (concat new "|") org-table-may-need-update t)))
8628 (or (equal n o)
8629 (let (org-table-may-need-update)
8630 (replace-match n t t))))
8631 (setq org-table-may-need-update t))
8632 (goto-char pos))))))
8634 (defun org-table-next-field ()
8635 "Go to the next field in the current table, creating new lines as needed.
8636 Before doing so, re-align the table if necessary."
8637 (interactive)
8638 (org-table-maybe-eval-formula)
8639 (org-table-maybe-recalculate-line)
8640 (if (and org-table-automatic-realign
8641 org-table-may-need-update)
8642 (org-table-align))
8643 (let ((end (org-table-end)))
8644 (if (org-at-table-hline-p)
8645 (end-of-line 1))
8646 (condition-case nil
8647 (progn
8648 (re-search-forward "|" end)
8649 (if (looking-at "[ \t]*$")
8650 (re-search-forward "|" end))
8651 (if (and (looking-at "-")
8652 org-table-tab-jumps-over-hlines
8653 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8654 (goto-char (match-beginning 1)))
8655 (if (looking-at "-")
8656 (progn
8657 (beginning-of-line 0)
8658 (org-table-insert-row 'below))
8659 (if (looking-at " ") (forward-char 1))))
8660 (error
8661 (org-table-insert-row 'below)))))
8663 (defun org-table-previous-field ()
8664 "Go to the previous field in the table.
8665 Before doing so, re-align the table if necessary."
8666 (interactive)
8667 (org-table-justify-field-maybe)
8668 (org-table-maybe-recalculate-line)
8669 (if (and org-table-automatic-realign
8670 org-table-may-need-update)
8671 (org-table-align))
8672 (if (org-at-table-hline-p)
8673 (end-of-line 1))
8674 (re-search-backward "|" (org-table-begin))
8675 (re-search-backward "|" (org-table-begin))
8676 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8677 (re-search-backward "|" (org-table-begin)))
8678 (if (looking-at "| ?")
8679 (goto-char (match-end 0))))
8681 (defun org-table-next-row ()
8682 "Go to the next row (same column) in the current table.
8683 Before doing so, re-align the table if necessary."
8684 (interactive)
8685 (org-table-maybe-eval-formula)
8686 (org-table-maybe-recalculate-line)
8687 (if (or (looking-at "[ \t]*$")
8688 (save-excursion (skip-chars-backward " \t") (bolp)))
8689 (newline)
8690 (if (and org-table-automatic-realign
8691 org-table-may-need-update)
8692 (org-table-align))
8693 (let ((col (org-table-current-column)))
8694 (beginning-of-line 2)
8695 (if (or (not (org-at-table-p))
8696 (org-at-table-hline-p))
8697 (progn
8698 (beginning-of-line 0)
8699 (org-table-insert-row 'below)))
8700 (org-table-goto-column col)
8701 (skip-chars-backward "^|\n\r")
8702 (if (looking-at " ") (forward-char 1)))))
8704 (defun org-table-copy-down (n)
8705 "Copy a field down in the current column.
8706 If the field at the cursor is empty, copy into it the content of the nearest
8707 non-empty field above. With argument N, use the Nth non-empty field.
8708 If the current field is not empty, it is copied down to the next row, and
8709 the cursor is moved with it. Therefore, repeating this command causes the
8710 column to be filled row-by-row.
8711 If the variable `org-table-copy-increment' is non-nil and the field is an
8712 integer or a timestamp, it will be incremented while copying. In the case of
8713 a timestamp, if the cursor is on the year, change the year. If it is on the
8714 month or the day, change that. Point will stay on the current date field
8715 in order to easily repeat the interval."
8716 (interactive "p")
8717 (let* ((colpos (org-table-current-column))
8718 (col (current-column))
8719 (field (org-table-get-field))
8720 (non-empty (string-match "[^ \t]" field))
8721 (beg (org-table-begin))
8722 txt)
8723 (org-table-check-inside-data-field)
8724 (if non-empty
8725 (progn
8726 (setq txt (org-trim field))
8727 (org-table-next-row)
8728 (org-table-blank-field))
8729 (save-excursion
8730 (setq txt
8731 (catch 'exit
8732 (while (progn (beginning-of-line 1)
8733 (re-search-backward org-table-dataline-regexp
8734 beg t))
8735 (org-table-goto-column colpos t)
8736 (if (and (looking-at
8737 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8738 (= (setq n (1- n)) 0))
8739 (throw 'exit (match-string 1))))))))
8740 (if txt
8741 (progn
8742 (if (and org-table-copy-increment
8743 (string-match "^[0-9]+$" txt))
8744 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8745 (insert txt)
8746 (move-to-column col)
8747 (if (and org-table-copy-increment (org-at-timestamp-p t))
8748 (org-timestamp-up 1)
8749 (org-table-maybe-recalculate-line))
8750 (org-table-align)
8751 (move-to-column col))
8752 (error "No non-empty field found"))))
8754 (defun org-table-check-inside-data-field ()
8755 "Is point inside a table data field?
8756 I.e. not on a hline or before the first or after the last column?
8757 This actually throws an error, so it aborts the current command."
8758 (if (or (not (org-at-table-p))
8759 (= (org-table-current-column) 0)
8760 (org-at-table-hline-p)
8761 (looking-at "[ \t]*$"))
8762 (error "Not in table data field")))
8764 (defvar org-table-clip nil
8765 "Clipboard for table regions.")
8767 (defun org-table-blank-field ()
8768 "Blank the current table field or active region."
8769 (interactive)
8770 (org-table-check-inside-data-field)
8771 (if (and (interactive-p) (org-region-active-p))
8772 (let (org-table-clip)
8773 (org-table-cut-region (region-beginning) (region-end)))
8774 (skip-chars-backward "^|")
8775 (backward-char 1)
8776 (if (looking-at "|[^|\n]+")
8777 (let* ((pos (match-beginning 0))
8778 (match (match-string 0))
8779 (len (org-string-width match)))
8780 (replace-match (concat "|" (make-string (1- len) ?\ )))
8781 (goto-char (+ 2 pos))
8782 (substring match 1)))))
8784 (defun org-table-get-field (&optional n replace)
8785 "Return the value of the field in column N of current row.
8786 N defaults to current field.
8787 If REPLACE is a string, replace field with this value. The return value
8788 is always the old value."
8789 (and n (org-table-goto-column n))
8790 (skip-chars-backward "^|\n")
8791 (backward-char 1)
8792 (if (looking-at "|[^|\r\n]*")
8793 (let* ((pos (match-beginning 0))
8794 (val (buffer-substring (1+ pos) (match-end 0))))
8795 (if replace
8796 (replace-match (concat "|" replace) t t))
8797 (goto-char (min (point-at-eol) (+ 2 pos)))
8798 val)
8799 (forward-char 1) ""))
8801 (defun org-table-field-info (arg)
8802 "Show info about the current field, and highlight any reference at point."
8803 (interactive "P")
8804 (org-table-get-specials)
8805 (save-excursion
8806 (let* ((pos (point))
8807 (col (org-table-current-column))
8808 (cname (car (rassoc (int-to-string col) org-table-column-names)))
8809 (name (car (rassoc (list (org-current-line) col)
8810 org-table-named-field-locations)))
8811 (eql (org-table-get-stored-formulas))
8812 (dline (org-table-current-dline))
8813 (ref (format "@%d$%d" dline col))
8814 (ref1 (org-table-convert-refs-to-an ref))
8815 (fequation (or (assoc name eql) (assoc ref eql)))
8816 (cequation (assoc (int-to-string col) eql))
8817 (eqn (or fequation cequation)))
8818 (goto-char pos)
8819 (condition-case nil
8820 (org-table-show-reference 'local)
8821 (error nil))
8822 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
8823 dline col
8824 (if cname (concat " or $" cname) "")
8825 dline col ref1
8826 (if name (concat " or $" name) "")
8827 ;; FIXME: formula info not correct if special table line
8828 (if eqn
8829 (concat ", formula: "
8830 (org-table-formula-to-user
8831 (concat
8832 (if (string-match "^[$@]"(car eqn)) "" "$")
8833 (car eqn) "=" (cdr eqn))))
8834 "")))))
8836 (defun org-table-current-column ()
8837 "Find out which column we are in.
8838 When called interactively, column is also displayed in echo area."
8839 (interactive)
8840 (if (interactive-p) (org-table-check-inside-data-field))
8841 (save-excursion
8842 (let ((cnt 0) (pos (point)))
8843 (beginning-of-line 1)
8844 (while (search-forward "|" pos t)
8845 (setq cnt (1+ cnt)))
8846 (if (interactive-p) (message "This is table column %d" cnt))
8847 cnt)))
8849 (defun org-table-current-dline ()
8850 "Find out what table data line we are in.
8851 Only datalins count for this."
8852 (interactive)
8853 (if (interactive-p) (org-table-check-inside-data-field))
8854 (save-excursion
8855 (let ((cnt 0) (pos (point)))
8856 (goto-char (org-table-begin))
8857 (while (<= (point) pos)
8858 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
8859 (beginning-of-line 2))
8860 (if (interactive-p) (message "This is table line %d" cnt))
8861 cnt)))
8863 (defun org-table-goto-column (n &optional on-delim force)
8864 "Move the cursor to the Nth column in the current table line.
8865 With optional argument ON-DELIM, stop with point before the left delimiter
8866 of the field.
8867 If there are less than N fields, just go to after the last delimiter.
8868 However, when FORCE is non-nil, create new columns if necessary."
8869 (interactive "p")
8870 (let ((pos (point-at-eol)))
8871 (beginning-of-line 1)
8872 (when (> n 0)
8873 (while (and (> (setq n (1- n)) -1)
8874 (or (search-forward "|" pos t)
8875 (and force
8876 (progn (end-of-line 1)
8877 (skip-chars-backward "^|")
8878 (insert " | "))))))
8879 ; (backward-char 2) t)))))
8880 (when (and force (not (looking-at ".*|")))
8881 (save-excursion (end-of-line 1) (insert " | ")))
8882 (if on-delim
8883 (backward-char 1)
8884 (if (looking-at " ") (forward-char 1))))))
8886 (defun org-at-table-p (&optional table-type)
8887 "Return t if the cursor is inside an org-type table.
8888 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8889 (if org-enable-table-editor
8890 (save-excursion
8891 (beginning-of-line 1)
8892 (looking-at (if table-type org-table-any-line-regexp
8893 org-table-line-regexp)))
8894 nil))
8896 (defun org-at-table.el-p ()
8897 "Return t if and only if we are at a table.el table."
8898 (and (org-at-table-p 'any)
8899 (save-excursion
8900 (goto-char (org-table-begin 'any))
8901 (looking-at org-table1-hline-regexp))))
8903 (defun org-table-recognize-table.el ()
8904 "If there is a table.el table nearby, recognize it and move into it."
8905 (if org-table-tab-recognizes-table.el
8906 (if (org-at-table.el-p)
8907 (progn
8908 (beginning-of-line 1)
8909 (if (looking-at org-table-dataline-regexp)
8911 (if (looking-at org-table1-hline-regexp)
8912 (progn
8913 (beginning-of-line 2)
8914 (if (looking-at org-table-any-border-regexp)
8915 (beginning-of-line -1)))))
8916 (if (re-search-forward "|" (org-table-end t) t)
8917 (progn
8918 (require 'table)
8919 (if (table--at-cell-p (point))
8921 (message "recognizing table.el table...")
8922 (table-recognize-table)
8923 (message "recognizing table.el table...done")))
8924 (error "This should not happen..."))
8926 nil)
8927 nil))
8929 (defun org-at-table-hline-p ()
8930 "Return t if the cursor is inside a hline in a table."
8931 (if org-enable-table-editor
8932 (save-excursion
8933 (beginning-of-line 1)
8934 (looking-at org-table-hline-regexp))
8935 nil))
8937 (defun org-table-insert-column ()
8938 "Insert a new column into the table."
8939 (interactive)
8940 (if (not (org-at-table-p))
8941 (error "Not at a table"))
8942 (org-table-find-dataline)
8943 (let* ((col (max 1 (org-table-current-column)))
8944 (beg (org-table-begin))
8945 (end (org-table-end))
8946 ;; Current cursor position
8947 (linepos (org-current-line))
8948 (colpos col))
8949 (goto-char beg)
8950 (while (< (point) end)
8951 (if (org-at-table-hline-p)
8953 (org-table-goto-column col t)
8954 (insert "| "))
8955 (beginning-of-line 2))
8956 (move-marker end nil)
8957 (goto-line linepos)
8958 (org-table-goto-column colpos)
8959 (org-table-align)
8960 (org-table-fix-formulas "$" nil (1- col) 1)))
8962 (defun org-table-find-dataline ()
8963 "Find a dataline in the current table, which is needed for column commands."
8964 (if (and (org-at-table-p)
8965 (not (org-at-table-hline-p)))
8967 (let ((col (current-column))
8968 (end (org-table-end)))
8969 (move-to-column col)
8970 (while (and (< (point) end)
8971 (or (not (= (current-column) col))
8972 (org-at-table-hline-p)))
8973 (beginning-of-line 2)
8974 (move-to-column col))
8975 (if (and (org-at-table-p)
8976 (not (org-at-table-hline-p)))
8978 (error
8979 "Please position cursor in a data line for column operations")))))
8981 (defun org-table-delete-column ()
8982 "Delete a column from the table."
8983 (interactive)
8984 (if (not (org-at-table-p))
8985 (error "Not at a table"))
8986 (org-table-find-dataline)
8987 (org-table-check-inside-data-field)
8988 (let* ((col (org-table-current-column))
8989 (beg (org-table-begin))
8990 (end (org-table-end))
8991 ;; Current cursor position
8992 (linepos (org-current-line))
8993 (colpos col))
8994 (goto-char beg)
8995 (while (< (point) end)
8996 (if (org-at-table-hline-p)
8998 (org-table-goto-column col t)
8999 (and (looking-at "|[^|\n]+|")
9000 (replace-match "|")))
9001 (beginning-of-line 2))
9002 (move-marker end nil)
9003 (goto-line linepos)
9004 (org-table-goto-column colpos)
9005 (org-table-align)
9006 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
9007 col -1 col)))
9009 (defun org-table-move-column-right ()
9010 "Move column to the right."
9011 (interactive)
9012 (org-table-move-column nil))
9013 (defun org-table-move-column-left ()
9014 "Move column to the left."
9015 (interactive)
9016 (org-table-move-column 'left))
9018 (defun org-table-move-column (&optional left)
9019 "Move the current column to the right. With arg LEFT, move to the left."
9020 (interactive "P")
9021 (if (not (org-at-table-p))
9022 (error "Not at a table"))
9023 (org-table-find-dataline)
9024 (org-table-check-inside-data-field)
9025 (let* ((col (org-table-current-column))
9026 (col1 (if left (1- col) col))
9027 (beg (org-table-begin))
9028 (end (org-table-end))
9029 ;; Current cursor position
9030 (linepos (org-current-line))
9031 (colpos (if left (1- col) (1+ col))))
9032 (if (and left (= col 1))
9033 (error "Cannot move column further left"))
9034 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9035 (error "Cannot move column further right"))
9036 (goto-char beg)
9037 (while (< (point) end)
9038 (if (org-at-table-hline-p)
9040 (org-table-goto-column col1 t)
9041 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9042 (replace-match "|\\2|\\1|")))
9043 (beginning-of-line 2))
9044 (move-marker end nil)
9045 (goto-line linepos)
9046 (org-table-goto-column colpos)
9047 (org-table-align)
9048 (org-table-fix-formulas
9049 "$" (list (cons (number-to-string col) (number-to-string colpos))
9050 (cons (number-to-string colpos) (number-to-string col))))))
9052 (defun org-table-move-row-down ()
9053 "Move table row down."
9054 (interactive)
9055 (org-table-move-row nil))
9056 (defun org-table-move-row-up ()
9057 "Move table row up."
9058 (interactive)
9059 (org-table-move-row 'up))
9061 (defun org-table-move-row (&optional up)
9062 "Move the current table line down. With arg UP, move it up."
9063 (interactive "P")
9064 (let* ((col (current-column))
9065 (pos (point))
9066 (hline1p (save-excursion (beginning-of-line 1)
9067 (looking-at org-table-hline-regexp)))
9068 (dline1 (org-table-current-dline))
9069 (dline2 (+ dline1 (if up -1 1)))
9070 (tonew (if up 0 2))
9071 txt hline2p)
9072 (beginning-of-line tonew)
9073 (unless (org-at-table-p)
9074 (goto-char pos)
9075 (error "Cannot move row further"))
9076 (setq hline2p (looking-at org-table-hline-regexp))
9077 (goto-char pos)
9078 (beginning-of-line 1)
9079 (setq pos (point))
9080 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9081 (delete-region (point) (1+ (point-at-eol)))
9082 (beginning-of-line tonew)
9083 (insert txt)
9084 (beginning-of-line 0)
9085 (move-to-column col)
9086 (unless (or hline1p hline2p)
9087 (org-table-fix-formulas
9088 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
9089 (cons (number-to-string dline2) (number-to-string dline1)))))))
9091 (defun org-table-insert-row (&optional arg)
9092 "Insert a new row above the current line into the table.
9093 With prefix ARG, insert below the current line."
9094 (interactive "P")
9095 (if (not (org-at-table-p))
9096 (error "Not at a table"))
9097 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9098 (new (org-table-clean-line line)))
9099 ;; Fix the first field if necessary
9100 (if (string-match "^[ \t]*| *[#$] *|" line)
9101 (setq new (replace-match (match-string 0 line) t t new)))
9102 (beginning-of-line (if arg 2 1))
9103 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9104 (beginning-of-line 0)
9105 (re-search-forward "| ?" (point-at-eol) t)
9106 (and (or org-table-may-need-update org-table-overlay-coordinates)
9107 (org-table-align))
9108 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
9110 (defun org-table-insert-hline (&optional above)
9111 "Insert a horizontal-line below the current line into the table.
9112 With prefix ABOVE, insert above the current line."
9113 (interactive "P")
9114 (if (not (org-at-table-p))
9115 (error "Not at a table"))
9116 (let ((line (org-table-clean-line
9117 (buffer-substring (point-at-bol) (point-at-eol))))
9118 (col (current-column)))
9119 (while (string-match "|\\( +\\)|" line)
9120 (setq line (replace-match
9121 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9122 ?-) "|") t t line)))
9123 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9124 (beginning-of-line (if above 1 2))
9125 (insert line "\n")
9126 (beginning-of-line (if above 1 -1))
9127 (move-to-column col)
9128 (and org-table-overlay-coordinates (org-table-align))))
9130 (defun org-table-hline-and-move (&optional same-column)
9131 "Insert a hline and move to the row below that line."
9132 (interactive "P")
9133 (let ((col (org-table-current-column)))
9134 (org-table-maybe-eval-formula)
9135 (org-table-maybe-recalculate-line)
9136 (org-table-insert-hline)
9137 (end-of-line 2)
9138 (if (looking-at "\n[ \t]*|-")
9139 (progn (insert "\n|") (org-table-align))
9140 (org-table-next-field))
9141 (if same-column (org-table-goto-column col))))
9143 (defun org-table-clean-line (s)
9144 "Convert a table line S into a string with only \"|\" and space.
9145 In particular, this does handle wide and invisible characters."
9146 (if (string-match "^[ \t]*|-" s)
9147 ;; It's a hline, just map the characters
9148 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
9149 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9150 (setq s (replace-match
9151 (concat "|" (make-string (org-string-width (match-string 1 s))
9152 ?\ ) "|")
9153 t t s)))
9156 (defun org-table-kill-row ()
9157 "Delete the current row or horizontal line from the table."
9158 (interactive)
9159 (if (not (org-at-table-p))
9160 (error "Not at a table"))
9161 (let ((col (current-column))
9162 (dline (org-table-current-dline)))
9163 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9164 (if (not (org-at-table-p)) (beginning-of-line 0))
9165 (move-to-column col)
9166 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
9167 dline -1 dline)))
9169 (defun org-table-sort-lines (with-case &optional sorting-type)
9170 "Sort table lines according to the column at point.
9172 The position of point indicates the column to be used for
9173 sorting, and the range of lines is the range between the nearest
9174 horizontal separator lines, or the entire table of no such lines
9175 exist. If point is before the first column, you will be prompted
9176 for the sorting column. If there is an active region, the mark
9177 specifies the first line and the sorting column, while point
9178 should be in the last line to be included into the sorting.
9180 The command then prompts for the sorting type which can be
9181 alphabetically, numerically, or by time (as given in a time stamp
9182 in the field). Sorting in reverse order is also possible.
9184 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
9186 If SORTING-TYPE is specified when this function is called from a Lisp
9187 program, no prompting will take place. SORTING-TYPE must be a character,
9188 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
9189 should be done in reverse order."
9190 (interactive "P")
9191 (let* ((thisline (org-current-line))
9192 (thiscol (org-table-current-column))
9193 beg end bcol ecol tend tbeg column lns pos)
9194 (when (equal thiscol 0)
9195 (if (interactive-p)
9196 (setq thiscol
9197 (string-to-number
9198 (read-string "Use column N for sorting: ")))
9199 (setq thiscol 1))
9200 (org-table-goto-column thiscol))
9201 (org-table-check-inside-data-field)
9202 (if (org-region-active-p)
9203 (progn
9204 (setq beg (region-beginning) end (region-end))
9205 (goto-char beg)
9206 (setq column (org-table-current-column)
9207 beg (point-at-bol))
9208 (goto-char end)
9209 (setq end (point-at-bol 2)))
9210 (setq column (org-table-current-column)
9211 pos (point)
9212 tbeg (org-table-begin)
9213 tend (org-table-end))
9214 (if (re-search-backward org-table-hline-regexp tbeg t)
9215 (setq beg (point-at-bol 2))
9216 (goto-char tbeg)
9217 (setq beg (point-at-bol 1)))
9218 (goto-char pos)
9219 (if (re-search-forward org-table-hline-regexp tend t)
9220 (setq end (point-at-bol 1))
9221 (goto-char tend)
9222 (setq end (point-at-bol))))
9223 (setq beg (move-marker (make-marker) beg)
9224 end (move-marker (make-marker) end))
9225 (untabify beg end)
9226 (goto-char beg)
9227 (org-table-goto-column column)
9228 (skip-chars-backward "^|")
9229 (setq bcol (current-column))
9230 (org-table-goto-column (1+ column))
9231 (skip-chars-backward "^|")
9232 (setq ecol (1- (current-column)))
9233 (org-table-goto-column column)
9234 (setq lns (mapcar (lambda(x) (cons
9235 (org-sort-remove-invisible
9236 (nth (1- column)
9237 (org-split-string x "[ \t]*|[ \t]*")))
9239 (org-split-string (buffer-substring beg end) "\n")))
9240 (setq lns (org-do-sort lns "Table" with-case sorting-type))
9241 (delete-region beg end)
9242 (move-marker beg nil)
9243 (move-marker end nil)
9244 (insert (mapconcat 'cdr lns "\n") "\n")
9245 (goto-line thisline)
9246 (org-table-goto-column thiscol)
9247 (message "%d lines sorted, based on column %d" (length lns) column)))
9249 ;; FIXME: maybe we will not need this? Table sorting is broken....
9250 (defun org-sort-remove-invisible (s)
9251 (remove-text-properties 0 (length s) org-rm-props s)
9252 (while (string-match org-bracket-link-regexp s)
9253 (setq s (replace-match (if (match-end 2)
9254 (match-string 3 s)
9255 (match-string 1 s)) t t s)))
9258 (defun org-table-cut-region (beg end)
9259 "Copy region in table to the clipboard and blank all relevant fields."
9260 (interactive "r")
9261 (org-table-copy-region beg end 'cut))
9263 (defun org-table-copy-region (beg end &optional cut)
9264 "Copy rectangular region in table to clipboard.
9265 A special clipboard is used which can only be accessed
9266 with `org-table-paste-rectangle'."
9267 (interactive "rP")
9268 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9269 region cols
9270 (rpl (if cut " " nil)))
9271 (goto-char beg)
9272 (org-table-check-inside-data-field)
9273 (setq l01 (org-current-line)
9274 c01 (org-table-current-column))
9275 (goto-char end)
9276 (org-table-check-inside-data-field)
9277 (setq l02 (org-current-line)
9278 c02 (org-table-current-column))
9279 (setq l1 (min l01 l02) l2 (max l01 l02)
9280 c1 (min c01 c02) c2 (max c01 c02))
9281 (catch 'exit
9282 (while t
9283 (catch 'nextline
9284 (if (> l1 l2) (throw 'exit t))
9285 (goto-line l1)
9286 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9287 (setq cols nil ic1 c1 ic2 c2)
9288 (while (< ic1 (1+ ic2))
9289 (push (org-table-get-field ic1 rpl) cols)
9290 (setq ic1 (1+ ic1)))
9291 (push (nreverse cols) region)
9292 (setq l1 (1+ l1)))))
9293 (setq org-table-clip (nreverse region))
9294 (if cut (org-table-align))
9295 org-table-clip))
9297 (defun org-table-paste-rectangle ()
9298 "Paste a rectangular region into a table.
9299 The upper right corner ends up in the current field. All involved fields
9300 will be overwritten. If the rectangle does not fit into the present table,
9301 the table is enlarged as needed. The process ignores horizontal separator
9302 lines."
9303 (interactive)
9304 (unless (and org-table-clip (listp org-table-clip))
9305 (error "First cut/copy a region to paste!"))
9306 (org-table-check-inside-data-field)
9307 (let* ((clip org-table-clip)
9308 (line (org-current-line))
9309 (col (org-table-current-column))
9310 (org-enable-table-editor t)
9311 (org-table-automatic-realign nil)
9312 c cols field)
9313 (while (setq cols (pop clip))
9314 (while (org-at-table-hline-p) (beginning-of-line 2))
9315 (if (not (org-at-table-p))
9316 (progn (end-of-line 0) (org-table-next-field)))
9317 (setq c col)
9318 (while (setq field (pop cols))
9319 (org-table-goto-column c nil 'force)
9320 (org-table-get-field nil field)
9321 (setq c (1+ c)))
9322 (beginning-of-line 2))
9323 (goto-line line)
9324 (org-table-goto-column col)
9325 (org-table-align)))
9327 (defun org-table-convert ()
9328 "Convert from `org-mode' table to table.el and back.
9329 Obviously, this only works within limits. When an Org-mode table is
9330 converted to table.el, all horizontal separator lines get lost, because
9331 table.el uses these as cell boundaries and has no notion of horizontal lines.
9332 A table.el table can be converted to an Org-mode table only if it does not
9333 do row or column spanning. Multiline cells will become multiple cells.
9334 Beware, Org-mode does not test if the table can be successfully converted - it
9335 blindly applies a recipe that works for simple tables."
9336 (interactive)
9337 (require 'table)
9338 (if (org-at-table.el-p)
9339 ;; convert to Org-mode table
9340 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9341 (end (move-marker (make-marker) (org-table-end t))))
9342 (table-unrecognize-region beg end)
9343 (goto-char beg)
9344 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9345 (replace-match ""))
9346 (goto-char beg))
9347 (if (org-at-table-p)
9348 ;; convert to table.el table
9349 (let ((beg (move-marker (make-marker) (org-table-begin)))
9350 (end (move-marker (make-marker) (org-table-end))))
9351 ;; first, get rid of all horizontal lines
9352 (goto-char beg)
9353 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9354 (replace-match ""))
9355 ;; insert a hline before first
9356 (goto-char beg)
9357 (org-table-insert-hline 'above)
9358 (beginning-of-line -1)
9359 ;; insert a hline after each line
9360 (while (progn (beginning-of-line 3) (< (point) end))
9361 (org-table-insert-hline))
9362 (goto-char beg)
9363 (setq end (move-marker end (org-table-end)))
9364 ;; replace "+" at beginning and ending of hlines
9365 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9366 (replace-match "\\1+-"))
9367 (goto-char beg)
9368 (while (re-search-forward "-|[ \t]*$" end t)
9369 (replace-match "-+"))
9370 (goto-char beg)))))
9372 (defun org-table-wrap-region (arg)
9373 "Wrap several fields in a column like a paragraph.
9374 This is useful if you'd like to spread the contents of a field over several
9375 lines, in order to keep the table compact.
9377 If there is an active region, and both point and mark are in the same column,
9378 the text in the column is wrapped to minimum width for the given number of
9379 lines. Generally, this makes the table more compact. A prefix ARG may be
9380 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9381 formats the selected text to two lines. If the region was longer than two
9382 lines, the remaining lines remain empty. A negative prefix argument reduces
9383 the current number of lines by that amount. The wrapped text is pasted back
9384 into the table. If you formatted it to more lines than it was before, fields
9385 further down in the table get overwritten - so you might need to make space in
9386 the table first.
9388 If there is no region, the current field is split at the cursor position and
9389 the text fragment to the right of the cursor is prepended to the field one
9390 line down.
9392 If there is no region, but you specify a prefix ARG, the current field gets
9393 blank, and the content is appended to the field above."
9394 (interactive "P")
9395 (org-table-check-inside-data-field)
9396 (if (org-region-active-p)
9397 ;; There is a region: fill as a paragraph
9398 (let* ((beg (region-beginning))
9399 (cline (save-excursion (goto-char beg) (org-current-line)))
9400 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9401 nlines)
9402 (org-table-cut-region (region-beginning) (region-end))
9403 (if (> (length (car org-table-clip)) 1)
9404 (error "Region must be limited to single column"))
9405 (setq nlines (if arg
9406 (if (< arg 1)
9407 (+ (length org-table-clip) arg)
9408 arg)
9409 (length org-table-clip)))
9410 (setq org-table-clip
9411 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9412 nil nlines)))
9413 (goto-line cline)
9414 (org-table-goto-column ccol)
9415 (org-table-paste-rectangle))
9416 ;; No region, split the current field at point
9417 (if arg
9418 ;; combine with field above
9419 (let ((s (org-table-blank-field))
9420 (col (org-table-current-column)))
9421 (beginning-of-line 0)
9422 (while (org-at-table-hline-p) (beginning-of-line 0))
9423 (org-table-goto-column col)
9424 (skip-chars-forward "^|")
9425 (skip-chars-backward " ")
9426 (insert " " (org-trim s))
9427 (org-table-align))
9428 ;; split field
9429 (when (looking-at "\\([^|]+\\)+|")
9430 (let ((s (match-string 1)))
9431 (replace-match " |")
9432 (goto-char (match-beginning 0))
9433 (org-table-next-row)
9434 (insert (org-trim s) " ")
9435 (org-table-align))))))
9437 (defvar org-field-marker nil)
9439 (defun org-table-edit-field (arg)
9440 "Edit table field in a different window.
9441 This is mainly useful for fields that contain hidden parts.
9442 When called with a \\[universal-argument] prefix, just make the full field visible so that
9443 it can be edited in place."
9444 (interactive "P")
9445 (if arg
9446 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9447 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9448 (remove-text-properties b e '(org-cwidth t invisible t
9449 display t intangible t))
9450 (if (and (boundp 'font-lock-mode) font-lock-mode)
9451 (font-lock-fontify-block)))
9452 (let ((pos (move-marker (make-marker) (point)))
9453 (field (org-table-get-field))
9454 (cw (current-window-configuration))
9456 (org-switch-to-buffer-other-window "*Org tmp*")
9457 (erase-buffer)
9458 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9459 (let ((org-inhibit-startup t)) (org-mode))
9460 (goto-char (setq p (point-max)))
9461 (insert (org-trim field))
9462 (remove-text-properties p (point-max)
9463 '(invisible t org-cwidth t display t
9464 intangible t))
9465 (goto-char p)
9466 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9467 (org-set-local 'org-window-configuration cw)
9468 (org-set-local 'org-field-marker pos)
9469 (message "Edit and finish with C-c C-c"))))
9471 (defun org-table-finish-edit-field ()
9472 "Finish editing a table data field.
9473 Remove all newline characters, insert the result into the table, realign
9474 the table and kill the editing buffer."
9475 (let ((pos org-field-marker)
9476 (cw org-window-configuration)
9477 (cb (current-buffer))
9478 text)
9479 (goto-char (point-min))
9480 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9481 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9482 (replace-match " "))
9483 (setq text (org-trim (buffer-string)))
9484 (set-window-configuration cw)
9485 (kill-buffer cb)
9486 (select-window (get-buffer-window (marker-buffer pos)))
9487 (goto-char pos)
9488 (move-marker pos nil)
9489 (org-table-check-inside-data-field)
9490 (org-table-get-field nil text)
9491 (org-table-align)
9492 (message "New field value inserted")))
9494 (defun org-trim (s)
9495 "Remove whitespace at beginning and end of string."
9496 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9497 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9500 (defun org-wrap (string &optional width lines)
9501 "Wrap string to either a number of lines, or a width in characters.
9502 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9503 that costs. If there is a word longer than WIDTH, the text is actually
9504 wrapped to the length of that word.
9505 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9506 many lines, whatever width that takes.
9507 The return value is a list of lines, without newlines at the end."
9508 (let* ((words (org-split-string string "[ \t\n]+"))
9509 (maxword (apply 'max (mapcar 'org-string-width words)))
9510 w ll)
9511 (cond (width
9512 (org-do-wrap words (max maxword width)))
9513 (lines
9514 (setq w maxword)
9515 (setq ll (org-do-wrap words maxword))
9516 (if (<= (length ll) lines)
9518 (setq ll words)
9519 (while (> (length ll) lines)
9520 (setq w (1+ w))
9521 (setq ll (org-do-wrap words w)))
9522 ll))
9523 (t (error "Cannot wrap this")))))
9526 (defun org-do-wrap (words width)
9527 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9528 (let (lines line)
9529 (while words
9530 (setq line (pop words))
9531 (while (and words (< (+ (length line) (length (car words))) width))
9532 (setq line (concat line " " (pop words))))
9533 (setq lines (push line lines)))
9534 (nreverse lines)))
9536 (defun org-split-string (string &optional separators)
9537 "Splits STRING into substrings at SEPARATORS.
9538 No empty strings are returned if there are matches at the beginning
9539 and end of string."
9540 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9541 (start 0)
9542 notfirst
9543 (list nil))
9544 (while (and (string-match rexp string
9545 (if (and notfirst
9546 (= start (match-beginning 0))
9547 (< start (length string)))
9548 (1+ start) start))
9549 (< (match-beginning 0) (length string)))
9550 (setq notfirst t)
9551 (or (eq (match-beginning 0) 0)
9552 (and (eq (match-beginning 0) (match-end 0))
9553 (eq (match-beginning 0) start))
9554 (setq list
9555 (cons (substring string start (match-beginning 0))
9556 list)))
9557 (setq start (match-end 0)))
9558 (or (eq start (length string))
9559 (setq list
9560 (cons (substring string start)
9561 list)))
9562 (nreverse list)))
9564 (defun org-table-map-tables (function)
9565 "Apply FUNCTION to the start of all tables in the buffer."
9566 (save-excursion
9567 (save-restriction
9568 (widen)
9569 (goto-char (point-min))
9570 (while (re-search-forward org-table-any-line-regexp nil t)
9571 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9572 (beginning-of-line 1)
9573 (if (looking-at org-table-line-regexp)
9574 (save-excursion (funcall function)))
9575 (re-search-forward org-table-any-border-regexp nil 1))))
9576 (message "Mapping tables: done"))
9578 (defvar org-timecnt) ; dynamically scoped parameter
9580 (defun org-table-sum (&optional beg end nlast)
9581 "Sum numbers in region of current table column.
9582 The result will be displayed in the echo area, and will be available
9583 as kill to be inserted with \\[yank].
9585 If there is an active region, it is interpreted as a rectangle and all
9586 numbers in that rectangle will be summed. If there is no active
9587 region and point is located in a table column, sum all numbers in that
9588 column.
9590 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9591 numbers are assumed to be times as well (in decimal hours) and the
9592 numbers are added as such.
9594 If NLAST is a number, only the NLAST fields will actually be summed."
9595 (interactive)
9596 (save-excursion
9597 (let (col (org-timecnt 0) diff h m s org-table-clip)
9598 (cond
9599 ((and beg end)) ; beg and end given explicitly
9600 ((org-region-active-p)
9601 (setq beg (region-beginning) end (region-end)))
9603 (setq col (org-table-current-column))
9604 (goto-char (org-table-begin))
9605 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9606 (error "No table data"))
9607 (org-table-goto-column col)
9608 (setq beg (point))
9609 (goto-char (org-table-end))
9610 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9611 (error "No table data"))
9612 (org-table-goto-column col)
9613 (setq end (point))))
9614 (let* ((items (apply 'append (org-table-copy-region beg end)))
9615 (items1 (cond ((not nlast) items)
9616 ((>= nlast (length items)) items)
9617 (t (setq items (reverse items))
9618 (setcdr (nthcdr (1- nlast) items) nil)
9619 (nreverse items))))
9620 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9621 items1)))
9622 (res (apply '+ numbers))
9623 (sres (if (= org-timecnt 0)
9624 (format "%g" res)
9625 (setq diff (* 3600 res)
9626 h (floor (/ diff 3600)) diff (mod diff 3600)
9627 m (floor (/ diff 60)) diff (mod diff 60)
9628 s diff)
9629 (format "%d:%02d:%02d" h m s))))
9630 (kill-new sres)
9631 (if (interactive-p)
9632 (message "%s"
9633 (substitute-command-keys
9634 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9635 (length numbers) sres))))
9636 sres))))
9638 (defun org-table-get-number-for-summing (s)
9639 (let (n)
9640 (if (string-match "^ *|? *" s)
9641 (setq s (replace-match "" nil nil s)))
9642 (if (string-match " *|? *$" s)
9643 (setq s (replace-match "" nil nil s)))
9644 (setq n (string-to-number s))
9645 (cond
9646 ((and (string-match "0" s)
9647 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9648 ((string-match "\\`[ \t]+\\'" s) nil)
9649 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9650 (let ((h (string-to-number (or (match-string 1 s) "0")))
9651 (m (string-to-number (or (match-string 2 s) "0")))
9652 (s (string-to-number (or (match-string 4 s) "0"))))
9653 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9654 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9655 ((equal n 0) nil)
9656 (t n))))
9658 (defun org-table-current-field-formula (&optional key noerror)
9659 "Return the formula active for the current field.
9660 Assumes that specials are in place.
9661 If KEY is given, return the key to this formula.
9662 Otherwise return the formula preceeded with \"=\" or \":=\"."
9663 (let* ((name (car (rassoc (list (org-current-line)
9664 (org-table-current-column))
9665 org-table-named-field-locations)))
9666 (col (org-table-current-column))
9667 (scol (int-to-string col))
9668 (ref (format "@%d$%d" (org-table-current-dline) col))
9669 (stored-list (org-table-get-stored-formulas noerror))
9670 (ass (or (assoc name stored-list)
9671 (assoc ref stored-list)
9672 (assoc scol stored-list))))
9673 (if key
9674 (car ass)
9675 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9676 (cdr ass))))))
9678 (defun org-table-get-formula (&optional equation named)
9679 "Read a formula from the minibuffer, offer stored formula as default.
9680 When NAMED is non-nil, look for a named equation."
9681 (let* ((stored-list (org-table-get-stored-formulas))
9682 (name (car (rassoc (list (org-current-line)
9683 (org-table-current-column))
9684 org-table-named-field-locations)))
9685 (ref (format "@%d$%d" (org-table-current-dline)
9686 (org-table-current-column)))
9687 (refass (assoc ref stored-list))
9688 (scol (if named
9689 (if name name ref)
9690 (int-to-string (org-table-current-column))))
9691 (dummy (and (or name refass) (not named)
9692 (not (y-or-n-p "Replace field formula with column formula? " ))
9693 (error "Abort")))
9694 (name (or name ref))
9695 (org-table-may-need-update nil)
9696 (stored (cdr (assoc scol stored-list)))
9697 (eq (cond
9698 ((and stored equation (string-match "^ *=? *$" equation))
9699 stored)
9700 ((stringp equation)
9701 equation)
9702 (t (org-table-formula-from-user
9703 (read-string
9704 (org-table-formula-to-user
9705 (format "%s formula %s%s="
9706 (if named "Field" "Column")
9707 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9708 scol))
9709 (if stored (org-table-formula-to-user stored) "")
9710 'org-table-formula-history
9711 )))))
9712 mustsave)
9713 (when (not (string-match "\\S-" eq))
9714 ;; remove formula
9715 (setq stored-list (delq (assoc scol stored-list) stored-list))
9716 (org-table-store-formulas stored-list)
9717 (error "Formula removed"))
9718 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9719 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9720 (if (and name (not named))
9721 ;; We set the column equation, delete the named one.
9722 (setq stored-list (delq (assoc name stored-list) stored-list)
9723 mustsave t))
9724 (if stored
9725 (setcdr (assoc scol stored-list) eq)
9726 (setq stored-list (cons (cons scol eq) stored-list)))
9727 (if (or mustsave (not (equal stored eq)))
9728 (org-table-store-formulas stored-list))
9729 eq))
9731 (defun org-table-store-formulas (alist)
9732 "Store the list of formulas below the current table."
9733 (setq alist (sort alist 'org-table-formula-less-p))
9734 (save-excursion
9735 (goto-char (org-table-end))
9736 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9737 (progn
9738 ;; don't overwrite TBLFM, we might use text properties to store stuff
9739 (goto-char (match-beginning 2))
9740 (delete-region (match-beginning 2) (match-end 0)))
9741 (insert "#+TBLFM:"))
9742 (insert " "
9743 (mapconcat (lambda (x)
9744 (concat
9745 (if (equal (string-to-char (car x)) ?@) "" "$")
9746 (car x) "=" (cdr x)))
9747 alist "::")
9748 "\n")))
9750 (defsubst org-table-formula-make-cmp-string (a)
9751 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9752 (concat
9753 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9754 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9755 (if (match-end 5) (concat "@@" (match-string 5 a))))))
9757 (defun org-table-formula-less-p (a b)
9758 "Compare two formulas for sorting."
9759 (let ((as (org-table-formula-make-cmp-string (car a)))
9760 (bs (org-table-formula-make-cmp-string (car b))))
9761 (and as bs (string< as bs))))
9763 (defun org-table-get-stored-formulas (&optional noerror)
9764 "Return an alist with the stored formulas directly after current table."
9765 (interactive)
9766 (let (scol eq eq-alist strings string seen)
9767 (save-excursion
9768 (goto-char (org-table-end))
9769 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9770 (setq strings (org-split-string (match-string 2) " *:: *"))
9771 (while (setq string (pop strings))
9772 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
9773 (setq scol (if (match-end 2)
9774 (match-string 2 string)
9775 (match-string 1 string))
9776 eq (match-string 3 string)
9777 eq-alist (cons (cons scol eq) eq-alist))
9778 (if (member scol seen)
9779 (if noerror
9780 (progn
9781 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9782 (ding)
9783 (sit-for 2))
9784 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
9785 (push scol seen))))))
9786 (nreverse eq-alist)))
9788 (defun org-table-fix-formulas (key replace &optional limit delta remove)
9789 "Modify the equations after the table structure has been edited.
9790 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
9791 For all numbers larger than LIMIT, shift them by DELTA."
9792 (save-excursion
9793 (goto-char (org-table-end))
9794 (when (looking-at "#\\+TBLFM:")
9795 (let ((re (concat key "\\([0-9]+\\)"))
9796 (re2
9797 (when remove
9798 (if (equal key "$")
9799 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
9800 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
9801 s n a)
9802 (when remove
9803 (while (re-search-forward re2 (point-at-eol) t)
9804 (replace-match "")))
9805 (while (re-search-forward re (point-at-eol) t)
9806 (setq s (match-string 1) n (string-to-number s))
9807 (cond
9808 ((setq a (assoc s replace))
9809 (replace-match (concat key (cdr a)) t t))
9810 ((and limit (> n limit))
9811 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
9813 (defun org-table-get-specials ()
9814 "Get the column names and local parameters for this table."
9815 (save-excursion
9816 (let ((beg (org-table-begin)) (end (org-table-end))
9817 names name fields fields1 field cnt
9818 c v l line col types dlines hlines)
9819 (setq org-table-column-names nil
9820 org-table-local-parameters nil
9821 org-table-named-field-locations nil
9822 org-table-current-begin-line nil
9823 org-table-current-begin-pos nil
9824 org-table-current-line-types nil)
9825 (goto-char beg)
9826 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9827 (setq names (org-split-string (match-string 1) " *| *")
9828 cnt 1)
9829 (while (setq name (pop names))
9830 (setq cnt (1+ cnt))
9831 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9832 (push (cons name (int-to-string cnt)) org-table-column-names))))
9833 (setq org-table-column-names (nreverse org-table-column-names))
9834 (setq org-table-column-name-regexp
9835 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9836 (goto-char beg)
9837 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9838 (setq fields (org-split-string (match-string 1) " *| *"))
9839 (while (setq field (pop fields))
9840 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9841 (push (cons (match-string 1 field) (match-string 2 field))
9842 org-table-local-parameters))))
9843 (goto-char beg)
9844 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9845 (setq c (match-string 1)
9846 fields (org-split-string (match-string 2) " *| *"))
9847 (save-excursion
9848 (beginning-of-line (if (equal c "_") 2 0))
9849 (setq line (org-current-line) col 1)
9850 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9851 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9852 (while (and fields1 (setq field (pop fields)))
9853 (setq v (pop fields1) col (1+ col))
9854 (when (and (stringp field) (stringp v)
9855 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9856 (push (cons field v) org-table-local-parameters)
9857 (push (list field line col) org-table-named-field-locations))))
9858 ;; Analyse the line types
9859 (goto-char beg)
9860 (setq org-table-current-begin-line (org-current-line)
9861 org-table-current-begin-pos (point)
9862 l org-table-current-begin-line)
9863 (while (looking-at "[ \t]*|\\(-\\)?")
9864 (push (if (match-end 1) 'hline 'dline) types)
9865 (if (match-end 1) (push l hlines) (push l dlines))
9866 (beginning-of-line 2)
9867 (setq l (1+ l)))
9868 (setq org-table-current-line-types (apply 'vector (nreverse types))
9869 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
9870 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
9872 (defun org-table-maybe-eval-formula ()
9873 "Check if the current field starts with \"=\" or \":=\".
9874 If yes, store the formula and apply it."
9875 ;; We already know we are in a table. Get field will only return a formula
9876 ;; when appropriate. It might return a separator line, but no problem.
9877 (when org-table-formula-evaluate-inline
9878 (let* ((field (org-trim (or (org-table-get-field) "")))
9879 named eq)
9880 (when (string-match "^:?=\\(.*\\)" field)
9881 (setq named (equal (string-to-char field) ?:)
9882 eq (match-string 1 field))
9883 (if (or (fboundp 'calc-eval)
9884 (equal (substring eq 0 (min 2 (length eq))) "'("))
9885 (org-table-eval-formula (if named '(4) nil)
9886 (org-table-formula-from-user eq))
9887 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
9889 (defvar org-recalc-commands nil
9890 "List of commands triggering the recalculation of a line.
9891 Will be filled automatically during use.")
9893 (defvar org-recalc-marks
9894 '((" " . "Unmarked: no special line, no automatic recalculation")
9895 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9896 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9897 ("!" . "Column name definition line. Reference in formula as $name.")
9898 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9899 ("_" . "Names for values in row below this one.")
9900 ("^" . "Names for values in row above this one.")))
9902 (defun org-table-rotate-recalc-marks (&optional newchar)
9903 "Rotate the recalculation mark in the first column.
9904 If in any row, the first field is not consistent with a mark,
9905 insert a new column for the markers.
9906 When there is an active region, change all the lines in the region,
9907 after prompting for the marking character.
9908 After each change, a message will be displayed indicating the meaning
9909 of the new mark."
9910 (interactive)
9911 (unless (org-at-table-p) (error "Not at a table"))
9912 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9913 (beg (org-table-begin))
9914 (end (org-table-end))
9915 (l (org-current-line))
9916 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9917 (l2 (if (org-region-active-p) (org-current-line (region-end))))
9918 (have-col
9919 (save-excursion
9920 (goto-char beg)
9921 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
9922 (col (org-table-current-column))
9923 (forcenew (car (assoc newchar org-recalc-marks)))
9924 epos new)
9925 (when l1
9926 (message "Change region to what mark? Type # * ! $ or SPC: ")
9927 (setq newchar (char-to-string (read-char-exclusive))
9928 forcenew (car (assoc newchar org-recalc-marks))))
9929 (if (and newchar (not forcenew))
9930 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
9931 newchar))
9932 (if l1 (goto-line l1))
9933 (save-excursion
9934 (beginning-of-line 1)
9935 (unless (looking-at org-table-dataline-regexp)
9936 (error "Not at a table data line")))
9937 (unless have-col
9938 (org-table-goto-column 1)
9939 (org-table-insert-column)
9940 (org-table-goto-column (1+ col)))
9941 (setq epos (point-at-eol))
9942 (save-excursion
9943 (beginning-of-line 1)
9944 (org-table-get-field
9945 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
9946 (concat " "
9947 (setq new (or forcenew
9948 (cadr (member (match-string 1) marks))))
9949 " ")
9950 " # ")))
9951 (if (and l1 l2)
9952 (progn
9953 (goto-line l1)
9954 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
9955 (and (looking-at org-table-dataline-regexp)
9956 (org-table-get-field 1 (concat " " new " "))))
9957 (goto-line l1)))
9958 (if (not (= epos (point-at-eol))) (org-table-align))
9959 (goto-line l)
9960 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
9962 (defun org-table-maybe-recalculate-line ()
9963 "Recompute the current line if marked for it, and if we haven't just done it."
9964 (interactive)
9965 (and org-table-allow-automatic-line-recalculation
9966 (not (and (memq last-command org-recalc-commands)
9967 (equal org-last-recalc-line (org-current-line))))
9968 (save-excursion (beginning-of-line 1)
9969 (looking-at org-table-auto-recalculate-regexp))
9970 (org-table-recalculate) t))
9972 (defvar org-table-formula-debug nil
9973 "Non-nil means, debug table formulas.
9974 When nil, simply write \"#ERROR\" in corrupted fields.")
9975 (make-variable-buffer-local 'org-table-formula-debug)
9977 (defvar modes)
9978 (defsubst org-set-calc-mode (var &optional value)
9979 (if (stringp var)
9980 (setq var (assoc var '(("D" calc-angle-mode deg)
9981 ("R" calc-angle-mode rad)
9982 ("F" calc-prefer-frac t)
9983 ("S" calc-symbolic-mode t)))
9984 value (nth 2 var) var (nth 1 var)))
9985 (if (memq var modes)
9986 (setcar (cdr (memq var modes)) value)
9987 (cons var (cons value modes)))
9988 modes)
9990 (defun org-table-eval-formula (&optional arg equation
9991 suppress-align suppress-const
9992 suppress-store suppress-analysis)
9993 "Replace the table field value at the cursor by the result of a calculation.
9995 This function makes use of Dave Gillespie's Calc package, in my view the
9996 most exciting program ever written for GNU Emacs. So you need to have Calc
9997 installed in order to use this function.
9999 In a table, this command replaces the value in the current field with the
10000 result of a formula. It also installs the formula as the \"current\" column
10001 formula, by storing it in a special line below the table. When called
10002 with a `C-u' prefix, the current field must ba a named field, and the
10003 formula is installed as valid in only this specific field.
10005 When called with two `C-u' prefixes, insert the active equation
10006 for the field back into the current field, so that it can be
10007 edited there. This is useful in order to use \\[org-table-show-reference]
10008 to check the referenced fields.
10010 When called, the command first prompts for a formula, which is read in
10011 the minibuffer. Previously entered formulas are available through the
10012 history list, and the last used formula is offered as a default.
10013 These stored formulas are adapted correctly when moving, inserting, or
10014 deleting columns with the corresponding commands.
10016 The formula can be any algebraic expression understood by the Calc package.
10017 For details, see the Org-mode manual.
10019 This function can also be called from Lisp programs and offers
10020 additional arguments: EQUATION can be the formula to apply. If this
10021 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10022 used to speed-up recursive calls by by-passing unnecessary aligns.
10023 SUPPRESS-CONST suppresses the interpretation of constants in the
10024 formula, assuming that this has been done already outside the function.
10025 SUPPRESS-STORE means the formula should not be stored, either because
10026 it is already stored, or because it is a modified equation that should
10027 not overwrite the stored one."
10028 (interactive "P")
10029 (org-table-check-inside-data-field)
10030 (or suppress-analysis (org-table-get-specials))
10031 (if (equal arg '(16))
10032 (let ((eq (org-table-current-field-formula)))
10033 (or eq (error "No equation active for current field"))
10034 (org-table-get-field nil eq)
10035 (org-table-align)
10036 (setq org-table-may-need-update t))
10037 (let* (fields
10038 (ndown (if (integerp arg) arg 1))
10039 (org-table-automatic-realign nil)
10040 (case-fold-search nil)
10041 (down (> ndown 1))
10042 (formula (if (and equation suppress-store)
10043 equation
10044 (org-table-get-formula equation (equal arg '(4)))))
10045 (n0 (org-table-current-column))
10046 (modes (copy-sequence org-calc-default-modes))
10047 (numbers nil) ; was a variable, now fixed default
10048 (keep-empty nil)
10049 n form form0 bw fmt x ev orig c lispp literal)
10050 ;; Parse the format string. Since we have a lot of modes, this is
10051 ;; a lot of work. However, I think calc still uses most of the time.
10052 (if (string-match ";" formula)
10053 (let ((tmp (org-split-string formula ";")))
10054 (setq formula (car tmp)
10055 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10056 (nth 1 tmp)))
10057 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
10058 (setq c (string-to-char (match-string 1 fmt))
10059 n (string-to-number (match-string 2 fmt)))
10060 (if (= c ?p)
10061 (setq modes (org-set-calc-mode 'calc-internal-prec n))
10062 (setq modes (org-set-calc-mode
10063 'calc-float-format
10064 (list (cdr (assoc c '((?n . float) (?f . fix)
10065 (?s . sci) (?e . eng))))
10066 n))))
10067 (setq fmt (replace-match "" t t fmt)))
10068 (if (string-match "[NT]" fmt)
10069 (setq numbers (equal (match-string 0 fmt) "N")
10070 fmt (replace-match "" t t fmt)))
10071 (if (string-match "L" fmt)
10072 (setq literal t
10073 fmt (replace-match "" t t fmt)))
10074 (if (string-match "E" fmt)
10075 (setq keep-empty t
10076 fmt (replace-match "" t t fmt)))
10077 (while (string-match "[DRFS]" fmt)
10078 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10079 (setq fmt (replace-match "" t t fmt)))
10080 (unless (string-match "\\S-" fmt)
10081 (setq fmt nil))))
10082 (if (and (not suppress-const) org-table-formula-use-constants)
10083 (setq formula (org-table-formula-substitute-names formula)))
10084 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10085 (while (> ndown 0)
10086 (setq fields (org-split-string
10087 (org-no-properties
10088 (buffer-substring (point-at-bol) (point-at-eol)))
10089 " *| *"))
10090 (if (eq numbers t)
10091 (setq fields (mapcar
10092 (lambda (x) (number-to-string (string-to-number x)))
10093 fields)))
10094 (setq ndown (1- ndown))
10095 (setq form (copy-sequence formula)
10096 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
10097 (if (and lispp literal) (setq lispp 'literal))
10098 ;; Check for old vertical references
10099 (setq form (org-rewrite-old-row-references form))
10100 ;; Insert complex ranges
10101 (while (string-match org-table-range-regexp form)
10102 (setq form
10103 (replace-match
10104 (save-match-data
10105 (org-table-make-reference
10106 (org-table-get-range (match-string 0 form) nil n0)
10107 keep-empty numbers lispp))
10108 t t form)))
10109 ;; Insert simple ranges
10110 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
10111 (setq form
10112 (replace-match
10113 (save-match-data
10114 (org-table-make-reference
10115 (org-sublist
10116 fields (string-to-number (match-string 1 form))
10117 (string-to-number (match-string 2 form)))
10118 keep-empty numbers lispp))
10119 t t form)))
10120 (setq form0 form)
10121 ;; Insert the references to fields in same row
10122 (while (string-match "\\$\\([0-9]+\\)" form)
10123 (setq n (string-to-number (match-string 1 form))
10124 x (nth (1- (if (= n 0) n0 n)) fields))
10125 (unless x (error "Invalid field specifier \"%s\""
10126 (match-string 0 form)))
10127 (setq form (replace-match
10128 (save-match-data
10129 (org-table-make-reference x nil numbers lispp))
10130 t t form)))
10132 (if lispp
10133 (setq ev (condition-case nil
10134 (eval (eval (read form)))
10135 (error "#ERROR"))
10136 ev (if (numberp ev) (number-to-string ev) ev))
10137 (or (fboundp 'calc-eval)
10138 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
10139 (setq ev (calc-eval (cons form modes)
10140 (if numbers 'num))))
10142 (when org-table-formula-debug
10143 (with-output-to-temp-buffer "*Substitution History*"
10144 (princ (format "Substitution history of formula
10145 Orig: %s
10146 $xyz-> %s
10147 @r$c-> %s
10148 $1-> %s\n" orig formula form0 form))
10149 (if (listp ev)
10150 (princ (format " %s^\nError: %s"
10151 (make-string (car ev) ?\-) (nth 1 ev)))
10152 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10153 ev (or fmt "NONE")
10154 (if fmt (format fmt (string-to-number ev)) ev)))))
10155 (setq bw (get-buffer-window "*Substitution History*"))
10156 (shrink-window-if-larger-than-buffer bw)
10157 (unless (and (interactive-p) (not ndown))
10158 (unless (let (inhibit-redisplay)
10159 (y-or-n-p "Debugging Formula. Continue to next? "))
10160 (org-table-align)
10161 (error "Abort"))
10162 (delete-window bw)
10163 (message "")))
10164 (if (listp ev) (setq fmt nil ev "#ERROR"))
10165 (org-table-justify-field-maybe
10166 (if fmt (format fmt (string-to-number ev)) ev))
10167 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10168 (call-interactively 'org-return)
10169 (setq ndown 0)))
10170 (and down (org-table-maybe-recalculate-line))
10171 (or suppress-align (and org-table-may-need-update
10172 (org-table-align))))))
10174 (defun org-table-put-field-property (prop value)
10175 (save-excursion
10176 (put-text-property (progn (skip-chars-backward "^|") (point))
10177 (progn (skip-chars-forward "^|") (point))
10178 prop value)))
10180 (defun org-table-get-range (desc &optional tbeg col highlight)
10181 "Get a calc vector from a column, accorting to descriptor DESC.
10182 Optional arguments TBEG and COL can give the beginning of the table and
10183 the current column, to avoid unnecessary parsing.
10184 HIGHLIGHT means, just highlight the range."
10185 (if (not (equal (string-to-char desc) ?@))
10186 (setq desc (concat "@" desc)))
10187 (save-excursion
10188 (or tbeg (setq tbeg (org-table-begin)))
10189 (or col (setq col (org-table-current-column)))
10190 (let ((thisline (org-current-line))
10191 beg end c1 c2 r1 r2 rangep tmp)
10192 (unless (string-match org-table-range-regexp desc)
10193 (error "Invalid table range specifier `%s'" desc))
10194 (setq rangep (match-end 3)
10195 r1 (and (match-end 1) (match-string 1 desc))
10196 r2 (and (match-end 4) (match-string 4 desc))
10197 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
10198 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
10200 (and c1 (setq c1 (+ (string-to-number c1)
10201 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
10202 (and c2 (setq c2 (+ (string-to-number c2)
10203 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
10204 (if (equal r1 "") (setq r1 nil))
10205 (if (equal r2 "") (setq r2 nil))
10206 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10207 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10208 ; (setq r2 (or r2 r1) c2 (or c2 c1))
10209 (if (not r1) (setq r1 thisline))
10210 (if (not r2) (setq r2 thisline))
10211 (if (not c1) (setq c1 col))
10212 (if (not c2) (setq c2 col))
10213 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10214 ;; just one field
10215 (progn
10216 (goto-line r1)
10217 (while (not (looking-at org-table-dataline-regexp))
10218 (beginning-of-line 2))
10219 (prog1 (org-trim (org-table-get-field c1))
10220 (if highlight (org-table-highlight-rectangle (point) (point)))))
10221 ;; A range, return a vector
10222 ;; First sort the numbers to get a regular ractangle
10223 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10224 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10225 (goto-line r1)
10226 (while (not (looking-at org-table-dataline-regexp))
10227 (beginning-of-line 2))
10228 (org-table-goto-column c1)
10229 (setq beg (point))
10230 (goto-line r2)
10231 (while (not (looking-at org-table-dataline-regexp))
10232 (beginning-of-line 0))
10233 (org-table-goto-column c2)
10234 (setq end (point))
10235 (if highlight
10236 (org-table-highlight-rectangle
10237 beg (progn (skip-chars-forward "^|\n") (point))))
10238 ;; return string representation of calc vector
10239 (mapcar 'org-trim
10240 (apply 'append (org-table-copy-region beg end)))))))
10242 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10243 "Analyze descriptor DESC and retrieve the corresponding line number.
10244 The cursor is currently in line CLINE, the table begins in line BLINE,
10245 and TABLE is a vector with line types."
10246 (if (string-match "^[0-9]+$" desc)
10247 (aref org-table-dlines (string-to-number desc))
10248 (setq cline (or cline (org-current-line))
10249 bline (or bline org-table-current-begin-line)
10250 table (or table org-table-current-line-types))
10251 (if (or
10252 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10253 ;; 1 2 3 4 5 6
10254 (and (not (match-end 3)) (not (match-end 6)))
10255 (and (match-end 3) (match-end 6) (not (match-end 5))))
10256 (error "invalid row descriptor `%s'" desc))
10257 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10258 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10259 (odir (and (match-end 5) (match-string 5 desc)))
10260 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10261 (i (- cline bline))
10262 (rel (and (match-end 6)
10263 (or (and (match-end 1) (not (match-end 3)))
10264 (match-end 5)))))
10265 (if (and hn (not hdir))
10266 (progn
10267 (setq i 0 hdir "+")
10268 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10269 (if (and (not hn) on (not odir))
10270 (error "should never happen");;(aref org-table-dlines on)
10271 (if (and hn (> hn 0))
10272 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10273 (if on
10274 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10275 (+ bline i)))))
10277 (defun org-find-row-type (table i type backwards relative n)
10278 (let ((l (length table)))
10279 (while (> n 0)
10280 (while (and (setq i (+ i (if backwards -1 1)))
10281 (>= i 0) (< i l)
10282 (not (eq (aref table i) type))
10283 (if (and relative (eq (aref table i) 'hline))
10284 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10285 t)))
10286 (setq n (1- n)))
10287 (if (or (< i 0) (>= i l))
10288 (error "Row descriptior leads outside table")
10289 i)))
10291 (defun org-rewrite-old-row-references (s)
10292 (if (string-match "&[-+0-9I]" s)
10293 (error "Formula contains old &row reference, please rewrite using @-syntax")
10296 (defun org-table-make-reference (elements keep-empty numbers lispp)
10297 "Convert list ELEMENTS to something appropriate to insert into formula.
10298 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10299 NUMBERS indicates that everything should be converted to numbers.
10300 LISPP means to return something appropriate for a Lisp list."
10301 (if (stringp elements) ; just a single val
10302 (if lispp
10303 (if (eq lispp 'literal)
10304 elements
10305 (prin1-to-string (if numbers (string-to-number elements) elements)))
10306 (if (equal elements "") (setq elements "0"))
10307 (if numbers (number-to-string (string-to-number elements)) elements))
10308 (unless keep-empty
10309 (setq elements
10310 (delq nil
10311 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10312 elements))))
10313 (setq elements (or elements '("0")))
10314 (if lispp
10315 (mapconcat
10316 (lambda (x)
10317 (if (eq lispp 'literal)
10319 (prin1-to-string (if numbers (string-to-number x) x))))
10320 elements " ")
10321 (concat "[" (mapconcat
10322 (lambda (x)
10323 (if numbers (number-to-string (string-to-number x)) x))
10324 elements
10325 ",") "]"))))
10327 (defun org-table-recalculate (&optional all noalign)
10328 "Recalculate the current table line by applying all stored formulas.
10329 With prefix arg ALL, do this for all lines in the table."
10330 (interactive "P")
10331 (or (memq this-command org-recalc-commands)
10332 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10333 (unless (org-at-table-p) (error "Not at a table"))
10334 (if (equal all '(16))
10335 (org-table-iterate)
10336 (org-table-get-specials)
10337 (let* ((eqlist (sort (org-table-get-stored-formulas)
10338 (lambda (a b) (string< (car a) (car b)))))
10339 (inhibit-redisplay (not debug-on-error))
10340 (line-re org-table-dataline-regexp)
10341 (thisline (org-current-line))
10342 (thiscol (org-table-current-column))
10343 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10344 ;; Insert constants in all formulas
10345 (setq eqlist
10346 (mapcar (lambda (x)
10347 (setcdr x (org-table-formula-substitute-names (cdr x)))
10349 eqlist))
10350 ;; Split the equation list
10351 (while (setq eq (pop eqlist))
10352 (if (<= (string-to-char (car eq)) ?9)
10353 (push eq eqlnum)
10354 (push eq eqlname)))
10355 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10356 (if all
10357 (progn
10358 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10359 (goto-char (setq beg (org-table-begin)))
10360 (if (re-search-forward org-table-calculate-mark-regexp end t)
10361 ;; This is a table with marked lines, compute selected lines
10362 (setq line-re org-table-recalculate-regexp)
10363 ;; Move forward to the first non-header line
10364 (if (and (re-search-forward org-table-dataline-regexp end t)
10365 (re-search-forward org-table-hline-regexp end t)
10366 (re-search-forward org-table-dataline-regexp end t))
10367 (setq beg (match-beginning 0))
10368 nil))) ;; just leave beg where it is
10369 (setq beg (point-at-bol)
10370 end (move-marker (make-marker) (1+ (point-at-eol)))))
10371 (goto-char beg)
10372 (and all (message "Re-applying formulas to full table..."))
10374 ;; First find the named fields, and mark them untouchanble
10375 (remove-text-properties beg end '(org-untouchable t))
10376 (while (setq eq (pop eqlname))
10377 (setq name (car eq)
10378 a (assoc name org-table-named-field-locations))
10379 (and (not a)
10380 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10381 (setq a (list name
10382 (aref org-table-dlines
10383 (string-to-number (match-string 1 name)))
10384 (string-to-number (match-string 2 name)))))
10385 (when (and a (or all (equal (nth 1 a) thisline)))
10386 (message "Re-applying formula to field: %s" name)
10387 (goto-line (nth 1 a))
10388 (org-table-goto-column (nth 2 a))
10389 (push (append a (list (cdr eq))) eqlname1)
10390 (org-table-put-field-property :org-untouchable t)))
10392 ;; Now evauluate the column formulas, but skip fields covered by
10393 ;; field formulas
10394 (goto-char beg)
10395 (while (re-search-forward line-re end t)
10396 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10397 ;; Unprotected line, recalculate
10398 (and all (message "Re-applying formulas to full table...(line %d)"
10399 (setq cnt (1+ cnt))))
10400 (setq org-last-recalc-line (org-current-line))
10401 (setq eql eqlnum)
10402 (while (setq entry (pop eql))
10403 (goto-line org-last-recalc-line)
10404 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10405 (unless (get-text-property (point) :org-untouchable)
10406 (org-table-eval-formula nil (cdr entry)
10407 'noalign 'nocst 'nostore 'noanalysis)))))
10409 ;; Now evaluate the field formulas
10410 (while (setq eq (pop eqlname1))
10411 (message "Re-applying formula to field: %s" (car eq))
10412 (goto-line (nth 1 eq))
10413 (org-table-goto-column (nth 2 eq))
10414 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10415 'nostore 'noanalysis))
10417 (goto-line thisline)
10418 (org-table-goto-column thiscol)
10419 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10420 (or noalign (and org-table-may-need-update (org-table-align))
10421 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10423 ;; back to initial position
10424 (message "Re-applying formulas...done")
10425 (goto-line thisline)
10426 (org-table-goto-column thiscol)
10427 (or noalign (and org-table-may-need-update (org-table-align))
10428 (and all (message "Re-applying formulas...done"))))))
10430 (defun org-table-iterate (&optional arg)
10431 "Recalculate the table until it does not change anymore."
10432 (interactive "P")
10433 (let ((imax (if arg (prefix-numeric-value arg) 10))
10434 (i 0)
10435 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10436 thistbl)
10437 (catch 'exit
10438 (while (< i imax)
10439 (setq i (1+ i))
10440 (org-table-recalculate 'all)
10441 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10442 (if (not (string= lasttbl thistbl))
10443 (setq lasttbl thistbl)
10444 (if (> i 1)
10445 (message "Convergence after %d iterations" i)
10446 (message "Table was already stable"))
10447 (throw 'exit t)))
10448 (error "No convergence after %d iterations" i))))
10450 (defun org-table-formula-substitute-names (f)
10451 "Replace $const with values in string F."
10452 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10453 ;; First, check for column names
10454 (while (setq start (string-match org-table-column-name-regexp f start))
10455 (setq start (1+ start))
10456 (setq a (assoc (match-string 1 f) org-table-column-names))
10457 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10458 ;; Parameters and constants
10459 (setq start 0)
10460 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10461 (setq start (1+ start))
10462 (if (setq a (save-match-data
10463 (org-table-get-constant (match-string 1 f))))
10464 (setq f (replace-match
10465 (concat (if pp "(") a (if pp ")")) t t f))))
10466 (if org-table-formula-debug
10467 (put-text-property 0 (length f) :orig-formula f1 f))
10470 (defun org-table-get-constant (const)
10471 "Find the value for a parameter or constant in a formula.
10472 Parameters get priority."
10473 (or (cdr (assoc const org-table-local-parameters))
10474 (cdr (assoc const org-table-formula-constants-local))
10475 (cdr (assoc const org-table-formula-constants))
10476 (and (fboundp 'constants-get) (constants-get const))
10477 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10478 (org-entry-get nil (substring const 5) 'inherit))
10479 "#UNDEFINED_NAME"))
10481 (defvar org-table-fedit-map
10482 (let ((map (make-sparse-keymap)))
10483 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10484 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10485 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10486 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10487 (org-defkey map "\C-c?" 'org-table-show-reference)
10488 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10489 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10490 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10491 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10492 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10493 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10494 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10495 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10496 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10497 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10498 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10499 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10500 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10501 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10502 map))
10504 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10505 '("Edit-Formulas"
10506 ["Finish and Install" org-table-fedit-finish t]
10507 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10508 ["Abort" org-table-fedit-abort t]
10509 "--"
10510 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10511 ["Complete Lisp Symbol" lisp-complete-symbol t]
10512 "--"
10513 "Shift Reference at Point"
10514 ["Up" org-table-fedit-ref-up t]
10515 ["Down" org-table-fedit-ref-down t]
10516 ["Left" org-table-fedit-ref-left t]
10517 ["Right" org-table-fedit-ref-right t]
10519 "Change Test Row for Column Formulas"
10520 ["Up" org-table-fedit-line-up t]
10521 ["Down" org-table-fedit-line-down t]
10522 "--"
10523 ["Scroll Table Window" org-table-fedit-scroll t]
10524 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10525 ["Show Table Grid" org-table-fedit-toggle-coordinates
10526 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10527 org-table-overlay-coordinates)]
10528 "--"
10529 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10530 :style toggle :selected org-table-buffer-is-an]))
10532 (defvar org-pos)
10534 (defun org-table-edit-formulas ()
10535 "Edit the formulas of the current table in a separate buffer."
10536 (interactive)
10537 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10538 (beginning-of-line 0))
10539 (unless (org-at-table-p) (error "Not at a table"))
10540 (org-table-get-specials)
10541 (let ((key (org-table-current-field-formula 'key 'noerror))
10542 (eql (sort (org-table-get-stored-formulas 'noerror)
10543 'org-table-formula-less-p))
10544 (pos (move-marker (make-marker) (point)))
10545 (startline 1)
10546 (wc (current-window-configuration))
10547 (titles '((column . "# Column Formulas\n")
10548 (field . "# Field Formulas\n")
10549 (named . "# Named Field Formulas\n")))
10550 entry s type title)
10551 (org-switch-to-buffer-other-window "*Edit Formulas*")
10552 (erase-buffer)
10553 ;; Keep global-font-lock-mode from turning on font-lock-mode
10554 (let ((font-lock-global-modes '(not fundamental-mode)))
10555 (fundamental-mode))
10556 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10557 (org-set-local 'org-pos pos)
10558 (org-set-local 'org-window-configuration wc)
10559 (use-local-map org-table-fedit-map)
10560 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10561 (easy-menu-add org-table-fedit-menu)
10562 (setq startline (org-current-line))
10563 (while (setq entry (pop eql))
10564 (setq type (cond
10565 ((equal (string-to-char (car entry)) ?@) 'field)
10566 ((string-match "^[0-9]" (car entry)) 'column)
10567 (t 'named)))
10568 (when (setq title (assq type titles))
10569 (or (bobp) (insert "\n"))
10570 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10571 (setq titles (delq title titles)))
10572 (if (equal key (car entry)) (setq startline (org-current-line)))
10573 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10574 (car entry) " = " (cdr entry) "\n"))
10575 (remove-text-properties 0 (length s) '(face nil) s)
10576 (insert s))
10577 (if (eq org-table-use-standard-references t)
10578 (org-table-fedit-toggle-ref-type))
10579 (goto-line startline)
10580 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10582 (defun org-table-fedit-post-command ()
10583 (when (not (memq this-command '(lisp-complete-symbol)))
10584 (let ((win (selected-window)))
10585 (save-excursion
10586 (condition-case nil
10587 (org-table-show-reference)
10588 (error nil))
10589 (select-window win)))))
10591 (defun org-table-formula-to-user (s)
10592 "Convert a formula from internal to user representation."
10593 (if (eq org-table-use-standard-references t)
10594 (org-table-convert-refs-to-an s)
10597 (defun org-table-formula-from-user (s)
10598 "Convert a formula from user to internal representation."
10599 (if org-table-use-standard-references
10600 (org-table-convert-refs-to-rc s)
10603 (defun org-table-convert-refs-to-rc (s)
10604 "Convert spreadsheet references from AB7 to @7$28.
10605 Works for single references, but also for entire formulas and even the
10606 full TBLFM line."
10607 (let ((start 0))
10608 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10609 (cond
10610 ((match-end 3)
10611 ;; format match, just advance
10612 (setq start (match-end 0)))
10613 ((and (> (match-beginning 0) 0)
10614 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10615 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10616 ;; 3.e5 or something like this.
10617 (setq start (match-end 0)))
10619 (setq start (match-beginning 0)
10620 s (replace-match
10621 (if (equal (match-string 2 s) "&")
10622 (format "$%d" (org-letters-to-number (match-string 1 s)))
10623 (format "@%d$%d"
10624 (string-to-number (match-string 2 s))
10625 (org-letters-to-number (match-string 1 s))))
10626 t t s)))))
10629 (defun org-table-convert-refs-to-an (s)
10630 "Convert spreadsheet references from to @7$28 to AB7.
10631 Works for single references, but also for entire formulas and even the
10632 full TBLFM line."
10633 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10634 (setq s (replace-match
10635 (format "%s%d"
10636 (org-number-to-letters
10637 (string-to-number (match-string 2 s)))
10638 (string-to-number (match-string 1 s)))
10639 t t s)))
10640 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10641 (setq s (replace-match (concat "\\1"
10642 (org-number-to-letters
10643 (string-to-number (match-string 2 s))) "&")
10644 t nil s)))
10647 (defun org-letters-to-number (s)
10648 "Convert a base 26 number represented by letters into an integer.
10649 For example: AB -> 28."
10650 (let ((n 0))
10651 (setq s (upcase s))
10652 (while (> (length s) 0)
10653 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10654 s (substring s 1)))
10657 (defun org-number-to-letters (n)
10658 "Convert an integer into a base 26 number represented by letters.
10659 For example: 28 -> AB."
10660 (let ((s ""))
10661 (while (> n 0)
10662 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10663 n (/ (1- n) 26)))
10666 (defun org-table-fedit-convert-buffer (function)
10667 "Convert all references in this buffer, using FUNTION."
10668 (let ((line (org-current-line)))
10669 (goto-char (point-min))
10670 (while (not (eobp))
10671 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10672 (delete-region (point) (point-at-eol))
10673 (or (eobp) (forward-char 1)))
10674 (goto-line line)))
10676 (defun org-table-fedit-toggle-ref-type ()
10677 "Convert all references in the buffer from B3 to @3$2 and back."
10678 (interactive)
10679 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10680 (org-table-fedit-convert-buffer
10681 (if org-table-buffer-is-an
10682 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10683 (message "Reference type switched to %s"
10684 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10686 (defun org-table-fedit-ref-up ()
10687 "Shift the reference at point one row/hline up."
10688 (interactive)
10689 (org-table-fedit-shift-reference 'up))
10690 (defun org-table-fedit-ref-down ()
10691 "Shift the reference at point one row/hline down."
10692 (interactive)
10693 (org-table-fedit-shift-reference 'down))
10694 (defun org-table-fedit-ref-left ()
10695 "Shift the reference at point one field to the left."
10696 (interactive)
10697 (org-table-fedit-shift-reference 'left))
10698 (defun org-table-fedit-ref-right ()
10699 "Shift the reference at point one field to the right."
10700 (interactive)
10701 (org-table-fedit-shift-reference 'right))
10703 (defun org-table-fedit-shift-reference (dir)
10704 (cond
10705 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10706 (if (memq dir '(left right))
10707 (org-rematch-and-replace 1 (eq dir 'left))
10708 (error "Cannot shift reference in this direction")))
10709 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10710 ;; A B3-like reference
10711 (if (memq dir '(up down))
10712 (org-rematch-and-replace 2 (eq dir 'up))
10713 (org-rematch-and-replace 1 (eq dir 'left))))
10714 ((org-at-regexp-p
10715 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10716 ;; An internal reference
10717 (if (memq dir '(up down))
10718 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10719 (org-rematch-and-replace 5 (eq dir 'left))))))
10721 (defun org-rematch-and-replace (n &optional decr hline)
10722 "Re-match the group N, and replace it with the shifted refrence."
10723 (or (match-end n) (error "Cannot shift reference in this direction"))
10724 (goto-char (match-beginning n))
10725 (and (looking-at (regexp-quote (match-string n)))
10726 (replace-match (org-shift-refpart (match-string 0) decr hline)
10727 t t)))
10729 (defun org-shift-refpart (ref &optional decr hline)
10730 "Shift a refrence part REF.
10731 If DECR is set, decrease the references row/column, else increase.
10732 If HLINE is set, this may be a hline reference, it certainly is not
10733 a translation reference."
10734 (save-match-data
10735 (let* ((sign (string-match "^[-+]" ref)) n)
10737 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10738 (cond
10739 ((and hline (string-match "^I+" ref))
10740 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10741 (setq n (+ n (if decr -1 1)))
10742 (if (= n 0) (setq n (+ n (if decr -1 1))))
10743 (if sign
10744 (setq sign (if (< n 0) "-" "+") n (abs n))
10745 (setq n (max 1 n)))
10746 (concat sign (make-string n ?I)))
10748 ((string-match "^[0-9]+" ref)
10749 (setq n (string-to-number (concat sign ref)))
10750 (setq n (+ n (if decr -1 1)))
10751 (if sign
10752 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10753 (number-to-string (max 1 n))))
10755 ((string-match "^[a-zA-Z]+" ref)
10756 (org-number-to-letters
10757 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10759 (t (error "Cannot shift reference"))))))
10761 (defun org-table-fedit-toggle-coordinates ()
10762 "Toggle the display of coordinates in the refrenced table."
10763 (interactive)
10764 (let ((pos (marker-position org-pos)))
10765 (with-current-buffer (marker-buffer org-pos)
10766 (save-excursion
10767 (goto-char pos)
10768 (org-table-toggle-coordinate-overlays)))))
10770 (defun org-table-fedit-finish (&optional arg)
10771 "Parse the buffer for formula definitions and install them.
10772 With prefix ARG, apply the new formulas to the table."
10773 (interactive "P")
10774 (org-table-remove-rectangle-highlight)
10775 (if org-table-use-standard-references
10776 (progn
10777 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
10778 (setq org-table-buffer-is-an nil)))
10779 (let ((pos org-pos) eql var form)
10780 (goto-char (point-min))
10781 (while (re-search-forward
10782 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
10783 nil t)
10784 (setq var (if (match-end 2) (match-string 2) (match-string 1))
10785 form (match-string 3))
10786 (setq form (org-trim form))
10787 (when (not (equal form ""))
10788 (while (string-match "[ \t]*\n[ \t]*" form)
10789 (setq form (replace-match " " t t form)))
10790 (when (assoc var eql)
10791 (error "Double formulas for %s" var))
10792 (push (cons var form) eql)))
10793 (setq org-pos nil)
10794 (set-window-configuration org-window-configuration)
10795 (select-window (get-buffer-window (marker-buffer pos)))
10796 (goto-char pos)
10797 (unless (org-at-table-p)
10798 (error "Lost table position - cannot install formulae"))
10799 (org-table-store-formulas eql)
10800 (move-marker pos nil)
10801 (kill-buffer "*Edit Formulas*")
10802 (if arg
10803 (org-table-recalculate 'all)
10804 (message "New formulas installed - press C-u C-c C-c to apply."))))
10806 (defun org-table-fedit-abort ()
10807 "Abort editing formulas, without installing the changes."
10808 (interactive)
10809 (org-table-remove-rectangle-highlight)
10810 (let ((pos org-pos))
10811 (set-window-configuration org-window-configuration)
10812 (select-window (get-buffer-window (marker-buffer pos)))
10813 (goto-char pos)
10814 (move-marker pos nil)
10815 (message "Formula editing aborted without installing changes")))
10817 (defun org-table-fedit-lisp-indent ()
10818 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
10819 (interactive)
10820 (let ((pos (point)) beg end ind)
10821 (beginning-of-line 1)
10822 (cond
10823 ((looking-at "[ \t]")
10824 (goto-char pos)
10825 (call-interactively 'lisp-indent-line))
10826 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
10827 ((not (fboundp 'pp-buffer))
10828 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
10829 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
10830 (goto-char (- (match-end 0) 2))
10831 (setq beg (point))
10832 (setq ind (make-string (current-column) ?\ ))
10833 (condition-case nil (forward-sexp 1)
10834 (error
10835 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
10836 (setq end (point))
10837 (save-restriction
10838 (narrow-to-region beg end)
10839 (if (eq last-command this-command)
10840 (progn
10841 (goto-char (point-min))
10842 (setq this-command nil)
10843 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
10844 (replace-match " ")))
10845 (pp-buffer)
10846 (untabify (point-min) (point-max))
10847 (goto-char (1+ (point-min)))
10848 (while (re-search-forward "^." nil t)
10849 (beginning-of-line 1)
10850 (insert ind))
10851 (goto-char (point-max))
10852 (backward-delete-char 1)))
10853 (goto-char beg))
10854 (t nil))))
10856 (defvar org-show-positions nil)
10858 (defun org-table-show-reference (&optional local)
10859 "Show the location/value of the $ expression at point."
10860 (interactive)
10861 (org-table-remove-rectangle-highlight)
10862 (catch 'exit
10863 (let ((pos (if local (point) org-pos))
10864 (face2 'highlight)
10865 (org-inhibit-highlight-removal t)
10866 (win (selected-window))
10867 (org-show-positions nil)
10868 var name e what match dest)
10869 (if local (org-table-get-specials))
10870 (setq what (cond
10871 ((or (org-at-regexp-p org-table-range-regexp2)
10872 (org-at-regexp-p org-table-translate-regexp)
10873 (org-at-regexp-p org-table-range-regexp))
10874 (setq match
10875 (save-match-data
10876 (org-table-convert-refs-to-rc (match-string 0))))
10877 'range)
10878 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
10879 ((org-at-regexp-p "\\$[0-9]+") 'column)
10880 ((not local) nil)
10881 (t (error "No reference at point")))
10882 match (and what (or match (match-string 0))))
10883 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
10884 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
10885 'secondary-selection))
10886 (org-add-hook 'before-change-functions
10887 'org-table-remove-rectangle-highlight)
10888 (if (eq what 'name) (setq var (substring match 1)))
10889 (when (eq what 'range)
10890 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
10891 (setq match (org-table-formula-substitute-names match)))
10892 (unless local
10893 (save-excursion
10894 (end-of-line 1)
10895 (re-search-backward "^\\S-" nil t)
10896 (beginning-of-line 1)
10897 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
10898 (setq dest
10899 (save-match-data
10900 (org-table-convert-refs-to-rc (match-string 1))))
10901 (org-table-add-rectangle-overlay
10902 (match-beginning 1) (match-end 1) face2))))
10903 (if (and (markerp pos) (marker-buffer pos))
10904 (if (get-buffer-window (marker-buffer pos))
10905 (select-window (get-buffer-window (marker-buffer pos)))
10906 (org-switch-to-buffer-other-window (get-buffer-window
10907 (marker-buffer pos)))))
10908 (goto-char pos)
10909 (org-table-force-dataline)
10910 (when dest
10911 (setq name (substring dest 1))
10912 (cond
10913 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
10914 (setq e (assoc name org-table-named-field-locations))
10915 (goto-line (nth 1 e))
10916 (org-table-goto-column (nth 2 e)))
10917 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
10918 (let ((l (string-to-number (match-string 1 dest)))
10919 (c (string-to-number (match-string 2 dest))))
10920 (goto-line (aref org-table-dlines l))
10921 (org-table-goto-column c)))
10922 (t (org-table-goto-column (string-to-number name))))
10923 (move-marker pos (point))
10924 (org-table-highlight-rectangle nil nil face2))
10925 (cond
10926 ((equal dest match))
10927 ((not match))
10928 ((eq what 'range)
10929 (condition-case nil
10930 (save-excursion
10931 (org-table-get-range match nil nil 'highlight))
10932 (error nil)))
10933 ((setq e (assoc var org-table-named-field-locations))
10934 (goto-line (nth 1 e))
10935 (org-table-goto-column (nth 2 e))
10936 (org-table-highlight-rectangle (point) (point))
10937 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
10938 ((setq e (assoc var org-table-column-names))
10939 (org-table-goto-column (string-to-number (cdr e)))
10940 (org-table-highlight-rectangle (point) (point))
10941 (goto-char (org-table-begin))
10942 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
10943 (org-table-end) t)
10944 (progn
10945 (goto-char (match-beginning 1))
10946 (org-table-highlight-rectangle)
10947 (message "Named column (column %s)" (cdr e)))
10948 (error "Column name not found")))
10949 ((eq what 'column)
10950 ;; column number
10951 (org-table-goto-column (string-to-number (substring match 1)))
10952 (org-table-highlight-rectangle (point) (point))
10953 (message "Column %s" (substring match 1)))
10954 ((setq e (assoc var org-table-local-parameters))
10955 (goto-char (org-table-begin))
10956 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
10957 (progn
10958 (goto-char (match-beginning 1))
10959 (org-table-highlight-rectangle)
10960 (message "Local parameter."))
10961 (error "Parameter not found")))
10963 (cond
10964 ((not var) (error "No reference at point"))
10965 ((setq e (assoc var org-table-formula-constants-local))
10966 (message "Local Constant: $%s=%s in #+CONSTANTS line."
10967 var (cdr e)))
10968 ((setq e (assoc var org-table-formula-constants))
10969 (message "Constant: $%s=%s in `org-table-formula-constants'."
10970 var (cdr e)))
10971 ((setq e (and (fboundp 'constants-get) (constants-get var)))
10972 (message "Constant: $%s=%s, from `constants.el'%s."
10973 var e (format " (%s units)" constants-unit-system)))
10974 (t (error "Undefined name $%s" var)))))
10975 (goto-char pos)
10976 (when (and org-show-positions
10977 (not (memq this-command '(org-table-fedit-scroll
10978 org-table-fedit-scroll-down))))
10979 (push pos org-show-positions)
10980 (push org-table-current-begin-pos org-show-positions)
10981 (let ((min (apply 'min org-show-positions))
10982 (max (apply 'max org-show-positions)))
10983 (goto-char min) (recenter 0)
10984 (goto-char max)
10985 (or (pos-visible-in-window-p max) (recenter -1))))
10986 (select-window win))))
10988 (defun org-table-force-dataline ()
10989 "Make sure the cursor is in a dataline in a table."
10990 (unless (save-excursion
10991 (beginning-of-line 1)
10992 (looking-at org-table-dataline-regexp))
10993 (let* ((re org-table-dataline-regexp)
10994 (p1 (save-excursion (re-search-forward re nil 'move)))
10995 (p2 (save-excursion (re-search-backward re nil 'move))))
10996 (cond ((and p1 p2)
10997 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
10998 p1 p2)))
10999 ((or p1 p2) (goto-char (or p1 p2)))
11000 (t (error "No table dataline around here"))))))
11002 (defun org-table-fedit-line-up ()
11003 "Move cursor one line up in the window showing the table."
11004 (interactive)
11005 (org-table-fedit-move 'previous-line))
11007 (defun org-table-fedit-line-down ()
11008 "Move cursor one line down in the window showing the table."
11009 (interactive)
11010 (org-table-fedit-move 'next-line))
11012 (defun org-table-fedit-move (command)
11013 "Move the cursor in the window shoinw the table.
11014 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
11015 (let ((org-table-allow-automatic-line-recalculation nil)
11016 (pos org-pos) (win (selected-window)) p)
11017 (select-window (get-buffer-window (marker-buffer org-pos)))
11018 (setq p (point))
11019 (call-interactively command)
11020 (while (and (org-at-table-p)
11021 (org-at-table-hline-p))
11022 (call-interactively command))
11023 (or (org-at-table-p) (goto-char p))
11024 (move-marker pos (point))
11025 (select-window win)))
11027 (defun org-table-fedit-scroll (N)
11028 (interactive "p")
11029 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
11030 (scroll-other-window N)))
11032 (defun org-table-fedit-scroll-down (N)
11033 (interactive "p")
11034 (org-table-fedit-scroll (- N)))
11036 (defvar org-table-rectangle-overlays nil)
11038 (defun org-table-add-rectangle-overlay (beg end &optional face)
11039 "Add a new overlay."
11040 (let ((ov (org-make-overlay beg end)))
11041 (org-overlay-put ov 'face (or face 'secondary-selection))
11042 (push ov org-table-rectangle-overlays)))
11044 (defun org-table-highlight-rectangle (&optional beg end face)
11045 "Highlight rectangular region in a table."
11046 (setq beg (or beg (point)) end (or end (point)))
11047 (let ((b (min beg end))
11048 (e (max beg end))
11049 l1 c1 l2 c2 tmp)
11050 (and (boundp 'org-show-positions)
11051 (setq org-show-positions (cons b (cons e org-show-positions))))
11052 (goto-char (min beg end))
11053 (setq l1 (org-current-line)
11054 c1 (org-table-current-column))
11055 (goto-char (max beg end))
11056 (setq l2 (org-current-line)
11057 c2 (org-table-current-column))
11058 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
11059 (goto-line l1)
11060 (beginning-of-line 1)
11061 (loop for line from l1 to l2 do
11062 (when (looking-at org-table-dataline-regexp)
11063 (org-table-goto-column c1)
11064 (skip-chars-backward "^|\n") (setq beg (point))
11065 (org-table-goto-column c2)
11066 (skip-chars-forward "^|\n") (setq end (point))
11067 (org-table-add-rectangle-overlay beg end face))
11068 (beginning-of-line 2))
11069 (goto-char b))
11070 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
11072 (defun org-table-remove-rectangle-highlight (&rest ignore)
11073 "Remove the rectangle overlays."
11074 (unless org-inhibit-highlight-removal
11075 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
11076 (mapc 'org-delete-overlay org-table-rectangle-overlays)
11077 (setq org-table-rectangle-overlays nil)))
11079 (defvar org-table-coordinate-overlays nil
11080 "Collects the cooordinate grid overlays, so that they can be removed.")
11081 (make-variable-buffer-local 'org-table-coordinate-overlays)
11083 (defun org-table-overlay-coordinates ()
11084 "Add overlays to the table at point, to show row/column coordinates."
11085 (interactive)
11086 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11087 (setq org-table-coordinate-overlays nil)
11088 (save-excursion
11089 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
11090 (goto-char (org-table-begin))
11091 (while (org-at-table-p)
11092 (setq eol (point-at-eol))
11093 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
11094 (push ov org-table-coordinate-overlays)
11095 (setq hline (looking-at org-table-hline-regexp))
11096 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
11097 (format "%4d" (setq id (1+ id)))))
11098 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
11099 (when hline
11100 (setq ic 0)
11101 (while (re-search-forward "[+|]\\(-+\\)" eol t)
11102 (setq beg (1+ (match-beginning 0))
11103 ic (1+ ic)
11104 s1 (concat "$" (int-to-string ic))
11105 s2 (org-number-to-letters ic)
11106 str (if (eq org-table-use-standard-references t) s2 s1))
11107 (setq ov (org-make-overlay beg (+ beg (length str))))
11108 (push ov org-table-coordinate-overlays)
11109 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
11110 (beginning-of-line 2)))))
11112 (defun org-table-toggle-coordinate-overlays ()
11113 "Toggle the display of Row/Column numbers in tables."
11114 (interactive)
11115 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
11116 (message "Row/Column number display turned %s"
11117 (if org-table-overlay-coordinates "on" "off"))
11118 (if (and (org-at-table-p) org-table-overlay-coordinates)
11119 (org-table-align))
11120 (unless org-table-overlay-coordinates
11121 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11122 (setq org-table-coordinate-overlays nil)))
11124 (defun org-table-toggle-formula-debugger ()
11125 "Toggle the formula debugger in tables."
11126 (interactive)
11127 (setq org-table-formula-debug (not org-table-formula-debug))
11128 (message "Formula debugging has been turned %s"
11129 (if org-table-formula-debug "on" "off")))
11131 ;;; The orgtbl minor mode
11133 ;; Define a minor mode which can be used in other modes in order to
11134 ;; integrate the org-mode table editor.
11136 ;; This is really a hack, because the org-mode table editor uses several
11137 ;; keys which normally belong to the major mode, for example the TAB and
11138 ;; RET keys. Here is how it works: The minor mode defines all the keys
11139 ;; necessary to operate the table editor, but wraps the commands into a
11140 ;; function which tests if the cursor is currently inside a table. If that
11141 ;; is the case, the table editor command is executed. However, when any of
11142 ;; those keys is used outside a table, the function uses `key-binding' to
11143 ;; look up if the key has an associated command in another currently active
11144 ;; keymap (minor modes, major mode, global), and executes that command.
11145 ;; There might be problems if any of the keys used by the table editor is
11146 ;; otherwise used as a prefix key.
11148 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11149 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11150 ;; addresses this by checking explicitly for both bindings.
11152 ;; The optimized version (see variable `orgtbl-optimized') takes over
11153 ;; all keys which are bound to `self-insert-command' in the *global map*.
11154 ;; Some modes bind other commands to simple characters, for example
11155 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11156 ;; active, this binding is ignored inside tables and replaced with a
11157 ;; modified self-insert.
11159 (defvar orgtbl-mode nil
11160 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11161 table editor in arbitrary modes.")
11162 (make-variable-buffer-local 'orgtbl-mode)
11164 (defvar orgtbl-mode-map (make-keymap)
11165 "Keymap for `orgtbl-mode'.")
11167 ;;;###autoload
11168 (defun turn-on-orgtbl ()
11169 "Unconditionally turn on `orgtbl-mode'."
11170 (orgtbl-mode 1))
11172 (defvar org-old-auto-fill-inhibit-regexp nil
11173 "Local variable used by `orgtbl-mode'")
11175 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
11176 "Matches a line belonging to an orgtbl.")
11178 (defconst orgtbl-extra-font-lock-keywords
11179 (list (list (concat "^" orgtbl-line-start-regexp ".*")
11180 0 (quote 'org-table) 'prepend))
11181 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
11183 ;;;###autoload
11184 (defun orgtbl-mode (&optional arg)
11185 "The `org-mode' table editor as a minor mode for use in other modes."
11186 (interactive)
11187 (if (org-mode-p)
11188 ;; Exit without error, in case some hook functions calls this
11189 ;; by accident in org-mode.
11190 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11191 (setq orgtbl-mode
11192 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11193 (if orgtbl-mode
11194 (progn
11195 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11196 ;; Make sure we are first in minor-mode-map-alist
11197 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11198 (and c (setq minor-mode-map-alist
11199 (cons c (delq c minor-mode-map-alist)))))
11200 (org-set-local (quote org-table-may-need-update) t)
11201 (org-add-hook 'before-change-functions 'org-before-change-function
11202 nil 'local)
11203 (org-set-local 'org-old-auto-fill-inhibit-regexp
11204 auto-fill-inhibit-regexp)
11205 (org-set-local 'auto-fill-inhibit-regexp
11206 (if auto-fill-inhibit-regexp
11207 (concat orgtbl-line-start-regexp "\\|"
11208 auto-fill-inhibit-regexp)
11209 orgtbl-line-start-regexp))
11210 (org-add-to-invisibility-spec '(org-cwidth))
11211 (when (fboundp 'font-lock-add-keywords)
11212 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11213 (org-restart-font-lock))
11214 (easy-menu-add orgtbl-mode-menu)
11215 (run-hooks 'orgtbl-mode-hook))
11216 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11217 (org-cleanup-narrow-column-properties)
11218 (org-remove-from-invisibility-spec '(org-cwidth))
11219 (remove-hook 'before-change-functions 'org-before-change-function t)
11220 (when (fboundp 'font-lock-remove-keywords)
11221 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11222 (org-restart-font-lock))
11223 (easy-menu-remove orgtbl-mode-menu)
11224 (force-mode-line-update 'all))))
11226 (defun org-cleanup-narrow-column-properties ()
11227 "Remove all properties related to narrow-column invisibility."
11228 (let ((s 1))
11229 (while (setq s (text-property-any s (point-max)
11230 'display org-narrow-column-arrow))
11231 (remove-text-properties s (1+ s) '(display t)))
11232 (setq s 1)
11233 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11234 (remove-text-properties s (1+ s) '(org-cwidth t)))
11235 (setq s 1)
11236 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11237 (remove-text-properties s (1+ s) '(invisible t)))))
11239 ;; Install it as a minor mode.
11240 (put 'orgtbl-mode :included t)
11241 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11242 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11244 (defun orgtbl-make-binding (fun n &rest keys)
11245 "Create a function for binding in the table minor mode.
11246 FUN is the command to call inside a table. N is used to create a unique
11247 command name. KEYS are keys that should be checked in for a command
11248 to execute outside of tables."
11249 (eval
11250 (list 'defun
11251 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11252 '(arg)
11253 (concat "In tables, run `" (symbol-name fun) "'.\n"
11254 "Outside of tables, run the binding of `"
11255 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11256 "'.")
11257 '(interactive "p")
11258 (list 'if
11259 '(org-at-table-p)
11260 (list 'call-interactively (list 'quote fun))
11261 (list 'let '(orgtbl-mode)
11262 (list 'call-interactively
11263 (append '(or)
11264 (mapcar (lambda (k)
11265 (list 'key-binding k))
11266 keys)
11267 '('orgtbl-error))))))))
11269 (defun orgtbl-error ()
11270 "Error when there is no default binding for a table key."
11271 (interactive)
11272 (error "This key has no function outside tables"))
11274 (defun orgtbl-setup ()
11275 "Setup orgtbl keymaps."
11276 (let ((nfunc 0)
11277 (bindings
11278 (list
11279 '([(meta shift left)] org-table-delete-column)
11280 '([(meta left)] org-table-move-column-left)
11281 '([(meta right)] org-table-move-column-right)
11282 '([(meta shift right)] org-table-insert-column)
11283 '([(meta shift up)] org-table-kill-row)
11284 '([(meta shift down)] org-table-insert-row)
11285 '([(meta up)] org-table-move-row-up)
11286 '([(meta down)] org-table-move-row-down)
11287 '("\C-c\C-w" org-table-cut-region)
11288 '("\C-c\M-w" org-table-copy-region)
11289 '("\C-c\C-y" org-table-paste-rectangle)
11290 '("\C-c-" org-table-insert-hline)
11291 '("\C-c}" org-table-toggle-coordinate-overlays)
11292 '("\C-c{" org-table-toggle-formula-debugger)
11293 '("\C-m" org-table-next-row)
11294 '([(shift return)] org-table-copy-down)
11295 '("\C-c\C-q" org-table-wrap-region)
11296 '("\C-c?" org-table-field-info)
11297 '("\C-c " org-table-blank-field)
11298 '("\C-c+" org-table-sum)
11299 '("\C-c=" org-table-eval-formula)
11300 '("\C-c'" org-table-edit-formulas)
11301 '("\C-c`" org-table-edit-field)
11302 '("\C-c*" org-table-recalculate)
11303 '("\C-c|" org-table-create-or-convert-from-region)
11304 '("\C-c^" org-table-sort-lines)
11305 '([(control ?#)] org-table-rotate-recalc-marks)))
11306 elt key fun cmd)
11307 (while (setq elt (pop bindings))
11308 (setq nfunc (1+ nfunc))
11309 (setq key (org-key (car elt))
11310 fun (nth 1 elt)
11311 cmd (orgtbl-make-binding fun nfunc key))
11312 (org-defkey orgtbl-mode-map key cmd))
11314 ;; Special treatment needed for TAB and RET
11315 (org-defkey orgtbl-mode-map [(return)]
11316 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11317 (org-defkey orgtbl-mode-map "\C-m"
11318 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11320 (org-defkey orgtbl-mode-map [(tab)]
11321 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11322 (org-defkey orgtbl-mode-map "\C-i"
11323 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11325 (org-defkey orgtbl-mode-map [(shift tab)]
11326 (orgtbl-make-binding 'org-table-previous-field 104
11327 [(shift tab)] [(tab)] "\C-i"))
11329 (org-defkey orgtbl-mode-map "\M-\C-m"
11330 (orgtbl-make-binding 'org-table-wrap-region 105
11331 "\M-\C-m" [(meta return)]))
11332 (org-defkey orgtbl-mode-map [(meta return)]
11333 (orgtbl-make-binding 'org-table-wrap-region 106
11334 [(meta return)] "\M-\C-m"))
11336 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11337 (when orgtbl-optimized
11338 ;; If the user wants maximum table support, we need to hijack
11339 ;; some standard editing functions
11340 (org-remap orgtbl-mode-map
11341 'self-insert-command 'orgtbl-self-insert-command
11342 'delete-char 'org-delete-char
11343 'delete-backward-char 'org-delete-backward-char)
11344 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11345 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11346 '("OrgTbl"
11347 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11348 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11349 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11350 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11351 "--"
11352 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11353 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11354 ["Copy Field from Above"
11355 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11356 "--"
11357 ("Column"
11358 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11359 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11360 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11361 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11362 ("Row"
11363 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11364 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11365 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11366 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11367 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
11368 "--"
11369 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11370 ("Rectangle"
11371 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11372 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11373 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11374 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11375 "--"
11376 ("Radio tables"
11377 ["Insert table template" orgtbl-insert-radio-table
11378 (assq major-mode orgtbl-radio-table-templates)]
11379 ["Comment/uncomment table" orgtbl-toggle-comment t])
11380 "--"
11381 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11382 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11383 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11384 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11385 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11386 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11387 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11388 ["Sum Column/Rectangle" org-table-sum
11389 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11390 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11391 ["Debug Formulas"
11392 org-table-toggle-formula-debugger :active (org-at-table-p)
11393 :keys "C-c {"
11394 :style toggle :selected org-table-formula-debug]
11395 ["Show Col/Row Numbers"
11396 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11397 :keys "C-c }"
11398 :style toggle :selected org-table-overlay-coordinates]
11402 (defun orgtbl-ctrl-c-ctrl-c (arg)
11403 "If the cursor is inside a table, realign the table.
11404 It it is a table to be sent away to a receiver, do it.
11405 With prefix arg, also recompute table."
11406 (interactive "P")
11407 (let ((pos (point)) action)
11408 (save-excursion
11409 (beginning-of-line 1)
11410 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11411 ((looking-at "[ \t]*|") pos)
11412 ((looking-at "#\\+TBLFM:") 'recalc))))
11413 (cond
11414 ((integerp action)
11415 (goto-char action)
11416 (org-table-maybe-eval-formula)
11417 (if arg
11418 (call-interactively 'org-table-recalculate)
11419 (org-table-maybe-recalculate-line))
11420 (call-interactively 'org-table-align)
11421 (orgtbl-send-table 'maybe))
11422 ((eq action 'recalc)
11423 (save-excursion
11424 (beginning-of-line 1)
11425 (skip-chars-backward " \r\n\t")
11426 (if (org-at-table-p)
11427 (org-call-with-arg 'org-table-recalculate t))))
11428 (t (let (orgtbl-mode)
11429 (call-interactively (key-binding "\C-c\C-c")))))))
11431 (defun orgtbl-tab (arg)
11432 "Justification and field motion for `orgtbl-mode'."
11433 (interactive "P")
11434 (if arg (org-table-edit-field t)
11435 (org-table-justify-field-maybe)
11436 (org-table-next-field)))
11438 (defun orgtbl-ret ()
11439 "Justification and field motion for `orgtbl-mode'."
11440 (interactive)
11441 (org-table-justify-field-maybe)
11442 (org-table-next-row))
11444 (defun orgtbl-self-insert-command (N)
11445 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11446 If the cursor is in a table looking at whitespace, the whitespace is
11447 overwritten, and the table is not marked as requiring realignment."
11448 (interactive "p")
11449 (if (and (org-at-table-p)
11451 (and org-table-auto-blank-field
11452 (member last-command
11453 '(orgtbl-hijacker-command-100
11454 orgtbl-hijacker-command-101
11455 orgtbl-hijacker-command-102
11456 orgtbl-hijacker-command-103
11457 orgtbl-hijacker-command-104
11458 orgtbl-hijacker-command-105))
11459 (org-table-blank-field))
11461 (eq N 1)
11462 (looking-at "[^|\n]* +|"))
11463 (let (org-table-may-need-update)
11464 (goto-char (1- (match-end 0)))
11465 (delete-backward-char 1)
11466 (goto-char (match-beginning 0))
11467 (self-insert-command N))
11468 (setq org-table-may-need-update t)
11469 (let (orgtbl-mode)
11470 (call-interactively (key-binding (vector last-input-event))))))
11472 (defun org-force-self-insert (N)
11473 "Needed to enforce self-insert under remapping."
11474 (interactive "p")
11475 (self-insert-command N))
11477 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11478 "Regula expression matching exponentials as produced by calc.")
11480 (defvar org-table-clean-did-remove-column nil)
11482 (defun orgtbl-export (table target)
11483 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11484 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11485 org-table-last-alignment org-table-last-column-widths
11486 maxcol column)
11487 (if (not (fboundp func))
11488 (error "Cannot export orgtbl table to %s" target))
11489 (setq lines (org-table-clean-before-export lines))
11490 (setq table
11491 (mapcar
11492 (lambda (x)
11493 (if (string-match org-table-hline-regexp x)
11494 'hline
11495 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11496 lines))
11497 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11498 table)))
11499 (loop for i from (1- maxcol) downto 0 do
11500 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11501 (setq column (delq nil column))
11502 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11503 (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))
11504 (funcall func table nil)))
11506 (defun orgtbl-send-table (&optional maybe)
11507 "Send a tranformed version of this table to the receiver position.
11508 With argument MAYBE, fail quietly if no transformation is defined for
11509 this table."
11510 (interactive)
11511 (catch 'exit
11512 (unless (org-at-table-p) (error "Not at a table"))
11513 ;; when non-interactive, we assume align has just happened.
11514 (when (interactive-p) (org-table-align))
11515 (save-excursion
11516 (goto-char (org-table-begin))
11517 (beginning-of-line 0)
11518 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11519 (if maybe
11520 (throw 'exit nil)
11521 (error "Don't know how to transform this table."))))
11522 (let* ((name (match-string 1))
11524 (transform (intern (match-string 2)))
11525 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11526 (skip (plist-get params :skip))
11527 (skipcols (plist-get params :skipcols))
11528 (txt (buffer-substring-no-properties
11529 (org-table-begin) (org-table-end)))
11530 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11531 (lines (org-table-clean-before-export lines))
11532 (i0 (if org-table-clean-did-remove-column 2 1))
11533 (table (mapcar
11534 (lambda (x)
11535 (if (string-match org-table-hline-regexp x)
11536 'hline
11537 (org-remove-by-index
11538 (org-split-string (org-trim x) "\\s-*|\\s-*")
11539 skipcols i0)))
11540 lines))
11541 (fun (if (= i0 2) 'cdr 'identity))
11542 (org-table-last-alignment
11543 (org-remove-by-index (funcall fun org-table-last-alignment)
11544 skipcols i0))
11545 (org-table-last-column-widths
11546 (org-remove-by-index (funcall fun org-table-last-column-widths)
11547 skipcols i0)))
11549 (unless (fboundp transform)
11550 (error "No such transformation function %s" transform))
11551 (setq txt (funcall transform table params))
11552 ;; Find the insertion place
11553 (save-excursion
11554 (goto-char (point-min))
11555 (unless (re-search-forward
11556 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11557 (error "Don't know where to insert translated table"))
11558 (goto-char (match-beginning 0))
11559 (beginning-of-line 2)
11560 (setq beg (point))
11561 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11562 (error "Cannot find end of insertion region"))
11563 (beginning-of-line 1)
11564 (delete-region beg (point))
11565 (goto-char beg)
11566 (insert txt "\n"))
11567 (message "Table converted and installed at receiver location"))))
11569 (defun org-remove-by-index (list indices &optional i0)
11570 "Remove the elements in LIST with indices in INDICES.
11571 First element has index 0, or I0 if given."
11572 (if (not indices)
11573 list
11574 (if (integerp indices) (setq indices (list indices)))
11575 (setq i0 (1- (or i0 0)))
11576 (delq :rm (mapcar (lambda (x)
11577 (setq i0 (1+ i0))
11578 (if (memq i0 indices) :rm x))
11579 list))))
11581 (defun orgtbl-toggle-comment ()
11582 "Comment or uncomment the orgtbl at point."
11583 (interactive)
11584 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11585 (re2 (concat "^" orgtbl-line-start-regexp))
11586 (commented (save-excursion (beginning-of-line 1)
11587 (cond ((looking-at re1) t)
11588 ((looking-at re2) nil)
11589 (t (error "Not at an org table")))))
11590 (re (if commented re1 re2))
11591 beg end)
11592 (save-excursion
11593 (beginning-of-line 1)
11594 (while (looking-at re) (beginning-of-line 0))
11595 (beginning-of-line 2)
11596 (setq beg (point))
11597 (while (looking-at re) (beginning-of-line 2))
11598 (setq end (point)))
11599 (comment-region beg end (if commented '(4) nil))))
11601 (defun orgtbl-insert-radio-table ()
11602 "Insert a radio table template appropriate for this major mode."
11603 (interactive)
11604 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11605 (txt (nth 1 e))
11606 name pos)
11607 (unless e (error "No radio table setup defined for %s" major-mode))
11608 (setq name (read-string "Table name: "))
11609 (while (string-match "%n" txt)
11610 (setq txt (replace-match name t t txt)))
11611 (or (bolp) (insert "\n"))
11612 (setq pos (point))
11613 (insert txt)
11614 (goto-char pos)))
11616 (defun org-get-param (params header i sym &optional hsym)
11617 "Get parameter value for symbol SYM.
11618 If this is a header line, actually get the value for the symbol with an
11619 additional \"h\" inserted after the colon.
11620 If the value is a protperty list, get the element for the current column.
11621 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11622 (let ((val (plist-get params sym)))
11623 (and hsym header (setq val (or (plist-get params hsym) val)))
11624 (if (consp val) (plist-get val i) val)))
11626 (defun orgtbl-to-generic (table params)
11627 "Convert the orgtbl-mode TABLE to some other format.
11628 This generic routine can be used for many standard cases.
11629 TABLE is a list, each entry either the symbol `hline' for a horizontal
11630 separator line, or a list of fields for that line.
11631 PARAMS is a property list of parameters that can influence the conversion.
11632 For the generic converter, some parameters are obligatory: You need to
11633 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11634 :splice, you must have :tstart and :tend.
11636 Valid parameters are
11638 :tstart String to start the table. Ignored when :splice is t.
11639 :tend String to end the table. Ignored when :splice is t.
11641 :splice When set to t, return only table body lines, don't wrap
11642 them into :tstart and :tend. Default is nil.
11644 :hline String to be inserted on horizontal separation lines.
11645 May be nil to ignore hlines.
11647 :lstart String to start a new table line.
11648 :lend String to end a table line
11649 :sep Separator between two fields
11650 :lfmt Format for entire line, with enough %s to capture all fields.
11651 If this is present, :lstart, :lend, and :sep are ignored.
11652 :fmt A format to be used to wrap the field, should contain
11653 %s for the original field value. For example, to wrap
11654 everything in dollars, you could use :fmt \"$%s$\".
11655 This may also be a property list with column numbers and
11656 formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11658 :hlstart :hlend :hlsep :hlfmt :hfmt
11659 Same as above, specific for the header lines in the table.
11660 All lines before the first hline are treated as header.
11661 If any of these is not present, the data line value is used.
11663 :efmt Use this format to print numbers with exponentials.
11664 The format should have %s twice for inserting mantissa
11665 and exponent, for example \"%s\\\\times10^{%s}\". This
11666 may also be a property list with column numbers and
11667 formats. :fmt will still be applied after :efmt.
11669 In addition to this, the parameters :skip and :skipcols are always handled
11670 directly by `orgtbl-send-table'. See manual."
11671 (interactive)
11672 (let* ((p params)
11673 (splicep (plist-get p :splice))
11674 (hline (plist-get p :hline))
11675 rtn line i fm efm lfmt h)
11677 ;; Do we have a header?
11678 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11679 (setq h t))
11681 ;; Put header
11682 (unless splicep
11683 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11685 ;; Now loop over all lines
11686 (while (setq line (pop table))
11687 (if (eq line 'hline)
11688 ;; A horizontal separator line
11689 (progn (if hline (push hline rtn))
11690 (setq h nil)) ; no longer in header
11691 ;; A normal line. Convert the fields, push line onto the result list
11692 (setq i 0)
11693 (setq line
11694 (mapcar
11695 (lambda (f)
11696 (setq i (1+ i)
11697 fm (org-get-param p h i :fmt :hfmt)
11698 efm (org-get-param p h i :efmt))
11699 (if (and efm (string-match orgtbl-exp-regexp f))
11700 (setq f (format
11701 efm (match-string 1 f) (match-string 2 f))))
11702 (if fm (setq f (format fm f)))
11704 line))
11705 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11706 (push (apply 'format lfmt line) rtn)
11707 (push (concat
11708 (org-get-param p h i :lstart :hlstart)
11709 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11710 (org-get-param p h i :lend :hlend))
11711 rtn))))
11713 (unless splicep
11714 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11716 (mapconcat 'identity (nreverse rtn) "\n")))
11718 (defun orgtbl-to-latex (table params)
11719 "Convert the orgtbl-mode TABLE to LaTeX.
11720 TABLE is a list, each entry either the symbol `hline' for a horizontal
11721 separator line, or a list of fields for that line.
11722 PARAMS is a property list of parameters that can influence the conversion.
11723 Supports all parameters from `orgtbl-to-generic'. Most important for
11724 LaTeX are:
11726 :splice When set to t, return only table body lines, don't wrap
11727 them into a tabular environment. Default is nil.
11729 :fmt A format to be used to wrap the field, should contain %s for the
11730 original field value. For example, to wrap everything in dollars,
11731 use :fmt \"$%s$\". This may also be a property list with column
11732 numbers and formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11734 :efmt Format for transforming numbers with exponentials. The format
11735 should have %s twice for inserting mantissa and exponent, for
11736 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11737 This may also be a property list with column numbers and formats.
11739 The general parameters :skip and :skipcols have already been applied when
11740 this function is called."
11741 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11742 org-table-last-alignment ""))
11743 (params2
11744 (list
11745 :tstart (concat "\\begin{tabular}{" alignment "}")
11746 :tend "\\end{tabular}"
11747 :lstart "" :lend " \\\\" :sep " & "
11748 :efmt "%s\\,(%s)" :hline "\\hline")))
11749 (orgtbl-to-generic table (org-combine-plists params2 params))))
11751 (defun orgtbl-to-html (table params)
11752 "Convert the orgtbl-mode TABLE to LaTeX.
11753 TABLE is a list, each entry either the symbol `hline' for a horizontal
11754 separator line, or a list of fields for that line.
11755 PARAMS is a property list of parameters that can influence the conversion.
11756 Currently this function recognizes the following parameters:
11758 :splice When set to t, return only table body lines, don't wrap
11759 them into a <table> environment. Default is nil.
11761 The general parameters :skip and :skipcols have already been applied when
11762 this function is called. The function does *not* use `orgtbl-to-generic',
11763 so you cannot specify parameters for it."
11764 (let* ((splicep (plist-get params :splice))
11765 html)
11766 ;; Just call the formatter we already have
11767 ;; We need to make text lines for it, so put the fields back together.
11768 (setq html (org-format-org-table-html
11769 (mapcar
11770 (lambda (x)
11771 (if (eq x 'hline)
11772 "|----+----|"
11773 (concat "| " (mapconcat 'identity x " | ") " |")))
11774 table)
11775 splicep))
11776 (if (string-match "\n+\\'" html)
11777 (setq html (replace-match "" t t html)))
11778 html))
11780 (defun orgtbl-to-texinfo (table params)
11781 "Convert the orgtbl-mode TABLE to TeXInfo.
11782 TABLE is a list, each entry either the symbol `hline' for a horizontal
11783 separator line, or a list of fields for that line.
11784 PARAMS is a property list of parameters that can influence the conversion.
11785 Supports all parameters from `orgtbl-to-generic'. Most important for
11786 TeXInfo are:
11788 :splice nil/t When set to t, return only table body lines, don't wrap
11789 them into a multitable environment. Default is nil.
11791 :fmt fmt A format to be used to wrap the field, should contain
11792 %s for the original field value. For example, to wrap
11793 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
11794 This may also be a property list with column numbers and
11795 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
11797 :cf \"f1 f2..\" The column fractions for the table. By default these
11798 are computed automatically from the width of the columns
11799 under org-mode.
11801 The general parameters :skip and :skipcols have already been applied when
11802 this function is called."
11803 (let* ((total (float (apply '+ org-table-last-column-widths)))
11804 (colfrac (or (plist-get params :cf)
11805 (mapconcat
11806 (lambda (x) (format "%.3f" (/ (float x) total)))
11807 org-table-last-column-widths " ")))
11808 (params2
11809 (list
11810 :tstart (concat "@multitable @columnfractions " colfrac)
11811 :tend "@end multitable"
11812 :lstart "@item " :lend "" :sep " @tab "
11813 :hlstart "@headitem ")))
11814 (orgtbl-to-generic table (org-combine-plists params2 params))))
11816 ;;;; Link Stuff
11818 ;;; Link abbreviations
11820 (defun org-link-expand-abbrev (link)
11821 "Apply replacements as defined in `org-link-abbrev-alist."
11822 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
11823 (let* ((key (match-string 1 link))
11824 (as (or (assoc key org-link-abbrev-alist-local)
11825 (assoc key org-link-abbrev-alist)))
11826 (tag (and (match-end 2) (match-string 3 link)))
11827 rpl)
11828 (if (not as)
11829 link
11830 (setq rpl (cdr as))
11831 (cond
11832 ((symbolp rpl) (funcall rpl tag))
11833 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
11834 (t (concat rpl tag)))))
11835 link))
11837 ;;; Storing and inserting links
11839 (defvar org-insert-link-history nil
11840 "Minibuffer history for links inserted with `org-insert-link'.")
11842 (defvar org-stored-links nil
11843 "Contains the links stored with `org-store-link'.")
11845 (defvar org-store-link-plist nil
11846 "Plist with info about the most recently link created with `org-store-link'.")
11848 (defvar org-link-protocols nil
11849 "Link protocols added to Org-mode using `org-add-link-type'.")
11851 (defvar org-store-link-functions nil
11852 "List of functions that are called to create and store a link.
11853 Each function will be called in turn until one returns a non-nil
11854 value. Each function should check if it is responsible for creating
11855 this link (for example by looking at the major mode).
11856 If not, it must exit and return nil.
11857 If yes, it should return a non-nil value after a calling
11858 `org-store-link-props' with a list of properties and values.
11859 Special properties are:
11861 :type The link prefix. like \"http\". This must be given.
11862 :link The link, like \"http://www.astro.uva.nl/~dominik\".
11863 This is obligatory as well.
11864 :description Optional default description for the second pair
11865 of brackets in an Org-mode link. The user can still change
11866 this when inserting this link into an Org-mode buffer.
11868 In addition to these, any additional properties can be specified
11869 and then used in remember templates.")
11871 (defun org-add-link-type (type &optional follow publish)
11872 "Add TYPE to the list of `org-link-types'.
11873 Re-compute all regular expressions depending on `org-link-types'
11874 FOLLOW and PUBLISH are two functions. Both take the link path as
11875 an argument.
11876 FOLLOW should do whatever is necessary to follow the link, for example
11877 to find a file or display a mail message.
11879 PUBLISH takes the path and retuns the string that should be used when
11880 this document is published. FIMXE: This is actually not yet implemented."
11881 (add-to-list 'org-link-types type t)
11882 (org-make-link-regexps)
11883 (add-to-list 'org-link-protocols
11884 (list type follow publish)))
11886 (defun org-add-agenda-custom-command (entry)
11887 "Replace or add a command in `org-agenda-custom-commands'.
11888 This is mostly for hacking and trying a new command - once the command
11889 works you probably want to add it to `org-agenda-custom-commands' for good."
11890 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
11891 (if ass
11892 (setcdr ass (cdr entry))
11893 (push entry org-agenda-custom-commands))))
11895 ;;;###autoload
11896 (defun org-store-link (arg)
11897 "\\<org-mode-map>Store an org-link to the current location.
11898 This link can later be inserted into an org-buffer with
11899 \\[org-insert-link].
11900 For some link types, a prefix arg is interpreted:
11901 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
11902 For file links, arg negates `org-context-in-file-links'."
11903 (interactive "P")
11904 (setq org-store-link-plist nil) ; reset
11905 (let (link cpltxt desc description search txt)
11906 (cond
11908 ((run-hook-with-args-until-success 'org-store-link-functions)
11909 (setq link (plist-get org-store-link-plist :link)
11910 desc (or (plist-get org-store-link-plist :description) link)))
11912 ((eq major-mode 'bbdb-mode)
11913 (let ((name (bbdb-record-name (bbdb-current-record)))
11914 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
11915 (setq cpltxt (concat "bbdb:" (or name company))
11916 link (org-make-link cpltxt))
11917 (org-store-link-props :type "bbdb" :name name :company company)))
11919 ((eq major-mode 'Info-mode)
11920 (setq link (org-make-link "info:"
11921 (file-name-nondirectory Info-current-file)
11922 ":" Info-current-node))
11923 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
11924 ":" Info-current-node))
11925 (org-store-link-props :type "info" :file Info-current-file
11926 :node Info-current-node))
11928 ((eq major-mode 'calendar-mode)
11929 (let ((cd (calendar-cursor-to-date)))
11930 (setq link
11931 (format-time-string
11932 (car org-time-stamp-formats)
11933 (apply 'encode-time
11934 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
11935 nil nil nil))))
11936 (org-store-link-props :type "calendar" :date cd)))
11938 ((or (eq major-mode 'vm-summary-mode)
11939 (eq major-mode 'vm-presentation-mode))
11940 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
11941 (vm-follow-summary-cursor)
11942 (save-excursion
11943 (vm-select-folder-buffer)
11944 (let* ((message (car vm-message-pointer))
11945 (folder buffer-file-name)
11946 (subject (vm-su-subject message))
11947 (to (vm-get-header-contents message "To"))
11948 (from (vm-get-header-contents message "From"))
11949 (message-id (vm-su-message-id message)))
11950 (org-store-link-props :type "vm" :from from :to to :subject subject
11951 :message-id message-id)
11952 (setq message-id (org-remove-angle-brackets message-id))
11953 (setq folder (abbreviate-file-name folder))
11954 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
11955 folder)
11956 (setq folder (replace-match "" t t folder)))
11957 (setq cpltxt (org-email-link-description))
11958 (setq link (org-make-link "vm:" folder "#" message-id)))))
11960 ((eq major-mode 'wl-summary-mode)
11961 (let* ((msgnum (wl-summary-message-number))
11962 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
11963 msgnum 'message-id))
11964 (wl-message-entity
11965 (if (fboundp 'elmo-message-entity)
11966 (elmo-message-entity
11967 wl-summary-buffer-elmo-folder msgnum)
11968 (elmo-msgdb-overview-get-entity
11969 msgnum (wl-summary-buffer-msgdb))))
11970 (from (wl-summary-line-from))
11971 (to (car (elmo-message-entity-field wl-message-entity 'to)))
11972 (subject (let (wl-thr-indent-string wl-parent-message-entity)
11973 (wl-summary-line-subject))))
11974 (org-store-link-props :type "wl" :from from :to to
11975 :subject subject :message-id message-id)
11976 (setq message-id (org-remove-angle-brackets message-id))
11977 (setq cpltxt (org-email-link-description))
11978 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
11979 "#" message-id))))
11981 ((or (equal major-mode 'mh-folder-mode)
11982 (equal major-mode 'mh-show-mode))
11983 (let ((from (org-mhe-get-header "From:"))
11984 (to (org-mhe-get-header "To:"))
11985 (message-id (org-mhe-get-header "Message-Id:"))
11986 (subject (org-mhe-get-header "Subject:")))
11987 (org-store-link-props :type "mh" :from from :to to
11988 :subject subject :message-id message-id)
11989 (setq cpltxt (org-email-link-description))
11990 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
11991 (org-remove-angle-brackets message-id)))))
11993 ((eq major-mode 'rmail-mode)
11994 (save-excursion
11995 (save-restriction
11996 (rmail-narrow-to-non-pruned-header)
11997 (let ((folder buffer-file-name)
11998 (message-id (mail-fetch-field "message-id"))
11999 (from (mail-fetch-field "from"))
12000 (to (mail-fetch-field "to"))
12001 (subject (mail-fetch-field "subject")))
12002 (org-store-link-props
12003 :type "rmail" :from from :to to
12004 :subject subject :message-id message-id)
12005 (setq message-id (org-remove-angle-brackets message-id))
12006 (setq cpltxt (org-email-link-description))
12007 (setq link (org-make-link "rmail:" folder "#" message-id))))))
12009 ((eq major-mode 'gnus-group-mode)
12010 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
12011 (gnus-group-group-name)) ; version
12012 ((fboundp 'gnus-group-name)
12013 (gnus-group-name))
12014 (t "???"))))
12015 (unless group (error "Not on a group"))
12016 (org-store-link-props :type "gnus" :group group)
12017 (setq cpltxt (concat
12018 (if (org-xor arg org-usenet-links-prefer-google)
12019 "http://groups.google.com/groups?group="
12020 "gnus:")
12021 group)
12022 link (org-make-link cpltxt))))
12024 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
12025 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
12026 (let* ((group gnus-newsgroup-name)
12027 (article (gnus-summary-article-number))
12028 (header (gnus-summary-article-header article))
12029 (from (mail-header-from header))
12030 (message-id (mail-header-id header))
12031 (date (mail-header-date header))
12032 (subject (gnus-summary-subject-string)))
12033 (org-store-link-props :type "gnus" :from from :subject subject
12034 :message-id message-id :group group)
12035 (setq cpltxt (org-email-link-description))
12036 (if (org-xor arg org-usenet-links-prefer-google)
12037 (setq link
12038 (concat
12039 cpltxt "\n "
12040 (format "http://groups.google.com/groups?as_umsgid=%s"
12041 (org-fixup-message-id-for-http message-id))))
12042 (setq link (org-make-link "gnus:" group
12043 "#" (number-to-string article))))))
12045 ((eq major-mode 'w3-mode)
12046 (setq cpltxt (url-view-url t)
12047 link (org-make-link cpltxt))
12048 (org-store-link-props :type "w3" :url (url-view-url t)))
12050 ((eq major-mode 'w3m-mode)
12051 (setq cpltxt (or w3m-current-title w3m-current-url)
12052 link (org-make-link w3m-current-url))
12053 (org-store-link-props :type "w3m" :url (url-view-url t)))
12055 ((setq search (run-hook-with-args-until-success
12056 'org-create-file-search-functions))
12057 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
12058 "::" search))
12059 (setq cpltxt (or description link)))
12061 ((eq major-mode 'image-mode)
12062 (setq cpltxt (concat "file:"
12063 (abbreviate-file-name buffer-file-name))
12064 link (org-make-link cpltxt))
12065 (org-store-link-props :type "image" :file buffer-file-name))
12067 ((eq major-mode 'dired-mode)
12068 ;; link to the file in the current line
12069 (setq cpltxt (concat "file:"
12070 (abbreviate-file-name
12071 (expand-file-name
12072 (dired-get-filename nil t))))
12073 link (org-make-link cpltxt)))
12075 ((and buffer-file-name (org-mode-p))
12076 ;; Just link to current headline
12077 (setq cpltxt (concat "file:"
12078 (abbreviate-file-name buffer-file-name)))
12079 ;; Add a context search string
12080 (when (org-xor org-context-in-file-links arg)
12081 ;; Check if we are on a target
12082 (if (org-in-regexp "<<\\(.*?\\)>>")
12083 (setq cpltxt (concat cpltxt "::" (match-string 1)))
12084 (setq txt (cond
12085 ((org-on-heading-p) nil)
12086 ((org-region-active-p)
12087 (buffer-substring (region-beginning) (region-end)))
12088 (t (buffer-substring (point-at-bol) (point-at-eol)))))
12089 (when (or (null txt) (string-match "\\S-" txt))
12090 (setq cpltxt
12091 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12092 desc "NONE"))))
12093 (if (string-match "::\\'" cpltxt)
12094 (setq cpltxt (substring cpltxt 0 -2)))
12095 (setq link (org-make-link cpltxt)))
12097 ((buffer-file-name (buffer-base-buffer))
12098 ;; Just link to this file here.
12099 (setq cpltxt (concat "file:"
12100 (abbreviate-file-name
12101 (buffer-file-name (buffer-base-buffer)))))
12102 ;; Add a context string
12103 (when (org-xor org-context-in-file-links arg)
12104 (setq txt (if (org-region-active-p)
12105 (buffer-substring (region-beginning) (region-end))
12106 (buffer-substring (point-at-bol) (point-at-eol))))
12107 ;; Only use search option if there is some text.
12108 (when (string-match "\\S-" txt)
12109 (setq cpltxt
12110 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12111 desc "NONE")))
12112 (setq link (org-make-link cpltxt)))
12114 ((interactive-p)
12115 (error "Cannot link to a buffer which is not visiting a file"))
12117 (t (setq link nil)))
12119 (if (consp link) (setq cpltxt (car link) link (cdr link)))
12120 (setq link (or link cpltxt)
12121 desc (or desc cpltxt))
12122 (if (equal desc "NONE") (setq desc nil))
12124 (if (and (interactive-p) link)
12125 (progn
12126 (setq org-stored-links
12127 (cons (list link desc) org-stored-links))
12128 (message "Stored: %s" (or desc link)))
12129 (and link (org-make-link-string link desc)))))
12131 (defun org-store-link-props (&rest plist)
12132 "Store link properties, extract names and addresses."
12133 (let (x adr)
12134 (when (setq x (plist-get plist :from))
12135 (setq adr (mail-extract-address-components x))
12136 (plist-put plist :fromname (car adr))
12137 (plist-put plist :fromaddress (nth 1 adr)))
12138 (when (setq x (plist-get plist :to))
12139 (setq adr (mail-extract-address-components x))
12140 (plist-put plist :toname (car adr))
12141 (plist-put plist :toaddress (nth 1 adr))))
12142 (let ((from (plist-get plist :from))
12143 (to (plist-get plist :to)))
12144 (when (and from to org-from-is-user-regexp)
12145 (plist-put plist :fromto
12146 (if (string-match org-from-is-user-regexp from)
12147 (concat "to %t")
12148 (concat "from %f")))))
12149 (setq org-store-link-plist plist))
12151 (defun org-email-link-description (&optional fmt)
12152 "Return the description part of an email link.
12153 This takes information from `org-store-link-plist' and formats it
12154 according to FMT (default from `org-email-link-description-format')."
12155 (setq fmt (or fmt org-email-link-description-format))
12156 (let* ((p org-store-link-plist)
12157 (to (plist-get p :toaddress))
12158 (from (plist-get p :fromaddress))
12159 (table
12160 (list
12161 (cons "%c" (plist-get p :fromto))
12162 (cons "%F" (plist-get p :from))
12163 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12164 (cons "%T" (plist-get p :to))
12165 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12166 (cons "%s" (plist-get p :subject))
12167 (cons "%m" (plist-get p :message-id)))))
12168 (when (string-match "%c" fmt)
12169 ;; Check if the user wrote this message
12170 (if (and org-from-is-user-regexp from to
12171 (save-match-data (string-match org-from-is-user-regexp from)))
12172 (setq fmt (replace-match "to %t" t t fmt))
12173 (setq fmt (replace-match "from %f" t t fmt))))
12174 (org-replace-escapes fmt table)))
12176 (defun org-make-org-heading-search-string (&optional string heading)
12177 "Make search string for STRING or current headline."
12178 (interactive)
12179 (let ((s (or string (org-get-heading))))
12180 (unless (and string (not heading))
12181 ;; We are using a headline, clean up garbage in there.
12182 (if (string-match org-todo-regexp s)
12183 (setq s (replace-match "" t t s)))
12184 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12185 (setq s (replace-match "" t t s)))
12186 (setq s (org-trim s))
12187 (if (string-match (concat "^\\(" org-quote-string "\\|"
12188 org-comment-string "\\)") s)
12189 (setq s (replace-match "" t t s)))
12190 (while (string-match org-ts-regexp s)
12191 (setq s (replace-match "" t t s))))
12192 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12193 (setq s (replace-match " " t t s)))
12194 (or string (setq s (concat "*" s))) ; Add * for headlines
12195 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12197 (defun org-make-link (&rest strings)
12198 "Concatenate STRINGS."
12199 (apply 'concat strings))
12201 (defun org-make-link-string (link &optional description)
12202 "Make a link with brackets, consisting of LINK and DESCRIPTION."
12203 (unless (string-match "\\S-" link)
12204 (error "Empty link"))
12205 (when (stringp description)
12206 ;; Remove brackets from the description, they are fatal.
12207 (while (string-match "\\[" description)
12208 (setq description (replace-match "{" t t description)))
12209 (while (string-match "\\]" description)
12210 (setq description (replace-match "}" t t description))))
12211 (when (equal (org-link-escape link) description)
12212 ;; No description needed, it is identical
12213 (setq description nil))
12214 (when (and (not description)
12215 (not (equal link (org-link-escape link))))
12216 (setq description link))
12217 (concat "[[" (org-link-escape link) "]"
12218 (if description (concat "[" description "]") "")
12219 "]"))
12221 (defconst org-link-escape-chars
12222 '((?\ . "%20")
12223 (?\[ . "%5B")
12224 (?\] . "%5D")
12225 (?\340 . "%E0") ; `a
12226 (?\342 . "%E2") ; ^a
12227 (?\347 . "%E7") ; ,c
12228 (?\350 . "%E8") ; `e
12229 (?\351 . "%E9") ; 'e
12230 (?\352 . "%EA") ; ^e
12231 (?\356 . "%EE") ; ^i
12232 (?\364 . "%F4") ; ^o
12233 (?\371 . "%F9") ; `u
12234 (?\373 . "%FB") ; ^u
12235 (?\; . "%3B")
12236 (?? . "%3F")
12237 (?= . "%3D")
12238 (?+ . "%2B")
12240 "Association list of escapes for some characters problematic in links.
12241 This is the list that is used for internal purposes.")
12243 (defconst org-link-escape-chars-browser
12244 '((?\ . "%20")) ; 32 for the SPC char
12245 "Association list of escapes for some characters problematic in links.
12246 This is the list that is used before handing over to the browser.")
12248 (defun org-link-escape (text &optional table)
12249 "Escape charaters in TEXT that are problematic for links."
12250 (setq table (or table org-link-escape-chars))
12251 (when text
12252 (let ((re (mapconcat (lambda (x) (regexp-quote
12253 (char-to-string (car x))))
12254 table "\\|")))
12255 (while (string-match re text)
12256 (setq text
12257 (replace-match
12258 (cdr (assoc (string-to-char (match-string 0 text))
12259 table))
12260 t t text)))
12261 text)))
12263 (defun org-link-unescape (text &optional table)
12264 "Reverse the action of `org-link-escape'."
12265 (setq table (or table org-link-escape-chars))
12266 (when text
12267 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12268 table "\\|")))
12269 (while (string-match re text)
12270 (setq text
12271 (replace-match
12272 (char-to-string (car (rassoc (match-string 0 text) table)))
12273 t t text)))
12274 text)))
12276 (defun org-xor (a b)
12277 "Exclusive or."
12278 (if a (not b) b))
12280 (defun org-get-header (header)
12281 "Find a header field in the current buffer."
12282 (save-excursion
12283 (goto-char (point-min))
12284 (let ((case-fold-search t) s)
12285 (cond
12286 ((eq header 'from)
12287 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12288 (setq s (match-string 1)))
12289 (while (string-match "\"" s)
12290 (setq s (replace-match "" t t s)))
12291 (if (string-match "[<(].*" s)
12292 (setq s (replace-match "" t t s))))
12293 ((eq header 'message-id)
12294 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12295 (setq s (match-string 1))))
12296 ((eq header 'subject)
12297 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12298 (setq s (match-string 1)))))
12299 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12300 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12301 s)))
12304 (defun org-fixup-message-id-for-http (s)
12305 "Replace special characters in a message id, so it can be used in an http query."
12306 (while (string-match "<" s)
12307 (setq s (replace-match "%3C" t t s)))
12308 (while (string-match ">" s)
12309 (setq s (replace-match "%3E" t t s)))
12310 (while (string-match "@" s)
12311 (setq s (replace-match "%40" t t s)))
12314 ;;;###autoload
12315 (defun org-insert-link-global ()
12316 "Insert a link like Org-mode does.
12317 This command can be called in any mode to insert a link in Org-mode syntax."
12318 (interactive)
12319 (org-run-like-in-org-mode 'org-insert-link))
12321 (defun org-insert-link (&optional complete-file)
12322 "Insert a link. At the prompt, enter the link.
12324 Completion can be used to select a link previously stored with
12325 `org-store-link'. When the empty string is entered (i.e. if you just
12326 press RET at the prompt), the link defaults to the most recently
12327 stored link. As SPC triggers completion in the minibuffer, you need to
12328 use M-SPC or C-q SPC to force the insertion of a space character.
12330 You will also be prompted for a description, and if one is given, it will
12331 be displayed in the buffer instead of the link.
12333 If there is already a link at point, this command will allow you to edit link
12334 and description parts.
12336 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12337 selected using completion. The path to the file will be relative to
12338 the current directory if the file is in the current directory or a
12339 subdirectory. Otherwise, the link will be the absolute path as
12340 completed in the minibuffer (i.e. normally ~/path/to/file).
12342 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12343 is in the current directory or below.
12344 With three \\[universal-argument] prefixes, negate the meaning of
12345 `org-keep-stored-link-after-insertion'."
12346 (interactive "P")
12347 (let* ((wcf (current-window-configuration))
12348 (region (if (org-region-active-p)
12349 (buffer-substring (region-beginning) (region-end))))
12350 (remove (and region (list (region-beginning) (region-end))))
12351 (desc region)
12352 tmphist ; byte-compile incorrectly complains about this
12353 link entry file)
12354 (cond
12355 ((org-in-regexp org-bracket-link-regexp 1)
12356 ;; We do have a link at point, and we are going to edit it.
12357 (setq remove (list (match-beginning 0) (match-end 0)))
12358 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12359 (setq link (read-string "Link: "
12360 (org-link-unescape
12361 (org-match-string-no-properties 1)))))
12362 ((or (org-in-regexp org-angle-link-re)
12363 (org-in-regexp org-plain-link-re))
12364 ;; Convert to bracket link
12365 (setq remove (list (match-beginning 0) (match-end 0))
12366 link (read-string "Link: "
12367 (org-remove-angle-brackets (match-string 0)))))
12368 ((equal complete-file '(4))
12369 ;; Completing read for file names.
12370 (setq file (read-file-name "File: "))
12371 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12372 (pwd1 (file-name-as-directory (abbreviate-file-name
12373 (expand-file-name ".")))))
12374 (cond
12375 ((equal complete-file '(16))
12376 (setq link (org-make-link
12377 "file:"
12378 (abbreviate-file-name (expand-file-name file)))))
12379 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12380 (setq link (org-make-link "file:" (match-string 1 file))))
12381 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12382 (expand-file-name file))
12383 (setq link (org-make-link
12384 "file:" (match-string 1 (expand-file-name file)))))
12385 (t (setq link (org-make-link "file:" file))))))
12387 ;; Read link, with completion for stored links.
12388 (with-output-to-temp-buffer "*Org Links*"
12389 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12390 (when org-stored-links
12391 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12392 (princ (mapconcat
12393 (lambda (x)
12394 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12395 (reverse org-stored-links) "\n"))))
12396 (let ((cw (selected-window)))
12397 (select-window (get-buffer-window "*Org Links*"))
12398 (shrink-window-if-larger-than-buffer)
12399 (setq truncate-lines t)
12400 (select-window cw))
12401 ;; Fake a link history, containing the stored links.
12402 (setq tmphist (append (mapcar 'car org-stored-links)
12403 org-insert-link-history))
12404 (unwind-protect
12405 (setq link (org-completing-read
12406 "Link: "
12407 (append
12408 (mapcar (lambda (x) (list (concat (car x) ":")))
12409 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12410 (mapcar (lambda (x) (list (concat x ":")))
12411 org-link-types))
12412 nil nil nil
12413 'tmphist
12414 (or (car (car org-stored-links)))))
12415 (set-window-configuration wcf)
12416 (kill-buffer "*Org Links*"))
12417 (setq entry (assoc link org-stored-links))
12418 (or entry (push link org-insert-link-history))
12419 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12420 (not org-keep-stored-link-after-insertion))
12421 (setq org-stored-links (delq (assoc link org-stored-links)
12422 org-stored-links)))
12423 (setq desc (or desc (nth 1 entry)))))
12425 (if (string-match org-plain-link-re link)
12426 ;; URL-like link, normalize the use of angular brackets.
12427 (setq link (org-make-link (org-remove-angle-brackets link))))
12429 ;; Check if we are linking to the current file with a search option
12430 ;; If yes, simplify the link by using only the search option.
12431 (when (and buffer-file-name
12432 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12433 (let* ((path (match-string 1 link))
12434 (case-fold-search nil)
12435 (search (match-string 2 link)))
12436 (save-match-data
12437 (if (equal (file-truename buffer-file-name) (file-truename path))
12438 ;; We are linking to this same file, with a search option
12439 (setq link search)))))
12441 ;; Check if we can/should use a relative path. If yes, simplify the link
12442 (when (string-match "\\<file:\\(.*\\)" link)
12443 (let* ((path (match-string 1 link))
12444 (origpath path)
12445 (desc-is-link (equal link desc))
12446 (case-fold-search nil))
12447 (cond
12448 ((eq org-link-file-path-type 'absolute)
12449 (setq path (abbreviate-file-name (expand-file-name path))))
12450 ((eq org-link-file-path-type 'noabbrev)
12451 (setq path (expand-file-name path)))
12452 ((eq org-link-file-path-type 'relative)
12453 (setq path (file-relative-name path)))
12455 (save-match-data
12456 (if (string-match (concat "^" (regexp-quote
12457 (file-name-as-directory
12458 (expand-file-name "."))))
12459 (expand-file-name path))
12460 ;; We are linking a file with relative path name.
12461 (setq path (substring (expand-file-name path)
12462 (match-end 0)))))))
12463 (setq link (concat "file:" path))
12464 (if (equal desc origpath)
12465 (setq desc path))))
12467 (setq desc (read-string "Description: " desc))
12468 (unless (string-match "\\S-" desc) (setq desc nil))
12469 (if remove (apply 'delete-region remove))
12470 (insert (org-make-link-string link desc))))
12472 (defun org-completing-read (&rest args)
12473 (let ((minibuffer-local-completion-map
12474 (copy-keymap minibuffer-local-completion-map)))
12475 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12476 (apply 'completing-read args)))
12478 ;;; Opening/following a link
12479 (defvar org-link-search-failed nil)
12481 (defun org-next-link ()
12482 "Move forward to the next link.
12483 If the link is in hidden text, expose it."
12484 (interactive)
12485 (when (and org-link-search-failed (eq this-command last-command))
12486 (goto-char (point-min))
12487 (message "Link search wrapped back to beginning of buffer"))
12488 (setq org-link-search-failed nil)
12489 (let* ((pos (point))
12490 (ct (org-context))
12491 (a (assoc :link ct)))
12492 (if a (goto-char (nth 2 a)))
12493 (if (re-search-forward org-any-link-re nil t)
12494 (progn
12495 (goto-char (match-beginning 0))
12496 (if (org-invisible-p) (org-show-context)))
12497 (goto-char pos)
12498 (setq org-link-search-failed t)
12499 (error "No further link found"))))
12501 (defun org-previous-link ()
12502 "Move backward to the previous link.
12503 If the link is in hidden text, expose it."
12504 (interactive)
12505 (when (and org-link-search-failed (eq this-command last-command))
12506 (goto-char (point-max))
12507 (message "Link search wrapped back to end of buffer"))
12508 (setq org-link-search-failed nil)
12509 (let* ((pos (point))
12510 (ct (org-context))
12511 (a (assoc :link ct)))
12512 (if a (goto-char (nth 1 a)))
12513 (if (re-search-backward org-any-link-re nil t)
12514 (progn
12515 (goto-char (match-beginning 0))
12516 (if (org-invisible-p) (org-show-context)))
12517 (goto-char pos)
12518 (setq org-link-search-failed t)
12519 (error "No further link found"))))
12521 (defun org-find-file-at-mouse (ev)
12522 "Open file link or URL at mouse."
12523 (interactive "e")
12524 (mouse-set-point ev)
12525 (org-open-at-point 'in-emacs))
12527 (defun org-open-at-mouse (ev)
12528 "Open file link or URL at mouse."
12529 (interactive "e")
12530 (mouse-set-point ev)
12531 (org-open-at-point))
12533 (defvar org-window-config-before-follow-link nil
12534 "The window configuration before following a link.
12535 This is saved in case the need arises to restore it.")
12537 (defvar org-open-link-marker (make-marker)
12538 "Marker pointing to the location where `org-open-at-point; was called.")
12540 ;;;###autoload
12541 (defun org-open-at-point-global ()
12542 "Follow a link like Org-mode does.
12543 This command can be called in any mode to follow a link that has
12544 Org-mode syntax."
12545 (interactive)
12546 (org-run-like-in-org-mode 'org-open-at-point))
12548 (defun org-open-at-point (&optional in-emacs)
12549 "Open link at or after point.
12550 If there is no link at point, this function will search forward up to
12551 the end of the current subtree.
12552 Normally, files will be opened by an appropriate application. If the
12553 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12554 (interactive "P")
12555 (catch 'abort
12556 (move-marker org-open-link-marker (point))
12557 (setq org-window-config-before-follow-link (current-window-configuration))
12558 (org-remove-occur-highlights nil nil t)
12559 (if (org-at-timestamp-p t)
12560 (org-follow-timestamp-link)
12561 (let (type path link line search (pos (point)))
12562 (catch 'match
12563 (save-excursion
12564 (skip-chars-forward "^]\n\r")
12565 (when (org-in-regexp org-bracket-link-regexp)
12566 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12567 (while (string-match " *\n *" link)
12568 (setq link (replace-match " " t t link)))
12569 (setq link (org-link-expand-abbrev link))
12570 (if (string-match org-link-re-with-space2 link)
12571 (setq type (match-string 1 link) path (match-string 2 link))
12572 (setq type "thisfile" path link))
12573 (throw 'match t)))
12575 (when (get-text-property (point) 'org-linked-text)
12576 (setq type "thisfile"
12577 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12578 (1+ (point)) (point))
12579 path (buffer-substring
12580 (previous-single-property-change pos 'org-linked-text)
12581 (next-single-property-change pos 'org-linked-text)))
12582 (throw 'match t))
12584 (save-excursion
12585 (when (or (org-in-regexp org-angle-link-re)
12586 (org-in-regexp org-plain-link-re))
12587 (setq type (match-string 1) path (match-string 2))
12588 (throw 'match t)))
12589 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12590 (setq type "tree-match"
12591 path (match-string 1))
12592 (throw 'match t))
12593 (save-excursion
12594 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12595 (setq type "tags"
12596 path (match-string 1))
12597 (while (string-match ":" path)
12598 (setq path (replace-match "+" t t path)))
12599 (throw 'match t))))
12600 (unless path
12601 (error "No link found"))
12602 ;; Remove any trailing spaces in path
12603 (if (string-match " +\\'" path)
12604 (setq path (replace-match "" t t path)))
12606 (cond
12608 ((assoc type org-link-protocols)
12609 (funcall (nth 1 (assoc type org-link-protocols)) path))
12611 ((equal type "mailto")
12612 (let ((cmd (car org-link-mailto-program))
12613 (args (cdr org-link-mailto-program)) args1
12614 (address path) (subject "") a)
12615 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12616 (setq address (match-string 1 path)
12617 subject (org-link-escape (match-string 2 path))))
12618 (while args
12619 (cond
12620 ((not (stringp (car args))) (push (pop args) args1))
12621 (t (setq a (pop args))
12622 (if (string-match "%a" a)
12623 (setq a (replace-match address t t a)))
12624 (if (string-match "%s" a)
12625 (setq a (replace-match subject t t a)))
12626 (push a args1))))
12627 (apply cmd (nreverse args1))))
12629 ((member type '("http" "https" "ftp" "news"))
12630 (browse-url (concat type ":" (org-link-escape
12631 path org-link-escape-chars-browser))))
12633 ((member type '("message"))
12634 (browse-url (concat type ":" path)))
12636 ((string= type "tags")
12637 (org-tags-view in-emacs path))
12638 ((string= type "thisfile")
12639 (if in-emacs
12640 (switch-to-buffer-other-window
12641 (org-get-buffer-for-internal-link (current-buffer)))
12642 (org-mark-ring-push))
12643 (let ((cmd `(org-link-search
12644 ,path
12645 ,(cond ((equal in-emacs '(4)) 'occur)
12646 ((equal in-emacs '(16)) 'org-occur)
12647 (t nil))
12648 ,pos)))
12649 (condition-case nil (eval cmd)
12650 (error (progn (widen) (eval cmd))))))
12652 ((string= type "tree-match")
12653 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12655 ((string= type "file")
12656 (if (string-match "::\\([0-9]+\\)\\'" path)
12657 (setq line (string-to-number (match-string 1 path))
12658 path (substring path 0 (match-beginning 0)))
12659 (if (string-match "::\\(.+\\)\\'" path)
12660 (setq search (match-string 1 path)
12661 path (substring path 0 (match-beginning 0)))))
12662 (if (string-match "[*?{]" (file-name-nondirectory path))
12663 (dired path)
12664 (org-open-file path in-emacs line search)))
12666 ((string= type "news")
12667 (org-follow-gnus-link path))
12669 ((string= type "bbdb")
12670 (org-follow-bbdb-link path))
12672 ((string= type "info")
12673 (org-follow-info-link path))
12675 ((string= type "gnus")
12676 (let (group article)
12677 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12678 (error "Error in Gnus link"))
12679 (setq group (match-string 1 path)
12680 article (match-string 3 path))
12681 (org-follow-gnus-link group article)))
12683 ((string= type "vm")
12684 (let (folder article)
12685 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12686 (error "Error in VM link"))
12687 (setq folder (match-string 1 path)
12688 article (match-string 3 path))
12689 ;; in-emacs is the prefix arg, will be interpreted as read-only
12690 (org-follow-vm-link folder article in-emacs)))
12692 ((string= type "wl")
12693 (let (folder article)
12694 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12695 (error "Error in Wanderlust link"))
12696 (setq folder (match-string 1 path)
12697 article (match-string 3 path))
12698 (org-follow-wl-link folder article)))
12700 ((string= type "mhe")
12701 (let (folder article)
12702 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12703 (error "Error in MHE link"))
12704 (setq folder (match-string 1 path)
12705 article (match-string 3 path))
12706 (org-follow-mhe-link folder article)))
12708 ((string= type "rmail")
12709 (let (folder article)
12710 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12711 (error "Error in RMAIL link"))
12712 (setq folder (match-string 1 path)
12713 article (match-string 3 path))
12714 (org-follow-rmail-link folder article)))
12716 ((string= type "shell")
12717 (let ((cmd path))
12718 (if (or (not org-confirm-shell-link-function)
12719 (funcall org-confirm-shell-link-function
12720 (format "Execute \"%s\" in shell? "
12721 (org-add-props cmd nil
12722 'face 'org-warning))))
12723 (progn
12724 (message "Executing %s" cmd)
12725 (shell-command cmd))
12726 (error "Abort"))))
12728 ((string= type "elisp")
12729 (let ((cmd path))
12730 (if (or (not org-confirm-elisp-link-function)
12731 (funcall org-confirm-elisp-link-function
12732 (format "Execute \"%s\" as elisp? "
12733 (org-add-props cmd nil
12734 'face 'org-warning))))
12735 (message "%s => %s" cmd (eval (read cmd)))
12736 (error "Abort"))))
12739 (browse-url-at-point)))))
12740 (move-marker org-open-link-marker nil)))
12742 ;;; File search
12744 (defvar org-create-file-search-functions nil
12745 "List of functions to construct the right search string for a file link.
12746 These functions are called in turn with point at the location to
12747 which the link should point.
12749 A function in the hook should first test if it would like to
12750 handle this file type, for example by checking the major-mode or
12751 the file extension. If it decides not to handle this file, it
12752 should just return nil to give other functions a chance. If it
12753 does handle the file, it must return the search string to be used
12754 when following the link. The search string will be part of the
12755 file link, given after a double colon, and `org-open-at-point'
12756 will automatically search for it. If special measures must be
12757 taken to make the search successful, another function should be
12758 added to the companion hook `org-execute-file-search-functions',
12759 which see.
12761 A function in this hook may also use `setq' to set the variable
12762 `description' to provide a suggestion for the descriptive text to
12763 be used for this link when it gets inserted into an Org-mode
12764 buffer with \\[org-insert-link].")
12766 (defvar org-execute-file-search-functions nil
12767 "List of functions to execute a file search triggered by a link.
12769 Functions added to this hook must accept a single argument, the
12770 search string that was part of the file link, the part after the
12771 double colon. The function must first check if it would like to
12772 handle this search, for example by checking the major-mode or the
12773 file extension. If it decides not to handle this search, it
12774 should just return nil to give other functions a chance. If it
12775 does handle the search, it must return a non-nil value to keep
12776 other functions from trying.
12778 Each function can access the current prefix argument through the
12779 variable `current-prefix-argument'. Note that a single prefix is
12780 used to force opening a link in Emacs, so it may be good to only
12781 use a numeric or double prefix to guide the search function.
12783 In case this is needed, a function in this hook can also restore
12784 the window configuration before `org-open-at-point' was called using:
12786 (set-window-configuration org-window-config-before-follow-link)")
12788 (defun org-link-search (s &optional type avoid-pos)
12789 "Search for a link search option.
12790 If S is surrounded by forward slashes, it is interpreted as a
12791 regular expression. In org-mode files, this will create an `org-occur'
12792 sparse tree. In ordinary files, `occur' will be used to list matches.
12793 If the current buffer is in `dired-mode', grep will be used to search
12794 in all files. If AVOID-POS is given, ignore matches near that position."
12795 (let ((case-fold-search t)
12796 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12797 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12798 (append '(("") (" ") ("\t") ("\n"))
12799 org-emphasis-alist)
12800 "\\|") "\\)"))
12801 (pos (point))
12802 (pre "") (post "")
12803 words re0 re1 re2 re3 re4 re5 re2a reall)
12804 (cond
12805 ;; First check if there are any special
12806 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12807 ;; Now try the builtin stuff
12808 ((save-excursion
12809 (goto-char (point-min))
12810 (and
12811 (re-search-forward
12812 (concat "<<" (regexp-quote s0) ">>") nil t)
12813 (setq pos (match-beginning 0))))
12814 ;; There is an exact target for this
12815 (goto-char pos))
12816 ((string-match "^/\\(.*\\)/$" s)
12817 ;; A regular expression
12818 (cond
12819 ((org-mode-p)
12820 (org-occur (match-string 1 s)))
12821 ;;((eq major-mode 'dired-mode)
12822 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12823 (t (org-do-occur (match-string 1 s)))))
12825 ;; A normal search strings
12826 (when (equal (string-to-char s) ?*)
12827 ;; Anchor on headlines, post may include tags.
12828 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
12829 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
12830 s (substring s 1)))
12831 (remove-text-properties
12832 0 (length s)
12833 '(face nil mouse-face nil keymap nil fontified nil) s)
12834 ;; Make a series of regular expressions to find a match
12835 (setq words (org-split-string s "[ \n\r\t]+")
12836 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
12837 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
12838 "\\)" markers)
12839 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
12840 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
12841 re1 (concat pre re2 post)
12842 re3 (concat pre re4 post)
12843 re5 (concat pre ".*" re4)
12844 re2 (concat pre re2)
12845 re2a (concat pre re2a)
12846 re4 (concat pre re4)
12847 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
12848 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
12849 re5 "\\)"
12851 (cond
12852 ((eq type 'org-occur) (org-occur reall))
12853 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
12854 (t (goto-char (point-min))
12855 (if (or (org-search-not-self 1 re0 nil t)
12856 (org-search-not-self 1 re1 nil t)
12857 (org-search-not-self 1 re2 nil t)
12858 (org-search-not-self 1 re2a nil t)
12859 (org-search-not-self 1 re3 nil t)
12860 (org-search-not-self 1 re4 nil t)
12861 (org-search-not-self 1 re5 nil t)
12863 (goto-char (match-beginning 1))
12864 (goto-char pos)
12865 (error "No match")))))
12867 ;; Normal string-search
12868 (goto-char (point-min))
12869 (if (search-forward s nil t)
12870 (goto-char (match-beginning 0))
12871 (error "No match"))))
12872 (and (org-mode-p) (org-show-context 'link-search))))
12874 (defun org-search-not-self (group &rest args)
12875 "Execute `re-search-forward', but only accept matches that do not
12876 enclose the position of `org-open-link-marker'."
12877 (let ((m org-open-link-marker))
12878 (catch 'exit
12879 (while (apply 're-search-forward args)
12880 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
12881 (goto-char (match-end group))
12882 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
12883 (> (match-beginning 0) (marker-position m))
12884 (< (match-end 0) (marker-position m)))
12885 (save-match-data
12886 (or (not (org-in-regexp
12887 org-bracket-link-analytic-regexp 1))
12888 (not (match-end 4)) ; no description
12889 (and (<= (match-beginning 4) (point))
12890 (>= (match-end 4) (point))))))
12891 (throw 'exit (point))))))))
12893 (defun org-get-buffer-for-internal-link (buffer)
12894 "Return a buffer to be used for displaying the link target of internal links."
12895 (cond
12896 ((not org-display-internal-link-with-indirect-buffer)
12897 buffer)
12898 ((string-match "(Clone)$" (buffer-name buffer))
12899 (message "Buffer is already a clone, not making another one")
12900 ;; we also do not modify visibility in this case
12901 buffer)
12902 (t ; make a new indirect buffer for displaying the link
12903 (let* ((bn (buffer-name buffer))
12904 (ibn (concat bn "(Clone)"))
12905 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
12906 (with-current-buffer ib (org-overview))
12907 ib))))
12909 (defun org-do-occur (regexp &optional cleanup)
12910 "Call the Emacs command `occur'.
12911 If CLEANUP is non-nil, remove the printout of the regular expression
12912 in the *Occur* buffer. This is useful if the regex is long and not useful
12913 to read."
12914 (occur regexp)
12915 (when cleanup
12916 (let ((cwin (selected-window)) win beg end)
12917 (when (setq win (get-buffer-window "*Occur*"))
12918 (select-window win))
12919 (goto-char (point-min))
12920 (when (re-search-forward "match[a-z]+" nil t)
12921 (setq beg (match-end 0))
12922 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
12923 (setq end (1- (match-beginning 0)))))
12924 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
12925 (goto-char (point-min))
12926 (select-window cwin))))
12928 ;;; The mark ring for links jumps
12930 (defvar org-mark-ring nil
12931 "Mark ring for positions before jumps in Org-mode.")
12932 (defvar org-mark-ring-last-goto nil
12933 "Last position in the mark ring used to go back.")
12934 ;; Fill and close the ring
12935 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
12936 (loop for i from 1 to org-mark-ring-length do
12937 (push (make-marker) org-mark-ring))
12938 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
12939 org-mark-ring)
12941 (defun org-mark-ring-push (&optional pos buffer)
12942 "Put the current position or POS into the mark ring and rotate it."
12943 (interactive)
12944 (setq pos (or pos (point)))
12945 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
12946 (move-marker (car org-mark-ring)
12947 (or pos (point))
12948 (or buffer (current-buffer)))
12949 (message "%s"
12950 (substitute-command-keys
12951 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
12953 (defun org-mark-ring-goto (&optional n)
12954 "Jump to the previous position in the mark ring.
12955 With prefix arg N, jump back that many stored positions. When
12956 called several times in succession, walk through the entire ring.
12957 Org-mode commands jumping to a different position in the current file,
12958 or to another Org-mode file, automatically push the old position
12959 onto the ring."
12960 (interactive "p")
12961 (let (p m)
12962 (if (eq last-command this-command)
12963 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
12964 (setq p org-mark-ring))
12965 (setq org-mark-ring-last-goto p)
12966 (setq m (car p))
12967 (switch-to-buffer (marker-buffer m))
12968 (goto-char m)
12969 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
12971 (defun org-remove-angle-brackets (s)
12972 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
12973 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
12975 (defun org-add-angle-brackets (s)
12976 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
12977 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
12980 ;;; Following specific links
12982 (defun org-follow-timestamp-link ()
12983 (cond
12984 ((org-at-date-range-p t)
12985 (let ((org-agenda-start-on-weekday)
12986 (t1 (match-string 1))
12987 (t2 (match-string 2)))
12988 (setq t1 (time-to-days (org-time-string-to-time t1))
12989 t2 (time-to-days (org-time-string-to-time t2)))
12990 (org-agenda-list nil t1 (1+ (- t2 t1)))))
12991 ((org-at-timestamp-p t)
12992 (org-agenda-list nil (time-to-days (org-time-string-to-time
12993 (substring (match-string 1) 0 10)))
12995 (t (error "This should not happen"))))
12998 (defun org-follow-bbdb-link (name)
12999 "Follow a BBDB link to NAME."
13000 (require 'bbdb)
13001 (let ((inhibit-redisplay (not debug-on-error))
13002 (bbdb-electric-p nil))
13003 (catch 'exit
13004 ;; Exact match on name
13005 (bbdb-name (concat "\\`" name "\\'") nil)
13006 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13007 ;; Exact match on name
13008 (bbdb-company (concat "\\`" name "\\'") nil)
13009 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13010 ;; Partial match on name
13011 (bbdb-name name nil)
13012 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13013 ;; Partial match on company
13014 (bbdb-company name nil)
13015 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13016 ;; General match including network address and notes
13017 (bbdb name nil)
13018 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
13019 (delete-window (get-buffer-window "*BBDB*"))
13020 (error "No matching BBDB record")))))
13022 (defun org-follow-info-link (name)
13023 "Follow an info file & node link to NAME."
13024 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
13025 (string-match "\\(.*\\)" name))
13026 (progn
13027 (require 'info)
13028 (if (match-string 2 name) ; If there isn't a node, choose "Top"
13029 (Info-find-node (match-string 1 name) (match-string 2 name))
13030 (Info-find-node (match-string 1 name) "Top")))
13031 (message "Could not open: %s" name)))
13033 (defun org-follow-gnus-link (&optional group article)
13034 "Follow a Gnus link to GROUP and ARTICLE."
13035 (require 'gnus)
13036 (funcall (cdr (assq 'gnus org-link-frame-setup)))
13037 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
13038 (cond ((and group article)
13039 (gnus-group-read-group 1 nil group)
13040 (gnus-summary-goto-article (string-to-number article) nil t))
13041 (group (gnus-group-jump-to-group group))))
13043 (defun org-follow-vm-link (&optional folder article readonly)
13044 "Follow a VM link to FOLDER and ARTICLE."
13045 (require 'vm)
13046 (setq article (org-add-angle-brackets article))
13047 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
13048 ;; ange-ftp or efs or tramp access
13049 (let ((user (or (match-string 1 folder) (user-login-name)))
13050 (host (match-string 2 folder))
13051 (file (match-string 3 folder)))
13052 (cond
13053 ((featurep 'tramp)
13054 ;; use tramp to access the file
13055 (if (featurep 'xemacs)
13056 (setq folder (format "[%s@%s]%s" user host file))
13057 (setq folder (format "/%s@%s:%s" user host file))))
13059 ;; use ange-ftp or efs
13060 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
13061 (setq folder (format "/%s@%s:%s" user host file))))))
13062 (when folder
13063 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
13064 (sit-for 0.1)
13065 (when article
13066 (vm-select-folder-buffer)
13067 (widen)
13068 (let ((case-fold-search t))
13069 (goto-char (point-min))
13070 (if (not (re-search-forward
13071 (concat "^" "message-id: *" (regexp-quote article))))
13072 (error "Could not find the specified message in this folder"))
13073 (vm-isearch-update)
13074 (vm-isearch-narrow)
13075 (vm-beginning-of-message)
13076 (vm-summarize)))))
13078 (defun org-follow-wl-link (folder article)
13079 "Follow a Wanderlust link to FOLDER and ARTICLE."
13080 (if (and (string= folder "%")
13081 article
13082 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
13083 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
13084 ;; Thus, we recompose folder and article ids.
13085 (setq folder (format "%s#%s" folder (match-string 1 article))
13086 article (match-string 3 article)))
13087 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
13088 (error "No such folder: %s" folder))
13089 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
13090 (and article
13091 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
13092 (wl-summary-redisplay)))
13094 (defun org-follow-rmail-link (folder article)
13095 "Follow an RMAIL link to FOLDER and ARTICLE."
13096 (setq article (org-add-angle-brackets article))
13097 (let (message-number)
13098 (save-excursion
13099 (save-window-excursion
13100 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13101 (setq message-number
13102 (save-restriction
13103 (widen)
13104 (goto-char (point-max))
13105 (if (re-search-backward
13106 (concat "^Message-ID:\\s-+" (regexp-quote
13107 (or article "")))
13108 nil t)
13109 (rmail-what-message))))))
13110 (if message-number
13111 (progn
13112 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13113 (rmail-show-message message-number)
13114 message-number)
13115 (error "Message not found"))))
13117 ;;; mh-e integration based on planner-mode
13118 (defun org-mhe-get-message-real-folder ()
13119 "Return the name of the current message real folder, so if you use
13120 sequences, it will now work."
13121 (save-excursion
13122 (let* ((folder
13123 (if (equal major-mode 'mh-folder-mode)
13124 mh-current-folder
13125 ;; Refer to the show buffer
13126 mh-show-folder-buffer))
13127 (end-index
13128 (if (boundp 'mh-index-folder)
13129 (min (length mh-index-folder) (length folder))))
13131 ;; a simple test on mh-index-data does not work, because
13132 ;; mh-index-data is always nil in a show buffer.
13133 (if (and (boundp 'mh-index-folder)
13134 (string= mh-index-folder (substring folder 0 end-index)))
13135 (if (equal major-mode 'mh-show-mode)
13136 (save-window-excursion
13137 (let (pop-up-frames)
13138 (when (buffer-live-p (get-buffer folder))
13139 (progn
13140 (pop-to-buffer folder)
13141 (org-mhe-get-message-folder-from-index)
13144 (org-mhe-get-message-folder-from-index)
13146 folder
13150 (defun org-mhe-get-message-folder-from-index ()
13151 "Returns the name of the message folder in a index folder buffer."
13152 (save-excursion
13153 (mh-index-previous-folder)
13154 (re-search-forward "^\\(+.*\\)$" nil t)
13155 (message "%s" (match-string 1))))
13157 (defun org-mhe-get-message-folder ()
13158 "Return the name of the current message folder. Be careful if you
13159 use sequences."
13160 (save-excursion
13161 (if (equal major-mode 'mh-folder-mode)
13162 mh-current-folder
13163 ;; Refer to the show buffer
13164 mh-show-folder-buffer)))
13166 (defun org-mhe-get-message-num ()
13167 "Return the number of the current message. Be careful if you
13168 use sequences."
13169 (save-excursion
13170 (if (equal major-mode 'mh-folder-mode)
13171 (mh-get-msg-num nil)
13172 ;; Refer to the show buffer
13173 (mh-show-buffer-message-number))))
13175 (defun org-mhe-get-header (header)
13176 "Return a header of the message in folder mode. This will create a
13177 show buffer for the corresponding message. If you have a more clever
13178 idea..."
13179 (let* ((folder (org-mhe-get-message-folder))
13180 (num (org-mhe-get-message-num))
13181 (buffer (get-buffer-create (concat "show-" folder)))
13182 (header-field))
13183 (with-current-buffer buffer
13184 (mh-display-msg num folder)
13185 (if (equal major-mode 'mh-folder-mode)
13186 (mh-header-display)
13187 (mh-show-header-display))
13188 (set-buffer buffer)
13189 (setq header-field (mh-get-header-field header))
13190 (if (equal major-mode 'mh-folder-mode)
13191 (mh-show)
13192 (mh-show-show))
13193 header-field)))
13195 (defun org-follow-mhe-link (folder article)
13196 "Follow an MHE link to FOLDER and ARTICLE.
13197 If ARTICLE is nil FOLDER is shown. If the configuration variable
13198 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
13199 ARTICLE is searched in all folders. Indexed searches (swish++,
13200 namazu, and others supported by MH-E) will always search in all
13201 folders."
13202 (require 'mh-e)
13203 (require 'mh-search)
13204 (require 'mh-utils)
13205 (mh-find-path)
13206 (if (not article)
13207 (mh-visit-folder (mh-normalize-folder-name folder))
13208 (setq article (org-add-angle-brackets article))
13209 (mh-search-choose)
13210 (if (equal mh-searcher 'pick)
13211 (progn
13212 (mh-search folder (list "--message-id" article))
13213 (when (and org-mhe-search-all-folders
13214 (not (org-mhe-get-message-real-folder)))
13215 (kill-this-buffer)
13216 (mh-search "+" (list "--message-id" article))))
13217 (mh-search "+" article))
13218 (if (org-mhe-get-message-real-folder)
13219 (mh-show-msg 1)
13220 (kill-this-buffer)
13221 (error "Message not found"))))
13223 ;;; BibTeX links
13225 ;; Use the custom search meachnism to construct and use search strings for
13226 ;; file links to BibTeX database entries.
13228 (defun org-create-file-search-in-bibtex ()
13229 "Create the search string and description for a BibTeX database entry."
13230 (when (eq major-mode 'bibtex-mode)
13231 ;; yes, we want to construct this search string.
13232 ;; Make a good description for this entry, using names, year and the title
13233 ;; Put it into the `description' variable which is dynamically scoped.
13234 (let ((bibtex-autokey-names 1)
13235 (bibtex-autokey-names-stretch 1)
13236 (bibtex-autokey-name-case-convert-function 'identity)
13237 (bibtex-autokey-name-separator " & ")
13238 (bibtex-autokey-additional-names " et al.")
13239 (bibtex-autokey-year-length 4)
13240 (bibtex-autokey-name-year-separator " ")
13241 (bibtex-autokey-titlewords 3)
13242 (bibtex-autokey-titleword-separator " ")
13243 (bibtex-autokey-titleword-case-convert-function 'identity)
13244 (bibtex-autokey-titleword-length 'infty)
13245 (bibtex-autokey-year-title-separator ": "))
13246 (setq description (bibtex-generate-autokey)))
13247 ;; Now parse the entry, get the key and return it.
13248 (save-excursion
13249 (bibtex-beginning-of-entry)
13250 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13252 (defun org-execute-file-search-in-bibtex (s)
13253 "Find the link search string S as a key for a database entry."
13254 (when (eq major-mode 'bibtex-mode)
13255 ;; Yes, we want to do the search in this file.
13256 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13257 (goto-char (point-min))
13258 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13259 (regexp-quote s) "[ \t\n]*,") nil t)
13260 (goto-char (match-beginning 0)))
13261 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13262 ;; Use double prefix to indicate that any web link should be browsed
13263 (let ((b (current-buffer)) (p (point)))
13264 ;; Restore the window configuration because we just use the web link
13265 (set-window-configuration org-window-config-before-follow-link)
13266 (save-excursion (set-buffer b) (goto-char p)
13267 (bibtex-url)))
13268 (recenter 0)) ; Move entry start to beginning of window
13269 ;; return t to indicate that the search is done.
13272 ;; Finally add the functions to the right hooks.
13273 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13274 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13276 ;; end of Bibtex link setup
13278 ;;; Following file links
13280 (defun org-open-file (path &optional in-emacs line search)
13281 "Open the file at PATH.
13282 First, this expands any special file name abbreviations. Then the
13283 configuration variable `org-file-apps' is checked if it contains an
13284 entry for this file type, and if yes, the corresponding command is launched.
13285 If no application is found, Emacs simply visits the file.
13286 With optional argument IN-EMACS, Emacs will visit the file.
13287 Optional LINE specifies a line to go to, optional SEARCH a string to
13288 search for. If LINE or SEARCH is given, the file will always be
13289 opened in Emacs.
13290 If the file does not exist, an error is thrown."
13291 (setq in-emacs (or in-emacs line search))
13292 (let* ((file (if (equal path "")
13293 buffer-file-name
13294 (substitute-in-file-name (expand-file-name path))))
13295 (apps (append org-file-apps (org-default-apps)))
13296 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13297 (dirp (if remp nil (file-directory-p file)))
13298 (dfile (downcase file))
13299 (old-buffer (current-buffer))
13300 (old-pos (point))
13301 (old-mode major-mode)
13302 ext cmd)
13303 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13304 (setq ext (match-string 1 dfile))
13305 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13306 (setq ext (match-string 1 dfile))))
13307 (if in-emacs
13308 (setq cmd 'emacs)
13309 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13310 (and dirp (cdr (assoc 'directory apps)))
13311 (cdr (assoc ext apps))
13312 (cdr (assoc t apps)))))
13313 (when (eq cmd 'mailcap)
13314 (require 'mailcap)
13315 (mailcap-parse-mailcaps)
13316 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13317 (command (mailcap-mime-info mime-type)))
13318 (if (stringp command)
13319 (setq cmd command)
13320 (setq cmd 'emacs))))
13321 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13322 (not (file-exists-p file))
13323 (not org-open-non-existing-files))
13324 (error "No such file: %s" file))
13325 (cond
13326 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13327 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13328 (while (string-match "['\"]%s['\"]" cmd)
13329 (setq cmd (replace-match "%s" t t cmd)))
13330 (while (string-match "%s" cmd)
13331 (setq cmd (replace-match
13332 (save-match-data (shell-quote-argument file))
13333 t t cmd)))
13334 (save-window-excursion
13335 (start-process-shell-command cmd nil cmd)))
13336 ((or (stringp cmd)
13337 (eq cmd 'emacs))
13338 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13339 (widen)
13340 (if line (goto-line line)
13341 (if search (org-link-search search))))
13342 ((consp cmd)
13343 (eval cmd))
13344 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13345 (and (org-mode-p) (eq old-mode 'org-mode)
13346 (or (not (equal old-buffer (current-buffer)))
13347 (not (equal old-pos (point))))
13348 (org-mark-ring-push old-pos old-buffer))))
13350 (defun org-default-apps ()
13351 "Return the default applications for this operating system."
13352 (cond
13353 ((eq system-type 'darwin)
13354 org-file-apps-defaults-macosx)
13355 ((eq system-type 'windows-nt)
13356 org-file-apps-defaults-windowsnt)
13357 (t org-file-apps-defaults-gnu)))
13359 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13360 (defun org-file-remote-p (file)
13361 "Test whether FILE specifies a location on a remote system.
13362 Return non-nil if the location is indeed remote.
13364 For example, the filename \"/user@host:/foo\" specifies a location
13365 on the system \"/user@host:\"."
13366 (cond ((fboundp 'file-remote-p)
13367 (file-remote-p file))
13368 ((fboundp 'tramp-handle-file-remote-p)
13369 (tramp-handle-file-remote-p file))
13370 ((and (boundp 'ange-ftp-name-format)
13371 (string-match (car ange-ftp-name-format) file))
13373 (t nil)))
13376 ;;;; Hooks for remember.el, and refiling
13378 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13379 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13381 ;;;###autoload
13382 (defun org-remember-insinuate ()
13383 "Setup remember.el for use wiht Org-mode."
13384 (require 'remember)
13385 (setq remember-annotation-functions '(org-remember-annotation))
13386 (setq remember-handler-functions '(org-remember-handler))
13387 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13389 ;;;###autoload
13390 (defun org-remember-annotation ()
13391 "Return a link to the current location as an annotation for remember.el.
13392 If you are using Org-mode files as target for data storage with
13393 remember.el, then the annotations should include a link compatible with the
13394 conventions in Org-mode. This function returns such a link."
13395 (org-store-link nil))
13397 (defconst org-remember-help
13398 "Select a destination location for the note.
13399 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13400 RET on headline -> Store as sublevel entry to current headline
13401 RET at beg-of-buf -> Append to file as level 2 headline
13402 <left>/<right> -> before/after current headline, same headings level")
13404 (defvar org-remember-previous-location nil)
13405 (defvar org-force-remember-template-char) ;; dynamically scoped
13407 (defun org-select-remember-template (&optional use-char)
13408 (when org-remember-templates
13409 (let* ((templates (mapcar (lambda (x)
13410 (if (stringp (car x))
13411 (append (list (nth 1 x) (car x)) (cddr x))
13412 (append (list (car x) "") (cdr x))))
13413 org-remember-templates))
13414 (char (or use-char
13415 (cond
13416 ((= (length templates) 1)
13417 (caar templates))
13418 ((and (boundp 'org-force-remember-template-char)
13419 org-force-remember-template-char)
13420 (if (stringp org-force-remember-template-char)
13421 (string-to-char org-force-remember-template-char)
13422 org-force-remember-template-char))
13424 (message "Select template: %s"
13425 (mapconcat
13426 (lambda (x)
13427 (cond
13428 ((not (string-match "\\S-" (nth 1 x)))
13429 (format "[%c]" (car x)))
13430 ((equal (downcase (car x))
13431 (downcase (aref (nth 1 x) 0)))
13432 (format "[%c]%s" (car x)
13433 (substring (nth 1 x) 1)))
13434 (t (format "[%c]%s" (car x) (nth 1 x)))))
13435 templates " "))
13436 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13437 (when (equal char0 ?\C-g)
13438 (jump-to-register remember-register)
13439 (kill-buffer remember-buffer))
13440 char0))))))
13441 (cddr (assoc char templates)))))
13443 (defvar x-last-selected-text)
13444 (defvar x-last-selected-text-primary)
13446 ;;;###autoload
13447 (defun org-remember-apply-template (&optional use-char skip-interactive)
13448 "Initialize *remember* buffer with template, invoke `org-mode'.
13449 This function should be placed into `remember-mode-hook' and in fact requires
13450 to be run from that hook to function properly."
13451 (if org-remember-templates
13452 (let* ((entry (org-select-remember-template use-char))
13453 (tpl (car entry))
13454 (plist-p (if org-store-link-plist t nil))
13455 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13456 (string-match "\\S-" (nth 1 entry)))
13457 (nth 1 entry)
13458 org-default-notes-file))
13459 (headline (nth 2 entry))
13460 (v-c (or (and (eq window-system 'x)
13461 (fboundp 'x-cut-buffer-or-selection-value)
13462 (x-cut-buffer-or-selection-value))
13463 (org-bound-and-true-p x-last-selected-text)
13464 (org-bound-and-true-p x-last-selected-text-primary)
13465 (and (> (length kill-ring) 0) (current-kill 0))))
13466 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13467 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13468 (v-u (concat "[" (substring v-t 1 -1) "]"))
13469 (v-U (concat "[" (substring v-T 1 -1) "]"))
13470 ;; `initial' and `annotation' are bound in `remember'
13471 (v-i (if (boundp 'initial) initial))
13472 (v-a (if (and (boundp 'annotation) annotation)
13473 (if (equal annotation "[[]]") "" annotation)
13474 ""))
13475 (v-A (if (and v-a
13476 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13477 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13478 v-a))
13479 (v-n user-full-name)
13480 (org-startup-folded nil)
13481 org-time-was-given org-end-time-was-given x
13482 prompt completions char time pos default histvar)
13483 (setq org-store-link-plist
13484 (append (list :annotation v-a :initial v-i)
13485 org-store-link-plist))
13486 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13487 (erase-buffer)
13488 (insert (substitute-command-keys
13489 (format
13490 "## Filing location: Select interactively, default, or last used:
13491 ## %s to select file and header location interactively.
13492 ## %s \"%s\" -> \"* %s\"
13493 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13494 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13495 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13496 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13497 (abbreviate-file-name (or file org-default-notes-file))
13498 (or headline "")
13499 (or (car org-remember-previous-location) "???")
13500 (or (cdr org-remember-previous-location) "???"))))
13501 (insert tpl) (goto-char (point-min))
13502 ;; Simple %-escapes
13503 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13504 (when (and initial (equal (match-string 0) "%i"))
13505 (save-match-data
13506 (let* ((lead (buffer-substring
13507 (point-at-bol) (match-beginning 0))))
13508 (setq v-i (mapconcat 'identity
13509 (org-split-string initial "\n")
13510 (concat "\n" lead))))))
13511 (replace-match
13512 (or (eval (intern (concat "v-" (match-string 1)))) "")
13513 t t))
13515 ;; %[] Insert contents of a file.
13516 (goto-char (point-min))
13517 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13518 (let ((start (match-beginning 0))
13519 (end (match-end 0))
13520 (filename (expand-file-name (match-string 1))))
13521 (goto-char start)
13522 (delete-region start end)
13523 (condition-case error
13524 (insert-file-contents filename)
13525 (error (insert (format "%%![Couldn't insert %s: %s]"
13526 filename error))))))
13527 ;; %() embedded elisp
13528 (goto-char (point-min))
13529 (while (re-search-forward "%\\((.+)\\)" nil t)
13530 (goto-char (match-beginning 0))
13531 (let ((template-start (point)))
13532 (forward-char 1)
13533 (let ((result
13534 (condition-case error
13535 (eval (read (current-buffer)))
13536 (error (format "%%![Error: %s]" error)))))
13537 (delete-region template-start (point))
13538 (insert result))))
13540 ;; From the property list
13541 (when plist-p
13542 (goto-char (point-min))
13543 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13544 (and (setq x (or (plist-get org-store-link-plist
13545 (intern (match-string 1))) ""))
13546 (replace-match x t t))))
13548 ;; Turn on org-mode in the remember buffer, set local variables
13549 (org-mode)
13550 (org-set-local 'org-finish-function 'org-remember-finalize)
13551 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13552 (org-set-local 'org-default-notes-file file))
13553 (if (and headline (stringp headline) (string-match "\\S-" headline))
13554 (org-set-local 'org-remember-default-headline headline))
13555 ;; Interactive template entries
13556 (goto-char (point-min))
13557 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGuUtT]\\)?" nil t)
13558 (setq char (if (match-end 3) (match-string 3))
13559 prompt (if (match-end 2) (match-string 2)))
13560 (goto-char (match-beginning 0))
13561 (replace-match "")
13562 (setq completions nil default nil)
13563 (when prompt
13564 (setq completions (org-split-string prompt "|")
13565 prompt (pop completions)
13566 default (car completions)
13567 histvar (intern (concat
13568 "org-remember-template-prompt-history::"
13569 (or prompt "")))
13570 completions (mapcar 'list completions)))
13571 (cond
13572 ((member char '("G" "g"))
13573 (let* ((org-last-tags-completion-table
13574 (org-global-tags-completion-table
13575 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13576 (org-add-colon-after-tag-completion t)
13577 (ins (completing-read
13578 (if prompt (concat prompt ": ") "Tags: ")
13579 'org-tags-completion-function nil nil nil
13580 'org-tags-history)))
13581 (setq ins (mapconcat 'identity
13582 (org-split-string ins (org-re "[^[:alnum:]_@]+"))
13583 ":"))
13584 (when (string-match "\\S-" ins)
13585 (or (equal (char-before) ?:) (insert ":"))
13586 (insert ins)
13587 (or (equal (char-after) ?:) (insert ":")))))
13588 (char
13589 (setq org-time-was-given (equal (upcase char) char))
13590 (setq time (org-read-date (equal (upcase char) "U") t nil
13591 prompt))
13592 (org-insert-time-stamp time org-time-was-given
13593 (member char '("u" "U"))
13594 nil nil (list org-end-time-was-given)))
13596 (insert (org-completing-read
13597 (concat (if prompt prompt "Enter string")
13598 (if default (concat " [" default "]"))
13599 ": ")
13600 completions nil nil nil histvar default)))))
13601 (goto-char (point-min))
13602 (if (re-search-forward "%\\?" nil t)
13603 (replace-match "")
13604 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13605 (org-mode)
13606 (org-set-local 'org-finish-function 'org-remember-finalize))
13607 (when (save-excursion
13608 (goto-char (point-min))
13609 (re-search-forward "%!" nil t))
13610 (replace-match "")
13611 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13613 (defun org-remember-finish-immediately ()
13614 "File remember note immediately.
13615 This should be run in `post-command-hook' and will remove itself
13616 from that hook."
13617 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13618 (when org-finish-function
13619 (funcall org-finish-function)))
13621 (defvar org-clock-marker) ; Defined below
13622 (defun org-remember-finalize ()
13623 "Finalize the remember process."
13624 (unless (fboundp 'remember-finalize)
13625 (defalias 'remember-finalize 'remember-buffer))
13626 (when (and org-clock-marker
13627 (equal (marker-buffer org-clock-marker) (current-buffer)))
13628 ;; FIXME: test this, this is w/o notetaking!
13629 (let (org-log-done) (org-clock-out)))
13630 (when buffer-file-name
13631 (save-buffer)
13632 (setq buffer-file-name nil))
13633 (remember-finalize))
13635 ;;;###autoload
13636 (defun org-remember (&optional goto org-force-remember-template-char)
13637 "Call `remember'. If this is already a remember buffer, re-apply template.
13638 If there is an active region, make sure remember uses it as initial content
13639 of the remember buffer.
13641 When called interactively with a `C-u' prefix argument GOTO, don't remember
13642 anything, just go to the file/headline where the selected template usually
13643 stores its notes. With a double prefix arg `C-u C-u', go to the last
13644 note stored by remember.
13646 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13647 associated with a template in `org-remember-templates'."
13648 (interactive "P")
13649 (cond
13650 ((equal goto '(4)) (org-go-to-remember-target))
13651 ((equal goto '(16)) (org-remember-goto-last-stored))
13653 (if (memq org-finish-function '(remember-buffer remember-finalize))
13654 (progn
13655 (when (< (length org-remember-templates) 2)
13656 (error "No other template available"))
13657 (erase-buffer)
13658 (let ((annotation (plist-get org-store-link-plist :annotation))
13659 (initial (plist-get org-store-link-plist :initial)))
13660 (org-remember-apply-template))
13661 (message "Press C-c C-c to remember data"))
13662 (if (org-region-active-p)
13663 (remember (buffer-substring (point) (mark)))
13664 (call-interactively 'remember))))))
13666 (defun org-remember-goto-last-stored ()
13667 "Go to the location where the last remember note was stored."
13668 (interactive)
13669 (bookmark-jump "org-remember-last-stored")
13670 (message "This is the last note stored by remember"))
13672 (defun org-go-to-remember-target (&optional template-key)
13673 "Go to the target location of a remember template.
13674 The user is queried for the template."
13675 (interactive)
13676 (let* ((entry (org-select-remember-template template-key))
13677 (file (nth 1 entry))
13678 (heading (nth 2 entry))
13679 visiting)
13680 (unless (and file (stringp file) (string-match "\\S-" file))
13681 (setq file org-default-notes-file))
13682 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13683 (setq heading org-remember-default-headline))
13684 (setq visiting (org-find-base-buffer-visiting file))
13685 (if (not visiting) (find-file-noselect file))
13686 (switch-to-buffer (or visiting (get-file-buffer file)))
13687 (widen)
13688 (goto-char (point-min))
13689 (if (re-search-forward
13690 (concat "^\\*+[ \t]+" (regexp-quote heading)
13691 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13692 nil t)
13693 (goto-char (match-beginning 0))
13694 (error "Target headline not found: %s" heading))))
13696 (defvar org-note-abort nil) ; dynamically scoped
13698 ;;;###autoload
13699 (defun org-remember-handler ()
13700 "Store stuff from remember.el into an org file.
13701 First prompts for an org file. If the user just presses return, the value
13702 of `org-default-notes-file' is used.
13703 Then the command offers the headings tree of the selected file in order to
13704 file the text at a specific location.
13705 You can either immediately press RET to get the note appended to the
13706 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13707 find a better place. Then press RET or <left> or <right> in insert the note.
13709 Key Cursor position Note gets inserted
13710 -----------------------------------------------------------------------------
13711 RET buffer-start as level 1 heading at end of file
13712 RET on headline as sublevel of the heading at cursor
13713 RET no heading at cursor position, level taken from context.
13714 Or use prefix arg to specify level manually.
13715 <left> on headline as same level, before current heading
13716 <right> on headline as same level, after current heading
13718 So the fastest way to store the note is to press RET RET to append it to
13719 the default file. This way your current train of thought is not
13720 interrupted, in accordance with the principles of remember.el.
13721 You can also get the fast execution without prompting by using
13722 C-u C-c C-c to exit the remember buffer. See also the variable
13723 `org-remember-store-without-prompt'.
13725 Before being stored away, the function ensures that the text has a
13726 headline, i.e. a first line that starts with a \"*\". If not, a headline
13727 is constructed from the current date and some additional data.
13729 If the variable `org-adapt-indentation' is non-nil, the entire text is
13730 also indented so that it starts in the same column as the headline
13731 \(i.e. after the stars).
13733 See also the variable `org-reverse-note-order'."
13734 (goto-char (point-min))
13735 (while (looking-at "^[ \t]*\n\\|^##.*\n")
13736 (replace-match ""))
13737 (goto-char (point-max))
13738 (beginning-of-line 1)
13739 (while (looking-at "[ \t]*$\\|##.*")
13740 (delete-region (1- (point)) (point-max))
13741 (beginning-of-line 1))
13742 (catch 'quit
13743 (if org-note-abort (throw 'quit nil))
13744 (let* ((txt (buffer-substring (point-min) (point-max)))
13745 (fastp (org-xor (equal current-prefix-arg '(4))
13746 org-remember-store-without-prompt))
13747 (file (cond
13748 (fastp org-default-notes-file)
13749 ((and (eq org-remember-interactive-interface 'refile)
13750 org-refile-targets)
13751 org-default-notes-file)
13752 ((not (and (equal current-prefix-arg '(16))
13753 org-remember-previous-location))
13754 (org-get-org-file))))
13755 (heading org-remember-default-headline)
13756 (visiting (and file (org-find-base-buffer-visiting file)))
13757 (org-startup-folded nil)
13758 (org-startup-align-all-tables nil)
13759 (org-goto-start-pos 1)
13760 spos exitcmd level indent reversed)
13761 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
13762 (setq file (car org-remember-previous-location)
13763 heading (cdr org-remember-previous-location)
13764 fastp t))
13765 (setq current-prefix-arg nil)
13766 (if (string-match "[ \t\n]+\\'" txt)
13767 (setq txt (replace-match "" t t txt)))
13768 ;; Modify text so that it becomes a nice subtree which can be inserted
13769 ;; into an org tree.
13770 (let* ((lines (split-string txt "\n"))
13771 first)
13772 (setq first (car lines) lines (cdr lines))
13773 (if (string-match "^\\*+ " first)
13774 ;; Is already a headline
13775 (setq indent nil)
13776 ;; We need to add a headline: Use time and first buffer line
13777 (setq lines (cons first lines)
13778 first (concat "* " (current-time-string)
13779 " (" (remember-buffer-desc) ")")
13780 indent " "))
13781 (if (and org-adapt-indentation indent)
13782 (setq lines (mapcar
13783 (lambda (x)
13784 (if (string-match "\\S-" x)
13785 (concat indent x) x))
13786 lines)))
13787 (setq txt (concat first "\n"
13788 (mapconcat 'identity lines "\n"))))
13789 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
13790 (setq txt (replace-match "\n\n" t t txt))
13791 (if (string-match "[ \t\n]*\\'" txt)
13792 (setq txt (replace-match "\n" t t txt))))
13793 ;; Put the modified text back into the remember buffer, for refile.
13794 (erase-buffer)
13795 (insert txt)
13796 (goto-char (point-min))
13797 (when (and (eq org-remember-interactive-interface 'refile)
13798 (not fastp))
13799 (org-refile nil (or visiting (find-file-noselect file)))
13800 (throw 'quit t))
13801 ;; Find the file
13802 (if (not visiting) (find-file-noselect file))
13803 (with-current-buffer (or visiting (get-file-buffer file))
13804 (unless (org-mode-p)
13805 (error "Target files for remember notes must be in Org-mode"))
13806 (save-excursion
13807 (save-restriction
13808 (widen)
13809 (and (goto-char (point-min))
13810 (not (re-search-forward "^\\* " nil t))
13811 (insert "\n* " (or heading "Notes") "\n"))
13812 (setq reversed (org-notes-order-reversed-p))
13814 ;; Find the default location
13815 (when (and heading (stringp heading) (string-match "\\S-" heading))
13816 (goto-char (point-min))
13817 (if (re-search-forward
13818 (concat "^\\*+[ \t]+" (regexp-quote heading)
13819 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13820 nil t)
13821 (setq org-goto-start-pos (match-beginning 0))
13822 (when fastp
13823 (goto-char (point-max))
13824 (unless (bolp) (newline))
13825 (insert "* " heading "\n")
13826 (setq org-goto-start-pos (point-at-bol 0)))))
13828 ;; Ask the User for a location, using the appropriate interface
13829 (cond
13830 (fastp (setq spos org-goto-start-pos
13831 exitcmd 'return))
13832 ((eq org-remember-interactive-interface 'outline)
13833 (setq spos (org-get-location (current-buffer)
13834 org-remember-help)
13835 exitcmd (cdr spos)
13836 spos (car spos)))
13837 ((eq org-remember-interactive-interface 'outline-path-completion)
13838 (let ((org-refile-targets '((nil . (:maxlevel . 10))))
13839 (org-refile-use-outline-path t))
13840 (setq spos (org-refile-get-location "Heading: ")
13841 exitcmd 'return
13842 spos (nth 3 spos))))
13843 (t (error "this should not hapen")))
13844 (if (not spos) (throw 'quit nil)) ; return nil to show we did
13845 ; not handle this note
13846 (goto-char spos)
13847 (cond ((org-on-heading-p t)
13848 (org-back-to-heading t)
13849 (setq level (funcall outline-level))
13850 (cond
13851 ((eq exitcmd 'return)
13852 ;; sublevel of current
13853 (setq org-remember-previous-location
13854 (cons (abbreviate-file-name file)
13855 (org-get-heading 'notags)))
13856 (if reversed
13857 (outline-next-heading)
13858 (org-end-of-subtree t)
13859 (if (not (bolp))
13860 (if (looking-at "[ \t]*\n")
13861 (beginning-of-line 2)
13862 (end-of-line 1)
13863 (insert "\n"))))
13864 (bookmark-set "org-remember-last-stored")
13865 (org-paste-subtree (org-get-legal-level level 1) txt))
13866 ((eq exitcmd 'left)
13867 ;; before current
13868 (bookmark-set "org-remember-last-stored")
13869 (org-paste-subtree level txt))
13870 ((eq exitcmd 'right)
13871 ;; after current
13872 (org-end-of-subtree t)
13873 (bookmark-set "org-remember-last-stored")
13874 (org-paste-subtree level txt))
13875 (t (error "This should not happen"))))
13877 ((and (bobp) (not reversed))
13878 ;; Put it at the end, one level below level 1
13879 (save-restriction
13880 (widen)
13881 (goto-char (point-max))
13882 (if (not (bolp)) (newline))
13883 (bookmark-set "org-remember-last-stored")
13884 (org-paste-subtree (org-get-legal-level 1 1) txt)))
13886 ((and (bobp) reversed)
13887 ;; Put it at the start, as level 1
13888 (save-restriction
13889 (widen)
13890 (goto-char (point-min))
13891 (re-search-forward "^\\*+ " nil t)
13892 (beginning-of-line 1)
13893 (bookmark-set "org-remember-last-stored")
13894 (org-paste-subtree 1 txt)))
13896 ;; Put it right there, with automatic level determined by
13897 ;; org-paste-subtree or from prefix arg
13898 (bookmark-set "org-remember-last-stored")
13899 (org-paste-subtree
13900 (if (numberp current-prefix-arg) current-prefix-arg)
13901 txt)))
13902 (when remember-save-after-remembering
13903 (save-buffer)
13904 (if (not visiting) (kill-buffer (current-buffer)))))))))
13906 t) ;; return t to indicate that we took care of this note.
13908 (defun org-get-org-file ()
13909 "Read a filename, with default directory `org-directory'."
13910 (let ((default (or org-default-notes-file remember-data-file)))
13911 (read-file-name (format "File name [%s]: " default)
13912 (file-name-as-directory org-directory)
13913 default)))
13915 (defun org-notes-order-reversed-p ()
13916 "Check if the current file should receive notes in reversed order."
13917 (cond
13918 ((not org-reverse-note-order) nil)
13919 ((eq t org-reverse-note-order) t)
13920 ((not (listp org-reverse-note-order)) nil)
13921 (t (catch 'exit
13922 (let ((all org-reverse-note-order)
13923 entry)
13924 (while (setq entry (pop all))
13925 (if (string-match (car entry) buffer-file-name)
13926 (throw 'exit (cdr entry))))
13927 nil)))))
13929 ;;; Refiling
13931 (defvar org-refile-target-table nil
13932 "The list of refile targets, created by `org-refile'.")
13934 (defvar org-agenda-new-buffers nil
13935 "Buffers created to visit agenda files.")
13937 (defun org-get-refile-targets (&optional default-buffer)
13938 "Produce a table with refile targets."
13939 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
13940 targets txt re files f desc descre)
13941 (with-current-buffer (or default-buffer (current-buffer))
13942 (while (setq entry (pop entries))
13943 (setq files (car entry) desc (cdr entry))
13944 (cond
13945 ((null files) (setq files (list (current-buffer))))
13946 ((eq files 'org-agenda-files)
13947 (setq files (org-agenda-files 'unrestricted)))
13948 ((and (symbolp files) (fboundp files))
13949 (setq files (funcall files)))
13950 ((and (symbolp files) (boundp files))
13951 (setq files (symbol-value files))))
13952 (if (stringp files) (setq files (list files)))
13953 (cond
13954 ((eq (car desc) :tag)
13955 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
13956 ((eq (car desc) :todo)
13957 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
13958 ((eq (car desc) :regexp)
13959 (setq descre (cdr desc)))
13960 ((eq (car desc) :level)
13961 (setq descre (concat "^\\*\\{" (number-to-string
13962 (if org-odd-levels-only
13963 (1- (* 2 (cdr desc)))
13964 (cdr desc)))
13965 "\\}[ \t]")))
13966 ((eq (car desc) :maxlevel)
13967 (setq descre (concat "^\\*\\{1," (number-to-string
13968 (if org-odd-levels-only
13969 (1- (* 2 (cdr desc)))
13970 (cdr desc)))
13971 "\\}[ \t]")))
13972 (t (error "Bad refiling target description %s" desc)))
13973 (while (setq f (pop files))
13974 (save-excursion
13975 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
13976 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
13977 (save-excursion
13978 (save-restriction
13979 (widen)
13980 (goto-char (point-min))
13981 (while (re-search-forward descre nil t)
13982 (goto-char (point-at-bol))
13983 (when (looking-at org-complex-heading-regexp)
13984 (setq txt (match-string 4)
13985 re (concat "^" (regexp-quote
13986 (buffer-substring (match-beginning 1)
13987 (match-end 4)))))
13988 (if (match-end 5) (setq re (concat re "[ \t]+"
13989 (regexp-quote
13990 (match-string 5)))))
13991 (setq re (concat re "[ \t]*$"))
13992 (when org-refile-use-outline-path
13993 (setq txt (mapconcat 'identity
13994 (append
13995 (if (eq org-refile-use-outline-path 'file)
13996 (list (file-name-nondirectory
13997 (buffer-file-name (buffer-base-buffer))))
13998 (if (eq org-refile-use-outline-path 'full-file-path)
13999 (list (buffer-file-name (buffer-base-buffer)))))
14000 (org-get-outline-path)
14001 (list txt))
14002 "/")))
14003 (push (list txt f re (point)) targets))
14004 (goto-char (point-at-eol))))))))
14005 (nreverse targets))))
14007 (defun org-get-outline-path ()
14008 "Return the outline path to the current entry, as a list."
14009 (let (rtn)
14010 (save-excursion
14011 (while (org-up-heading-safe)
14012 (when (looking-at org-complex-heading-regexp)
14013 (push (org-match-string-no-properties 4) rtn)))
14014 rtn)))
14016 (defvar org-refile-history nil
14017 "History for refiling operations.")
14019 (defun org-refile (&optional goto default-buffer)
14020 "Move the entry at point to another heading.
14021 The list of target headings is compiled using the information in
14022 `org-refile-targets', which see. This list is created upon first use, and
14023 you can update it by calling this command with a double prefix (`C-u C-u').
14024 FIXME: Can we find a better way of updating?
14026 At the target location, the entry is filed as a subitem of the target heading.
14027 Depending on `org-reverse-note-order', the new subitem will either be the
14028 first of the last subitem.
14030 With prefix arg GOTO, the command will only visit the target location,
14031 not actually move anything.
14032 With a double prefix `C-c C-c', go to the location where the last refiling
14033 operation has put the subtree.
14035 With a double prefix argument, the command can be used to jump to any
14036 heading in the current buffer."
14037 (interactive "P")
14038 (let* ((cbuf (current-buffer))
14039 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14040 (fname (and filename (file-truename filename)))
14041 pos it nbuf file re level reversed)
14042 (if (equal goto '(16))
14043 (org-refile-goto-last-stored)
14044 (when (setq it (org-refile-get-location
14045 (if goto "Goto: " "Refile to: ") default-buffer))
14046 (setq file (nth 1 it)
14047 re (nth 2 it)
14048 pos (nth 3 it))
14049 (setq nbuf (or (find-buffer-visiting file)
14050 (find-file-noselect file)))
14051 (if goto
14052 (progn
14053 (switch-to-buffer nbuf)
14054 (goto-char pos)
14055 (org-show-context 'org-goto))
14056 (org-copy-special)
14057 (save-excursion
14058 (set-buffer (setq nbuf (or (find-buffer-visiting file)
14059 (find-file-noselect file))))
14060 (setq reversed (org-notes-order-reversed-p))
14061 (save-excursion
14062 (save-restriction
14063 (widen)
14064 (goto-char pos)
14065 (looking-at outline-regexp)
14066 (setq level (org-get-legal-level (funcall outline-level) 1))
14067 (goto-char
14068 (if reversed
14069 (outline-next-heading)
14070 (or (save-excursion (outline-get-next-sibling))
14071 (org-end-of-subtree t t)
14072 (point-max))))
14073 (bookmark-set "org-refile-last-stored")
14074 (org-paste-subtree level))))
14075 (org-cut-special)
14076 (message "Entry refiled to \"%s\"" (car it)))))))
14078 (defun org-refile-goto-last-stored ()
14079 "Go to the location where the last refile was stored."
14080 (interactive)
14081 (bookmark-jump "org-refile-last-stored")
14082 (message "This is the location of the last refile"))
14084 (defun org-refile-get-location (&optional prompt default-buffer)
14085 "Prompt the user for a refile location, using PROMPT."
14086 (let ((org-refile-targets org-refile-targets)
14087 (org-refile-use-outline-path org-refile-use-outline-path))
14088 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
14089 (unless org-refile-target-table
14090 (error "No refile targets"))
14091 (let* ((cbuf (current-buffer))
14092 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14093 (fname (and filename (file-truename filename)))
14094 (tbl (mapcar
14095 (lambda (x)
14096 (if (not (equal fname (file-truename (nth 1 x))))
14097 (cons (concat (car x) " (" (file-name-nondirectory
14098 (nth 1 x)) ")")
14099 (cdr x))
14101 org-refile-target-table))
14102 (completion-ignore-case t)
14103 pos it nbuf file re level reversed)
14104 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
14105 tbl)))
14107 ;;;; Dynamic blocks
14109 (defun org-find-dblock (name)
14110 "Find the first dynamic block with name NAME in the buffer.
14111 If not found, stay at current position and return nil."
14112 (let (pos)
14113 (save-excursion
14114 (goto-char (point-min))
14115 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
14116 nil t)
14117 (match-beginning 0))))
14118 (if pos (goto-char pos))
14119 pos))
14121 (defconst org-dblock-start-re
14122 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
14123 "Matches the startline of a dynamic block, with parameters.")
14125 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
14126 "Matches the end of a dyhamic block.")
14128 (defun org-create-dblock (plist)
14129 "Create a dynamic block section, with parameters taken from PLIST.
14130 PLIST must containe a :name entry which is used as name of the block."
14131 (unless (bolp) (newline))
14132 (let ((name (plist-get plist :name)))
14133 (insert "#+BEGIN: " name)
14134 (while plist
14135 (if (eq (car plist) :name)
14136 (setq plist (cddr plist))
14137 (insert " " (prin1-to-string (pop plist)))))
14138 (insert "\n\n#+END:\n")
14139 (beginning-of-line -2)))
14141 (defun org-prepare-dblock ()
14142 "Prepare dynamic block for refresh.
14143 This empties the block, puts the cursor at the insert position and returns
14144 the property list including an extra property :name with the block name."
14145 (unless (looking-at org-dblock-start-re)
14146 (error "Not at a dynamic block"))
14147 (let* ((begdel (1+ (match-end 0)))
14148 (name (org-no-properties (match-string 1)))
14149 (params (append (list :name name)
14150 (read (concat "(" (match-string 3) ")")))))
14151 (unless (re-search-forward org-dblock-end-re nil t)
14152 (error "Dynamic block not terminated"))
14153 (delete-region begdel (match-beginning 0))
14154 (goto-char begdel)
14155 (open-line 1)
14156 params))
14158 (defun org-map-dblocks (&optional command)
14159 "Apply COMMAND to all dynamic blocks in the current buffer.
14160 If COMMAND is not given, use `org-update-dblock'."
14161 (let ((cmd (or command 'org-update-dblock))
14162 pos)
14163 (save-excursion
14164 (goto-char (point-min))
14165 (while (re-search-forward org-dblock-start-re nil t)
14166 (goto-char (setq pos (match-beginning 0)))
14167 (condition-case nil
14168 (funcall cmd)
14169 (error (message "Error during update of dynamic block")))
14170 (goto-char pos)
14171 (unless (re-search-forward org-dblock-end-re nil t)
14172 (error "Dynamic block not terminated"))))))
14174 (defun org-dblock-update (&optional arg)
14175 "User command for updating dynamic blocks.
14176 Update the dynamic block at point. With prefix ARG, update all dynamic
14177 blocks in the buffer."
14178 (interactive "P")
14179 (if arg
14180 (org-update-all-dblocks)
14181 (or (looking-at org-dblock-start-re)
14182 (org-beginning-of-dblock))
14183 (org-update-dblock)))
14185 (defun org-update-dblock ()
14186 "Update the dynamic block at point
14187 This means to empty the block, parse for parameters and then call
14188 the correct writing function."
14189 (save-window-excursion
14190 (let* ((pos (point))
14191 (line (org-current-line))
14192 (params (org-prepare-dblock))
14193 (name (plist-get params :name))
14194 (cmd (intern (concat "org-dblock-write:" name))))
14195 (message "Updating dynamic block `%s' at line %d..." name line)
14196 (funcall cmd params)
14197 (message "Updating dynamic block `%s' at line %d...done" name line)
14198 (goto-char pos))))
14200 (defun org-beginning-of-dblock ()
14201 "Find the beginning of the dynamic block at point.
14202 Error if there is no scuh block at point."
14203 (let ((pos (point))
14204 beg)
14205 (end-of-line 1)
14206 (if (and (re-search-backward org-dblock-start-re nil t)
14207 (setq beg (match-beginning 0))
14208 (re-search-forward org-dblock-end-re nil t)
14209 (> (match-end 0) pos))
14210 (goto-char beg)
14211 (goto-char pos)
14212 (error "Not in a dynamic block"))))
14214 (defun org-update-all-dblocks ()
14215 "Update all dynamic blocks in the buffer.
14216 This function can be used in a hook."
14217 (when (org-mode-p)
14218 (org-map-dblocks 'org-update-dblock)))
14221 ;;;; Completion
14223 (defconst org-additional-option-like-keywords
14224 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14225 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
14226 "BEGIN_EXAMPLE" "END_EXAMPLE"))
14228 (defun org-complete (&optional arg)
14229 "Perform completion on word at point.
14230 At the beginning of a headline, this completes TODO keywords as given in
14231 `org-todo-keywords'.
14232 If the current word is preceded by a backslash, completes the TeX symbols
14233 that are supported for HTML support.
14234 If the current word is preceded by \"#+\", completes special words for
14235 setting file options.
14236 In the line after \"#+STARTUP:, complete valid keywords.\"
14237 At all other locations, this simply calls the value of
14238 `org-completion-fallback-command'."
14239 (interactive "P")
14240 (org-without-partial-completion
14241 (catch 'exit
14242 (let* ((end (point))
14243 (beg1 (save-excursion
14244 (skip-chars-backward (org-re "[:alnum:]_@"))
14245 (point)))
14246 (beg (save-excursion
14247 (skip-chars-backward "a-zA-Z0-9_:$")
14248 (point)))
14249 (confirm (lambda (x) (stringp (car x))))
14250 (searchhead (equal (char-before beg) ?*))
14251 (tag (and (equal (char-before beg1) ?:)
14252 (equal (char-after (point-at-bol)) ?*)))
14253 (prop (and (equal (char-before beg1) ?:)
14254 (not (equal (char-after (point-at-bol)) ?*))))
14255 (texp (equal (char-before beg) ?\\))
14256 (link (equal (char-before beg) ?\[))
14257 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14258 beg)
14259 "#+"))
14260 (startup (string-match "^#\\+STARTUP:.*"
14261 (buffer-substring (point-at-bol) (point))))
14262 (completion-ignore-case opt)
14263 (type nil)
14264 (tbl nil)
14265 (table (cond
14266 (opt
14267 (setq type :opt)
14268 (append
14269 (mapcar
14270 (lambda (x)
14271 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14272 (cons (match-string 2 x) (match-string 1 x)))
14273 (org-split-string (org-get-current-options) "\n"))
14274 (mapcar 'list org-additional-option-like-keywords)))
14275 (startup
14276 (setq type :startup)
14277 org-startup-options)
14278 (link (append org-link-abbrev-alist-local
14279 org-link-abbrev-alist))
14280 (texp
14281 (setq type :tex)
14282 org-html-entities)
14283 ((string-match "\\`\\*+[ \t]+\\'"
14284 (buffer-substring (point-at-bol) beg))
14285 (setq type :todo)
14286 (mapcar 'list org-todo-keywords-1))
14287 (searchhead
14288 (setq type :searchhead)
14289 (save-excursion
14290 (goto-char (point-min))
14291 (while (re-search-forward org-todo-line-regexp nil t)
14292 (push (list
14293 (org-make-org-heading-search-string
14294 (match-string 3) t))
14295 tbl)))
14296 tbl)
14297 (tag (setq type :tag beg beg1)
14298 (or org-tag-alist (org-get-buffer-tags)))
14299 (prop (setq type :prop beg beg1)
14300 (mapcar 'list (org-buffer-property-keys nil t t)))
14301 (t (progn
14302 (call-interactively org-completion-fallback-command)
14303 (throw 'exit nil)))))
14304 (pattern (buffer-substring-no-properties beg end))
14305 (completion (try-completion pattern table confirm)))
14306 (cond ((eq completion t)
14307 (if (not (assoc (upcase pattern) table))
14308 (message "Already complete")
14309 (if (equal type :opt)
14310 (insert (substring (cdr (assoc (upcase pattern) table))
14311 (length pattern)))
14312 (if (memq type '(:tag :prop)) (insert ":")))))
14313 ((null completion)
14314 (message "Can't find completion for \"%s\"" pattern)
14315 (ding))
14316 ((not (string= pattern completion))
14317 (delete-region beg end)
14318 (if (string-match " +$" completion)
14319 (setq completion (replace-match "" t t completion)))
14320 (insert completion)
14321 (if (get-buffer-window "*Completions*")
14322 (delete-window (get-buffer-window "*Completions*")))
14323 (if (assoc completion table)
14324 (if (eq type :todo) (insert " ")
14325 (if (memq type '(:tag :prop)) (insert ":"))))
14326 (if (and (equal type :opt) (assoc completion table))
14327 (message "%s" (substitute-command-keys
14328 "Press \\[org-complete] again to insert example settings"))))
14330 (message "Making completion list...")
14331 (let ((list (sort (all-completions pattern table confirm)
14332 'string<)))
14333 (with-output-to-temp-buffer "*Completions*"
14334 (condition-case nil
14335 ;; Protection needed for XEmacs and emacs 21
14336 (display-completion-list list pattern)
14337 (error (display-completion-list list)))))
14338 (message "Making completion list...%s" "done")))))))
14340 ;;;; TODO, DEADLINE, Comments
14342 (defun org-toggle-comment ()
14343 "Change the COMMENT state of an entry."
14344 (interactive)
14345 (save-excursion
14346 (org-back-to-heading)
14347 (let (case-fold-search)
14348 (if (looking-at (concat outline-regexp
14349 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14350 (replace-match "" t t nil 1)
14351 (if (looking-at outline-regexp)
14352 (progn
14353 (goto-char (match-end 0))
14354 (insert org-comment-string " ")))))))
14356 (defvar org-last-todo-state-is-todo nil
14357 "This is non-nil when the last TODO state change led to a TODO state.
14358 If the last change removed the TODO tag or switched to DONE, then
14359 this is nil.")
14361 (defvar org-setting-tags nil) ; dynamically skiped
14363 ;; FIXME: better place
14364 (defun org-property-or-variable-value (var &optional inherit)
14365 "Check if there is a property fixing the value of VAR.
14366 If yes, return this value. If not, return the current value of the variable."
14367 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14368 (if (and prop (stringp prop) (string-match "\\S-" prop))
14369 (read prop)
14370 (symbol-value var))))
14372 (defun org-parse-local-options (string var)
14373 "Parse STRING for startup setting relevant for variable VAR."
14374 (let ((rtn (symbol-value var))
14375 e opts)
14376 (save-match-data
14377 (if (or (not string) (not (string-match "\\S-" string)))
14379 (setq opts (delq nil (mapcar (lambda (x)
14380 (setq e (assoc x org-startup-options))
14381 (if (eq (nth 1 e) var) e nil))
14382 (org-split-string string "[ \t]+"))))
14383 (if (not opts)
14385 (setq rtn nil)
14386 (while (setq e (pop opts))
14387 (if (not (nth 3 e))
14388 (setq rtn (nth 2 e))
14389 (if (not (listp rtn)) (setq rtn nil))
14390 (push (nth 2 e) rtn)))
14391 rtn)))))
14393 (defvar org-blocker-hook nil
14394 "Hook for functions that are allowed to block a state change.
14396 Each function gets as its single argument a property list, see
14397 `org-trigger-hook' for more information about this list.
14399 If any of the functions in this hook returns nil, the state change
14400 is blocked.")
14402 (defvar org-trigger-hook nil
14403 "Hook for functions that are triggered by a state change.
14405 Each function gets as its single argument a property list with at least
14406 the following elements:
14408 (:type type-of-change :position pos-at-entry-start
14409 :from old-state :to new-state)
14411 Depending on the type, more properties may be present.
14413 This mechanism is currently implemented for:
14415 TODO state changes
14416 ------------------
14417 :type todo-state-change
14418 :from previous state (keyword as a string), or nil
14419 :to new state (keyword as a string), or nil")
14422 (defun org-todo (&optional arg)
14423 "Change the TODO state of an item.
14424 The state of an item is given by a keyword at the start of the heading,
14425 like
14426 *** TODO Write paper
14427 *** DONE Call mom
14429 The different keywords are specified in the variable `org-todo-keywords'.
14430 By default the available states are \"TODO\" and \"DONE\".
14431 So for this example: when the item starts with TODO, it is changed to DONE.
14432 When it starts with DONE, the DONE is removed. And when neither TODO nor
14433 DONE are present, add TODO at the beginning of the heading.
14435 With C-u prefix arg, use completion to determine the new state.
14436 With numeric prefix arg, switch to that state.
14438 For calling through lisp, arg is also interpreted in the following way:
14439 'none -> empty state
14440 \"\"(empty string) -> switch to empty state
14441 'done -> switch to DONE
14442 'nextset -> switch to the next set of keywords
14443 'previousset -> switch to the previous set of keywords
14444 \"WAITING\" -> switch to the specified keyword, but only if it
14445 really is a member of `org-todo-keywords'."
14446 (interactive "P")
14447 (save-excursion
14448 (catch 'exit
14449 (org-back-to-heading)
14450 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14451 (or (looking-at (concat " +" org-todo-regexp " *"))
14452 (looking-at " *"))
14453 (let* ((match-data (match-data))
14454 (startpos (point-at-bol))
14455 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14456 (org-log-done (org-parse-local-options logging 'org-log-done))
14457 (org-log-repeat (org-parse-local-options logging 'org-log-repeat))
14458 (this (match-string 1))
14459 (hl-pos (match-beginning 0))
14460 (head (org-get-todo-sequence-head this))
14461 (ass (assoc head org-todo-kwd-alist))
14462 (interpret (nth 1 ass))
14463 (done-word (nth 3 ass))
14464 (final-done-word (nth 4 ass))
14465 (last-state (or this ""))
14466 (completion-ignore-case t)
14467 (member (member this org-todo-keywords-1))
14468 (tail (cdr member))
14469 (state (cond
14470 ((and org-todo-key-trigger
14471 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14472 (and (not arg) org-use-fast-todo-selection
14473 (not (eq org-use-fast-todo-selection 'prefix)))))
14474 ;; Use fast selection
14475 (org-fast-todo-selection))
14476 ((and (equal arg '(4))
14477 (or (not org-use-fast-todo-selection)
14478 (not org-todo-key-trigger)))
14479 ;; Read a state with completion
14480 (completing-read "State: " (mapcar (lambda(x) (list x))
14481 org-todo-keywords-1)
14482 nil t))
14483 ((eq arg 'right)
14484 (if this
14485 (if tail (car tail) nil)
14486 (car org-todo-keywords-1)))
14487 ((eq arg 'left)
14488 (if (equal member org-todo-keywords-1)
14490 (if this
14491 (nth (- (length org-todo-keywords-1) (length tail) 2)
14492 org-todo-keywords-1)
14493 (org-last org-todo-keywords-1))))
14494 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14495 (setq arg nil))) ; hack to fall back to cycling
14496 (arg
14497 ;; user or caller requests a specific state
14498 (cond
14499 ((equal arg "") nil)
14500 ((eq arg 'none) nil)
14501 ((eq arg 'done) (or done-word (car org-done-keywords)))
14502 ((eq arg 'nextset)
14503 (or (car (cdr (member head org-todo-heads)))
14504 (car org-todo-heads)))
14505 ((eq arg 'previousset)
14506 (let ((org-todo-heads (reverse org-todo-heads)))
14507 (or (car (cdr (member head org-todo-heads)))
14508 (car org-todo-heads))))
14509 ((car (member arg org-todo-keywords-1)))
14510 ((nth (1- (prefix-numeric-value arg))
14511 org-todo-keywords-1))))
14512 ((null member) (or head (car org-todo-keywords-1)))
14513 ((equal this final-done-word) nil) ;; -> make empty
14514 ((null tail) nil) ;; -> first entry
14515 ((eq interpret 'sequence)
14516 (car tail))
14517 ((memq interpret '(type priority))
14518 (if (eq this-command last-command)
14519 (car tail)
14520 (if (> (length tail) 0)
14521 (or done-word (car org-done-keywords))
14522 nil)))
14523 (t nil)))
14524 (next (if state (concat " " state " ") " "))
14525 (change-plist (list :type 'todo-state-change :from this :to state
14526 :position startpos))
14527 dostates)
14528 (when org-blocker-hook
14529 (unless (save-excursion
14530 (save-match-data
14531 (run-hook-with-args-until-failure
14532 'org-blocker-hook change-plist)))
14533 (if (interactive-p)
14534 (error "TODO state change from %s to %s blocked" this state)
14535 ;; fail silently
14536 (message "TODO state change from %s to %s blocked" this state)
14537 (throw 'exit nil))))
14538 (store-match-data match-data)
14539 (replace-match next t t)
14540 (unless (pos-visible-in-window-p hl-pos)
14541 (message "TODO state changed to %s" (org-trim next)))
14542 (unless head
14543 (setq head (org-get-todo-sequence-head state)
14544 ass (assoc head org-todo-kwd-alist)
14545 interpret (nth 1 ass)
14546 done-word (nth 3 ass)
14547 final-done-word (nth 4 ass)))
14548 (when (memq arg '(nextset previousset))
14549 (message "Keyword-Set %d/%d: %s"
14550 (- (length org-todo-sets) -1
14551 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14552 (length org-todo-sets)
14553 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14554 (setq org-last-todo-state-is-todo
14555 (not (member state org-done-keywords)))
14556 (when (and org-log-done (not (memq arg '(nextset previousset))))
14557 (setq dostates (and (listp org-log-done) (memq 'state org-log-done)
14558 (or (not org-todo-log-states)
14559 (member state org-todo-log-states))))
14561 (cond
14562 ((and state (member state org-not-done-keywords)
14563 (not (member this org-not-done-keywords)))
14564 ;; This is now a todo state and was not one before
14565 ;; Remove any CLOSED timestamp, and possibly log the state change
14566 (org-add-planning-info nil nil 'closed)
14567 (and dostates (org-add-log-maybe 'state state 'findpos)))
14568 ((and state dostates)
14569 ;; This is a non-nil state, and we need to log it
14570 (org-add-log-maybe 'state state 'findpos))
14571 ((and (member state org-done-keywords)
14572 (not (member this org-done-keywords)))
14573 ;; It is now done, and it was not done before
14574 (org-add-planning-info 'closed (org-current-time))
14575 (org-add-log-maybe 'done state 'findpos))))
14576 ;; Fixup tag positioning
14577 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14578 (run-hooks 'org-after-todo-state-change-hook)
14579 (and (member state org-done-keywords) (org-auto-repeat-maybe))
14580 (if (and arg (not (member state org-done-keywords)))
14581 (setq head (org-get-todo-sequence-head state)))
14582 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14583 ;; Fixup cursor location if close to the keyword
14584 (if (and (outline-on-heading-p)
14585 (not (bolp))
14586 (save-excursion (beginning-of-line 1)
14587 (looking-at org-todo-line-regexp))
14588 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14589 (progn
14590 (goto-char (or (match-end 2) (match-end 1)))
14591 (just-one-space)))
14592 (when org-trigger-hook
14593 (save-excursion
14594 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14596 (defun org-get-todo-sequence-head (kwd)
14597 "Return the head of the TODO sequence to which KWD belongs.
14598 If KWD is not set, check if there is a text property remembering the
14599 right sequence."
14600 (let (p)
14601 (cond
14602 ((not kwd)
14603 (or (get-text-property (point-at-bol) 'org-todo-head)
14604 (progn
14605 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14606 nil (point-at-eol)))
14607 (get-text-property p 'org-todo-head))))
14608 ((not (member kwd org-todo-keywords-1))
14609 (car org-todo-keywords-1))
14610 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14612 (defun org-fast-todo-selection ()
14613 "Fast TODO keyword selection with single keys.
14614 Returns the new TODO keyword, or nil if no state change should occur."
14615 (let* ((fulltable org-todo-key-alist)
14616 (done-keywords org-done-keywords) ;; needed for the faces.
14617 (maxlen (apply 'max (mapcar
14618 (lambda (x)
14619 (if (stringp (car x)) (string-width (car x)) 0))
14620 fulltable)))
14621 (expert nil)
14622 (fwidth (+ maxlen 3 1 3))
14623 (ncol (/ (- (window-width) 4) fwidth))
14624 tg cnt e c tbl
14625 groups ingroup)
14626 (save-window-excursion
14627 (if expert
14628 (set-buffer (get-buffer-create " *Org todo*"))
14629 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14630 (erase-buffer)
14631 (org-set-local 'org-done-keywords done-keywords)
14632 (setq tbl fulltable cnt 0)
14633 (while (setq e (pop tbl))
14634 (cond
14635 ((equal e '(:startgroup))
14636 (push '() groups) (setq ingroup t)
14637 (when (not (= cnt 0))
14638 (setq cnt 0)
14639 (insert "\n"))
14640 (insert "{ "))
14641 ((equal e '(:endgroup))
14642 (setq ingroup nil cnt 0)
14643 (insert "}\n"))
14645 (setq tg (car e) c (cdr e))
14646 (if ingroup (push tg (car groups)))
14647 (setq tg (org-add-props tg nil 'face
14648 (org-get-todo-face tg)))
14649 (if (and (= cnt 0) (not ingroup)) (insert " "))
14650 (insert "[" c "] " tg (make-string
14651 (- fwidth 4 (length tg)) ?\ ))
14652 (when (= (setq cnt (1+ cnt)) ncol)
14653 (insert "\n")
14654 (if ingroup (insert " "))
14655 (setq cnt 0)))))
14656 (insert "\n")
14657 (goto-char (point-min))
14658 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14659 (fit-window-to-buffer))
14660 (message "[a-z..]:Set [SPC]:clear")
14661 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14662 (cond
14663 ((or (= c ?\C-g)
14664 (and (= c ?q) (not (rassoc c fulltable))))
14665 (setq quit-flag t))
14666 ((= c ?\ ) nil)
14667 ((setq e (rassoc c fulltable) tg (car e))
14669 (t (setq quit-flag t))))))
14671 (defun org-get-repeat ()
14672 "Check if tere is a deadline/schedule with repeater in this entry."
14673 (save-match-data
14674 (save-excursion
14675 (org-back-to-heading t)
14676 (if (re-search-forward
14677 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
14678 (match-string 1)))))
14680 (defvar org-last-changed-timestamp)
14681 (defvar org-log-post-message)
14682 (defun org-auto-repeat-maybe ()
14683 "Check if the current headline contains a repeated deadline/schedule.
14684 If yes, set TODO state back to what it was and change the base date
14685 of repeating deadline/scheduled time stamps to new date.
14686 This function should be run in the `org-after-todo-state-change-hook'."
14687 ;; last-state is dynamically scoped into this function
14688 (let* ((repeat (org-get-repeat))
14689 (aa (assoc last-state org-todo-kwd-alist))
14690 (interpret (nth 1 aa))
14691 (head (nth 2 aa))
14692 (done-word (nth 3 aa))
14693 (whata '(("d" . day) ("m" . month) ("y" . year)))
14694 (msg "Entry repeats: ")
14695 (org-log-done)
14696 re type n what ts)
14697 (when repeat
14698 (org-todo (if (eq interpret 'type) last-state head))
14699 (when (and org-log-repeat
14700 (not (memq 'org-add-log-note
14701 (default-value 'post-command-hook))))
14702 ;; Make sure a note is taken
14703 (let ((org-log-done '(done)))
14704 (org-add-log-maybe 'done (or done-word (car org-done-keywords))
14705 'findpos)))
14706 (org-back-to-heading t)
14707 (org-add-planning-info nil nil 'closed)
14708 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
14709 org-deadline-time-regexp "\\)\\|\\("
14710 org-ts-regexp "\\)"))
14711 (while (re-search-forward
14712 re (save-excursion (outline-next-heading) (point)) t)
14713 (setq type (if (match-end 1) org-scheduled-string
14714 (if (match-end 3) org-deadline-string "Plain:"))
14715 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
14716 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
14717 (setq n (string-to-number (match-string 1 ts))
14718 what (match-string 2 ts))
14719 (if (equal what "w") (setq n (* n 7) what "d"))
14720 (org-timestamp-change n (cdr (assoc what whata)))
14721 (setq msg (concat msg type org-last-changed-timestamp " "))))
14722 (setq org-log-post-message msg)
14723 (message "%s" msg))))
14725 (defun org-show-todo-tree (arg)
14726 "Make a compact tree which shows all headlines marked with TODO.
14727 The tree will show the lines where the regexp matches, and all higher
14728 headlines above the match.
14729 With \\[universal-argument] prefix, also show the DONE entries.
14730 With a numeric prefix N, construct a sparse tree for the Nth element
14731 of `org-todo-keywords-1'."
14732 (interactive "P")
14733 (let ((case-fold-search nil)
14734 (kwd-re
14735 (cond ((null arg) org-not-done-regexp)
14736 ((equal arg '(4))
14737 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
14738 (mapcar 'list org-todo-keywords-1))))
14739 (concat "\\("
14740 (mapconcat 'identity (org-split-string kwd "|") "\\|")
14741 "\\)\\>")))
14742 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
14743 (regexp-quote (nth (1- (prefix-numeric-value arg))
14744 org-todo-keywords-1)))
14745 (t (error "Invalid prefix argument: %s" arg)))))
14746 (message "%d TODO entries found"
14747 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
14749 (defun org-deadline (&optional remove)
14750 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
14751 With argument REMOVE, remove any deadline from the item."
14752 (interactive "P")
14753 (if remove
14754 (progn
14755 (org-remove-timestamp-with-keyword org-deadline-string)
14756 (message "Item no longer has a deadline."))
14757 (org-add-planning-info 'deadline nil 'closed)))
14759 (defun org-schedule (&optional remove)
14760 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
14761 With argument REMOVE, remove any scheduling date from the item."
14762 (interactive "P")
14763 (if remove
14764 (progn
14765 (org-remove-timestamp-with-keyword org-scheduled-string)
14766 (message "Item is no longer scheduled."))
14767 (org-add-planning-info 'scheduled nil 'closed)))
14769 (defun org-remove-timestamp-with-keyword (keyword)
14770 "Remove all time stamps with KEYWORD in the current entry."
14771 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
14772 beg)
14773 (save-excursion
14774 (org-back-to-heading t)
14775 (setq beg (point))
14776 (org-end-of-subtree t t)
14777 (while (re-search-backward re beg t)
14778 (replace-match "")
14779 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
14780 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
14782 (defun org-add-planning-info (what &optional time &rest remove)
14783 "Insert new timestamp with keyword in the line directly after the headline.
14784 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
14785 If non is given, the user is prompted for a date.
14786 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
14787 be removed."
14788 (interactive)
14789 (let (org-time-was-given org-end-time-was-given)
14790 (when what (setq time (or time (org-read-date nil 'to-time))))
14791 (when (and org-insert-labeled-timestamps-at-point
14792 (member what '(scheduled deadline)))
14793 (insert
14794 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
14795 (org-insert-time-stamp time org-time-was-given
14796 nil nil nil (list org-end-time-was-given))
14797 (setq what nil))
14798 (save-excursion
14799 (save-restriction
14800 (let (col list elt ts buffer-invisibility-spec)
14801 (org-back-to-heading t)
14802 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
14803 (goto-char (match-end 1))
14804 (setq col (current-column))
14805 (goto-char (match-end 0))
14806 (if (eobp) (insert "\n") (forward-char 1))
14807 (if (and (not (looking-at outline-regexp))
14808 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
14809 "[^\r\n]*"))
14810 (not (equal (match-string 1) org-clock-string)))
14811 (narrow-to-region (match-beginning 0) (match-end 0))
14812 (insert-before-markers "\n")
14813 (backward-char 1)
14814 (narrow-to-region (point) (point))
14815 (indent-to-column col))
14816 ;; Check if we have to remove something.
14817 (setq list (cons what remove))
14818 (while list
14819 (setq elt (pop list))
14820 (goto-char (point-min))
14821 (when (or (and (eq elt 'scheduled)
14822 (re-search-forward org-scheduled-time-regexp nil t))
14823 (and (eq elt 'deadline)
14824 (re-search-forward org-deadline-time-regexp nil t))
14825 (and (eq elt 'closed)
14826 (re-search-forward org-closed-time-regexp nil t)))
14827 (replace-match "")
14828 (if (looking-at "--+<[^>]+>") (replace-match ""))
14829 (if (looking-at " +") (replace-match ""))))
14830 (goto-char (point-max))
14831 (when what
14832 (insert
14833 (if (not (equal (char-before) ?\ )) " " "")
14834 (cond ((eq what 'scheduled) org-scheduled-string)
14835 ((eq what 'deadline) org-deadline-string)
14836 ((eq what 'closed) org-closed-string))
14837 " ")
14838 (setq ts (org-insert-time-stamp
14839 time
14840 (or org-time-was-given
14841 (and (eq what 'closed) org-log-done-with-time))
14842 (eq what 'closed)
14843 nil nil (list org-end-time-was-given)))
14844 (end-of-line 1))
14845 (goto-char (point-min))
14846 (widen)
14847 (if (looking-at "[ \t]+\r?\n")
14848 (replace-match ""))
14849 ts)))))
14851 (defvar org-log-note-marker (make-marker))
14852 (defvar org-log-note-purpose nil)
14853 (defvar org-log-note-state nil)
14854 (defvar org-log-note-window-configuration nil)
14855 (defvar org-log-note-return-to (make-marker))
14856 (defvar org-log-post-message nil
14857 "Message to be displayed after a log note has been stored.
14858 The auto-repeater uses this.")
14860 (defun org-add-log-maybe (&optional purpose state findpos)
14861 "Set up the post command hook to take a note."
14862 (save-excursion
14863 (when (and (listp org-log-done)
14864 (memq purpose org-log-done))
14865 (when findpos
14866 (org-back-to-heading t)
14867 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
14868 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
14869 "[^\r\n]*\\)?"))
14870 (goto-char (match-end 0))
14871 (unless org-log-states-order-reversed
14872 (and (= (char-after) ?\n) (forward-char 1))
14873 (org-skip-over-state-notes)
14874 (skip-chars-backward " \t\n\r")))
14875 (move-marker org-log-note-marker (point))
14876 (setq org-log-note-purpose purpose)
14877 (setq org-log-note-state state)
14878 (add-hook 'post-command-hook 'org-add-log-note 'append))))
14880 (defun org-skip-over-state-notes ()
14881 "Skip past the list of State notes in an entry."
14882 (if (looking-at "\n[ \t]*- State") (forward-char 1))
14883 (while (looking-at "[ \t]*- State")
14884 (condition-case nil
14885 (org-next-item)
14886 (error (org-end-of-item)))))
14888 (defun org-add-log-note (&optional purpose)
14889 "Pop up a window for taking a note, and add this note later at point."
14890 (remove-hook 'post-command-hook 'org-add-log-note)
14891 (setq org-log-note-window-configuration (current-window-configuration))
14892 (delete-other-windows)
14893 (move-marker org-log-note-return-to (point))
14894 (switch-to-buffer (marker-buffer org-log-note-marker))
14895 (goto-char org-log-note-marker)
14896 (org-switch-to-buffer-other-window "*Org Note*")
14897 (erase-buffer)
14898 (let ((org-inhibit-startup t)) (org-mode))
14899 (insert (format "# Insert note for %s.
14900 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
14901 (cond
14902 ((eq org-log-note-purpose 'clock-out) "stopped clock")
14903 ((eq org-log-note-purpose 'done) "closed todo item")
14904 ((eq org-log-note-purpose 'state)
14905 (format "state change to \"%s\"" org-log-note-state))
14906 (t (error "This should not happen")))))
14907 (org-set-local 'org-finish-function 'org-store-log-note))
14909 (defun org-store-log-note ()
14910 "Finish taking a log note, and insert it to where it belongs."
14911 (let ((txt (buffer-string))
14912 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
14913 lines ind)
14914 (kill-buffer (current-buffer))
14915 (while (string-match "\\`#.*\n[ \t\n]*" txt)
14916 (setq txt (replace-match "" t t txt)))
14917 (if (string-match "\\s-+\\'" txt)
14918 (setq txt (replace-match "" t t txt)))
14919 (setq lines (org-split-string txt "\n"))
14920 (when (and note (string-match "\\S-" note))
14921 (setq note
14922 (org-replace-escapes
14923 note
14924 (list (cons "%u" (user-login-name))
14925 (cons "%U" user-full-name)
14926 (cons "%t" (format-time-string
14927 (org-time-stamp-format 'long 'inactive)
14928 (current-time)))
14929 (cons "%s" (if org-log-note-state
14930 (concat "\"" org-log-note-state "\"")
14931 "")))))
14932 (if lines (setq note (concat note " \\\\")))
14933 (push note lines))
14934 (when (or current-prefix-arg org-note-abort) (setq lines nil))
14935 (when lines
14936 (save-excursion
14937 (set-buffer (marker-buffer org-log-note-marker))
14938 (save-excursion
14939 (goto-char org-log-note-marker)
14940 (move-marker org-log-note-marker nil)
14941 (end-of-line 1)
14942 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
14943 (indent-relative nil)
14944 (insert "- " (pop lines))
14945 (org-indent-line-function)
14946 (beginning-of-line 1)
14947 (looking-at "[ \t]*")
14948 (setq ind (concat (match-string 0) " "))
14949 (end-of-line 1)
14950 (while lines (insert "\n" ind (pop lines)))))))
14951 (set-window-configuration org-log-note-window-configuration)
14952 (with-current-buffer (marker-buffer org-log-note-return-to)
14953 (goto-char org-log-note-return-to))
14954 (move-marker org-log-note-return-to nil)
14955 (and org-log-post-message (message "%s" org-log-post-message)))
14957 ;; FIXME: what else would be useful?
14958 ;; - priority
14959 ;; - date
14961 (defun org-sparse-tree (&optional arg)
14962 "Create a sparse tree, prompt for the details.
14963 This command can create sparse trees. You first need to select the type
14964 of match used to create the tree:
14966 t Show entries with a specific TODO keyword.
14967 T Show entries selected by a tags match.
14968 p Enter a property name and its value (both with completion on existing
14969 names/values) and show entries with that property.
14970 r Show entries matching a regular expression
14971 d Show deadlines due within `org-deadline-warning-days'."
14972 (interactive "P")
14973 (let (ans kwd value)
14974 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
14975 (setq ans (read-char-exclusive))
14976 (cond
14977 ((equal ans ?d)
14978 (call-interactively 'org-check-deadlines))
14979 ((equal ans ?b)
14980 (call-interactively 'org-check-before-date))
14981 ((equal ans ?t)
14982 (org-show-todo-tree '(4)))
14983 ((equal ans ?T)
14984 (call-interactively 'org-tags-sparse-tree))
14985 ((member ans '(?p ?P))
14986 (setq kwd (completing-read "Property: "
14987 (mapcar 'list (org-buffer-property-keys))))
14988 (setq value (completing-read "Value: "
14989 (mapcar 'list (org-property-values kwd))))
14990 (unless (string-match "\\`{.*}\\'" value)
14991 (setq value (concat "\"" value "\"")))
14992 (org-tags-sparse-tree arg (concat kwd "=" value)))
14993 ((member ans '(?r ?R ?/))
14994 (call-interactively 'org-occur))
14995 (t (error "No such sparse tree command \"%c\"" ans)))))
14997 (defvar org-occur-highlights nil)
14998 (make-variable-buffer-local 'org-occur-highlights)
15000 (defun org-occur (regexp &optional keep-previous callback)
15001 "Make a compact tree which shows all matches of REGEXP.
15002 The tree will show the lines where the regexp matches, and all higher
15003 headlines above the match. It will also show the heading after the match,
15004 to make sure editing the matching entry is easy.
15005 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
15006 call to `org-occur' will be kept, to allow stacking of calls to this
15007 command.
15008 If CALLBACK is non-nil, it is a function which is called to confirm
15009 that the match should indeed be shown."
15010 (interactive "sRegexp: \nP")
15011 (or keep-previous (org-remove-occur-highlights nil nil t))
15012 (let ((cnt 0))
15013 (save-excursion
15014 (goto-char (point-min))
15015 (if (or (not keep-previous) ; do not want to keep
15016 (not org-occur-highlights)) ; no previous matches
15017 ;; hide everything
15018 (org-overview))
15019 (while (re-search-forward regexp nil t)
15020 (when (or (not callback)
15021 (save-match-data (funcall callback)))
15022 (setq cnt (1+ cnt))
15023 (when org-highlight-sparse-tree-matches
15024 (org-highlight-new-match (match-beginning 0) (match-end 0)))
15025 (org-show-context 'occur-tree))))
15026 (when org-remove-highlights-with-change
15027 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
15028 nil 'local))
15029 (unless org-sparse-tree-open-archived-trees
15030 (org-hide-archived-subtrees (point-min) (point-max)))
15031 (run-hooks 'org-occur-hook)
15032 (if (interactive-p)
15033 (message "%d match(es) for regexp %s" cnt regexp))
15034 cnt))
15036 (defun org-show-context (&optional key)
15037 "Make sure point and context and visible.
15038 How much context is shown depends upon the variables
15039 `org-show-hierarchy-above', `org-show-following-heading'. and
15040 `org-show-siblings'."
15041 (let ((heading-p (org-on-heading-p t))
15042 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
15043 (following-p (org-get-alist-option org-show-following-heading key))
15044 (entry-p (org-get-alist-option org-show-entry-below key))
15045 (siblings-p (org-get-alist-option org-show-siblings key)))
15046 (catch 'exit
15047 ;; Show heading or entry text
15048 (if (and heading-p (not entry-p))
15049 (org-flag-heading nil) ; only show the heading
15050 (and (or entry-p (org-invisible-p) (org-invisible-p2))
15051 (org-show-hidden-entry))) ; show entire entry
15052 (when following-p
15053 ;; Show next sibling, or heading below text
15054 (save-excursion
15055 (and (if heading-p (org-goto-sibling) (outline-next-heading))
15056 (org-flag-heading nil))))
15057 (when siblings-p (org-show-siblings))
15058 (when hierarchy-p
15059 ;; show all higher headings, possibly with siblings
15060 (save-excursion
15061 (while (and (condition-case nil
15062 (progn (org-up-heading-all 1) t)
15063 (error nil))
15064 (not (bobp)))
15065 (org-flag-heading nil)
15066 (when siblings-p (org-show-siblings))))))))
15068 (defun org-reveal (&optional siblings)
15069 "Show current entry, hierarchy above it, and the following headline.
15070 This can be used to show a consistent set of context around locations
15071 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
15072 not t for the search context.
15074 With optional argument SIBLINGS, on each level of the hierarchy all
15075 siblings are shown. This repairs the tree structure to what it would
15076 look like when opened with hierarchical calls to `org-cycle'."
15077 (interactive "P")
15078 (let ((org-show-hierarchy-above t)
15079 (org-show-following-heading t)
15080 (org-show-siblings (if siblings t org-show-siblings)))
15081 (org-show-context nil)))
15083 (defun org-highlight-new-match (beg end)
15084 "Highlight from BEG to END and mark the highlight is an occur headline."
15085 (let ((ov (org-make-overlay beg end)))
15086 (org-overlay-put ov 'face 'secondary-selection)
15087 (push ov org-occur-highlights)))
15089 (defun org-remove-occur-highlights (&optional beg end noremove)
15090 "Remove the occur highlights from the buffer.
15091 BEG and END are ignored. If NOREMOVE is nil, remove this function
15092 from the `before-change-functions' in the current buffer."
15093 (interactive)
15094 (unless org-inhibit-highlight-removal
15095 (mapc 'org-delete-overlay org-occur-highlights)
15096 (setq org-occur-highlights nil)
15097 (unless noremove
15098 (remove-hook 'before-change-functions
15099 'org-remove-occur-highlights 'local))))
15101 ;;;; Priorities
15103 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
15104 "Regular expression matching the priority indicator.")
15106 (defvar org-remove-priority-next-time nil)
15108 (defun org-priority-up ()
15109 "Increase the priority of the current item."
15110 (interactive)
15111 (org-priority 'up))
15113 (defun org-priority-down ()
15114 "Decrease the priority of the current item."
15115 (interactive)
15116 (org-priority 'down))
15118 (defun org-priority (&optional action)
15119 "Change the priority of an item by ARG.
15120 ACTION can be `set', `up', `down', or a character."
15121 (interactive)
15122 (setq action (or action 'set))
15123 (let (current new news have remove)
15124 (save-excursion
15125 (org-back-to-heading)
15126 (if (looking-at org-priority-regexp)
15127 (setq current (string-to-char (match-string 2))
15128 have t)
15129 (setq current org-default-priority))
15130 (cond
15131 ((or (eq action 'set) (integerp action))
15132 (if (integerp action)
15133 (setq new action)
15134 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
15135 (setq new (read-char-exclusive)))
15136 (if (and (= (upcase org-highest-priority) org-highest-priority)
15137 (= (upcase org-lowest-priority) org-lowest-priority))
15138 (setq new (upcase new)))
15139 (cond ((equal new ?\ ) (setq remove t))
15140 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
15141 (error "Priority must be between `%c' and `%c'"
15142 org-highest-priority org-lowest-priority))))
15143 ((eq action 'up)
15144 (if (and (not have) (eq last-command this-command))
15145 (setq new org-lowest-priority)
15146 (setq new (if (and org-priority-start-cycle-with-default (not have))
15147 org-default-priority (1- current)))))
15148 ((eq action 'down)
15149 (if (and (not have) (eq last-command this-command))
15150 (setq new org-highest-priority)
15151 (setq new (if (and org-priority-start-cycle-with-default (not have))
15152 org-default-priority (1+ current)))))
15153 (t (error "Invalid action")))
15154 (if (or (< (upcase new) org-highest-priority)
15155 (> (upcase new) org-lowest-priority))
15156 (setq remove t))
15157 (setq news (format "%c" new))
15158 (if have
15159 (if remove
15160 (replace-match "" t t nil 1)
15161 (replace-match news t t nil 2))
15162 (if remove
15163 (error "No priority cookie found in line")
15164 (looking-at org-todo-line-regexp)
15165 (if (match-end 2)
15166 (progn
15167 (goto-char (match-end 2))
15168 (insert " [#" news "]"))
15169 (goto-char (match-beginning 3))
15170 (insert "[#" news "] ")))))
15171 (org-preserve-lc (org-set-tags nil 'align))
15172 (if remove
15173 (message "Priority removed")
15174 (message "Priority of current item set to %s" news))))
15177 (defun org-get-priority (s)
15178 "Find priority cookie and return priority."
15179 (save-match-data
15180 (if (not (string-match org-priority-regexp s))
15181 (* 1000 (- org-lowest-priority org-default-priority))
15182 (* 1000 (- org-lowest-priority
15183 (string-to-char (match-string 2 s)))))))
15185 ;;;; Tags
15187 (defun org-scan-tags (action matcher &optional todo-only)
15188 "Scan headline tags with inheritance and produce output ACTION.
15189 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
15190 evaluated, testing if a given set of tags qualifies a headline for
15191 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
15192 are included in the output."
15193 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
15194 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
15195 (org-re
15196 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
15197 (props (list 'face nil
15198 'done-face 'org-done
15199 'undone-face nil
15200 'mouse-face 'highlight
15201 'org-not-done-regexp org-not-done-regexp
15202 'org-todo-regexp org-todo-regexp
15203 'keymap org-agenda-keymap
15204 'help-echo
15205 (format "mouse-2 or RET jump to org file %s"
15206 (abbreviate-file-name
15207 (or (buffer-file-name (buffer-base-buffer))
15208 (buffer-name (buffer-base-buffer)))))))
15209 (case-fold-search nil)
15210 lspos
15211 tags tags-list tags-alist (llast 0) rtn level category i txt
15212 todo marker entry priority)
15213 (save-excursion
15214 (goto-char (point-min))
15215 (when (eq action 'sparse-tree)
15216 (org-overview)
15217 (org-remove-occur-highlights))
15218 (while (re-search-forward re nil t)
15219 (catch :skip
15220 (setq todo (if (match-end 1) (match-string 2))
15221 tags (if (match-end 4) (match-string 4)))
15222 (goto-char (setq lspos (1+ (match-beginning 0))))
15223 (setq level (org-reduced-level (funcall outline-level))
15224 category (org-get-category))
15225 (setq i llast llast level)
15226 ;; remove tag lists from same and sublevels
15227 (while (>= i level)
15228 (when (setq entry (assoc i tags-alist))
15229 (setq tags-alist (delete entry tags-alist)))
15230 (setq i (1- i)))
15231 ;; add the nex tags
15232 (when tags
15233 (setq tags (mapcar 'downcase (org-split-string tags ":"))
15234 tags-alist
15235 (cons (cons level tags) tags-alist)))
15236 ;; compile tags for current headline
15237 (setq tags-list
15238 (if org-use-tag-inheritance
15239 (apply 'append (mapcar 'cdr tags-alist))
15240 tags))
15241 (when (and (or (not todo-only) (member todo org-not-done-keywords))
15242 (eval matcher)
15243 (or (not org-agenda-skip-archived-trees)
15244 (not (member org-archive-tag tags-list))))
15245 (and (eq action 'agenda) (org-agenda-skip))
15246 ;; list this headline
15248 (if (eq action 'sparse-tree)
15249 (progn
15250 (and org-highlight-sparse-tree-matches
15251 (org-get-heading) (match-end 0)
15252 (org-highlight-new-match
15253 (match-beginning 0) (match-beginning 1)))
15254 (org-show-context 'tags-tree))
15255 (setq txt (org-format-agenda-item
15257 (concat
15258 (if org-tags-match-list-sublevels
15259 (make-string (1- level) ?.) "")
15260 (org-get-heading))
15261 category tags-list)
15262 priority (org-get-priority txt))
15263 (goto-char lspos)
15264 (setq marker (org-agenda-new-marker))
15265 (org-add-props txt props
15266 'org-marker marker 'org-hd-marker marker 'org-category category
15267 'priority priority 'type "tagsmatch")
15268 (push txt rtn))
15269 ;; if we are to skip sublevels, jump to end of subtree
15270 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15271 (when (and (eq action 'sparse-tree)
15272 (not org-sparse-tree-open-archived-trees))
15273 (org-hide-archived-subtrees (point-min) (point-max)))
15274 (nreverse rtn)))
15276 (defvar todo-only) ;; dynamically scoped
15278 (defun org-tags-sparse-tree (&optional todo-only match)
15279 "Create a sparse tree according to tags string MATCH.
15280 MATCH can contain positive and negative selection of tags, like
15281 \"+WORK+URGENT-WITHBOSS\".
15282 If optional argument TODO_ONLY is non-nil, only select lines that are
15283 also TODO lines."
15284 (interactive "P")
15285 (org-prepare-agenda-buffers (list (current-buffer)))
15286 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15288 (defvar org-cached-props nil)
15289 (defun org-cached-entry-get (pom property)
15290 (if (or (eq t org-use-property-inheritance)
15291 (member property org-use-property-inheritance))
15292 ;; Caching is not possible, check it directly
15293 (org-entry-get pom property 'inherit)
15294 ;; Get all properties, so that we can do complicated checks easily
15295 (cdr (assoc property (or org-cached-props
15296 (setq org-cached-props
15297 (org-entry-properties pom)))))))
15299 (defun org-global-tags-completion-table (&optional files)
15300 "Return the list of all tags in all agenda buffer/files."
15301 (save-excursion
15302 (org-uniquify
15303 (delq nil
15304 (apply 'append
15305 (mapcar
15306 (lambda (file)
15307 (set-buffer (find-file-noselect file))
15308 (append (org-get-buffer-tags)
15309 (mapcar (lambda (x) (if (stringp (car-safe x))
15310 (list (car-safe x)) nil))
15311 org-tag-alist)))
15312 (if (and files (car files))
15313 files
15314 (org-agenda-files))))))))
15316 (defun org-make-tags-matcher (match)
15317 "Create the TAGS//TODO matcher form for the selection string MATCH."
15318 ;; todo-only is scoped dynamically into this function, and the function
15319 ;; may change it it the matcher asksk for it.
15320 (unless match
15321 ;; Get a new match request, with completion
15322 (let ((org-last-tags-completion-table
15323 (org-global-tags-completion-table)))
15324 (setq match (completing-read
15325 "Match: " 'org-tags-completion-function nil nil nil
15326 'org-tags-history))))
15328 ;; Parse the string and create a lisp form
15329 (let ((match0 match)
15330 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]+\"\\)\\|[[:alnum:]_@]+\\)"))
15331 minus tag mm
15332 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15333 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15334 (if (string-match "/+" match)
15335 ;; match contains also a todo-matching request
15336 (progn
15337 (setq tagsmatch (substring match 0 (match-beginning 0))
15338 todomatch (substring match (match-end 0)))
15339 (if (string-match "^!" todomatch)
15340 (setq todo-only t todomatch (substring todomatch 1)))
15341 (if (string-match "^\\s-*$" todomatch)
15342 (setq todomatch nil)))
15343 ;; only matching tags
15344 (setq tagsmatch match todomatch nil))
15346 ;; Make the tags matcher
15347 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15348 (setq tagsmatcher t)
15349 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15350 (while (setq term (pop orterms))
15351 (while (and (equal (substring term -1) "\\") orterms)
15352 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15353 (while (string-match re term)
15354 (setq minus (and (match-end 1)
15355 (equal (match-string 1 term) "-"))
15356 tag (match-string 2 term)
15357 re-p (equal (string-to-char tag) ?{)
15358 level-p (match-end 3)
15359 prop-p (match-end 4)
15360 mm (cond
15361 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15362 (level-p `(= level ,(string-to-number
15363 (match-string 3 term))))
15364 (prop-p
15365 (setq pn (match-string 4 term)
15366 pv (match-string 5 term)
15367 cat-p (equal pn "CATEGORY")
15368 re-p (equal (string-to-char pv) ?{)
15369 pv (substring pv 1 -1))
15370 (if (equal pn "CATEGORY")
15371 (setq gv '(get-text-property (point) 'org-category))
15372 (setq gv `(org-cached-entry-get nil ,pn)))
15373 (if re-p
15374 `(string-match ,pv (or ,gv ""))
15375 `(equal ,pv ,gv)))
15376 (t `(member ,(downcase tag) tags-list)))
15377 mm (if minus (list 'not mm) mm)
15378 term (substring term (match-end 0)))
15379 (push mm tagsmatcher))
15380 (push (if (> (length tagsmatcher) 1)
15381 (cons 'and tagsmatcher)
15382 (car tagsmatcher))
15383 orlist)
15384 (setq tagsmatcher nil))
15385 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15386 (setq tagsmatcher
15387 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15389 ;; Make the todo matcher
15390 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15391 (setq todomatcher t)
15392 (setq orterms (org-split-string todomatch "|") orlist nil)
15393 (while (setq term (pop orterms))
15394 (while (string-match re term)
15395 (setq minus (and (match-end 1)
15396 (equal (match-string 1 term) "-"))
15397 kwd (match-string 2 term)
15398 re-p (equal (string-to-char kwd) ?{)
15399 term (substring term (match-end 0))
15400 mm (if re-p
15401 `(string-match ,(substring kwd 1 -1) todo)
15402 (list 'equal 'todo kwd))
15403 mm (if minus (list 'not mm) mm))
15404 (push mm todomatcher))
15405 (push (if (> (length todomatcher) 1)
15406 (cons 'and todomatcher)
15407 (car todomatcher))
15408 orlist)
15409 (setq todomatcher nil))
15410 (setq todomatcher (if (> (length orlist) 1)
15411 (cons 'or orlist) (car orlist))))
15413 ;; Return the string and lisp forms of the matcher
15414 (setq matcher (if todomatcher
15415 (list 'and tagsmatcher todomatcher)
15416 tagsmatcher))
15417 (cons match0 matcher)))
15419 (defun org-match-any-p (re list)
15420 "Does re match any element of list?"
15421 (setq list (mapcar (lambda (x) (string-match re x)) list))
15422 (delq nil list))
15424 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15425 (defvar org-tags-overlay (org-make-overlay 1 1))
15426 (org-detach-overlay org-tags-overlay)
15428 (defun org-align-tags-here (to-col)
15429 ;; Assumes that this is a headline
15430 (let ((pos (point)) (col (current-column)) tags)
15431 (beginning-of-line 1)
15432 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15433 (< pos (match-beginning 2)))
15434 (progn
15435 (setq tags (match-string 2))
15436 (goto-char (match-beginning 1))
15437 (insert " ")
15438 (delete-region (point) (1+ (match-end 0)))
15439 (backward-char 1)
15440 (move-to-column
15441 (max (1+ (current-column))
15442 (1+ col)
15443 (if (> to-col 0)
15444 to-col
15445 (- (abs to-col) (length tags))))
15447 (insert tags)
15448 (move-to-column (min (current-column) col) t))
15449 (goto-char pos))))
15451 (defun org-set-tags (&optional arg just-align)
15452 "Set the tags for the current headline.
15453 With prefix ARG, realign all tags in headings in the current buffer."
15454 (interactive "P")
15455 (let* ((re (concat "^" outline-regexp))
15456 (current (org-get-tags-string))
15457 (col (current-column))
15458 (org-setting-tags t)
15459 table current-tags inherited-tags ; computed below when needed
15460 tags p0 c0 c1 rpl)
15461 (if arg
15462 (save-excursion
15463 (goto-char (point-min))
15464 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15465 (while (re-search-forward re nil t)
15466 (org-set-tags nil t)
15467 (end-of-line 1)))
15468 (message "All tags realigned to column %d" org-tags-column))
15469 (if just-align
15470 (setq tags current)
15471 ;; Get a new set of tags from the user
15472 (save-excursion
15473 (setq table (or org-tag-alist (org-get-buffer-tags))
15474 org-last-tags-completion-table table
15475 current-tags (org-split-string current ":")
15476 inherited-tags (nreverse
15477 (nthcdr (length current-tags)
15478 (nreverse (org-get-tags-at))))
15479 tags
15480 (if (or (eq t org-use-fast-tag-selection)
15481 (and org-use-fast-tag-selection
15482 (delq nil (mapcar 'cdr table))))
15483 (org-fast-tag-selection
15484 current-tags inherited-tags table
15485 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15486 (let ((org-add-colon-after-tag-completion t))
15487 (org-trim
15488 (org-without-partial-completion
15489 (completing-read "Tags: " 'org-tags-completion-function
15490 nil nil current 'org-tags-history)))))))
15491 (while (string-match "[-+&]+" tags)
15492 ;; No boolean logic, just a list
15493 (setq tags (replace-match ":" t t tags))))
15495 (if (string-match "\\`[\t ]*\\'" tags)
15496 (setq tags "")
15497 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15498 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15500 ;; Insert new tags at the correct column
15501 (beginning-of-line 1)
15502 (cond
15503 ((and (equal current "") (equal tags "")))
15504 ((re-search-forward
15505 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15506 (point-at-eol) t)
15507 (if (equal tags "")
15508 (setq rpl "")
15509 (goto-char (match-beginning 0))
15510 (setq c0 (current-column) p0 (point)
15511 c1 (max (1+ c0) (if (> org-tags-column 0)
15512 org-tags-column
15513 (- (- org-tags-column) (length tags))))
15514 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15515 (replace-match rpl t t)
15516 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
15517 tags)
15518 (t (error "Tags alignment failed")))
15519 (move-to-column col)
15520 (unless just-align
15521 (run-hooks 'org-after-tags-change-hook)))))
15523 (defun org-change-tag-in-region (beg end tag off)
15524 "Add or remove TAG for each entry in the region.
15525 This works in the agenda, and also in an org-mode buffer."
15526 (interactive
15527 (list (region-beginning) (region-end)
15528 (let ((org-last-tags-completion-table
15529 (if (org-mode-p)
15530 (org-get-buffer-tags)
15531 (org-global-tags-completion-table))))
15532 (completing-read
15533 "Tag: " 'org-tags-completion-function nil nil nil
15534 'org-tags-history))
15535 (progn
15536 (message "[s]et or [r]emove? ")
15537 (equal (read-char-exclusive) ?r))))
15538 (if (fboundp 'deactivate-mark) (deactivate-mark))
15539 (let ((agendap (equal major-mode 'org-agenda-mode))
15540 l1 l2 m buf pos newhead (cnt 0))
15541 (goto-char end)
15542 (setq l2 (1- (org-current-line)))
15543 (goto-char beg)
15544 (setq l1 (org-current-line))
15545 (loop for l from l1 to l2 do
15546 (goto-line l)
15547 (setq m (get-text-property (point) 'org-hd-marker))
15548 (when (or (and (org-mode-p) (org-on-heading-p))
15549 (and agendap m))
15550 (setq buf (if agendap (marker-buffer m) (current-buffer))
15551 pos (if agendap m (point)))
15552 (with-current-buffer buf
15553 (save-excursion
15554 (save-restriction
15555 (goto-char pos)
15556 (setq cnt (1+ cnt))
15557 (org-toggle-tag tag (if off 'off 'on))
15558 (setq newhead (org-get-heading)))))
15559 (and agendap (org-agenda-change-all-lines newhead m))))
15560 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15562 (defun org-tags-completion-function (string predicate &optional flag)
15563 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15564 (confirm (lambda (x) (stringp (car x)))))
15565 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15566 (setq s1 (match-string 1 string)
15567 s2 (match-string 2 string))
15568 (setq s1 "" s2 string))
15569 (cond
15570 ((eq flag nil)
15571 ;; try completion
15572 (setq rtn (try-completion s2 ctable confirm))
15573 (if (stringp rtn)
15574 (setq rtn
15575 (concat s1 s2 (substring rtn (length s2))
15576 (if (and org-add-colon-after-tag-completion
15577 (assoc rtn ctable))
15578 ":" ""))))
15579 rtn)
15580 ((eq flag t)
15581 ;; all-completions
15582 (all-completions s2 ctable confirm)
15584 ((eq flag 'lambda)
15585 ;; exact match?
15586 (assoc s2 ctable)))
15589 (defun org-fast-tag-insert (kwd tags face &optional end)
15590 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15591 (insert (format "%-12s" (concat kwd ":"))
15592 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15593 (or end "")))
15595 (defun org-fast-tag-show-exit (flag)
15596 (save-excursion
15597 (goto-line 3)
15598 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15599 (replace-match ""))
15600 (when flag
15601 (end-of-line 1)
15602 (move-to-column (- (window-width) 19) t)
15603 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15605 (defun org-set-current-tags-overlay (current prefix)
15606 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15607 (if (featurep 'xemacs)
15608 (org-overlay-display org-tags-overlay (concat prefix s)
15609 'secondary-selection)
15610 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15611 (org-overlay-display org-tags-overlay (concat prefix s)))))
15613 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15614 "Fast tag selection with single keys.
15615 CURRENT is the current list of tags in the headline, INHERITED is the
15616 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15617 possibly with grouping information. TODO-TABLE is a similar table with
15618 TODO keywords, should these have keys assigned to them.
15619 If the keys are nil, a-z are automatically assigned.
15620 Returns the new tags string, or nil to not change the current settings."
15621 (let* ((fulltable (append table todo-table))
15622 (maxlen (apply 'max (mapcar
15623 (lambda (x)
15624 (if (stringp (car x)) (string-width (car x)) 0))
15625 fulltable)))
15626 (buf (current-buffer))
15627 (expert (eq org-fast-tag-selection-single-key 'expert))
15628 (buffer-tags nil)
15629 (fwidth (+ maxlen 3 1 3))
15630 (ncol (/ (- (window-width) 4) fwidth))
15631 (i-face 'org-done)
15632 (c-face 'org-todo)
15633 tg cnt e c char c1 c2 ntable tbl rtn
15634 ov-start ov-end ov-prefix
15635 (exit-after-next org-fast-tag-selection-single-key)
15636 (done-keywords org-done-keywords)
15637 groups ingroup)
15638 (save-excursion
15639 (beginning-of-line 1)
15640 (if (looking-at
15641 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15642 (setq ov-start (match-beginning 1)
15643 ov-end (match-end 1)
15644 ov-prefix "")
15645 (setq ov-start (1- (point-at-eol))
15646 ov-end (1+ ov-start))
15647 (skip-chars-forward "^\n\r")
15648 (setq ov-prefix
15649 (concat
15650 (buffer-substring (1- (point)) (point))
15651 (if (> (current-column) org-tags-column)
15653 (make-string (- org-tags-column (current-column)) ?\ ))))))
15654 (org-move-overlay org-tags-overlay ov-start ov-end)
15655 (save-window-excursion
15656 (if expert
15657 (set-buffer (get-buffer-create " *Org tags*"))
15658 (delete-other-windows)
15659 (split-window-vertically)
15660 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
15661 (erase-buffer)
15662 (org-set-local 'org-done-keywords done-keywords)
15663 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15664 (org-fast-tag-insert "Current" current c-face "\n\n")
15665 (org-fast-tag-show-exit exit-after-next)
15666 (org-set-current-tags-overlay current ov-prefix)
15667 (setq tbl fulltable char ?a cnt 0)
15668 (while (setq e (pop tbl))
15669 (cond
15670 ((equal e '(:startgroup))
15671 (push '() groups) (setq ingroup t)
15672 (when (not (= cnt 0))
15673 (setq cnt 0)
15674 (insert "\n"))
15675 (insert "{ "))
15676 ((equal e '(:endgroup))
15677 (setq ingroup nil cnt 0)
15678 (insert "}\n"))
15680 (setq tg (car e) c2 nil)
15681 (if (cdr e)
15682 (setq c (cdr e))
15683 ;; automatically assign a character.
15684 (setq c1 (string-to-char
15685 (downcase (substring
15686 tg (if (= (string-to-char tg) ?@) 1 0)))))
15687 (if (or (rassoc c1 ntable) (rassoc c1 table))
15688 (while (or (rassoc char ntable) (rassoc char table))
15689 (setq char (1+ char)))
15690 (setq c2 c1))
15691 (setq c (or c2 char)))
15692 (if ingroup (push tg (car groups)))
15693 (setq tg (org-add-props tg nil 'face
15694 (cond
15695 ((not (assoc tg table))
15696 (org-get-todo-face tg))
15697 ((member tg current) c-face)
15698 ((member tg inherited) i-face)
15699 (t nil))))
15700 (if (and (= cnt 0) (not ingroup)) (insert " "))
15701 (insert "[" c "] " tg (make-string
15702 (- fwidth 4 (length tg)) ?\ ))
15703 (push (cons tg c) ntable)
15704 (when (= (setq cnt (1+ cnt)) ncol)
15705 (insert "\n")
15706 (if ingroup (insert " "))
15707 (setq cnt 0)))))
15708 (setq ntable (nreverse ntable))
15709 (insert "\n")
15710 (goto-char (point-min))
15711 (if (and (not expert) (fboundp 'fit-window-to-buffer))
15712 (fit-window-to-buffer))
15713 (setq rtn
15714 (catch 'exit
15715 (while t
15716 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
15717 (if groups " [!] no groups" " [!]groups")
15718 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15719 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15720 (cond
15721 ((= c ?\r) (throw 'exit t))
15722 ((= c ?!)
15723 (setq groups (not groups))
15724 (goto-char (point-min))
15725 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15726 ((= c ?\C-c)
15727 (if (not expert)
15728 (org-fast-tag-show-exit
15729 (setq exit-after-next (not exit-after-next)))
15730 (setq expert nil)
15731 (delete-other-windows)
15732 (split-window-vertically)
15733 (org-switch-to-buffer-other-window " *Org tags*")
15734 (and (fboundp 'fit-window-to-buffer)
15735 (fit-window-to-buffer))))
15736 ((or (= c ?\C-g)
15737 (and (= c ?q) (not (rassoc c ntable))))
15738 (org-detach-overlay org-tags-overlay)
15739 (setq quit-flag t))
15740 ((= c ?\ )
15741 (setq current nil)
15742 (if exit-after-next (setq exit-after-next 'now)))
15743 ((= c ?\t)
15744 (condition-case nil
15745 (setq tg (completing-read
15746 "Tag: "
15747 (or buffer-tags
15748 (with-current-buffer buf
15749 (org-get-buffer-tags)))))
15750 (quit (setq tg "")))
15751 (when (string-match "\\S-" tg)
15752 (add-to-list 'buffer-tags (list tg))
15753 (if (member tg current)
15754 (setq current (delete tg current))
15755 (push tg current)))
15756 (if exit-after-next (setq exit-after-next 'now)))
15757 ((setq e (rassoc c todo-table) tg (car e))
15758 (with-current-buffer buf
15759 (save-excursion (org-todo tg)))
15760 (if exit-after-next (setq exit-after-next 'now)))
15761 ((setq e (rassoc c ntable) tg (car e))
15762 (if (member tg current)
15763 (setq current (delete tg current))
15764 (loop for g in groups do
15765 (if (member tg g)
15766 (mapc (lambda (x)
15767 (setq current (delete x current)))
15768 g)))
15769 (push tg current))
15770 (if exit-after-next (setq exit-after-next 'now))))
15772 ;; Create a sorted list
15773 (setq current
15774 (sort current
15775 (lambda (a b)
15776 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15777 (if (eq exit-after-next 'now) (throw 'exit t))
15778 (goto-char (point-min))
15779 (beginning-of-line 2)
15780 (delete-region (point) (point-at-eol))
15781 (org-fast-tag-insert "Current" current c-face)
15782 (org-set-current-tags-overlay current ov-prefix)
15783 (while (re-search-forward
15784 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
15785 (setq tg (match-string 1))
15786 (add-text-properties
15787 (match-beginning 1) (match-end 1)
15788 (list 'face
15789 (cond
15790 ((member tg current) c-face)
15791 ((member tg inherited) i-face)
15792 (t (get-text-property (match-beginning 1) 'face))))))
15793 (goto-char (point-min)))))
15794 (org-detach-overlay org-tags-overlay)
15795 (if rtn
15796 (mapconcat 'identity current ":")
15797 nil))))
15799 (defun org-get-tags-string ()
15800 "Get the TAGS string in the current headline."
15801 (unless (org-on-heading-p t)
15802 (error "Not on a heading"))
15803 (save-excursion
15804 (beginning-of-line 1)
15805 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15806 (org-match-string-no-properties 1)
15807 "")))
15809 (defun org-get-tags ()
15810 "Get the list of tags specified in the current headline."
15811 (org-split-string (org-get-tags-string) ":"))
15813 (defun org-get-buffer-tags ()
15814 "Get a table of all tags used in the buffer, for completion."
15815 (let (tags)
15816 (save-excursion
15817 (goto-char (point-min))
15818 (while (re-search-forward
15819 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
15820 (when (equal (char-after (point-at-bol 0)) ?*)
15821 (mapc (lambda (x) (add-to-list 'tags x))
15822 (org-split-string (org-match-string-no-properties 1) ":")))))
15823 (mapcar 'list tags)))
15826 ;;;; Properties
15828 ;;; Setting and retrieving properties
15830 (defconst org-special-properties
15831 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
15832 "TIMESTAMP" "TIMESTAMP_IA")
15833 "The special properties valid in Org-mode.
15835 These are properties that are not defined in the property drawer,
15836 but in some other way.")
15838 (defconst org-default-properties
15839 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
15840 "LOCATION" "LOGGING" "COLUMNS")
15841 "Some properties that are used by Org-mode for various purposes.
15842 Being in this list makes sure that they are offered for completion.")
15844 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15845 "Regular expression matching the first line of a property drawer.")
15847 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15848 "Regular expression matching the first line of a property drawer.")
15850 (defun org-property-action ()
15851 "Do an action on properties."
15852 (interactive)
15853 (let (c)
15854 (org-at-property-p)
15855 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15856 (setq c (read-char-exclusive))
15857 (cond
15858 ((equal c ?s)
15859 (call-interactively 'org-set-property))
15860 ((equal c ?d)
15861 (call-interactively 'org-delete-property))
15862 ((equal c ?D)
15863 (call-interactively 'org-delete-property-globally))
15864 ((equal c ?c)
15865 (call-interactively 'org-compute-property-at-point))
15866 (t (error "No such property action %c" c)))))
15868 (defun org-at-property-p ()
15869 "Is the cursor in a property line?"
15870 ;; FIXME: Does not check if we are actually in the drawer.
15871 ;; FIXME: also returns true on any drawers.....
15872 ;; This is used by C-c C-c for property action.
15873 (save-excursion
15874 (beginning-of-line 1)
15875 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
15877 (defmacro org-with-point-at (pom &rest body)
15878 "Move to buffer and point of point-or-marker POM for the duration of BODY."
15879 (declare (indent 1) (debug t))
15880 `(save-excursion
15881 (if (markerp pom) (set-buffer (marker-buffer pom)))
15882 (save-excursion
15883 (goto-char (or pom (point)))
15884 ,@body)))
15886 (defun org-get-property-block (&optional beg end force)
15887 "Return the (beg . end) range of the body of the property drawer.
15888 BEG and END can be beginning and end of subtree, if not given
15889 they will be found.
15890 If the drawer does not exist and FORCE is non-nil, create the drawer."
15891 (catch 'exit
15892 (save-excursion
15893 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
15894 (end (or end (progn (outline-next-heading) (point)))))
15895 (goto-char beg)
15896 (if (re-search-forward org-property-start-re end t)
15897 (setq beg (1+ (match-end 0)))
15898 (if force
15899 (save-excursion
15900 (org-insert-property-drawer)
15901 (setq end (progn (outline-next-heading) (point))))
15902 (throw 'exit nil))
15903 (goto-char beg)
15904 (if (re-search-forward org-property-start-re end t)
15905 (setq beg (1+ (match-end 0)))))
15906 (if (re-search-forward org-property-end-re end t)
15907 (setq end (match-beginning 0))
15908 (or force (throw 'exit nil))
15909 (goto-char beg)
15910 (setq end beg)
15911 (org-indent-line-function)
15912 (insert ":END:\n"))
15913 (cons beg end)))))
15915 (defun org-entry-properties (&optional pom which)
15916 "Get all properties of the entry at point-or-marker POM.
15917 This includes the TODO keyword, the tags, time strings for deadline,
15918 scheduled, and clocking, and any additional properties defined in the
15919 entry. The return value is an alist, keys may occur multiple times
15920 if the property key was used several times.
15921 POM may also be nil, in which case the current entry is used.
15922 If WHICH is nil or `all', get all properties. If WHICH is
15923 `special' or `standard', only get that subclass."
15924 (setq which (or which 'all))
15925 (org-with-point-at pom
15926 (let ((clockstr (substring org-clock-string 0 -1))
15927 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
15928 beg end range props sum-props key value string clocksum)
15929 (save-excursion
15930 (when (condition-case nil (org-back-to-heading t) (error nil))
15931 (setq beg (point))
15932 (setq sum-props (get-text-property (point) 'org-summaries))
15933 (setq clocksum (get-text-property (point) :org-clock-minutes))
15934 (outline-next-heading)
15935 (setq end (point))
15936 (when (memq which '(all special))
15937 ;; Get the special properties, like TODO and tags
15938 (goto-char beg)
15939 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15940 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15941 (when (looking-at org-priority-regexp)
15942 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15943 (when (and (setq value (org-get-tags-string))
15944 (string-match "\\S-" value))
15945 (push (cons "TAGS" value) props))
15946 (when (setq value (org-get-tags-at))
15947 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
15948 props))
15949 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15950 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
15951 string (if (equal key clockstr)
15952 (org-no-properties
15953 (org-trim
15954 (buffer-substring
15955 (match-beginning 3) (goto-char (point-at-eol)))))
15956 (substring (org-match-string-no-properties 3) 1 -1)))
15957 (unless key
15958 (if (= (char-after (match-beginning 3)) ?\[)
15959 (setq key "TIMESTAMP_IA")
15960 (setq key "TIMESTAMP")))
15961 (when (or (equal key clockstr) (not (assoc key props)))
15962 (push (cons key string) props)))
15966 (when (memq which '(all standard))
15967 ;; Get the standard properties, like :PORP: ...
15968 (setq range (org-get-property-block beg end))
15969 (when range
15970 (goto-char (car range))
15971 (while (re-search-forward
15972 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15973 (cdr range) t)
15974 (setq key (org-match-string-no-properties 1)
15975 value (org-trim (or (org-match-string-no-properties 2) "")))
15976 (unless (member key excluded)
15977 (push (cons key (or value "")) props)))))
15978 (if clocksum
15979 (push (cons "CLOCKSUM"
15980 (org-column-number-to-string (/ (float clocksum) 60.)
15981 'add_times))
15982 props))
15983 (append sum-props (nreverse props)))))))
15985 (defun org-entry-get (pom property &optional inherit)
15986 "Get value of PROPERTY for entry at point-or-marker POM.
15987 If INHERIT is non-nil and the entry does not have the property,
15988 then also check higher levels of the hierarchy.
15989 If the property is present but empty, the return value is the empty string.
15990 If the property is not present at all, nil is returned."
15991 (org-with-point-at pom
15992 (if inherit
15993 (org-entry-get-with-inheritance property)
15994 (if (member property org-special-properties)
15995 ;; We need a special property. Use brute force, get all properties.
15996 (cdr (assoc property (org-entry-properties nil 'special)))
15997 (let ((range (org-get-property-block)))
15998 (if (and range
15999 (goto-char (car range))
16000 (re-search-forward
16001 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
16002 (cdr range) t))
16003 ;; Found the property, return it.
16004 (if (match-end 1)
16005 (org-match-string-no-properties 1)
16006 "")))))))
16008 (defun org-entry-delete (pom property)
16009 "Delete the property PROPERTY from entry at point-or-marker POM."
16010 (org-with-point-at pom
16011 (if (member property org-special-properties)
16012 nil ; cannot delete these properties.
16013 (let ((range (org-get-property-block)))
16014 (if (and range
16015 (goto-char (car range))
16016 (re-search-forward
16017 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
16018 (cdr range) t))
16019 (progn
16020 (delete-region (match-beginning 0) (1+ (point-at-eol)))
16022 nil)))))
16024 ;; Multi-values properties are properties that contain multiple values
16025 ;; These values are assumed to be single words, separated by whitespace.
16026 (defun org-entry-add-to-multivalued-property (pom property value)
16027 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16028 (let* ((old (org-entry-get pom property))
16029 (values (and old (org-split-string old "[ \t]"))))
16030 (unless (member value values)
16031 (setq values (cons value values))
16032 (org-entry-put pom property
16033 (mapconcat 'identity values " ")))))
16035 (defun org-entry-remove-from-multivalued-property (pom property value)
16036 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16037 (let* ((old (org-entry-get pom property))
16038 (values (and old (org-split-string old "[ \t]"))))
16039 (when (member value values)
16040 (setq values (delete value values))
16041 (org-entry-put pom property
16042 (mapconcat 'identity values " ")))))
16044 (defun org-entry-member-in-multivalued-property (pom property value)
16045 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16046 (let* ((old (org-entry-get pom property))
16047 (values (and old (org-split-string old "[ \t]"))))
16048 (member value values)))
16050 (defvar org-entry-property-inherited-from (make-marker))
16052 (defun org-entry-get-with-inheritance (property)
16053 "Get entry property, and search higher levels if not present."
16054 (let (tmp)
16055 (save-excursion
16056 (save-restriction
16057 (widen)
16058 (catch 'ex
16059 (while t
16060 (when (setq tmp (org-entry-get nil property))
16061 (org-back-to-heading t)
16062 (move-marker org-entry-property-inherited-from (point))
16063 (throw 'ex tmp))
16064 (or (org-up-heading-safe) (throw 'ex nil)))))
16065 (or tmp (cdr (assoc property org-local-properties))
16066 (cdr (assoc property org-global-properties))))))
16068 (defun org-entry-put (pom property value)
16069 "Set PROPERTY to VALUE for entry at point-or-marker POM."
16070 (org-with-point-at pom
16071 (org-back-to-heading t)
16072 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
16073 range)
16074 (cond
16075 ((equal property "TODO")
16076 (when (and (stringp value) (string-match "\\S-" value)
16077 (not (member value org-todo-keywords-1)))
16078 (error "\"%s\" is not a valid TODO state" value))
16079 (if (or (not value)
16080 (not (string-match "\\S-" value)))
16081 (setq value 'none))
16082 (org-todo value)
16083 (org-set-tags nil 'align))
16084 ((equal property "PRIORITY")
16085 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
16086 (string-to-char value) ?\ ))
16087 (org-set-tags nil 'align))
16088 ((equal property "SCHEDULED")
16089 (if (re-search-forward org-scheduled-time-regexp end t)
16090 (cond
16091 ((eq value 'earlier) (org-timestamp-change -1 'day))
16092 ((eq value 'later) (org-timestamp-change 1 'day))
16093 (t (call-interactively 'org-schedule)))
16094 (call-interactively 'org-schedule)))
16095 ((equal property "DEADLINE")
16096 (if (re-search-forward org-deadline-time-regexp end t)
16097 (cond
16098 ((eq value 'earlier) (org-timestamp-change -1 'day))
16099 ((eq value 'later) (org-timestamp-change 1 'day))
16100 (t (call-interactively 'org-deadline)))
16101 (call-interactively 'org-deadline)))
16102 ((member property org-special-properties)
16103 (error "The %s property can not yet be set with `org-entry-put'"
16104 property))
16105 (t ; a non-special property
16106 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
16107 (setq range (org-get-property-block beg end 'force))
16108 (goto-char (car range))
16109 (if (re-search-forward
16110 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
16111 (progn
16112 (delete-region (match-beginning 1) (match-end 1))
16113 (goto-char (match-beginning 1)))
16114 (goto-char (cdr range))
16115 (insert "\n")
16116 (backward-char 1)
16117 (org-indent-line-function)
16118 (insert ":" property ":"))
16119 (and value (insert " " value))
16120 (org-indent-line-function)))))))
16122 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
16123 "Get all property keys in the current buffer.
16124 With INCLUDE-SPECIALS, also list the special properties that relect things
16125 like tags and TODO state.
16126 With INCLUDE-DEFAULTS, also include properties that has special meaning
16127 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
16128 With INCLUDE-COLUMNS, also include property names given in COLUMN
16129 formats in the current buffer."
16130 (let (rtn range cfmt cols)
16131 (save-excursion
16132 (save-restriction
16133 (widen)
16134 (goto-char (point-min))
16135 (while (re-search-forward org-property-start-re nil t)
16136 (setq range (org-get-property-block))
16137 (goto-char (car range))
16138 (while (re-search-forward
16139 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
16140 (cdr range) t)
16141 (add-to-list 'rtn (org-match-string-no-properties 1)))
16142 (outline-next-heading))))
16144 (when include-specials
16145 (setq rtn (append org-special-properties rtn)))
16147 (when include-defaults
16148 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
16150 (when include-columns
16151 (save-excursion
16152 (save-restriction
16153 (widen)
16154 (goto-char (point-min))
16155 (while (re-search-forward
16156 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
16157 nil t)
16158 (setq cfmt (match-string 2) s 0)
16159 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
16160 cfmt s)
16161 (setq s (match-end 0)
16162 p (match-string 1 cfmt))
16163 (unless (or (equal p "ITEM")
16164 (member p org-special-properties))
16165 (add-to-list 'rtn (match-string 1 cfmt))))))))
16167 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
16169 (defun org-property-values (key)
16170 "Return a list of all values of property KEY."
16171 (save-excursion
16172 (save-restriction
16173 (widen)
16174 (goto-char (point-min))
16175 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
16176 values)
16177 (while (re-search-forward re nil t)
16178 (add-to-list 'values (org-trim (match-string 1))))
16179 (delete "" values)))))
16181 (defun org-insert-property-drawer ()
16182 "Insert a property drawer into the current entry."
16183 (interactive)
16184 (org-back-to-heading t)
16185 (looking-at outline-regexp)
16186 (let ((indent (- (match-end 0)(match-beginning 0)))
16187 (beg (point))
16188 (re (concat "^[ \t]*" org-keyword-time-regexp))
16189 end hiddenp)
16190 (outline-next-heading)
16191 (setq end (point))
16192 (goto-char beg)
16193 (while (re-search-forward re end t))
16194 (setq hiddenp (org-invisible-p))
16195 (end-of-line 1)
16196 (and (equal (char-after) ?\n) (forward-char 1))
16197 (org-skip-over-state-notes)
16198 (skip-chars-backward " \t\n\r")
16199 (if (eq (char-before) ?*) (forward-char 1))
16200 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
16201 (beginning-of-line 0)
16202 (indent-to-column indent)
16203 (beginning-of-line 2)
16204 (indent-to-column indent)
16205 (beginning-of-line 0)
16206 (if hiddenp
16207 (save-excursion
16208 (org-back-to-heading t)
16209 (hide-entry))
16210 (org-flag-drawer t))))
16212 (defun org-set-property (property value)
16213 "In the current entry, set PROPERTY to VALUE.
16214 When called interactively, this will prompt for a property name, offering
16215 completion on existing and default properties. And then it will prompt
16216 for a value, offering competion either on allowed values (via an inherited
16217 xxx_ALL property) or on existing values in other instances of this property
16218 in the current file."
16219 (interactive
16220 (let* ((prop (completing-read
16221 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
16222 (cur (org-entry-get nil prop))
16223 (allowed (org-property-get-allowed-values nil prop 'table))
16224 (existing (mapcar 'list (org-property-values prop)))
16225 (val (if allowed
16226 (completing-read "Value: " allowed nil 'req-match)
16227 (completing-read
16228 (concat "Value" (if (and cur (string-match "\\S-" cur))
16229 (concat "[" cur "]") "")
16230 ": ")
16231 existing nil nil "" nil cur))))
16232 (list prop (if (equal val "") cur val))))
16233 (unless (equal (org-entry-get nil property) value)
16234 (org-entry-put nil property value)))
16236 (defun org-delete-property (property)
16237 "In the current entry, delete PROPERTY."
16238 (interactive
16239 (let* ((prop (completing-read
16240 "Property: " (org-entry-properties nil 'standard))))
16241 (list prop)))
16242 (message "Property %s %s" property
16243 (if (org-entry-delete nil property)
16244 "deleted"
16245 "was not present in the entry")))
16247 (defun org-delete-property-globally (property)
16248 "Remove PROPERTY globally, from all entries."
16249 (interactive
16250 (let* ((prop (completing-read
16251 "Globally remove property: "
16252 (mapcar 'list (org-buffer-property-keys)))))
16253 (list prop)))
16254 (save-excursion
16255 (save-restriction
16256 (widen)
16257 (goto-char (point-min))
16258 (let ((cnt 0))
16259 (while (re-search-forward
16260 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16261 nil t)
16262 (setq cnt (1+ cnt))
16263 (replace-match ""))
16264 (message "Property \"%s\" removed from %d entries" property cnt)))))
16266 (defvar org-columns-current-fmt-compiled) ; defined below
16268 (defun org-compute-property-at-point ()
16269 "Compute the property at point.
16270 This looks for an enclosing column format, extracts the operator and
16271 then applies it to the proerty in the column format's scope."
16272 (interactive)
16273 (unless (org-at-property-p)
16274 (error "Not at a property"))
16275 (let ((prop (org-match-string-no-properties 2)))
16276 (org-columns-get-format-and-top-level)
16277 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16278 (error "No operator defined for property %s" prop))
16279 (org-columns-compute prop)))
16281 (defun org-property-get-allowed-values (pom property &optional table)
16282 "Get allowed values for the property PROPERTY.
16283 When TABLE is non-nil, return an alist that can directly be used for
16284 completion."
16285 (let (vals)
16286 (cond
16287 ((equal property "TODO")
16288 (setq vals (org-with-point-at pom
16289 (append org-todo-keywords-1 '("")))))
16290 ((equal property "PRIORITY")
16291 (let ((n org-lowest-priority))
16292 (while (>= n org-highest-priority)
16293 (push (char-to-string n) vals)
16294 (setq n (1- n)))))
16295 ((member property org-special-properties))
16297 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16299 (when (and vals (string-match "\\S-" vals))
16300 (setq vals (car (read-from-string (concat "(" vals ")"))))
16301 (setq vals (mapcar (lambda (x)
16302 (cond ((stringp x) x)
16303 ((numberp x) (number-to-string x))
16304 ((symbolp x) (symbol-name x))
16305 (t "???")))
16306 vals)))))
16307 (if table (mapcar 'list vals) vals)))
16309 (defun org-property-previous-allowed-value (&optional previous)
16310 "Switch to the next allowed value for this property."
16311 (interactive)
16312 (org-property-next-allowed-value t))
16314 (defun org-property-next-allowed-value (&optional previous)
16315 "Switch to the next allowed value for this property."
16316 (interactive)
16317 (unless (org-at-property-p)
16318 (error "Not at a property"))
16319 (let* ((key (match-string 2))
16320 (value (match-string 3))
16321 (allowed (or (org-property-get-allowed-values (point) key)
16322 (and (member value '("[ ]" "[-]" "[X]"))
16323 '("[ ]" "[X]"))))
16324 nval)
16325 (unless allowed
16326 (error "Allowed values for this property have not been defined"))
16327 (if previous (setq allowed (reverse allowed)))
16328 (if (member value allowed)
16329 (setq nval (car (cdr (member value allowed)))))
16330 (setq nval (or nval (car allowed)))
16331 (if (equal nval value)
16332 (error "Only one allowed value for this property"))
16333 (org-at-property-p)
16334 (replace-match (concat " :" key ": " nval) t t)
16335 (org-indent-line-function)
16336 (beginning-of-line 1)
16337 (skip-chars-forward " \t")))
16339 (defun org-find-entry-with-id (ident)
16340 "Locate the entry that contains the ID property with exact value IDENT.
16341 IDENT can be a string, a symbol or a number, this function will search for
16342 the string representation of it.
16343 Return the position where this entry starts, or nil if there is no such entry."
16344 (let ((id (cond
16345 ((stringp ident) ident)
16346 ((symbol-name ident) (symbol-name ident))
16347 ((numberp ident) (number-to-string ident))
16348 (t (error "IDENT %s must be a string, symbol or number" ident))))
16349 (case-fold-search nil))
16350 (save-excursion
16351 (save-restriction
16352 (goto-char (point-min))
16353 (when (re-search-forward
16354 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16355 nil t)
16356 (org-back-to-heading)
16357 (point))))))
16359 ;;; Column View
16361 (defvar org-columns-overlays nil
16362 "Holds the list of current column overlays.")
16364 (defvar org-columns-current-fmt nil
16365 "Local variable, holds the currently active column format.")
16366 (defvar org-columns-current-fmt-compiled nil
16367 "Local variable, holds the currently active column format.
16368 This is the compiled version of the format.")
16369 (defvar org-columns-current-widths nil
16370 "Loval variable, holds the currently widths of fields.")
16371 (defvar org-columns-current-maxwidths nil
16372 "Loval variable, holds the currently active maximum column widths.")
16373 (defvar org-columns-begin-marker (make-marker)
16374 "Points to the position where last a column creation command was called.")
16375 (defvar org-columns-top-level-marker (make-marker)
16376 "Points to the position where current columns region starts.")
16378 (defvar org-columns-map (make-sparse-keymap)
16379 "The keymap valid in column display.")
16381 (defun org-columns-content ()
16382 "Switch to contents view while in columns view."
16383 (interactive)
16384 (org-overview)
16385 (org-content))
16387 (org-defkey org-columns-map "c" 'org-columns-content)
16388 (org-defkey org-columns-map "o" 'org-overview)
16389 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16390 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16391 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16392 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16393 (org-defkey org-columns-map "v" 'org-columns-show-value)
16394 (org-defkey org-columns-map "q" 'org-columns-quit)
16395 (org-defkey org-columns-map "r" 'org-columns-redo)
16396 (org-defkey org-columns-map "g" 'org-columns-redo)
16397 (org-defkey org-columns-map [left] 'backward-char)
16398 (org-defkey org-columns-map "\M-b" 'backward-char)
16399 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16400 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16401 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16402 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16403 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16404 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16405 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16406 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16407 (org-defkey org-columns-map "<" 'org-columns-narrow)
16408 (org-defkey org-columns-map ">" 'org-columns-widen)
16409 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16410 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16411 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16412 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16414 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16415 '("Column"
16416 ["Edit property" org-columns-edit-value t]
16417 ["Next allowed value" org-columns-next-allowed-value t]
16418 ["Previous allowed value" org-columns-previous-allowed-value t]
16419 ["Show full value" org-columns-show-value t]
16420 ["Edit allowed values" org-columns-edit-allowed t]
16421 "--"
16422 ["Edit column attributes" org-columns-edit-attributes t]
16423 ["Increase column width" org-columns-widen t]
16424 ["Decrease column width" org-columns-narrow t]
16425 "--"
16426 ["Move column right" org-columns-move-right t]
16427 ["Move column left" org-columns-move-left t]
16428 ["Add column" org-columns-new t]
16429 ["Delete column" org-columns-delete t]
16430 "--"
16431 ["CONTENTS" org-columns-content t]
16432 ["OVERVIEW" org-overview t]
16433 ["Refresh columns display" org-columns-redo t]
16434 "--"
16435 ["Open link" org-columns-open-link t]
16436 "--"
16437 ["Quit" org-columns-quit t]))
16439 (defun org-columns-new-overlay (beg end &optional string face)
16440 "Create a new column overlay and add it to the list."
16441 (let ((ov (org-make-overlay beg end)))
16442 (org-overlay-put ov 'face (or face 'secondary-selection))
16443 (org-overlay-display ov string face)
16444 (push ov org-columns-overlays)
16445 ov))
16447 (defun org-columns-display-here (&optional props)
16448 "Overlay the current line with column display."
16449 (interactive)
16450 (let* ((fmt org-columns-current-fmt-compiled)
16451 (beg (point-at-bol))
16452 (level-face (save-excursion
16453 (beginning-of-line 1)
16454 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16455 (org-get-level-face 2))))
16456 (color (list :foreground
16457 (face-attribute (or level-face 'default) :foreground)))
16458 props pom property ass width f string ov column val modval)
16459 ;; Check if the entry is in another buffer.
16460 (unless props
16461 (if (eq major-mode 'org-agenda-mode)
16462 (setq pom (or (get-text-property (point) 'org-hd-marker)
16463 (get-text-property (point) 'org-marker))
16464 props (if pom (org-entry-properties pom) nil))
16465 (setq props (org-entry-properties nil))))
16466 ;; Walk the format
16467 (while (setq column (pop fmt))
16468 (setq property (car column)
16469 ass (if (equal property "ITEM")
16470 (cons "ITEM"
16471 (save-match-data
16472 (org-no-properties
16473 (org-remove-tabs
16474 (buffer-substring-no-properties
16475 (point-at-bol) (point-at-eol))))))
16476 (assoc property props))
16477 width (or (cdr (assoc property org-columns-current-maxwidths))
16478 (nth 2 column)
16479 (length property))
16480 f (format "%%-%d.%ds | " width width)
16481 val (or (cdr ass) "")
16482 modval (if (equal property "ITEM")
16483 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16484 string (format f (or modval val)))
16485 ;; Create the overlay
16486 (org-unmodified
16487 (setq ov (org-columns-new-overlay
16488 beg (setq beg (1+ beg)) string
16489 (list color 'org-column)))
16490 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16491 (org-overlay-put ov 'keymap org-columns-map)
16492 (org-overlay-put ov 'org-columns-key property)
16493 (org-overlay-put ov 'org-columns-value (cdr ass))
16494 (org-overlay-put ov 'org-columns-value-modified modval)
16495 (org-overlay-put ov 'org-columns-pom pom)
16496 (org-overlay-put ov 'org-columns-format f))
16497 (if (or (not (char-after beg))
16498 (equal (char-after beg) ?\n))
16499 (let ((inhibit-read-only t))
16500 (save-excursion
16501 (goto-char beg)
16502 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16503 ;; Make the rest of the line disappear.
16504 (org-unmodified
16505 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16506 (org-overlay-put ov 'invisible t)
16507 (org-overlay-put ov 'keymap org-columns-map)
16508 (org-overlay-put ov 'intangible t)
16509 (push ov org-columns-overlays)
16510 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16511 (org-overlay-put ov 'keymap org-columns-map)
16512 (push ov org-columns-overlays)
16513 (let ((inhibit-read-only t))
16514 (put-text-property (max (point-min) (1- (point-at-bol)))
16515 (min (point-max) (1+ (point-at-eol)))
16516 'read-only "Type `e' to edit property")))))
16518 (defvar org-previous-header-line-format nil
16519 "The header line format before column view was turned on.")
16520 (defvar org-columns-inhibit-recalculation nil
16521 "Inhibit recomputing of columns on column view startup.")
16524 (defvar header-line-format)
16525 (defun org-columns-display-here-title ()
16526 "Overlay the newline before the current line with the table title."
16527 (interactive)
16528 (let ((fmt org-columns-current-fmt-compiled)
16529 string (title "")
16530 property width f column str widths)
16531 (while (setq column (pop fmt))
16532 (setq property (car column)
16533 str (or (nth 1 column) property)
16534 width (or (cdr (assoc property org-columns-current-maxwidths))
16535 (nth 2 column)
16536 (length str))
16537 widths (push width widths)
16538 f (format "%%-%d.%ds | " width width)
16539 string (format f str)
16540 title (concat title string)))
16541 (setq title (concat
16542 (org-add-props " " nil 'display '(space :align-to 0))
16543 (org-add-props title nil 'face '(:weight bold :underline t))))
16544 (org-set-local 'org-previous-header-line-format header-line-format)
16545 (org-set-local 'org-columns-current-widths (nreverse widths))
16546 (setq header-line-format title)))
16548 (defun org-columns-remove-overlays ()
16549 "Remove all currently active column overlays."
16550 (interactive)
16551 (when (marker-buffer org-columns-begin-marker)
16552 (with-current-buffer (marker-buffer org-columns-begin-marker)
16553 (when (local-variable-p 'org-previous-header-line-format)
16554 (setq header-line-format org-previous-header-line-format)
16555 (kill-local-variable 'org-previous-header-line-format))
16556 (move-marker org-columns-begin-marker nil)
16557 (move-marker org-columns-top-level-marker nil)
16558 (org-unmodified
16559 (mapc 'org-delete-overlay org-columns-overlays)
16560 (setq org-columns-overlays nil)
16561 (let ((inhibit-read-only t))
16562 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16564 (defun org-columns-cleanup-item (item fmt)
16565 "Remove from ITEM what is a column in the format FMT."
16566 (if (not org-complex-heading-regexp)
16567 item
16568 (when (string-match org-complex-heading-regexp item)
16569 (concat
16570 (org-add-props (concat (match-string 1 item) " ") nil
16571 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16572 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16573 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16574 " " (match-string 4 item)
16575 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16577 (defun org-columns-show-value ()
16578 "Show the full value of the property."
16579 (interactive)
16580 (let ((value (get-char-property (point) 'org-columns-value)))
16581 (message "Value is: %s" (or value ""))))
16583 (defun org-columns-quit ()
16584 "Remove the column overlays and in this way exit column editing."
16585 (interactive)
16586 (org-unmodified
16587 (org-columns-remove-overlays)
16588 (let ((inhibit-read-only t))
16589 (remove-text-properties (point-min) (point-max) '(read-only t))))
16590 (when (eq major-mode 'org-agenda-mode)
16591 (message
16592 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16594 (defun org-columns-check-computed ()
16595 "Check if this column value is computed.
16596 If yes, throw an error indicating that changing it does not make sense."
16597 (let ((val (get-char-property (point) 'org-columns-value)))
16598 (when (and (stringp val)
16599 (get-char-property 0 'org-computed val))
16600 (error "This value is computed from the entry's children"))))
16602 (defun org-columns-todo (&optional arg)
16603 "Change the TODO state during column view."
16604 (interactive "P")
16605 (org-columns-edit-value "TODO"))
16607 (defun org-columns-set-tags-or-toggle (&optional arg)
16608 "Toggle checkbox at point, or set tags for current headline."
16609 (interactive "P")
16610 (if (string-match "\\`\\[[ xX-]\\]\\'"
16611 (get-char-property (point) 'org-columns-value))
16612 (org-columns-next-allowed-value)
16613 (org-columns-edit-value "TAGS")))
16615 (defun org-columns-edit-value (&optional key)
16616 "Edit the value of the property at point in column view.
16617 Where possible, use the standard interface for changing this line."
16618 (interactive)
16619 (org-columns-check-computed)
16620 (let* ((external-key key)
16621 (col (current-column))
16622 (key (or key (get-char-property (point) 'org-columns-key)))
16623 (value (get-char-property (point) 'org-columns-value))
16624 (bol (point-at-bol)) (eol (point-at-eol))
16625 (pom (or (get-text-property bol 'org-hd-marker)
16626 (point))) ; keep despite of compiler waring
16627 (line-overlays
16628 (delq nil (mapcar (lambda (x)
16629 (and (eq (overlay-buffer x) (current-buffer))
16630 (>= (overlay-start x) bol)
16631 (<= (overlay-start x) eol)
16633 org-columns-overlays)))
16634 nval eval allowed)
16635 (cond
16636 ((equal key "CLOCKSUM")
16637 (error "This special column cannot be edited"))
16638 ((equal key "ITEM")
16639 (setq eval '(org-with-point-at pom
16640 (org-edit-headline))))
16641 ((equal key "TODO")
16642 (setq eval '(org-with-point-at pom
16643 (let ((current-prefix-arg
16644 (if external-key current-prefix-arg '(4))))
16645 (call-interactively 'org-todo)))))
16646 ((equal key "PRIORITY")
16647 (setq eval '(org-with-point-at pom
16648 (call-interactively 'org-priority))))
16649 ((equal key "TAGS")
16650 (setq eval '(org-with-point-at pom
16651 (let ((org-fast-tag-selection-single-key
16652 (if (eq org-fast-tag-selection-single-key 'expert)
16653 t org-fast-tag-selection-single-key)))
16654 (call-interactively 'org-set-tags)))))
16655 ((equal key "DEADLINE")
16656 (setq eval '(org-with-point-at pom
16657 (call-interactively 'org-deadline))))
16658 ((equal key "SCHEDULED")
16659 (setq eval '(org-with-point-at pom
16660 (call-interactively 'org-schedule))))
16662 (setq allowed (org-property-get-allowed-values pom key 'table))
16663 (if allowed
16664 (setq nval (completing-read "Value: " allowed nil t))
16665 (setq nval (read-string "Edit: " value)))
16666 (setq nval (org-trim nval))
16667 (when (not (equal nval value))
16668 (setq eval '(org-entry-put pom key nval)))))
16669 (when eval
16670 (let ((inhibit-read-only t))
16671 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
16672 (unwind-protect
16673 (progn
16674 (setq org-columns-overlays
16675 (org-delete-all line-overlays org-columns-overlays))
16676 (mapc 'org-delete-overlay line-overlays)
16677 (org-columns-eval eval))
16678 (org-columns-display-here))))
16679 (move-to-column col)
16680 (if (and (org-mode-p)
16681 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16682 (org-columns-update key))))
16684 (defun org-edit-headline () ; FIXME: this is not columns specific
16685 "Edit the current headline, the part without TODO keyword, TAGS."
16686 (org-back-to-heading)
16687 (when (looking-at org-todo-line-regexp)
16688 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
16689 (txt (match-string 3))
16690 (post "")
16691 txt2)
16692 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
16693 (setq post (match-string 0 txt)
16694 txt (substring txt 0 (match-beginning 0))))
16695 (setq txt2 (read-string "Edit: " txt))
16696 (when (not (equal txt txt2))
16697 (beginning-of-line 1)
16698 (insert pre txt2 post)
16699 (delete-region (point) (point-at-eol))
16700 (org-set-tags nil t)))))
16702 (defun org-columns-edit-allowed ()
16703 "Edit the list of allowed values for the current property."
16704 (interactive)
16705 (let* ((key (get-char-property (point) 'org-columns-key))
16706 (key1 (concat key "_ALL"))
16707 (allowed (org-entry-get (point) key1 t))
16708 nval)
16709 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
16710 (setq nval (read-string "Allowed: " allowed))
16711 (org-entry-put
16712 (cond ((marker-position org-entry-property-inherited-from)
16713 org-entry-property-inherited-from)
16714 ((marker-position org-columns-top-level-marker)
16715 org-columns-top-level-marker))
16716 key1 nval)))
16718 (defmacro org-no-warnings (&rest body)
16719 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
16721 (defun org-columns-eval (form)
16722 (let (hidep)
16723 (save-excursion
16724 (beginning-of-line 1)
16725 ;; `next-line' is needed here, because it skips invisible line.
16726 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
16727 (setq hidep (org-on-heading-p 1)))
16728 (eval form)
16729 (and hidep (hide-entry))))
16731 (defun org-columns-previous-allowed-value ()
16732 "Switch to the previous allowed value for this column."
16733 (interactive)
16734 (org-columns-next-allowed-value t))
16736 (defun org-columns-next-allowed-value (&optional previous)
16737 "Switch to the next allowed value for this column."
16738 (interactive)
16739 (org-columns-check-computed)
16740 (let* ((col (current-column))
16741 (key (get-char-property (point) 'org-columns-key))
16742 (value (get-char-property (point) 'org-columns-value))
16743 (bol (point-at-bol)) (eol (point-at-eol))
16744 (pom (or (get-text-property bol 'org-hd-marker)
16745 (point))) ; keep despite of compiler waring
16746 (line-overlays
16747 (delq nil (mapcar (lambda (x)
16748 (and (eq (overlay-buffer x) (current-buffer))
16749 (>= (overlay-start x) bol)
16750 (<= (overlay-start x) eol)
16752 org-columns-overlays)))
16753 (allowed (or (org-property-get-allowed-values pom key)
16754 (and (equal
16755 (nth 4 (assoc key org-columns-current-fmt-compiled))
16756 'checkbox) '("[ ]" "[X]"))))
16757 nval)
16758 (when (equal key "ITEM")
16759 (error "Cannot edit item headline from here"))
16760 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
16761 (error "Allowed values for this property have not been defined"))
16762 (if (member key '("SCHEDULED" "DEADLINE"))
16763 (setq nval (if previous 'earlier 'later))
16764 (if previous (setq allowed (reverse allowed)))
16765 (if (member value allowed)
16766 (setq nval (car (cdr (member value allowed)))))
16767 (setq nval (or nval (car allowed)))
16768 (if (equal nval value)
16769 (error "Only one allowed value for this property")))
16770 (let ((inhibit-read-only t))
16771 (remove-text-properties (1- bol) eol '(read-only t))
16772 (unwind-protect
16773 (progn
16774 (setq org-columns-overlays
16775 (org-delete-all line-overlays org-columns-overlays))
16776 (mapc 'org-delete-overlay line-overlays)
16777 (org-columns-eval '(org-entry-put pom key nval)))
16778 (org-columns-display-here)))
16779 (move-to-column col)
16780 (if (and (org-mode-p)
16781 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16782 (org-columns-update key))))
16784 (defun org-verify-version (task)
16785 (cond
16786 ((eq task 'columns)
16787 (if (or (featurep 'xemacs)
16788 (< emacs-major-version 22))
16789 (error "Emacs 22 is required for the columns feature")))))
16791 (defun org-columns-open-link (&optional arg)
16792 (interactive "P")
16793 (let ((key (get-char-property (point) 'org-columns-key))
16794 (value (get-char-property (point) 'org-columns-value)))
16795 (org-open-link-from-string arg)))
16797 (defun org-open-link-from-string (s &optional arg)
16798 "Open a link in the string S, as if it was in Org-mode."
16799 (interactive)
16800 (with-temp-buffer
16801 (let ((org-inhibit-startup t))
16802 (org-mode)
16803 (insert s)
16804 (goto-char (point-min))
16805 (org-open-at-point arg))))
16807 (defun org-columns-get-format-and-top-level ()
16808 (let (fmt)
16809 (when (condition-case nil (org-back-to-heading) (error nil))
16810 (move-marker org-entry-property-inherited-from nil)
16811 (setq fmt (org-entry-get nil "COLUMNS" t)))
16812 (setq fmt (or fmt org-columns-default-format))
16813 (org-set-local 'org-columns-current-fmt fmt)
16814 (org-columns-compile-format fmt)
16815 (if (marker-position org-entry-property-inherited-from)
16816 (move-marker org-columns-top-level-marker
16817 org-entry-property-inherited-from)
16818 (move-marker org-columns-top-level-marker (point)))
16819 fmt))
16821 (defun org-columns ()
16822 "Turn on column view on an org-mode file."
16823 (interactive)
16824 (org-verify-version 'columns)
16825 (org-columns-remove-overlays)
16826 (move-marker org-columns-begin-marker (point))
16827 (let (beg end fmt cache maxwidths clocksump)
16828 (setq fmt (org-columns-get-format-and-top-level))
16829 (save-excursion
16830 (goto-char org-columns-top-level-marker)
16831 (setq beg (point))
16832 (unless org-columns-inhibit-recalculation
16833 (org-columns-compute-all))
16834 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
16835 (point-max)))
16836 ;; Get and cache the properties
16837 (goto-char beg)
16838 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
16839 (setq clocksump t)
16840 (save-excursion
16841 (save-restriction
16842 (narrow-to-region beg end)
16843 (org-clock-sum))))
16844 (while (re-search-forward (concat "^" outline-regexp) end t)
16845 (push (cons (org-current-line) (org-entry-properties)) cache))
16846 (when cache
16847 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16848 (org-set-local 'org-columns-current-maxwidths maxwidths)
16849 (org-columns-display-here-title)
16850 (mapc (lambda (x)
16851 (goto-line (car x))
16852 (org-columns-display-here (cdr x)))
16853 cache)))))
16855 (defun org-columns-new (&optional prop title width op fmt &rest rest)
16856 "Insert a new column, to the leeft o the current column."
16857 (interactive)
16858 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
16859 cell)
16860 (setq prop (completing-read
16861 "Property: " (mapcar 'list (org-buffer-property-keys t nil t))
16862 nil nil prop))
16863 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
16864 (setq width (read-string "Column width: " (if width (number-to-string width))))
16865 (if (string-match "\\S-" width)
16866 (setq width (string-to-number width))
16867 (setq width nil))
16868 (setq fmt (completing-read "Summary [none]: "
16869 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox"))
16870 nil t))
16871 (if (string-match "\\S-" fmt)
16872 (setq fmt (intern fmt))
16873 (setq fmt nil))
16874 (if (eq fmt 'none) (setq fmt nil))
16875 (if editp
16876 (progn
16877 (setcar editp prop)
16878 (setcdr editp (list title width nil fmt)))
16879 (setq cell (nthcdr (1- (current-column))
16880 org-columns-current-fmt-compiled))
16881 (setcdr cell (cons (list prop title width nil fmt)
16882 (cdr cell))))
16883 (org-columns-store-format)
16884 (org-columns-redo)))
16886 (defun org-columns-delete ()
16887 "Delete the column at point from columns view."
16888 (interactive)
16889 (let* ((n (current-column))
16890 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
16891 (when (y-or-n-p
16892 (format "Are you sure you want to remove column \"%s\"? " title))
16893 (setq org-columns-current-fmt-compiled
16894 (delq (nth n org-columns-current-fmt-compiled)
16895 org-columns-current-fmt-compiled))
16896 (org-columns-store-format)
16897 (org-columns-redo)
16898 (if (>= (current-column) (length org-columns-current-fmt-compiled))
16899 (backward-char 1)))))
16901 (defun org-columns-edit-attributes ()
16902 "Edit the attributes of the current column."
16903 (interactive)
16904 (let* ((n (current-column))
16905 (info (nth n org-columns-current-fmt-compiled)))
16906 (apply 'org-columns-new info)))
16908 (defun org-columns-widen (arg)
16909 "Make the column wider by ARG characters."
16910 (interactive "p")
16911 (let* ((n (current-column))
16912 (entry (nth n org-columns-current-fmt-compiled))
16913 (width (or (nth 2 entry)
16914 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
16915 (setq width (max 1 (+ width arg)))
16916 (setcar (nthcdr 2 entry) width)
16917 (org-columns-store-format)
16918 (org-columns-redo)))
16920 (defun org-columns-narrow (arg)
16921 "Make the column nrrower by ARG characters."
16922 (interactive "p")
16923 (org-columns-widen (- arg)))
16925 (defun org-columns-move-right ()
16926 "Swap this column with the one to the right."
16927 (interactive)
16928 (let* ((n (current-column))
16929 (cell (nthcdr n org-columns-current-fmt-compiled))
16931 (when (>= n (1- (length org-columns-current-fmt-compiled)))
16932 (error "Cannot shift this column further to the right"))
16933 (setq e (car cell))
16934 (setcar cell (car (cdr cell)))
16935 (setcdr cell (cons e (cdr (cdr cell))))
16936 (org-columns-store-format)
16937 (org-columns-redo)
16938 (forward-char 1)))
16940 (defun org-columns-move-left ()
16941 "Swap this column with the one to the left."
16942 (interactive)
16943 (let* ((n (current-column)))
16944 (when (= n 0)
16945 (error "Cannot shift this column further to the left"))
16946 (backward-char 1)
16947 (org-columns-move-right)
16948 (backward-char 1)))
16950 (defun org-columns-store-format ()
16951 "Store the text version of the current columns format in appropriate place.
16952 This is either in the COLUMNS property of the node starting the current column
16953 display, or in the #+COLUMNS line of the current buffer."
16954 (let (fmt (cnt 0))
16955 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
16956 (org-set-local 'org-columns-current-fmt fmt)
16957 (if (marker-position org-columns-top-level-marker)
16958 (save-excursion
16959 (goto-char org-columns-top-level-marker)
16960 (if (and (org-at-heading-p)
16961 (org-entry-get nil "COLUMNS"))
16962 (org-entry-put nil "COLUMNS" fmt)
16963 (goto-char (point-min))
16964 ;; Overwrite all #+COLUMNS lines....
16965 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
16966 (setq cnt (1+ cnt))
16967 (replace-match (concat "#+COLUMNS: " fmt) t t))
16968 (unless (> cnt 0)
16969 (goto-char (point-min))
16970 (or (org-on-heading-p t) (outline-next-heading))
16971 (let ((inhibit-read-only t))
16972 (insert-before-markers "#+COLUMNS: " fmt "\n")))
16973 (org-set-local 'org-columns-default-format fmt))))))
16975 (defvar org-overriding-columns-format nil
16976 "When set, overrides any other definition.")
16977 (defvar org-agenda-view-columns-initially nil
16978 "When set, switch to columns view immediately after creating the agenda.")
16980 (defun org-agenda-columns ()
16981 "Turn on column view in the agenda."
16982 (interactive)
16983 (org-verify-version 'columns)
16984 (org-columns-remove-overlays)
16985 (move-marker org-columns-begin-marker (point))
16986 (let (fmt cache maxwidths m)
16987 (cond
16988 ((and (local-variable-p 'org-overriding-columns-format)
16989 org-overriding-columns-format)
16990 (setq fmt org-overriding-columns-format))
16991 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
16992 (setq fmt (org-entry-get m "COLUMNS" t)))
16993 ((and (boundp 'org-columns-current-fmt)
16994 (local-variable-p 'org-columns-current-fmt)
16995 org-columns-current-fmt)
16996 (setq fmt org-columns-current-fmt))
16997 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
16998 (setq m (get-text-property m 'org-hd-marker))
16999 (setq fmt (org-entry-get m "COLUMNS" t))))
17000 (setq fmt (or fmt org-columns-default-format))
17001 (org-set-local 'org-columns-current-fmt fmt)
17002 (org-columns-compile-format fmt)
17003 (save-excursion
17004 ;; Get and cache the properties
17005 (goto-char (point-min))
17006 (while (not (eobp))
17007 (when (setq m (or (get-text-property (point) 'org-hd-marker)
17008 (get-text-property (point) 'org-marker)))
17009 (push (cons (org-current-line) (org-entry-properties m)) cache))
17010 (beginning-of-line 2))
17011 (when cache
17012 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17013 (org-set-local 'org-columns-current-maxwidths maxwidths)
17014 (org-columns-display-here-title)
17015 (mapc (lambda (x)
17016 (goto-line (car x))
17017 (org-columns-display-here (cdr x)))
17018 cache)))))
17020 (defun org-columns-get-autowidth-alist (s cache)
17021 "Derive the maximum column widths from the format and the cache."
17022 (let ((start 0) rtn)
17023 (while (string-match (org-re "%\\([[:alpha:]]\\S-*\\)") s start)
17024 (push (cons (match-string 1 s) 1) rtn)
17025 (setq start (match-end 0)))
17026 (mapc (lambda (x)
17027 (setcdr x (apply 'max
17028 (mapcar
17029 (lambda (y)
17030 (length (or (cdr (assoc (car x) (cdr y))) " ")))
17031 cache))))
17032 rtn)
17033 rtn))
17035 (defun org-columns-compute-all ()
17036 "Compute all columns that have operators defined."
17037 (org-unmodified
17038 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
17039 (let ((columns org-columns-current-fmt-compiled) col)
17040 (while (setq col (pop columns))
17041 (when (nth 3 col)
17042 (save-excursion
17043 (org-columns-compute (car col)))))))
17045 (defun org-columns-update (property)
17046 "Recompute PROPERTY, and update the columns display for it."
17047 (org-columns-compute property)
17048 (let (fmt val pos)
17049 (save-excursion
17050 (mapc (lambda (ov)
17051 (when (equal (org-overlay-get ov 'org-columns-key) property)
17052 (setq pos (org-overlay-start ov))
17053 (goto-char pos)
17054 (when (setq val (cdr (assoc property
17055 (get-text-property
17056 (point-at-bol) 'org-summaries))))
17057 (setq fmt (org-overlay-get ov 'org-columns-format))
17058 (org-overlay-put ov 'org-columns-value val)
17059 (org-overlay-put ov 'display (format fmt val)))))
17060 org-columns-overlays))))
17062 (defun org-columns-compute (property)
17063 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
17064 (interactive)
17065 (let* ((re (concat "^" outline-regexp))
17066 (lmax 30) ; Does anyone use deeper levels???
17067 (lsum (make-vector lmax 0))
17068 (lflag (make-vector lmax nil))
17069 (level 0)
17070 (ass (assoc property org-columns-current-fmt-compiled))
17071 (format (nth 4 ass))
17072 (printf (nth 5 ass))
17073 (beg org-columns-top-level-marker)
17074 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
17075 (save-excursion
17076 ;; Find the region to compute
17077 (goto-char beg)
17078 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
17079 (goto-char end)
17080 ;; Walk the tree from the back and do the computations
17081 (while (re-search-backward re beg t)
17082 (setq sumpos (match-beginning 0)
17083 last-level level
17084 level (org-outline-level)
17085 val (org-entry-get nil property)
17086 valflag (and val (string-match "\\S-" val)))
17087 (cond
17088 ((< level last-level)
17089 ;; put the sum of lower levels here as a property
17090 (setq sum (aref lsum last-level) ; current sum
17091 flag (aref lflag last-level) ; any valid entries from children?
17092 str (org-column-number-to-string sum format printf)
17093 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
17094 useval (if flag str1 (if valflag val ""))
17095 sum-alist (get-text-property sumpos 'org-summaries))
17096 (if (assoc property sum-alist)
17097 (setcdr (assoc property sum-alist) useval)
17098 (push (cons property useval) sum-alist)
17099 (org-unmodified
17100 (add-text-properties sumpos (1+ sumpos)
17101 (list 'org-summaries sum-alist))))
17102 (when val
17103 (org-entry-put nil property (if flag str val)))
17104 ;; add current to current level accumulator
17105 (when (or flag valflag)
17106 (aset lsum level (+ (aref lsum level)
17107 (if flag sum (org-column-string-to-number
17108 (if flag str val) format))))
17109 (aset lflag level t))
17110 ;; clear accumulators for deeper levels
17111 (loop for l from (1+ level) to (1- lmax) do
17112 (aset lsum l 0)
17113 (aset lflag l nil)))
17114 ((>= level last-level)
17115 ;; add what we have here to the accumulator for this level
17116 (aset lsum level (+ (aref lsum level)
17117 (org-column-string-to-number (or val "0") format)))
17118 (and valflag (aset lflag level t)))
17119 (t (error "This should not happen")))))))
17121 (defun org-columns-redo ()
17122 "Construct the column display again."
17123 (interactive)
17124 (message "Recomputing columns...")
17125 (save-excursion
17126 (if (marker-position org-columns-begin-marker)
17127 (goto-char org-columns-begin-marker))
17128 (org-columns-remove-overlays)
17129 (if (org-mode-p)
17130 (call-interactively 'org-columns)
17131 (call-interactively 'org-agenda-columns)))
17132 (message "Recomputing columns...done"))
17134 (defun org-columns-not-in-agenda ()
17135 (if (eq major-mode 'org-agenda-mode)
17136 (error "This command is only allowed in Org-mode buffers")))
17139 (defun org-string-to-number (s)
17140 "Convert string to number, and interpret hh:mm:ss."
17141 (if (not (string-match ":" s))
17142 (string-to-number s)
17143 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17144 (while l
17145 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17146 sum)))
17148 (defun org-column-number-to-string (n fmt &optional printf)
17149 "Convert a computed column number to a string value, according to FMT."
17150 (cond
17151 ((eq fmt 'add_times)
17152 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
17153 (format "%d:%02d" h m)))
17154 ((eq fmt 'checkbox)
17155 (cond ((= n (floor n)) "[X]")
17156 ((> n 1.) "[-]")
17157 (t "[ ]")))
17158 (printf (format printf n))
17159 ((eq fmt 'currency)
17160 (format "%.2f" n))
17161 (t (number-to-string n))))
17163 (defun org-column-string-to-number (s fmt)
17164 "Convert a column value to a number that can be used for column computing."
17165 (cond
17166 ((string-match ":" s)
17167 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17168 (while l
17169 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17170 sum))
17171 ((eq fmt 'checkbox)
17172 (if (equal s "[X]") 1. 0.000001))
17173 (t (string-to-number s))))
17175 (defun org-columns-uncompile-format (cfmt)
17176 "Turn the compiled columns format back into a string representation."
17177 (let ((rtn "") e s prop title op width fmt printf)
17178 (while (setq e (pop cfmt))
17179 (setq prop (car e)
17180 title (nth 1 e)
17181 width (nth 2 e)
17182 op (nth 3 e)
17183 fmt (nth 4 e)
17184 printf (nth 5 e))
17185 (cond
17186 ((eq fmt 'add_times) (setq op ":"))
17187 ((eq fmt 'checkbox) (setq op "X"))
17188 ((eq fmt 'add_numbers) (setq op "+"))
17189 ((eq fmt 'currency) (setq op "$")))
17190 (if (and op printf) (setq op (concat op ";" printf)))
17191 (if (equal title prop) (setq title nil))
17192 (setq s (concat "%" (if width (number-to-string width))
17193 prop
17194 (if title (concat "(" title ")"))
17195 (if op (concat "{" op "}"))))
17196 (setq rtn (concat rtn " " s)))
17197 (org-trim rtn)))
17199 (defun org-columns-compile-format (fmt)
17200 "Turn a column format string into an alist of specifications.
17201 The alist has one entry for each column in the format. The elements of
17202 that list are:
17203 property the property
17204 title the title field for the columns
17205 width the column width in characters, can be nil for automatic
17206 operator the operator if any
17207 format the output format for computed results, derived from operator
17208 printf a printf format for computed values"
17209 (let ((start 0) width prop title op f printf)
17210 (setq org-columns-current-fmt-compiled nil)
17211 (while (string-match
17212 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
17213 fmt start)
17214 (setq start (match-end 0)
17215 width (match-string 1 fmt)
17216 prop (match-string 2 fmt)
17217 title (or (match-string 3 fmt) prop)
17218 op (match-string 4 fmt)
17219 f nil
17220 printf nil)
17221 (if width (setq width (string-to-number width)))
17222 (when (and op (string-match ";" op))
17223 (setq printf (substring op (match-end 0))
17224 op (substring op 0 (match-beginning 0))))
17225 (cond
17226 ((equal op "+") (setq f 'add_numbers))
17227 ((equal op "$") (setq f 'currency))
17228 ((equal op ":") (setq f 'add_times))
17229 ((equal op "X") (setq f 'checkbox)))
17230 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
17231 (setq org-columns-current-fmt-compiled
17232 (nreverse org-columns-current-fmt-compiled))))
17235 ;;; Dynamic block for Column view
17237 (defun org-columns-capture-view ()
17238 "Get the column view of the current buffer and return it as a list.
17239 The list will contains the title row and all other rows. Each row is
17240 a list of fields."
17241 (save-excursion
17242 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
17243 (n (length title)) row tbl)
17244 (goto-char (point-min))
17245 (while (re-search-forward "^\\*+ " nil t)
17246 (when (get-char-property (match-beginning 0) 'org-columns-key)
17247 (setq row nil)
17248 (loop for i from 0 to (1- n) do
17249 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
17250 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
17252 row))
17253 (setq row (nreverse row))
17254 (push row tbl)))
17255 (append (list title 'hline) (nreverse tbl)))))
17257 (defun org-dblock-write:columnview (params)
17258 "Write the column view table.
17259 PARAMS is a property list of parameters:
17261 :width enforce same column widths with <N> specifiers.
17262 :id the :ID: property of the entry where the columns view
17263 should be built, as a string. When `local', call locally.
17264 When `global' call column view with the cursor at the beginning
17265 of the buffer (usually this means that the whole buffer switches
17266 to column view).
17267 :hlines When t, insert a hline before each item. When a number, insert
17268 a hline before each level <= that number.
17269 :vlines When t, make each column a colgroup to enforce vertical lines."
17270 (let ((pos (move-marker (make-marker) (point)))
17271 (hlines (plist-get params :hlines))
17272 (vlines (plist-get params :vlines))
17273 tbl id idpos nfields tmp)
17274 (save-excursion
17275 (save-restriction
17276 (when (setq id (plist-get params :id))
17277 (cond ((not id) nil)
17278 ((eq id 'global) (goto-char (point-min)))
17279 ((eq id 'local) nil)
17280 ((setq idpos (org-find-entry-with-id id))
17281 (goto-char idpos))
17282 (t (error "Cannot find entry with :ID: %s" id))))
17283 (org-columns)
17284 (setq tbl (org-columns-capture-view))
17285 (setq nfields (length (car tbl)))
17286 (org-columns-quit)))
17287 (goto-char pos)
17288 (move-marker pos nil)
17289 (when tbl
17290 (when (plist-get params :hlines)
17291 (setq tmp nil)
17292 (while tbl
17293 (if (eq (car tbl) 'hline)
17294 (push (pop tbl) tmp)
17295 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17296 (if (and (not (eq (car tmp) 'hline))
17297 (or (eq hlines t)
17298 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17299 (push 'hline tmp)))
17300 (push (pop tbl) tmp)))
17301 (setq tbl (nreverse tmp)))
17302 (when vlines
17303 (setq tbl (mapcar (lambda (x)
17304 (if (eq 'hline x) x (cons "" x)))
17305 tbl))
17306 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17307 (setq pos (point))
17308 (insert (org-listtable-to-string tbl))
17309 (when (plist-get params :width)
17310 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17311 org-columns-current-widths "|")))
17312 (goto-char pos)
17313 (org-table-align))))
17315 (defun org-listtable-to-string (tbl)
17316 "Convert a listtable TBL to a string that contains the Org-mode table.
17317 The table still need to be alligned. The resulting string has no leading
17318 and tailing newline characters."
17319 (mapconcat
17320 (lambda (x)
17321 (cond
17322 ((listp x)
17323 (concat "|" (mapconcat 'identity x "|") "|"))
17324 ((eq x 'hline) "|-|")
17325 (t (error "Garbage in listtable: %s" x))))
17326 tbl "\n"))
17328 (defun org-insert-columns-dblock ()
17329 "Create a dynamic block capturing a column view table."
17330 (interactive)
17331 (let ((defaults '(:name "columnview" :hlines 1))
17332 (id (completing-read
17333 "Capture columns (local, global, entry with :ID: property) [local]: "
17334 (append '(("global") ("local"))
17335 (mapcar 'list (org-property-values "ID"))))))
17336 (if (equal id "") (setq id 'local))
17337 (if (equal id "global") (setq id 'global))
17338 (setq defaults (append defaults (list :id id)))
17339 (org-create-dblock defaults)
17340 (org-update-dblock)))
17342 ;;;; Timestamps
17344 (defvar org-last-changed-timestamp nil)
17345 (defvar org-time-was-given) ; dynamically scoped parameter
17346 (defvar org-end-time-was-given) ; dynamically scoped parameter
17347 (defvar org-ts-what) ; dynamically scoped parameter
17349 (defun org-time-stamp (arg)
17350 "Prompt for a date/time and insert a time stamp.
17351 If the user specifies a time like HH:MM, or if this command is called
17352 with a prefix argument, the time stamp will contain date and time.
17353 Otherwise, only the date will be included. All parts of a date not
17354 specified by the user will be filled in from the current date/time.
17355 So if you press just return without typing anything, the time stamp
17356 will represent the current date/time. If there is already a timestamp
17357 at the cursor, it will be modified."
17358 (interactive "P")
17359 (let* ((ts nil)
17360 (default-time
17361 ;; Default time is either today, or, when entering a range,
17362 ;; the range start.
17363 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17364 (save-excursion
17365 (re-search-backward
17366 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17367 (- (point) 20) t)))
17368 (apply 'encode-time (org-parse-time-string (match-string 1)))
17369 (current-time)))
17370 (default-input (and ts (org-get-compact-tod ts)))
17371 org-time-was-given org-end-time-was-given time)
17372 (cond
17373 ((and (org-at-timestamp-p)
17374 (eq last-command 'org-time-stamp)
17375 (eq this-command 'org-time-stamp))
17376 (insert "--")
17377 (setq time (let ((this-command this-command))
17378 (org-read-date arg 'totime nil nil default-time default-input)))
17379 (org-insert-time-stamp time (or org-time-was-given arg)))
17380 ((org-at-timestamp-p)
17381 (setq time (let ((this-command this-command))
17382 (org-read-date arg 'totime nil nil default-time default-input)))
17383 (when (org-at-timestamp-p) ; just to get the match data
17384 (replace-match "")
17385 (setq org-last-changed-timestamp
17386 (org-insert-time-stamp
17387 time (or org-time-was-given arg)
17388 nil nil nil (list org-end-time-was-given))))
17389 (message "Timestamp updated"))
17391 (setq time (let ((this-command this-command))
17392 (org-read-date arg 'totime nil nil default-time default-input)))
17393 (org-insert-time-stamp time (or org-time-was-given arg)
17394 nil nil nil (list org-end-time-was-given))))))
17396 ;; FIXME: can we use this for something else????
17397 ;; like computing time differences?????
17398 (defun org-get-compact-tod (s)
17399 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17400 (let* ((t1 (match-string 1 s))
17401 (h1 (string-to-number (match-string 2 s)))
17402 (m1 (string-to-number (match-string 3 s)))
17403 (t2 (and (match-end 4) (match-string 5 s)))
17404 (h2 (and t2 (string-to-number (match-string 6 s))))
17405 (m2 (and t2 (string-to-number (match-string 7 s))))
17406 dh dm)
17407 (if (not t2)
17409 (setq dh (- h2 h1) dm (- m2 m1))
17410 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17411 (concat t1 "+" (number-to-string dh)
17412 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17414 (defun org-time-stamp-inactive (&optional arg)
17415 "Insert an inactive time stamp.
17416 An inactive time stamp is enclosed in square brackets instead of angle
17417 brackets. It is inactive in the sense that it does not trigger agenda entries,
17418 does not link to the calendar and cannot be changed with the S-cursor keys.
17419 So these are more for recording a certain time/date."
17420 (interactive "P")
17421 (let (org-time-was-given org-end-time-was-given time)
17422 (setq time (org-read-date arg 'totime))
17423 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17424 nil nil (list org-end-time-was-given))))
17426 (defvar org-date-ovl (org-make-overlay 1 1))
17427 (org-overlay-put org-date-ovl 'face 'org-warning)
17428 (org-detach-overlay org-date-ovl)
17430 (defvar org-ans1) ; dynamically scoped parameter
17431 (defvar org-ans2) ; dynamically scoped parameter
17433 (defvar org-plain-time-of-day-regexp) ; defined below
17435 (defvar org-read-date-overlay nil)
17436 (defvar org-dcst nil) ; dynamically scoped
17438 (defun org-read-date (&optional with-time to-time from-string prompt
17439 default-time default-input)
17440 "Read a date, possibly a time, and make things smooth for the user.
17441 The prompt will suggest to enter an ISO date, but you can also enter anything
17442 which will at least partially be understood by `parse-time-string'.
17443 Unrecognized parts of the date will default to the current day, month, year,
17444 hour and minute. If this command is called to replace a timestamp at point,
17445 of to enter the second timestamp of a range, the default time is taken from the
17446 existing stamp. For example,
17447 3-2-5 --> 2003-02-05
17448 feb 15 --> currentyear-02-15
17449 sep 12 9 --> 2009-09-12
17450 12:45 --> today 12:45
17451 22 sept 0:34 --> currentyear-09-22 0:34
17452 12 --> currentyear-currentmonth-12
17453 Fri --> nearest Friday (today or later)
17454 etc.
17456 Furthermore you can specify a relative date by giving, as the *first* thing
17457 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17458 change in days weeks, months, years.
17459 With a single plus or minus, the date is relative to today. With a double
17460 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17461 +4d --> four days from today
17462 +4 --> same as above
17463 +2w --> two weeks from today
17464 ++5 --> five days from default date
17466 The function understands only English month and weekday abbreviations,
17467 but this can be configured with the variables `parse-time-months' and
17468 `parse-time-weekdays'.
17470 While prompting, a calendar is popped up - you can also select the
17471 date with the mouse (button 1). The calendar shows a period of three
17472 months. To scroll it to other months, use the keys `>' and `<'.
17473 If you don't like the calendar, turn it off with
17474 \(setq org-read-date-popup-calendar nil)
17476 With optional argument TO-TIME, the date will immediately be converted
17477 to an internal time.
17478 With an optional argument WITH-TIME, the prompt will suggest to also
17479 insert a time. Note that when WITH-TIME is not set, you can still
17480 enter a time, and this function will inform the calling routine about
17481 this change. The calling routine may then choose to change the format
17482 used to insert the time stamp into the buffer to include the time.
17483 With optional argument FROM-STRING, read from this string instead from
17484 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17485 the time/date that is used for everything that is not specified by the
17486 user."
17487 (require 'parse-time)
17488 (let* ((org-time-stamp-rounding-minutes
17489 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
17490 (org-dcst org-display-custom-times)
17491 (ct (org-current-time))
17492 (def (or default-time ct))
17493 (defdecode (decode-time def))
17494 (dummy (progn
17495 (when (< (nth 2 defdecode) org-extend-today-until)
17496 (setcar (nthcdr 2 defdecode) -1)
17497 (setcar (nthcdr 1 defdecode) 59)
17498 (setq def (apply 'encode-time defdecode)
17499 defdecode (decode-time def)))))
17500 (calendar-move-hook nil)
17501 (view-diary-entries-initially nil)
17502 (view-calendar-holidays-initially nil)
17503 (timestr (format-time-string
17504 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17505 (prompt (concat (if prompt (concat prompt " ") "")
17506 (format "Date+time [%s]: " timestr)))
17507 ans (org-ans0 "") org-ans1 org-ans2 final)
17509 (cond
17510 (from-string (setq ans from-string))
17511 (org-read-date-popup-calendar
17512 (save-excursion
17513 (save-window-excursion
17514 (calendar)
17515 (calendar-forward-day (- (time-to-days def)
17516 (calendar-absolute-from-gregorian
17517 (calendar-current-date))))
17518 (org-eval-in-calendar nil t)
17519 (let* ((old-map (current-local-map))
17520 (map (copy-keymap calendar-mode-map))
17521 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17522 (org-defkey map (kbd "RET") 'org-calendar-select)
17523 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17524 'org-calendar-select-mouse)
17525 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17526 'org-calendar-select-mouse)
17527 (org-defkey minibuffer-local-map [(meta shift left)]
17528 (lambda () (interactive)
17529 (org-eval-in-calendar '(calendar-backward-month 1))))
17530 (org-defkey minibuffer-local-map [(meta shift right)]
17531 (lambda () (interactive)
17532 (org-eval-in-calendar '(calendar-forward-month 1))))
17533 (org-defkey minibuffer-local-map [(meta shift up)]
17534 (lambda () (interactive)
17535 (org-eval-in-calendar '(calendar-backward-year 1))))
17536 (org-defkey minibuffer-local-map [(meta shift down)]
17537 (lambda () (interactive)
17538 (org-eval-in-calendar '(calendar-forward-year 1))))
17539 (org-defkey minibuffer-local-map [(shift up)]
17540 (lambda () (interactive)
17541 (org-eval-in-calendar '(calendar-backward-week 1))))
17542 (org-defkey minibuffer-local-map [(shift down)]
17543 (lambda () (interactive)
17544 (org-eval-in-calendar '(calendar-forward-week 1))))
17545 (org-defkey minibuffer-local-map [(shift left)]
17546 (lambda () (interactive)
17547 (org-eval-in-calendar '(calendar-backward-day 1))))
17548 (org-defkey minibuffer-local-map [(shift right)]
17549 (lambda () (interactive)
17550 (org-eval-in-calendar '(calendar-forward-day 1))))
17551 (org-defkey minibuffer-local-map ">"
17552 (lambda () (interactive)
17553 (org-eval-in-calendar '(scroll-calendar-left 1))))
17554 (org-defkey minibuffer-local-map "<"
17555 (lambda () (interactive)
17556 (org-eval-in-calendar '(scroll-calendar-right 1))))
17557 (unwind-protect
17558 (progn
17559 (use-local-map map)
17560 (add-hook 'post-command-hook 'org-read-date-display)
17561 (setq org-ans0 (read-string prompt default-input nil nil))
17562 ;; org-ans0: from prompt
17563 ;; org-ans1: from mouse click
17564 ;; org-ans2: from calendar motion
17565 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17566 (remove-hook 'post-command-hook 'org-read-date-display)
17567 (use-local-map old-map)
17568 (when org-read-date-overlay
17569 (org-delete-overlay org-read-date-overlay)
17570 (setq org-read-date-overlay nil)))))))
17572 (t ; Naked prompt only
17573 (unwind-protect
17574 (setq ans (read-string prompt default-input nil timestr))
17575 (when org-read-date-overlay
17576 (org-delete-overlay org-read-date-overlay)
17577 (setq org-read-date-overlay nil)))))
17579 (setq final (org-read-date-analyze ans def defdecode))
17581 (if to-time
17582 (apply 'encode-time final)
17583 (if (and (boundp 'org-time-was-given) org-time-was-given)
17584 (format "%04d-%02d-%02d %02d:%02d"
17585 (nth 5 final) (nth 4 final) (nth 3 final)
17586 (nth 2 final) (nth 1 final))
17587 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17588 (defvar def)
17589 (defvar defdecode)
17590 (defvar with-time)
17591 (defun org-read-date-display ()
17592 "Display the currrent date prompt interpretation in the minibuffer."
17593 (when org-read-date-display-live
17594 (when org-read-date-overlay
17595 (org-delete-overlay org-read-date-overlay))
17596 (let ((p (point)))
17597 (end-of-line 1)
17598 (while (not (equal (buffer-substring
17599 (max (point-min) (- (point) 4)) (point))
17600 " "))
17601 (insert " "))
17602 (goto-char p))
17603 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17604 " " (or org-ans1 org-ans2)))
17605 (org-end-time-was-given nil)
17606 (f (org-read-date-analyze ans def defdecode))
17607 (fmts (if org-dcst
17608 org-time-stamp-custom-formats
17609 org-time-stamp-formats))
17610 (fmt (if (or with-time
17611 (and (boundp 'org-time-was-given) org-time-was-given))
17612 (cdr fmts)
17613 (car fmts)))
17614 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
17615 (when (and org-end-time-was-given
17616 (string-match org-plain-time-of-day-regexp txt))
17617 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17618 org-end-time-was-given
17619 (substring txt (match-end 0)))))
17620 (setq org-read-date-overlay
17621 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17622 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
17624 (defun org-read-date-analyze (ans def defdecode)
17625 "Analyze the combined answer of the date prompt."
17626 ;; FIXME: cleanup and comment
17627 (let (delta deltan deltaw deltadef year month day
17628 hour minute second wday pm h2 m2 tl wday1)
17630 (when (setq delta (org-read-date-get-relative ans (current-time) def))
17631 (setq ans (replace-match "" t t ans)
17632 deltan (car delta)
17633 deltaw (nth 1 delta)
17634 deltadef (nth 2 delta)))
17636 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
17637 (when (string-match
17638 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17639 (setq year (if (match-end 2)
17640 (string-to-number (match-string 2 ans))
17641 (string-to-number (format-time-string "%Y")))
17642 month (string-to-number (match-string 3 ans))
17643 day (string-to-number (match-string 4 ans)))
17644 (if (< year 100) (setq year (+ 2000 year)))
17645 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17646 t nil ans)))
17647 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17648 ;; If there is a time with am/pm, and *no* time without it, we convert
17649 ;; so that matching will be successful.
17650 (loop for i from 1 to 2 do ; twice, for end time as well
17651 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17652 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17653 (setq hour (string-to-number (match-string 1 ans))
17654 minute (if (match-end 3)
17655 (string-to-number (match-string 3 ans))
17657 pm (equal ?p
17658 (string-to-char (downcase (match-string 4 ans)))))
17659 (if (and (= hour 12) (not pm))
17660 (setq hour 0)
17661 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17662 (setq ans (replace-match (format "%02d:%02d" hour minute)
17663 t t ans))))
17665 ;; Check if a time range is given as a duration
17666 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17667 (setq hour (string-to-number (match-string 1 ans))
17668 h2 (+ hour (string-to-number (match-string 3 ans)))
17669 minute (string-to-number (match-string 2 ans))
17670 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
17671 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17672 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
17674 ;; Check if there is a time range
17675 (when (boundp 'org-end-time-was-given)
17676 (setq org-time-was-given nil)
17677 (when (and (string-match org-plain-time-of-day-regexp ans)
17678 (match-end 8))
17679 (setq org-end-time-was-given (match-string 8 ans))
17680 (setq ans (concat (substring ans 0 (match-beginning 7))
17681 (substring ans (match-end 7))))))
17683 (setq tl (parse-time-string ans)
17684 day (or (nth 3 tl) (nth 3 defdecode))
17685 month (or (nth 4 tl)
17686 (if (and org-read-date-prefer-future
17687 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
17688 (1+ (nth 4 defdecode))
17689 (nth 4 defdecode)))
17690 year (or (nth 5 tl)
17691 (if (and org-read-date-prefer-future
17692 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
17693 (1+ (nth 5 defdecode))
17694 (nth 5 defdecode)))
17695 hour (or (nth 2 tl) (nth 2 defdecode))
17696 minute (or (nth 1 tl) (nth 1 defdecode))
17697 second (or (nth 0 tl) 0)
17698 wday (nth 6 tl))
17699 (when deltan
17700 (unless deltadef
17701 (let ((now (decode-time (current-time))))
17702 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17703 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17704 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17705 ((equal deltaw "m") (setq month (+ month deltan)))
17706 ((equal deltaw "y") (setq year (+ year deltan)))))
17707 (when (and wday (not (nth 3 tl)))
17708 ;; Weekday was given, but no day, so pick that day in the week
17709 ;; on or after the derived date.
17710 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17711 (unless (equal wday wday1)
17712 (setq day (+ day (% (- wday wday1 -7) 7)))))
17713 (if (and (boundp 'org-time-was-given)
17714 (nth 2 tl))
17715 (setq org-time-was-given t))
17716 (if (< year 100) (setq year (+ 2000 year)))
17717 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
17718 (list second minute hour day month year)))
17720 (defvar parse-time-weekdays)
17722 (defun org-read-date-get-relative (s today default)
17723 "Check string S for special relative date string.
17724 TODAY and DEFAULT are internal times, for today and for a default.
17725 Return shift list (N what def-flag)
17726 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17727 N is the number of WHATs to shift.
17728 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17729 the DEFAULT date rather than TODAY."
17730 (when (string-match
17731 (concat
17732 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
17733 "\\([0-9]+\\)?"
17734 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17735 "\\([ \t]\\|$\\)") s)
17736 (let* ((dir (if (match-end 1)
17737 (string-to-char (substring (match-string 1 s) -1))
17738 ?+))
17739 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17740 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17741 (what (if (match-end 3) (match-string 3 s) "d"))
17742 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17743 (date (if rel default today))
17744 (wday (nth 6 (decode-time date)))
17745 delta)
17746 (if wday1
17747 (progn
17748 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17749 (if (= dir ?-) (setq delta (- delta 7)))
17750 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17751 (list delta "d" rel))
17752 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17754 (defun org-eval-in-calendar (form &optional keepdate)
17755 "Eval FORM in the calendar window and return to current window.
17756 Also, store the cursor date in variable org-ans2."
17757 (let ((sw (selected-window)))
17758 (select-window (get-buffer-window "*Calendar*"))
17759 (eval form)
17760 (when (and (not keepdate) (calendar-cursor-to-date))
17761 (let* ((date (calendar-cursor-to-date))
17762 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17763 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17764 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17765 (select-window sw)))
17767 ; ;; Update the prompt to show new default date
17768 ; (save-excursion
17769 ; (goto-char (point-min))
17770 ; (when (and org-ans2
17771 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
17772 ; (get-text-property (match-end 0) 'field))
17773 ; (let ((inhibit-read-only t))
17774 ; (replace-match (concat "[" org-ans2 "]") t t)
17775 ; (add-text-properties (point-min) (1+ (match-end 0))
17776 ; (text-properties-at (1+ (point-min)))))))))
17778 (defun org-calendar-select ()
17779 "Return to `org-read-date' with the date currently selected.
17780 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17781 (interactive)
17782 (when (calendar-cursor-to-date)
17783 (let* ((date (calendar-cursor-to-date))
17784 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17785 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17786 (if (active-minibuffer-window) (exit-minibuffer))))
17788 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17789 "Insert a date stamp for the date given by the internal TIME.
17790 WITH-HM means, use the stamp format that includes the time of the day.
17791 INACTIVE means use square brackets instead of angular ones, so that the
17792 stamp will not contribute to the agenda.
17793 PRE and POST are optional strings to be inserted before and after the
17794 stamp.
17795 The command returns the inserted time stamp."
17796 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17797 stamp)
17798 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17799 (insert-before-markers (or pre ""))
17800 (insert-before-markers (setq stamp (format-time-string fmt time)))
17801 (when (listp extra)
17802 (setq extra (car extra))
17803 (if (and (stringp extra)
17804 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17805 (setq extra (format "-%02d:%02d"
17806 (string-to-number (match-string 1 extra))
17807 (string-to-number (match-string 2 extra))))
17808 (setq extra nil)))
17809 (when extra
17810 (backward-char 1)
17811 (insert-before-markers extra)
17812 (forward-char 1))
17813 (insert-before-markers (or post ""))
17814 stamp))
17816 (defun org-toggle-time-stamp-overlays ()
17817 "Toggle the use of custom time stamp formats."
17818 (interactive)
17819 (setq org-display-custom-times (not org-display-custom-times))
17820 (unless org-display-custom-times
17821 (let ((p (point-min)) (bmp (buffer-modified-p)))
17822 (while (setq p (next-single-property-change p 'display))
17823 (if (and (get-text-property p 'display)
17824 (eq (get-text-property p 'face) 'org-date))
17825 (remove-text-properties
17826 p (setq p (next-single-property-change p 'display))
17827 '(display t))))
17828 (set-buffer-modified-p bmp)))
17829 (if (featurep 'xemacs)
17830 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17831 (org-restart-font-lock)
17832 (setq org-table-may-need-update t)
17833 (if org-display-custom-times
17834 (message "Time stamps are overlayed with custom format")
17835 (message "Time stamp overlays removed")))
17837 (defun org-display-custom-time (beg end)
17838 "Overlay modified time stamp format over timestamp between BED and END."
17839 (let* ((ts (buffer-substring beg end))
17840 t1 w1 with-hm tf time str w2 (off 0))
17841 (save-match-data
17842 (setq t1 (org-parse-time-string ts t))
17843 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
17844 (setq off (- (match-end 0) (match-beginning 0)))))
17845 (setq end (- end off))
17846 (setq w1 (- end beg)
17847 with-hm (and (nth 1 t1) (nth 2 t1))
17848 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17849 time (org-fix-decoded-time t1)
17850 str (org-add-props
17851 (format-time-string
17852 (substring tf 1 -1) (apply 'encode-time time))
17853 nil 'mouse-face 'highlight)
17854 w2 (length str))
17855 (if (not (= w2 w1))
17856 (add-text-properties (1+ beg) (+ 2 beg)
17857 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17858 (if (featurep 'xemacs)
17859 (progn
17860 (put-text-property beg end 'invisible t)
17861 (put-text-property beg end 'end-glyph (make-glyph str)))
17862 (put-text-property beg end 'display str))))
17864 (defun org-translate-time (string)
17865 "Translate all timestamps in STRING to custom format.
17866 But do this only if the variable `org-display-custom-times' is set."
17867 (when org-display-custom-times
17868 (save-match-data
17869 (let* ((start 0)
17870 (re org-ts-regexp-both)
17871 t1 with-hm inactive tf time str beg end)
17872 (while (setq start (string-match re string start))
17873 (setq beg (match-beginning 0)
17874 end (match-end 0)
17875 t1 (save-match-data
17876 (org-parse-time-string (substring string beg end) t))
17877 with-hm (and (nth 1 t1) (nth 2 t1))
17878 inactive (equal (substring string beg (1+ beg)) "[")
17879 tf (funcall (if with-hm 'cdr 'car)
17880 org-time-stamp-custom-formats)
17881 time (org-fix-decoded-time t1)
17882 str (format-time-string
17883 (concat
17884 (if inactive "[" "<") (substring tf 1 -1)
17885 (if inactive "]" ">"))
17886 (apply 'encode-time time))
17887 string (replace-match str t t string)
17888 start (+ start (length str)))))))
17889 string)
17891 (defun org-fix-decoded-time (time)
17892 "Set 0 instead of nil for the first 6 elements of time.
17893 Don't touch the rest."
17894 (let ((n 0))
17895 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17897 (defun org-days-to-time (timestamp-string)
17898 "Difference between TIMESTAMP-STRING and now in days."
17899 (- (time-to-days (org-time-string-to-time timestamp-string))
17900 (time-to-days (current-time))))
17902 (defun org-deadline-close (timestamp-string &optional ndays)
17903 "Is the time in TIMESTAMP-STRING close to the current date?"
17904 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17905 (and (< (org-days-to-time timestamp-string) ndays)
17906 (not (org-entry-is-done-p))))
17908 (defun org-get-wdays (ts)
17909 "Get the deadline lead time appropriate for timestring TS."
17910 (cond
17911 ((<= org-deadline-warning-days 0)
17912 ;; 0 or negative, enforce this value no matter what
17913 (- org-deadline-warning-days))
17914 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
17915 ;; lead time is specified.
17916 (floor (* (string-to-number (match-string 1 ts))
17917 (cdr (assoc (match-string 2 ts)
17918 '(("d" . 1) ("w" . 7)
17919 ("m" . 30.4) ("y" . 365.25)))))))
17920 ;; go for the default.
17921 (t org-deadline-warning-days)))
17923 (defun org-calendar-select-mouse (ev)
17924 "Return to `org-read-date' with the date currently selected.
17925 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17926 (interactive "e")
17927 (mouse-set-point ev)
17928 (when (calendar-cursor-to-date)
17929 (let* ((date (calendar-cursor-to-date))
17930 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17931 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17932 (if (active-minibuffer-window) (exit-minibuffer))))
17934 (defun org-check-deadlines (ndays)
17935 "Check if there are any deadlines due or past due.
17936 A deadline is considered due if it happens within `org-deadline-warning-days'
17937 days from today's date. If the deadline appears in an entry marked DONE,
17938 it is not shown. The prefix arg NDAYS can be used to test that many
17939 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17940 (interactive "P")
17941 (let* ((org-warn-days
17942 (cond
17943 ((equal ndays '(4)) 100000)
17944 (ndays (prefix-numeric-value ndays))
17945 (t (abs org-deadline-warning-days))))
17946 (case-fold-search nil)
17947 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17948 (callback
17949 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17951 (message "%d deadlines past-due or due within %d days"
17952 (org-occur regexp nil callback)
17953 org-warn-days)))
17955 (defun org-check-before-date (date)
17956 "Check if there are deadlines or scheduled entries before DATE."
17957 (interactive (list (org-read-date)))
17958 (let ((case-fold-search nil)
17959 (regexp (concat "\\<\\(" org-deadline-string
17960 "\\|" org-scheduled-string
17961 "\\) *<\\([^>]+\\)>"))
17962 (callback
17963 (lambda () (time-less-p
17964 (org-time-string-to-time (match-string 2))
17965 (org-time-string-to-time date)))))
17966 (message "%d entries before %s"
17967 (org-occur regexp nil callback) date)))
17969 (defun org-evaluate-time-range (&optional to-buffer)
17970 "Evaluate a time range by computing the difference between start and end.
17971 Normally the result is just printed in the echo area, but with prefix arg
17972 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17973 If the time range is actually in a table, the result is inserted into the
17974 next column.
17975 For time difference computation, a year is assumed to be exactly 365
17976 days in order to avoid rounding problems."
17977 (interactive "P")
17979 (org-clock-update-time-maybe)
17980 (save-excursion
17981 (unless (org-at-date-range-p t)
17982 (goto-char (point-at-bol))
17983 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17984 (if (not (org-at-date-range-p t))
17985 (error "Not at a time-stamp range, and none found in current line")))
17986 (let* ((ts1 (match-string 1))
17987 (ts2 (match-string 2))
17988 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17989 (match-end (match-end 0))
17990 (time1 (org-time-string-to-time ts1))
17991 (time2 (org-time-string-to-time ts2))
17992 (t1 (time-to-seconds time1))
17993 (t2 (time-to-seconds time2))
17994 (diff (abs (- t2 t1)))
17995 (negative (< (- t2 t1) 0))
17996 ;; (ys (floor (* 365 24 60 60)))
17997 (ds (* 24 60 60))
17998 (hs (* 60 60))
17999 (fy "%dy %dd %02d:%02d")
18000 (fy1 "%dy %dd")
18001 (fd "%dd %02d:%02d")
18002 (fd1 "%dd")
18003 (fh "%02d:%02d")
18004 y d h m align)
18005 (if havetime
18006 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18008 d (floor (/ diff ds)) diff (mod diff ds)
18009 h (floor (/ diff hs)) diff (mod diff hs)
18010 m (floor (/ diff 60)))
18011 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18013 d (floor (+ (/ diff ds) 0.5))
18014 h 0 m 0))
18015 (if (not to-buffer)
18016 (message "%s" (org-make-tdiff-string y d h m))
18017 (if (org-at-table-p)
18018 (progn
18019 (goto-char match-end)
18020 (setq align t)
18021 (and (looking-at " *|") (goto-char (match-end 0))))
18022 (goto-char match-end))
18023 (if (looking-at
18024 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
18025 (replace-match ""))
18026 (if negative (insert " -"))
18027 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
18028 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
18029 (insert " " (format fh h m))))
18030 (if align (org-table-align))
18031 (message "Time difference inserted")))))
18033 (defun org-make-tdiff-string (y d h m)
18034 (let ((fmt "")
18035 (l nil))
18036 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
18037 l (push y l)))
18038 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
18039 l (push d l)))
18040 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
18041 l (push h l)))
18042 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
18043 l (push m l)))
18044 (apply 'format fmt (nreverse l))))
18046 (defun org-time-string-to-time (s)
18047 (apply 'encode-time (org-parse-time-string s)))
18049 (defun org-time-string-to-absolute (s &optional daynr prefer)
18050 "Convert a time stamp to an absolute day number.
18051 If there is a specifyer for a cyclic time stamp, get the closest date to
18052 DAYNR."
18053 (cond
18054 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
18055 (if (org-diary-sexp-entry (match-string 1 s) "" date)
18056 daynr
18057 (+ daynr 1000)))
18058 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
18059 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
18060 (time-to-days (current-time))) (match-string 0 s)
18061 prefer))
18062 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
18064 (defun org-time-from-absolute (d)
18065 "Return the time corresponding to date D.
18066 D may be an absolute day number, or a calendar-type list (month day year)."
18067 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
18068 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
18070 (defun org-calendar-holiday ()
18071 "List of holidays, for Diary display in Org-mode."
18072 (require 'holidays)
18073 (let ((hl (funcall
18074 (if (fboundp 'calendar-check-holidays)
18075 'calendar-check-holidays 'check-calendar-holidays) date)))
18076 (if hl (mapconcat 'identity hl "; "))))
18078 (defun org-diary-sexp-entry (sexp entry date)
18079 "Process a SEXP diary ENTRY for DATE."
18080 (require 'diary-lib)
18081 (let ((result (if calendar-debug-sexp
18082 (let ((stack-trace-on-error t))
18083 (eval (car (read-from-string sexp))))
18084 (condition-case nil
18085 (eval (car (read-from-string sexp)))
18086 (error
18087 (beep)
18088 (message "Bad sexp at line %d in %s: %s"
18089 (org-current-line)
18090 (buffer-file-name) sexp)
18091 (sleep-for 2))))))
18092 (cond ((stringp result) result)
18093 ((and (consp result)
18094 (stringp (cdr result))) (cdr result))
18095 (result entry)
18096 (t nil))))
18098 (defun org-diary-to-ical-string (frombuf)
18099 "Get iCalendar entries from diary entries in buffer FROMBUF.
18100 This uses the icalendar.el library."
18101 (let* ((tmpdir (if (featurep 'xemacs)
18102 (temp-directory)
18103 temporary-file-directory))
18104 (tmpfile (make-temp-name
18105 (expand-file-name "orgics" tmpdir)))
18106 buf rtn b e)
18107 (save-excursion
18108 (set-buffer frombuf)
18109 (icalendar-export-region (point-min) (point-max) tmpfile)
18110 (setq buf (find-buffer-visiting tmpfile))
18111 (set-buffer buf)
18112 (goto-char (point-min))
18113 (if (re-search-forward "^BEGIN:VEVENT" nil t)
18114 (setq b (match-beginning 0)))
18115 (goto-char (point-max))
18116 (if (re-search-backward "^END:VEVENT" nil t)
18117 (setq e (match-end 0)))
18118 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
18119 (kill-buffer buf)
18120 (kill-buffer frombuf)
18121 (delete-file tmpfile)
18122 rtn))
18124 (defun org-closest-date (start current change prefer)
18125 "Find the date closest to CURRENT that is consistent with START and CHANGE.
18126 When PREFER is `past' return a date that is either CURRENT or past.
18127 When PREFER is `future', return a date that is either CURRENT or future."
18128 ;; Make the proper lists from the dates
18129 (catch 'exit
18130 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
18131 dn dw sday cday n1 n2
18132 d m y y1 y2 date1 date2 nmonths nm ny m2)
18134 (setq start (org-date-to-gregorian start)
18135 current (org-date-to-gregorian
18136 (if org-agenda-repeating-timestamp-show-all
18137 current
18138 (time-to-days (current-time))))
18139 sday (calendar-absolute-from-gregorian start)
18140 cday (calendar-absolute-from-gregorian current))
18142 (if (<= cday sday) (throw 'exit sday))
18144 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
18145 (setq dn (string-to-number (match-string 1 change))
18146 dw (cdr (assoc (match-string 2 change) a1)))
18147 (error "Invalid change specifyer: %s" change))
18148 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
18149 (cond
18150 ((eq dw 'day)
18151 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
18152 n2 (+ n1 dn)))
18153 ((eq dw 'year)
18154 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
18155 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
18156 (setq date1 (list m d y1)
18157 n1 (calendar-absolute-from-gregorian date1)
18158 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
18159 n2 (calendar-absolute-from-gregorian date2)))
18160 ((eq dw 'month)
18161 ;; approx number of month between the tow dates
18162 (setq nmonths (floor (/ (- cday sday) 30.436875)))
18163 ;; How often does dn fit in there?
18164 (setq d (nth 1 start) m (car start) y (nth 2 start)
18165 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
18166 m (+ m nm)
18167 ny (floor (/ m 12))
18168 y (+ y ny)
18169 m (- m (* ny 12)))
18170 (while (> m 12) (setq m (- m 12) y (1+ y)))
18171 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
18172 (setq m2 (+ m dn) y2 y)
18173 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18174 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
18175 (while (< n2 cday)
18176 (setq n1 n2 m m2 y y2)
18177 (setq m2 (+ m dn) y2 y)
18178 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18179 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
18181 (if org-agenda-repeating-timestamp-show-all
18182 (cond
18183 ((eq prefer 'past) n1)
18184 ((eq prefer 'future) (if (= cday n1) n1 n2))
18185 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
18186 (cond
18187 ((eq prefer 'past) n1)
18188 ((eq prefer 'future) (if (= cday n1) n1 n2))
18189 (t (if (= cday n1) n1 n2)))))))
18191 (defun org-date-to-gregorian (date)
18192 "Turn any specification of DATE into a gregorian date for the calendar."
18193 (cond ((integerp date) (calendar-gregorian-from-absolute date))
18194 ((and (listp date) (= (length date) 3)) date)
18195 ((stringp date)
18196 (setq date (org-parse-time-string date))
18197 (list (nth 4 date) (nth 3 date) (nth 5 date)))
18198 ((listp date)
18199 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
18201 (defun org-parse-time-string (s &optional nodefault)
18202 "Parse the standard Org-mode time string.
18203 This should be a lot faster than the normal `parse-time-string'.
18204 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18205 hour and minute fields will be nil if not given."
18206 (if (string-match org-ts-regexp0 s)
18207 (list 0
18208 (if (or (match-beginning 8) (not nodefault))
18209 (string-to-number (or (match-string 8 s) "0")))
18210 (if (or (match-beginning 7) (not nodefault))
18211 (string-to-number (or (match-string 7 s) "0")))
18212 (string-to-number (match-string 4 s))
18213 (string-to-number (match-string 3 s))
18214 (string-to-number (match-string 2 s))
18215 nil nil nil)
18216 (make-list 9 0)))
18218 (defun org-timestamp-up (&optional arg)
18219 "Increase the date item at the cursor by one.
18220 If the cursor is on the year, change the year. If it is on the month or
18221 the day, change that.
18222 With prefix ARG, change by that many units."
18223 (interactive "p")
18224 (org-timestamp-change (prefix-numeric-value arg)))
18226 (defun org-timestamp-down (&optional arg)
18227 "Decrease the date item at the cursor by one.
18228 If the cursor is on the year, change the year. If it is on the month or
18229 the day, change that.
18230 With prefix ARG, change by that many units."
18231 (interactive "p")
18232 (org-timestamp-change (- (prefix-numeric-value arg))))
18234 (defun org-timestamp-up-day (&optional arg)
18235 "Increase the date in the time stamp by one day.
18236 With prefix ARG, change that many days."
18237 (interactive "p")
18238 (if (and (not (org-at-timestamp-p t))
18239 (org-on-heading-p))
18240 (org-todo 'up)
18241 (org-timestamp-change (prefix-numeric-value arg) 'day)))
18243 (defun org-timestamp-down-day (&optional arg)
18244 "Decrease the date in the time stamp by one day.
18245 With prefix ARG, change that many days."
18246 (interactive "p")
18247 (if (and (not (org-at-timestamp-p t))
18248 (org-on-heading-p))
18249 (org-todo 'down)
18250 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
18252 (defsubst org-pos-in-match-range (pos n)
18253 (and (match-beginning n)
18254 (<= (match-beginning n) pos)
18255 (>= (match-end n) pos)))
18257 (defun org-at-timestamp-p (&optional inactive-ok)
18258 "Determine if the cursor is in or at a timestamp."
18259 (interactive)
18260 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18261 (pos (point))
18262 (ans (or (looking-at tsr)
18263 (save-excursion
18264 (skip-chars-backward "^[<\n\r\t")
18265 (if (> (point) (point-min)) (backward-char 1))
18266 (and (looking-at tsr)
18267 (> (- (match-end 0) pos) -1))))))
18268 (and ans
18269 (boundp 'org-ts-what)
18270 (setq org-ts-what
18271 (cond
18272 ((= pos (match-beginning 0)) 'bracket)
18273 ((= pos (1- (match-end 0))) 'bracket)
18274 ((org-pos-in-match-range pos 2) 'year)
18275 ((org-pos-in-match-range pos 3) 'month)
18276 ((org-pos-in-match-range pos 7) 'hour)
18277 ((org-pos-in-match-range pos 8) 'minute)
18278 ((or (org-pos-in-match-range pos 4)
18279 (org-pos-in-match-range pos 5)) 'day)
18280 ((and (> pos (or (match-end 8) (match-end 5)))
18281 (< pos (match-end 0)))
18282 (- pos (or (match-end 8) (match-end 5))))
18283 (t 'day))))
18284 ans))
18286 (defun org-toggle-timestamp-type ()
18288 (interactive)
18289 (when (org-at-timestamp-p t)
18290 (save-excursion
18291 (goto-char (match-beginning 0))
18292 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18293 (goto-char (1- (match-end 0)))
18294 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18295 (message "Timestamp is now %sactive"
18296 (if (equal (char-before) ?>) "in" ""))))
18298 (defun org-timestamp-change (n &optional what)
18299 "Change the date in the time stamp at point.
18300 The date will be changed by N times WHAT. WHAT can be `day', `month',
18301 `year', `minute', `second'. If WHAT is not given, the cursor position
18302 in the timestamp determines what will be changed."
18303 (let ((pos (point))
18304 with-hm inactive
18305 org-ts-what
18306 extra
18307 ts time time0)
18308 (if (not (org-at-timestamp-p t))
18309 (error "Not at a timestamp"))
18310 (if (and (not what) (eq org-ts-what 'bracket))
18311 (org-toggle-timestamp-type)
18312 (if (and (not what) (not (eq org-ts-what 'day))
18313 org-display-custom-times
18314 (get-text-property (point) 'display)
18315 (not (get-text-property (1- (point)) 'display)))
18316 (setq org-ts-what 'day))
18317 (setq org-ts-what (or what org-ts-what)
18318 inactive (= (char-after (match-beginning 0)) ?\[)
18319 ts (match-string 0))
18320 (replace-match "")
18321 (if (string-match
18322 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
18324 (setq extra (match-string 1 ts)))
18325 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18326 (setq with-hm t))
18327 (setq time0 (org-parse-time-string ts))
18328 (setq time
18329 (encode-time (or (car time0) 0)
18330 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18331 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18332 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18333 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18334 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18335 (nthcdr 6 time0)))
18336 (when (integerp org-ts-what)
18337 (setq extra (org-modify-ts-extra extra org-ts-what n)))
18338 (if (eq what 'calendar)
18339 (let ((cal-date (org-get-date-from-calendar)))
18340 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18341 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18342 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18343 (setcar time0 (or (car time0) 0))
18344 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18345 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18346 (setq time (apply 'encode-time time0))))
18347 (setq org-last-changed-timestamp
18348 (org-insert-time-stamp time with-hm inactive nil nil extra))
18349 (org-clock-update-time-maybe)
18350 (goto-char pos)
18351 ;; Try to recenter the calendar window, if any
18352 (if (and org-calendar-follow-timestamp-change
18353 (get-buffer-window "*Calendar*" t)
18354 (memq org-ts-what '(day month year)))
18355 (org-recenter-calendar (time-to-days time))))))
18357 ;; FIXME: does not yet work for lead times
18358 (defun org-modify-ts-extra (s pos n)
18359 "Change the different parts of the lead-time and repeat fields in timestamp."
18360 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18361 ng h m new)
18362 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18363 (cond
18364 ((or (org-pos-in-match-range pos 2)
18365 (org-pos-in-match-range pos 3))
18366 (setq m (string-to-number (match-string 3 s))
18367 h (string-to-number (match-string 2 s)))
18368 (if (org-pos-in-match-range pos 2)
18369 (setq h (+ h n))
18370 (setq m (+ m n)))
18371 (if (< m 0) (setq m (+ m 60) h (1- h)))
18372 (if (> m 59) (setq m (- m 60) h (1+ h)))
18373 (setq h (min 24 (max 0 h)))
18374 (setq ng 1 new (format "-%02d:%02d" h m)))
18375 ((org-pos-in-match-range pos 6)
18376 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18377 ((org-pos-in-match-range pos 5)
18378 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
18380 (when ng
18381 (setq s (concat
18382 (substring s 0 (match-beginning ng))
18384 (substring s (match-end ng))))))
18387 (defun org-recenter-calendar (date)
18388 "If the calendar is visible, recenter it to DATE."
18389 (let* ((win (selected-window))
18390 (cwin (get-buffer-window "*Calendar*" t))
18391 (calendar-move-hook nil))
18392 (when cwin
18393 (select-window cwin)
18394 (calendar-goto-date (if (listp date) date
18395 (calendar-gregorian-from-absolute date)))
18396 (select-window win))))
18398 (defun org-goto-calendar (&optional arg)
18399 "Go to the Emacs calendar at the current date.
18400 If there is a time stamp in the current line, go to that date.
18401 A prefix ARG can be used to force the current date."
18402 (interactive "P")
18403 (let ((tsr org-ts-regexp) diff
18404 (calendar-move-hook nil)
18405 (view-calendar-holidays-initially nil)
18406 (view-diary-entries-initially nil))
18407 (if (or (org-at-timestamp-p)
18408 (save-excursion
18409 (beginning-of-line 1)
18410 (looking-at (concat ".*" tsr))))
18411 (let ((d1 (time-to-days (current-time)))
18412 (d2 (time-to-days
18413 (org-time-string-to-time (match-string 1)))))
18414 (setq diff (- d2 d1))))
18415 (calendar)
18416 (calendar-goto-today)
18417 (if (and diff (not arg)) (calendar-forward-day diff))))
18419 (defun org-get-date-from-calendar ()
18420 "Return a list (month day year) of date at point in calendar."
18421 (with-current-buffer "*Calendar*"
18422 (save-match-data
18423 (calendar-cursor-to-date))))
18425 (defun org-date-from-calendar ()
18426 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18427 If there is already a time stamp at the cursor position, update it."
18428 (interactive)
18429 (if (org-at-timestamp-p t)
18430 (org-timestamp-change 0 'calendar)
18431 (let ((cal-date (org-get-date-from-calendar)))
18432 (org-insert-time-stamp
18433 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18435 ;; Make appt aware of appointments from the agenda
18436 ;;;###autoload
18437 (defun org-agenda-to-appt (&optional filter)
18438 "Activate appointments found in `org-agenda-files'.
18439 When prefixed, prompt for a regular expression and use it as a
18440 filter: only add entries if they match this regular expression.
18442 FILTER can be a string. In this case, use this string as a
18443 regular expression to filter results.
18445 FILTER can also be an alist, with the car of each cell being
18446 either 'headline or 'category. For example:
18448 '((headline \"IMPORTANT\")
18449 (category \"Work\"))
18451 will only add headlines containing IMPORTANT or headlines
18452 belonging to the category \"Work\"."
18453 (interactive "P")
18454 (require 'calendar)
18455 (if (equal filter '(4))
18456 (setq filter (read-from-minibuffer "Regexp filter: ")))
18457 (let* ((cnt 0) ; count added events
18458 (org-agenda-new-buffers nil)
18459 (today (org-date-to-gregorian
18460 (time-to-days (current-time))))
18461 (files (org-agenda-files)) entries file)
18462 ;; Get all entries which may contain an appt
18463 (while (setq file (pop files))
18464 (setq entries
18465 (append entries
18466 (org-agenda-get-day-entries
18467 file today
18468 :timestamp :scheduled :deadline))))
18469 (setq entries (delq nil entries))
18470 ;; Map thru entries and find if they pass thru the filter
18471 (mapc
18472 (lambda(x)
18473 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18474 (cat (get-text-property 1 'org-category x))
18475 (tod (get-text-property 1 'time-of-day x))
18476 (ok (or (null filter)
18477 (and (stringp filter) (string-match filter evt))
18478 (and (listp filter)
18479 (or (string-match
18480 (cadr (assoc 'category filter)) cat)
18481 (string-match
18482 (cadr (assoc 'headline filter)) evt))))))
18483 ;; FIXME: Shall we remove text-properties for the appt text?
18484 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18485 (when (and ok tod)
18486 (setq tod (number-to-string tod)
18487 tod (when (string-match
18488 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18489 (concat (match-string 1 tod) ":"
18490 (match-string 2 tod))))
18491 (appt-add tod evt)
18492 (setq cnt (1+ cnt))))) entries)
18493 (org-release-buffers org-agenda-new-buffers)
18494 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" ""))))
18496 ;;; The clock for measuring work time.
18498 (defvar org-mode-line-string "")
18499 (put 'org-mode-line-string 'risky-local-variable t)
18501 (defvar org-mode-line-timer nil)
18502 (defvar org-clock-heading "")
18503 (defvar org-clock-start-time "")
18505 (defun org-update-mode-line ()
18506 (let* ((delta (- (time-to-seconds (current-time))
18507 (time-to-seconds org-clock-start-time)))
18508 (h (floor delta 3600))
18509 (m (floor (- delta (* 3600 h)) 60)))
18510 (setq org-mode-line-string
18511 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18512 'help-echo "Org-mode clock is running"))
18513 (force-mode-line-update)))
18515 (defvar org-clock-marker (make-marker)
18516 "Marker recording the last clock-in.")
18517 (defvar org-clock-mode-line-entry nil
18518 "Information for the modeline about the running clock.")
18520 (defun org-clock-in ()
18521 "Start the clock on the current item.
18522 If necessary, clock-out of the currently active clock."
18523 (interactive)
18524 (org-clock-out t)
18525 (let (ts)
18526 (save-excursion
18527 (org-back-to-heading t)
18528 (when (and org-clock-in-switch-to-state
18529 (not (looking-at (concat outline-regexp "[ \t]*"
18530 org-clock-in-switch-to-state
18531 "\\>"))))
18532 (org-todo org-clock-in-switch-to-state))
18533 (if (and org-clock-heading-function
18534 (functionp org-clock-heading-function))
18535 (setq org-clock-heading (funcall org-clock-heading-function))
18536 (if (looking-at org-complex-heading-regexp)
18537 (setq org-clock-heading (match-string 4))
18538 (setq org-clock-heading "???")))
18539 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18540 (org-clock-find-position)
18542 (insert "\n") (backward-char 1)
18543 (indent-relative)
18544 (insert org-clock-string " ")
18545 (setq org-clock-start-time (current-time))
18546 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18547 (move-marker org-clock-marker (point) (buffer-base-buffer))
18548 (or global-mode-string (setq global-mode-string '("")))
18549 (or (memq 'org-mode-line-string global-mode-string)
18550 (setq global-mode-string
18551 (append global-mode-string '(org-mode-line-string))))
18552 (org-update-mode-line)
18553 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18554 (message "Clock started at %s" ts))))
18556 (defun org-clock-find-position ()
18557 "Find the location where the next clock line should be inserted."
18558 (org-back-to-heading t)
18559 (catch 'exit
18560 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
18561 (re (concat "^[ \t]*" org-clock-string))
18562 (cnt 0)
18563 first last)
18564 (goto-char beg)
18565 (when (eobp) (newline) (setq end (max (point) end)))
18566 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
18567 ;; we seem to have a CLOCK drawer, so go there.
18568 (beginning-of-line 2)
18569 (throw 'exit t))
18570 ;; Lets count the CLOCK lines
18571 (goto-char beg)
18572 (while (re-search-forward re end t)
18573 (setq first (or first (match-beginning 0))
18574 last (match-beginning 0)
18575 cnt (1+ cnt)))
18576 (when (and (integerp org-clock-into-drawer)
18577 (>= (1+ cnt) org-clock-into-drawer))
18578 ;; Wrap current entries into a new drawer
18579 (goto-char last)
18580 (beginning-of-line 2)
18581 (if (org-at-item-p) (org-end-of-item))
18582 (insert ":END:\n")
18583 (beginning-of-line 0)
18584 (org-indent-line-function)
18585 (goto-char first)
18586 (insert ":CLOCK:\n")
18587 (beginning-of-line 0)
18588 (org-indent-line-function)
18589 (org-flag-drawer t)
18590 (beginning-of-line 2)
18591 (throw 'exit nil))
18593 (goto-char beg)
18594 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18595 (not (equal (match-string 1) org-clock-string)))
18596 ;; Planning info, skip to after it
18597 (beginning-of-line 2)
18598 (or (bolp) (newline)))
18599 (when (eq t org-clock-into-drawer)
18600 (insert ":CLOCK:\n:END:\n")
18601 (beginning-of-line -1)
18602 (org-indent-line-function)
18603 (org-flag-drawer t)
18604 (beginning-of-line 2)
18605 (org-indent-line-function)))))
18607 (defun org-clock-out (&optional fail-quietly)
18608 "Stop the currently running clock.
18609 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
18610 (interactive)
18611 (catch 'exit
18612 (if (not (marker-buffer org-clock-marker))
18613 (if fail-quietly (throw 'exit t) (error "No active clock")))
18614 (let (ts te s h m)
18615 (save-excursion
18616 (set-buffer (marker-buffer org-clock-marker))
18617 (goto-char org-clock-marker)
18618 (beginning-of-line 1)
18619 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18620 (equal (match-string 1) org-clock-string))
18621 (setq ts (match-string 2))
18622 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
18623 (goto-char (match-end 0))
18624 (delete-region (point) (point-at-eol))
18625 (insert "--")
18626 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18627 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
18628 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
18629 h (floor (/ s 3600))
18630 s (- s (* 3600 h))
18631 m (floor (/ s 60))
18632 s (- s (* 60 s)))
18633 (insert " => " (format "%2d:%02d" h m))
18634 (move-marker org-clock-marker nil)
18635 (let* ((logging (save-match-data (org-entry-get nil "LOGGING" t)))
18636 (org-log-done (org-parse-local-options logging 'org-log-done))
18637 (org-log-repeat (org-parse-local-options logging 'org-log-repeat)))
18638 (org-add-log-maybe 'clock-out))
18639 (when org-mode-line-timer
18640 (cancel-timer org-mode-line-timer)
18641 (setq org-mode-line-timer nil))
18642 (setq global-mode-string
18643 (delq 'org-mode-line-string global-mode-string))
18644 (force-mode-line-update)
18645 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
18647 (defun org-clock-cancel ()
18648 "Cancel the running clock be removing the start timestamp."
18649 (interactive)
18650 (if (not (marker-buffer org-clock-marker))
18651 (error "No active clock"))
18652 (save-excursion
18653 (set-buffer (marker-buffer org-clock-marker))
18654 (goto-char org-clock-marker)
18655 (delete-region (1- (point-at-bol)) (point-at-eol)))
18656 (setq global-mode-string
18657 (delq 'org-mode-line-string global-mode-string))
18658 (force-mode-line-update)
18659 (message "Clock canceled"))
18661 (defun org-clock-goto (&optional delete-windows)
18662 "Go to the currently clocked-in entry."
18663 (interactive "P")
18664 (if (not (marker-buffer org-clock-marker))
18665 (error "No active clock"))
18666 (switch-to-buffer-other-window
18667 (marker-buffer org-clock-marker))
18668 (if delete-windows (delete-other-windows))
18669 (goto-char org-clock-marker)
18670 (org-show-entry)
18671 (org-back-to-heading)
18672 (recenter))
18674 (defvar org-clock-file-total-minutes nil
18675 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
18676 (make-variable-buffer-local 'org-clock-file-total-minutes)
18678 (defun org-clock-sum (&optional tstart tend)
18679 "Sum the times for each subtree.
18680 Puts the resulting times in minutes as a text property on each headline."
18681 (interactive)
18682 (let* ((bmp (buffer-modified-p))
18683 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
18684 org-clock-string
18685 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
18686 (lmax 30)
18687 (ltimes (make-vector lmax 0))
18688 (t1 0)
18689 (level 0)
18690 ts te dt
18691 time)
18692 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
18693 (save-excursion
18694 (goto-char (point-max))
18695 (while (re-search-backward re nil t)
18696 (cond
18697 ((match-end 2)
18698 ;; Two time stamps
18699 (setq ts (match-string 2)
18700 te (match-string 3)
18701 ts (time-to-seconds
18702 (apply 'encode-time (org-parse-time-string ts)))
18703 te (time-to-seconds
18704 (apply 'encode-time (org-parse-time-string te)))
18705 ts (if tstart (max ts tstart) ts)
18706 te (if tend (min te tend) te)
18707 dt (- te ts)
18708 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
18709 ((match-end 4)
18710 ;; A naket time
18711 (setq t1 (+ t1 (string-to-number (match-string 5))
18712 (* 60 (string-to-number (match-string 4))))))
18713 (t ;; A headline
18714 (setq level (- (match-end 1) (match-beginning 1)))
18715 (when (or (> t1 0) (> (aref ltimes level) 0))
18716 (loop for l from 0 to level do
18717 (aset ltimes l (+ (aref ltimes l) t1)))
18718 (setq t1 0 time (aref ltimes level))
18719 (loop for l from level to (1- lmax) do
18720 (aset ltimes l 0))
18721 (goto-char (match-beginning 0))
18722 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
18723 (setq org-clock-file-total-minutes (aref ltimes 0)))
18724 (set-buffer-modified-p bmp)))
18726 (defun org-clock-display (&optional total-only)
18727 "Show subtree times in the entire buffer.
18728 If TOTAL-ONLY is non-nil, only show the total time for the entire file
18729 in the echo area."
18730 (interactive)
18731 (org-remove-clock-overlays)
18732 (let (time h m p)
18733 (org-clock-sum)
18734 (unless total-only
18735 (save-excursion
18736 (goto-char (point-min))
18737 (while (or (and (equal (setq p (point)) (point-min))
18738 (get-text-property p :org-clock-minutes))
18739 (setq p (next-single-property-change
18740 (point) :org-clock-minutes)))
18741 (goto-char p)
18742 (when (setq time (get-text-property p :org-clock-minutes))
18743 (org-put-clock-overlay time (funcall outline-level))))
18744 (setq h (/ org-clock-file-total-minutes 60)
18745 m (- org-clock-file-total-minutes (* 60 h)))
18746 ;; Arrange to remove the overlays upon next change.
18747 (when org-remove-highlights-with-change
18748 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
18749 nil 'local))))
18750 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
18752 (defvar org-clock-overlays nil)
18753 (make-variable-buffer-local 'org-clock-overlays)
18755 (defun org-put-clock-overlay (time &optional level)
18756 "Put an overlays on the current line, displaying TIME.
18757 If LEVEL is given, prefix time with a corresponding number of stars.
18758 This creates a new overlay and stores it in `org-clock-overlays', so that it
18759 will be easy to remove."
18760 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
18761 (l (if level (org-get-legal-level level 0) 0))
18762 (off 0)
18763 ov tx)
18764 (move-to-column c)
18765 (unless (eolp) (skip-chars-backward "^ \t"))
18766 (skip-chars-backward " \t")
18767 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
18768 tx (concat (buffer-substring (1- (point)) (point))
18769 (make-string (+ off (max 0 (- c (current-column)))) ?.)
18770 (org-add-props (format "%s %2d:%02d%s"
18771 (make-string l ?*) h m
18772 (make-string (- 10 l) ?\ ))
18773 '(face secondary-selection))
18774 ""))
18775 (if (not (featurep 'xemacs))
18776 (org-overlay-put ov 'display tx)
18777 (org-overlay-put ov 'invisible t)
18778 (org-overlay-put ov 'end-glyph (make-glyph tx)))
18779 (push ov org-clock-overlays)))
18781 (defun org-remove-clock-overlays (&optional beg end noremove)
18782 "Remove the occur highlights from the buffer.
18783 BEG and END are ignored. If NOREMOVE is nil, remove this function
18784 from the `before-change-functions' in the current buffer."
18785 (interactive)
18786 (unless org-inhibit-highlight-removal
18787 (mapc 'org-delete-overlay org-clock-overlays)
18788 (setq org-clock-overlays nil)
18789 (unless noremove
18790 (remove-hook 'before-change-functions
18791 'org-remove-clock-overlays 'local))))
18793 (defun org-clock-out-if-current ()
18794 "Clock out if the current entry contains the running clock.
18795 This is used to stop the clock after a TODO entry is marked DONE,
18796 and is only done if the variable `org-clock-out-when-done' is not nil."
18797 (when (and org-clock-out-when-done
18798 (member state org-done-keywords)
18799 (equal (marker-buffer org-clock-marker) (current-buffer))
18800 (< (point) org-clock-marker)
18801 (> (save-excursion (outline-next-heading) (point))
18802 org-clock-marker))
18803 ;; Clock out, but don't accept a logging message for this.
18804 (let ((org-log-done (if (and (listp org-log-done)
18805 (member 'clock-out org-log-done))
18806 '(done)
18807 org-log-done)))
18808 (org-clock-out))))
18810 (add-hook 'org-after-todo-state-change-hook
18811 'org-clock-out-if-current)
18813 (defun org-check-running-clock ()
18814 "Check if the current buffer contains the running clock.
18815 If yes, offer to stop it and to save the buffer with the changes."
18816 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
18817 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
18818 (buffer-name))))
18819 (org-clock-out)
18820 (when (y-or-n-p "Save changed buffer?")
18821 (save-buffer))))
18823 (defun org-clock-report (&optional arg)
18824 "Create a table containing a report about clocked time.
18825 If the cursor is inside an existing clocktable block, then the table
18826 will be updated. If not, a new clocktable will be inserted.
18827 When called with a prefix argument, move to the first clock table in the
18828 buffer and update it."
18829 (interactive "P")
18830 (org-remove-clock-overlays)
18831 (when arg
18832 (org-find-dblock "clocktable")
18833 (org-show-entry))
18834 (if (org-in-clocktable-p)
18835 (goto-char (org-in-clocktable-p))
18836 (org-create-dblock (list :name "clocktable"
18837 :maxlevel 2 :scope 'file)))
18838 (org-update-dblock))
18840 (defun org-in-clocktable-p ()
18841 "Check if the cursor is in a clocktable."
18842 (let ((pos (point)) start)
18843 (save-excursion
18844 (end-of-line 1)
18845 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
18846 (setq start (match-beginning 0))
18847 (re-search-forward "^#\\+END:.*" nil t)
18848 (>= (match-end 0) pos)
18849 start))))
18851 (defun org-clock-update-time-maybe ()
18852 "If this is a CLOCK line, update it and return t.
18853 Otherwise, return nil."
18854 (interactive)
18855 (save-excursion
18856 (beginning-of-line 1)
18857 (skip-chars-forward " \t")
18858 (when (looking-at org-clock-string)
18859 (let ((re (concat "[ \t]*" org-clock-string
18860 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
18861 "\\([ \t]*=>.*\\)?"))
18862 ts te h m s)
18863 (if (not (looking-at re))
18865 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
18866 (end-of-line 1)
18867 (setq ts (match-string 1)
18868 te (match-string 2))
18869 (setq s (- (time-to-seconds
18870 (apply 'encode-time (org-parse-time-string te)))
18871 (time-to-seconds
18872 (apply 'encode-time (org-parse-time-string ts))))
18873 h (floor (/ s 3600))
18874 s (- s (* 3600 h))
18875 m (floor (/ s 60))
18876 s (- s (* 60 s)))
18877 (insert " => " (format "%2d:%02d" h m))
18878 t)))))
18880 (defun org-clock-special-range (key &optional time as-strings)
18881 "Return two times bordering a special time range.
18882 Key is a symbol specifying the range and can be one of `today', `yesterday',
18883 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
18884 A week starts Monday 0:00 and ends Sunday 24:00.
18885 The range is determined relative to TIME. TIME defaults to the current time.
18886 The return value is a cons cell with two internal times like the ones
18887 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
18888 the returned times will be formatted strings."
18889 (let* ((tm (decode-time (or time (current-time))))
18890 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
18891 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
18892 (dow (nth 6 tm))
18893 s1 m1 h1 d1 month1 y1 diff ts te fm)
18894 (cond
18895 ((eq key 'today)
18896 (setq h 0 m 0 h1 24 m1 0))
18897 ((eq key 'yesterday)
18898 (setq d (1- d) h 0 m 0 h1 24 m1 0))
18899 ((eq key 'thisweek)
18900 (setq diff (if (= dow 0) 6 (1- dow))
18901 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18902 ((eq key 'lastweek)
18903 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
18904 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18905 ((eq key 'thismonth)
18906 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
18907 ((eq key 'lastmonth)
18908 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
18909 ((eq key 'thisyear)
18910 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
18911 ((eq key 'lastyear)
18912 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
18913 (t (error "No such time block %s" key)))
18914 (setq ts (encode-time s m h d month y)
18915 te (encode-time (or s1 s) (or m1 m) (or h1 h)
18916 (or d1 d) (or month1 month) (or y1 y)))
18917 (setq fm (cdr org-time-stamp-formats))
18918 (if as-strings
18919 (cons (format-time-string fm ts) (format-time-string fm te))
18920 (cons ts te))))
18922 (defun org-dblock-write:clocktable (params)
18923 "Write the standard clocktable."
18924 (catch 'exit
18925 (let* ((hlchars '((1 . "*") (2 . "/")))
18926 (ins (make-marker))
18927 (total-time nil)
18928 (scope (plist-get params :scope))
18929 (tostring (plist-get params :tostring))
18930 (multifile (plist-get params :multifile))
18931 (header (plist-get params :header))
18932 (maxlevel (or (plist-get params :maxlevel) 3))
18933 (step (plist-get params :step))
18934 (emph (plist-get params :emphasize))
18935 (ts (plist-get params :tstart))
18936 (te (plist-get params :tend))
18937 (block (plist-get params :block))
18938 ipos time h m p level hlc hdl
18939 cc beg end pos tbl)
18940 (when step
18941 (org-clocktable-steps params)
18942 (throw 'exit nil))
18943 (when block
18944 (setq cc (org-clock-special-range block nil t)
18945 ts (car cc) te (cdr cc)))
18946 (if ts (setq ts (time-to-seconds
18947 (apply 'encode-time (org-parse-time-string ts)))))
18948 (if te (setq te (time-to-seconds
18949 (apply 'encode-time (org-parse-time-string te)))))
18950 (move-marker ins (point))
18951 (setq ipos (point))
18953 ;; Get the right scope
18954 (setq pos (point))
18955 (save-restriction
18956 (cond
18957 ((not scope))
18958 ((eq scope 'file) (widen))
18959 ((eq scope 'subtree) (org-narrow-to-subtree))
18960 ((eq scope 'tree)
18961 (while (org-up-heading-safe))
18962 (org-narrow-to-subtree))
18963 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
18964 (symbol-name scope)))
18965 (setq level (string-to-number (match-string 1 (symbol-name scope))))
18966 (catch 'exit
18967 (while (org-up-heading-safe)
18968 (looking-at outline-regexp)
18969 (if (<= (org-reduced-level (funcall outline-level)) level)
18970 (throw 'exit nil))))
18971 (org-narrow-to-subtree))
18972 ((or (listp scope) (eq scope 'agenda))
18973 (let* ((files (if (listp scope) scope (org-agenda-files)))
18974 (scope 'agenda)
18975 (p1 (copy-sequence params))
18976 file)
18977 (plist-put p1 :tostring t)
18978 (plist-put p1 :multifile t)
18979 (plist-put p1 :scope 'file)
18980 (org-prepare-agenda-buffers files)
18981 (while (setq file (pop files))
18982 (with-current-buffer (find-buffer-visiting file)
18983 (push (org-clocktable-add-file
18984 file (org-dblock-write:clocktable p1)) tbl)
18985 (setq total-time (+ (or total-time 0)
18986 org-clock-file-total-minutes)))))))
18987 (goto-char pos)
18989 (unless (eq scope 'agenda)
18990 (org-clock-sum ts te)
18991 (goto-char (point-min))
18992 (while (setq p (next-single-property-change (point) :org-clock-minutes))
18993 (goto-char p)
18994 (when (setq time (get-text-property p :org-clock-minutes))
18995 (save-excursion
18996 (beginning-of-line 1)
18997 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
18998 (setq level (org-reduced-level
18999 (- (match-end 1) (match-beginning 1))))
19000 (<= level maxlevel))
19001 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
19002 hdl (match-string 2)
19003 h (/ time 60)
19004 m (- time (* 60 h)))
19005 (if (and (not multifile) (= level 1)) (push "|-" tbl))
19006 (push (concat
19007 "| " (int-to-string level) "|" hlc hdl hlc " |"
19008 (make-string (1- level) ?|)
19009 hlc (format "%d:%02d" h m) hlc
19010 " |") tbl))))))
19011 (setq tbl (nreverse tbl))
19012 (if tostring
19013 (if tbl (mapconcat 'identity tbl "\n") nil)
19014 (goto-char ins)
19015 (insert-before-markers
19016 (or header
19017 (concat
19018 "Clock summary at ["
19019 (substring
19020 (format-time-string (cdr org-time-stamp-formats))
19021 1 -1)
19022 "]."
19023 (if block
19024 (format " Considered range is /%s/." block)
19026 "\n\n"))
19027 (if (eq scope 'agenda) "|File" "")
19028 "|L|Headline|Time|\n")
19029 (setq total-time (or total-time org-clock-file-total-minutes)
19030 h (/ total-time 60)
19031 m (- total-time (* 60 h)))
19032 (insert-before-markers
19033 "|-\n|"
19034 (if (eq scope 'agenda) "|" "")
19036 "*Total time*| "
19037 (format "*%d:%02d*" h m)
19038 "|\n|-\n")
19039 (setq tbl (delq nil tbl))
19040 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
19041 (equal (substring (car tbl) 0 2) "|-"))
19042 (pop tbl))
19043 (insert-before-markers (mapconcat
19044 'identity (delq nil tbl)
19045 (if (eq scope 'agenda) "\n|-\n" "\n")))
19046 (backward-delete-char 1)
19047 (goto-char ipos)
19048 (skip-chars-forward "^|")
19049 (org-table-align))))))
19051 (defun org-clocktable-steps (params)
19052 (let* ((p1 (copy-sequence params))
19053 (ts (plist-get p1 :tstart))
19054 (te (plist-get p1 :tend))
19055 (step0 (plist-get p1 :step))
19056 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
19057 (block (plist-get p1 :block))
19059 (when block
19060 (setq cc (org-clock-special-range block nil t)
19061 ts (car cc) te (cdr cc)))
19062 (if ts (setq ts (time-to-seconds
19063 (apply 'encode-time (org-parse-time-string ts)))))
19064 (if te (setq te (time-to-seconds
19065 (apply 'encode-time (org-parse-time-string te)))))
19066 (plist-put p1 :header "")
19067 (plist-put p1 :step nil)
19068 (plist-put p1 :block nil)
19069 (while (< ts te)
19070 (or (bolp) (insert "\n"))
19071 (plist-put p1 :tstart (format-time-string
19072 (car org-time-stamp-formats)
19073 (seconds-to-time ts)))
19074 (plist-put p1 :tend (format-time-string
19075 (car org-time-stamp-formats)
19076 (seconds-to-time (setq ts (+ ts step)))))
19077 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
19078 (plist-get p1 :tstart) "\n")
19079 (org-dblock-write:clocktable p1)
19080 (re-search-forward "#\\+END:")
19081 (end-of-line 0))))
19084 (defun org-clocktable-add-file (file table)
19085 (if table
19086 (let ((lines (org-split-string table "\n"))
19087 (ff (file-name-nondirectory file)))
19088 (mapconcat 'identity
19089 (mapcar (lambda (x)
19090 (if (string-match org-table-dataline-regexp x)
19091 (concat "|" ff x)
19093 lines)
19094 "\n"))))
19096 ;; FIXME: I don't think anybody uses this, ask David
19097 (defun org-collect-clock-time-entries ()
19098 "Return an internal list with clocking information.
19099 This list has one entry for each CLOCK interval.
19100 FIXME: describe the elements."
19101 (interactive)
19102 (let ((re (concat "^[ \t]*" org-clock-string
19103 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
19104 rtn beg end next cont level title total closedp leafp
19105 clockpos titlepos h m donep)
19106 (save-excursion
19107 (org-clock-sum)
19108 (goto-char (point-min))
19109 (while (re-search-forward re nil t)
19110 (setq clockpos (match-beginning 0)
19111 beg (match-string 1) end (match-string 2)
19112 cont (match-end 0))
19113 (setq beg (apply 'encode-time (org-parse-time-string beg))
19114 end (apply 'encode-time (org-parse-time-string end)))
19115 (org-back-to-heading t)
19116 (setq donep (org-entry-is-done-p))
19117 (setq titlepos (point)
19118 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
19119 h (/ total 60) m (- total (* 60 h))
19120 total (cons h m))
19121 (looking-at "\\(\\*+\\) +\\(.*\\)")
19122 (setq level (- (match-end 1) (match-beginning 1))
19123 title (org-match-string-no-properties 2))
19124 (save-excursion (outline-next-heading) (setq next (point)))
19125 (setq closedp (re-search-forward org-closed-time-regexp next t))
19126 (goto-char next)
19127 (setq leafp (and (looking-at "^\\*+ ")
19128 (<= (- (match-end 0) (point)) level)))
19129 (push (list beg end clockpos closedp donep
19130 total title titlepos level leafp)
19131 rtn)
19132 (goto-char cont)))
19133 (nreverse rtn)))
19135 ;;;; Agenda, and Diary Integration
19137 ;;; Define the Org-agenda-mode
19139 (defvar org-agenda-mode-map (make-sparse-keymap)
19140 "Keymap for `org-agenda-mode'.")
19142 (defvar org-agenda-menu) ; defined later in this file.
19143 (defvar org-agenda-follow-mode nil)
19144 (defvar org-agenda-show-log nil)
19145 (defvar org-agenda-redo-command nil)
19146 (defvar org-agenda-mode-hook nil)
19147 (defvar org-agenda-type nil)
19148 (defvar org-agenda-force-single-file nil)
19150 (defun org-agenda-mode ()
19151 "Mode for time-sorted view on action items in Org-mode files.
19153 The following commands are available:
19155 \\{org-agenda-mode-map}"
19156 (interactive)
19157 (kill-all-local-variables)
19158 (setq org-agenda-undo-list nil
19159 org-agenda-pending-undo-list nil)
19160 (setq major-mode 'org-agenda-mode)
19161 ;; Keep global-font-lock-mode from turning on font-lock-mode
19162 (org-set-local 'font-lock-global-modes (list 'not major-mode))
19163 (setq mode-name "Org-Agenda")
19164 (use-local-map org-agenda-mode-map)
19165 (easy-menu-add org-agenda-menu)
19166 (if org-startup-truncated (setq truncate-lines t))
19167 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
19168 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
19169 ;; Make sure properties are removed when copying text
19170 (when (boundp 'buffer-substring-filters)
19171 (org-set-local 'buffer-substring-filters
19172 (cons (lambda (x)
19173 (set-text-properties 0 (length x) nil x) x)
19174 buffer-substring-filters)))
19175 (unless org-agenda-keep-modes
19176 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
19177 org-agenda-show-log nil))
19178 (easy-menu-change
19179 '("Agenda") "Agenda Files"
19180 (append
19181 (list
19182 (vector
19183 (if (get 'org-agenda-files 'org-restrict)
19184 "Restricted to single file"
19185 "Edit File List")
19186 '(org-edit-agenda-file-list)
19187 (not (get 'org-agenda-files 'org-restrict)))
19188 "--")
19189 (mapcar 'org-file-menu-entry (org-agenda-files))))
19190 (org-agenda-set-mode-name)
19191 (apply
19192 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
19193 (list 'org-agenda-mode-hook)))
19195 (substitute-key-definition 'undo 'org-agenda-undo
19196 org-agenda-mode-map global-map)
19197 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
19198 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
19199 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
19200 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
19201 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
19202 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
19203 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
19204 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
19205 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
19206 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
19207 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
19208 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
19209 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
19210 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
19211 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
19212 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
19213 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
19214 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
19215 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
19216 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
19217 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
19218 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
19219 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
19220 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
19221 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
19222 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
19223 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
19224 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
19225 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
19227 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
19228 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
19229 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
19230 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
19231 (while l (org-defkey org-agenda-mode-map
19232 (int-to-string (pop l)) 'digit-argument)))
19234 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
19235 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
19236 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
19237 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
19238 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
19239 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
19240 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
19241 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
19242 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
19243 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
19244 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
19245 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
19246 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
19247 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
19248 (org-defkey org-agenda-mode-map "n" 'next-line)
19249 (org-defkey org-agenda-mode-map "p" 'previous-line)
19250 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
19251 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
19252 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
19253 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
19254 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
19255 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
19256 (eval-after-load "calendar"
19257 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
19258 'org-calendar-goto-agenda))
19259 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
19260 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
19261 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
19262 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
19263 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
19264 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
19265 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
19266 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
19267 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
19268 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
19269 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
19270 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19271 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
19272 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
19273 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
19274 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
19275 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
19276 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
19277 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
19278 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
19279 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
19280 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
19282 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
19283 "Local keymap for agenda entries from Org-mode.")
19285 (org-defkey org-agenda-keymap
19286 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
19287 (org-defkey org-agenda-keymap
19288 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
19289 (when org-agenda-mouse-1-follows-link
19290 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
19291 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
19292 '("Agenda"
19293 ("Agenda Files")
19294 "--"
19295 ["Show" org-agenda-show t]
19296 ["Go To (other window)" org-agenda-goto t]
19297 ["Go To (this window)" org-agenda-switch-to t]
19298 ["Follow Mode" org-agenda-follow-mode
19299 :style toggle :selected org-agenda-follow-mode :active t]
19300 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
19301 "--"
19302 ["Cycle TODO" org-agenda-todo t]
19303 ["Archive subtree" org-agenda-archive t]
19304 ["Delete subtree" org-agenda-kill t]
19305 "--"
19306 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
19307 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
19308 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
19309 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
19310 "--"
19311 ("Tags and Properties"
19312 ["Show all Tags" org-agenda-show-tags t]
19313 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
19314 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
19315 "--"
19316 ["Column View" org-columns t])
19317 ("Date/Schedule"
19318 ["Schedule" org-agenda-schedule t]
19319 ["Set Deadline" org-agenda-deadline t]
19320 "--"
19321 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19322 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19323 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19324 ("Clock"
19325 ["Clock in" org-agenda-clock-in t]
19326 ["Clock out" org-agenda-clock-out t]
19327 ["Clock cancel" org-agenda-clock-cancel t]
19328 ["Goto running clock" org-clock-goto t])
19329 ("Priority"
19330 ["Set Priority" org-agenda-priority t]
19331 ["Increase Priority" org-agenda-priority-up t]
19332 ["Decrease Priority" org-agenda-priority-down t]
19333 ["Show Priority" org-agenda-show-priority t])
19334 ("Calendar/Diary"
19335 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19336 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19337 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19338 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19339 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19340 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19341 "--"
19342 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19343 "--"
19344 ("View"
19345 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19346 :style radio :selected (equal org-agenda-ndays 1)]
19347 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19348 :style radio :selected (equal org-agenda-ndays 7)]
19349 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19350 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19351 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19352 :style radio :selected (member org-agenda-ndays '(365 366))]
19353 "--"
19354 ["Show Logbook entries" org-agenda-log-mode
19355 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19356 ["Include Diary" org-agenda-toggle-diary
19357 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19358 ["Use Time Grid" org-agenda-toggle-time-grid
19359 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19360 ["Write view to file" org-write-agenda t]
19361 ["Rebuild buffer" org-agenda-redo t]
19362 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19363 "--"
19364 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19365 "--"
19366 ["Quit" org-agenda-quit t]
19367 ["Exit and Release Buffers" org-agenda-exit t]
19370 ;;; Agenda undo
19372 (defvar org-agenda-allow-remote-undo t
19373 "Non-nil means, allow remote undo from the agenda buffer.")
19374 (defvar org-agenda-undo-list nil
19375 "List of undoable operations in the agenda since last refresh.")
19376 (defvar org-agenda-undo-has-started-in nil
19377 "Buffers that have already seen `undo-start' in the current undo sequence.")
19378 (defvar org-agenda-pending-undo-list nil
19379 "In a series of undo commands, this is the list of remaning undo items.")
19381 (defmacro org-if-unprotected (&rest body)
19382 "Execute BODY if there is no `org-protected' text property at point."
19383 (declare (debug t))
19384 `(unless (get-text-property (point) 'org-protected)
19385 ,@body))
19387 (defmacro org-with-remote-undo (_buffer &rest _body)
19388 "Execute BODY while recording undo information in two buffers."
19389 (declare (indent 1) (debug t))
19390 `(let ((_cline (org-current-line))
19391 (_cmd this-command)
19392 (_buf1 (current-buffer))
19393 (_buf2 ,_buffer)
19394 (_undo1 buffer-undo-list)
19395 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19396 _c1 _c2)
19397 ,@_body
19398 (when org-agenda-allow-remote-undo
19399 (setq _c1 (org-verify-change-for-undo
19400 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19401 _c2 (org-verify-change-for-undo
19402 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19403 (when (or _c1 _c2)
19404 ;; make sure there are undo boundaries
19405 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19406 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19407 ;; remember which buffer to undo
19408 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19409 org-agenda-undo-list)))))
19411 (defun org-agenda-undo ()
19412 "Undo a remote editing step in the agenda.
19413 This undoes changes both in the agenda buffer and in the remote buffer
19414 that have been changed along."
19415 (interactive)
19416 (or org-agenda-allow-remote-undo
19417 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19418 (if (not (eq this-command last-command))
19419 (setq org-agenda-undo-has-started-in nil
19420 org-agenda-pending-undo-list org-agenda-undo-list))
19421 (if (not org-agenda-pending-undo-list)
19422 (error "No further undo information"))
19423 (let* ((entry (pop org-agenda-pending-undo-list))
19424 buf line cmd rembuf)
19425 (setq cmd (pop entry) line (pop entry))
19426 (setq rembuf (nth 2 entry))
19427 (org-with-remote-undo rembuf
19428 (while (bufferp (setq buf (pop entry)))
19429 (if (pop entry)
19430 (with-current-buffer buf
19431 (let ((last-undo-buffer buf)
19432 (inhibit-read-only t))
19433 (unless (memq buf org-agenda-undo-has-started-in)
19434 (push buf org-agenda-undo-has-started-in)
19435 (make-local-variable 'pending-undo-list)
19436 (undo-start))
19437 (while (and pending-undo-list
19438 (listp pending-undo-list)
19439 (not (car pending-undo-list)))
19440 (pop pending-undo-list))
19441 (undo-more 1))))))
19442 (goto-line line)
19443 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19445 (defun org-verify-change-for-undo (l1 l2)
19446 "Verify that a real change occurred between the undo lists L1 and L2."
19447 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19448 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19449 (not (eq l1 l2)))
19451 ;;; Agenda dispatch
19453 (defvar org-agenda-restrict nil)
19454 (defvar org-agenda-restrict-begin (make-marker))
19455 (defvar org-agenda-restrict-end (make-marker))
19456 (defvar org-agenda-last-dispatch-buffer nil)
19457 (defvar org-agenda-overriding-restriction nil)
19459 ;;;###autoload
19460 (defun org-agenda (arg &optional keys restriction)
19461 "Dispatch agenda commands to collect entries to the agenda buffer.
19462 Prompts for a command to execute. Any prefix arg will be passed
19463 on to the selected command. The default selections are:
19465 a Call `org-agenda-list' to display the agenda for current day or week.
19466 t Call `org-todo-list' to display the global todo list.
19467 T Call `org-todo-list' to display the global todo list, select only
19468 entries with a specific TODO keyword (the user gets a prompt).
19469 m Call `org-tags-view' to display headlines with tags matching
19470 a condition (the user is prompted for the condition).
19471 M Like `m', but select only TODO entries, no ordinary headlines.
19472 L Create a timeline for the current buffer.
19473 e Export views to associated files.
19475 More commands can be added by configuring the variable
19476 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19477 searches can be pre-defined in this way.
19479 If the current buffer is in Org-mode and visiting a file, you can also
19480 first press `<' once to indicate that the agenda should be temporarily
19481 \(until the next use of \\[org-agenda]) restricted to the current file.
19482 Pressing `<' twice means to restrict to the current subtree or region
19483 \(if active)."
19484 (interactive "P")
19485 (catch 'exit
19486 (let* ((prefix-descriptions nil)
19487 (org-agenda-custom-commands-orig org-agenda-custom-commands)
19488 (org-agenda-custom-commands
19489 ;; normalize different versions
19490 (delq nil
19491 (mapcar
19492 (lambda (x)
19493 (cond ((stringp (cdr x))
19494 (push x prefix-descriptions)
19495 nil)
19496 ((stringp (nth 1 x)) x)
19497 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19498 (t (cons (car x) (cons "" (cdr x))))))
19499 org-agenda-custom-commands)))
19500 (buf (current-buffer))
19501 (bfn (buffer-file-name (buffer-base-buffer)))
19502 entry key type match lprops ans)
19503 ;; Turn off restriction unless there is an overriding one
19504 (unless org-agenda-overriding-restriction
19505 (put 'org-agenda-files 'org-restrict nil)
19506 (setq org-agenda-restrict nil)
19507 (move-marker org-agenda-restrict-begin nil)
19508 (move-marker org-agenda-restrict-end nil))
19509 ;; Delete old local properties
19510 (put 'org-agenda-redo-command 'org-lprops nil)
19511 ;; Remember where this call originated
19512 (setq org-agenda-last-dispatch-buffer (current-buffer))
19513 (unless keys
19514 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19515 keys (car ans)
19516 restriction (cdr ans)))
19517 ;; Estabish the restriction, if any
19518 (when (and (not org-agenda-overriding-restriction) restriction)
19519 (put 'org-agenda-files 'org-restrict (list bfn))
19520 (cond
19521 ((eq restriction 'region)
19522 (setq org-agenda-restrict t)
19523 (move-marker org-agenda-restrict-begin (region-beginning))
19524 (move-marker org-agenda-restrict-end (region-end)))
19525 ((eq restriction 'subtree)
19526 (save-excursion
19527 (setq org-agenda-restrict t)
19528 (org-back-to-heading t)
19529 (move-marker org-agenda-restrict-begin (point))
19530 (move-marker org-agenda-restrict-end
19531 (progn (org-end-of-subtree t)))))))
19533 (require 'calendar) ; FIXME: can we avoid this for some commands?
19534 ;; For example the todo list should not need it (but does...)
19535 (cond
19536 ((setq entry (assoc keys org-agenda-custom-commands))
19537 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19538 (progn
19539 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19540 (put 'org-agenda-redo-command 'org-lprops lprops)
19541 (cond
19542 ((eq type 'agenda)
19543 (org-let lprops '(org-agenda-list current-prefix-arg)))
19544 ((eq type 'alltodo)
19545 (org-let lprops '(org-todo-list current-prefix-arg)))
19546 ((eq type 'stuck)
19547 (org-let lprops '(org-agenda-list-stuck-projects
19548 current-prefix-arg)))
19549 ((eq type 'tags)
19550 (org-let lprops '(org-tags-view current-prefix-arg match)))
19551 ((eq type 'tags-todo)
19552 (org-let lprops '(org-tags-view '(4) match)))
19553 ((eq type 'todo)
19554 (org-let lprops '(org-todo-list match)))
19555 ((eq type 'tags-tree)
19556 (org-check-for-org-mode)
19557 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
19558 ((eq type 'todo-tree)
19559 (org-check-for-org-mode)
19560 (org-let lprops
19561 '(org-occur (concat "^" outline-regexp "[ \t]*"
19562 (regexp-quote match) "\\>"))))
19563 ((eq type 'occur-tree)
19564 (org-check-for-org-mode)
19565 (org-let lprops '(org-occur match)))
19566 ((functionp type)
19567 (org-let lprops '(funcall type match)))
19568 ((fboundp type)
19569 (org-let lprops '(funcall type match)))
19570 (t (error "Invalid custom agenda command type %s" type))))
19571 (org-run-agenda-series (nth 1 entry) (cddr entry))))
19572 ((equal keys "C")
19573 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
19574 (customize-variable 'org-agenda-custom-commands))
19575 ((equal keys "a") (call-interactively 'org-agenda-list))
19576 ((equal keys "t") (call-interactively 'org-todo-list))
19577 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
19578 ((equal keys "m") (call-interactively 'org-tags-view))
19579 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
19580 ((equal keys "e") (call-interactively 'org-store-agenda-views))
19581 ((equal keys "L")
19582 (unless (org-mode-p)
19583 (error "This is not an Org-mode file"))
19584 (unless restriction
19585 (put 'org-agenda-files 'org-restrict (list bfn))
19586 (org-call-with-arg 'org-timeline arg)))
19587 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
19588 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
19589 ((equal keys "!") (customize-variable 'org-stuck-projects))
19590 (t (error "Invalid agenda key"))))))
19592 (defun org-agenda-normalize-custom-commands (cmds)
19593 (delq nil
19594 (mapcar
19595 (lambda (x)
19596 (cond ((stringp (cdr x)) nil)
19597 ((stringp (nth 1 x)) x)
19598 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19599 (t (cons (car x) (cons "" (cdr x))))))
19600 cmds)))
19602 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
19603 "The user interface for selecting an agenda command."
19604 (catch 'exit
19605 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
19606 (restrict-ok (and bfn (org-mode-p)))
19607 (region-p (org-region-active-p))
19608 (custom org-agenda-custom-commands)
19609 (selstring "")
19610 restriction second-time
19611 c entry key type match prefixes rmheader header-end custom1 desc)
19612 (save-window-excursion
19613 (delete-other-windows)
19614 (org-switch-to-buffer-other-window " *Agenda Commands*")
19615 (erase-buffer)
19616 (insert (eval-when-compile
19617 (let ((header
19619 Press key for an agenda command: < Buffer,subtree/region restriction
19620 -------------------------------- > Remove restriction
19621 a Agenda for current week or day e Export agenda views
19622 t List of all TODO entries T Entries with special TODO kwd
19623 m Match a TAGS query M Like m, but only TODO entries
19624 L Timeline for current buffer # List stuck projects (!=configure)
19625 / Multi-occur C Configure custom agenda commands
19627 (start 0))
19628 (while (string-match
19629 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
19630 header start)
19631 (setq start (match-end 0))
19632 (add-text-properties (match-beginning 2) (match-end 2)
19633 '(face bold) header))
19634 header)))
19635 (setq header-end (move-marker (make-marker) (point)))
19636 (while t
19637 (setq custom1 custom)
19638 (when (eq rmheader t)
19639 (goto-line 1)
19640 (re-search-forward ":" nil t)
19641 (delete-region (match-end 0) (point-at-eol))
19642 (forward-char 1)
19643 (looking-at "-+")
19644 (delete-region (match-end 0) (point-at-eol))
19645 (move-marker header-end (match-end 0)))
19646 (goto-char header-end)
19647 (delete-region (point) (point-max))
19648 (while (setq entry (pop custom1))
19649 (setq key (car entry) desc (nth 1 entry)
19650 type (nth 2 entry) match (nth 3 entry))
19651 (if (> (length key) 1)
19652 (add-to-list 'prefixes (string-to-char key))
19653 (insert
19654 (format
19655 "\n%-4s%-14s: %s"
19656 (org-add-props (copy-sequence key)
19657 '(face bold))
19658 (cond
19659 ((string-match "\\S-" desc) desc)
19660 ((eq type 'agenda) "Agenda for current week or day")
19661 ((eq type 'alltodo) "List of all TODO entries")
19662 ((eq type 'stuck) "List of stuck projects")
19663 ((eq type 'todo) "TODO keyword")
19664 ((eq type 'tags) "Tags query")
19665 ((eq type 'tags-todo) "Tags (TODO)")
19666 ((eq type 'tags-tree) "Tags tree")
19667 ((eq type 'todo-tree) "TODO kwd tree")
19668 ((eq type 'occur-tree) "Occur tree")
19669 ((functionp type) (if (symbolp type)
19670 (symbol-name type)
19671 "Lambda expression"))
19672 (t "???"))
19673 (cond
19674 ((stringp match)
19675 (org-add-props match nil 'face 'org-warning))
19676 (match
19677 (format "set of %d commands" (length match)))
19678 (t ""))))))
19679 (when prefixes
19680 (mapc (lambda (x)
19681 (insert
19682 (format "\n%s %s"
19683 (org-add-props (char-to-string x)
19684 nil 'face 'bold)
19685 (or (cdr (assoc (concat selstring (char-to-string x))
19686 prefix-descriptions))
19687 "Prefix key"))))
19688 prefixes))
19689 (goto-char (point-min))
19690 (when (fboundp 'fit-window-to-buffer)
19691 (if second-time
19692 (if (not (pos-visible-in-window-p (point-max)))
19693 (fit-window-to-buffer))
19694 (setq second-time t)
19695 (fit-window-to-buffer)))
19696 (message "Press key for agenda command%s:"
19697 (if (or restrict-ok org-agenda-overriding-restriction)
19698 (if org-agenda-overriding-restriction
19699 " (restriction lock active)"
19700 (if restriction
19701 (format " (restricted to %s)" restriction)
19702 " (unrestricted)"))
19703 ""))
19704 (setq c (read-char-exclusive))
19705 (message "")
19706 (cond
19707 ((assoc (char-to-string c) custom)
19708 (setq selstring (concat selstring (char-to-string c)))
19709 (throw 'exit (cons selstring restriction)))
19710 ((memq c prefixes)
19711 (setq selstring (concat selstring (char-to-string c))
19712 prefixes nil
19713 rmheader (or rmheader t)
19714 custom (delq nil (mapcar
19715 (lambda (x)
19716 (if (or (= (length (car x)) 1)
19717 (/= (string-to-char (car x)) c))
19719 (cons (substring (car x) 1) (cdr x))))
19720 custom))))
19721 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
19722 (message "Restriction is only possible in Org-mode buffers")
19723 (ding) (sit-for 1))
19724 ((eq c ?1)
19725 (org-agenda-remove-restriction-lock 'noupdate)
19726 (setq restriction 'buffer))
19727 ((eq c ?0)
19728 (org-agenda-remove-restriction-lock 'noupdate)
19729 (setq restriction (if region-p 'region 'subtree)))
19730 ((eq c ?<)
19731 (org-agenda-remove-restriction-lock 'noupdate)
19732 (setq restriction
19733 (cond
19734 ((eq restriction 'buffer)
19735 (if region-p 'region 'subtree))
19736 ((memq restriction '(subtree region))
19737 nil)
19738 (t 'buffer))))
19739 ((eq c ?>)
19740 (org-agenda-remove-restriction-lock 'noupdate)
19741 (setq restriction nil))
19742 ((and (equal selstring "") (memq c '(?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
19743 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
19744 ((and (> (length selstring) 0) (eq c ?\d))
19745 (delete-window)
19746 (org-agenda-get-restriction-and-command prefix-descriptions))
19748 ((equal c ?q) (error "Abort"))
19749 (t (error "Invalid key %c" c))))))))
19751 (defun org-run-agenda-series (name series)
19752 (org-prepare-agenda name)
19753 (let* ((org-agenda-multi t)
19754 (redo (list 'org-run-agenda-series name (list 'quote series)))
19755 (cmds (car series))
19756 (gprops (nth 1 series))
19757 match ;; The byte compiler incorrectly complains about this. Keep it!
19758 cmd type lprops)
19759 (while (setq cmd (pop cmds))
19760 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
19761 (cond
19762 ((eq type 'agenda)
19763 (org-let2 gprops lprops
19764 '(call-interactively 'org-agenda-list)))
19765 ((eq type 'alltodo)
19766 (org-let2 gprops lprops
19767 '(call-interactively 'org-todo-list)))
19768 ((eq type 'stuck)
19769 (org-let2 gprops lprops
19770 '(call-interactively 'org-agenda-list-stuck-projects)))
19771 ((eq type 'tags)
19772 (org-let2 gprops lprops
19773 '(org-tags-view current-prefix-arg match)))
19774 ((eq type 'tags-todo)
19775 (org-let2 gprops lprops
19776 '(org-tags-view '(4) match)))
19777 ((eq type 'todo)
19778 (org-let2 gprops lprops
19779 '(org-todo-list match)))
19780 ((fboundp type)
19781 (org-let2 gprops lprops
19782 '(funcall type match)))
19783 (t (error "Invalid type in command series"))))
19784 (widen)
19785 (setq org-agenda-redo-command redo)
19786 (goto-char (point-min)))
19787 (org-finalize-agenda))
19789 ;;;###autoload
19790 (defmacro org-batch-agenda (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."
19797 (let (pars)
19798 (while parameters
19799 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19800 (if (> (length cmd-key) 2)
19801 (eval (list 'let (nreverse pars)
19802 (list 'org-tags-view nil cmd-key)))
19803 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19804 (set-buffer org-agenda-buffer-name)
19805 (princ (org-encode-for-stdout (buffer-string)))))
19807 (defun org-encode-for-stdout (string)
19808 (if (fboundp 'encode-coding-string)
19809 (encode-coding-string string buffer-file-coding-system)
19810 string))
19812 (defvar org-agenda-info nil)
19814 ;;;###autoload
19815 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
19816 "Run an agenda command in batch mode and send the result to STDOUT.
19817 If CMD-KEY is a string of length 1, it is used as a key in
19818 `org-agenda-custom-commands' and triggers this command. If it is a
19819 longer string it is used as a tags/todo match string.
19820 Paramters are alternating variable names and values that will be bound
19821 before running the agenda command.
19823 The output gives a line for each selected agenda item. Each
19824 item is a list of comma-separated values, like this:
19826 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
19828 category The category of the item
19829 head The headline, without TODO kwd, TAGS and PRIORITY
19830 type The type of the agenda entry, can be
19831 todo selected in TODO match
19832 tagsmatch selected in tags match
19833 diary imported from diary
19834 deadline a deadline on given date
19835 scheduled scheduled on given date
19836 timestamp entry has timestamp on given date
19837 closed entry was closed on given date
19838 upcoming-deadline warning about deadline
19839 past-scheduled forwarded scheduled item
19840 block entry has date block including g. date
19841 todo The todo keyword, if any
19842 tags All tags including inherited ones, separated by colons
19843 date The relevant date, like 2007-2-14
19844 time The time, like 15:00-16:50
19845 extra Sting with extra planning info
19846 priority-l The priority letter if any was given
19847 priority-n The computed numerical priority
19848 agenda-day The day in the agenda where this is listed"
19850 (let (pars)
19851 (while parameters
19852 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19853 (push (list 'org-agenda-remove-tags t) pars)
19854 (if (> (length cmd-key) 2)
19855 (eval (list 'let (nreverse pars)
19856 (list 'org-tags-view nil cmd-key)))
19857 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19858 (set-buffer org-agenda-buffer-name)
19859 (let* ((lines (org-split-string (buffer-string) "\n"))
19860 line)
19861 (while (setq line (pop lines))
19862 (catch 'next
19863 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
19864 (setq org-agenda-info
19865 (org-fix-agenda-info (text-properties-at 0 line)))
19866 (princ
19867 (org-encode-for-stdout
19868 (mapconcat 'org-agenda-export-csv-mapper
19869 '(org-category txt type todo tags date time-of-day extra
19870 priority-letter priority agenda-day)
19871 ",")))
19872 (princ "\n"))))))
19874 (defun org-fix-agenda-info (props)
19875 "Make sure all properties on an agenda item have a canonical form,
19876 so the export commands can easily use it."
19877 (let (tmp re)
19878 (when (setq tmp (plist-get props 'tags))
19879 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
19880 (when (setq tmp (plist-get props 'date))
19881 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19882 (let ((calendar-date-display-form '(year "-" month "-" day)))
19883 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
19885 (setq tmp (calendar-date-string tmp)))
19886 (setq props (plist-put props 'date tmp)))
19887 (when (setq tmp (plist-get props 'day))
19888 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19889 (let ((calendar-date-display-form '(year "-" month "-" day)))
19890 (setq tmp (calendar-date-string tmp)))
19891 (setq props (plist-put props 'day tmp))
19892 (setq props (plist-put props 'agenda-day tmp)))
19893 (when (setq tmp (plist-get props 'txt))
19894 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
19895 (plist-put props 'priority-letter (match-string 1 tmp))
19896 (setq tmp (replace-match "" t t tmp)))
19897 (when (and (setq re (plist-get props 'org-todo-regexp))
19898 (setq re (concat "\\`\\.*" re " ?"))
19899 (string-match re tmp))
19900 (plist-put props 'todo (match-string 1 tmp))
19901 (setq tmp (replace-match "" t t tmp)))
19902 (plist-put props 'txt tmp)))
19903 props)
19905 (defun org-agenda-export-csv-mapper (prop)
19906 (let ((res (plist-get org-agenda-info prop)))
19907 (setq res
19908 (cond
19909 ((not res) "")
19910 ((stringp res) res)
19911 (t (prin1-to-string res))))
19912 (while (string-match "," res)
19913 (setq res (replace-match ";" t t res)))
19914 (org-trim res)))
19917 ;;;###autoload
19918 (defun org-store-agenda-views (&rest parameters)
19919 (interactive)
19920 (eval (list 'org-batch-store-agenda-views)))
19922 ;; FIXME, why is this a macro?????
19923 ;;;###autoload
19924 (defmacro org-batch-store-agenda-views (&rest parameters)
19925 "Run all custom agenda commands that have a file argument."
19926 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
19927 (pop-up-frames nil)
19928 (dir default-directory)
19929 pars cmd thiscmdkey files opts)
19930 (while parameters
19931 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19932 (setq pars (reverse pars))
19933 (save-window-excursion
19934 (while cmds
19935 (setq cmd (pop cmds)
19936 thiscmdkey (car cmd)
19937 opts (nth 4 cmd)
19938 files (nth 5 cmd))
19939 (if (stringp files) (setq files (list files)))
19940 (when files
19941 (eval (list 'let (append org-agenda-exporter-settings opts pars)
19942 (list 'org-agenda nil thiscmdkey)))
19943 (set-buffer org-agenda-buffer-name)
19944 (while files
19945 (eval (list 'let (append org-agenda-exporter-settings opts pars)
19946 (list 'org-write-agenda
19947 (expand-file-name (pop files) dir) t))))
19948 (and (get-buffer org-agenda-buffer-name)
19949 (kill-buffer org-agenda-buffer-name)))))))
19951 (defun org-write-agenda (file &optional nosettings)
19952 "Write the current buffer (an agenda view) as a file.
19953 Depending on the extension of the file name, plain text (.txt),
19954 HTML (.html or .htm) or Postscript (.ps) is produced.
19955 If NOSETTINGS is given, do not scope the settings of
19956 `org-agenda-exporter-settings' into the export commands. This is used when
19957 the settings have already been scoped and we do not wish to overrule other,
19958 higher priority settings."
19959 (interactive "FWrite agenda to file: ")
19960 (if (not (file-writable-p file))
19961 (error "Cannot write agenda to file %s" file))
19962 (cond
19963 ((string-match "\\.html?\\'" file) (require 'htmlize))
19964 ((string-match "\\.ps\\'" file) (require 'ps-print)))
19965 (org-let (if nosettings nil org-agenda-exporter-settings)
19966 '(save-excursion
19967 (save-window-excursion
19968 (cond
19969 ((string-match "\\.html?\\'" file)
19970 (set-buffer (htmlize-buffer (current-buffer)))
19972 (when (and org-agenda-export-html-style
19973 (string-match "<style>" org-agenda-export-html-style))
19974 ;; replace <style> section with org-agenda-export-html-style
19975 (goto-char (point-min))
19976 (kill-region (- (search-forward "<style") 6)
19977 (search-forward "</style>"))
19978 (insert org-agenda-export-html-style))
19979 (write-file file)
19980 (kill-buffer (current-buffer))
19981 (message "HTML written to %s" file))
19982 ((string-match "\\.ps\\'" file)
19983 (ps-print-buffer-with-faces file)
19984 (message "Postscript written to %s" file))
19986 (let ((bs (buffer-string)))
19987 (find-file file)
19988 (insert bs)
19989 (save-buffer 0)
19990 (kill-buffer (current-buffer))
19991 (message "Plain text written to %s" file))))))
19992 (set-buffer org-agenda-buffer-name)))
19994 (defmacro org-no-read-only (&rest body)
19995 "Inhibit read-only for BODY."
19996 `(let ((inhibit-read-only t)) ,@body))
19998 (defun org-check-for-org-mode ()
19999 "Make sure current buffer is in org-mode. Error if not."
20000 (or (org-mode-p)
20001 (error "Cannot execute org-mode agenda command on buffer in %s."
20002 major-mode)))
20004 (defun org-fit-agenda-window ()
20005 "Fit the window to the buffer size."
20006 (and (memq org-agenda-window-setup '(reorganize-frame))
20007 (fboundp 'fit-window-to-buffer)
20008 (fit-window-to-buffer
20010 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
20011 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
20013 ;;; Agenda file list
20015 (defun org-agenda-files (&optional unrestricted)
20016 "Get the list of agenda files.
20017 Optional UNRESTRICTED means return the full list even if a restriction
20018 is currently in place."
20019 (let ((files
20020 (cond
20021 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
20022 ((stringp org-agenda-files) (org-read-agenda-file-list))
20023 ((listp org-agenda-files) org-agenda-files)
20024 (t (error "Invalid value of `org-agenda-files'")))))
20025 (setq files (apply 'append
20026 (mapcar (lambda (f)
20027 (if (file-directory-p f)
20028 (directory-files f t
20029 org-agenda-file-regexp)
20030 (list f)))
20031 files)))
20032 (if org-agenda-skip-unavailable-files
20033 (delq nil
20034 (mapcar (function
20035 (lambda (file)
20036 (and (file-readable-p file) file)))
20037 files))
20038 files))) ; `org-check-agenda-file' will remove them from the list
20040 (defun org-edit-agenda-file-list ()
20041 "Edit the list of agenda files.
20042 Depending on setup, this either uses customize to edit the variable
20043 `org-agenda-files', or it visits the file that is holding the list. In the
20044 latter case, the buffer is set up in a way that saving it automatically kills
20045 the buffer and restores the previous window configuration."
20046 (interactive)
20047 (if (stringp org-agenda-files)
20048 (let ((cw (current-window-configuration)))
20049 (find-file org-agenda-files)
20050 (org-set-local 'org-window-configuration cw)
20051 (org-add-hook 'after-save-hook
20052 (lambda ()
20053 (set-window-configuration
20054 (prog1 org-window-configuration
20055 (kill-buffer (current-buffer))))
20056 (org-install-agenda-files-menu)
20057 (message "New agenda file list installed"))
20058 nil 'local)
20059 (message "%s" (substitute-command-keys
20060 "Edit list and finish with \\[save-buffer]")))
20061 (customize-variable 'org-agenda-files)))
20063 (defun org-store-new-agenda-file-list (list)
20064 "Set new value for the agenda file list and save it correcly."
20065 (if (stringp org-agenda-files)
20066 (let ((f org-agenda-files) b)
20067 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
20068 (with-temp-file f
20069 (insert (mapconcat 'identity list "\n") "\n")))
20070 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
20071 (setq org-agenda-files list)
20072 (customize-save-variable 'org-agenda-files org-agenda-files))))
20074 (defun org-read-agenda-file-list ()
20075 "Read the list of agenda files from a file."
20076 (when (stringp org-agenda-files)
20077 (with-temp-buffer
20078 (insert-file-contents org-agenda-files)
20079 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
20082 ;;;###autoload
20083 (defun org-cycle-agenda-files ()
20084 "Cycle through the files in `org-agenda-files'.
20085 If the current buffer visits an agenda file, find the next one in the list.
20086 If the current buffer does not, find the first agenda file."
20087 (interactive)
20088 (let* ((fs (org-agenda-files t))
20089 (files (append fs (list (car fs))))
20090 (tcf (if buffer-file-name (file-truename buffer-file-name)))
20091 file)
20092 (unless files (error "No agenda files"))
20093 (catch 'exit
20094 (while (setq file (pop files))
20095 (if (equal (file-truename file) tcf)
20096 (when (car files)
20097 (find-file (car files))
20098 (throw 'exit t))))
20099 (find-file (car fs)))
20100 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
20102 (defun org-agenda-file-to-front (&optional to-end)
20103 "Move/add the current file to the top of the agenda file list.
20104 If the file is not present in the list, it is added to the front. If it is
20105 present, it is moved there. With optional argument TO-END, add/move to the
20106 end of the list."
20107 (interactive "P")
20108 (let ((org-agenda-skip-unavailable-files nil)
20109 (file-alist (mapcar (lambda (x)
20110 (cons (file-truename x) x))
20111 (org-agenda-files t)))
20112 (ctf (file-truename buffer-file-name))
20113 x had)
20114 (setq x (assoc ctf file-alist) had x)
20116 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
20117 (if to-end
20118 (setq file-alist (append (delq x file-alist) (list x)))
20119 (setq file-alist (cons x (delq x file-alist))))
20120 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
20121 (org-install-agenda-files-menu)
20122 (message "File %s to %s of agenda file list"
20123 (if had "moved" "added") (if to-end "end" "front"))))
20125 (defun org-remove-file (&optional file)
20126 "Remove current file from the list of files in variable `org-agenda-files'.
20127 These are the files which are being checked for agenda entries.
20128 Optional argument FILE means, use this file instead of the current."
20129 (interactive)
20130 (let* ((org-agenda-skip-unavailable-files nil)
20131 (file (or file buffer-file-name))
20132 (true-file (file-truename file))
20133 (afile (abbreviate-file-name file))
20134 (files (delq nil (mapcar
20135 (lambda (x)
20136 (if (equal true-file
20137 (file-truename x))
20138 nil x))
20139 (org-agenda-files t)))))
20140 (if (not (= (length files) (length (org-agenda-files t))))
20141 (progn
20142 (org-store-new-agenda-file-list files)
20143 (org-install-agenda-files-menu)
20144 (message "Removed file: %s" afile))
20145 (message "File was not in list: %s (not removed)" afile))))
20147 (defun org-file-menu-entry (file)
20148 (vector file (list 'find-file file) t))
20150 (defun org-check-agenda-file (file)
20151 "Make sure FILE exists. If not, ask user what to do."
20152 (when (not (file-exists-p file))
20153 (message "non-existent file %s. [R]emove from list or [A]bort?"
20154 (abbreviate-file-name file))
20155 (let ((r (downcase (read-char-exclusive))))
20156 (cond
20157 ((equal r ?r)
20158 (org-remove-file file)
20159 (throw 'nextfile t))
20160 (t (error "Abort"))))))
20162 ;;; Agenda prepare and finalize
20164 (defvar org-agenda-multi nil) ; dynammically scoped
20165 (defvar org-agenda-buffer-name "*Org Agenda*")
20166 (defvar org-pre-agenda-window-conf nil)
20167 (defvar org-agenda-name nil)
20168 (defun org-prepare-agenda (&optional name)
20169 (setq org-todo-keywords-for-agenda nil)
20170 (setq org-done-keywords-for-agenda nil)
20171 (if org-agenda-multi
20172 (progn
20173 (setq buffer-read-only nil)
20174 (goto-char (point-max))
20175 (unless (or (bobp) org-agenda-compact-blocks)
20176 (insert "\n" (make-string (window-width) ?=) "\n"))
20177 (narrow-to-region (point) (point-max)))
20178 (org-agenda-maybe-reset-markers 'force)
20179 (org-prepare-agenda-buffers (org-agenda-files))
20180 (setq org-todo-keywords-for-agenda
20181 (org-uniquify org-todo-keywords-for-agenda))
20182 (setq org-done-keywords-for-agenda
20183 (org-uniquify org-done-keywords-for-agenda))
20184 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
20185 (awin (get-buffer-window abuf)))
20186 (cond
20187 ((equal (current-buffer) abuf) nil)
20188 (awin (select-window awin))
20189 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
20190 ((equal org-agenda-window-setup 'current-window)
20191 (switch-to-buffer abuf))
20192 ((equal org-agenda-window-setup 'other-window)
20193 (org-switch-to-buffer-other-window abuf))
20194 ((equal org-agenda-window-setup 'other-frame)
20195 (switch-to-buffer-other-frame abuf))
20196 ((equal org-agenda-window-setup 'reorganize-frame)
20197 (delete-other-windows)
20198 (org-switch-to-buffer-other-window abuf))))
20199 (setq buffer-read-only nil)
20200 (erase-buffer)
20201 (org-agenda-mode)
20202 (and name (not org-agenda-name)
20203 (org-set-local 'org-agenda-name name)))
20204 (setq buffer-read-only nil))
20206 (defun org-finalize-agenda ()
20207 "Finishing touch for the agenda buffer, called just before displaying it."
20208 (unless org-agenda-multi
20209 (save-excursion
20210 (let ((inhibit-read-only t))
20211 (goto-char (point-min))
20212 (while (org-activate-bracket-links (point-max))
20213 (add-text-properties (match-beginning 0) (match-end 0)
20214 '(face org-link)))
20215 (org-agenda-align-tags)
20216 (unless org-agenda-with-colors
20217 (remove-text-properties (point-min) (point-max) '(face nil))))
20218 (if (and (boundp 'org-overriding-columns-format)
20219 org-overriding-columns-format)
20220 (org-set-local 'org-overriding-columns-format
20221 org-overriding-columns-format))
20222 (if (and (boundp 'org-agenda-view-columns-initially)
20223 org-agenda-view-columns-initially)
20224 (org-agenda-columns))
20225 (when org-agenda-fontify-priorities
20226 (org-fontify-priorities))
20227 (run-hooks 'org-finalize-agenda-hook)
20228 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20231 (defun org-fontify-priorities ()
20232 "Make highest priority lines bold, and lowest italic."
20233 (interactive)
20234 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
20235 (org-delete-overlay o)))
20236 (org-overlays-in (point-min) (point-max)))
20237 (save-excursion
20238 (let ((inhibit-read-only t)
20239 b e p ov h l)
20240 (goto-char (point-min))
20241 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
20242 (setq h (or (get-char-property (point) 'org-highest-priority)
20243 org-highest-priority)
20244 l (or (get-char-property (point) 'org-lowest-priority)
20245 org-lowest-priority)
20246 p (string-to-char (match-string 1))
20247 b (match-beginning 0) e (point-at-eol)
20248 ov (org-make-overlay b e))
20249 (org-overlay-put
20250 ov 'face
20251 (cond ((listp org-agenda-fontify-priorities)
20252 (cdr (assoc p org-agenda-fontify-priorities)))
20253 ((equal p l) 'italic)
20254 ((equal p h) 'bold)))
20255 (org-overlay-put ov 'org-type 'org-priority)))))
20257 (defun org-prepare-agenda-buffers (files)
20258 "Create buffers for all agenda files, protect archived trees and comments."
20259 (interactive)
20260 (let ((pa '(:org-archived t))
20261 (pc '(:org-comment t))
20262 (pall '(:org-archived t :org-comment t))
20263 (inhibit-read-only t)
20264 (rea (concat ":" org-archive-tag ":"))
20265 bmp file re)
20266 (save-excursion
20267 (save-restriction
20268 (while (setq file (pop files))
20269 (if (bufferp file)
20270 (set-buffer file)
20271 (org-check-agenda-file file)
20272 (set-buffer (org-get-agenda-file-buffer file)))
20273 (widen)
20274 (setq bmp (buffer-modified-p))
20275 (org-refresh-category-properties)
20276 (setq org-todo-keywords-for-agenda
20277 (append org-todo-keywords-for-agenda org-todo-keywords-1))
20278 (setq org-done-keywords-for-agenda
20279 (append org-done-keywords-for-agenda org-done-keywords))
20280 (save-excursion
20281 (remove-text-properties (point-min) (point-max) pall)
20282 (when org-agenda-skip-archived-trees
20283 (goto-char (point-min))
20284 (while (re-search-forward rea nil t)
20285 (if (org-on-heading-p t)
20286 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
20287 (goto-char (point-min))
20288 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
20289 (while (re-search-forward re nil t)
20290 (add-text-properties
20291 (match-beginning 0) (org-end-of-subtree t) pc)))
20292 (set-buffer-modified-p bmp))))))
20294 (defvar org-agenda-skip-function nil
20295 "Function to be called at each match during agenda construction.
20296 If this function returns nil, the current match should not be skipped.
20297 Otherwise, the function must return a position from where the search
20298 should be continued.
20299 This may also be a Lisp form, it will be evaluated.
20300 Never set this variable using `setq' or so, because then it will apply
20301 to all future agenda commands. Instead, bind it with `let' to scope
20302 it dynamically into the agenda-constructing command. A good way to set
20303 it is through options in org-agenda-custom-commands.")
20305 (defun org-agenda-skip ()
20306 "Throw to `:skip' in places that should be skipped.
20307 Also moves point to the end of the skipped region, so that search can
20308 continue from there."
20309 (let ((p (point-at-bol)) to fp)
20310 (and org-agenda-skip-archived-trees
20311 (get-text-property p :org-archived)
20312 (org-end-of-subtree t)
20313 (throw :skip t))
20314 (and (get-text-property p :org-comment)
20315 (org-end-of-subtree t)
20316 (throw :skip t))
20317 (if (equal (char-after p) ?#) (throw :skip t))
20318 (when (and (or (setq fp (functionp org-agenda-skip-function))
20319 (consp org-agenda-skip-function))
20320 (setq to (save-excursion
20321 (save-match-data
20322 (if fp
20323 (funcall org-agenda-skip-function)
20324 (eval org-agenda-skip-function))))))
20325 (goto-char to)
20326 (throw :skip t))))
20328 (defvar org-agenda-markers nil
20329 "List of all currently active markers created by `org-agenda'.")
20330 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20331 "Creation time of the last agenda marker.")
20333 (defun org-agenda-new-marker (&optional pos)
20334 "Return a new agenda marker.
20335 Org-mode keeps a list of these markers and resets them when they are
20336 no longer in use."
20337 (let ((m (copy-marker (or pos (point)))))
20338 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20339 (push m org-agenda-markers)
20342 (defun org-agenda-maybe-reset-markers (&optional force)
20343 "Reset markers created by `org-agenda'. But only if they are old enough."
20344 (if (or (and force (not org-agenda-multi))
20345 (> (- (time-to-seconds (current-time))
20346 org-agenda-last-marker-time)
20348 (while org-agenda-markers
20349 (move-marker (pop org-agenda-markers) nil))))
20351 (defun org-get-agenda-file-buffer (file)
20352 "Get a buffer visiting FILE. If the buffer needs to be created, add
20353 it to the list of buffers which might be released later."
20354 (let ((buf (org-find-base-buffer-visiting file)))
20355 (if buf
20356 buf ; just return it
20357 ;; Make a new buffer and remember it
20358 (setq buf (find-file-noselect file))
20359 (if buf (push buf org-agenda-new-buffers))
20360 buf)))
20362 (defun org-release-buffers (blist)
20363 "Release all buffers in list, asking the user for confirmation when needed.
20364 When a buffer is unmodified, it is just killed. When modified, it is saved
20365 \(if the user agrees) and then killed."
20366 (let (buf file)
20367 (while (setq buf (pop blist))
20368 (setq file (buffer-file-name buf))
20369 (when (and (buffer-modified-p buf)
20370 file
20371 (y-or-n-p (format "Save file %s? " file)))
20372 (with-current-buffer buf (save-buffer)))
20373 (kill-buffer buf))))
20375 (defun org-get-category (&optional pos)
20376 "Get the category applying to position POS."
20377 (get-text-property (or pos (point)) 'org-category))
20379 ;;; Agenda timeline
20381 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20383 (defun org-timeline (&optional include-all)
20384 "Show a time-sorted view of the entries in the current org file.
20385 Only entries with a time stamp of today or later will be listed. With
20386 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20387 under the current date.
20388 If the buffer contains an active region, only check the region for
20389 dates."
20390 (interactive "P")
20391 (require 'calendar)
20392 (org-compile-prefix-format 'timeline)
20393 (org-set-sorting-strategy 'timeline)
20394 (let* ((dopast t)
20395 (dotodo include-all)
20396 (doclosed org-agenda-show-log)
20397 (entry buffer-file-name)
20398 (date (calendar-current-date))
20399 (beg (if (org-region-active-p) (region-beginning) (point-min)))
20400 (end (if (org-region-active-p) (region-end) (point-max)))
20401 (day-numbers (org-get-all-dates beg end 'no-ranges
20402 t doclosed ; always include today
20403 org-timeline-show-empty-dates))
20404 (org-deadline-warning-days 0)
20405 (org-agenda-only-exact-dates t)
20406 (today (time-to-days (current-time)))
20407 (past t)
20408 args
20409 s e rtn d emptyp)
20410 (setq org-agenda-redo-command
20411 (list 'progn
20412 (list 'org-switch-to-buffer-other-window (current-buffer))
20413 (list 'org-timeline (list 'quote include-all))))
20414 (if (not dopast)
20415 ;; Remove past dates from the list of dates.
20416 (setq day-numbers (delq nil (mapcar (lambda(x)
20417 (if (>= x today) x nil))
20418 day-numbers))))
20419 (org-prepare-agenda (concat "Timeline "
20420 (file-name-nondirectory buffer-file-name)))
20421 (if doclosed (push :closed args))
20422 (push :timestamp args)
20423 (push :deadline args)
20424 (push :scheduled args)
20425 (push :sexp args)
20426 (if dotodo (push :todo args))
20427 (while (setq d (pop day-numbers))
20428 (if (and (listp d) (eq (car d) :omitted))
20429 (progn
20430 (setq s (point))
20431 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20432 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20433 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20434 (if (and (>= d today)
20435 dopast
20436 past)
20437 (progn
20438 (setq past nil)
20439 (insert (make-string 79 ?-) "\n")))
20440 (setq date (calendar-gregorian-from-absolute d))
20441 (setq s (point))
20442 (setq rtn (and (not emptyp)
20443 (apply 'org-agenda-get-day-entries entry
20444 date args)))
20445 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20446 (progn
20447 (insert
20448 (if (stringp org-agenda-format-date)
20449 (format-time-string org-agenda-format-date
20450 (org-time-from-absolute date))
20451 (funcall org-agenda-format-date date))
20452 "\n")
20453 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20454 (put-text-property s (1- (point)) 'org-date-line t)
20455 (if (equal d today)
20456 (put-text-property s (1- (point)) 'org-today t))
20457 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20458 (put-text-property s (1- (point)) 'day d)))))
20459 (goto-char (point-min))
20460 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20461 (point-min)))
20462 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20463 (org-finalize-agenda)
20464 (setq buffer-read-only t)))
20466 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty pre-re)
20467 "Return a list of all relevant day numbers from BEG to END buffer positions.
20468 If NO-RANGES is non-nil, include only the start and end dates of a range,
20469 not every single day in the range. If FORCE-TODAY is non-nil, make
20470 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20471 inactive time stamps (those in square brackets) are included.
20472 When EMPTY is non-nil, also include days without any entries."
20473 (let ((re (concat
20474 (if pre-re pre-re "")
20475 (if inactive org-ts-regexp-both org-ts-regexp)))
20476 dates dates1 date day day1 day2 ts1 ts2)
20477 (if force-today
20478 (setq dates (list (time-to-days (current-time)))))
20479 (save-excursion
20480 (goto-char beg)
20481 (while (re-search-forward re end t)
20482 (setq day (time-to-days (org-time-string-to-time
20483 (substring (match-string 1) 0 10))))
20484 (or (memq day dates) (push day dates)))
20485 (unless no-ranges
20486 (goto-char beg)
20487 (while (re-search-forward org-tr-regexp end t)
20488 (setq ts1 (substring (match-string 1) 0 10)
20489 ts2 (substring (match-string 2) 0 10)
20490 day1 (time-to-days (org-time-string-to-time ts1))
20491 day2 (time-to-days (org-time-string-to-time ts2)))
20492 (while (< (setq day1 (1+ day1)) day2)
20493 (or (memq day1 dates) (push day1 dates)))))
20494 (setq dates (sort dates '<))
20495 (when empty
20496 (while (setq day (pop dates))
20497 (setq day2 (car dates))
20498 (push day dates1)
20499 (when (and day2 empty)
20500 (if (or (eq empty t)
20501 (and (numberp empty) (<= (- day2 day) empty)))
20502 (while (< (setq day (1+ day)) day2)
20503 (push (list day) dates1))
20504 (push (cons :omitted (- day2 day)) dates1))))
20505 (setq dates (nreverse dates1)))
20506 dates)))
20508 ;;; Agenda Daily/Weekly
20510 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
20511 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
20512 (defvar org-agenda-last-arguments nil
20513 "The arguments of the previous call to org-agenda")
20514 (defvar org-starting-day nil) ; local variable in the agenda buffer
20515 (defvar org-agenda-span nil) ; local variable in the agenda buffer
20516 (defvar org-include-all-loc nil) ; local variable
20517 (defvar org-agenda-remove-date nil) ; dynamically scoped
20519 ;;;###autoload
20520 (defun org-agenda-list (&optional include-all start-day ndays)
20521 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
20522 The view will be for the current day or week, but from the overview buffer
20523 you will be able to go to other days/weeks.
20525 With one \\[universal-argument] prefix argument INCLUDE-ALL,
20526 all unfinished TODO items will also be shown, before the agenda.
20527 This feature is considered obsolete, please use the TODO list or a block
20528 agenda instead.
20530 With a numeric prefix argument in an interactive call, the agenda will
20531 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
20532 the number of days. NDAYS defaults to `org-agenda-ndays'.
20534 START-DAY defaults to TODAY, or to the most recent match for the weekday
20535 given in `org-agenda-start-on-weekday'."
20536 (interactive "P")
20537 (if (and (integerp include-all) (> include-all 0))
20538 (setq ndays include-all include-all nil))
20539 (setq ndays (or ndays org-agenda-ndays)
20540 start-day (or start-day org-agenda-start-day))
20541 (if org-agenda-overriding-arguments
20542 (setq include-all (car org-agenda-overriding-arguments)
20543 start-day (nth 1 org-agenda-overriding-arguments)
20544 ndays (nth 2 org-agenda-overriding-arguments)))
20545 (if (stringp start-day)
20546 ;; Convert to an absolute day number
20547 (setq start-day (time-to-days (org-read-date nil t start-day))))
20548 (setq org-agenda-last-arguments (list include-all start-day ndays))
20549 (org-compile-prefix-format 'agenda)
20550 (org-set-sorting-strategy 'agenda)
20551 (require 'calendar)
20552 (let* ((org-agenda-start-on-weekday
20553 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
20554 org-agenda-start-on-weekday nil))
20555 (thefiles (org-agenda-files))
20556 (files thefiles)
20557 (today (time-to-days
20558 (time-subtract (current-time)
20559 (list 0 (* 3600 org-extend-today-until) 0))))
20560 (sd (or start-day today))
20561 (start (if (or (null org-agenda-start-on-weekday)
20562 (< org-agenda-ndays 7))
20564 (let* ((nt (calendar-day-of-week
20565 (calendar-gregorian-from-absolute sd)))
20566 (n1 org-agenda-start-on-weekday)
20567 (d (- nt n1)))
20568 (- sd (+ (if (< d 0) 7 0) d)))))
20569 (day-numbers (list start))
20570 (day-cnt 0)
20571 (inhibit-redisplay (not debug-on-error))
20572 s e rtn rtnall file date d start-pos end-pos todayp nd)
20573 (setq org-agenda-redo-command
20574 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
20575 ;; Make the list of days
20576 (setq ndays (or ndays org-agenda-ndays)
20577 nd ndays)
20578 (while (> ndays 1)
20579 (push (1+ (car day-numbers)) day-numbers)
20580 (setq ndays (1- ndays)))
20581 (setq day-numbers (nreverse day-numbers))
20582 (org-prepare-agenda "Day/Week")
20583 (org-set-local 'org-starting-day (car day-numbers))
20584 (org-set-local 'org-include-all-loc include-all)
20585 (org-set-local 'org-agenda-span
20586 (org-agenda-ndays-to-span nd))
20587 (when (and (or include-all org-agenda-include-all-todo)
20588 (member today day-numbers))
20589 (setq files thefiles
20590 rtnall nil)
20591 (while (setq file (pop files))
20592 (catch 'nextfile
20593 (org-check-agenda-file file)
20594 (setq date (calendar-gregorian-from-absolute today)
20595 rtn (org-agenda-get-day-entries
20596 file date :todo))
20597 (setq rtnall (append rtnall rtn))))
20598 (when rtnall
20599 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
20600 (add-text-properties (point-min) (1- (point))
20601 (list 'face 'org-agenda-structure))
20602 (insert (org-finalize-agenda-entries rtnall) "\n")))
20603 (unless org-agenda-compact-blocks
20604 (setq s (point))
20605 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
20606 "-agenda:\n")
20607 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
20608 'org-date-line t)))
20609 (while (setq d (pop day-numbers))
20610 (setq date (calendar-gregorian-from-absolute d)
20611 s (point))
20612 (if (or (setq todayp (= d today))
20613 (and (not start-pos) (= d sd)))
20614 (setq start-pos (point))
20615 (if (and start-pos (not end-pos))
20616 (setq end-pos (point))))
20617 (setq files thefiles
20618 rtnall nil)
20619 (while (setq file (pop files))
20620 (catch 'nextfile
20621 (org-check-agenda-file file)
20622 (if org-agenda-show-log
20623 (setq rtn (org-agenda-get-day-entries
20624 file date
20625 :deadline :scheduled :timestamp :sexp :closed))
20626 (setq rtn (org-agenda-get-day-entries
20627 file date
20628 :deadline :scheduled :sexp :timestamp)))
20629 (setq rtnall (append rtnall rtn))))
20630 (if org-agenda-include-diary
20631 (progn
20632 (require 'diary-lib)
20633 (setq rtn (org-get-entries-from-diary date))
20634 (setq rtnall (append rtnall rtn))))
20635 (if (or rtnall org-agenda-show-all-dates)
20636 (progn
20637 (setq day-cnt (1+ day-cnt))
20638 (insert
20639 (if (stringp org-agenda-format-date)
20640 (format-time-string org-agenda-format-date
20641 (org-time-from-absolute date))
20642 (funcall org-agenda-format-date date))
20643 "\n")
20644 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20645 (put-text-property s (1- (point)) 'org-date-line t)
20646 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
20647 (if todayp (put-text-property s (1- (point)) 'org-today t))
20648 (if rtnall (insert
20649 (org-finalize-agenda-entries
20650 (org-agenda-add-time-grid-maybe
20651 rtnall nd todayp))
20652 "\n"))
20653 (put-text-property s (1- (point)) 'day d)
20654 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
20655 (goto-char (point-min))
20656 (org-fit-agenda-window)
20657 (unless (and (pos-visible-in-window-p (point-min))
20658 (pos-visible-in-window-p (point-max)))
20659 (goto-char (1- (point-max)))
20660 (recenter -1)
20661 (if (not (pos-visible-in-window-p (or start-pos 1)))
20662 (progn
20663 (goto-char (or start-pos 1))
20664 (recenter 1))))
20665 (goto-char (or start-pos 1))
20666 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
20667 (org-finalize-agenda)
20668 (setq buffer-read-only t)
20669 (message "")))
20671 (defun org-agenda-ndays-to-span (n)
20672 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
20674 ;;; Agenda TODO list
20676 (defvar org-select-this-todo-keyword nil)
20677 (defvar org-last-arg nil)
20679 ;;;###autoload
20680 (defun org-todo-list (arg)
20681 "Show all TODO entries from all agenda file in a single list.
20682 The prefix arg can be used to select a specific TODO keyword and limit
20683 the list to these. When using \\[universal-argument], you will be prompted
20684 for a keyword. A numeric prefix directly selects the Nth keyword in
20685 `org-todo-keywords-1'."
20686 (interactive "P")
20687 (require 'calendar)
20688 (org-compile-prefix-format 'todo)
20689 (org-set-sorting-strategy 'todo)
20690 (org-prepare-agenda "TODO")
20691 (let* ((today (time-to-days (current-time)))
20692 (date (calendar-gregorian-from-absolute today))
20693 (kwds org-todo-keywords-for-agenda)
20694 (completion-ignore-case t)
20695 (org-select-this-todo-keyword
20696 (if (stringp arg) arg
20697 (and arg (integerp arg) (> arg 0)
20698 (nth (1- arg) kwds))))
20699 rtn rtnall files file pos)
20700 (when (equal arg '(4))
20701 (setq org-select-this-todo-keyword
20702 (completing-read "Keyword (or KWD1|K2D2|...): "
20703 (mapcar 'list kwds) nil nil)))
20704 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
20705 (org-set-local 'org-last-arg arg)
20706 (setq org-agenda-redo-command
20707 '(org-todo-list (or current-prefix-arg org-last-arg)))
20708 (setq files (org-agenda-files)
20709 rtnall nil)
20710 (while (setq file (pop files))
20711 (catch 'nextfile
20712 (org-check-agenda-file file)
20713 (setq rtn (org-agenda-get-day-entries file date :todo))
20714 (setq rtnall (append rtnall rtn))))
20715 (if org-agenda-overriding-header
20716 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20717 nil 'face 'org-agenda-structure) "\n")
20718 (insert "Global list of TODO items of type: ")
20719 (add-text-properties (point-min) (1- (point))
20720 (list 'face 'org-agenda-structure))
20721 (setq pos (point))
20722 (insert (or org-select-this-todo-keyword "ALL") "\n")
20723 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20724 (setq pos (point))
20725 (unless org-agenda-multi
20726 (insert "Available with `N r': (0)ALL")
20727 (let ((n 0) s)
20728 (mapc (lambda (x)
20729 (setq s (format "(%d)%s" (setq n (1+ n)) x))
20730 (if (> (+ (current-column) (string-width s) 1) (frame-width))
20731 (insert "\n "))
20732 (insert " " s))
20733 kwds))
20734 (insert "\n"))
20735 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20736 (when rtnall
20737 (insert (org-finalize-agenda-entries rtnall) "\n"))
20738 (goto-char (point-min))
20739 (org-fit-agenda-window)
20740 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
20741 (org-finalize-agenda)
20742 (setq buffer-read-only t)))
20744 ;;; Agenda tags match
20746 ;;;###autoload
20747 (defun org-tags-view (&optional todo-only match)
20748 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
20749 The prefix arg TODO-ONLY limits the search to TODO entries."
20750 (interactive "P")
20751 (org-compile-prefix-format 'tags)
20752 (org-set-sorting-strategy 'tags)
20753 (let* ((org-tags-match-list-sublevels
20754 (if todo-only t org-tags-match-list-sublevels))
20755 (completion-ignore-case t)
20756 rtn rtnall files file pos matcher
20757 buffer)
20758 (setq matcher (org-make-tags-matcher match)
20759 match (car matcher) matcher (cdr matcher))
20760 (org-prepare-agenda (concat "TAGS " match))
20761 (setq org-agenda-redo-command
20762 (list 'org-tags-view (list 'quote todo-only)
20763 (list 'if 'current-prefix-arg nil match)))
20764 (setq files (org-agenda-files)
20765 rtnall nil)
20766 (while (setq file (pop files))
20767 (catch 'nextfile
20768 (org-check-agenda-file file)
20769 (setq buffer (if (file-exists-p file)
20770 (org-get-agenda-file-buffer file)
20771 (error "No such file %s" file)))
20772 (if (not buffer)
20773 ;; If file does not exist, merror message to agenda
20774 (setq rtn (list
20775 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
20776 rtnall (append rtnall rtn))
20777 (with-current-buffer buffer
20778 (unless (org-mode-p)
20779 (error "Agenda file %s is not in `org-mode'" file))
20780 (save-excursion
20781 (save-restriction
20782 (if org-agenda-restrict
20783 (narrow-to-region org-agenda-restrict-begin
20784 org-agenda-restrict-end)
20785 (widen))
20786 (setq rtn (org-scan-tags 'agenda matcher todo-only))
20787 (setq rtnall (append rtnall rtn))))))))
20788 (if org-agenda-overriding-header
20789 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20790 nil 'face 'org-agenda-structure) "\n")
20791 (insert "Headlines with TAGS match: ")
20792 (add-text-properties (point-min) (1- (point))
20793 (list 'face 'org-agenda-structure))
20794 (setq pos (point))
20795 (insert match "\n")
20796 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20797 (setq pos (point))
20798 (unless org-agenda-multi
20799 (insert "Press `C-u r' to search again with new search string\n"))
20800 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20801 (when rtnall
20802 (insert (org-finalize-agenda-entries rtnall) "\n"))
20803 (goto-char (point-min))
20804 (org-fit-agenda-window)
20805 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
20806 (org-finalize-agenda)
20807 (setq buffer-read-only t)))
20809 ;;; Agenda Finding stuck projects
20811 (defvar org-agenda-skip-regexp nil
20812 "Regular expression used in skipping subtrees for the agenda.
20813 This is basically a temporary global variable that can be set and then
20814 used by user-defined selections using `org-agenda-skip-function'.")
20816 (defvar org-agenda-overriding-header nil
20817 "When this is set during todo and tags searches, will replace header.")
20819 (defun org-agenda-skip-subtree-when-regexp-matches ()
20820 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
20821 If yes, it returns the end position of this tree, causing agenda commands
20822 to skip this subtree. This is a function that can be put into
20823 `org-agenda-skip-function' for the duration of a command."
20824 (let ((end (save-excursion (org-end-of-subtree t)))
20825 skip)
20826 (save-excursion
20827 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
20828 (and skip end)))
20830 (defun org-agenda-skip-entry-if (&rest conditions)
20831 "Skip entry if any of CONDITIONS is true.
20832 See `org-agenda-skip-if' for details."
20833 (org-agenda-skip-if nil conditions))
20835 (defun org-agenda-skip-subtree-if (&rest conditions)
20836 "Skip entry if any of CONDITIONS is true.
20837 See `org-agenda-skip-if' for details."
20838 (org-agenda-skip-if t conditions))
20840 (defun org-agenda-skip-if (subtree conditions)
20841 "Checks current entity for CONDITIONS.
20842 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
20843 the entry, i.e. the text before the next heading is checked.
20845 CONDITIONS is a list of symbols, boolean OR is used to combine the results
20846 from different tests. Valid conditions are:
20848 scheduled Check if there is a scheduled cookie
20849 notscheduled Check if there is no scheduled cookie
20850 deadline Check if there is a deadline
20851 notdeadline Check if there is no deadline
20852 regexp Check if regexp matches
20853 notregexp Check if regexp does not match.
20855 The regexp is taken from the conditions list, it must come right after
20856 the `regexp' or `notregexp' element.
20858 If any of these conditions is met, this function returns the end point of
20859 the entity, causing the search to continue from there. This is a function
20860 that can be put into `org-agenda-skip-function' for the duration of a command."
20861 (let (beg end m)
20862 (org-back-to-heading t)
20863 (setq beg (point)
20864 end (if subtree
20865 (progn (org-end-of-subtree t) (point))
20866 (progn (outline-next-heading) (1- (point)))))
20867 (goto-char beg)
20868 (and
20870 (and (memq 'scheduled conditions)
20871 (re-search-forward org-scheduled-time-regexp end t))
20872 (and (memq 'notscheduled conditions)
20873 (not (re-search-forward org-scheduled-time-regexp end t)))
20874 (and (memq 'deadline conditions)
20875 (re-search-forward org-deadline-time-regexp end t))
20876 (and (memq 'notdeadline conditions)
20877 (not (re-search-forward org-deadline-time-regexp end t)))
20878 (and (setq m (memq 'regexp conditions))
20879 (stringp (nth 1 m))
20880 (re-search-forward (nth 1 m) end t))
20881 (and (setq m (memq 'notregexp conditions))
20882 (stringp (nth 1 m))
20883 (not (re-search-forward (nth 1 m) end t))))
20884 end)))
20886 ;;;###autoload
20887 (defun org-agenda-list-stuck-projects (&rest ignore)
20888 "Create agenda view for projects that are stuck.
20889 Stuck projects are project that have no next actions. For the definitions
20890 of what a project is and how to check if it stuck, customize the variable
20891 `org-stuck-projects'.
20892 MATCH is being ignored."
20893 (interactive)
20894 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
20895 ;; FIXME: we could have used org-agenda-skip-if here.
20896 (org-agenda-overriding-header "List of stuck projects: ")
20897 (matcher (nth 0 org-stuck-projects))
20898 (todo (nth 1 org-stuck-projects))
20899 (todo-wds (if (member "*" todo)
20900 (progn
20901 (org-prepare-agenda-buffers (org-agenda-files))
20902 (org-delete-all
20903 org-done-keywords-for-agenda
20904 (copy-sequence org-todo-keywords-for-agenda)))
20905 todo))
20906 (todo-re (concat "^\\*+[ \t]+\\("
20907 (mapconcat 'identity todo-wds "\\|")
20908 "\\)\\>"))
20909 (tags (nth 2 org-stuck-projects))
20910 (tags-re (if (member "*" tags)
20911 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
20912 (concat "^\\*+ .*:\\("
20913 (mapconcat 'identity tags "\\|")
20914 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
20915 (gen-re (nth 3 org-stuck-projects))
20916 (re-list
20917 (delq nil
20918 (list
20919 (if todo todo-re)
20920 (if tags tags-re)
20921 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
20922 gen-re)))))
20923 (setq org-agenda-skip-regexp
20924 (if re-list
20925 (mapconcat 'identity re-list "\\|")
20926 (error "No information how to identify unstuck projects")))
20927 (org-tags-view nil matcher)
20928 (with-current-buffer org-agenda-buffer-name
20929 (setq org-agenda-redo-command
20930 '(org-agenda-list-stuck-projects
20931 (or current-prefix-arg org-last-arg))))))
20933 ;;; Diary integration
20935 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
20937 (defun org-get-entries-from-diary (date)
20938 "Get the (Emacs Calendar) diary entries for DATE."
20939 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
20940 (diary-display-hook '(fancy-diary-display))
20941 (pop-up-frames nil)
20942 (list-diary-entries-hook
20943 (cons 'org-diary-default-entry list-diary-entries-hook))
20944 (diary-file-name-prefix-function nil) ; turn this feature off
20945 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
20946 entries
20947 (org-disable-agenda-to-diary t))
20948 (save-excursion
20949 (save-window-excursion
20950 (funcall (if (fboundp 'diary-list-entries)
20951 'diary-list-entries 'list-diary-entries)
20952 date 1)))
20953 (if (not (get-buffer fancy-diary-buffer))
20954 (setq entries nil)
20955 (with-current-buffer fancy-diary-buffer
20956 (setq buffer-read-only nil)
20957 (if (zerop (buffer-size))
20958 ;; No entries
20959 (setq entries nil)
20960 ;; Omit the date and other unnecessary stuff
20961 (org-agenda-cleanup-fancy-diary)
20962 ;; Add prefix to each line and extend the text properties
20963 (if (zerop (buffer-size))
20964 (setq entries nil)
20965 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
20966 (set-buffer-modified-p nil)
20967 (kill-buffer fancy-diary-buffer)))
20968 (when entries
20969 (setq entries (org-split-string entries "\n"))
20970 (setq entries
20971 (mapcar
20972 (lambda (x)
20973 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
20974 ;; Extend the text properties to the beginning of the line
20975 (org-add-props x (text-properties-at (1- (length x)) x)
20976 'type "diary" 'date date))
20977 entries)))))
20979 (defun org-agenda-cleanup-fancy-diary ()
20980 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
20981 This gets rid of the date, the underline under the date, and
20982 the dummy entry installed by `org-mode' to ensure non-empty diary for each
20983 date. It also removes lines that contain only whitespace."
20984 (goto-char (point-min))
20985 (if (looking-at ".*?:[ \t]*")
20986 (progn
20987 (replace-match "")
20988 (re-search-forward "\n=+$" nil t)
20989 (replace-match "")
20990 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
20991 (re-search-forward "\n=+$" nil t)
20992 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
20993 (goto-char (point-min))
20994 (while (re-search-forward "^ +\n" nil t)
20995 (replace-match ""))
20996 (goto-char (point-min))
20997 (if (re-search-forward "^Org-mode dummy\n?" nil t)
20998 (replace-match "")))
21000 ;; Make sure entries from the diary have the right text properties.
21001 (eval-after-load "diary-lib"
21002 '(if (boundp 'diary-modify-entry-list-string-function)
21003 ;; We can rely on the hook, nothing to do
21005 ;; Hook not avaiable, must use advice to make this work
21006 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
21007 "Make the position visible."
21008 (if (and org-disable-agenda-to-diary ;; called from org-agenda
21009 (stringp string)
21010 buffer-file-name)
21011 (setq string (org-modify-diary-entry-string string))))))
21013 (defun org-modify-diary-entry-string (string)
21014 "Add text properties to string, allowing org-mode to act on it."
21015 (org-add-props string nil
21016 'mouse-face 'highlight
21017 'keymap org-agenda-keymap
21018 'help-echo (if buffer-file-name
21019 (format "mouse-2 or RET jump to diary file %s"
21020 (abbreviate-file-name buffer-file-name))
21022 'org-agenda-diary-link t
21023 'org-marker (org-agenda-new-marker (point-at-bol))))
21025 (defun org-diary-default-entry ()
21026 "Add a dummy entry to the diary.
21027 Needed to avoid empty dates which mess up holiday display."
21028 ;; Catch the error if dealing with the new add-to-diary-alist
21029 (when org-disable-agenda-to-diary
21030 (condition-case nil
21031 (add-to-diary-list original-date "Org-mode dummy" "")
21032 (error
21033 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
21035 ;;;###autoload
21036 (defun org-diary (&rest args)
21037 "Return diary information from org-files.
21038 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
21039 It accesses org files and extracts information from those files to be
21040 listed in the diary. The function accepts arguments specifying what
21041 items should be listed. The following arguments are allowed:
21043 :timestamp List the headlines of items containing a date stamp or
21044 date range matching the selected date. Deadlines will
21045 also be listed, on the expiration day.
21047 :sexp List entries resulting from diary-like sexps.
21049 :deadline List any deadlines past due, or due within
21050 `org-deadline-warning-days'. The listing occurs only
21051 in the diary for *today*, not at any other date. If
21052 an entry is marked DONE, it is no longer listed.
21054 :scheduled List all items which are scheduled for the given date.
21055 The diary for *today* also contains items which were
21056 scheduled earlier and are not yet marked DONE.
21058 :todo List all TODO items from the org-file. This may be a
21059 long list - so this is not turned on by default.
21060 Like deadlines, these entries only show up in the
21061 diary for *today*, not at any other date.
21063 The call in the diary file should look like this:
21065 &%%(org-diary) ~/path/to/some/orgfile.org
21067 Use a separate line for each org file to check. Or, if you omit the file name,
21068 all files listed in `org-agenda-files' will be checked automatically:
21070 &%%(org-diary)
21072 If you don't give any arguments (as in the example above), the default
21073 arguments (:deadline :scheduled :timestamp :sexp) are used.
21074 So the example above may also be written as
21076 &%%(org-diary :deadline :timestamp :sexp :scheduled)
21078 The function expects the lisp variables `entry' and `date' to be provided
21079 by the caller, because this is how the calendar works. Don't use this
21080 function from a program - use `org-agenda-get-day-entries' instead."
21081 (org-agenda-maybe-reset-markers)
21082 (org-compile-prefix-format 'agenda)
21083 (org-set-sorting-strategy 'agenda)
21084 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21085 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
21086 (list entry)
21087 (org-agenda-files t)))
21088 file rtn results)
21089 (org-prepare-agenda-buffers files)
21090 ;; If this is called during org-agenda, don't return any entries to
21091 ;; the calendar. Org Agenda will list these entries itself.
21092 (if org-disable-agenda-to-diary (setq files nil))
21093 (while (setq file (pop files))
21094 (setq rtn (apply 'org-agenda-get-day-entries file date args))
21095 (setq results (append results rtn)))
21096 (if results
21097 (concat (org-finalize-agenda-entries results) "\n"))))
21099 ;;; Agenda entry finders
21101 (defun org-agenda-get-day-entries (file date &rest args)
21102 "Does the work for `org-diary' and `org-agenda'.
21103 FILE is the path to a file to be checked for entries. DATE is date like
21104 the one returned by `calendar-current-date'. ARGS are symbols indicating
21105 which kind of entries should be extracted. For details about these, see
21106 the documentation of `org-diary'."
21107 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21108 (let* ((org-startup-folded nil)
21109 (org-startup-align-all-tables nil)
21110 (buffer (if (file-exists-p file)
21111 (org-get-agenda-file-buffer file)
21112 (error "No such file %s" file)))
21113 arg results rtn)
21114 (if (not buffer)
21115 ;; If file does not exist, make sure an error message ends up in diary
21116 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21117 (with-current-buffer buffer
21118 (unless (org-mode-p)
21119 (error "Agenda file %s is not in `org-mode'" file))
21120 (let ((case-fold-search nil))
21121 (save-excursion
21122 (save-restriction
21123 (if org-agenda-restrict
21124 (narrow-to-region org-agenda-restrict-begin
21125 org-agenda-restrict-end)
21126 (widen))
21127 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
21128 (while (setq arg (pop args))
21129 (cond
21130 ((and (eq arg :todo)
21131 (equal date (calendar-current-date)))
21132 (setq rtn (org-agenda-get-todos))
21133 (setq results (append results rtn)))
21134 ((eq arg :timestamp)
21135 (setq rtn (org-agenda-get-blocks))
21136 (setq results (append results rtn))
21137 (setq rtn (org-agenda-get-timestamps))
21138 (setq results (append results rtn)))
21139 ((eq arg :sexp)
21140 (setq rtn (org-agenda-get-sexps))
21141 (setq results (append results rtn)))
21142 ((eq arg :scheduled)
21143 (setq rtn (org-agenda-get-scheduled))
21144 (setq results (append results rtn)))
21145 ((eq arg :closed)
21146 (setq rtn (org-agenda-get-closed))
21147 (setq results (append results rtn)))
21148 ((eq arg :deadline)
21149 (setq rtn (org-agenda-get-deadlines))
21150 (setq results (append results rtn))))))))
21151 results))))
21153 (defun org-entry-is-todo-p ()
21154 (member (org-get-todo-state) org-not-done-keywords))
21156 (defun org-entry-is-done-p ()
21157 (member (org-get-todo-state) org-done-keywords))
21159 (defun org-get-todo-state ()
21160 (save-excursion
21161 (org-back-to-heading t)
21162 (and (looking-at org-todo-line-regexp)
21163 (match-end 2)
21164 (match-string 2))))
21166 (defun org-at-date-range-p (&optional inactive-ok)
21167 "Is the cursor inside a date range?"
21168 (interactive)
21169 (save-excursion
21170 (catch 'exit
21171 (let ((pos (point)))
21172 (skip-chars-backward "^[<\r\n")
21173 (skip-chars-backward "<[")
21174 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21175 (>= (match-end 0) pos)
21176 (throw 'exit t))
21177 (skip-chars-backward "^<[\r\n")
21178 (skip-chars-backward "<[")
21179 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21180 (>= (match-end 0) pos)
21181 (throw 'exit t)))
21182 nil)))
21184 (defun org-agenda-get-todos ()
21185 "Return the TODO information for agenda display."
21186 (let* ((props (list 'face nil
21187 'done-face 'org-done
21188 'org-not-done-regexp org-not-done-regexp
21189 'org-todo-regexp org-todo-regexp
21190 'mouse-face 'highlight
21191 'keymap org-agenda-keymap
21192 'help-echo
21193 (format "mouse-2 or RET jump to org file %s"
21194 (abbreviate-file-name buffer-file-name))))
21195 ;; FIXME: get rid of the \n at some point but watch out
21196 (regexp (concat "^\\*+[ \t]+\\("
21197 (if org-select-this-todo-keyword
21198 (if (equal org-select-this-todo-keyword "*")
21199 org-todo-regexp
21200 (concat "\\<\\("
21201 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
21202 "\\)\\>"))
21203 org-not-done-regexp)
21204 "[^\n\r]*\\)"))
21205 marker priority category tags
21206 ee txt beg end)
21207 (goto-char (point-min))
21208 (while (re-search-forward regexp nil t)
21209 (catch :skip
21210 (save-match-data
21211 (beginning-of-line)
21212 (setq beg (point) end (progn (outline-next-heading) (point)))
21213 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
21214 (re-search-forward org-ts-regexp end t))
21215 (and org-agenda-todo-ignore-scheduled (goto-char beg)
21216 (re-search-forward org-scheduled-time-regexp end t))
21217 (and org-agenda-todo-ignore-deadlines (goto-char beg)
21218 (re-search-forward org-deadline-time-regexp end t)
21219 (org-deadline-close (match-string 1))))
21220 (goto-char (1+ beg))
21221 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
21222 (throw :skip nil)))
21223 (goto-char beg)
21224 (org-agenda-skip)
21225 (goto-char (match-beginning 1))
21226 (setq marker (org-agenda-new-marker (match-beginning 0))
21227 category (org-get-category)
21228 tags (org-get-tags-at (point))
21229 txt (org-format-agenda-item "" (match-string 1) category tags)
21230 priority (1+ (org-get-priority txt)))
21231 (org-add-props txt props
21232 'org-marker marker 'org-hd-marker marker
21233 'priority priority 'org-category category
21234 'type "todo")
21235 (push txt ee)
21236 (if org-agenda-todo-list-sublevels
21237 (goto-char (match-end 1))
21238 (org-end-of-subtree 'invisible))))
21239 (nreverse ee)))
21241 (defconst org-agenda-no-heading-message
21242 "No heading for this item in buffer or region.")
21244 (defun org-agenda-get-timestamps ()
21245 "Return the date stamp information for agenda display."
21246 (let* ((props (list 'face nil
21247 'org-not-done-regexp org-not-done-regexp
21248 'org-todo-regexp org-todo-regexp
21249 'mouse-face 'highlight
21250 'keymap org-agenda-keymap
21251 'help-echo
21252 (format "mouse-2 or RET jump to org file %s"
21253 (abbreviate-file-name buffer-file-name))))
21254 (d1 (calendar-absolute-from-gregorian date))
21255 (remove-re
21256 (concat
21257 (regexp-quote
21258 (format-time-string
21259 "<%Y-%m-%d"
21260 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
21261 ".*?>"))
21262 (regexp
21263 (concat
21264 (regexp-quote
21265 (substring
21266 (format-time-string
21267 (car org-time-stamp-formats)
21268 (apply 'encode-time ; DATE bound by calendar
21269 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21270 0 11))
21271 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
21272 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
21273 marker hdmarker deadlinep scheduledp donep tmp priority category
21274 ee txt timestr tags b0 b3 e3 head)
21275 (goto-char (point-min))
21276 (while (re-search-forward regexp nil t)
21277 (setq b0 (match-beginning 0)
21278 b3 (match-beginning 3) e3 (match-end 3))
21279 (catch :skip
21280 (and (org-at-date-range-p) (throw :skip nil))
21281 (org-agenda-skip)
21282 (if (and (match-end 1)
21283 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
21284 (throw :skip nil))
21285 (if (and e3
21286 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
21287 (throw :skip nil))
21288 (setq marker (org-agenda-new-marker b0)
21289 category (org-get-category b0)
21290 tmp (buffer-substring (max (point-min)
21291 (- b0 org-ds-keyword-length))
21293 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
21294 deadlinep (string-match org-deadline-regexp tmp)
21295 scheduledp (string-match org-scheduled-regexp tmp)
21296 donep (org-entry-is-done-p))
21297 (if (or scheduledp deadlinep) (throw :skip t))
21298 (if (string-match ">" timestr)
21299 ;; substring should only run to end of time stamp
21300 (setq timestr (substring timestr 0 (match-end 0))))
21301 (save-excursion
21302 (if (re-search-backward "^\\*+ " nil t)
21303 (progn
21304 (goto-char (match-beginning 0))
21305 (setq hdmarker (org-agenda-new-marker)
21306 tags (org-get-tags-at))
21307 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21308 (setq head (match-string 1))
21309 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
21310 (setq txt (org-format-agenda-item
21311 nil head category tags timestr nil
21312 remove-re)))
21313 (setq txt org-agenda-no-heading-message))
21314 (setq priority (org-get-priority txt))
21315 (org-add-props txt props
21316 'org-marker marker 'org-hd-marker hdmarker)
21317 (org-add-props txt nil 'priority priority
21318 'org-category category 'date date
21319 'type "timestamp")
21320 (push txt ee))
21321 (outline-next-heading)))
21322 (nreverse ee)))
21324 (defun org-agenda-get-sexps ()
21325 "Return the sexp information for agenda display."
21326 (require 'diary-lib)
21327 (let* ((props (list 'face nil
21328 'mouse-face 'highlight
21329 'keymap org-agenda-keymap
21330 'help-echo
21331 (format "mouse-2 or RET jump to org file %s"
21332 (abbreviate-file-name buffer-file-name))))
21333 (regexp "^&?%%(")
21334 marker category ee txt tags entry result beg b sexp sexp-entry)
21335 (goto-char (point-min))
21336 (while (re-search-forward regexp nil t)
21337 (catch :skip
21338 (org-agenda-skip)
21339 (setq beg (match-beginning 0))
21340 (goto-char (1- (match-end 0)))
21341 (setq b (point))
21342 (forward-sexp 1)
21343 (setq sexp (buffer-substring b (point)))
21344 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
21345 (org-trim (match-string 1))
21346 ""))
21347 (setq result (org-diary-sexp-entry sexp sexp-entry date))
21348 (when result
21349 (setq marker (org-agenda-new-marker beg)
21350 category (org-get-category beg))
21352 (if (string-match "\\S-" result)
21353 (setq txt result)
21354 (setq txt "SEXP entry returned empty string"))
21356 (setq txt (org-format-agenda-item
21357 "" txt category tags 'time))
21358 (org-add-props txt props 'org-marker marker)
21359 (org-add-props txt nil
21360 'org-category category 'date date
21361 'type "sexp")
21362 (push txt ee))))
21363 (nreverse ee)))
21365 (defun org-agenda-get-closed ()
21366 "Return the logged TODO entries for agenda display."
21367 (let* ((props (list 'mouse-face 'highlight
21368 'org-not-done-regexp org-not-done-regexp
21369 'org-todo-regexp org-todo-regexp
21370 'keymap org-agenda-keymap
21371 'help-echo
21372 (format "mouse-2 or RET jump to org file %s"
21373 (abbreviate-file-name buffer-file-name))))
21374 (regexp (concat
21375 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
21376 (regexp-quote
21377 (substring
21378 (format-time-string
21379 (car org-time-stamp-formats)
21380 (apply 'encode-time ; DATE bound by calendar
21381 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21382 1 11))))
21383 marker hdmarker priority category tags closedp
21384 ee txt timestr)
21385 (goto-char (point-min))
21386 (while (re-search-forward regexp nil t)
21387 (catch :skip
21388 (org-agenda-skip)
21389 (setq marker (org-agenda-new-marker (match-beginning 0))
21390 closedp (equal (match-string 1) org-closed-string)
21391 category (org-get-category (match-beginning 0))
21392 timestr (buffer-substring (match-beginning 0) (point-at-eol))
21393 ;; donep (org-entry-is-done-p)
21395 (if (string-match "\\]" timestr)
21396 ;; substring should only run to end of time stamp
21397 (setq timestr (substring timestr 0 (match-end 0))))
21398 (save-excursion
21399 (if (re-search-backward "^\\*+ " nil t)
21400 (progn
21401 (goto-char (match-beginning 0))
21402 (setq hdmarker (org-agenda-new-marker)
21403 tags (org-get-tags-at))
21404 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21405 (setq txt (org-format-agenda-item
21406 (if closedp "Closed: " "Clocked: ")
21407 (match-string 1) category tags timestr)))
21408 (setq txt org-agenda-no-heading-message))
21409 (setq priority 100000)
21410 (org-add-props txt props
21411 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
21412 'priority priority 'org-category category
21413 'type "closed" 'date date
21414 'undone-face 'org-warning 'done-face 'org-done)
21415 (push txt ee))
21416 (goto-char (point-at-eol))))
21417 (nreverse ee)))
21419 (defun org-agenda-get-deadlines ()
21420 "Return the deadline information for agenda display."
21421 (let* ((props (list 'mouse-face 'highlight
21422 'org-not-done-regexp org-not-done-regexp
21423 'org-todo-regexp org-todo-regexp
21424 'keymap org-agenda-keymap
21425 'help-echo
21426 (format "mouse-2 or RET jump to org file %s"
21427 (abbreviate-file-name buffer-file-name))))
21428 (regexp org-deadline-time-regexp)
21429 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21430 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21431 d2 diff dfrac wdays pos pos1 category tags
21432 ee txt head face s upcomingp donep timestr)
21433 (goto-char (point-min))
21434 (while (re-search-forward regexp nil t)
21435 (catch :skip
21436 (org-agenda-skip)
21437 (setq s (match-string 1)
21438 pos (1- (match-beginning 1))
21439 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21440 diff (- d2 d1)
21441 wdays (org-get-wdays s)
21442 dfrac (/ (* 1.0 (- wdays diff)) (max wdays 1))
21443 upcomingp (and todayp (> diff 0)))
21444 ;; When to show a deadline in the calendar:
21445 ;; If the expiration is within wdays warning time.
21446 ;; Past-due deadlines are only shown on the current date
21447 (if (or (and (<= diff wdays)
21448 (and todayp (not org-agenda-only-exact-dates)))
21449 (= diff 0))
21450 (save-excursion
21451 (setq category (org-get-category))
21452 (if (re-search-backward "^\\*+[ \t]+" nil t)
21453 (progn
21454 (goto-char (match-end 0))
21455 (setq pos1 (match-beginning 0))
21456 (setq tags (org-get-tags-at pos1))
21457 (setq head (buffer-substring-no-properties
21458 (point)
21459 (progn (skip-chars-forward "^\r\n")
21460 (point))))
21461 (setq donep (string-match org-looking-at-done-regexp head))
21462 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21463 (setq timestr
21464 (concat (substring s (match-beginning 1)) " "))
21465 (setq timestr 'time))
21466 (if (and donep
21467 (or org-agenda-skip-deadline-if-done
21468 (not (= diff 0))))
21469 (setq txt nil)
21470 (setq txt (org-format-agenda-item
21471 (if (= diff 0)
21472 (car org-agenda-deadline-leaders)
21473 (format (nth 1 org-agenda-deadline-leaders)
21474 diff))
21475 head category tags timestr))))
21476 (setq txt org-agenda-no-heading-message))
21477 (when txt
21478 (setq face (org-agenda-deadline-face dfrac))
21479 (org-add-props txt props
21480 'org-marker (org-agenda-new-marker pos)
21481 'org-hd-marker (org-agenda-new-marker pos1)
21482 'priority (+ (- diff)
21483 (org-get-priority txt))
21484 'org-category category
21485 'type (if upcomingp "upcoming-deadline" "deadline")
21486 'date (if upcomingp date d2)
21487 'face (if donep 'org-done face)
21488 'undone-face face 'done-face 'org-done)
21489 (push txt ee))))))
21490 (nreverse ee)))
21492 (defun org-agenda-deadline-face (fraction)
21493 "Return the face to displaying a deadline item.
21494 FRACTION is what fraction of the head-warning time has passed."
21495 (let ((faces org-agenda-deadline-faces) f)
21496 (catch 'exit
21497 (while (setq f (pop faces))
21498 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
21500 (defun org-agenda-get-scheduled ()
21501 "Return the scheduled information for agenda display."
21502 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
21503 'org-todo-regexp org-todo-regexp
21504 'done-face 'org-done
21505 'mouse-face 'highlight
21506 'keymap org-agenda-keymap
21507 'help-echo
21508 (format "mouse-2 or RET jump to org file %s"
21509 (abbreviate-file-name buffer-file-name))))
21510 (regexp org-scheduled-time-regexp)
21511 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21512 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21513 d2 diff pos pos1 category tags
21514 ee txt head pastschedp donep face timestr s)
21515 (goto-char (point-min))
21516 (while (re-search-forward regexp nil t)
21517 (catch :skip
21518 (org-agenda-skip)
21519 (setq s (match-string 1)
21520 pos (1- (match-beginning 1))
21521 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21522 ;;; is this right?
21523 ;;; do we need to do this for deadleine too????
21524 ;;; d2 (org-time-string-to-absolute (match-string 1) (if todayp nil d1))
21525 diff (- d2 d1))
21526 (setq pastschedp (and todayp (< diff 0)))
21527 ;; When to show a scheduled item in the calendar:
21528 ;; If it is on or past the date.
21529 (if (or (and (< diff 0)
21530 (and todayp (not org-agenda-only-exact-dates)))
21531 (= diff 0))
21532 (save-excursion
21533 (setq category (org-get-category))
21534 (if (re-search-backward "^\\*+[ \t]+" nil t)
21535 (progn
21536 (goto-char (match-end 0))
21537 (setq pos1 (match-beginning 0))
21538 (setq tags (org-get-tags-at))
21539 (setq head (buffer-substring-no-properties
21540 (point)
21541 (progn (skip-chars-forward "^\r\n") (point))))
21542 (setq donep (string-match org-looking-at-done-regexp head))
21543 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21544 (setq timestr
21545 (concat (substring s (match-beginning 1)) " "))
21546 (setq timestr 'time))
21547 (if (and donep
21548 (or org-agenda-skip-scheduled-if-done
21549 (not (= diff 0))))
21550 (setq txt nil)
21551 (setq txt (org-format-agenda-item
21552 (if (= diff 0)
21553 (car org-agenda-scheduled-leaders)
21554 (format (nth 1 org-agenda-scheduled-leaders)
21555 (- 1 diff)))
21556 head category tags timestr))))
21557 (setq txt org-agenda-no-heading-message))
21558 (when txt
21559 (setq face (if pastschedp
21560 'org-scheduled-previously
21561 'org-scheduled-today))
21562 (org-add-props txt props
21563 'undone-face face
21564 'face (if donep 'org-done face)
21565 'org-marker (org-agenda-new-marker pos)
21566 'org-hd-marker (org-agenda-new-marker pos1)
21567 'type (if pastschedp "past-scheduled" "scheduled")
21568 'date (if pastschedp d2 date)
21569 'priority (+ 94 (- 5 diff) (org-get-priority txt))
21570 'org-category category)
21571 (push txt ee))))))
21572 (nreverse ee)))
21574 (defun org-agenda-get-blocks ()
21575 "Return the date-range information for agenda display."
21576 (let* ((props (list 'face nil
21577 'org-not-done-regexp org-not-done-regexp
21578 'org-todo-regexp org-todo-regexp
21579 'mouse-face 'highlight
21580 'keymap org-agenda-keymap
21581 'help-echo
21582 (format "mouse-2 or RET jump to org file %s"
21583 (abbreviate-file-name buffer-file-name))))
21584 (regexp org-tr-regexp)
21585 (d0 (calendar-absolute-from-gregorian date))
21586 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
21587 donep head)
21588 (goto-char (point-min))
21589 (while (re-search-forward regexp nil t)
21590 (catch :skip
21591 (org-agenda-skip)
21592 (setq pos (point))
21593 (setq timestr (match-string 0)
21594 s1 (match-string 1)
21595 s2 (match-string 2)
21596 d1 (time-to-days (org-time-string-to-time s1))
21597 d2 (time-to-days (org-time-string-to-time s2)))
21598 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
21599 ;; Only allow days between the limits, because the normal
21600 ;; date stamps will catch the limits.
21601 (save-excursion
21602 (setq marker (org-agenda-new-marker (point)))
21603 (setq category (org-get-category))
21604 (if (re-search-backward "^\\*+ " nil t)
21605 (progn
21606 (goto-char (match-beginning 0))
21607 (setq hdmarker (org-agenda-new-marker (point)))
21608 (setq tags (org-get-tags-at))
21609 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21610 (setq head (match-string 1))
21611 (and org-agenda-skip-timestamp-if-done
21612 (org-entry-is-done-p)
21613 (throw :skip t))
21614 (setq txt (org-format-agenda-item
21615 (format (if (= d1 d2) "" "(%d/%d): ")
21616 (1+ (- d0 d1)) (1+ (- d2 d1)))
21617 head category tags
21618 (if (= d0 d1) timestr))))
21619 (setq txt org-agenda-no-heading-message))
21620 (org-add-props txt props
21621 'org-marker marker 'org-hd-marker hdmarker
21622 'type "block" 'date date
21623 'priority (org-get-priority txt) 'org-category category)
21624 (push txt ee)))
21625 (goto-char pos)))
21626 ;; Sort the entries by expiration date.
21627 (nreverse ee)))
21629 ;;; Agenda presentation and sorting
21631 (defconst org-plain-time-of-day-regexp
21632 (concat
21633 "\\(\\<[012]?[0-9]"
21634 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21635 "\\(--?"
21636 "\\(\\<[012]?[0-9]"
21637 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21638 "\\)?")
21639 "Regular expression to match a plain time or time range.
21640 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
21641 groups carry important information:
21642 0 the full match
21643 1 the first time, range or not
21644 8 the second time, if it is a range.")
21646 (defconst org-plain-time-extension-regexp
21647 (concat
21648 "\\(\\<[012]?[0-9]"
21649 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21650 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
21651 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
21652 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
21653 groups carry important information:
21654 0 the full match
21655 7 hours of duration
21656 9 minutes of duration")
21658 (defconst org-stamp-time-of-day-regexp
21659 (concat
21660 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
21661 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
21662 "\\(--?"
21663 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
21664 "Regular expression to match a timestamp time or time range.
21665 After a match, the following groups carry important information:
21666 0 the full match
21667 1 date plus weekday, for backreferencing to make sure both times on same day
21668 2 the first time, range or not
21669 4 the second time, if it is a range.")
21671 (defvar org-prefix-has-time nil
21672 "A flag, set by `org-compile-prefix-format'.
21673 The flag is set if the currently compiled format contains a `%t'.")
21674 (defvar org-prefix-has-tag nil
21675 "A flag, set by `org-compile-prefix-format'.
21676 The flag is set if the currently compiled format contains a `%T'.")
21678 (defun org-format-agenda-item (extra txt &optional category tags dotime
21679 noprefix remove-re)
21680 "Format TXT to be inserted into the agenda buffer.
21681 In particular, it adds the prefix and corresponding text properties. EXTRA
21682 must be a string and replaces the `%s' specifier in the prefix format.
21683 CATEGORY (string, symbol or nil) may be used to overrule the default
21684 category taken from local variable or file name. It will replace the `%c'
21685 specifier in the format. DOTIME, when non-nil, indicates that a
21686 time-of-day should be extracted from TXT for sorting of this entry, and for
21687 the `%t' specifier in the format. When DOTIME is a string, this string is
21688 searched for a time before TXT is. NOPREFIX is a flag and indicates that
21689 only the correctly processes TXT should be returned - this is used by
21690 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
21691 Any match of REMOVE-RE will be removed from TXT."
21692 (save-match-data
21693 ;; Diary entries sometimes have extra whitespace at the beginning
21694 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
21695 (let* ((category (or category
21696 org-category
21697 (if buffer-file-name
21698 (file-name-sans-extension
21699 (file-name-nondirectory buffer-file-name))
21700 "")))
21701 (tag (if tags (nth (1- (length tags)) tags) ""))
21702 time ; time and tag are needed for the eval of the prefix format
21703 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
21704 (time-of-day (and dotime (org-get-time-of-day ts)))
21705 stamp plain s0 s1 s2 rtn srp)
21706 (when (and dotime time-of-day org-prefix-has-time)
21707 ;; Extract starting and ending time and move them to prefix
21708 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
21709 (setq plain (string-match org-plain-time-of-day-regexp ts)))
21710 (setq s0 (match-string 0 ts)
21711 srp (and stamp (match-end 3))
21712 s1 (match-string (if plain 1 2) ts)
21713 s2 (match-string (if plain 8 (if srp 4 6)) ts))
21715 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
21716 ;; them, we might want to remove them there to avoid duplication.
21717 ;; The user can turn this off with a variable.
21718 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
21719 (string-match (concat (regexp-quote s0) " *") txt)
21720 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
21721 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
21722 (= (match-beginning 0) 0)
21724 (setq txt (replace-match "" nil nil txt))))
21725 ;; Normalize the time(s) to 24 hour
21726 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
21727 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
21729 (when (and s1 (not s2) org-agenda-default-appointment-duration
21730 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
21731 (let ((m (+ (string-to-number (match-string 2 s1))
21732 (* 60 (string-to-number (match-string 1 s1)))
21733 org-agenda-default-appointment-duration))
21735 (setq h (/ m 60) m (- m (* h 60)))
21736 (setq s2 (format "%02d:%02d" h m))))
21738 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
21739 txt)
21740 ;; Tags are in the string
21741 (if (or (eq org-agenda-remove-tags t)
21742 (and org-agenda-remove-tags
21743 org-prefix-has-tag))
21744 (setq txt (replace-match "" t t txt))
21745 (setq txt (replace-match
21746 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
21747 (match-string 2 txt))
21748 t t txt))))
21750 (when remove-re
21751 (while (string-match remove-re txt)
21752 (setq txt (replace-match "" t t txt))))
21754 ;; Create the final string
21755 (if noprefix
21756 (setq rtn txt)
21757 ;; Prepare the variables needed in the eval of the compiled format
21758 (setq time (cond (s2 (concat s1 "-" s2))
21759 (s1 (concat s1 "......"))
21760 (t ""))
21761 extra (or extra "")
21762 category (if (symbolp category) (symbol-name category) category))
21763 ;; Evaluate the compiled format
21764 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
21766 ;; And finally add the text properties
21767 (org-add-props rtn nil
21768 'org-category (downcase category) 'tags tags
21769 'org-highest-priority org-highest-priority
21770 'org-lowest-priority org-lowest-priority
21771 'prefix-length (- (length rtn) (length txt))
21772 'time-of-day time-of-day
21773 'txt txt
21774 'time time
21775 'extra extra
21776 'dotime dotime))))
21778 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
21779 (defvar org-agenda-sorting-strategy-selected nil)
21781 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
21782 (catch 'exit
21783 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
21784 ((and todayp (member 'today (car org-agenda-time-grid))))
21785 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
21786 ((member 'weekly (car org-agenda-time-grid)))
21787 (t (throw 'exit list)))
21788 (let* ((have (delq nil (mapcar
21789 (lambda (x) (get-text-property 1 'time-of-day x))
21790 list)))
21791 (string (nth 1 org-agenda-time-grid))
21792 (gridtimes (nth 2 org-agenda-time-grid))
21793 (req (car org-agenda-time-grid))
21794 (remove (member 'remove-match req))
21795 new time)
21796 (if (and (member 'require-timed req) (not have))
21797 ;; don't show empty grid
21798 (throw 'exit list))
21799 (while (setq time (pop gridtimes))
21800 (unless (and remove (member time have))
21801 (setq time (int-to-string time))
21802 (push (org-format-agenda-item
21803 nil string "" nil
21804 (concat (substring time 0 -2) ":" (substring time -2)))
21805 new)
21806 (put-text-property
21807 1 (length (car new)) 'face 'org-time-grid (car new))))
21808 (if (member 'time-up org-agenda-sorting-strategy-selected)
21809 (append new list)
21810 (append list new)))))
21812 (defun org-compile-prefix-format (key)
21813 "Compile the prefix format into a Lisp form that can be evaluated.
21814 The resulting form is returned and stored in the variable
21815 `org-prefix-format-compiled'."
21816 (setq org-prefix-has-time nil org-prefix-has-tag nil)
21817 (let ((s (cond
21818 ((stringp org-agenda-prefix-format)
21819 org-agenda-prefix-format)
21820 ((assq key org-agenda-prefix-format)
21821 (cdr (assq key org-agenda-prefix-format)))
21822 (t " %-12:c%?-12t% s")))
21823 (start 0)
21824 varform vars var e c f opt)
21825 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
21826 s start)
21827 (setq var (cdr (assoc (match-string 4 s)
21828 '(("c" . category) ("t" . time) ("s" . extra)
21829 ("T" . tag))))
21830 c (or (match-string 3 s) "")
21831 opt (match-beginning 1)
21832 start (1+ (match-beginning 0)))
21833 (if (equal var 'time) (setq org-prefix-has-time t))
21834 (if (equal var 'tag) (setq org-prefix-has-tag t))
21835 (setq f (concat "%" (match-string 2 s) "s"))
21836 (if opt
21837 (setq varform
21838 `(if (equal "" ,var)
21840 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
21841 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
21842 (setq s (replace-match "%s" t nil s))
21843 (push varform vars))
21844 (setq vars (nreverse vars))
21845 (setq org-prefix-format-compiled `(format ,s ,@vars))))
21847 (defun org-set-sorting-strategy (key)
21848 (if (symbolp (car org-agenda-sorting-strategy))
21849 ;; the old format
21850 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
21851 (setq org-agenda-sorting-strategy-selected
21852 (or (cdr (assq key org-agenda-sorting-strategy))
21853 (cdr (assq 'agenda org-agenda-sorting-strategy))
21854 '(time-up category-keep priority-down)))))
21856 (defun org-get-time-of-day (s &optional string mod24)
21857 "Check string S for a time of day.
21858 If found, return it as a military time number between 0 and 2400.
21859 If not found, return nil.
21860 The optional STRING argument forces conversion into a 5 character wide string
21861 HH:MM."
21862 (save-match-data
21863 (when
21864 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
21865 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
21866 (let* ((h (string-to-number (match-string 1 s)))
21867 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
21868 (ampm (if (match-end 4) (downcase (match-string 4 s))))
21869 (am-p (equal ampm "am"))
21870 (h1 (cond ((not ampm) h)
21871 ((= h 12) (if am-p 0 12))
21872 (t (+ h (if am-p 0 12)))))
21873 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
21874 (mod h1 24) h1))
21875 (t0 (+ (* 100 h2) m))
21876 (t1 (concat (if (>= h1 24) "+" " ")
21877 (if (< t0 100) "0" "")
21878 (if (< t0 10) "0" "")
21879 (int-to-string t0))))
21880 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
21882 (defun org-finalize-agenda-entries (list &optional nosort)
21883 "Sort and concatenate the agenda items."
21884 (setq list (mapcar 'org-agenda-highlight-todo list))
21885 (if nosort
21886 list
21887 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
21889 (defun org-agenda-highlight-todo (x)
21890 (let (re pl)
21891 (if (eq x 'line)
21892 (save-excursion
21893 (beginning-of-line 1)
21894 (setq re (get-text-property (point) 'org-todo-regexp))
21895 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
21896 (when (looking-at (concat "[ \t]*\\.*" re " +"))
21897 (add-text-properties (match-beginning 0) (match-end 0)
21898 (list 'face (org-get-todo-face 0)))
21899 (let ((s (buffer-substring (match-beginning 1) (match-end 1))))
21900 (delete-region (match-beginning 1) (1- (match-end 0)))
21901 (goto-char (match-beginning 1))
21902 (insert (format org-agenda-todo-keyword-format s)))))
21903 (setq re (concat (get-text-property 0 'org-todo-regexp x))
21904 pl (get-text-property 0 'prefix-length x))
21905 ; (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
21906 ; (add-text-properties
21907 ; (or (match-end 1) (match-end 0)) (match-end 0)
21908 ; (list 'face (org-get-todo-face (match-string 2 x)))
21909 ; x))
21910 (when (and re
21911 (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)")
21912 x (or pl 0)) pl))
21913 (add-text-properties
21914 (or (match-end 1) (match-end 0)) (match-end 0)
21915 (list 'face (org-get-todo-face (match-string 2 x)))
21917 (setq x (concat (substring x 0 (match-end 1))
21918 (format org-agenda-todo-keyword-format
21919 (match-string 2 x))
21921 (substring x (match-end 3)))))
21922 x)))
21924 (defsubst org-cmp-priority (a b)
21925 "Compare the priorities of string A and B."
21926 (let ((pa (or (get-text-property 1 'priority a) 0))
21927 (pb (or (get-text-property 1 'priority b) 0)))
21928 (cond ((> pa pb) +1)
21929 ((< pa pb) -1)
21930 (t nil))))
21932 (defsubst org-cmp-category (a b)
21933 "Compare the string values of categories of strings A and B."
21934 (let ((ca (or (get-text-property 1 'org-category a) ""))
21935 (cb (or (get-text-property 1 'org-category b) "")))
21936 (cond ((string-lessp ca cb) -1)
21937 ((string-lessp cb ca) +1)
21938 (t nil))))
21940 (defsubst org-cmp-tag (a b)
21941 "Compare the string values of categories of strings A and B."
21942 (let ((ta (car (last (get-text-property 1 'tags a))))
21943 (tb (car (last (get-text-property 1 'tags b)))))
21944 (cond ((not ta) +1)
21945 ((not tb) -1)
21946 ((string-lessp ta tb) -1)
21947 ((string-lessp tb ta) +1)
21948 (t nil))))
21950 (defsubst org-cmp-time (a b)
21951 "Compare the time-of-day values of strings A and B."
21952 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
21953 (ta (or (get-text-property 1 'time-of-day a) def))
21954 (tb (or (get-text-property 1 'time-of-day b) def)))
21955 (cond ((< ta tb) -1)
21956 ((< tb ta) +1)
21957 (t nil))))
21959 (defun org-entries-lessp (a b)
21960 "Predicate for sorting agenda entries."
21961 ;; The following variables will be used when the form is evaluated.
21962 ;; So even though the compiler complains, keep them.
21963 (let* ((time-up (org-cmp-time a b))
21964 (time-down (if time-up (- time-up) nil))
21965 (priority-up (org-cmp-priority a b))
21966 (priority-down (if priority-up (- priority-up) nil))
21967 (category-up (org-cmp-category a b))
21968 (category-down (if category-up (- category-up) nil))
21969 (category-keep (if category-up +1 nil))
21970 (tag-up (org-cmp-tag a b))
21971 (tag-down (if tag-up (- tag-up) nil)))
21972 (cdr (assoc
21973 (eval (cons 'or org-agenda-sorting-strategy-selected))
21974 '((-1 . t) (1 . nil) (nil . nil))))))
21976 ;;; Agenda restriction lock
21978 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
21979 "Overlay to mark the headline to which arenda commands are restricted.")
21980 (org-overlay-put org-agenda-restriction-lock-overlay
21981 'face 'org-agenda-restriction-lock)
21982 (org-overlay-put org-agenda-restriction-lock-overlay
21983 'help-echo "Agendas are currently limited to this subtree.")
21984 (org-detach-overlay org-agenda-restriction-lock-overlay)
21985 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
21986 "Overlay marking the agenda restriction line in speedbar.")
21987 (org-overlay-put org-speedbar-restriction-lock-overlay
21988 'face 'org-agenda-restriction-lock)
21989 (org-overlay-put org-speedbar-restriction-lock-overlay
21990 'help-echo "Agendas are currently limited to this item.")
21991 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21993 (defun org-agenda-set-restriction-lock (&optional type)
21994 "Set restriction lock for agenda, to current subtree or file.
21995 Restriction will be the file if TYPE is `file', or if type is the
21996 universal prefix '(4), or if the cursor is before the first headline
21997 in the file. Otherwise, restriction will be to the current subtree."
21998 (interactive "P")
21999 (and (equal type '(4)) (setq type 'file))
22000 (setq type (cond
22001 (type type)
22002 ((org-at-heading-p) 'subtree)
22003 ((condition-case nil (org-back-to-heading t) (error nil))
22004 'subtree)
22005 (t 'file)))
22006 (if (eq type 'subtree)
22007 (progn
22008 (setq org-agenda-restrict t)
22009 (setq org-agenda-overriding-restriction 'subtree)
22010 (put 'org-agenda-files 'org-restrict
22011 (list (buffer-file-name (buffer-base-buffer))))
22012 (org-back-to-heading t)
22013 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
22014 (move-marker org-agenda-restrict-begin (point))
22015 (move-marker org-agenda-restrict-end
22016 (save-excursion (org-end-of-subtree t)))
22017 (message "Locking agenda restriction to subtree"))
22018 (put 'org-agenda-files 'org-restrict
22019 (list (buffer-file-name (buffer-base-buffer))))
22020 (setq org-agenda-restrict nil)
22021 (setq org-agenda-overriding-restriction 'file)
22022 (move-marker org-agenda-restrict-begin nil)
22023 (move-marker org-agenda-restrict-end nil)
22024 (message "Locking agenda restriction to file"))
22025 (setq current-prefix-arg nil)
22026 (org-agenda-maybe-redo))
22028 (defun org-agenda-remove-restriction-lock (&optional noupdate)
22029 "Remove the agenda restriction lock."
22030 (interactive "P")
22031 (org-detach-overlay org-agenda-restriction-lock-overlay)
22032 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22033 (setq org-agenda-overriding-restriction nil)
22034 (setq org-agenda-restrict nil)
22035 (put 'org-agenda-files 'org-restrict nil)
22036 (move-marker org-agenda-restrict-begin nil)
22037 (move-marker org-agenda-restrict-end nil)
22038 (setq current-prefix-arg nil)
22039 (message "Agenda restriction lock removed")
22040 (or noupdate (org-agenda-maybe-redo)))
22042 (defun org-agenda-maybe-redo ()
22043 "If there is any window showing the agenda view, update it."
22044 (let ((w (get-buffer-window org-agenda-buffer-name t))
22045 (w0 (selected-window)))
22046 (when w
22047 (select-window w)
22048 (org-agenda-redo)
22049 (select-window w0)
22050 (if org-agenda-overriding-restriction
22051 (message "Agenda view shifted to new %s restriction"
22052 org-agenda-overriding-restriction)
22053 (message "Agenda restriction lock removed")))))
22055 ;;; Agenda commands
22057 (defun org-agenda-check-type (error &rest types)
22058 "Check if agenda buffer is of allowed type.
22059 If ERROR is non-nil, throw an error, otherwise just return nil."
22060 (if (memq org-agenda-type types)
22062 (if error
22063 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
22064 nil)))
22066 (defun org-agenda-quit ()
22067 "Exit agenda by removing the window or the buffer."
22068 (interactive)
22069 (let ((buf (current-buffer)))
22070 (if (not (one-window-p)) (delete-window))
22071 (kill-buffer buf)
22072 (org-agenda-maybe-reset-markers 'force)
22073 (org-columns-remove-overlays))
22074 ;; Maybe restore the pre-agenda window configuration.
22075 (and org-agenda-restore-windows-after-quit
22076 (not (eq org-agenda-window-setup 'other-frame))
22077 org-pre-agenda-window-conf
22078 (set-window-configuration org-pre-agenda-window-conf)))
22080 (defun org-agenda-exit ()
22081 "Exit agenda by removing the window or the buffer.
22082 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
22083 Org-mode buffers visited directly by the user will not be touched."
22084 (interactive)
22085 (org-release-buffers org-agenda-new-buffers)
22086 (setq org-agenda-new-buffers nil)
22087 (org-agenda-quit))
22089 (defun org-agenda-execute (arg)
22090 "Execute another agenda command, keeping same window.\\<global-map>
22091 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
22092 (interactive "P")
22093 (let ((org-agenda-window-setup 'current-window))
22094 (org-agenda arg)))
22096 (defun org-save-all-org-buffers ()
22097 "Save all Org-mode buffers without user confirmation."
22098 (interactive)
22099 (message "Saving all Org-mode buffers...")
22100 (save-some-buffers t 'org-mode-p)
22101 (message "Saving all Org-mode buffers... done"))
22103 (defun org-agenda-redo ()
22104 "Rebuild Agenda.
22105 When this is the global TODO list, a prefix argument will be interpreted."
22106 (interactive)
22107 (let* ((org-agenda-keep-modes t)
22108 (line (org-current-line))
22109 (window-line (- line (org-current-line (window-start))))
22110 (lprops (get 'org-agenda-redo-command 'org-lprops)))
22111 (message "Rebuilding agenda buffer...")
22112 (org-let lprops '(eval org-agenda-redo-command))
22113 (setq org-agenda-undo-list nil
22114 org-agenda-pending-undo-list nil)
22115 (message "Rebuilding agenda buffer...done")
22116 (goto-line line)
22117 (recenter window-line)))
22119 (defun org-agenda-goto-date (date)
22120 "Jump to DATE in agenda."
22121 (interactive (list (org-read-date)))
22122 (org-agenda-list nil date))
22124 (defun org-agenda-goto-today ()
22125 "Go to today."
22126 (interactive)
22127 (org-agenda-check-type t 'timeline 'agenda)
22128 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
22129 (cond
22130 (tdpos (goto-char tdpos))
22131 ((eq org-agenda-type 'agenda)
22132 (let* ((sd (time-to-days
22133 (time-subtract (current-time)
22134 (list 0 (* 3600 org-extend-today-until) 0))))
22135 (comp (org-agenda-compute-time-span sd org-agenda-span))
22136 (org-agenda-overriding-arguments org-agenda-last-arguments))
22137 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
22138 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
22139 (org-agenda-redo)
22140 (org-agenda-find-same-or-today-or-agenda)))
22141 (t (error "Cannot find today")))))
22143 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
22144 (goto-char
22145 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
22146 (text-property-any (point-min) (point-max) 'org-today t)
22147 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
22148 (point-min))))
22150 (defun org-agenda-later (arg)
22151 "Go forward in time by thee current span.
22152 With prefix ARG, go forward that many times the current span."
22153 (interactive "p")
22154 (org-agenda-check-type t 'agenda)
22155 (let* ((span org-agenda-span)
22156 (sd org-starting-day)
22157 (greg (calendar-gregorian-from-absolute sd))
22158 (cnt (get-text-property (point) 'org-day-cnt))
22159 greg2 nd)
22160 (cond
22161 ((eq span 'day)
22162 (setq sd (+ arg sd) nd 1))
22163 ((eq span 'week)
22164 (setq sd (+ (* 7 arg) sd) nd 7))
22165 ((eq span 'month)
22166 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
22167 sd (calendar-absolute-from-gregorian greg2))
22168 (setcar greg2 (1+ (car greg2)))
22169 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
22170 ((eq span 'year)
22171 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
22172 sd (calendar-absolute-from-gregorian greg2))
22173 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
22174 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
22175 (let ((org-agenda-overriding-arguments
22176 (list (car org-agenda-last-arguments) sd nd t)))
22177 (org-agenda-redo)
22178 (org-agenda-find-same-or-today-or-agenda cnt))))
22180 (defun org-agenda-earlier (arg)
22181 "Go backward in time by the current span.
22182 With prefix ARG, go backward that many times the current span."
22183 (interactive "p")
22184 (org-agenda-later (- arg)))
22186 (defun org-agenda-day-view ()
22187 "Switch to daily view for agenda."
22188 (interactive)
22189 (setq org-agenda-ndays 1)
22190 (org-agenda-change-time-span 'day))
22191 (defun org-agenda-week-view ()
22192 "Switch to daily view for agenda."
22193 (interactive)
22194 (setq org-agenda-ndays 7)
22195 (org-agenda-change-time-span 'week))
22196 (defun org-agenda-month-view ()
22197 "Switch to daily view for agenda."
22198 (interactive)
22199 (org-agenda-change-time-span 'month))
22200 (defun org-agenda-year-view ()
22201 "Switch to daily view for agenda."
22202 (interactive)
22203 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
22204 (org-agenda-change-time-span 'year)
22205 (error "Abort")))
22207 (defun org-agenda-change-time-span (span)
22208 "Change the agenda view to SPAN.
22209 SPAN may be `day', `week', `month', `year'."
22210 (org-agenda-check-type t 'agenda)
22211 (if (equal org-agenda-span span)
22212 (error "Viewing span is already \"%s\"" span))
22213 (let* ((sd (or (get-text-property (point) 'day)
22214 org-starting-day))
22215 (computed (org-agenda-compute-time-span sd span))
22216 (org-agenda-overriding-arguments
22217 (list (car org-agenda-last-arguments)
22218 (car computed) (cdr computed) t)))
22219 (org-agenda-redo)
22220 (org-agenda-find-same-or-today-or-agenda))
22221 (org-agenda-set-mode-name)
22222 (message "Switched to %s view" span))
22224 (defun org-agenda-compute-time-span (sd span)
22225 "Compute starting date and number of days for agenda.
22226 SPAN may be `day', `week', `month', `year'. The return value
22227 is a cons cell with the starting date and the number of days,
22228 so that the date SD will be in that range."
22229 (let* ((greg (calendar-gregorian-from-absolute sd))
22231 (cond
22232 ((eq span 'day)
22233 (setq nd 1))
22234 ((eq span 'week)
22235 (let* ((nt (calendar-day-of-week
22236 (calendar-gregorian-from-absolute sd)))
22237 (d (if org-agenda-start-on-weekday
22238 (- nt org-agenda-start-on-weekday)
22239 0)))
22240 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
22241 (setq nd 7)))
22242 ((eq span 'month)
22243 (setq sd (calendar-absolute-from-gregorian
22244 (list (car greg) 1 (nth 2 greg)))
22245 nd (- (calendar-absolute-from-gregorian
22246 (list (1+ (car greg)) 1 (nth 2 greg)))
22247 sd)))
22248 ((eq span 'year)
22249 (setq sd (calendar-absolute-from-gregorian
22250 (list 1 1 (nth 2 greg)))
22251 nd (- (calendar-absolute-from-gregorian
22252 (list 1 1 (1+ (nth 2 greg))))
22253 sd))))
22254 (cons sd nd)))
22256 ;; FIXME: does not work if user makes date format that starts with a blank
22257 (defun org-agenda-next-date-line (&optional arg)
22258 "Jump to the next line indicating a date in agenda buffer."
22259 (interactive "p")
22260 (org-agenda-check-type t 'agenda 'timeline)
22261 (beginning-of-line 1)
22262 (if (looking-at "^\\S-") (forward-char 1))
22263 (if (not (re-search-forward "^\\S-" nil t arg))
22264 (progn
22265 (backward-char 1)
22266 (error "No next date after this line in this buffer")))
22267 (goto-char (match-beginning 0)))
22269 (defun org-agenda-previous-date-line (&optional arg)
22270 "Jump to the previous line indicating a date in agenda buffer."
22271 (interactive "p")
22272 (org-agenda-check-type t 'agenda 'timeline)
22273 (beginning-of-line 1)
22274 (if (not (re-search-backward "^\\S-" nil t arg))
22275 (error "No previous date before this line in this buffer")))
22277 ;; Initialize the highlight
22278 (defvar org-hl (org-make-overlay 1 1))
22279 (org-overlay-put org-hl 'face 'highlight)
22281 (defun org-highlight (begin end &optional buffer)
22282 "Highlight a region with overlay."
22283 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
22284 org-hl begin end (or buffer (current-buffer))))
22286 (defun org-unhighlight ()
22287 "Detach overlay INDEX."
22288 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
22290 ;; FIXME this is currently not used.
22291 (defun org-highlight-until-next-command (beg end &optional buffer)
22292 (org-highlight beg end buffer)
22293 (add-hook 'pre-command-hook 'org-unhighlight-once))
22294 (defun org-unhighlight-once ()
22295 (remove-hook 'pre-command-hook 'org-unhighlight-once)
22296 (org-unhighlight))
22298 (defun org-agenda-follow-mode ()
22299 "Toggle follow mode in an agenda buffer."
22300 (interactive)
22301 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
22302 (org-agenda-set-mode-name)
22303 (message "Follow mode is %s"
22304 (if org-agenda-follow-mode "on" "off")))
22306 (defun org-agenda-log-mode ()
22307 "Toggle log mode in an agenda buffer."
22308 (interactive)
22309 (org-agenda-check-type t 'agenda 'timeline)
22310 (setq org-agenda-show-log (not org-agenda-show-log))
22311 (org-agenda-set-mode-name)
22312 (org-agenda-redo)
22313 (message "Log mode is %s"
22314 (if org-agenda-show-log "on" "off")))
22316 (defun org-agenda-toggle-diary ()
22317 "Toggle diary inclusion in an agenda buffer."
22318 (interactive)
22319 (org-agenda-check-type t 'agenda)
22320 (setq org-agenda-include-diary (not org-agenda-include-diary))
22321 (org-agenda-redo)
22322 (org-agenda-set-mode-name)
22323 (message "Diary inclusion turned %s"
22324 (if org-agenda-include-diary "on" "off")))
22326 (defun org-agenda-toggle-time-grid ()
22327 "Toggle time grid in an agenda buffer."
22328 (interactive)
22329 (org-agenda-check-type t 'agenda)
22330 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
22331 (org-agenda-redo)
22332 (org-agenda-set-mode-name)
22333 (message "Time-grid turned %s"
22334 (if org-agenda-use-time-grid "on" "off")))
22336 (defun org-agenda-set-mode-name ()
22337 "Set the mode name to indicate all the small mode settings."
22338 (setq mode-name
22339 (concat "Org-Agenda"
22340 (if (equal org-agenda-ndays 1) " Day" "")
22341 (if (equal org-agenda-ndays 7) " Week" "")
22342 (if org-agenda-follow-mode " Follow" "")
22343 (if org-agenda-include-diary " Diary" "")
22344 (if org-agenda-use-time-grid " Grid" "")
22345 (if org-agenda-show-log " Log" "")))
22346 (force-mode-line-update))
22348 (defun org-agenda-post-command-hook ()
22349 (and (eolp) (not (bolp)) (backward-char 1))
22350 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
22351 (if (and org-agenda-follow-mode
22352 (get-text-property (point) 'org-marker))
22353 (org-agenda-show)))
22355 (defun org-agenda-show-priority ()
22356 "Show the priority of the current item.
22357 This priority is composed of the main priority given with the [#A] cookies,
22358 and by additional input from the age of a schedules or deadline entry."
22359 (interactive)
22360 (let* ((pri (get-text-property (point-at-bol) 'priority)))
22361 (message "Priority is %d" (if pri pri -1000))))
22363 (defun org-agenda-show-tags ()
22364 "Show the tags applicable to the current item."
22365 (interactive)
22366 (let* ((tags (get-text-property (point-at-bol) 'tags)))
22367 (if tags
22368 (message "Tags are :%s:"
22369 (org-no-properties (mapconcat 'identity tags ":")))
22370 (message "No tags associated with this line"))))
22372 (defun org-agenda-goto (&optional highlight)
22373 "Go to the Org-mode file which contains the item at point."
22374 (interactive)
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 (switch-to-buffer-other-window buffer)
22380 (widen)
22381 (goto-char pos)
22382 (when (org-mode-p)
22383 (org-show-context 'agenda)
22384 (save-excursion
22385 (and (outline-next-heading)
22386 (org-flag-heading nil)))) ; show the next heading
22387 (recenter (/ (window-height) 2))
22388 (run-hooks 'org-agenda-after-show-hook)
22389 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
22391 (defvar org-agenda-after-show-hook nil
22392 "Normal hook run after an item has been shown from the agenda.
22393 Point is in the buffer where the item originated.")
22395 (defun org-agenda-kill ()
22396 "Kill the entry or subtree belonging to the current agenda entry."
22397 (interactive)
22398 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22399 (let* ((marker (or (get-text-property (point) 'org-marker)
22400 (org-agenda-error)))
22401 (buffer (marker-buffer marker))
22402 (pos (marker-position marker))
22403 (type (get-text-property (point) 'type))
22404 dbeg dend (n 0) conf)
22405 (org-with-remote-undo buffer
22406 (with-current-buffer buffer
22407 (save-excursion
22408 (goto-char pos)
22409 (if (and (org-mode-p) (not (member type '("sexp"))))
22410 (setq dbeg (progn (org-back-to-heading t) (point))
22411 dend (org-end-of-subtree t t))
22412 (setq dbeg (point-at-bol)
22413 dend (min (point-max) (1+ (point-at-eol)))))
22414 (goto-char dbeg)
22415 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
22416 (setq conf (or (eq t org-agenda-confirm-kill)
22417 (and (numberp org-agenda-confirm-kill)
22418 (> n org-agenda-confirm-kill))))
22419 (and conf
22420 (not (y-or-n-p
22421 (format "Delete entry with %d lines in buffer \"%s\"? "
22422 n (buffer-name buffer))))
22423 (error "Abort"))
22424 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
22425 (with-current-buffer buffer (delete-region dbeg dend))
22426 (message "Agenda item and source killed"))))
22428 (defun org-agenda-archive ()
22429 "Kill the entry or subtree belonging to the current agenda entry."
22430 (interactive)
22431 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22432 (let* ((marker (or (get-text-property (point) 'org-marker)
22433 (org-agenda-error)))
22434 (buffer (marker-buffer marker))
22435 (pos (marker-position marker)))
22436 (org-with-remote-undo buffer
22437 (with-current-buffer buffer
22438 (if (org-mode-p)
22439 (save-excursion
22440 (goto-char pos)
22441 (org-remove-subtree-entries-from-agenda)
22442 (org-back-to-heading t)
22443 (org-archive-subtree))
22444 (error "Archiving works only in Org-mode files"))))))
22446 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
22447 "Remove all lines in the agenda that correspond to a given subtree.
22448 The subtree is the one in buffer BUF, starting at BEG and ending at END.
22449 If this information is not given, the function uses the tree at point."
22450 (let ((buf (or buf (current-buffer))) m p)
22451 (save-excursion
22452 (unless (and beg end)
22453 (org-back-to-heading t)
22454 (setq beg (point))
22455 (org-end-of-subtree t)
22456 (setq end (point)))
22457 (set-buffer (get-buffer org-agenda-buffer-name))
22458 (save-excursion
22459 (goto-char (point-max))
22460 (beginning-of-line 1)
22461 (while (not (bobp))
22462 (when (and (setq m (get-text-property (point) 'org-marker))
22463 (equal buf (marker-buffer m))
22464 (setq p (marker-position m))
22465 (>= p beg)
22466 (<= p end))
22467 (let ((inhibit-read-only t))
22468 (delete-region (point-at-bol) (1+ (point-at-eol)))))
22469 (beginning-of-line 0))))))
22471 (defun org-agenda-open-link ()
22472 "Follow the link in the current line, if any."
22473 (interactive)
22474 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
22475 (save-excursion
22476 (save-restriction
22477 (narrow-to-region (point-at-bol) (point-at-eol))
22478 (org-open-at-point))))
22480 (defun org-agenda-copy-local-variable (var)
22481 "Get a variable from a referenced buffer and install it here."
22482 (let ((m (get-text-property (point) 'org-marker)))
22483 (when (and m (buffer-live-p (marker-buffer m)))
22484 (org-set-local var (with-current-buffer (marker-buffer m)
22485 (symbol-value var))))))
22487 (defun org-agenda-switch-to (&optional delete-other-windows)
22488 "Go to the Org-mode file which contains the item at point."
22489 (interactive)
22490 (let* ((marker (or (get-text-property (point) 'org-marker)
22491 (org-agenda-error)))
22492 (buffer (marker-buffer marker))
22493 (pos (marker-position marker)))
22494 (switch-to-buffer buffer)
22495 (and delete-other-windows (delete-other-windows))
22496 (widen)
22497 (goto-char pos)
22498 (when (org-mode-p)
22499 (org-show-context 'agenda)
22500 (save-excursion
22501 (and (outline-next-heading)
22502 (org-flag-heading nil)))))) ; show the next heading
22504 (defun org-agenda-goto-mouse (ev)
22505 "Go to the Org-mode file which contains the item at the mouse click."
22506 (interactive "e")
22507 (mouse-set-point ev)
22508 (org-agenda-goto))
22510 (defun org-agenda-show ()
22511 "Display the Org-mode file which contains the item at point."
22512 (interactive)
22513 (let ((win (selected-window)))
22514 (org-agenda-goto t)
22515 (select-window win)))
22517 (defun org-agenda-recenter (arg)
22518 "Display the Org-mode file which contains the item at point and recenter."
22519 (interactive "P")
22520 (let ((win (selected-window)))
22521 (org-agenda-goto t)
22522 (recenter arg)
22523 (select-window win)))
22525 (defun org-agenda-show-mouse (ev)
22526 "Display the Org-mode file which contains the item at the mouse click."
22527 (interactive "e")
22528 (mouse-set-point ev)
22529 (org-agenda-show))
22531 (defun org-agenda-check-no-diary ()
22532 "Check if the entry is a diary link and abort if yes."
22533 (if (get-text-property (point) 'org-agenda-diary-link)
22534 (org-agenda-error)))
22536 (defun org-agenda-error ()
22537 (error "Command not allowed in this line"))
22539 (defun org-agenda-tree-to-indirect-buffer ()
22540 "Show the subtree corresponding to the current entry in an indirect buffer.
22541 This calls the command `org-tree-to-indirect-buffer' from the original
22542 Org-mode buffer.
22543 With numerical prefix arg ARG, go up to this level and then take that tree.
22544 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
22545 dedicated frame)."
22546 (interactive)
22547 (org-agenda-check-no-diary)
22548 (let* ((marker (or (get-text-property (point) 'org-marker)
22549 (org-agenda-error)))
22550 (buffer (marker-buffer marker))
22551 (pos (marker-position marker)))
22552 (with-current-buffer buffer
22553 (save-excursion
22554 (goto-char pos)
22555 (call-interactively 'org-tree-to-indirect-buffer)))))
22557 (defvar org-last-heading-marker (make-marker)
22558 "Marker pointing to the headline that last changed its TODO state
22559 by a remote command from the agenda.")
22561 (defun org-agenda-todo-nextset ()
22562 "Switch TODO entry to next sequence."
22563 (interactive)
22564 (org-agenda-todo 'nextset))
22566 (defun org-agenda-todo-previousset ()
22567 "Switch TODO entry to previous sequence."
22568 (interactive)
22569 (org-agenda-todo 'previousset))
22571 (defun org-agenda-todo (&optional arg)
22572 "Cycle TODO state of line at point, also in Org-mode file.
22573 This changes the line at point, all other lines in the agenda referring to
22574 the same tree node, and the headline of the tree node in the Org-mode file."
22575 (interactive "P")
22576 (org-agenda-check-no-diary)
22577 (let* ((col (current-column))
22578 (marker (or (get-text-property (point) 'org-marker)
22579 (org-agenda-error)))
22580 (buffer (marker-buffer marker))
22581 (pos (marker-position marker))
22582 (hdmarker (get-text-property (point) 'org-hd-marker))
22583 (inhibit-read-only t)
22584 newhead)
22585 (org-with-remote-undo buffer
22586 (with-current-buffer buffer
22587 (widen)
22588 (goto-char pos)
22589 (org-show-context 'agenda)
22590 (save-excursion
22591 (and (outline-next-heading)
22592 (org-flag-heading nil))) ; show the next heading
22593 (org-todo arg)
22594 (and (bolp) (forward-char 1))
22595 (setq newhead (org-get-heading))
22596 (save-excursion
22597 (org-back-to-heading)
22598 (move-marker org-last-heading-marker (point))))
22599 (beginning-of-line 1)
22600 (save-excursion
22601 (org-agenda-change-all-lines newhead hdmarker 'fixface))
22602 (move-to-column col))))
22604 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
22605 "Change all lines in the agenda buffer which match HDMARKER.
22606 The new content of the line will be NEWHEAD (as modified by
22607 `org-format-agenda-item'). HDMARKER is checked with
22608 `equal' against all `org-hd-marker' text properties in the file.
22609 If FIXFACE is non-nil, the face of each item is modified acording to
22610 the new TODO state."
22611 (let* ((inhibit-read-only t)
22612 props m pl undone-face done-face finish new dotime cat tags)
22613 (save-excursion
22614 (goto-char (point-max))
22615 (beginning-of-line 1)
22616 (while (not finish)
22617 (setq finish (bobp))
22618 (when (and (setq m (get-text-property (point) 'org-hd-marker))
22619 (equal m hdmarker))
22620 (setq props (text-properties-at (point))
22621 dotime (get-text-property (point) 'dotime)
22622 cat (get-text-property (point) 'org-category)
22623 tags (get-text-property (point) 'tags)
22624 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
22625 pl (get-text-property (point) 'prefix-length)
22626 undone-face (get-text-property (point) 'undone-face)
22627 done-face (get-text-property (point) 'done-face))
22628 (move-to-column pl)
22629 (cond
22630 ((equal new "")
22631 (beginning-of-line 1)
22632 (and (looking-at ".*\n?") (replace-match "")))
22633 ((looking-at ".*")
22634 (replace-match new t t)
22635 (beginning-of-line 1)
22636 (add-text-properties (point-at-bol) (point-at-eol) props)
22637 (when fixface
22638 (add-text-properties
22639 (point-at-bol) (point-at-eol)
22640 (list 'face
22641 (if org-last-todo-state-is-todo
22642 undone-face done-face))))
22643 (org-agenda-highlight-todo 'line)
22644 (beginning-of-line 1))
22645 (t (error "Line update did not work"))))
22646 (beginning-of-line 0)))
22647 (org-finalize-agenda)))
22649 (defun org-agenda-align-tags (&optional line)
22650 "Align all tags in agenda items to `org-agenda-tags-column'."
22651 (let ((inhibit-read-only t) l c)
22652 (save-excursion
22653 (goto-char (if line (point-at-bol) (point-min)))
22654 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22655 (if line (point-at-eol) nil) t)
22656 (add-text-properties
22657 (match-beginning 2) (match-end 2)
22658 (list 'face (list 'org-tag (get-text-property
22659 (match-beginning 2) 'face))))
22660 (setq l (- (match-end 2) (match-beginning 2))
22661 c (if (< org-agenda-tags-column 0)
22662 (- (abs org-agenda-tags-column) l)
22663 org-agenda-tags-column))
22664 (delete-region (match-beginning 1) (match-end 1))
22665 (goto-char (match-beginning 1))
22666 (insert (org-add-props
22667 (make-string (max 1 (- c (current-column))) ?\ )
22668 (text-properties-at (point))))))))
22670 (defun org-agenda-priority-up ()
22671 "Increase the priority of line at point, also in Org-mode file."
22672 (interactive)
22673 (org-agenda-priority 'up))
22675 (defun org-agenda-priority-down ()
22676 "Decrease the priority of line at point, also in Org-mode file."
22677 (interactive)
22678 (org-agenda-priority 'down))
22680 (defun org-agenda-priority (&optional force-direction)
22681 "Set the priority of line at point, also in Org-mode file.
22682 This changes the line at point, all other lines in the agenda referring to
22683 the same tree node, and the headline of the tree node in the Org-mode file."
22684 (interactive)
22685 (org-agenda-check-no-diary)
22686 (let* ((marker (or (get-text-property (point) 'org-marker)
22687 (org-agenda-error)))
22688 (hdmarker (get-text-property (point) 'org-hd-marker))
22689 (buffer (marker-buffer hdmarker))
22690 (pos (marker-position hdmarker))
22691 (inhibit-read-only t)
22692 newhead)
22693 (org-with-remote-undo buffer
22694 (with-current-buffer buffer
22695 (widen)
22696 (goto-char pos)
22697 (org-show-context 'agenda)
22698 (save-excursion
22699 (and (outline-next-heading)
22700 (org-flag-heading nil))) ; show the next heading
22701 (funcall 'org-priority force-direction)
22702 (end-of-line 1)
22703 (setq newhead (org-get-heading)))
22704 (org-agenda-change-all-lines newhead hdmarker)
22705 (beginning-of-line 1))))
22707 (defun org-get-tags-at (&optional pos)
22708 "Get a list of all headline tags applicable at POS.
22709 POS defaults to point. If tags are inherited, the list contains
22710 the targets in the same sequence as the headlines appear, i.e.
22711 the tags of the current headline come last."
22712 (interactive)
22713 (let (tags lastpos)
22714 (save-excursion
22715 (save-restriction
22716 (widen)
22717 (goto-char (or pos (point)))
22718 (save-match-data
22719 (org-back-to-heading t)
22720 (condition-case nil
22721 (while (not (equal lastpos (point)))
22722 (setq lastpos (point))
22723 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
22724 (setq tags (append (org-split-string
22725 (org-match-string-no-properties 1) ":")
22726 tags)))
22727 (or org-use-tag-inheritance (error ""))
22728 (org-up-heading-all 1))
22729 (error nil))))
22730 tags)))
22732 ;; FIXME: should fix the tags property of the agenda line.
22733 (defun org-agenda-set-tags ()
22734 "Set tags for the current headline."
22735 (interactive)
22736 (org-agenda-check-no-diary)
22737 (if (and (org-region-active-p) (interactive-p))
22738 (call-interactively 'org-change-tag-in-region)
22739 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22740 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22741 (org-agenda-error)))
22742 (buffer (marker-buffer hdmarker))
22743 (pos (marker-position hdmarker))
22744 (inhibit-read-only t)
22745 newhead)
22746 (org-with-remote-undo buffer
22747 (with-current-buffer buffer
22748 (widen)
22749 (goto-char pos)
22750 (save-excursion
22751 (org-show-context 'agenda))
22752 (save-excursion
22753 (and (outline-next-heading)
22754 (org-flag-heading nil))) ; show the next heading
22755 (goto-char pos)
22756 (call-interactively 'org-set-tags)
22757 (end-of-line 1)
22758 (setq newhead (org-get-heading)))
22759 (org-agenda-change-all-lines newhead hdmarker)
22760 (beginning-of-line 1)))))
22762 (defun org-agenda-toggle-archive-tag ()
22763 "Toggle the archive tag for the current entry."
22764 (interactive)
22765 (org-agenda-check-no-diary)
22766 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22767 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22768 (org-agenda-error)))
22769 (buffer (marker-buffer hdmarker))
22770 (pos (marker-position hdmarker))
22771 (inhibit-read-only t)
22772 newhead)
22773 (org-with-remote-undo buffer
22774 (with-current-buffer buffer
22775 (widen)
22776 (goto-char pos)
22777 (org-show-context 'agenda)
22778 (save-excursion
22779 (and (outline-next-heading)
22780 (org-flag-heading nil))) ; show the next heading
22781 (call-interactively 'org-toggle-archive-tag)
22782 (end-of-line 1)
22783 (setq newhead (org-get-heading)))
22784 (org-agenda-change-all-lines newhead hdmarker)
22785 (beginning-of-line 1))))
22787 (defun org-agenda-date-later (arg &optional what)
22788 "Change the date of this item to one day later."
22789 (interactive "p")
22790 (org-agenda-check-type t 'agenda 'timeline)
22791 (org-agenda-check-no-diary)
22792 (let* ((marker (or (get-text-property (point) 'org-marker)
22793 (org-agenda-error)))
22794 (buffer (marker-buffer marker))
22795 (pos (marker-position marker)))
22796 (org-with-remote-undo buffer
22797 (with-current-buffer buffer
22798 (widen)
22799 (goto-char pos)
22800 (if (not (org-at-timestamp-p))
22801 (error "Cannot find time stamp"))
22802 (org-timestamp-change arg (or what 'day)))
22803 (org-agenda-show-new-time marker org-last-changed-timestamp))
22804 (message "Time stamp changed to %s" org-last-changed-timestamp)))
22806 (defun org-agenda-date-earlier (arg &optional what)
22807 "Change the date of this item to one day earlier."
22808 (interactive "p")
22809 (org-agenda-date-later (- arg) what))
22811 (defun org-agenda-show-new-time (marker stamp &optional prefix)
22812 "Show new date stamp via text properties."
22813 ;; We use text properties to make this undoable
22814 (let ((inhibit-read-only t))
22815 (setq stamp (concat " " prefix " => " stamp))
22816 (save-excursion
22817 (goto-char (point-max))
22818 (while (not (bobp))
22819 (when (equal marker (get-text-property (point) 'org-marker))
22820 (move-to-column (- (window-width) (length stamp)) t)
22821 (if (featurep 'xemacs)
22822 ;; Use `duplicable' property to trigger undo recording
22823 (let ((ex (make-extent nil nil))
22824 (gl (make-glyph stamp)))
22825 (set-glyph-face gl 'secondary-selection)
22826 (set-extent-properties
22827 ex (list 'invisible t 'end-glyph gl 'duplicable t))
22828 (insert-extent ex (1- (point)) (point-at-eol)))
22829 (add-text-properties
22830 (1- (point)) (point-at-eol)
22831 (list 'display (org-add-props stamp nil
22832 'face 'secondary-selection))))
22833 (beginning-of-line 1))
22834 (beginning-of-line 0)))))
22836 (defun org-agenda-date-prompt (arg)
22837 "Change the date of this item. Date is prompted for, with default today.
22838 The prefix ARG is passed to the `org-time-stamp' command and can therefore
22839 be used to request time specification in the time stamp."
22840 (interactive "P")
22841 (org-agenda-check-type t 'agenda 'timeline)
22842 (org-agenda-check-no-diary)
22843 (let* ((marker (or (get-text-property (point) 'org-marker)
22844 (org-agenda-error)))
22845 (buffer (marker-buffer marker))
22846 (pos (marker-position marker)))
22847 (org-with-remote-undo buffer
22848 (with-current-buffer buffer
22849 (widen)
22850 (goto-char pos)
22851 (if (not (org-at-timestamp-p))
22852 (error "Cannot find time stamp"))
22853 (org-time-stamp arg)
22854 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
22856 (defun org-agenda-schedule (arg)
22857 "Schedule the item at point."
22858 (interactive "P")
22859 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22860 (org-agenda-check-no-diary)
22861 (let* ((marker (or (get-text-property (point) 'org-marker)
22862 (org-agenda-error)))
22863 (buffer (marker-buffer marker))
22864 (pos (marker-position marker))
22865 (org-insert-labeled-timestamps-at-point nil)
22867 (org-with-remote-undo buffer
22868 (with-current-buffer buffer
22869 (widen)
22870 (goto-char pos)
22871 (setq ts (org-schedule arg)))
22872 (org-agenda-show-new-time marker ts "S"))
22873 (message "Item scheduled for %s" ts)))
22875 (defun org-agenda-deadline (arg)
22876 "Schedule the item at point."
22877 (interactive "P")
22878 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22879 (org-agenda-check-no-diary)
22880 (let* ((marker (or (get-text-property (point) 'org-marker)
22881 (org-agenda-error)))
22882 (buffer (marker-buffer marker))
22883 (pos (marker-position marker))
22884 (org-insert-labeled-timestamps-at-point nil)
22886 (org-with-remote-undo buffer
22887 (with-current-buffer buffer
22888 (widen)
22889 (goto-char pos)
22890 (setq ts (org-deadline arg)))
22891 (org-agenda-show-new-time marker ts "S"))
22892 (message "Deadline for this item set to %s" ts)))
22894 (defun org-get-heading (&optional no-tags)
22895 "Return the heading of the current entry, without the stars."
22896 (save-excursion
22897 (org-back-to-heading t)
22898 (if (looking-at
22899 (if no-tags
22900 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
22901 "\\*+[ \t]+\\([^\r\n]*\\)"))
22902 (match-string 1) "")))
22904 (defun org-agenda-clock-in (&optional arg)
22905 "Start the clock on the currently selected item."
22906 (interactive "P")
22907 (org-agenda-check-no-diary)
22908 (let* ((marker (or (get-text-property (point) 'org-marker)
22909 (org-agenda-error)))
22910 (pos (marker-position marker)))
22911 (org-with-remote-undo (marker-buffer marker)
22912 (with-current-buffer (marker-buffer marker)
22913 (widen)
22914 (goto-char pos)
22915 (org-clock-in)))))
22917 (defun org-agenda-clock-out (&optional arg)
22918 "Stop the currently running clock."
22919 (interactive "P")
22920 (unless (marker-buffer org-clock-marker)
22921 (error "No running clock"))
22922 (org-with-remote-undo (marker-buffer org-clock-marker)
22923 (org-clock-out)))
22925 (defun org-agenda-clock-cancel (&optional arg)
22926 "Cancel the currently running clock."
22927 (interactive "P")
22928 (unless (marker-buffer org-clock-marker)
22929 (error "No running clock"))
22930 (org-with-remote-undo (marker-buffer org-clock-marker)
22931 (org-clock-cancel)))
22933 (defun org-agenda-diary-entry ()
22934 "Make a diary entry, like the `i' command from the calendar.
22935 All the standard commands work: block, weekly etc."
22936 (interactive)
22937 (org-agenda-check-type t 'agenda 'timeline)
22938 (require 'diary-lib)
22939 (let* ((char (progn
22940 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
22941 (read-char-exclusive)))
22942 (cmd (cdr (assoc char
22943 '((?d . insert-diary-entry)
22944 (?w . insert-weekly-diary-entry)
22945 (?m . insert-monthly-diary-entry)
22946 (?y . insert-yearly-diary-entry)
22947 (?a . insert-anniversary-diary-entry)
22948 (?b . insert-block-diary-entry)
22949 (?c . insert-cyclic-diary-entry)))))
22950 (oldf (symbol-function 'calendar-cursor-to-date))
22951 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
22952 (point (point))
22953 (mark (or (mark t) (point))))
22954 (unless cmd
22955 (error "No command associated with <%c>" char))
22956 (unless (and (get-text-property point 'day)
22957 (or (not (equal ?b char))
22958 (get-text-property mark 'day)))
22959 (error "Don't know which date to use for diary entry"))
22960 ;; We implement this by hacking the `calendar-cursor-to-date' function
22961 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
22962 (let ((calendar-mark-ring
22963 (list (calendar-gregorian-from-absolute
22964 (or (get-text-property mark 'day)
22965 (get-text-property point 'day))))))
22966 (unwind-protect
22967 (progn
22968 (fset 'calendar-cursor-to-date
22969 (lambda (&optional error)
22970 (calendar-gregorian-from-absolute
22971 (get-text-property point 'day))))
22972 (call-interactively cmd))
22973 (fset 'calendar-cursor-to-date oldf)))))
22976 (defun org-agenda-execute-calendar-command (cmd)
22977 "Execute a calendar command from the agenda, with the date associated to
22978 the cursor position."
22979 (org-agenda-check-type t 'agenda 'timeline)
22980 (require 'diary-lib)
22981 (unless (get-text-property (point) 'day)
22982 (error "Don't know which date to use for calendar command"))
22983 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
22984 (point (point))
22985 (date (calendar-gregorian-from-absolute
22986 (get-text-property point 'day)))
22987 ;; the following 3 vars are needed in the calendar
22988 (displayed-day (extract-calendar-day date))
22989 (displayed-month (extract-calendar-month date))
22990 (displayed-year (extract-calendar-year date)))
22991 (unwind-protect
22992 (progn
22993 (fset 'calendar-cursor-to-date
22994 (lambda (&optional error)
22995 (calendar-gregorian-from-absolute
22996 (get-text-property point 'day))))
22997 (call-interactively cmd))
22998 (fset 'calendar-cursor-to-date oldf))))
23000 (defun org-agenda-phases-of-moon ()
23001 "Display the phases of the moon for the 3 months around the cursor date."
23002 (interactive)
23003 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
23005 (defun org-agenda-holidays ()
23006 "Display the holidays for the 3 months around the cursor date."
23007 (interactive)
23008 (org-agenda-execute-calendar-command 'list-calendar-holidays))
23010 (defun org-agenda-sunrise-sunset (arg)
23011 "Display sunrise and sunset for the cursor date.
23012 Latitude and longitude can be specified with the variables
23013 `calendar-latitude' and `calendar-longitude'. When called with prefix
23014 argument, latitude and longitude will be prompted for."
23015 (interactive "P")
23016 (let ((calendar-longitude (if arg nil calendar-longitude))
23017 (calendar-latitude (if arg nil calendar-latitude))
23018 (calendar-location-name
23019 (if arg "the given coordinates" calendar-location-name)))
23020 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
23022 (defun org-agenda-goto-calendar ()
23023 "Open the Emacs calendar with the date at the cursor."
23024 (interactive)
23025 (org-agenda-check-type t 'agenda 'timeline)
23026 (let* ((day (or (get-text-property (point) 'day)
23027 (error "Don't know which date to open in calendar")))
23028 (date (calendar-gregorian-from-absolute day))
23029 (calendar-move-hook nil)
23030 (view-calendar-holidays-initially nil)
23031 (view-diary-entries-initially nil))
23032 (calendar)
23033 (calendar-goto-date date)))
23035 (defun org-calendar-goto-agenda ()
23036 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
23037 This is a command that has to be installed in `calendar-mode-map'."
23038 (interactive)
23039 (org-agenda-list nil (calendar-absolute-from-gregorian
23040 (calendar-cursor-to-date))
23041 nil))
23043 (defun org-agenda-convert-date ()
23044 (interactive)
23045 (org-agenda-check-type t 'agenda 'timeline)
23046 (let ((day (get-text-property (point) 'day))
23047 date s)
23048 (unless day
23049 (error "Don't know which date to convert"))
23050 (setq date (calendar-gregorian-from-absolute day))
23051 (setq s (concat
23052 "Gregorian: " (calendar-date-string date) "\n"
23053 "ISO: " (calendar-iso-date-string date) "\n"
23054 "Day of Yr: " (calendar-day-of-year-string date) "\n"
23055 "Julian: " (calendar-julian-date-string date) "\n"
23056 "Astron. JD: " (calendar-astro-date-string date)
23057 " (Julian date number at noon UTC)\n"
23058 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
23059 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
23060 "French: " (calendar-french-date-string date) "\n"
23061 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
23062 "Mayan: " (calendar-mayan-date-string date) "\n"
23063 "Coptic: " (calendar-coptic-date-string date) "\n"
23064 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
23065 "Persian: " (calendar-persian-date-string date) "\n"
23066 "Chinese: " (calendar-chinese-date-string date) "\n"))
23067 (with-output-to-temp-buffer "*Dates*"
23068 (princ s))
23069 (if (fboundp 'fit-window-to-buffer)
23070 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
23073 ;;;; Embedded LaTeX
23075 (defvar org-cdlatex-mode-map (make-sparse-keymap)
23076 "Keymap for the minor `org-cdlatex-mode'.")
23078 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
23079 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
23080 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
23081 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
23082 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
23084 (defvar org-cdlatex-texmathp-advice-is-done nil
23085 "Flag remembering if we have applied the advice to texmathp already.")
23087 (define-minor-mode org-cdlatex-mode
23088 "Toggle the minor `org-cdlatex-mode'.
23089 This mode supports entering LaTeX environment and math in LaTeX fragments
23090 in Org-mode.
23091 \\{org-cdlatex-mode-map}"
23092 nil " OCDL" nil
23093 (when org-cdlatex-mode (require 'cdlatex))
23094 (unless org-cdlatex-texmathp-advice-is-done
23095 (setq org-cdlatex-texmathp-advice-is-done t)
23096 (defadvice texmathp (around org-math-always-on activate)
23097 "Always return t in org-mode buffers.
23098 This is because we want to insert math symbols without dollars even outside
23099 the LaTeX math segments. If Orgmode thinks that point is actually inside
23100 en embedded LaTeX fragement, let texmathp do its job.
23101 \\[org-cdlatex-mode-map]"
23102 (interactive)
23103 (let (p)
23104 (cond
23105 ((not (org-mode-p)) ad-do-it)
23106 ((eq this-command 'cdlatex-math-symbol)
23107 (setq ad-return-value t
23108 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
23110 (let ((p (org-inside-LaTeX-fragment-p)))
23111 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
23112 (setq ad-return-value t
23113 texmathp-why '("Org-mode embedded math" . 0))
23114 (if p ad-do-it)))))))))
23116 (defun turn-on-org-cdlatex ()
23117 "Unconditionally turn on `org-cdlatex-mode'."
23118 (org-cdlatex-mode 1))
23120 (defun org-inside-LaTeX-fragment-p ()
23121 "Test if point is inside a LaTeX fragment.
23122 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
23123 sequence appearing also before point.
23124 Even though the matchers for math are configurable, this function assumes
23125 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
23126 delimiters are skipped when they have been removed by customization.
23127 The return value is nil, or a cons cell with the delimiter and
23128 and the position of this delimiter.
23130 This function does a reasonably good job, but can locally be fooled by
23131 for example currency specifications. For example it will assume being in
23132 inline math after \"$22.34\". The LaTeX fragment formatter will only format
23133 fragments that are properly closed, but during editing, we have to live
23134 with the uncertainty caused by missing closing delimiters. This function
23135 looks only before point, not after."
23136 (catch 'exit
23137 (let ((pos (point))
23138 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
23139 (lim (progn
23140 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
23141 (point)))
23142 dd-on str (start 0) m re)
23143 (goto-char pos)
23144 (when dodollar
23145 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
23146 re (nth 1 (assoc "$" org-latex-regexps)))
23147 (while (string-match re str start)
23148 (cond
23149 ((= (match-end 0) (length str))
23150 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
23151 ((= (match-end 0) (- (length str) 5))
23152 (throw 'exit nil))
23153 (t (setq start (match-end 0))))))
23154 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
23155 (goto-char pos)
23156 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
23157 (and (match-beginning 2) (throw 'exit nil))
23158 ;; count $$
23159 (while (re-search-backward "\\$\\$" lim t)
23160 (setq dd-on (not dd-on)))
23161 (goto-char pos)
23162 (if dd-on (cons "$$" m))))))
23165 (defun org-try-cdlatex-tab ()
23166 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
23167 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
23168 - inside a LaTeX fragment, or
23169 - after the first word in a line, where an abbreviation expansion could
23170 insert a LaTeX environment."
23171 (when org-cdlatex-mode
23172 (cond
23173 ((save-excursion
23174 (skip-chars-backward "a-zA-Z0-9*")
23175 (skip-chars-backward " \t")
23176 (bolp))
23177 (cdlatex-tab) t)
23178 ((org-inside-LaTeX-fragment-p)
23179 (cdlatex-tab) t)
23180 (t nil))))
23182 (defun org-cdlatex-underscore-caret (&optional arg)
23183 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
23184 Revert to the normal definition outside of these fragments."
23185 (interactive "P")
23186 (if (org-inside-LaTeX-fragment-p)
23187 (call-interactively 'cdlatex-sub-superscript)
23188 (let (org-cdlatex-mode)
23189 (call-interactively (key-binding (vector last-input-event))))))
23191 (defun org-cdlatex-math-modify (&optional arg)
23192 "Execute `cdlatex-math-modify' in LaTeX fragments.
23193 Revert to the normal definition outside of these fragments."
23194 (interactive "P")
23195 (if (org-inside-LaTeX-fragment-p)
23196 (call-interactively 'cdlatex-math-modify)
23197 (let (org-cdlatex-mode)
23198 (call-interactively (key-binding (vector last-input-event))))))
23200 (defvar org-latex-fragment-image-overlays nil
23201 "List of overlays carrying the images of latex fragments.")
23202 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
23204 (defun org-remove-latex-fragment-image-overlays ()
23205 "Remove all overlays with LaTeX fragment images in current buffer."
23206 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
23207 (setq org-latex-fragment-image-overlays nil))
23209 (defun org-preview-latex-fragment (&optional subtree)
23210 "Preview the LaTeX fragment at point, or all locally or globally.
23211 If the cursor is in a LaTeX fragment, create the image and overlay
23212 it over the source code. If there is no fragment at point, display
23213 all fragments in the current text, from one headline to the next. With
23214 prefix SUBTREE, display all fragments in the current subtree. With a
23215 double prefix `C-u C-u', or when the cursor is before the first headline,
23216 display all fragments in the buffer.
23217 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
23218 (interactive "P")
23219 (org-remove-latex-fragment-image-overlays)
23220 (save-excursion
23221 (save-restriction
23222 (let (beg end at msg)
23223 (cond
23224 ((or (equal subtree '(16))
23225 (not (save-excursion
23226 (re-search-backward (concat "^" outline-regexp) nil t))))
23227 (setq beg (point-min) end (point-max)
23228 msg "Creating images for buffer...%s"))
23229 ((equal subtree '(4))
23230 (org-back-to-heading)
23231 (setq beg (point) end (org-end-of-subtree t)
23232 msg "Creating images for subtree...%s"))
23234 (if (setq at (org-inside-LaTeX-fragment-p))
23235 (goto-char (max (point-min) (- (cdr at) 2)))
23236 (org-back-to-heading))
23237 (setq beg (point) end (progn (outline-next-heading) (point))
23238 msg (if at "Creating image...%s"
23239 "Creating images for entry...%s"))))
23240 (message msg "")
23241 (narrow-to-region beg end)
23242 (goto-char beg)
23243 (org-format-latex
23244 (concat "ltxpng/" (file-name-sans-extension
23245 (file-name-nondirectory
23246 buffer-file-name)))
23247 default-directory 'overlays msg at 'forbuffer)
23248 (message msg "done. Use `C-c C-c' to remove images.")))))
23250 (defvar org-latex-regexps
23251 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
23252 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
23253 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
23254 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
23255 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
23256 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
23257 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
23258 "Regular expressions for matching embedded LaTeX.")
23260 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
23261 "Replace LaTeX fragments with links to an image, and produce images."
23262 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
23263 (let* ((prefixnodir (file-name-nondirectory prefix))
23264 (absprefix (expand-file-name prefix dir))
23265 (todir (file-name-directory absprefix))
23266 (opt org-format-latex-options)
23267 (matchers (plist-get opt :matchers))
23268 (re-list org-latex-regexps)
23269 (cnt 0) txt link beg end re e checkdir
23270 m n block linkfile movefile ov)
23271 ;; Check if there are old images files with this prefix, and remove them
23272 (when (file-directory-p todir)
23273 (mapc 'delete-file
23274 (directory-files
23275 todir 'full
23276 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
23277 ;; Check the different regular expressions
23278 (while (setq e (pop re-list))
23279 (setq m (car e) re (nth 1 e) n (nth 2 e)
23280 block (if (nth 3 e) "\n\n" ""))
23281 (when (member m matchers)
23282 (goto-char (point-min))
23283 (while (re-search-forward re nil t)
23284 (when (or (not at) (equal (cdr at) (match-beginning n)))
23285 (setq txt (match-string n)
23286 beg (match-beginning n) end (match-end n)
23287 cnt (1+ cnt)
23288 linkfile (format "%s_%04d.png" prefix cnt)
23289 movefile (format "%s_%04d.png" absprefix cnt)
23290 link (concat block "[[file:" linkfile "]]" block))
23291 (if msg (message msg cnt))
23292 (goto-char beg)
23293 (unless checkdir ; make sure the directory exists
23294 (setq checkdir t)
23295 (or (file-directory-p todir) (make-directory todir)))
23296 (org-create-formula-image
23297 txt movefile opt forbuffer)
23298 (if overlays
23299 (progn
23300 (setq ov (org-make-overlay beg end))
23301 (if (featurep 'xemacs)
23302 (progn
23303 (org-overlay-put ov 'invisible t)
23304 (org-overlay-put
23305 ov 'end-glyph
23306 (make-glyph (vector 'png :file movefile))))
23307 (org-overlay-put
23308 ov 'display
23309 (list 'image :type 'png :file movefile :ascent 'center)))
23310 (push ov org-latex-fragment-image-overlays)
23311 (goto-char end))
23312 (delete-region beg end)
23313 (insert link))))))))
23315 ;; This function borrows from Ganesh Swami's latex2png.el
23316 (defun org-create-formula-image (string tofile options buffer)
23317 (let* ((tmpdir (if (featurep 'xemacs)
23318 (temp-directory)
23319 temporary-file-directory))
23320 (texfilebase (make-temp-name
23321 (expand-file-name "orgtex" tmpdir)))
23322 (texfile (concat texfilebase ".tex"))
23323 (dvifile (concat texfilebase ".dvi"))
23324 (pngfile (concat texfilebase ".png"))
23325 (fnh (face-attribute 'default :height nil))
23326 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
23327 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
23328 (fg (or (plist-get options (if buffer :foreground :html-foreground))
23329 "Black"))
23330 (bg (or (plist-get options (if buffer :background :html-background))
23331 "Transparent")))
23332 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
23333 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
23334 (with-temp-file texfile
23335 (insert org-format-latex-header
23336 "\n\\begin{document}\n" string "\n\\end{document}\n"))
23337 (let ((dir default-directory))
23338 (condition-case nil
23339 (progn
23340 (cd tmpdir)
23341 (call-process "latex" nil nil nil texfile))
23342 (error nil))
23343 (cd dir))
23344 (if (not (file-exists-p dvifile))
23345 (progn (message "Failed to create dvi file from %s" texfile) nil)
23346 (call-process "dvipng" nil nil nil
23347 "-E" "-fg" fg "-bg" bg
23348 "-D" dpi
23349 ;;"-x" scale "-y" scale
23350 "-T" "tight"
23351 "-o" pngfile
23352 dvifile)
23353 (if (not (file-exists-p pngfile))
23354 (progn (message "Failed to create png file from %s" texfile) nil)
23355 ;; Use the requested file name and clean up
23356 (copy-file pngfile tofile 'replace)
23357 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
23358 (delete-file (concat texfilebase e)))
23359 pngfile))))
23361 (defun org-dvipng-color (attr)
23362 "Return an rgb color specification for dvipng."
23363 (apply 'format "rgb %s %s %s"
23364 (mapcar 'org-normalize-color
23365 (color-values (face-attribute 'default attr nil)))))
23367 (defun org-normalize-color (value)
23368 "Return string to be used as color value for an RGB component."
23369 (format "%g" (/ value 65535.0)))
23371 ;;;; Exporting
23373 ;;; Variables, constants, and parameter plists
23375 (defconst org-level-max 20)
23377 (defvar org-export-html-preamble nil
23378 "Preamble, to be inserted just after <body>. Set by publishing functions.")
23379 (defvar org-export-html-postamble nil
23380 "Preamble, to be inserted just before </body>. Set by publishing functions.")
23381 (defvar org-export-html-auto-preamble t
23382 "Should default preamble be inserted? Set by publishing functions.")
23383 (defvar org-export-html-auto-postamble t
23384 "Should default postamble be inserted? Set by publishing functions.")
23385 (defvar org-current-export-file nil) ; dynamically scoped parameter
23386 (defvar org-current-export-dir nil) ; dynamically scoped parameter
23389 (defconst org-export-plist-vars
23390 '((:language . org-export-default-language)
23391 (:customtime . org-display-custom-times)
23392 (:headline-levels . org-export-headline-levels)
23393 (:section-numbers . org-export-with-section-numbers)
23394 (:table-of-contents . org-export-with-toc)
23395 (:preserve-breaks . org-export-preserve-breaks)
23396 (:archived-trees . org-export-with-archived-trees)
23397 (:emphasize . org-export-with-emphasize)
23398 (:sub-superscript . org-export-with-sub-superscripts)
23399 (:special-strings . org-export-with-special-strings)
23400 (:footnotes . org-export-with-footnotes)
23401 (:drawers . org-export-with-drawers)
23402 (:tags . org-export-with-tags)
23403 (:TeX-macros . org-export-with-TeX-macros)
23404 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
23405 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
23406 (:fixed-width . org-export-with-fixed-width)
23407 (:timestamps . org-export-with-timestamps)
23408 (:author-info . org-export-author-info)
23409 (:time-stamp-file . org-export-time-stamp-file)
23410 (:tables . org-export-with-tables)
23411 (:table-auto-headline . org-export-highlight-first-table-line)
23412 (:style . org-export-html-style)
23413 (:agenda-style . org-agenda-export-html-style)
23414 (:convert-org-links . org-export-html-link-org-files-as-html)
23415 (:inline-images . org-export-html-inline-images)
23416 (:html-extension . org-export-html-extension)
23417 (:html-table-tag . org-export-html-table-tag)
23418 (:expand-quoted-html . org-export-html-expand)
23419 (:timestamp . org-export-html-with-timestamp)
23420 (:publishing-directory . org-export-publishing-directory)
23421 (:preamble . org-export-html-preamble)
23422 (:postamble . org-export-html-postamble)
23423 (:auto-preamble . org-export-html-auto-preamble)
23424 (:auto-postamble . org-export-html-auto-postamble)
23425 (:author . user-full-name)
23426 (:email . user-mail-address)))
23428 (defun org-default-export-plist ()
23429 "Return the property list with default settings for the export variables."
23430 (let ((l org-export-plist-vars) rtn e)
23431 (while (setq e (pop l))
23432 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
23433 rtn))
23435 (defun org-infile-export-plist ()
23436 "Return the property list with file-local settings for export."
23437 (save-excursion
23438 (save-restriction
23439 (widen)
23440 (goto-char 0)
23441 (let ((re (org-make-options-regexp
23442 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
23443 p key val text options)
23444 (while (re-search-forward re nil t)
23445 (setq key (org-match-string-no-properties 1)
23446 val (org-match-string-no-properties 2))
23447 (cond
23448 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
23449 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
23450 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
23451 ((string-equal key "DATE") (setq p (plist-put p :date val)))
23452 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
23453 ((string-equal key "TEXT")
23454 (setq text (if text (concat text "\n" val) val)))
23455 ((string-equal key "OPTIONS") (setq options val))))
23456 (setq p (plist-put p :text text))
23457 (when options
23458 (let ((op '(("H" . :headline-levels)
23459 ("num" . :section-numbers)
23460 ("toc" . :table-of-contents)
23461 ("\\n" . :preserve-breaks)
23462 ("@" . :expand-quoted-html)
23463 (":" . :fixed-width)
23464 ("|" . :tables)
23465 ("^" . :sub-superscript)
23466 ("-" . :special-strings)
23467 ("f" . :footnotes)
23468 ("d" . :drawers)
23469 ("tags" . :tags)
23470 ("*" . :emphasize)
23471 ("TeX" . :TeX-macros)
23472 ("LaTeX" . :LaTeX-fragments)
23473 ("skip" . :skip-before-1st-heading)
23474 ("author" . :author-info)
23475 ("timestamp" . :time-stamp-file)))
23477 (while (setq o (pop op))
23478 (if (string-match (concat (regexp-quote (car o))
23479 ":\\([^ \t\n\r;,.]*\\)")
23480 options)
23481 (setq p (plist-put p (cdr o)
23482 (car (read-from-string
23483 (match-string 1 options)))))))))
23484 p))))
23486 (defun org-export-directory (type plist)
23487 (let* ((val (plist-get plist :publishing-directory))
23488 (dir (if (listp val)
23489 (or (cdr (assoc type val)) ".")
23490 val)))
23491 dir))
23493 (defun org-skip-comments (lines)
23494 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
23495 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
23496 (re2 "^\\(\\*+\\)[ \t\n\r]")
23497 (case-fold-search nil)
23498 rtn line level)
23499 (while (setq line (pop lines))
23500 (cond
23501 ((and (string-match re1 line)
23502 (setq level (- (match-end 1) (match-beginning 1))))
23503 ;; Beginning of a COMMENT subtree. Skip it.
23504 (while (and (setq line (pop lines))
23505 (or (not (string-match re2 line))
23506 (> (- (match-end 1) (match-beginning 1)) level))))
23507 (setq lines (cons line lines)))
23508 ((string-match "^#" line)
23509 ;; an ordinary comment line
23511 ((and org-export-table-remove-special-lines
23512 (string-match "^[ \t]*|" line)
23513 (or (string-match "^[ \t]*| *[!_^] *|" line)
23514 (and (string-match "| *<[0-9]+> *|" line)
23515 (not (string-match "| *[^ <|]" line)))))
23516 ;; a special table line that should be removed
23518 (t (setq rtn (cons line rtn)))))
23519 (nreverse rtn)))
23521 (defun org-export (&optional arg)
23522 (interactive)
23523 (let ((help "[t] insert the export option template
23524 \[v] limit export to visible part of outline tree
23526 \[a] export as ASCII
23528 \[h] export as HTML
23529 \[H] export as HTML to temporary buffer
23530 \[R] export region as HTML
23531 \[b] export as HTML and browse immediately
23532 \[x] export as XOXO
23534 \[l] export as LaTeX
23535 \[L] export as LaTeX to temporary buffer
23537 \[i] export current file as iCalendar file
23538 \[I] export all agenda files as iCalendar files
23539 \[c] export agenda files into combined iCalendar file
23541 \[F] publish current file
23542 \[P] publish current project
23543 \[X] publish... (project will be prompted for)
23544 \[A] publish all projects")
23545 (cmds
23546 '((?t . org-insert-export-options-template)
23547 (?v . org-export-visible)
23548 (?a . org-export-as-ascii)
23549 (?h . org-export-as-html)
23550 (?b . org-export-as-html-and-open)
23551 (?H . org-export-as-html-to-buffer)
23552 (?R . org-export-region-as-html)
23553 (?x . org-export-as-xoxo)
23554 (?l . org-export-as-latex)
23555 (?L . org-export-as-latex-to-buffer)
23556 (?i . org-export-icalendar-this-file)
23557 (?I . org-export-icalendar-all-agenda-files)
23558 (?c . org-export-icalendar-combine-agenda-files)
23559 (?F . org-publish-current-file)
23560 (?P . org-publish-current-project)
23561 (?X . org-publish)
23562 (?A . org-publish-all)))
23563 r1 r2 ass)
23564 (save-window-excursion
23565 (delete-other-windows)
23566 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
23567 (princ help))
23568 (message "Select command: ")
23569 (setq r1 (read-char-exclusive)))
23570 (setq r2 (if (< r1 27) (+ r1 96) r1))
23571 (if (setq ass (assq r2 cmds))
23572 (call-interactively (cdr ass))
23573 (error "No command associated with key %c" r1))))
23575 (defconst org-html-entities
23576 '(("nbsp")
23577 ("iexcl")
23578 ("cent")
23579 ("pound")
23580 ("curren")
23581 ("yen")
23582 ("brvbar")
23583 ("vert" . "&#124;")
23584 ("sect")
23585 ("uml")
23586 ("copy")
23587 ("ordf")
23588 ("laquo")
23589 ("not")
23590 ("shy")
23591 ("reg")
23592 ("macr")
23593 ("deg")
23594 ("plusmn")
23595 ("sup2")
23596 ("sup3")
23597 ("acute")
23598 ("micro")
23599 ("para")
23600 ("middot")
23601 ("odot"."o")
23602 ("star"."*")
23603 ("cedil")
23604 ("sup1")
23605 ("ordm")
23606 ("raquo")
23607 ("frac14")
23608 ("frac12")
23609 ("frac34")
23610 ("iquest")
23611 ("Agrave")
23612 ("Aacute")
23613 ("Acirc")
23614 ("Atilde")
23615 ("Auml")
23616 ("Aring") ("AA"."&Aring;")
23617 ("AElig")
23618 ("Ccedil")
23619 ("Egrave")
23620 ("Eacute")
23621 ("Ecirc")
23622 ("Euml")
23623 ("Igrave")
23624 ("Iacute")
23625 ("Icirc")
23626 ("Iuml")
23627 ("ETH")
23628 ("Ntilde")
23629 ("Ograve")
23630 ("Oacute")
23631 ("Ocirc")
23632 ("Otilde")
23633 ("Ouml")
23634 ("times")
23635 ("Oslash")
23636 ("Ugrave")
23637 ("Uacute")
23638 ("Ucirc")
23639 ("Uuml")
23640 ("Yacute")
23641 ("THORN")
23642 ("szlig")
23643 ("agrave")
23644 ("aacute")
23645 ("acirc")
23646 ("atilde")
23647 ("auml")
23648 ("aring")
23649 ("aelig")
23650 ("ccedil")
23651 ("egrave")
23652 ("eacute")
23653 ("ecirc")
23654 ("euml")
23655 ("igrave")
23656 ("iacute")
23657 ("icirc")
23658 ("iuml")
23659 ("eth")
23660 ("ntilde")
23661 ("ograve")
23662 ("oacute")
23663 ("ocirc")
23664 ("otilde")
23665 ("ouml")
23666 ("divide")
23667 ("oslash")
23668 ("ugrave")
23669 ("uacute")
23670 ("ucirc")
23671 ("uuml")
23672 ("yacute")
23673 ("thorn")
23674 ("yuml")
23675 ("fnof")
23676 ("Alpha")
23677 ("Beta")
23678 ("Gamma")
23679 ("Delta")
23680 ("Epsilon")
23681 ("Zeta")
23682 ("Eta")
23683 ("Theta")
23684 ("Iota")
23685 ("Kappa")
23686 ("Lambda")
23687 ("Mu")
23688 ("Nu")
23689 ("Xi")
23690 ("Omicron")
23691 ("Pi")
23692 ("Rho")
23693 ("Sigma")
23694 ("Tau")
23695 ("Upsilon")
23696 ("Phi")
23697 ("Chi")
23698 ("Psi")
23699 ("Omega")
23700 ("alpha")
23701 ("beta")
23702 ("gamma")
23703 ("delta")
23704 ("epsilon")
23705 ("varepsilon"."&epsilon;")
23706 ("zeta")
23707 ("eta")
23708 ("theta")
23709 ("iota")
23710 ("kappa")
23711 ("lambda")
23712 ("mu")
23713 ("nu")
23714 ("xi")
23715 ("omicron")
23716 ("pi")
23717 ("rho")
23718 ("sigmaf") ("varsigma"."&sigmaf;")
23719 ("sigma")
23720 ("tau")
23721 ("upsilon")
23722 ("phi")
23723 ("chi")
23724 ("psi")
23725 ("omega")
23726 ("thetasym") ("vartheta"."&thetasym;")
23727 ("upsih")
23728 ("piv")
23729 ("bull") ("bullet"."&bull;")
23730 ("hellip") ("dots"."&hellip;")
23731 ("prime")
23732 ("Prime")
23733 ("oline")
23734 ("frasl")
23735 ("weierp")
23736 ("image")
23737 ("real")
23738 ("trade")
23739 ("alefsym")
23740 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
23741 ("uarr") ("uparrow"."&uarr;")
23742 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
23743 ("darr")("downarrow"."&darr;")
23744 ("harr") ("leftrightarrow"."&harr;")
23745 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
23746 ("lArr") ("Leftarrow"."&lArr;")
23747 ("uArr") ("Uparrow"."&uArr;")
23748 ("rArr") ("Rightarrow"."&rArr;")
23749 ("dArr") ("Downarrow"."&dArr;")
23750 ("hArr") ("Leftrightarrow"."&hArr;")
23751 ("forall")
23752 ("part") ("partial"."&part;")
23753 ("exist") ("exists"."&exist;")
23754 ("empty") ("emptyset"."&empty;")
23755 ("nabla")
23756 ("isin") ("in"."&isin;")
23757 ("notin")
23758 ("ni")
23759 ("prod")
23760 ("sum")
23761 ("minus")
23762 ("lowast") ("ast"."&lowast;")
23763 ("radic")
23764 ("prop") ("proptp"."&prop;")
23765 ("infin") ("infty"."&infin;")
23766 ("ang") ("angle"."&ang;")
23767 ("and") ("wedge"."&and;")
23768 ("or") ("vee"."&or;")
23769 ("cap")
23770 ("cup")
23771 ("int")
23772 ("there4")
23773 ("sim")
23774 ("cong") ("simeq"."&cong;")
23775 ("asymp")("approx"."&asymp;")
23776 ("ne") ("neq"."&ne;")
23777 ("equiv")
23778 ("le")
23779 ("ge")
23780 ("sub") ("subset"."&sub;")
23781 ("sup") ("supset"."&sup;")
23782 ("nsub")
23783 ("sube")
23784 ("supe")
23785 ("oplus")
23786 ("otimes")
23787 ("perp")
23788 ("sdot") ("cdot"."&sdot;")
23789 ("lceil")
23790 ("rceil")
23791 ("lfloor")
23792 ("rfloor")
23793 ("lang")
23794 ("rang")
23795 ("loz") ("Diamond"."&loz;")
23796 ("spades") ("spadesuit"."&spades;")
23797 ("clubs") ("clubsuit"."&clubs;")
23798 ("hearts") ("diamondsuit"."&hearts;")
23799 ("diams") ("diamondsuit"."&diams;")
23800 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
23801 ("quot")
23802 ("amp")
23803 ("lt")
23804 ("gt")
23805 ("OElig")
23806 ("oelig")
23807 ("Scaron")
23808 ("scaron")
23809 ("Yuml")
23810 ("circ")
23811 ("tilde")
23812 ("ensp")
23813 ("emsp")
23814 ("thinsp")
23815 ("zwnj")
23816 ("zwj")
23817 ("lrm")
23818 ("rlm")
23819 ("ndash")
23820 ("mdash")
23821 ("lsquo")
23822 ("rsquo")
23823 ("sbquo")
23824 ("ldquo")
23825 ("rdquo")
23826 ("bdquo")
23827 ("dagger")
23828 ("Dagger")
23829 ("permil")
23830 ("lsaquo")
23831 ("rsaquo")
23832 ("euro")
23834 ("arccos"."arccos")
23835 ("arcsin"."arcsin")
23836 ("arctan"."arctan")
23837 ("arg"."arg")
23838 ("cos"."cos")
23839 ("cosh"."cosh")
23840 ("cot"."cot")
23841 ("coth"."coth")
23842 ("csc"."csc")
23843 ("deg"."deg")
23844 ("det"."det")
23845 ("dim"."dim")
23846 ("exp"."exp")
23847 ("gcd"."gcd")
23848 ("hom"."hom")
23849 ("inf"."inf")
23850 ("ker"."ker")
23851 ("lg"."lg")
23852 ("lim"."lim")
23853 ("liminf"."liminf")
23854 ("limsup"."limsup")
23855 ("ln"."ln")
23856 ("log"."log")
23857 ("max"."max")
23858 ("min"."min")
23859 ("Pr"."Pr")
23860 ("sec"."sec")
23861 ("sin"."sin")
23862 ("sinh"."sinh")
23863 ("sup"."sup")
23864 ("tan"."tan")
23865 ("tanh"."tanh")
23867 "Entities for TeX->HTML translation.
23868 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
23869 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
23870 In that case, \"\\ent\" will be translated to \"&other;\".
23871 The list contains HTML entities for Latin-1, Greek and other symbols.
23872 It is supplemented by a number of commonly used TeX macros with appropriate
23873 translations. There is currently no way for users to extend this.")
23875 ;;; General functions for all backends
23877 (defun org-cleaned-string-for-export (string &rest parameters)
23878 "Cleanup a buffer STRING so that links can be created safely."
23879 (interactive)
23880 (let* ((re-radio (and org-target-link-regexp
23881 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
23882 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
23883 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
23884 (re-archive (concat ":" org-archive-tag ":"))
23885 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
23886 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
23887 (htmlp (plist-get parameters :for-html))
23888 (asciip (plist-get parameters :for-ascii))
23889 (latexp (plist-get parameters :for-LaTeX))
23890 (commentsp (plist-get parameters :comments))
23891 (archived-trees (plist-get parameters :archived-trees))
23892 (inhibit-read-only t)
23893 (drawers org-drawers)
23894 (exp-drawers (plist-get parameters :drawers))
23895 (outline-regexp "\\*+ ")
23896 a b xx
23897 rtn p)
23898 (with-current-buffer (get-buffer-create " org-mode-tmp")
23899 (erase-buffer)
23900 (insert string)
23901 ;; Remove license-to-kill stuff
23902 (while (setq p (text-property-any (point-min) (point-max)
23903 :org-license-to-kill t))
23904 (delete-region p (next-single-property-change p :org-license-to-kill)))
23906 (let ((org-inhibit-startup t)) (org-mode))
23907 (untabify (point-min) (point-max))
23909 ;; Get rid of drawers
23910 (unless (eq t exp-drawers)
23911 (goto-char (point-min))
23912 (let ((re (concat "^[ \t]*:\\("
23913 (mapconcat
23914 'identity
23915 (org-delete-all exp-drawers
23916 (copy-sequence drawers))
23917 "\\|")
23918 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
23919 (while (re-search-forward re nil t)
23920 (replace-match ""))))
23922 ;; Get the correct stuff before the first headline
23923 (when (plist-get parameters :skip-before-1st-heading)
23924 (goto-char (point-min))
23925 (when (re-search-forward "^\\*+[ \t]" nil t)
23926 (delete-region (point-min) (match-beginning 0))
23927 (goto-char (point-min))
23928 (insert "\n")))
23929 (when (plist-get parameters :add-text)
23930 (goto-char (point-min))
23931 (insert (plist-get parameters :add-text) "\n"))
23933 ;; Get rid of archived trees
23934 (when (not (eq archived-trees t))
23935 (goto-char (point-min))
23936 (while (re-search-forward re-archive nil t)
23937 (if (not (org-on-heading-p t))
23938 (org-end-of-subtree t)
23939 (beginning-of-line 1)
23940 (setq a (if archived-trees
23941 (1+ (point-at-eol)) (point))
23942 b (org-end-of-subtree t))
23943 (if (> b a) (delete-region a b)))))
23945 ;; Find targets in comments and move them out of comments,
23946 ;; but mark them as targets that should be invisible
23947 (goto-char (point-min))
23948 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
23949 (replace-match "\\1(INVISIBLE)"))
23951 ;; Protect backend specific stuff, throw away the others.
23952 (let ((formatters
23953 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
23954 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
23955 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
23956 fmt)
23957 (goto-char (point-min))
23958 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
23959 (goto-char (match-end 0))
23960 (while (not (looking-at "#\\+END_EXAMPLE"))
23961 (insert ": ")
23962 (beginning-of-line 2)))
23963 (goto-char (point-min))
23964 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
23965 (add-text-properties (match-beginning 0) (match-end 0)
23966 '(org-protected t)))
23967 (while formatters
23968 (setq fmt (pop formatters))
23969 (when (car fmt)
23970 (goto-char (point-min))
23971 (while (re-search-forward (concat "^#\\+" (cadr fmt)
23972 ":[ \t]*\\(.*\\)") nil t)
23973 (replace-match "\\1" t)
23974 (add-text-properties
23975 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
23976 '(org-protected t))))
23977 (goto-char (point-min))
23978 (while (re-search-forward
23979 (concat "^#\\+"
23980 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
23981 (cadddr fmt) "\\>.*\n?") nil t)
23982 (if (car fmt)
23983 (add-text-properties (match-beginning 1) (1+ (match-end 1))
23984 '(org-protected t))
23985 (delete-region (match-beginning 0) (match-end 0))))))
23987 ;; Protect quoted subtrees
23988 (goto-char (point-min))
23989 (while (re-search-forward re-quote nil t)
23990 (goto-char (match-beginning 0))
23991 (end-of-line 1)
23992 (add-text-properties (point) (org-end-of-subtree t)
23993 '(org-protected t)))
23995 ;; Protect verbatim elements
23996 (goto-char (point-min))
23997 (while (re-search-forward org-verbatim-re nil t)
23998 (add-text-properties (match-beginning 4) (match-end 4)
23999 '(org-protected t))
24000 (goto-char (1+ (match-end 4))))
24002 ;; Remove subtrees that are commented
24003 (goto-char (point-min))
24004 (while (re-search-forward re-commented nil t)
24005 (goto-char (match-beginning 0))
24006 (delete-region (point) (org-end-of-subtree t)))
24008 ;; Remove special table lines
24009 (when org-export-table-remove-special-lines
24010 (goto-char (point-min))
24011 (while (re-search-forward "^[ \t]*|" nil t)
24012 (beginning-of-line 1)
24013 (if (or (looking-at "[ \t]*| *[!_^] *|")
24014 (and (looking-at ".*?| *<[0-9]+> *|")
24015 (not (looking-at ".*?| *[^ <|]"))))
24016 (delete-region (max (point-min) (1- (point-at-bol)))
24017 (point-at-eol))
24018 (end-of-line 1))))
24020 ;; Specific LaTeX stuff
24021 (when latexp
24022 (require 'org-export-latex nil)
24023 (org-export-latex-cleaned-string))
24025 (when asciip
24026 (org-export-ascii-clean-string))
24028 ;; Specific HTML stuff
24029 (when htmlp
24030 ;; Convert LaTeX fragments to images
24031 (when (plist-get parameters :LaTeX-fragments)
24032 (org-format-latex
24033 (concat "ltxpng/" (file-name-sans-extension
24034 (file-name-nondirectory
24035 org-current-export-file)))
24036 org-current-export-dir nil "Creating LaTeX image %s"))
24037 (message "Exporting..."))
24039 ;; Remove or replace comments
24040 (goto-char (point-min))
24041 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
24042 (if commentsp
24043 (progn (add-text-properties
24044 (match-beginning 0) (match-end 0) '(org-protected t))
24045 (replace-match (format commentsp (match-string 1)) t t))
24046 (replace-match "")))
24048 ;; Find matches for radio targets and turn them into internal links
24049 (goto-char (point-min))
24050 (when re-radio
24051 (while (re-search-forward re-radio nil t)
24052 (org-if-unprotected
24053 (replace-match "\\1[[\\2]]"))))
24055 ;; Find all links that contain a newline and put them into a single line
24056 (goto-char (point-min))
24057 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
24058 (org-if-unprotected
24059 (replace-match "\\1 \\3")
24060 (goto-char (match-beginning 0))))
24063 ;; Normalize links: Convert angle and plain links into bracket links
24064 ;; Expand link abbreviations
24065 (goto-char (point-min))
24066 (while (re-search-forward re-plain-link nil t)
24067 (goto-char (1- (match-end 0)))
24068 (org-if-unprotected
24069 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24070 ":" (match-string 3) "]]")))
24071 ;; added 'org-link face to links
24072 (put-text-property 0 (length s) 'face 'org-link s)
24073 (replace-match s t t))))
24074 (goto-char (point-min))
24075 (while (re-search-forward re-angle-link nil t)
24076 (goto-char (1- (match-end 0)))
24077 (org-if-unprotected
24078 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24079 ":" (match-string 3) "]]")))
24080 (put-text-property 0 (length s) 'face 'org-link s)
24081 (replace-match s t t))))
24082 (goto-char (point-min))
24083 (while (re-search-forward org-bracket-link-regexp nil t)
24084 (org-if-unprotected
24085 (let* ((s (concat "[[" (setq xx (save-match-data
24086 (org-link-expand-abbrev (match-string 1))))
24088 (if (match-end 3)
24089 (match-string 2)
24090 (concat "[" xx "]"))
24091 "]")))
24092 (put-text-property 0 (length s) 'face 'org-link s)
24093 (replace-match s t t))))
24095 ;; Find multiline emphasis and put them into single line
24096 (when (plist-get parameters :emph-multiline)
24097 (goto-char (point-min))
24098 (while (re-search-forward org-emph-re nil t)
24099 (if (not (= (char-after (match-beginning 3))
24100 (char-after (match-beginning 4))))
24101 (org-if-unprotected
24102 (subst-char-in-region (match-beginning 0) (match-end 0)
24103 ?\n ?\ t)
24104 (goto-char (1- (match-end 0))))
24105 (goto-char (1+ (match-beginning 0))))))
24107 (setq rtn (buffer-string)))
24108 (kill-buffer " org-mode-tmp")
24109 rtn))
24111 (defun org-export-grab-title-from-buffer ()
24112 "Get a title for the current document, from looking at the buffer."
24113 (let ((inhibit-read-only t))
24114 (save-excursion
24115 (goto-char (point-min))
24116 (let ((end (save-excursion (outline-next-heading) (point))))
24117 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
24118 ;; Mark the line so that it will not be exported as normal text.
24119 (org-unmodified
24120 (add-text-properties (match-beginning 0) (match-end 0)
24121 (list :org-license-to-kill t)))
24122 ;; Return the title string
24123 (org-trim (match-string 0)))))))
24125 (defun org-export-get-title-from-subtree ()
24126 "Return subtree title and exclude it from export."
24127 (let (title (m (mark)))
24128 (save-excursion
24129 (goto-char (region-beginning))
24130 (when (and (org-at-heading-p)
24131 (>= (org-end-of-subtree t t) (region-end)))
24132 ;; This is a subtree, we take the title from the first heading
24133 (goto-char (region-beginning))
24134 (looking-at org-todo-line-regexp)
24135 (setq title (match-string 3))
24136 (org-unmodified
24137 (add-text-properties (point) (1+ (point-at-eol))
24138 (list :org-license-to-kill t)))))
24139 title))
24141 (defun org-solidify-link-text (s &optional alist)
24142 "Take link text and make a safe target out of it."
24143 (save-match-data
24144 (let* ((rtn
24145 (mapconcat
24146 'identity
24147 (org-split-string s "[ \t\r\n]+") "--"))
24148 (a (assoc rtn alist)))
24149 (or (cdr a) rtn))))
24151 (defun org-get-min-level (lines)
24152 "Get the minimum level in LINES."
24153 (let ((re "^\\(\\*+\\) ") l min)
24154 (catch 'exit
24155 (while (setq l (pop lines))
24156 (if (string-match re l)
24157 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24158 1)))
24160 ;; Variable holding the vector with section numbers
24161 (defvar org-section-numbers (make-vector org-level-max 0))
24163 (defun org-init-section-numbers ()
24164 "Initialize the vector for the section numbers."
24165 (let* ((level -1)
24166 (numbers (nreverse (org-split-string "" "\\.")))
24167 (depth (1- (length org-section-numbers)))
24168 (i depth) number-string)
24169 (while (>= i 0)
24170 (if (> i level)
24171 (aset org-section-numbers i 0)
24172 (setq number-string (or (car numbers) "0"))
24173 (if (string-match "\\`[A-Z]\\'" number-string)
24174 (aset org-section-numbers i
24175 (- (string-to-char number-string) ?A -1))
24176 (aset org-section-numbers i (string-to-number number-string)))
24177 (pop numbers))
24178 (setq i (1- i)))))
24180 (defun org-section-number (&optional level)
24181 "Return a string with the current section number.
24182 When LEVEL is non-nil, increase section numbers on that level."
24183 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
24184 (when level
24185 (when (> level -1)
24186 (aset org-section-numbers
24187 level (1+ (aref org-section-numbers level))))
24188 (setq idx (1+ level))
24189 (while (<= idx depth)
24190 (if (not (= idx 1))
24191 (aset org-section-numbers idx 0))
24192 (setq idx (1+ idx))))
24193 (setq idx 0)
24194 (while (<= idx depth)
24195 (setq n (aref org-section-numbers idx))
24196 (setq string (concat string (if (not (string= string "")) "." "")
24197 (int-to-string n)))
24198 (setq idx (1+ idx)))
24199 (save-match-data
24200 (if (string-match "\\`\\([@0]\\.\\)+" string)
24201 (setq string (replace-match "" t nil string)))
24202 (if (string-match "\\(\\.0\\)+\\'" string)
24203 (setq string (replace-match "" t nil string))))
24204 string))
24206 ;;; ASCII export
24208 (defvar org-last-level nil) ; dynamically scoped variable
24209 (defvar org-min-level nil) ; dynamically scoped variable
24210 (defvar org-levels-open nil) ; dynamically scoped parameter
24211 (defvar org-ascii-current-indentation nil) ; For communication
24213 (defun org-export-as-ascii (arg)
24214 "Export the outline as a pretty ASCII file.
24215 If there is an active region, export only the region.
24216 The prefix ARG specifies how many levels of the outline should become
24217 underlined headlines. The default is 3."
24218 (interactive "P")
24219 (setq-default org-todo-line-regexp org-todo-line-regexp)
24220 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24221 (org-infile-export-plist)))
24222 (region-p (org-region-active-p))
24223 (subtree-p
24224 (when region-p
24225 (save-excursion
24226 (goto-char (region-beginning))
24227 (and (org-at-heading-p)
24228 (>= (org-end-of-subtree t t) (region-end))))))
24229 (custom-times org-display-custom-times)
24230 (org-ascii-current-indentation '(0 . 0))
24231 (level 0) line txt
24232 (umax nil)
24233 (umax-toc nil)
24234 (case-fold-search nil)
24235 (filename (concat (file-name-as-directory
24236 (org-export-directory :ascii opt-plist))
24237 (file-name-sans-extension
24238 (or (and subtree-p
24239 (org-entry-get (region-beginning)
24240 "EXPORT_FILE_NAME" t))
24241 (file-name-nondirectory buffer-file-name)))
24242 ".txt"))
24243 (filename (if (equal (file-truename filename)
24244 (file-truename buffer-file-name))
24245 (concat filename ".txt")
24246 filename))
24247 (buffer (find-file-noselect filename))
24248 (org-levels-open (make-vector org-level-max nil))
24249 (odd org-odd-levels-only)
24250 (date (plist-get opt-plist :date))
24251 (author (plist-get opt-plist :author))
24252 (title (or (and subtree-p (org-export-get-title-from-subtree))
24253 (plist-get opt-plist :title)
24254 (and (not
24255 (plist-get opt-plist :skip-before-1st-heading))
24256 (org-export-grab-title-from-buffer))
24257 (file-name-sans-extension
24258 (file-name-nondirectory buffer-file-name))))
24259 (email (plist-get opt-plist :email))
24260 (language (plist-get opt-plist :language))
24261 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24262 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
24263 (todo nil)
24264 (lang-words nil)
24265 (region
24266 (buffer-substring
24267 (if (org-region-active-p) (region-beginning) (point-min))
24268 (if (org-region-active-p) (region-end) (point-max))))
24269 (lines (org-split-string
24270 (org-cleaned-string-for-export
24271 region
24272 :for-ascii t
24273 :skip-before-1st-heading
24274 (plist-get opt-plist :skip-before-1st-heading)
24275 :drawers (plist-get opt-plist :drawers)
24276 :verbatim-multiline t
24277 :archived-trees
24278 (plist-get opt-plist :archived-trees)
24279 :add-text (plist-get opt-plist :text))
24280 "\n"))
24281 thetoc have-headings first-heading-pos
24282 table-open table-buffer)
24284 (let ((inhibit-read-only t))
24285 (org-unmodified
24286 (remove-text-properties (point-min) (point-max)
24287 '(:org-license-to-kill t))))
24289 (setq org-min-level (org-get-min-level lines))
24290 (setq org-last-level org-min-level)
24291 (org-init-section-numbers)
24293 (find-file-noselect filename)
24295 (setq lang-words (or (assoc language org-export-language-setup)
24296 (assoc "en" org-export-language-setup)))
24297 (switch-to-buffer-other-window buffer)
24298 (erase-buffer)
24299 (fundamental-mode)
24300 ;; create local variables for all options, to make sure all called
24301 ;; functions get the correct information
24302 (mapc (lambda (x)
24303 (set (make-local-variable (cdr x))
24304 (plist-get opt-plist (car x))))
24305 org-export-plist-vars)
24306 (org-set-local 'org-odd-levels-only odd)
24307 (setq umax (if arg (prefix-numeric-value arg)
24308 org-export-headline-levels))
24309 (setq umax-toc (if (integerp org-export-with-toc)
24310 (min org-export-with-toc umax)
24311 umax))
24313 ;; File header
24314 (if title (org-insert-centered title ?=))
24315 (insert "\n")
24316 (if (and (or author email)
24317 org-export-author-info)
24318 (insert (concat (nth 1 lang-words) ": " (or author "")
24319 (if email (concat " <" email ">") "")
24320 "\n")))
24322 (cond
24323 ((and date (string-match "%" date))
24324 (setq date (format-time-string date (current-time))))
24325 (date)
24326 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24328 (if (and date org-export-time-stamp-file)
24329 (insert (concat (nth 2 lang-words) ": " date"\n")))
24331 (insert "\n\n")
24333 (if org-export-with-toc
24334 (progn
24335 (push (concat (nth 3 lang-words) "\n") thetoc)
24336 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
24337 (mapc '(lambda (line)
24338 (if (string-match org-todo-line-regexp
24339 line)
24340 ;; This is a headline
24341 (progn
24342 (setq have-headings t)
24343 (setq level (- (match-end 1) (match-beginning 1))
24344 level (org-tr-level level)
24345 txt (match-string 3 line)
24346 todo
24347 (or (and org-export-mark-todo-in-toc
24348 (match-beginning 2)
24349 (not (member (match-string 2 line)
24350 org-done-keywords)))
24351 ; TODO, not DONE
24352 (and org-export-mark-todo-in-toc
24353 (= level umax-toc)
24354 (org-search-todo-below
24355 line lines level))))
24356 (setq txt (org-html-expand-for-ascii txt))
24358 (while (string-match org-bracket-link-regexp txt)
24359 (setq txt
24360 (replace-match
24361 (match-string (if (match-end 2) 3 1) txt)
24362 t t txt)))
24364 (if (and (memq org-export-with-tags '(not-in-toc nil))
24365 (string-match
24366 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
24367 txt))
24368 (setq txt (replace-match "" t t txt)))
24369 (if (string-match quote-re0 txt)
24370 (setq txt (replace-match "" t t txt)))
24372 (if org-export-with-section-numbers
24373 (setq txt (concat (org-section-number level)
24374 " " txt)))
24375 (if (<= level umax-toc)
24376 (progn
24377 (push
24378 (concat
24379 (make-string
24380 (* (max 0 (- level org-min-level)) 4) ?\ )
24381 (format (if todo "%s (*)\n" "%s\n") txt))
24382 thetoc)
24383 (setq org-last-level level))
24384 ))))
24385 lines)
24386 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24388 (org-init-section-numbers)
24389 (while (setq line (pop lines))
24390 ;; Remove the quoted HTML tags.
24391 (setq line (org-html-expand-for-ascii line))
24392 ;; Remove targets
24393 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
24394 (setq line (replace-match "" t t line)))
24395 ;; Replace internal links
24396 (while (string-match org-bracket-link-regexp line)
24397 (setq line (replace-match
24398 (if (match-end 3) "[\\3]" "[\\1]")
24399 t nil line)))
24400 (when custom-times
24401 (setq line (org-translate-time line)))
24402 (cond
24403 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24404 ;; a Headline
24405 (setq first-heading-pos (or first-heading-pos (point)))
24406 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24407 txt (match-string 2 line))
24408 (org-ascii-level-start level txt umax lines))
24410 ((and org-export-with-tables
24411 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24412 (if (not table-open)
24413 ;; New table starts
24414 (setq table-open t table-buffer nil))
24415 ;; Accumulate lines
24416 (setq table-buffer (cons line table-buffer))
24417 (when (or (not lines)
24418 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24419 (car lines))))
24420 (setq table-open nil
24421 table-buffer (nreverse table-buffer))
24422 (insert (mapconcat
24423 (lambda (x)
24424 (org-fix-indentation x org-ascii-current-indentation))
24425 (org-format-table-ascii table-buffer)
24426 "\n") "\n")))
24428 (setq line (org-fix-indentation line org-ascii-current-indentation))
24429 (if (and org-export-with-fixed-width
24430 (string-match "^\\([ \t]*\\)\\(:\\)" line))
24431 (setq line (replace-match "\\1" nil nil line)))
24432 (insert line "\n"))))
24434 (normal-mode)
24436 ;; insert the table of contents
24437 (when thetoc
24438 (goto-char (point-min))
24439 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
24440 (progn
24441 (goto-char (match-beginning 0))
24442 (replace-match ""))
24443 (goto-char first-heading-pos))
24444 (mapc 'insert thetoc)
24445 (or (looking-at "[ \t]*\n[ \t]*\n")
24446 (insert "\n\n")))
24448 ;; Convert whitespace place holders
24449 (goto-char (point-min))
24450 (let (beg end)
24451 (while (setq beg (next-single-property-change (point) 'org-whitespace))
24452 (setq end (next-single-property-change beg 'org-whitespace))
24453 (goto-char beg)
24454 (delete-region beg end)
24455 (insert (make-string (- end beg) ?\ ))))
24457 (save-buffer)
24458 ;; remove display and invisible chars
24459 (let (beg end)
24460 (goto-char (point-min))
24461 (while (setq beg (next-single-property-change (point) 'display))
24462 (setq end (next-single-property-change beg 'display))
24463 (delete-region beg end)
24464 (goto-char beg)
24465 (insert "=>"))
24466 (goto-char (point-min))
24467 (while (setq beg (next-single-property-change (point) 'org-cwidth))
24468 (setq end (next-single-property-change beg 'org-cwidth))
24469 (delete-region beg end)
24470 (goto-char beg)))
24471 (goto-char (point-min))))
24473 (defun org-export-ascii-clean-string ()
24474 "Do extra work for ASCII export"
24475 (goto-char (point-min))
24476 (while (re-search-forward org-verbatim-re nil t)
24477 (goto-char (match-end 2))
24478 (backward-delete-char 1) (insert "'")
24479 (goto-char (match-beginning 2))
24480 (delete-char 1) (insert "`")
24481 (goto-char (match-end 2))))
24483 (defun org-search-todo-below (line lines level)
24484 "Search the subtree below LINE for any TODO entries."
24485 (let ((rest (cdr (memq line lines)))
24486 (re org-todo-line-regexp)
24487 line lv todo)
24488 (catch 'exit
24489 (while (setq line (pop rest))
24490 (if (string-match re line)
24491 (progn
24492 (setq lv (- (match-end 1) (match-beginning 1))
24493 todo (and (match-beginning 2)
24494 (not (member (match-string 2 line)
24495 org-done-keywords))))
24496 ; TODO, not DONE
24497 (if (<= lv level) (throw 'exit nil))
24498 (if todo (throw 'exit t))))))))
24500 (defun org-html-expand-for-ascii (line)
24501 "Handle quoted HTML for ASCII export."
24502 (if org-export-html-expand
24503 (while (string-match "@<[^<>\n]*>" line)
24504 ;; We just remove the tags for now.
24505 (setq line (replace-match "" nil nil line))))
24506 line)
24508 (defun org-insert-centered (s &optional underline)
24509 "Insert the string S centered and underline it with character UNDERLINE."
24510 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
24511 (insert (make-string ind ?\ ) s "\n")
24512 (if underline
24513 (insert (make-string ind ?\ )
24514 (make-string (string-width s) underline)
24515 "\n"))))
24517 (defun org-ascii-level-start (level title umax &optional lines)
24518 "Insert a new level in ASCII export."
24519 (let (char (n (- level umax 1)) (ind 0))
24520 (if (> level umax)
24521 (progn
24522 (insert (make-string (* 2 n) ?\ )
24523 (char-to-string (nth (% n (length org-export-ascii-bullets))
24524 org-export-ascii-bullets))
24525 " " title "\n")
24526 ;; find the indentation of the next non-empty line
24527 (catch 'stop
24528 (while lines
24529 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
24530 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
24531 (throw 'stop (setq ind (org-get-indentation (car lines)))))
24532 (pop lines)))
24533 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
24534 (if (or (not (equal (char-before) ?\n))
24535 (not (equal (char-before (1- (point))) ?\n)))
24536 (insert "\n"))
24537 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
24538 (unless org-export-with-tags
24539 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
24540 (setq title (replace-match "" t t title))))
24541 (if org-export-with-section-numbers
24542 (setq title (concat (org-section-number level) " " title)))
24543 (insert title "\n" (make-string (string-width title) char) "\n")
24544 (setq org-ascii-current-indentation '(0 . 0)))))
24546 (defun org-export-visible (type arg)
24547 "Create a copy of the visible part of the current buffer, and export it.
24548 The copy is created in a temporary buffer and removed after use.
24549 TYPE is the final key (as a string) that also select the export command in
24550 the `C-c C-e' export dispatcher.
24551 As a special case, if the you type SPC at the prompt, the temporary
24552 org-mode file will not be removed but presented to you so that you can
24553 continue to use it. The prefix arg ARG is passed through to the exporting
24554 command."
24555 (interactive
24556 (list (progn
24557 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
24558 (read-char-exclusive))
24559 current-prefix-arg))
24560 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
24561 (error "Invalid export key"))
24562 (let* ((binding (cdr (assoc type
24563 '((?a . org-export-as-ascii)
24564 (?\C-a . org-export-as-ascii)
24565 (?b . org-export-as-html-and-open)
24566 (?\C-b . org-export-as-html-and-open)
24567 (?h . org-export-as-html)
24568 (?H . org-export-as-html-to-buffer)
24569 (?R . org-export-region-as-html)
24570 (?x . org-export-as-xoxo)))))
24571 (keepp (equal type ?\ ))
24572 (file buffer-file-name)
24573 (buffer (get-buffer-create "*Org Export Visible*"))
24574 s e)
24575 ;; Need to hack the drawers here.
24576 (save-excursion
24577 (goto-char (point-min))
24578 (while (re-search-forward org-drawer-regexp nil t)
24579 (goto-char (match-beginning 1))
24580 (or (org-invisible-p) (org-flag-drawer nil))))
24581 (with-current-buffer buffer (erase-buffer))
24582 (save-excursion
24583 (setq s (goto-char (point-min)))
24584 (while (not (= (point) (point-max)))
24585 (goto-char (org-find-invisible))
24586 (append-to-buffer buffer s (point))
24587 (setq s (goto-char (org-find-visible))))
24588 (org-cycle-hide-drawers 'all)
24589 (goto-char (point-min))
24590 (unless keepp
24591 ;; Copy all comment lines to the end, to make sure #+ settings are
24592 ;; still available for the second export step. Kind of a hack, but
24593 ;; does do the trick.
24594 (if (looking-at "#[^\r\n]*")
24595 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
24596 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
24597 (append-to-buffer buffer (1+ (match-beginning 0))
24598 (min (point-max) (1+ (match-end 0))))))
24599 (set-buffer buffer)
24600 (let ((buffer-file-name file)
24601 (org-inhibit-startup t))
24602 (org-mode)
24603 (show-all)
24604 (unless keepp (funcall binding arg))))
24605 (if (not keepp)
24606 (kill-buffer buffer)
24607 (switch-to-buffer-other-window buffer)
24608 (goto-char (point-min)))))
24610 (defun org-find-visible ()
24611 (let ((s (point)))
24612 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24613 (get-char-property s 'invisible)))
24615 (defun org-find-invisible ()
24616 (let ((s (point)))
24617 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24618 (not (get-char-property s 'invisible))))
24621 ;;; HTML export
24623 (defun org-get-current-options ()
24624 "Return a string with current options as keyword options.
24625 Does include HTML export options as well as TODO and CATEGORY stuff."
24626 (format
24627 "#+TITLE: %s
24628 #+AUTHOR: %s
24629 #+EMAIL: %s
24630 #+LANGUAGE: %s
24631 #+TEXT: Some descriptive text to be emitted. Several lines OK.
24632 #+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
24633 #+CATEGORY: %s
24634 #+SEQ_TODO: %s
24635 #+TYP_TODO: %s
24636 #+PRIORITIES: %c %c %c
24637 #+DRAWERS: %s
24638 #+STARTUP: %s %s %s %s %s
24639 #+TAGS: %s
24640 #+ARCHIVE: %s
24641 #+LINK: %s
24643 (buffer-name) (user-full-name) user-mail-address org-export-default-language
24644 org-export-headline-levels
24645 org-export-with-section-numbers
24646 org-export-with-toc
24647 org-export-preserve-breaks
24648 org-export-html-expand
24649 org-export-with-fixed-width
24650 org-export-with-tables
24651 org-export-with-sub-superscripts
24652 org-export-with-special-strings
24653 org-export-with-footnotes
24654 org-export-with-emphasize
24655 org-export-with-TeX-macros
24656 org-export-with-LaTeX-fragments
24657 org-export-skip-text-before-1st-heading
24658 org-export-with-drawers
24659 org-export-with-tags
24660 (file-name-nondirectory buffer-file-name)
24661 "TODO FEEDBACK VERIFY DONE"
24662 "Me Jason Marie DONE"
24663 org-highest-priority org-lowest-priority org-default-priority
24664 (mapconcat 'identity org-drawers " ")
24665 (cdr (assoc org-startup-folded
24666 '((nil . "showall") (t . "overview") (content . "content"))))
24667 (if org-odd-levels-only "odd" "oddeven")
24668 (if org-hide-leading-stars "hidestars" "showstars")
24669 (if org-startup-align-all-tables "align" "noalign")
24670 (cond ((eq t org-log-done) "logdone")
24671 ((not org-log-done) "nologging")
24672 ((listp org-log-done)
24673 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
24674 org-log-done " ")))
24675 (or (mapconcat (lambda (x)
24676 (cond
24677 ((equal '(:startgroup) x) "{")
24678 ((equal '(:endgroup) x) "}")
24679 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
24680 (t (car x))))
24681 (or org-tag-alist (org-get-buffer-tags)) " ") "")
24682 org-archive-location
24683 "org file:~/org/%s.org"
24686 (defun org-insert-export-options-template ()
24687 "Insert into the buffer a template with information for exporting."
24688 (interactive)
24689 (if (not (bolp)) (newline))
24690 (let ((s (org-get-current-options)))
24691 (and (string-match "#\\+CATEGORY" s)
24692 (setq s (substring s 0 (match-beginning 0))))
24693 (insert s)))
24695 (defun org-toggle-fixed-width-section (arg)
24696 "Toggle the fixed-width export.
24697 If there is no active region, the QUOTE keyword at the current headline is
24698 inserted or removed. When present, it causes the text between this headline
24699 and the next to be exported as fixed-width text, and unmodified.
24700 If there is an active region, this command adds or removes a colon as the
24701 first character of this line. If the first character of a line is a colon,
24702 this line is also exported in fixed-width font."
24703 (interactive "P")
24704 (let* ((cc 0)
24705 (regionp (org-region-active-p))
24706 (beg (if regionp (region-beginning) (point)))
24707 (end (if regionp (region-end)))
24708 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
24709 (case-fold-search nil)
24710 (re "[ \t]*\\(:\\)")
24711 off)
24712 (if regionp
24713 (save-excursion
24714 (goto-char beg)
24715 (setq cc (current-column))
24716 (beginning-of-line 1)
24717 (setq off (looking-at re))
24718 (while (> nlines 0)
24719 (setq nlines (1- nlines))
24720 (beginning-of-line 1)
24721 (cond
24722 (arg
24723 (move-to-column cc t)
24724 (insert ":\n")
24725 (forward-line -1))
24726 ((and off (looking-at re))
24727 (replace-match "" t t nil 1))
24728 ((not off) (move-to-column cc t) (insert ":")))
24729 (forward-line 1)))
24730 (save-excursion
24731 (org-back-to-heading)
24732 (if (looking-at (concat outline-regexp
24733 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
24734 (replace-match "" t t nil 1)
24735 (if (looking-at outline-regexp)
24736 (progn
24737 (goto-char (match-end 0))
24738 (insert org-quote-string " "))))))))
24740 (defun org-export-as-html-and-open (arg)
24741 "Export the outline as HTML and immediately open it with a browser.
24742 If there is an active region, export only the region.
24743 The prefix ARG specifies how many levels of the outline should become
24744 headlines. The default is 3. Lower levels will become bulleted lists."
24745 (interactive "P")
24746 (org-export-as-html arg 'hidden)
24747 (org-open-file buffer-file-name))
24749 (defun org-export-as-html-batch ()
24750 "Call `org-export-as-html', may be used in batch processing as
24751 emacs --batch
24752 --load=$HOME/lib/emacs/org.el
24753 --eval \"(setq org-export-headline-levels 2)\"
24754 --visit=MyFile --funcall org-export-as-html-batch"
24755 (org-export-as-html org-export-headline-levels 'hidden))
24757 (defun org-export-as-html-to-buffer (arg)
24758 "Call `org-exort-as-html` with output to a temporary buffer.
24759 No file is created. The prefix ARG is passed through to `org-export-as-html'."
24760 (interactive "P")
24761 (org-export-as-html arg nil nil "*Org HTML Export*")
24762 (switch-to-buffer-other-window "*Org HTML Export*"))
24764 (defun org-replace-region-by-html (beg end)
24765 "Assume the current region has org-mode syntax, and convert it to HTML.
24766 This can be used in any buffer. For example, you could write an
24767 itemized list in org-mode syntax in an HTML buffer and then use this
24768 command to convert it."
24769 (interactive "r")
24770 (let (reg html buf pop-up-frames)
24771 (save-window-excursion
24772 (if (org-mode-p)
24773 (setq html (org-export-region-as-html
24774 beg end t 'string))
24775 (setq reg (buffer-substring beg end)
24776 buf (get-buffer-create "*Org tmp*"))
24777 (with-current-buffer buf
24778 (erase-buffer)
24779 (insert reg)
24780 (org-mode)
24781 (setq html (org-export-region-as-html
24782 (point-min) (point-max) t 'string)))
24783 (kill-buffer buf)))
24784 (delete-region beg end)
24785 (insert html)))
24787 (defun org-export-region-as-html (beg end &optional body-only buffer)
24788 "Convert region from BEG to END in org-mode buffer to HTML.
24789 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
24790 contents, and only produce the region of converted text, useful for
24791 cut-and-paste operations.
24792 If BUFFER is a buffer or a string, use/create that buffer as a target
24793 of the converted HTML. If BUFFER is the symbol `string', return the
24794 produced HTML as a string and leave not buffer behind. For example,
24795 a Lisp program could call this function in the following way:
24797 (setq html (org-export-region-as-html beg end t 'string))
24799 When called interactively, the output buffer is selected, and shown
24800 in a window. A non-interactive call will only retunr the buffer."
24801 (interactive "r\nP")
24802 (when (interactive-p)
24803 (setq buffer "*Org HTML Export*"))
24804 (let ((transient-mark-mode t) (zmacs-regions t)
24805 rtn)
24806 (goto-char end)
24807 (set-mark (point)) ;; to activate the region
24808 (goto-char beg)
24809 (setq rtn (org-export-as-html
24810 nil nil nil
24811 buffer body-only))
24812 (if (fboundp 'deactivate-mark) (deactivate-mark))
24813 (if (and (interactive-p) (bufferp rtn))
24814 (switch-to-buffer-other-window rtn)
24815 rtn)))
24817 (defvar html-table-tag nil) ; dynamically scoped into this.
24818 (defun org-export-as-html (arg &optional hidden ext-plist
24819 to-buffer body-only)
24820 "Export the outline as a pretty HTML file.
24821 If there is an active region, export only the region. The prefix
24822 ARG specifies how many levels of the outline should become
24823 headlines. The default is 3. Lower levels will become bulleted
24824 lists. When HIDDEN is non-nil, don't display the HTML buffer.
24825 EXT-PLIST is a property list with external parameters overriding
24826 org-mode's default settings, but still inferior to file-local
24827 settings. When TO-BUFFER is non-nil, create a buffer with that
24828 name and export to that buffer. If TO-BUFFER is the symbol `string',
24829 don't leave any buffer behind but just return the resulting HTML as
24830 a string. When BODY-ONLY is set, don't produce the file header and footer,
24831 simply return the content of <body>...</body>, without even
24832 the body tags themselves."
24833 (interactive "P")
24835 ;; Make sure we have a file name when we need it.
24836 (when (and (not (or to-buffer body-only))
24837 (not buffer-file-name))
24838 (if (buffer-base-buffer)
24839 (org-set-local 'buffer-file-name
24840 (with-current-buffer (buffer-base-buffer)
24841 buffer-file-name))
24842 (error "Need a file name to be able to export.")))
24844 (message "Exporting...")
24845 (setq-default org-todo-line-regexp org-todo-line-regexp)
24846 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
24847 (setq-default org-done-keywords org-done-keywords)
24848 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
24849 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24850 ext-plist
24851 (org-infile-export-plist)))
24853 (style (plist-get opt-plist :style))
24854 (link-validate (plist-get opt-plist :link-validation-function))
24855 valid thetoc have-headings first-heading-pos
24856 (odd org-odd-levels-only)
24857 (region-p (org-region-active-p))
24858 (subtree-p
24859 (when region-p
24860 (save-excursion
24861 (goto-char (region-beginning))
24862 (and (org-at-heading-p)
24863 (>= (org-end-of-subtree t t) (region-end))))))
24864 ;; The following two are dynamically scoped into other
24865 ;; routines below.
24866 (org-current-export-dir (org-export-directory :html opt-plist))
24867 (org-current-export-file buffer-file-name)
24868 (level 0) (line "") (origline "") txt todo
24869 (umax nil)
24870 (umax-toc nil)
24871 (filename (if to-buffer nil
24872 (expand-file-name
24873 (concat
24874 (file-name-sans-extension
24875 (or (and subtree-p
24876 (org-entry-get (region-beginning)
24877 "EXPORT_FILE_NAME" t))
24878 (file-name-nondirectory buffer-file-name)))
24879 "." org-export-html-extension)
24880 (file-name-as-directory
24881 (org-export-directory :html opt-plist)))))
24882 (current-dir (if buffer-file-name
24883 (file-name-directory buffer-file-name)
24884 default-directory))
24885 (buffer (if to-buffer
24886 (cond
24887 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
24888 (t (get-buffer-create to-buffer)))
24889 (find-file-noselect filename)))
24890 (org-levels-open (make-vector org-level-max nil))
24891 (date (plist-get opt-plist :date))
24892 (author (plist-get opt-plist :author))
24893 (title (or (and subtree-p (org-export-get-title-from-subtree))
24894 (plist-get opt-plist :title)
24895 (and (not
24896 (plist-get opt-plist :skip-before-1st-heading))
24897 (org-export-grab-title-from-buffer))
24898 (and buffer-file-name
24899 (file-name-sans-extension
24900 (file-name-nondirectory buffer-file-name)))
24901 "UNTITLED"))
24902 (html-table-tag (plist-get opt-plist :html-table-tag))
24903 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24904 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
24905 (inquote nil)
24906 (infixed nil)
24907 (in-local-list nil)
24908 (local-list-num nil)
24909 (local-list-indent nil)
24910 (llt org-plain-list-ordered-item-terminator)
24911 (email (plist-get opt-plist :email))
24912 (language (plist-get opt-plist :language))
24913 (lang-words nil)
24914 (target-alist nil) tg
24915 (head-count 0) cnt
24916 (start 0)
24917 (coding-system (and (boundp 'buffer-file-coding-system)
24918 buffer-file-coding-system))
24919 (coding-system-for-write (or org-export-html-coding-system
24920 coding-system))
24921 (save-buffer-coding-system (or org-export-html-coding-system
24922 coding-system))
24923 (charset (and coding-system-for-write
24924 (fboundp 'coding-system-get)
24925 (coding-system-get coding-system-for-write
24926 'mime-charset)))
24927 (region
24928 (buffer-substring
24929 (if region-p (region-beginning) (point-min))
24930 (if region-p (region-end) (point-max))))
24931 (lines
24932 (org-split-string
24933 (org-cleaned-string-for-export
24934 region
24935 :emph-multiline t
24936 :for-html t
24937 :skip-before-1st-heading
24938 (plist-get opt-plist :skip-before-1st-heading)
24939 :drawers (plist-get opt-plist :drawers)
24940 :archived-trees
24941 (plist-get opt-plist :archived-trees)
24942 :add-text
24943 (plist-get opt-plist :text)
24944 :LaTeX-fragments
24945 (plist-get opt-plist :LaTeX-fragments))
24946 "[\r\n]"))
24947 table-open type
24948 table-buffer table-orig-buffer
24949 ind start-is-num starter didclose
24950 rpl path desc descp desc1 desc2 link
24953 (let ((inhibit-read-only t))
24954 (org-unmodified
24955 (remove-text-properties (point-min) (point-max)
24956 '(:org-license-to-kill t))))
24958 (message "Exporting...")
24960 (setq org-min-level (org-get-min-level lines))
24961 (setq org-last-level org-min-level)
24962 (org-init-section-numbers)
24964 (cond
24965 ((and date (string-match "%" date))
24966 (setq date (format-time-string date (current-time))))
24967 (date)
24968 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24970 ;; Get the language-dependent settings
24971 (setq lang-words (or (assoc language org-export-language-setup)
24972 (assoc "en" org-export-language-setup)))
24974 ;; Switch to the output buffer
24975 (set-buffer buffer)
24976 (let ((inhibit-read-only t)) (erase-buffer))
24977 (fundamental-mode)
24979 (and (fboundp 'set-buffer-file-coding-system)
24980 (set-buffer-file-coding-system coding-system-for-write))
24982 (let ((case-fold-search nil)
24983 (org-odd-levels-only odd))
24984 ;; create local variables for all options, to make sure all called
24985 ;; functions get the correct information
24986 (mapc (lambda (x)
24987 (set (make-local-variable (cdr x))
24988 (plist-get opt-plist (car x))))
24989 org-export-plist-vars)
24990 (setq umax (if arg (prefix-numeric-value arg)
24991 org-export-headline-levels))
24992 (setq umax-toc (if (integerp org-export-with-toc)
24993 (min org-export-with-toc umax)
24994 umax))
24995 (unless body-only
24996 ;; File header
24997 (insert (format
24998 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
24999 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
25000 <html xmlns=\"http://www.w3.org/1999/xhtml\"
25001 lang=\"%s\" xml:lang=\"%s\">
25002 <head>
25003 <title>%s</title>
25004 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
25005 <meta name=\"generator\" content=\"Org-mode\"/>
25006 <meta name=\"generated\" content=\"%s\"/>
25007 <meta name=\"author\" content=\"%s\"/>
25009 </head><body>
25011 language language (org-html-expand title)
25012 (or charset "iso-8859-1") date author style))
25014 (insert (or (plist-get opt-plist :preamble) ""))
25016 (when (plist-get opt-plist :auto-preamble)
25017 (if title (insert (format org-export-html-title-format
25018 (org-html-expand title))))))
25020 (if (and org-export-with-toc (not body-only))
25021 (progn
25022 (push (format "<h%d>%s</h%d>\n"
25023 org-export-html-toplevel-hlevel
25024 (nth 3 lang-words)
25025 org-export-html-toplevel-hlevel)
25026 thetoc)
25027 (push "<ul>\n<li>" thetoc)
25028 (setq lines
25029 (mapcar '(lambda (line)
25030 (if (string-match org-todo-line-regexp line)
25031 ;; This is a headline
25032 (progn
25033 (setq have-headings t)
25034 (setq level (- (match-end 1) (match-beginning 1))
25035 level (org-tr-level level)
25036 txt (save-match-data
25037 (org-html-expand
25038 (org-export-cleanup-toc-line
25039 (match-string 3 line))))
25040 todo
25041 (or (and org-export-mark-todo-in-toc
25042 (match-beginning 2)
25043 (not (member (match-string 2 line)
25044 org-done-keywords)))
25045 ; TODO, not DONE
25046 (and org-export-mark-todo-in-toc
25047 (= level umax-toc)
25048 (org-search-todo-below
25049 line lines level))))
25050 (if (string-match
25051 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
25052 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
25053 (if (string-match quote-re0 txt)
25054 (setq txt (replace-match "" t t txt)))
25055 (if org-export-with-section-numbers
25056 (setq txt (concat (org-section-number level)
25057 " " txt)))
25058 (if (<= level (max umax umax-toc))
25059 (setq head-count (+ head-count 1)))
25060 (if (<= level umax-toc)
25061 (progn
25062 (if (> level org-last-level)
25063 (progn
25064 (setq cnt (- level org-last-level))
25065 (while (>= (setq cnt (1- cnt)) 0)
25066 (push "\n<ul>\n<li>" thetoc))
25067 (push "\n" thetoc)))
25068 (if (< level org-last-level)
25069 (progn
25070 (setq cnt (- org-last-level level))
25071 (while (>= (setq cnt (1- cnt)) 0)
25072 (push "</li>\n</ul>" thetoc))
25073 (push "\n" thetoc)))
25074 ;; Check for targets
25075 (while (string-match org-target-regexp line)
25076 (setq tg (match-string 1 line)
25077 line (replace-match
25078 (concat "@<span class=\"target\">" tg "@</span> ")
25079 t t line))
25080 (push (cons (org-solidify-link-text tg)
25081 (format "sec-%d" head-count))
25082 target-alist))
25083 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
25084 (setq txt (replace-match "" t t txt)))
25085 (push
25086 (format
25087 (if todo
25088 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
25089 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
25090 head-count txt) thetoc)
25092 (setq org-last-level level))
25094 line)
25095 lines))
25096 (while (> org-last-level (1- org-min-level))
25097 (setq org-last-level (1- org-last-level))
25098 (push "</li>\n</ul>\n" thetoc))
25099 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25101 (setq head-count 0)
25102 (org-init-section-numbers)
25104 (while (setq line (pop lines) origline line)
25105 (catch 'nextline
25107 ;; end of quote section?
25108 (when (and inquote (string-match "^\\*+ " line))
25109 (insert "</pre>\n")
25110 (setq inquote nil))
25111 ;; inside a quote section?
25112 (when inquote
25113 (insert (org-html-protect line) "\n")
25114 (throw 'nextline nil))
25116 ;; verbatim lines
25117 (when (and org-export-with-fixed-width
25118 (string-match "^[ \t]*:\\(.*\\)" line))
25119 (when (not infixed)
25120 (setq infixed t)
25121 (insert "<pre>\n"))
25122 (insert (org-html-protect (match-string 1 line)) "\n")
25123 (when (and lines
25124 (not (string-match "^[ \t]*\\(:.*\\)"
25125 (car lines))))
25126 (setq infixed nil)
25127 (insert "</pre>\n"))
25128 (throw 'nextline nil))
25130 ;; Protected HTML
25131 (when (get-text-property 0 'org-protected line)
25132 (let (par)
25133 (when (re-search-backward
25134 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
25135 (setq par (match-string 1))
25136 (replace-match "\\2\n"))
25137 (insert line "\n")
25138 (while (and lines
25139 (or (= (length (car lines)) 0)
25140 (get-text-property 0 'org-protected (car lines))))
25141 (insert (pop lines) "\n"))
25142 (and par (insert "<p>\n")))
25143 (throw 'nextline nil))
25145 ;; Horizontal line
25146 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
25147 (insert "\n<hr/>\n")
25148 (throw 'nextline nil))
25150 ;; make targets to anchors
25151 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
25152 (cond
25153 ((match-end 2)
25154 (setq line (replace-match
25155 (concat "@<a name=\""
25156 (org-solidify-link-text (match-string 1 line))
25157 "\">\\nbsp@</a>")
25158 t t line)))
25159 ((and org-export-with-toc (equal (string-to-char line) ?*))
25160 (setq line (replace-match
25161 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
25162 ; (concat "@<i>" (match-string 1 line) "@</i> ")
25163 t t line)))
25165 (setq line (replace-match
25166 (concat "@<a name=\""
25167 (org-solidify-link-text (match-string 1 line))
25168 "\" class=\"target\">" (match-string 1 line) "@</a> ")
25169 t t line)))))
25171 (setq line (org-html-handle-time-stamps line))
25173 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
25174 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
25175 ;; Also handle sub_superscripts and checkboxes
25176 (or (string-match org-table-hline-regexp line)
25177 (setq line (org-html-expand line)))
25179 ;; Format the links
25180 (setq start 0)
25181 (while (string-match org-bracket-link-analytic-regexp line start)
25182 (setq start (match-beginning 0))
25183 (setq type (if (match-end 2) (match-string 2 line) "internal"))
25184 (setq path (match-string 3 line))
25185 (setq desc1 (if (match-end 5) (match-string 5 line))
25186 desc2 (if (match-end 2) (concat type ":" path) path)
25187 descp (and desc1 (not (equal desc1 desc2)))
25188 desc (or desc1 desc2))
25189 ;; Make an image out of the description if that is so wanted
25190 (when (and descp (org-file-image-p desc))
25191 (save-match-data
25192 (if (string-match "^file:" desc)
25193 (setq desc (substring desc (match-end 0)))))
25194 (setq desc (concat "<img src=\"" desc "\"/>")))
25195 ;; FIXME: do we need to unescape here somewhere?
25196 (cond
25197 ((equal type "internal")
25198 (setq rpl
25199 (concat
25200 "<a href=\"#"
25201 (org-solidify-link-text
25202 (save-match-data (org-link-unescape path)) target-alist)
25203 "\">" desc "</a>")))
25204 ((member type '("http" "https"))
25205 ;; standard URL, just check if we need to inline an image
25206 (if (and (or (eq t org-export-html-inline-images)
25207 (and org-export-html-inline-images (not descp)))
25208 (org-file-image-p path))
25209 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
25210 (setq link (concat type ":" path))
25211 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
25212 ((member type '("ftp" "mailto" "news"))
25213 ;; standard URL
25214 (setq link (concat type ":" path))
25215 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
25216 ((string= type "file")
25217 ;; FILE link
25218 (let* ((filename path)
25219 (abs-p (file-name-absolute-p filename))
25220 thefile file-is-image-p search)
25221 (save-match-data
25222 (if (string-match "::\\(.*\\)" filename)
25223 (setq search (match-string 1 filename)
25224 filename (replace-match "" t nil filename)))
25225 (setq valid
25226 (if (functionp link-validate)
25227 (funcall link-validate filename current-dir)
25229 (setq file-is-image-p (org-file-image-p filename))
25230 (setq thefile (if abs-p (expand-file-name filename) filename))
25231 (when (and org-export-html-link-org-files-as-html
25232 (string-match "\\.org$" thefile))
25233 (setq thefile (concat (substring thefile 0
25234 (match-beginning 0))
25235 "." org-export-html-extension))
25236 (if (and search
25237 ;; make sure this is can be used as target search
25238 (not (string-match "^[0-9]*$" search))
25239 (not (string-match "^\\*" search))
25240 (not (string-match "^/.*/$" search)))
25241 (setq thefile (concat thefile "#"
25242 (org-solidify-link-text
25243 (org-link-unescape search)))))
25244 (when (string-match "^file:" desc)
25245 (setq desc (replace-match "" t t desc))
25246 (if (string-match "\\.org$" desc)
25247 (setq desc (replace-match "" t t desc))))))
25248 (setq rpl (if (and file-is-image-p
25249 (or (eq t org-export-html-inline-images)
25250 (and org-export-html-inline-images
25251 (not descp))))
25252 (concat "<img src=\"" thefile "\"/>")
25253 (concat "<a href=\"" thefile "\">" desc "</a>")))
25254 (if (not valid) (setq rpl desc))))
25255 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
25256 (setq rpl (concat "<i>&lt;" type ":"
25257 (save-match-data (org-link-unescape path))
25258 "&gt;</i>"))))
25259 (setq line (replace-match rpl t t line)
25260 start (+ start (length rpl))))
25262 ;; TODO items
25263 (if (and (string-match org-todo-line-regexp line)
25264 (match-beginning 2))
25266 (setq line
25267 (concat (substring line 0 (match-beginning 2))
25268 "<span class=\""
25269 (if (member (match-string 2 line)
25270 org-done-keywords)
25271 "done" "todo")
25272 "\">" (match-string 2 line)
25273 "</span>" (substring line (match-end 2)))))
25275 ;; Does this contain a reference to a footnote?
25276 (when org-export-with-footnotes
25277 (setq start 0)
25278 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
25279 (if (get-text-property (match-beginning 2) 'org-protected line)
25280 (setq start (match-end 2))
25281 (let ((n (match-string 2 line)))
25282 (setq line
25283 (replace-match
25284 (format
25285 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
25286 (match-string 1 line) n n n)
25287 t t line))))))
25289 (cond
25290 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25291 ;; This is a headline
25292 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25293 txt (match-string 2 line))
25294 (if (string-match quote-re0 txt)
25295 (setq txt (replace-match "" t t txt)))
25296 (if (<= level (max umax umax-toc))
25297 (setq head-count (+ head-count 1)))
25298 (when in-local-list
25299 ;; Close any local lists before inserting a new header line
25300 (while local-list-num
25301 (org-close-li)
25302 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25303 (pop local-list-num))
25304 (setq local-list-indent nil
25305 in-local-list nil))
25306 (setq first-heading-pos (or first-heading-pos (point)))
25307 (org-html-level-start level txt umax
25308 (and org-export-with-toc (<= level umax))
25309 head-count)
25310 ;; QUOTES
25311 (when (string-match quote-re line)
25312 (insert "<pre>")
25313 (setq inquote t)))
25315 ((and org-export-with-tables
25316 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25317 (if (not table-open)
25318 ;; New table starts
25319 (setq table-open t table-buffer nil table-orig-buffer nil))
25320 ;; Accumulate lines
25321 (setq table-buffer (cons line table-buffer)
25322 table-orig-buffer (cons origline table-orig-buffer))
25323 (when (or (not lines)
25324 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25325 (car lines))))
25326 (setq table-open nil
25327 table-buffer (nreverse table-buffer)
25328 table-orig-buffer (nreverse table-orig-buffer))
25329 (org-close-par-maybe)
25330 (insert (org-format-table-html table-buffer table-orig-buffer))))
25332 ;; Normal lines
25333 (when (string-match
25334 (cond
25335 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25336 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25337 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25338 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
25339 line)
25340 (setq ind (org-get-string-indentation line)
25341 start-is-num (match-beginning 4)
25342 starter (if (match-beginning 2)
25343 (substring (match-string 2 line) 0 -1))
25344 line (substring line (match-beginning 5)))
25345 (unless (string-match "[^ \t]" line)
25346 ;; empty line. Pretend indentation is large.
25347 (setq ind (if org-empty-line-terminates-plain-lists
25349 (1+ (or (car local-list-indent) 1)))))
25350 (setq didclose nil)
25351 (while (and in-local-list
25352 (or (and (= ind (car local-list-indent))
25353 (not starter))
25354 (< ind (car local-list-indent))))
25355 (setq didclose t)
25356 (org-close-li)
25357 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25358 (pop local-list-num) (pop local-list-indent)
25359 (setq in-local-list local-list-indent))
25360 (cond
25361 ((and starter
25362 (or (not in-local-list)
25363 (> ind (car local-list-indent))))
25364 ;; Start new (level of) list
25365 (org-close-par-maybe)
25366 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
25367 (push start-is-num local-list-num)
25368 (push ind local-list-indent)
25369 (setq in-local-list t))
25370 (starter
25371 ;; continue current list
25372 (org-close-li)
25373 (insert "<li>\n"))
25374 (didclose
25375 ;; we did close a list, normal text follows: need <p>
25376 (org-open-par)))
25377 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
25378 (setq line
25379 (replace-match
25380 (if (equal (match-string 1 line) "X")
25381 "<b>[X]</b>"
25382 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
25383 t t line))))
25385 ;; Empty lines start a new paragraph. If hand-formatted lists
25386 ;; are not fully interpreted, lines starting with "-", "+", "*"
25387 ;; also start a new paragraph.
25388 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
25390 ;; Is this the start of a footnote?
25391 (when org-export-with-footnotes
25392 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
25393 (org-close-par-maybe)
25394 (let ((n (match-string 1 line)))
25395 (setq line (replace-match
25396 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
25398 ;; Check if the line break needs to be conserved
25399 (cond
25400 ((string-match "\\\\\\\\[ \t]*$" line)
25401 (setq line (replace-match "<br/>" t t line)))
25402 (org-export-preserve-breaks
25403 (setq line (concat line "<br/>"))))
25405 (insert line "\n")))))
25407 ;; Properly close all local lists and other lists
25408 (when inquote (insert "</pre>\n"))
25409 (when in-local-list
25410 ;; Close any local lists before inserting a new header line
25411 (while local-list-num
25412 (org-close-li)
25413 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
25414 (pop local-list-num))
25415 (setq local-list-indent nil
25416 in-local-list nil))
25417 (org-html-level-start 1 nil umax
25418 (and org-export-with-toc (<= level umax))
25419 head-count)
25421 (unless body-only
25422 (when (plist-get opt-plist :auto-postamble)
25423 (insert "<div id=\"postamble\">")
25424 (when (and org-export-author-info author)
25425 (insert "<p class=\"author\"> "
25426 (nth 1 lang-words) ": " author "\n")
25427 (when email
25428 (if (listp (split-string email ",+ *"))
25429 (mapc (lambda(e)
25430 (insert "<a href=\"mailto:" e "\">&lt;"
25431 e "&gt;</a>\n"))
25432 (split-string email ",+ *"))
25433 (insert "<a href=\"mailto:" email "\">&lt;"
25434 email "&gt;</a>\n")))
25435 (insert "</p>\n"))
25436 (when (and date org-export-time-stamp-file)
25437 (insert "<p class=\"date\"> "
25438 (nth 2 lang-words) ": "
25439 date "</p>\n"))
25440 (insert "</div>"))
25442 (if org-export-html-with-timestamp
25443 (insert org-export-html-html-helper-timestamp))
25444 (insert (or (plist-get opt-plist :postamble) ""))
25445 (insert "</body>\n</html>\n"))
25447 (normal-mode)
25448 (if (eq major-mode default-major-mode) (html-mode))
25450 ;; insert the table of contents
25451 (goto-char (point-min))
25452 (when thetoc
25453 (if (or (re-search-forward
25454 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
25455 (re-search-forward
25456 "\\[TABLE-OF-CONTENTS\\]" nil t))
25457 (progn
25458 (goto-char (match-beginning 0))
25459 (replace-match ""))
25460 (goto-char first-heading-pos)
25461 (when (looking-at "\\s-*</p>")
25462 (goto-char (match-end 0))
25463 (insert "\n")))
25464 (insert "<div id=\"table-of-contents\">\n")
25465 (mapc 'insert thetoc)
25466 (insert "</div>\n"))
25467 ;; remove empty paragraphs and lists
25468 (goto-char (point-min))
25469 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
25470 (replace-match ""))
25471 (goto-char (point-min))
25472 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
25473 (replace-match ""))
25474 ;; Convert whitespace place holders
25475 (goto-char (point-min))
25476 (let (beg end n)
25477 (while (setq beg (next-single-property-change (point) 'org-whitespace))
25478 (setq n (get-text-property beg 'org-whitespace)
25479 end (next-single-property-change beg 'org-whitespace))
25480 (goto-char beg)
25481 (delete-region beg end)
25482 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
25483 (make-string n ?x)))))
25485 (or to-buffer (save-buffer))
25486 (goto-char (point-min))
25487 (message "Exporting... done")
25488 (if (eq to-buffer 'string)
25489 (prog1 (buffer-substring (point-min) (point-max))
25490 (kill-buffer (current-buffer)))
25491 (current-buffer)))))
25493 (defvar org-table-colgroup-info nil)
25494 (defun org-format-table-ascii (lines)
25495 "Format a table for ascii export."
25496 (if (stringp lines)
25497 (setq lines (org-split-string lines "\n")))
25498 (if (not (string-match "^[ \t]*|" (car lines)))
25499 ;; Table made by table.el - test for spanning
25500 lines
25502 ;; A normal org table
25503 ;; Get rid of hlines at beginning and end
25504 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25505 (setq lines (nreverse lines))
25506 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25507 (setq lines (nreverse lines))
25508 (when org-export-table-remove-special-lines
25509 ;; Check if the table has a marking column. If yes remove the
25510 ;; column and the special lines
25511 (setq lines (org-table-clean-before-export lines)))
25512 ;; Get rid of the vertical lines except for grouping
25513 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
25514 rtn line vl1 start)
25515 (while (setq line (pop lines))
25516 (if (string-match org-table-hline-regexp line)
25517 (and (string-match "|\\(.*\\)|" line)
25518 (setq line (replace-match " \\1" t nil line)))
25519 (setq start 0 vl1 vl)
25520 (while (string-match "|" line start)
25521 (setq start (match-end 0))
25522 (or (pop vl1) (setq line (replace-match " " t t line)))))
25523 (push line rtn))
25524 (nreverse rtn))))
25526 (defun org-colgroup-info-to-vline-list (info)
25527 (let (vl new last)
25528 (while info
25529 (setq last new new (pop info))
25530 (if (or (memq last '(:end :startend))
25531 (memq new '(:start :startend)))
25532 (push t vl)
25533 (push nil vl)))
25534 (setq vl (nreverse vl))
25535 (and vl (setcar vl nil))
25536 vl))
25538 (defun org-format-table-html (lines olines)
25539 "Find out which HTML converter to use and return the HTML code."
25540 (if (stringp lines)
25541 (setq lines (org-split-string lines "\n")))
25542 (if (string-match "^[ \t]*|" (car lines))
25543 ;; A normal org table
25544 (org-format-org-table-html lines)
25545 ;; Table made by table.el - test for spanning
25546 (let* ((hlines (delq nil (mapcar
25547 (lambda (x)
25548 (if (string-match "^[ \t]*\\+-" x) x
25549 nil))
25550 lines)))
25551 (first (car hlines))
25552 (ll (and (string-match "\\S-+" first)
25553 (match-string 0 first)))
25554 (re (concat "^[ \t]*" (regexp-quote ll)))
25555 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
25556 hlines))))
25557 (if (and (not spanning)
25558 (not org-export-prefer-native-exporter-for-tables))
25559 ;; We can use my own converter with HTML conversions
25560 (org-format-table-table-html lines)
25561 ;; Need to use the code generator in table.el, with the original text.
25562 (org-format-table-table-html-using-table-generate-source olines)))))
25564 (defun org-format-org-table-html (lines &optional splice)
25565 "Format a table into HTML."
25566 ;; Get rid of hlines at beginning and end
25567 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25568 (setq lines (nreverse lines))
25569 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25570 (setq lines (nreverse lines))
25571 (when org-export-table-remove-special-lines
25572 ;; Check if the table has a marking column. If yes remove the
25573 ;; column and the special lines
25574 (setq lines (org-table-clean-before-export lines)))
25576 (let ((head (and org-export-highlight-first-table-line
25577 (delq nil (mapcar
25578 (lambda (x) (string-match "^[ \t]*|-" x))
25579 (cdr lines)))))
25580 (nlines 0) fnum i
25581 tbopen line fields html gr colgropen)
25582 (if splice (setq head nil))
25583 (unless splice (push (if head "<thead>" "<tbody>") html))
25584 (setq tbopen t)
25585 (while (setq line (pop lines))
25586 (catch 'next-line
25587 (if (string-match "^[ \t]*|-" line)
25588 (progn
25589 (unless splice
25590 (push (if head "</thead>" "</tbody>") html)
25591 (if lines (push "<tbody>" html) (setq tbopen nil)))
25592 (setq head nil) ;; head ends here, first time around
25593 ;; ignore this line
25594 (throw 'next-line t)))
25595 ;; Break the line into fields
25596 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25597 (unless fnum (setq fnum (make-vector (length fields) 0)))
25598 (setq nlines (1+ nlines) i -1)
25599 (push (concat "<tr>"
25600 (mapconcat
25601 (lambda (x)
25602 (setq i (1+ i))
25603 (if (and (< i nlines)
25604 (string-match org-table-number-regexp x))
25605 (incf (aref fnum i)))
25606 (if head
25607 (concat (car org-export-table-header-tags) x
25608 (cdr org-export-table-header-tags))
25609 (concat (car org-export-table-data-tags) x
25610 (cdr org-export-table-data-tags))))
25611 fields "")
25612 "</tr>")
25613 html)))
25614 (unless splice (if tbopen (push "</tbody>" html)))
25615 (unless splice (push "</table>\n" html))
25616 (setq html (nreverse html))
25617 (unless splice
25618 ;; Put in col tags with the alignment (unfortuntely often ignored...)
25619 (push (mapconcat
25620 (lambda (x)
25621 (setq gr (pop org-table-colgroup-info))
25622 (format "%s<col align=\"%s\"></col>%s"
25623 (if (memq gr '(:start :startend))
25624 (prog1
25625 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
25626 (setq colgropen t))
25628 (if (> (/ (float x) nlines) org-table-number-fraction)
25629 "right" "left")
25630 (if (memq gr '(:end :startend))
25631 (progn (setq colgropen nil) "</colgroup>")
25632 "")))
25633 fnum "")
25634 html)
25635 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
25636 (push html-table-tag html))
25637 (concat (mapconcat 'identity html "\n") "\n")))
25639 (defun org-table-clean-before-export (lines)
25640 "Check if the table has a marking column.
25641 If yes remove the column and the special lines."
25642 (setq org-table-colgroup-info nil)
25643 (if (memq nil
25644 (mapcar
25645 (lambda (x) (or (string-match "^[ \t]*|-" x)
25646 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
25647 lines))
25648 (progn
25649 (setq org-table-clean-did-remove-column nil)
25650 (delq nil
25651 (mapcar
25652 (lambda (x)
25653 (cond
25654 ((string-match "^[ \t]*| */ *|" x)
25655 (setq org-table-colgroup-info
25656 (mapcar (lambda (x)
25657 (cond ((member x '("<" "&lt;")) :start)
25658 ((member x '(">" "&gt;")) :end)
25659 ((member x '("<>" "&lt;&gt;")) :startend)
25660 (t nil)))
25661 (org-split-string x "[ \t]*|[ \t]*")))
25662 nil)
25663 (t x)))
25664 lines)))
25665 (setq org-table-clean-did-remove-column t)
25666 (delq nil
25667 (mapcar
25668 (lambda (x)
25669 (cond
25670 ((string-match "^[ \t]*| */ *|" x)
25671 (setq org-table-colgroup-info
25672 (mapcar (lambda (x)
25673 (cond ((member x '("<" "&lt;")) :start)
25674 ((member x '(">" "&gt;")) :end)
25675 ((member x '("<>" "&lt;&gt;")) :startend)
25676 (t nil)))
25677 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
25678 nil)
25679 ((string-match "^[ \t]*| *[!_^/] *|" x)
25680 nil) ; ignore this line
25681 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
25682 (string-match "^\\([ \t]*\\)|[^|]*|" x))
25683 ;; remove the first column
25684 (replace-match "\\1|" t nil x))))
25685 lines))))
25687 (defun org-format-table-table-html (lines)
25688 "Format a table generated by table.el into HTML.
25689 This conversion does *not* use `table-generate-source' from table.el.
25690 This has the advantage that Org-mode's HTML conversions can be used.
25691 But it has the disadvantage, that no cell- or row-spanning is allowed."
25692 (let (line field-buffer
25693 (head org-export-highlight-first-table-line)
25694 fields html empty)
25695 (setq html (concat html-table-tag "\n"))
25696 (while (setq line (pop lines))
25697 (setq empty "&nbsp;")
25698 (catch 'next-line
25699 (if (string-match "^[ \t]*\\+-" line)
25700 (progn
25701 (if field-buffer
25702 (progn
25703 (setq
25704 html
25705 (concat
25706 html
25707 "<tr>"
25708 (mapconcat
25709 (lambda (x)
25710 (if (equal x "") (setq x empty))
25711 (if head
25712 (concat (car org-export-table-header-tags) x
25713 (cdr org-export-table-header-tags))
25714 (concat (car org-export-table-data-tags) x
25715 (cdr org-export-table-data-tags))))
25716 field-buffer "\n")
25717 "</tr>\n"))
25718 (setq head nil)
25719 (setq field-buffer nil)))
25720 ;; Ignore this line
25721 (throw 'next-line t)))
25722 ;; Break the line into fields and store the fields
25723 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25724 (if field-buffer
25725 (setq field-buffer (mapcar
25726 (lambda (x)
25727 (concat x "<br/>" (pop fields)))
25728 field-buffer))
25729 (setq field-buffer fields))))
25730 (setq html (concat html "</table>\n"))
25731 html))
25733 (defun org-format-table-table-html-using-table-generate-source (lines)
25734 "Format a table into html, using `table-generate-source' from table.el.
25735 This has the advantage that cell- or row-spanning is allowed.
25736 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
25737 (require 'table)
25738 (with-current-buffer (get-buffer-create " org-tmp1 ")
25739 (erase-buffer)
25740 (insert (mapconcat 'identity lines "\n"))
25741 (goto-char (point-min))
25742 (if (not (re-search-forward "|[^+]" nil t))
25743 (error "Error processing table"))
25744 (table-recognize-table)
25745 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
25746 (table-generate-source 'html " org-tmp2 ")
25747 (set-buffer " org-tmp2 ")
25748 (buffer-substring (point-min) (point-max))))
25750 (defun org-html-handle-time-stamps (s)
25751 "Format time stamps in string S, or remove them."
25752 (catch 'exit
25753 (let (r b)
25754 (while (string-match org-maybe-keyword-time-regexp s)
25755 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
25756 ;; never export CLOCK
25757 (throw 'exit ""))
25758 (or b (setq b (substring s 0 (match-beginning 0))))
25759 (if (not org-export-with-timestamps)
25760 (setq r (concat r (substring s 0 (match-beginning 0)))
25761 s (substring s (match-end 0)))
25762 (setq r (concat
25763 r (substring s 0 (match-beginning 0))
25764 (if (match-end 1)
25765 (format "@<span class=\"timestamp-kwd\">%s @</span>"
25766 (match-string 1 s)))
25767 (format " @<span class=\"timestamp\">%s@</span>"
25768 (substring
25769 (org-translate-time (match-string 3 s)) 1 -1)))
25770 s (substring s (match-end 0)))))
25771 ;; Line break if line started and ended with time stamp stuff
25772 (if (not r)
25774 (setq r (concat r s))
25775 (unless (string-match "\\S-" (concat b s))
25776 (setq r (concat r "@<br/>")))
25777 r))))
25779 (defun org-html-protect (s)
25780 ;; convert & to &amp;, < to &lt; and > to &gt;
25781 (let ((start 0))
25782 (while (string-match "&" s start)
25783 (setq s (replace-match "&amp;" t t s)
25784 start (1+ (match-beginning 0))))
25785 (while (string-match "<" s)
25786 (setq s (replace-match "&lt;" t t s)))
25787 (while (string-match ">" s)
25788 (setq s (replace-match "&gt;" t t s))))
25791 (defun org-export-cleanup-toc-line (s)
25792 "Remove tags and time staps from lines going into the toc."
25793 (when (memq org-export-with-tags '(not-in-toc nil))
25794 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
25795 (setq s (replace-match "" t t s))))
25796 (when org-export-remove-timestamps-from-toc
25797 (while (string-match org-maybe-keyword-time-regexp s)
25798 (setq s (replace-match "" t t s))))
25799 (while (string-match org-bracket-link-regexp s)
25800 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
25801 t t s)))
25804 (defun org-html-expand (string)
25805 "Prepare STRING for HTML export. Applies all active conversions.
25806 If there are links in the string, don't modify these."
25807 (let* ((re (concat org-bracket-link-regexp "\\|"
25808 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
25809 m s l res)
25810 (while (setq m (string-match re string))
25811 (setq s (substring string 0 m)
25812 l (match-string 0 string)
25813 string (substring string (match-end 0)))
25814 (push (org-html-do-expand s) res)
25815 (push l res))
25816 (push (org-html-do-expand string) res)
25817 (apply 'concat (nreverse res))))
25819 (defun org-html-do-expand (s)
25820 "Apply all active conversions to translate special ASCII to HTML."
25821 (setq s (org-html-protect s))
25822 (if org-export-html-expand
25823 (let ((start 0))
25824 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
25825 (setq s (replace-match "<\\1>" t nil s)))))
25826 (if org-export-with-emphasize
25827 (setq s (org-export-html-convert-emphasize s)))
25828 (if org-export-with-special-strings
25829 (setq s (org-export-html-convert-special-strings s)))
25830 (if org-export-with-sub-superscripts
25831 (setq s (org-export-html-convert-sub-super s)))
25832 (if org-export-with-TeX-macros
25833 (let ((start 0) wd ass)
25834 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
25835 (if (get-text-property (match-beginning 0) 'org-protected s)
25836 (setq start (match-end 0))
25837 (setq wd (match-string 1 s))
25838 (if (setq ass (assoc wd org-html-entities))
25839 (setq s (replace-match (or (cdr ass)
25840 (concat "&" (car ass) ";"))
25841 t t s))
25842 (setq start (+ start (length wd))))))))
25845 (defun org-create-multibrace-regexp (left right n)
25846 "Create a regular expression which will match a balanced sexp.
25847 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
25848 as single character strings.
25849 The regexp returned will match the entire expression including the
25850 delimiters. It will also define a single group which contains the
25851 match except for the outermost delimiters. The maximum depth of
25852 stacked delimiters is N. Escaping delimiters is not possible."
25853 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
25854 (or "\\|")
25855 (re nothing)
25856 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
25857 (while (> n 1)
25858 (setq n (1- n)
25859 re (concat re or next)
25860 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
25861 (concat left "\\(" re "\\)" right)))
25863 (defvar org-match-substring-regexp
25864 (concat
25865 "\\([^\\]\\)\\([_^]\\)\\("
25866 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
25867 "\\|"
25868 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
25869 "\\|"
25870 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
25871 "The regular expression matching a sub- or superscript.")
25873 (defvar org-match-substring-with-braces-regexp
25874 (concat
25875 "\\([^\\]\\)\\([_^]\\)\\("
25876 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
25877 "\\)")
25878 "The regular expression matching a sub- or superscript, forcing braces.")
25880 (defconst org-export-html-special-string-regexps
25881 '(("\\\\-" . "&shy;")
25882 ("---\\([^-]\\)" . "&mdash;\\1")
25883 ("--\\([^-]\\)" . "&ndash;\\1")
25884 ("\\.\\.\\." . "&hellip;"))
25885 "Regular expressions for special string conversion.")
25887 (defun org-export-html-convert-special-strings (string)
25888 "Convert special characters in STRING to HTML."
25889 (let ((all org-export-html-special-string-regexps)
25890 e a re rpl start)
25891 (while (setq a (pop all))
25892 (setq re (car a) rpl (cdr a) start 0)
25893 (while (string-match re string start)
25894 (if (get-text-property (match-beginning 0) 'org-protected string)
25895 (setq start (match-end 0))
25896 (setq string (replace-match rpl t nil string)))))
25897 string))
25899 (defun org-export-html-convert-sub-super (string)
25900 "Convert sub- and superscripts in STRING to HTML."
25901 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
25902 (while (string-match org-match-substring-regexp string s)
25903 (cond
25904 ((and requireb (match-end 8)) (setq s (match-end 2)))
25905 ((get-text-property (match-beginning 2) 'org-protected string)
25906 (setq s (match-end 2)))
25908 (setq s (match-end 1)
25909 key (if (string= (match-string 2 string) "_") "sub" "sup")
25910 c (or (match-string 8 string)
25911 (match-string 6 string)
25912 (match-string 5 string))
25913 string (replace-match
25914 (concat (match-string 1 string)
25915 "<" key ">" c "</" key ">")
25916 t t string)))))
25917 (while (string-match "\\\\\\([_^]\\)" string)
25918 (setq string (replace-match (match-string 1 string) t t string)))
25919 string))
25921 (defun org-export-html-convert-emphasize (string)
25922 "Apply emphasis."
25923 (let ((s 0) rpl)
25924 (while (string-match org-emph-re string s)
25925 (if (not (equal
25926 (substring string (match-beginning 3) (1+ (match-beginning 3)))
25927 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
25928 (setq s (match-beginning 0)
25930 (concat
25931 (match-string 1 string)
25932 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
25933 (match-string 4 string)
25934 (nth 3 (assoc (match-string 3 string)
25935 org-emphasis-alist))
25936 (match-string 5 string))
25937 string (replace-match rpl t t string)
25938 s (+ s (- (length rpl) 2)))
25939 (setq s (1+ s))))
25940 string))
25942 (defvar org-par-open nil)
25943 (defun org-open-par ()
25944 "Insert <p>, but first close previous paragraph if any."
25945 (org-close-par-maybe)
25946 (insert "\n<p>")
25947 (setq org-par-open t))
25948 (defun org-close-par-maybe ()
25949 "Close paragraph if there is one open."
25950 (when org-par-open
25951 (insert "</p>")
25952 (setq org-par-open nil)))
25953 (defun org-close-li ()
25954 "Close <li> if necessary."
25955 (org-close-par-maybe)
25956 (insert "</li>\n"))
25958 (defvar body-only) ; dynamically scoped into this.
25959 (defun org-html-level-start (level title umax with-toc head-count)
25960 "Insert a new level in HTML export.
25961 When TITLE is nil, just close all open levels."
25962 (org-close-par-maybe)
25963 (let ((l org-level-max))
25964 (while (>= l level)
25965 (if (aref org-levels-open (1- l))
25966 (progn
25967 (org-html-level-close l umax)
25968 (aset org-levels-open (1- l) nil)))
25969 (setq l (1- l)))
25970 (when title
25971 ;; If title is nil, this means this function is called to close
25972 ;; all levels, so the rest is done only if title is given
25973 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
25974 (setq title (replace-match
25975 (if org-export-with-tags
25976 (save-match-data
25977 (concat
25978 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
25979 (mapconcat 'identity (org-split-string
25980 (match-string 1 title) ":")
25981 "&nbsp;")
25982 "</span>"))
25984 t t title)))
25985 (if (> level umax)
25986 (progn
25987 (if (aref org-levels-open (1- level))
25988 (progn
25989 (org-close-li)
25990 (insert "<li>" title "<br/>\n"))
25991 (aset org-levels-open (1- level) t)
25992 (org-close-par-maybe)
25993 (insert "<ul>\n<li>" title "<br/>\n")))
25994 (aset org-levels-open (1- level) t)
25995 (if (and org-export-with-section-numbers (not body-only))
25996 (setq title (concat (org-section-number level) " " title)))
25997 (setq level (+ level org-export-html-toplevel-hlevel -1))
25998 (if with-toc
25999 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
26000 level level head-count title level))
26001 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
26002 (org-open-par)))))
26004 (defun org-html-level-close (level max-outline-level)
26005 "Terminate one level in HTML export."
26006 (if (<= level max-outline-level)
26007 (insert "</div>\n")
26008 (org-close-li)
26009 (insert "</ul>\n")))
26011 ;;; iCalendar export
26013 ;;;###autoload
26014 (defun org-export-icalendar-this-file ()
26015 "Export current file as an iCalendar file.
26016 The iCalendar file will be located in the same directory as the Org-mode
26017 file, but with extension `.ics'."
26018 (interactive)
26019 (org-export-icalendar nil buffer-file-name))
26021 ;;;###autoload
26022 (defun org-export-icalendar-all-agenda-files ()
26023 "Export all files in `org-agenda-files' to iCalendar .ics files.
26024 Each iCalendar file will be located in the same directory as the Org-mode
26025 file, but with extension `.ics'."
26026 (interactive)
26027 (apply 'org-export-icalendar nil (org-agenda-files t)))
26029 ;;;###autoload
26030 (defun org-export-icalendar-combine-agenda-files ()
26031 "Export all files in `org-agenda-files' to a single combined iCalendar file.
26032 The file is stored under the name `org-combined-agenda-icalendar-file'."
26033 (interactive)
26034 (apply 'org-export-icalendar t (org-agenda-files t)))
26036 (defun org-export-icalendar (combine &rest files)
26037 "Create iCalendar files for all elements of FILES.
26038 If COMBINE is non-nil, combine all calendar entries into a single large
26039 file and store it under the name `org-combined-agenda-icalendar-file'."
26040 (save-excursion
26041 (org-prepare-agenda-buffers files)
26042 (let* ((dir (org-export-directory
26043 :ical (list :publishing-directory
26044 org-export-publishing-directory)))
26045 file ical-file ical-buffer category started org-agenda-new-buffers)
26047 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
26048 (when combine
26049 (setq ical-file
26050 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
26051 org-combined-agenda-icalendar-file
26052 (expand-file-name org-combined-agenda-icalendar-file dir))
26053 ical-buffer (org-get-agenda-file-buffer ical-file))
26054 (set-buffer ical-buffer) (erase-buffer))
26055 (while (setq file (pop files))
26056 (catch 'nextfile
26057 (org-check-agenda-file file)
26058 (set-buffer (org-get-agenda-file-buffer file))
26059 (unless combine
26060 (setq ical-file (concat (file-name-as-directory dir)
26061 (file-name-sans-extension
26062 (file-name-nondirectory buffer-file-name))
26063 ".ics"))
26064 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
26065 (with-current-buffer ical-buffer (erase-buffer)))
26066 (setq category (or org-category
26067 (file-name-sans-extension
26068 (file-name-nondirectory buffer-file-name))))
26069 (if (symbolp category) (setq category (symbol-name category)))
26070 (let ((standard-output ical-buffer))
26071 (if combine
26072 (and (not started) (setq started t)
26073 (org-start-icalendar-file org-icalendar-combined-name))
26074 (org-start-icalendar-file category))
26075 (org-print-icalendar-entries combine)
26076 (when (or (and combine (not files)) (not combine))
26077 (org-finish-icalendar-file)
26078 (set-buffer ical-buffer)
26079 (save-buffer)
26080 (run-hooks 'org-after-save-iCalendar-file-hook)))))
26081 (org-release-buffers org-agenda-new-buffers))))
26083 (defvar org-after-save-iCalendar-file-hook nil
26084 "Hook run after an iCalendar file has been saved.
26085 The iCalendar buffer is still current when this hook is run.
26086 A good way to use this is to tell a desktop calenndar application to re-read
26087 the iCalendar file.")
26089 (defun org-print-icalendar-entries (&optional combine)
26090 "Print iCalendar entries for the current Org-mode file to `standard-output'.
26091 When COMBINE is non nil, add the category to each line."
26092 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
26093 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
26094 (dts (org-ical-ts-to-string
26095 (format-time-string (cdr org-time-stamp-formats) (current-time))
26096 "DTSTART"))
26097 hd ts ts2 state status (inc t) pos b sexp rrule
26098 scheduledp deadlinep tmp pri category entry location summary desc
26099 (sexp-buffer (get-buffer-create "*ical-tmp*")))
26100 (org-refresh-category-properties)
26101 (save-excursion
26102 (goto-char (point-min))
26103 (while (re-search-forward re1 nil t)
26104 (catch :skip
26105 (org-agenda-skip)
26106 (setq pos (match-beginning 0)
26107 ts (match-string 0)
26108 inc t
26109 hd (org-get-heading)
26110 summary (org-icalendar-cleanup-string
26111 (org-entry-get nil "SUMMARY"))
26112 desc (org-icalendar-cleanup-string
26113 (or (org-entry-get nil "DESCRIPTION")
26114 (and org-icalendar-include-body (org-get-entry)))
26115 t org-icalendar-include-body)
26116 location (org-icalendar-cleanup-string
26117 (org-entry-get nil "LOCATION"))
26118 category (org-get-category))
26119 (if (looking-at re2)
26120 (progn
26121 (goto-char (match-end 0))
26122 (setq ts2 (match-string 1) inc nil))
26123 (setq tmp (buffer-substring (max (point-min)
26124 (- pos org-ds-keyword-length))
26125 pos)
26126 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
26127 (progn
26128 (setq inc nil)
26129 (replace-match "\\1" t nil ts))
26131 deadlinep (string-match org-deadline-regexp tmp)
26132 scheduledp (string-match org-scheduled-regexp tmp)
26133 ;; donep (org-entry-is-done-p)
26135 (if (or (string-match org-tr-regexp hd)
26136 (string-match org-ts-regexp hd))
26137 (setq hd (replace-match "" t t hd)))
26138 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
26139 (setq rrule
26140 (concat "\nRRULE:FREQ="
26141 (cdr (assoc
26142 (match-string 2 ts)
26143 '(("d" . "DAILY")("w" . "WEEKLY")
26144 ("m" . "MONTHLY")("y" . "YEARLY"))))
26145 ";INTERVAL=" (match-string 1 ts)))
26146 (setq rrule ""))
26147 (setq summary (or summary hd))
26148 (if (string-match org-bracket-link-regexp summary)
26149 (setq summary
26150 (replace-match (if (match-end 3)
26151 (match-string 3 summary)
26152 (match-string 1 summary))
26153 t t summary)))
26154 (if deadlinep (setq summary (concat "DL: " summary)))
26155 (if scheduledp (setq summary (concat "S: " summary)))
26156 (if (string-match "\\`<%%" ts)
26157 (with-current-buffer sexp-buffer
26158 (insert (substring ts 1 -1) " " summary "\n"))
26159 (princ (format "BEGIN:VEVENT
26161 %s%s
26162 SUMMARY:%s%s%s
26163 CATEGORIES:%s
26164 END:VEVENT\n"
26165 (org-ical-ts-to-string ts "DTSTART")
26166 (org-ical-ts-to-string ts2 "DTEND" inc)
26167 rrule summary
26168 (if (and desc (string-match "\\S-" desc))
26169 (concat "\nDESCRIPTION: " desc) "")
26170 (if (and location (string-match "\\S-" location))
26171 (concat "\nLOCATION: " location) "")
26172 category)))))
26174 (when (and org-icalendar-include-sexps
26175 (condition-case nil (require 'icalendar) (error nil))
26176 (fboundp 'icalendar-export-region))
26177 ;; Get all the literal sexps
26178 (goto-char (point-min))
26179 (while (re-search-forward "^&?%%(" nil t)
26180 (catch :skip
26181 (org-agenda-skip)
26182 (setq b (match-beginning 0))
26183 (goto-char (1- (match-end 0)))
26184 (forward-sexp 1)
26185 (end-of-line 1)
26186 (setq sexp (buffer-substring b (point)))
26187 (with-current-buffer sexp-buffer
26188 (insert sexp "\n"))
26189 (princ (org-diary-to-ical-string sexp-buffer)))))
26191 (when org-icalendar-include-todo
26192 (goto-char (point-min))
26193 (while (re-search-forward org-todo-line-regexp nil t)
26194 (catch :skip
26195 (org-agenda-skip)
26196 (setq state (match-string 2))
26197 (setq status (if (member state org-done-keywords)
26198 "COMPLETED" "NEEDS-ACTION"))
26199 (when (and state
26200 (or (not (member state org-done-keywords))
26201 (eq org-icalendar-include-todo 'all))
26202 (not (member org-archive-tag (org-get-tags-at)))
26204 (setq hd (match-string 3)
26205 summary (org-icalendar-cleanup-string
26206 (org-entry-get nil "SUMMARY"))
26207 desc (org-icalendar-cleanup-string
26208 (or (org-entry-get nil "DESCRIPTION")
26209 (and org-icalendar-include-body (org-get-entry)))
26210 t org-icalendar-include-body)
26211 location (org-icalendar-cleanup-string
26212 (org-entry-get nil "LOCATION")))
26213 (if (string-match org-bracket-link-regexp hd)
26214 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
26215 (match-string 1 hd))
26216 t t hd)))
26217 (if (string-match org-priority-regexp hd)
26218 (setq pri (string-to-char (match-string 2 hd))
26219 hd (concat (substring hd 0 (match-beginning 1))
26220 (substring hd (match-end 1))))
26221 (setq pri org-default-priority))
26222 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
26223 (- org-lowest-priority org-highest-priority))))))
26225 (princ (format "BEGIN:VTODO
26227 SUMMARY:%s%s%s
26228 CATEGORIES:%s
26229 SEQUENCE:1
26230 PRIORITY:%d
26231 STATUS:%s
26232 END:VTODO\n"
26234 (or summary hd)
26235 (if (and location (string-match "\\S-" location))
26236 (concat "\nLOCATION: " location) "")
26237 (if (and desc (string-match "\\S-" desc))
26238 (concat "\nDESCRIPTION: " desc) "")
26239 category pri status)))))))))
26241 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
26242 "Take out stuff and quote what needs to be quoted.
26243 When IS-BODY is non-nil, assume that this is the body of an item, clean up
26244 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
26245 characters."
26246 (if (not s)
26248 (when is-body
26249 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
26250 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
26251 (while (string-match re s) (setq s (replace-match "" t t s)))
26252 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
26253 (let ((start 0))
26254 (while (string-match "\\([,;\\]\\)" s start)
26255 (setq start (+ (match-beginning 0) 2)
26256 s (replace-match "\\\\\\1" nil nil s))))
26257 (when is-body
26258 (while (string-match "[ \t]*\n[ \t]*" s)
26259 (setq s (replace-match "\\n" t t s))))
26260 (setq s (org-trim s))
26261 (if is-body
26262 (if maxlength
26263 (if (and (numberp maxlength)
26264 (> (length s) maxlength))
26265 (setq s (substring s 0 maxlength)))))
26268 (defun org-get-entry ()
26269 "Clean-up description string."
26270 (save-excursion
26271 (org-back-to-heading t)
26272 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
26274 (defun org-start-icalendar-file (name)
26275 "Start an iCalendar file by inserting the header."
26276 (let ((user user-full-name)
26277 (name (or name "unknown"))
26278 (timezone (cadr (current-time-zone))))
26279 (princ
26280 (format "BEGIN:VCALENDAR
26281 VERSION:2.0
26282 X-WR-CALNAME:%s
26283 PRODID:-//%s//Emacs with Org-mode//EN
26284 X-WR-TIMEZONE:%s
26285 CALSCALE:GREGORIAN\n" name user timezone))))
26287 (defun org-finish-icalendar-file ()
26288 "Finish an iCalendar file by inserting the END statement."
26289 (princ "END:VCALENDAR\n"))
26291 (defun org-ical-ts-to-string (s keyword &optional inc)
26292 "Take a time string S and convert it to iCalendar format.
26293 KEYWORD is added in front, to make a complete line like DTSTART....
26294 When INC is non-nil, increase the hour by two (if time string contains
26295 a time), or the day by one (if it does not contain a time)."
26296 (let ((t1 (org-parse-time-string s 'nodefault))
26297 t2 fmt have-time time)
26298 (if (and (car t1) (nth 1 t1) (nth 2 t1))
26299 (setq t2 t1 have-time t)
26300 (setq t2 (org-parse-time-string s)))
26301 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
26302 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
26303 (when inc
26304 (if have-time
26305 (if org-agenda-default-appointment-duration
26306 (setq mi (+ org-agenda-default-appointment-duration mi))
26307 (setq h (+ 2 h)))
26308 (setq d (1+ d))))
26309 (setq time (encode-time s mi h d m y)))
26310 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
26311 (concat keyword (format-time-string fmt time))))
26313 ;;; XOXO export
26315 (defun org-export-as-xoxo-insert-into (buffer &rest output)
26316 (with-current-buffer buffer
26317 (apply 'insert output)))
26318 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
26320 (defun org-export-as-xoxo (&optional buffer)
26321 "Export the org buffer as XOXO.
26322 The XOXO buffer is named *xoxo-<source buffer name>*"
26323 (interactive (list (current-buffer)))
26324 ;; A quickie abstraction
26326 ;; Output everything as XOXO
26327 (with-current-buffer (get-buffer buffer)
26328 (let* ((pos (point))
26329 (opt-plist (org-combine-plists (org-default-export-plist)
26330 (org-infile-export-plist)))
26331 (filename (concat (file-name-as-directory
26332 (org-export-directory :xoxo opt-plist))
26333 (file-name-sans-extension
26334 (file-name-nondirectory buffer-file-name))
26335 ".html"))
26336 (out (find-file-noselect filename))
26337 (last-level 1)
26338 (hanging-li nil))
26339 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
26340 ;; Check the output buffer is empty.
26341 (with-current-buffer out (erase-buffer))
26342 ;; Kick off the output
26343 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
26344 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
26345 (let* ((hd (match-string-no-properties 1))
26346 (level (length hd))
26347 (text (concat
26348 (match-string-no-properties 2)
26349 (save-excursion
26350 (goto-char (match-end 0))
26351 (let ((str ""))
26352 (catch 'loop
26353 (while 't
26354 (forward-line)
26355 (if (looking-at "^[ \t]\\(.*\\)")
26356 (setq str (concat str (match-string-no-properties 1)))
26357 (throw 'loop str)))))))))
26359 ;; Handle level rendering
26360 (cond
26361 ((> level last-level)
26362 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
26364 ((< level last-level)
26365 (dotimes (- (- last-level level) 1)
26366 (if hanging-li
26367 (org-export-as-xoxo-insert-into out "</li>\n"))
26368 (org-export-as-xoxo-insert-into out "</ol>\n"))
26369 (when hanging-li
26370 (org-export-as-xoxo-insert-into out "</li>\n")
26371 (setq hanging-li nil)))
26373 ((equal level last-level)
26374 (if hanging-li
26375 (org-export-as-xoxo-insert-into out "</li>\n")))
26378 (setq last-level level)
26380 ;; And output the new li
26381 (setq hanging-li 't)
26382 (if (equal ?+ (elt text 0))
26383 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
26384 (org-export-as-xoxo-insert-into out "<li>" text))))
26386 ;; Finally finish off the ol
26387 (dotimes (- last-level 1)
26388 (if hanging-li
26389 (org-export-as-xoxo-insert-into out "</li>\n"))
26390 (org-export-as-xoxo-insert-into out "</ol>\n"))
26392 (goto-char pos)
26393 ;; Finish the buffer off and clean it up.
26394 (switch-to-buffer-other-window out)
26395 (indent-region (point-min) (point-max) nil)
26396 (save-buffer)
26397 (goto-char (point-min))
26401 ;;;; Key bindings
26403 ;; Make `C-c C-x' a prefix key
26404 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
26406 ;; TAB key with modifiers
26407 (org-defkey org-mode-map "\C-i" 'org-cycle)
26408 (org-defkey org-mode-map [(tab)] 'org-cycle)
26409 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
26410 (org-defkey org-mode-map [(meta tab)] 'org-complete)
26411 (org-defkey org-mode-map "\M-\t" 'org-complete)
26412 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
26413 ;; The following line is necessary under Suse GNU/Linux
26414 (unless (featurep 'xemacs)
26415 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
26416 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
26417 (define-key org-mode-map [backtab] 'org-shifttab)
26419 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
26420 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
26421 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
26423 ;; Cursor keys with modifiers
26424 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
26425 (org-defkey org-mode-map [(meta right)] 'org-metaright)
26426 (org-defkey org-mode-map [(meta up)] 'org-metaup)
26427 (org-defkey org-mode-map [(meta down)] 'org-metadown)
26429 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
26430 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
26431 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
26432 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
26434 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
26435 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
26436 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
26437 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
26439 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
26440 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
26442 ;;; Extra keys for tty access.
26443 ;; We only set them when really needed because otherwise the
26444 ;; menus don't show the simple keys
26446 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
26447 (not window-system))
26448 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
26449 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
26450 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
26451 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
26452 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
26453 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
26454 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
26455 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
26456 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
26457 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
26458 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
26459 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
26460 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
26461 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
26462 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
26463 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
26464 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
26465 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
26466 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
26467 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
26468 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
26469 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
26471 ;; All the other keys
26473 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
26474 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
26475 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
26476 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
26477 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
26478 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
26479 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
26480 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
26481 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
26482 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
26483 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
26484 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
26485 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
26486 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
26487 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
26488 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
26489 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
26490 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
26491 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
26492 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
26493 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
26494 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
26495 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
26496 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
26497 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
26498 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
26499 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
26500 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
26501 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
26502 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
26503 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
26504 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
26505 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
26506 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
26507 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
26508 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
26509 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
26510 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
26511 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
26512 (org-defkey org-mode-map "\C-c^" 'org-sort)
26513 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
26514 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
26515 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
26516 (org-defkey org-mode-map "\C-m" 'org-return)
26517 (org-defkey org-mode-map "\C-j" 'org-return-indent)
26518 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
26519 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
26520 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
26521 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
26522 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
26523 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
26524 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
26525 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
26526 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
26527 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
26528 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
26529 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
26530 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
26531 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
26532 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
26533 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
26535 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
26536 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
26537 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
26538 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
26540 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
26541 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
26542 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
26543 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
26544 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
26545 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
26546 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
26547 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
26548 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
26549 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
26550 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
26551 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
26553 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
26555 (when (featurep 'xemacs)
26556 (org-defkey org-mode-map 'button3 'popup-mode-menu))
26558 (defsubst org-table-p () (org-at-table-p))
26560 (defun org-self-insert-command (N)
26561 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
26562 If the cursor is in a table looking at whitespace, the whitespace is
26563 overwritten, and the table is not marked as requiring realignment."
26564 (interactive "p")
26565 (if (and (org-table-p)
26566 (progn
26567 ;; check if we blank the field, and if that triggers align
26568 (and org-table-auto-blank-field
26569 (member last-command
26570 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
26571 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
26572 ;; got extra space, this field does not determine column width
26573 (let (org-table-may-need-update) (org-table-blank-field))
26574 ;; no extra space, this field may determine column width
26575 (org-table-blank-field)))
26577 (eq N 1)
26578 (looking-at "[^|\n]* |"))
26579 (let (org-table-may-need-update)
26580 (goto-char (1- (match-end 0)))
26581 (delete-backward-char 1)
26582 (goto-char (match-beginning 0))
26583 (self-insert-command N))
26584 (setq org-table-may-need-update t)
26585 (self-insert-command N)
26586 (org-fix-tags-on-the-fly)))
26588 (defun org-fix-tags-on-the-fly ()
26589 (when (and (equal (char-after (point-at-bol)) ?*)
26590 (org-on-heading-p))
26591 (org-align-tags-here org-tags-column)))
26593 (defun org-delete-backward-char (N)
26594 "Like `delete-backward-char', insert whitespace at field end in tables.
26595 When deleting backwards, 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 (eq N 1)
26602 (string-match "|" (buffer-substring (point-at-bol) (point)))
26603 (looking-at ".*?|"))
26604 (let ((pos (point))
26605 (noalign (looking-at "[^|\n\r]* |"))
26606 (c org-table-may-need-update))
26607 (backward-delete-char N)
26608 (skip-chars-forward "^|")
26609 (insert " ")
26610 (goto-char (1- pos))
26611 ;; noalign: if there were two spaces at the end, this field
26612 ;; does not determine the width of the column.
26613 (if noalign (setq org-table-may-need-update c)))
26614 (backward-delete-char N)
26615 (org-fix-tags-on-the-fly)))
26617 (defun org-delete-char (N)
26618 "Like `delete-char', but insert whitespace at field end in tables.
26619 When deleting characters, in tables this function will insert whitespace in
26620 front of the next \"|\" separator, to keep the table aligned. The table will
26621 still be marked for re-alignment if the field did fill the entire column,
26622 because, in this case the deletion might narrow the column."
26623 (interactive "p")
26624 (if (and (org-table-p)
26625 (not (bolp))
26626 (not (= (char-after) ?|))
26627 (eq N 1))
26628 (if (looking-at ".*?|")
26629 (let ((pos (point))
26630 (noalign (looking-at "[^|\n\r]* |"))
26631 (c org-table-may-need-update))
26632 (replace-match (concat
26633 (substring (match-string 0) 1 -1)
26634 " |"))
26635 (goto-char pos)
26636 ;; noalign: if there were two spaces at the end, this field
26637 ;; does not determine the width of the column.
26638 (if noalign (setq org-table-may-need-update c)))
26639 (delete-char N))
26640 (delete-char N)
26641 (org-fix-tags-on-the-fly)))
26643 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
26644 (put 'org-self-insert-command 'delete-selection t)
26645 (put 'orgtbl-self-insert-command 'delete-selection t)
26646 (put 'org-delete-char 'delete-selection 'supersede)
26647 (put 'org-delete-backward-char 'delete-selection 'supersede)
26649 ;; Make `flyspell-mode' delay after some commands
26650 (put 'org-self-insert-command 'flyspell-delayed t)
26651 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
26652 (put 'org-delete-char 'flyspell-delayed t)
26653 (put 'org-delete-backward-char 'flyspell-delayed t)
26655 ;; Make pabbrev-mode expand after org-mode commands
26656 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
26657 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
26659 ;; How to do this: Measure non-white length of current string
26660 ;; If equal to column width, we should realign.
26662 (defun org-remap (map &rest commands)
26663 "In MAP, remap the functions given in COMMANDS.
26664 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
26665 (let (new old)
26666 (while commands
26667 (setq old (pop commands) new (pop commands))
26668 (if (fboundp 'command-remapping)
26669 (org-defkey map (vector 'remap old) new)
26670 (substitute-key-definition old new map global-map)))))
26672 (when (eq org-enable-table-editor 'optimized)
26673 ;; If the user wants maximum table support, we need to hijack
26674 ;; some standard editing functions
26675 (org-remap org-mode-map
26676 'self-insert-command 'org-self-insert-command
26677 'delete-char 'org-delete-char
26678 'delete-backward-char 'org-delete-backward-char)
26679 (org-defkey org-mode-map "|" 'org-force-self-insert))
26681 (defun org-shiftcursor-error ()
26682 "Throw an error because Shift-Cursor command was applied in wrong context."
26683 (error "This command is active in special context like tables, headlines or timestamps"))
26685 (defun org-shifttab (&optional arg)
26686 "Global visibility cycling or move to previous table field.
26687 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
26688 on context.
26689 See the individual commands for more information."
26690 (interactive "P")
26691 (cond
26692 ((org-at-table-p) (call-interactively 'org-table-previous-field))
26693 (arg (message "Content view to level: ")
26694 (org-content (prefix-numeric-value arg))
26695 (setq org-cycle-global-status 'overview))
26696 (t (call-interactively 'org-global-cycle))))
26698 (defun org-shiftmetaleft ()
26699 "Promote subtree or delete table column.
26700 Calls `org-promote-subtree', `org-outdent-item',
26701 or `org-table-delete-column', depending on context.
26702 See the individual commands for more information."
26703 (interactive)
26704 (cond
26705 ((org-at-table-p) (call-interactively 'org-table-delete-column))
26706 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
26707 ((org-at-item-p) (call-interactively 'org-outdent-item))
26708 (t (org-shiftcursor-error))))
26710 (defun org-shiftmetaright ()
26711 "Demote subtree or insert table column.
26712 Calls `org-demote-subtree', `org-indent-item',
26713 or `org-table-insert-column', depending on context.
26714 See the individual commands for more information."
26715 (interactive)
26716 (cond
26717 ((org-at-table-p) (call-interactively 'org-table-insert-column))
26718 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
26719 ((org-at-item-p) (call-interactively 'org-indent-item))
26720 (t (org-shiftcursor-error))))
26722 (defun org-shiftmetaup (&optional arg)
26723 "Move subtree up or kill table row.
26724 Calls `org-move-subtree-up' or `org-table-kill-row' or
26725 `org-move-item-up' depending on context. See the individual commands
26726 for more information."
26727 (interactive "P")
26728 (cond
26729 ((org-at-table-p) (call-interactively 'org-table-kill-row))
26730 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26731 ((org-at-item-p) (call-interactively 'org-move-item-up))
26732 (t (org-shiftcursor-error))))
26733 (defun org-shiftmetadown (&optional arg)
26734 "Move subtree down or insert table row.
26735 Calls `org-move-subtree-down' or `org-table-insert-row' or
26736 `org-move-item-down', depending on context. See the individual
26737 commands for more information."
26738 (interactive "P")
26739 (cond
26740 ((org-at-table-p) (call-interactively 'org-table-insert-row))
26741 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26742 ((org-at-item-p) (call-interactively 'org-move-item-down))
26743 (t (org-shiftcursor-error))))
26745 (defun org-metaleft (&optional arg)
26746 "Promote heading or move table column to left.
26747 Calls `org-do-promote' or `org-table-move-column', depending on context.
26748 With no specific context, calls the Emacs default `backward-word'.
26749 See the individual commands for more information."
26750 (interactive "P")
26751 (cond
26752 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
26753 ((or (org-on-heading-p) (org-region-active-p))
26754 (call-interactively 'org-do-promote))
26755 ((org-at-item-p) (call-interactively 'org-outdent-item))
26756 (t (call-interactively 'backward-word))))
26758 (defun org-metaright (&optional arg)
26759 "Demote subtree or move table column to right.
26760 Calls `org-do-demote' or `org-table-move-column', depending on context.
26761 With no specific context, calls the Emacs default `forward-word'.
26762 See the individual commands for more information."
26763 (interactive "P")
26764 (cond
26765 ((org-at-table-p) (call-interactively 'org-table-move-column))
26766 ((or (org-on-heading-p) (org-region-active-p))
26767 (call-interactively 'org-do-demote))
26768 ((org-at-item-p) (call-interactively 'org-indent-item))
26769 (t (call-interactively 'forward-word))))
26771 (defun org-metaup (&optional arg)
26772 "Move subtree up or move table row up.
26773 Calls `org-move-subtree-up' or `org-table-move-row' or
26774 `org-move-item-up', depending on context. See the individual commands
26775 for more information."
26776 (interactive "P")
26777 (cond
26778 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
26779 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26780 ((org-at-item-p) (call-interactively 'org-move-item-up))
26781 (t (transpose-lines 1) (beginning-of-line -1))))
26783 (defun org-metadown (&optional arg)
26784 "Move subtree down or move table row down.
26785 Calls `org-move-subtree-down' or `org-table-move-row' or
26786 `org-move-item-down', depending on context. See the individual
26787 commands for more information."
26788 (interactive "P")
26789 (cond
26790 ((org-at-table-p) (call-interactively 'org-table-move-row))
26791 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26792 ((org-at-item-p) (call-interactively 'org-move-item-down))
26793 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
26795 (defun org-shiftup (&optional arg)
26796 "Increase item in timestamp or increase priority of current headline.
26797 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
26798 depending on context. See the individual commands for more information."
26799 (interactive "P")
26800 (cond
26801 ((org-at-timestamp-p t)
26802 (call-interactively (if org-edit-timestamp-down-means-later
26803 'org-timestamp-down 'org-timestamp-up)))
26804 ((org-on-heading-p) (call-interactively 'org-priority-up))
26805 ((org-at-item-p) (call-interactively 'org-previous-item))
26806 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
26808 (defun org-shiftdown (&optional arg)
26809 "Decrease item in timestamp or decrease priority of current headline.
26810 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
26811 depending on context. See the individual commands for more information."
26812 (interactive "P")
26813 (cond
26814 ((org-at-timestamp-p t)
26815 (call-interactively (if org-edit-timestamp-down-means-later
26816 'org-timestamp-up 'org-timestamp-down)))
26817 ((org-on-heading-p) (call-interactively 'org-priority-down))
26818 (t (call-interactively 'org-next-item))))
26820 (defun org-shiftright ()
26821 "Next TODO keyword or timestamp one day later, depending on context."
26822 (interactive)
26823 (cond
26824 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
26825 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
26826 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
26827 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
26828 (t (org-shiftcursor-error))))
26830 (defun org-shiftleft ()
26831 "Previous TODO keyword or timestamp one day earlier, depending on context."
26832 (interactive)
26833 (cond
26834 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
26835 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
26836 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
26837 ((org-at-property-p)
26838 (call-interactively 'org-property-previous-allowed-value))
26839 (t (org-shiftcursor-error))))
26841 (defun org-shiftcontrolright ()
26842 "Switch to next TODO set."
26843 (interactive)
26844 (cond
26845 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
26846 (t (org-shiftcursor-error))))
26848 (defun org-shiftcontrolleft ()
26849 "Switch to previous TODO set."
26850 (interactive)
26851 (cond
26852 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
26853 (t (org-shiftcursor-error))))
26855 (defun org-ctrl-c-ret ()
26856 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
26857 (interactive)
26858 (cond
26859 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
26860 (t (call-interactively 'org-insert-heading))))
26862 (defun org-copy-special ()
26863 "Copy region in table or copy current subtree.
26864 Calls `org-table-copy' or `org-copy-subtree', depending on context.
26865 See the individual commands for more information."
26866 (interactive)
26867 (call-interactively
26868 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
26870 (defun org-cut-special ()
26871 "Cut region in table or cut current subtree.
26872 Calls `org-table-copy' or `org-cut-subtree', depending on context.
26873 See the individual commands for more information."
26874 (interactive)
26875 (call-interactively
26876 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
26878 (defun org-paste-special (arg)
26879 "Paste rectangular region into table, or past subtree relative to level.
26880 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
26881 See the individual commands for more information."
26882 (interactive "P")
26883 (if (org-at-table-p)
26884 (org-table-paste-rectangle)
26885 (org-paste-subtree arg)))
26887 (defun org-ctrl-c-ctrl-c (&optional arg)
26888 "Set tags in headline, or update according to changed information at point.
26890 This command does many different things, depending on context:
26892 - If the cursor is in a headline, prompt for tags and insert them
26893 into the current line, aligned to `org-tags-column'. When called
26894 with prefix arg, realign all tags in the current buffer.
26896 - If the cursor is in one of the special #+KEYWORD lines, this
26897 triggers scanning the buffer for these lines and updating the
26898 information.
26900 - If the cursor is inside a table, realign the table. This command
26901 works even if the automatic table editor has been turned off.
26903 - If the cursor is on a #+TBLFM line, re-apply the formulas to
26904 the entire table.
26906 - If the cursor is a the beginning of a dynamic block, update it.
26908 - If the cursor is inside a table created by the table.el package,
26909 activate that table.
26911 - If the current buffer is a remember buffer, close note and file it.
26912 with a prefix argument, file it without further interaction to the default
26913 location.
26915 - If the cursor is on a <<<target>>>, update radio targets and corresponding
26916 links in this buffer.
26918 - If the cursor is on a numbered item in a plain list, renumber the
26919 ordered list.
26921 - If the cursor is on a checkbox, toggle it."
26922 (interactive "P")
26923 (let ((org-enable-table-editor t))
26924 (cond
26925 ((or org-clock-overlays
26926 org-occur-highlights
26927 org-latex-fragment-image-overlays)
26928 (org-remove-clock-overlays)
26929 (org-remove-occur-highlights)
26930 (org-remove-latex-fragment-image-overlays)
26931 (message "Temporary highlights/overlays removed from current buffer"))
26932 ((and (local-variable-p 'org-finish-function (current-buffer))
26933 (fboundp org-finish-function))
26934 (funcall org-finish-function))
26935 ((org-at-property-p)
26936 (call-interactively 'org-property-action))
26937 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
26938 ((org-on-heading-p) (call-interactively 'org-set-tags))
26939 ((org-at-table.el-p)
26940 (require 'table)
26941 (beginning-of-line 1)
26942 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
26943 (call-interactively 'table-recognize-table))
26944 ((org-at-table-p)
26945 (org-table-maybe-eval-formula)
26946 (if arg
26947 (call-interactively 'org-table-recalculate)
26948 (org-table-maybe-recalculate-line))
26949 (call-interactively 'org-table-align))
26950 ((org-at-item-checkbox-p)
26951 (call-interactively 'org-toggle-checkbox))
26952 ((org-at-item-p)
26953 (call-interactively 'org-maybe-renumber-ordered-list))
26954 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
26955 ;; Dynamic block
26956 (beginning-of-line 1)
26957 (org-update-dblock))
26958 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
26959 (cond
26960 ((equal (match-string 1) "TBLFM")
26961 ;; Recalculate the table before this line
26962 (save-excursion
26963 (beginning-of-line 1)
26964 (skip-chars-backward " \r\n\t")
26965 (if (org-at-table-p)
26966 (org-call-with-arg 'org-table-recalculate t))))
26968 (call-interactively 'org-mode-restart))))
26969 (t (error "C-c C-c can do nothing useful at this location.")))))
26971 (defun org-mode-restart ()
26972 "Restart Org-mode, to scan again for special lines.
26973 Also updates the keyword regular expressions."
26974 (interactive)
26975 (let ((org-inhibit-startup t)) (org-mode))
26976 (message "Org-mode restarted to refresh keyword and special line setup"))
26978 (defun org-kill-note-or-show-branches ()
26979 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
26980 (interactive)
26981 (if (not org-finish-function)
26982 (call-interactively 'show-branches)
26983 (let ((org-note-abort t))
26984 (funcall org-finish-function))))
26986 (defun org-return (&optional indent)
26987 "Goto next table row or insert a newline.
26988 Calls `org-table-next-row' or `newline', depending on context.
26989 See the individual commands for more information."
26990 (interactive)
26991 (cond
26992 ((bobp) (if indent (newline-and-indent) (newline)))
26993 ((and (org-at-heading-p)
26994 (looking-at
26995 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
26996 (org-show-entry)
26997 (end-of-line 1)
26998 (newline))
26999 ((org-at-table-p)
27000 (org-table-justify-field-maybe)
27001 (call-interactively 'org-table-next-row))
27002 (t (if indent (newline-and-indent) (newline)))))
27004 (defun org-return-indent ()
27005 (interactive)
27006 "Goto next table row or insert a newline and indent.
27007 Calls `org-table-next-row' or `newline-and-indent', depending on
27008 context. See the individual commands for more information."
27009 (org-return t))
27011 (defun org-ctrl-c-minus ()
27012 "Insert separator line in table or modify bullet type in list.
27013 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
27014 depending on context."
27015 (interactive)
27016 (cond
27017 ((org-at-table-p)
27018 (call-interactively 'org-table-insert-hline))
27019 ((org-on-heading-p)
27020 ;; Convert to item
27021 (save-excursion
27022 (beginning-of-line 1)
27023 (if (looking-at "\\*+ ")
27024 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
27025 ((org-in-item-p)
27026 (call-interactively 'org-cycle-list-bullet))
27027 (t (error "`C-c -' does have no function here."))))
27029 (defun org-meta-return (&optional arg)
27030 "Insert a new heading or wrap a region in a table.
27031 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
27032 See the individual commands for more information."
27033 (interactive "P")
27034 (cond
27035 ((org-at-table-p)
27036 (call-interactively 'org-table-wrap-region))
27037 (t (call-interactively 'org-insert-heading))))
27039 ;;; Menu entries
27041 ;; Define the Org-mode menus
27042 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
27043 '("Tbl"
27044 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
27045 ["Next Field" org-cycle (org-at-table-p)]
27046 ["Previous Field" org-shifttab (org-at-table-p)]
27047 ["Next Row" org-return (org-at-table-p)]
27048 "--"
27049 ["Blank Field" org-table-blank-field (org-at-table-p)]
27050 ["Edit Field" org-table-edit-field (org-at-table-p)]
27051 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
27052 "--"
27053 ("Column"
27054 ["Move Column Left" org-metaleft (org-at-table-p)]
27055 ["Move Column Right" org-metaright (org-at-table-p)]
27056 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
27057 ["Insert Column" org-shiftmetaright (org-at-table-p)])
27058 ("Row"
27059 ["Move Row Up" org-metaup (org-at-table-p)]
27060 ["Move Row Down" org-metadown (org-at-table-p)]
27061 ["Delete Row" org-shiftmetaup (org-at-table-p)]
27062 ["Insert Row" org-shiftmetadown (org-at-table-p)]
27063 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
27064 "--"
27065 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
27066 ("Rectangle"
27067 ["Copy Rectangle" org-copy-special (org-at-table-p)]
27068 ["Cut Rectangle" org-cut-special (org-at-table-p)]
27069 ["Paste Rectangle" org-paste-special (org-at-table-p)]
27070 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
27071 "--"
27072 ("Calculate"
27073 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
27074 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
27075 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
27076 "--"
27077 ["Recalculate line" org-table-recalculate (org-at-table-p)]
27078 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
27079 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
27080 "--"
27081 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
27082 "--"
27083 ["Sum Column/Rectangle" org-table-sum
27084 (or (org-at-table-p) (org-region-active-p))]
27085 ["Which Column?" org-table-current-column (org-at-table-p)])
27086 ["Debug Formulas"
27087 org-table-toggle-formula-debugger
27088 :style toggle :selected org-table-formula-debug]
27089 ["Show Col/Row Numbers"
27090 org-table-toggle-coordinate-overlays
27091 :style toggle :selected org-table-overlay-coordinates]
27092 "--"
27093 ["Create" org-table-create (and (not (org-at-table-p))
27094 org-enable-table-editor)]
27095 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
27096 ["Import from File" org-table-import (not (org-at-table-p))]
27097 ["Export to File" org-table-export (org-at-table-p)]
27098 "--"
27099 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
27101 (easy-menu-define org-org-menu org-mode-map "Org menu"
27102 '("Org"
27103 ("Show/Hide"
27104 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
27105 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
27106 ["Sparse Tree" org-occur t]
27107 ["Reveal Context" org-reveal t]
27108 ["Show All" show-all t]
27109 "--"
27110 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
27111 "--"
27112 ["New Heading" org-insert-heading t]
27113 ("Navigate Headings"
27114 ["Up" outline-up-heading t]
27115 ["Next" outline-next-visible-heading t]
27116 ["Previous" outline-previous-visible-heading t]
27117 ["Next Same Level" outline-forward-same-level t]
27118 ["Previous Same Level" outline-backward-same-level t]
27119 "--"
27120 ["Jump" org-goto t])
27121 ("Edit Structure"
27122 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
27123 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
27124 "--"
27125 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
27126 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
27127 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
27128 "--"
27129 ["Promote Heading" org-metaleft (not (org-at-table-p))]
27130 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
27131 ["Demote Heading" org-metaright (not (org-at-table-p))]
27132 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
27133 "--"
27134 ["Sort Region/Children" org-sort (not (org-at-table-p))]
27135 "--"
27136 ["Convert to odd levels" org-convert-to-odd-levels t]
27137 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
27138 ("Editing"
27139 ["Emphasis..." org-emphasize t])
27140 ("Archive"
27141 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
27142 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
27143 ; :active t :keys "C-u C-c C-x C-a"]
27144 ["Sparse trees open ARCHIVE trees"
27145 (setq org-sparse-tree-open-archived-trees
27146 (not org-sparse-tree-open-archived-trees))
27147 :style toggle :selected org-sparse-tree-open-archived-trees]
27148 ["Cycling opens ARCHIVE trees"
27149 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
27150 :style toggle :selected org-cycle-open-archived-trees]
27151 ["Agenda includes ARCHIVE trees"
27152 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
27153 :style toggle :selected (not org-agenda-skip-archived-trees)]
27154 "--"
27155 ["Move Subtree to Archive" org-advertized-archive-subtree t]
27156 ; ["Check and Move Children" (org-archive-subtree '(4))
27157 ; :active t :keys "C-u C-c C-x C-s"]
27159 "--"
27160 ("TODO Lists"
27161 ["TODO/DONE/-" org-todo t]
27162 ("Select keyword"
27163 ["Next keyword" org-shiftright (org-on-heading-p)]
27164 ["Previous keyword" org-shiftleft (org-on-heading-p)]
27165 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
27166 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
27167 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
27168 ["Show TODO Tree" org-show-todo-tree t]
27169 ["Global TODO list" org-todo-list t]
27170 "--"
27171 ["Set Priority" org-priority t]
27172 ["Priority Up" org-shiftup t]
27173 ["Priority Down" org-shiftdown t])
27174 ("TAGS and Properties"
27175 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
27176 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
27177 "--"
27178 ["Set property" 'org-set-property t]
27179 ["Column view of properties" org-columns t]
27180 ["Insert Column View DBlock" org-insert-columns-dblock t])
27181 ("Dates and Scheduling"
27182 ["Timestamp" org-time-stamp t]
27183 ["Timestamp (inactive)" org-time-stamp-inactive t]
27184 ("Change Date"
27185 ["1 Day Later" org-shiftright t]
27186 ["1 Day Earlier" org-shiftleft t]
27187 ["1 ... Later" org-shiftup t]
27188 ["1 ... Earlier" org-shiftdown t])
27189 ["Compute Time Range" org-evaluate-time-range t]
27190 ["Schedule Item" org-schedule t]
27191 ["Deadline" org-deadline t]
27192 "--"
27193 ["Custom time format" org-toggle-time-stamp-overlays
27194 :style radio :selected org-display-custom-times]
27195 "--"
27196 ["Goto Calendar" org-goto-calendar t]
27197 ["Date from Calendar" org-date-from-calendar t])
27198 ("Logging work"
27199 ["Clock in" org-clock-in t]
27200 ["Clock out" org-clock-out t]
27201 ["Clock cancel" org-clock-cancel t]
27202 ["Goto running clock" org-clock-goto t]
27203 ["Display times" org-clock-display t]
27204 ["Create clock table" org-clock-report t]
27205 "--"
27206 ["Record DONE time"
27207 (progn (setq org-log-done (not org-log-done))
27208 (message "Switching to %s will %s record a timestamp"
27209 (car org-done-keywords)
27210 (if org-log-done "automatically" "not")))
27211 :style toggle :selected org-log-done])
27212 "--"
27213 ["Agenda Command..." org-agenda t]
27214 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
27215 ("File List for Agenda")
27216 ("Special views current file"
27217 ["TODO Tree" org-show-todo-tree t]
27218 ["Check Deadlines" org-check-deadlines t]
27219 ["Timeline" org-timeline t]
27220 ["Tags Tree" org-tags-sparse-tree t])
27221 "--"
27222 ("Hyperlinks"
27223 ["Store Link (Global)" org-store-link t]
27224 ["Insert Link" org-insert-link t]
27225 ["Follow Link" org-open-at-point t]
27226 "--"
27227 ["Next link" org-next-link t]
27228 ["Previous link" org-previous-link t]
27229 "--"
27230 ["Descriptive Links"
27231 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
27232 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
27233 ["Literal Links"
27234 (progn
27235 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
27236 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
27237 "--"
27238 ["Export/Publish..." org-export t]
27239 ("LaTeX"
27240 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
27241 :selected org-cdlatex-mode]
27242 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
27243 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
27244 ["Modify math symbol" org-cdlatex-math-modify
27245 (org-inside-LaTeX-fragment-p)]
27246 ["Export LaTeX fragments as images"
27247 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
27248 :style toggle :selected org-export-with-LaTeX-fragments])
27249 "--"
27250 ("Documentation"
27251 ["Show Version" org-version t]
27252 ["Info Documentation" org-info t])
27253 ("Customize"
27254 ["Browse Org Group" org-customize t]
27255 "--"
27256 ["Expand This Menu" org-create-customize-menu
27257 (fboundp 'customize-menu-create)])
27258 "--"
27259 ["Refresh setup" org-mode-restart t]
27262 (defun org-info (&optional node)
27263 "Read documentation for Org-mode in the info system.
27264 With optional NODE, go directly to that node."
27265 (interactive)
27266 (require 'info)
27267 (Info-goto-node (format "(org)%s" (or node ""))))
27269 (defun org-install-agenda-files-menu ()
27270 (let ((bl (buffer-list)))
27271 (save-excursion
27272 (while bl
27273 (set-buffer (pop bl))
27274 (if (org-mode-p) (setq bl nil)))
27275 (when (org-mode-p)
27276 (easy-menu-change
27277 '("Org") "File List for Agenda"
27278 (append
27279 (list
27280 ["Edit File List" (org-edit-agenda-file-list) t]
27281 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
27282 ["Remove Current File from List" org-remove-file t]
27283 ["Cycle through agenda files" org-cycle-agenda-files t]
27284 ["Occur in all agenda files" org-occur-in-agenda-files t]
27285 "--")
27286 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
27288 ;;;; Documentation
27290 (defun org-customize ()
27291 "Call the customize function with org as argument."
27292 (interactive)
27293 (customize-browse 'org))
27295 (defun org-create-customize-menu ()
27296 "Create a full customization menu for Org-mode, insert it into the menu."
27297 (interactive)
27298 (if (fboundp 'customize-menu-create)
27299 (progn
27300 (easy-menu-change
27301 '("Org") "Customize"
27302 `(["Browse Org group" org-customize t]
27303 "--"
27304 ,(customize-menu-create 'org)
27305 ["Set" Custom-set t]
27306 ["Save" Custom-save t]
27307 ["Reset to Current" Custom-reset-current t]
27308 ["Reset to Saved" Custom-reset-saved t]
27309 ["Reset to Standard Settings" Custom-reset-standard t]))
27310 (message "\"Org\"-menu now contains full customization menu"))
27311 (error "Cannot expand menu (outdated version of cus-edit.el)")))
27313 ;;;; Miscellaneous stuff
27316 ;;; Generally useful functions
27318 (defun org-context ()
27319 "Return a list of contexts of the current cursor position.
27320 If several contexts apply, all are returned.
27321 Each context entry is a list with a symbol naming the context, and
27322 two positions indicating start and end of the context. Possible
27323 contexts are:
27325 :headline anywhere in a headline
27326 :headline-stars on the leading stars in a headline
27327 :todo-keyword on a TODO keyword (including DONE) in a headline
27328 :tags on the TAGS in a headline
27329 :priority on the priority cookie in a headline
27330 :item on the first line of a plain list item
27331 :item-bullet on the bullet/number of a plain list item
27332 :checkbox on the checkbox in a plain list item
27333 :table in an org-mode table
27334 :table-special on a special filed in a table
27335 :table-table in a table.el table
27336 :link on a hyperlink
27337 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
27338 :target on a <<target>>
27339 :radio-target on a <<<radio-target>>>
27340 :latex-fragment on a LaTeX fragment
27341 :latex-preview on a LaTeX fragment with overlayed preview image
27343 This function expects the position to be visible because it uses font-lock
27344 faces as a help to recognize the following contexts: :table-special, :link,
27345 and :keyword."
27346 (let* ((f (get-text-property (point) 'face))
27347 (faces (if (listp f) f (list f)))
27348 (p (point)) clist o)
27349 ;; First the large context
27350 (cond
27351 ((org-on-heading-p t)
27352 (push (list :headline (point-at-bol) (point-at-eol)) clist)
27353 (when (progn
27354 (beginning-of-line 1)
27355 (looking-at org-todo-line-tags-regexp))
27356 (push (org-point-in-group p 1 :headline-stars) clist)
27357 (push (org-point-in-group p 2 :todo-keyword) clist)
27358 (push (org-point-in-group p 4 :tags) clist))
27359 (goto-char p)
27360 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
27361 (if (looking-at "\\[#[A-Z0-9]\\]")
27362 (push (org-point-in-group p 0 :priority) clist)))
27364 ((org-at-item-p)
27365 (push (org-point-in-group p 2 :item-bullet) clist)
27366 (push (list :item (point-at-bol)
27367 (save-excursion (org-end-of-item) (point)))
27368 clist)
27369 (and (org-at-item-checkbox-p)
27370 (push (org-point-in-group p 0 :checkbox) clist)))
27372 ((org-at-table-p)
27373 (push (list :table (org-table-begin) (org-table-end)) clist)
27374 (if (memq 'org-formula faces)
27375 (push (list :table-special
27376 (previous-single-property-change p 'face)
27377 (next-single-property-change p 'face)) clist)))
27378 ((org-at-table-p 'any)
27379 (push (list :table-table) clist)))
27380 (goto-char p)
27382 ;; Now the small context
27383 (cond
27384 ((org-at-timestamp-p)
27385 (push (org-point-in-group p 0 :timestamp) clist))
27386 ((memq 'org-link faces)
27387 (push (list :link
27388 (previous-single-property-change p 'face)
27389 (next-single-property-change p 'face)) clist))
27390 ((memq 'org-special-keyword faces)
27391 (push (list :keyword
27392 (previous-single-property-change p 'face)
27393 (next-single-property-change p 'face)) clist))
27394 ((org-on-target-p)
27395 (push (org-point-in-group p 0 :target) clist)
27396 (goto-char (1- (match-beginning 0)))
27397 (if (looking-at org-radio-target-regexp)
27398 (push (org-point-in-group p 0 :radio-target) clist))
27399 (goto-char p))
27400 ((setq o (car (delq nil
27401 (mapcar
27402 (lambda (x)
27403 (if (memq x org-latex-fragment-image-overlays) x))
27404 (org-overlays-at (point))))))
27405 (push (list :latex-fragment
27406 (org-overlay-start o) (org-overlay-end o)) clist)
27407 (push (list :latex-preview
27408 (org-overlay-start o) (org-overlay-end o)) clist))
27409 ((org-inside-LaTeX-fragment-p)
27410 ;; FIXME: positions wrong.
27411 (push (list :latex-fragment (point) (point)) clist)))
27413 (setq clist (nreverse (delq nil clist)))
27414 clist))
27416 ;; FIXME: Compare with at-regexp-p Do we need both?
27417 (defun org-in-regexp (re &optional nlines visually)
27418 "Check if point is inside a match of regexp.
27419 Normally only the current line is checked, but you can include NLINES extra
27420 lines both before and after point into the search.
27421 If VISUALLY is set, require that the cursor is not after the match but
27422 really on, so that the block visually is on the match."
27423 (catch 'exit
27424 (let ((pos (point))
27425 (eol (point-at-eol (+ 1 (or nlines 0))))
27426 (inc (if visually 1 0)))
27427 (save-excursion
27428 (beginning-of-line (- 1 (or nlines 0)))
27429 (while (re-search-forward re eol t)
27430 (if (and (<= (match-beginning 0) pos)
27431 (>= (+ inc (match-end 0)) pos))
27432 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
27434 (defun org-at-regexp-p (regexp)
27435 "Is point inside a match of REGEXP in the current line?"
27436 (catch 'exit
27437 (save-excursion
27438 (let ((pos (point)) (end (point-at-eol)))
27439 (beginning-of-line 1)
27440 (while (re-search-forward regexp end t)
27441 (if (and (<= (match-beginning 0) pos)
27442 (>= (match-end 0) pos))
27443 (throw 'exit t)))
27444 nil))))
27446 (defun org-occur-in-agenda-files (regexp &optional nlines)
27447 "Call `multi-occur' with buffers for all agenda files."
27448 (interactive "sOrg-files matching: \np")
27449 (let* ((files (org-agenda-files))
27450 (tnames (mapcar 'file-truename files))
27451 (extra org-agenda-multi-occur-extra-files)
27453 (while (setq f (pop extra))
27454 (unless (member (file-truename f) tnames)
27455 (add-to-list 'files f 'append)
27456 (add-to-list 'tnames (file-truename f) 'append)))
27457 (multi-occur
27458 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
27459 regexp)))
27461 (if (boundp 'occur-mode-find-occurrence-hook)
27462 ;; Emacs 23
27463 (add-hook 'occur-mode-find-occurrence-hook
27464 (lambda ()
27465 (when (org-mode-p)
27466 (org-reveal))))
27467 ;; Emacs 22
27468 (defadvice occur-mode-goto-occurrence
27469 (after org-occur-reveal activate)
27470 (and (org-mode-p) (org-reveal)))
27471 (defadvice occur-mode-goto-occurrence-other-window
27472 (after org-occur-reveal activate)
27473 (and (org-mode-p) (org-reveal)))
27474 (defadvice occur-mode-display-occurrence
27475 (after org-occur-reveal activate)
27476 (when (org-mode-p)
27477 (let ((pos (occur-mode-find-occurrence)))
27478 (with-current-buffer (marker-buffer pos)
27479 (save-excursion
27480 (goto-char pos)
27481 (org-reveal)))))))
27483 (defun org-uniquify (list)
27484 "Remove duplicate elements from LIST."
27485 (let (res)
27486 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
27487 res))
27489 (defun org-delete-all (elts list)
27490 "Remove all elements in ELTS from LIST."
27491 (while elts
27492 (setq list (delete (pop elts) list)))
27493 list)
27495 (defun org-back-over-empty-lines ()
27496 "Move backwards over witespace, to the beginning of the first empty line.
27497 Returns the number o empty lines passed."
27498 (let ((pos (point)))
27499 (skip-chars-backward " \t\n\r")
27500 (beginning-of-line 2)
27501 (goto-char (min (point) pos))
27502 (count-lines (point) pos)))
27504 (defun org-skip-whitespace ()
27505 (skip-chars-forward " \t\n\r"))
27507 (defun org-point-in-group (point group &optional context)
27508 "Check if POINT is in match-group GROUP.
27509 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
27510 match. If the match group does ot exist or point is not inside it,
27511 return nil."
27512 (and (match-beginning group)
27513 (>= point (match-beginning group))
27514 (<= point (match-end group))
27515 (if context
27516 (list context (match-beginning group) (match-end group))
27517 t)))
27519 (defun org-switch-to-buffer-other-window (&rest args)
27520 "Switch to buffer in a second window on the current frame.
27521 In particular, do not allow pop-up frames."
27522 (let (pop-up-frames special-display-buffer-names special-display-regexps
27523 special-display-function)
27524 (apply 'switch-to-buffer-other-window args)))
27526 (defun org-combine-plists (&rest plists)
27527 "Create a single property list from all plists in PLISTS.
27528 The process starts by copying the first list, and then setting properties
27529 from the other lists. Settings in the last list are the most significant
27530 ones and overrule settings in the other lists."
27531 (let ((rtn (copy-sequence (pop plists)))
27532 p v ls)
27533 (while plists
27534 (setq ls (pop plists))
27535 (while ls
27536 (setq p (pop ls) v (pop ls))
27537 (setq rtn (plist-put rtn p v))))
27538 rtn))
27540 (defun org-move-line-down (arg)
27541 "Move the current line down. With prefix argument, move it past ARG lines."
27542 (interactive "p")
27543 (let ((col (current-column))
27544 beg end pos)
27545 (beginning-of-line 1) (setq beg (point))
27546 (beginning-of-line 2) (setq end (point))
27547 (beginning-of-line (+ 1 arg))
27548 (setq pos (move-marker (make-marker) (point)))
27549 (insert (delete-and-extract-region beg end))
27550 (goto-char pos)
27551 (move-to-column col)))
27553 (defun org-move-line-up (arg)
27554 "Move the current line up. With prefix argument, move it past ARG lines."
27555 (interactive "p")
27556 (let ((col (current-column))
27557 beg end pos)
27558 (beginning-of-line 1) (setq beg (point))
27559 (beginning-of-line 2) (setq end (point))
27560 (beginning-of-line (- arg))
27561 (setq pos (move-marker (make-marker) (point)))
27562 (insert (delete-and-extract-region beg end))
27563 (goto-char pos)
27564 (move-to-column col)))
27566 (defun org-replace-escapes (string table)
27567 "Replace %-escapes in STRING with values in TABLE.
27568 TABLE is an association list with keys like \"%a\" and string values.
27569 The sequences in STRING may contain normal field width and padding information,
27570 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
27571 so values can contain further %-escapes if they are define later in TABLE."
27572 (let ((case-fold-search nil)
27573 e re rpl)
27574 (while (setq e (pop table))
27575 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
27576 (while (string-match re string)
27577 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
27578 (cdr e)))
27579 (setq string (replace-match rpl t t string))))
27580 string))
27583 (defun org-sublist (list start end)
27584 "Return a section of LIST, from START to END.
27585 Counting starts at 1."
27586 (let (rtn (c start))
27587 (setq list (nthcdr (1- start) list))
27588 (while (and list (<= c end))
27589 (push (pop list) rtn)
27590 (setq c (1+ c)))
27591 (nreverse rtn)))
27593 (defun org-find-base-buffer-visiting (file)
27594 "Like `find-buffer-visiting' but alway return the base buffer and
27595 not an indirect buffer"
27596 (let ((buf (find-buffer-visiting file)))
27597 (if buf
27598 (or (buffer-base-buffer buf) buf)
27599 nil)))
27601 (defun org-image-file-name-regexp ()
27602 "Return regexp matching the file names of images."
27603 (if (fboundp 'image-file-name-regexp)
27604 (image-file-name-regexp)
27605 (let ((image-file-name-extensions
27606 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
27607 "xbm" "xpm" "pbm" "pgm" "ppm")))
27608 (concat "\\."
27609 (regexp-opt (nconc (mapcar 'upcase
27610 image-file-name-extensions)
27611 image-file-name-extensions)
27613 "\\'"))))
27615 (defun org-file-image-p (file)
27616 "Return non-nil if FILE is an image."
27617 (save-match-data
27618 (string-match (org-image-file-name-regexp) file)))
27620 ;;; Paragraph filling stuff.
27621 ;; We want this to be just right, so use the full arsenal.
27623 (defun org-indent-line-function ()
27624 "Indent line like previous, but further if previous was headline or item."
27625 (interactive)
27626 (let* ((pos (point))
27627 (itemp (org-at-item-p))
27628 column bpos bcol tpos tcol bullet btype bullet-type)
27629 ;; Find the previous relevant line
27630 (beginning-of-line 1)
27631 (cond
27632 ((looking-at "#") (setq column 0))
27633 ((looking-at "\\*+ ") (setq column 0))
27635 (beginning-of-line 0)
27636 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
27637 (beginning-of-line 0))
27638 (cond
27639 ((looking-at "\\*+[ \t]+")
27640 (goto-char (match-end 0))
27641 (setq column (current-column)))
27642 ((org-in-item-p)
27643 (org-beginning-of-item)
27644 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
27645 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
27646 (setq bpos (match-beginning 1) tpos (match-end 0)
27647 bcol (progn (goto-char bpos) (current-column))
27648 tcol (progn (goto-char tpos) (current-column))
27649 bullet (match-string 1)
27650 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
27651 (if (not itemp)
27652 (setq column tcol)
27653 (goto-char pos)
27654 (beginning-of-line 1)
27655 (if (looking-at "\\S-")
27656 (progn
27657 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
27658 (setq bullet (match-string 1)
27659 btype (if (string-match "[0-9]" bullet) "n" bullet))
27660 (setq column (if (equal btype bullet-type) bcol tcol)))
27661 (setq column (org-get-indentation)))))
27662 (t (setq column (org-get-indentation))))))
27663 (goto-char pos)
27664 (if (<= (current-column) (current-indentation))
27665 (indent-line-to column)
27666 (save-excursion (indent-line-to column)))
27667 (setq column (current-column))
27668 (beginning-of-line 1)
27669 (if (looking-at
27670 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
27671 (replace-match (concat "\\1" (format org-property-format
27672 (match-string 2) (match-string 3)))
27673 t nil))
27674 (move-to-column column)))
27676 (defun org-set-autofill-regexps ()
27677 (interactive)
27678 ;; In the paragraph separator we include headlines, because filling
27679 ;; text in a line directly attached to a headline would otherwise
27680 ;; fill the headline as well.
27681 (org-set-local 'comment-start-skip "^#+[ \t]*")
27682 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
27683 ;; The paragraph starter includes hand-formatted lists.
27684 (org-set-local 'paragraph-start
27685 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
27686 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
27687 ;; But only if the user has not turned off tables or fixed-width regions
27688 (org-set-local
27689 'auto-fill-inhibit-regexp
27690 (concat "\\*+ \\|#\\+"
27691 "\\|[ \t]*" org-keyword-time-regexp
27692 (if (or org-enable-table-editor org-enable-fixed-width-editor)
27693 (concat
27694 "\\|[ \t]*["
27695 (if org-enable-table-editor "|" "")
27696 (if org-enable-fixed-width-editor ":" "")
27697 "]"))))
27698 ;; We use our own fill-paragraph function, to make sure that tables
27699 ;; and fixed-width regions are not wrapped. That function will pass
27700 ;; through to `fill-paragraph' when appropriate.
27701 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
27702 ; Adaptive filling: To get full control, first make sure that
27703 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
27704 (org-set-local 'adaptive-fill-regexp "\000")
27705 (org-set-local 'adaptive-fill-function
27706 'org-adaptive-fill-function)
27707 (org-set-local
27708 'align-mode-rules-list
27709 '((org-in-buffer-settings
27710 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
27711 (modes . '(org-mode))))))
27713 (defun org-fill-paragraph (&optional justify)
27714 "Re-align a table, pass through to fill-paragraph if no table."
27715 (let ((table-p (org-at-table-p))
27716 (table.el-p (org-at-table.el-p)))
27717 (cond ((and (equal (char-after (point-at-bol)) ?*)
27718 (save-excursion (goto-char (point-at-bol))
27719 (looking-at outline-regexp)))
27720 t) ; skip headlines
27721 (table.el-p t) ; skip table.el tables
27722 (table-p (org-table-align) t) ; align org-mode tables
27723 (t nil)))) ; call paragraph-fill
27725 ;; For reference, this is the default value of adaptive-fill-regexp
27726 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
27728 (defun org-adaptive-fill-function ()
27729 "Return a fill prefix for org-mode files.
27730 In particular, this makes sure hanging paragraphs for hand-formatted lists
27731 work correctly."
27732 (cond ((looking-at "#[ \t]+")
27733 (match-string 0))
27734 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
27735 (save-excursion
27736 (goto-char (match-end 0))
27737 (make-string (current-column) ?\ )))
27738 (t nil)))
27740 ;;;; Functions extending outline functionality
27743 (defun org-beginning-of-line (&optional arg)
27744 "Go to the beginning of the current line. If that is invisible, continue
27745 to a visible line beginning. This makes the function of C-a more intuitive.
27746 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27747 first attempt, and only move to after the tags when the cursor is already
27748 beyond the end of the headline."
27749 (interactive "P")
27750 (let ((pos (point)))
27751 (beginning-of-line 1)
27752 (if (bobp)
27754 (backward-char 1)
27755 (if (org-invisible-p)
27756 (while (and (not (bobp)) (org-invisible-p))
27757 (backward-char 1)
27758 (beginning-of-line 1))
27759 (forward-char 1)))
27760 (when org-special-ctrl-a/e
27761 (cond
27762 ((and (looking-at org-todo-line-regexp)
27763 (= (char-after (match-end 1)) ?\ ))
27764 (goto-char
27765 (if (eq org-special-ctrl-a/e t)
27766 (cond ((> pos (match-beginning 3)) (match-beginning 3))
27767 ((= pos (point)) (match-beginning 3))
27768 (t (point)))
27769 (cond ((> pos (point)) (point))
27770 ((not (eq last-command this-command)) (point))
27771 (t (match-beginning 3))))))
27772 ((org-at-item-p)
27773 (goto-char
27774 (if (eq org-special-ctrl-a/e t)
27775 (cond ((> pos (match-end 4)) (match-end 4))
27776 ((= pos (point)) (match-end 4))
27777 (t (point)))
27778 (cond ((> pos (point)) (point))
27779 ((not (eq last-command this-command)) (point))
27780 (t (match-end 4))))))))))
27782 (defun org-end-of-line (&optional arg)
27783 "Go to the end of the line.
27784 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27785 first attempt, and only move to after the tags when the cursor is already
27786 beyond the end of the headline."
27787 (interactive "P")
27788 (if (or (not org-special-ctrl-a/e)
27789 (not (org-on-heading-p)))
27790 (end-of-line arg)
27791 (let ((pos (point)))
27792 (beginning-of-line 1)
27793 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
27794 (if (eq org-special-ctrl-a/e t)
27795 (if (or (< pos (match-beginning 1))
27796 (= pos (match-end 0)))
27797 (goto-char (match-beginning 1))
27798 (goto-char (match-end 0)))
27799 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
27800 (goto-char (match-end 0))
27801 (goto-char (match-beginning 1))))
27802 (end-of-line arg)))))
27804 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
27805 (define-key org-mode-map "\C-e" 'org-end-of-line)
27807 (defun org-kill-line (&optional arg)
27808 "Kill line, to tags or end of line."
27809 (interactive "P")
27810 (cond
27811 ((or (not org-special-ctrl-k)
27812 (bolp)
27813 (not (org-on-heading-p)))
27814 (call-interactively 'kill-line))
27815 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
27816 (kill-region (point) (match-beginning 1))
27817 (org-set-tags nil t))
27818 (t (kill-region (point) (point-at-eol)))))
27820 (define-key org-mode-map "\C-k" 'org-kill-line)
27822 (defun org-invisible-p ()
27823 "Check if point is at a character currently not visible."
27824 ;; Early versions of noutline don't have `outline-invisible-p'.
27825 (if (fboundp 'outline-invisible-p)
27826 (outline-invisible-p)
27827 (get-char-property (point) 'invisible)))
27829 (defun org-invisible-p2 ()
27830 "Check if point is at a character currently not visible."
27831 (save-excursion
27832 (if (and (eolp) (not (bobp))) (backward-char 1))
27833 ;; Early versions of noutline don't have `outline-invisible-p'.
27834 (if (fboundp 'outline-invisible-p)
27835 (outline-invisible-p)
27836 (get-char-property (point) 'invisible))))
27838 (defalias 'org-back-to-heading 'outline-back-to-heading)
27839 (defalias 'org-on-heading-p 'outline-on-heading-p)
27840 (defalias 'org-at-heading-p 'outline-on-heading-p)
27841 (defun org-at-heading-or-item-p ()
27842 (or (org-on-heading-p) (org-at-item-p)))
27844 (defun org-on-target-p ()
27845 (or (org-in-regexp org-radio-target-regexp)
27846 (org-in-regexp org-target-regexp)))
27848 (defun org-up-heading-all (arg)
27849 "Move to the heading line of which the present line is a subheading.
27850 This function considers both visible and invisible heading lines.
27851 With argument, move up ARG levels."
27852 (if (fboundp 'outline-up-heading-all)
27853 (outline-up-heading-all arg) ; emacs 21 version of outline.el
27854 (outline-up-heading arg t))) ; emacs 22 version of outline.el
27856 (defun org-up-heading-safe ()
27857 "Move to the heading line of which the present line is a subheading.
27858 This version will not throw an error. It will return the level of the
27859 headline found, or nil if no higher level is found."
27860 (let ((pos (point)) start-level level
27861 (re (concat "^" outline-regexp)))
27862 (catch 'exit
27863 (outline-back-to-heading t)
27864 (setq start-level (funcall outline-level))
27865 (if (equal start-level 1) (throw 'exit nil))
27866 (while (re-search-backward re nil t)
27867 (setq level (funcall outline-level))
27868 (if (< level start-level) (throw 'exit level)))
27869 nil)))
27871 (defun org-first-sibling-p ()
27872 "Is this heading the first child of its parents?"
27873 (interactive)
27874 (let ((re (concat "^" outline-regexp))
27875 level l)
27876 (unless (org-at-heading-p t)
27877 (error "Not at a heading"))
27878 (setq level (funcall outline-level))
27879 (save-excursion
27880 (if (not (re-search-backward re nil t))
27882 (setq l (funcall outline-level))
27883 (< l level)))))
27885 (defun org-goto-sibling (&optional previous)
27886 "Goto the next sibling, even if it is invisible.
27887 When PREVIOUS is set, go to the previous sibling instead. Returns t
27888 when a sibling was found. When none is found, return nil and don't
27889 move point."
27890 (let ((fun (if previous 're-search-backward 're-search-forward))
27891 (pos (point))
27892 (re (concat "^" outline-regexp))
27893 level l)
27894 (when (condition-case nil (org-back-to-heading t) (error nil))
27895 (setq level (funcall outline-level))
27896 (catch 'exit
27897 (or previous (forward-char 1))
27898 (while (funcall fun re nil t)
27899 (setq l (funcall outline-level))
27900 (when (< l level) (goto-char pos) (throw 'exit nil))
27901 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
27902 (goto-char pos)
27903 nil))))
27905 (defun org-show-siblings ()
27906 "Show all siblings of the current headline."
27907 (save-excursion
27908 (while (org-goto-sibling) (org-flag-heading nil)))
27909 (save-excursion
27910 (while (org-goto-sibling 'previous)
27911 (org-flag-heading nil))))
27913 (defun org-show-hidden-entry ()
27914 "Show an entry where even the heading is hidden."
27915 (save-excursion
27916 (org-show-entry)))
27918 (defun org-flag-heading (flag &optional entry)
27919 "Flag the current heading. FLAG non-nil means make invisible.
27920 When ENTRY is non-nil, show the entire entry."
27921 (save-excursion
27922 (org-back-to-heading t)
27923 ;; Check if we should show the entire entry
27924 (if entry
27925 (progn
27926 (org-show-entry)
27927 (save-excursion
27928 (and (outline-next-heading)
27929 (org-flag-heading nil))))
27930 (outline-flag-region (max (point-min) (1- (point)))
27931 (save-excursion (outline-end-of-heading) (point))
27932 flag))))
27934 (defun org-end-of-subtree (&optional invisible-OK to-heading)
27935 ;; This is an exact copy of the original function, but it uses
27936 ;; `org-back-to-heading', to make it work also in invisible
27937 ;; trees. And is uses an invisible-OK argument.
27938 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
27939 (org-back-to-heading invisible-OK)
27940 (let ((first t)
27941 (level (funcall outline-level)))
27942 (while (and (not (eobp))
27943 (or first (> (funcall outline-level) level)))
27944 (setq first nil)
27945 (outline-next-heading))
27946 (unless to-heading
27947 (if (memq (preceding-char) '(?\n ?\^M))
27948 (progn
27949 ;; Go to end of line before heading
27950 (forward-char -1)
27951 (if (memq (preceding-char) '(?\n ?\^M))
27952 ;; leave blank line before heading
27953 (forward-char -1))))))
27954 (point))
27956 (defun org-show-subtree ()
27957 "Show everything after this heading at deeper levels."
27958 (outline-flag-region
27959 (point)
27960 (save-excursion
27961 (outline-end-of-subtree) (outline-next-heading) (point))
27962 nil))
27964 (defun org-show-entry ()
27965 "Show the body directly following this heading.
27966 Show the heading too, if it is currently invisible."
27967 (interactive)
27968 (save-excursion
27969 (condition-case nil
27970 (progn
27971 (org-back-to-heading t)
27972 (outline-flag-region
27973 (max (point-min) (1- (point)))
27974 (save-excursion
27975 (re-search-forward
27976 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
27977 (or (match-beginning 1) (point-max)))
27978 nil))
27979 (error nil))))
27981 (defun org-make-options-regexp (kwds)
27982 "Make a regular expression for keyword lines."
27983 (concat
27985 "#?[ \t]*\\+\\("
27986 (mapconcat 'regexp-quote kwds "\\|")
27987 "\\):[ \t]*"
27988 "\\(.+\\)"))
27990 ;; Make isearch reveal the necessary context
27991 (defun org-isearch-end ()
27992 "Reveal context after isearch exits."
27993 (when isearch-success ; only if search was successful
27994 (if (featurep 'xemacs)
27995 ;; Under XEmacs, the hook is run in the correct place,
27996 ;; we directly show the context.
27997 (org-show-context 'isearch)
27998 ;; In Emacs the hook runs *before* restoring the overlays.
27999 ;; So we have to use a one-time post-command-hook to do this.
28000 ;; (Emacs 22 has a special variable, see function `org-mode')
28001 (unless (and (boundp 'isearch-mode-end-hook-quit)
28002 isearch-mode-end-hook-quit)
28003 ;; Only when the isearch was not quitted.
28004 (org-add-hook 'post-command-hook 'org-isearch-post-command
28005 'append 'local)))))
28007 (defun org-isearch-post-command ()
28008 "Remove self from hook, and show context."
28009 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
28010 (org-show-context 'isearch))
28013 ;;;; Integration with and fixes for other packages
28015 ;;; Imenu support
28017 (defvar org-imenu-markers nil
28018 "All markers currently used by Imenu.")
28019 (make-variable-buffer-local 'org-imenu-markers)
28021 (defun org-imenu-new-marker (&optional pos)
28022 "Return a new marker for use by Imenu, and remember the marker."
28023 (let ((m (make-marker)))
28024 (move-marker m (or pos (point)))
28025 (push m org-imenu-markers)
28028 (defun org-imenu-get-tree ()
28029 "Produce the index for Imenu."
28030 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
28031 (setq org-imenu-markers nil)
28032 (let* ((n org-imenu-depth)
28033 (re (concat "^" outline-regexp))
28034 (subs (make-vector (1+ n) nil))
28035 (last-level 0)
28036 m tree level head)
28037 (save-excursion
28038 (save-restriction
28039 (widen)
28040 (goto-char (point-max))
28041 (while (re-search-backward re nil t)
28042 (setq level (org-reduced-level (funcall outline-level)))
28043 (when (<= level n)
28044 (looking-at org-complex-heading-regexp)
28045 (setq head (org-match-string-no-properties 4)
28046 m (org-imenu-new-marker))
28047 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
28048 (if (>= level last-level)
28049 (push (cons head m) (aref subs level))
28050 (push (cons head (aref subs (1+ level))) (aref subs level))
28051 (loop for i from (1+ level) to n do (aset subs i nil)))
28052 (setq last-level level)))))
28053 (aref subs 1)))
28055 (eval-after-load "imenu"
28056 '(progn
28057 (add-hook 'imenu-after-jump-hook
28058 (lambda () (org-show-context 'org-goto)))))
28060 ;; Speedbar support
28062 (defun org-speedbar-set-agenda-restriction ()
28063 "Restrict future agenda commands to the location at point in speedbar.
28064 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
28065 (interactive)
28066 (let (p m tp np dir txt w)
28067 (cond
28068 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28069 'org-imenu t))
28070 (setq m (get-text-property p 'org-imenu-marker))
28071 (save-excursion
28072 (save-restriction
28073 (set-buffer (marker-buffer m))
28074 (goto-char m)
28075 (org-agenda-set-restriction-lock 'subtree))))
28076 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28077 'speedbar-function 'speedbar-find-file))
28078 (setq tp (previous-single-property-change
28079 (1+ p) 'speedbar-function)
28080 np (next-single-property-change
28081 tp 'speedbar-function)
28082 dir (speedbar-line-directory)
28083 txt (buffer-substring-no-properties (or tp (point-min))
28084 (or np (point-max))))
28085 (save-excursion
28086 (save-restriction
28087 (set-buffer (find-file-noselect
28088 (let ((default-directory dir))
28089 (expand-file-name txt))))
28090 (unless (org-mode-p)
28091 (error "Cannot restrict to non-Org-mode file"))
28092 (org-agenda-set-restriction-lock 'file))))
28093 (t (error "Don't know how to restrict Org-mode's agenda")))
28094 (org-move-overlay org-speedbar-restriction-lock-overlay
28095 (point-at-bol) (point-at-eol))
28096 (setq current-prefix-arg nil)
28097 (org-agenda-maybe-redo)))
28099 (eval-after-load "speedbar"
28100 '(progn
28101 (speedbar-add-supported-extension ".org")
28102 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
28103 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
28104 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
28105 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
28106 (add-hook 'speedbar-visiting-tag-hook
28107 (lambda () (org-show-context 'org-goto)))))
28110 ;;; Fixes and Hacks
28112 ;; Make flyspell not check words in links, to not mess up our keymap
28113 (defun org-mode-flyspell-verify ()
28114 "Don't let flyspell put overlays at active buttons."
28115 (not (get-text-property (point) 'keymap)))
28117 ;; Make `bookmark-jump' show the jump location if it was hidden.
28118 (eval-after-load "bookmark"
28119 '(if (boundp 'bookmark-after-jump-hook)
28120 ;; We can use the hook
28121 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
28122 ;; Hook not available, use advice
28123 (defadvice bookmark-jump (after org-make-visible activate)
28124 "Make the position visible."
28125 (org-bookmark-jump-unhide))))
28127 (defun org-bookmark-jump-unhide ()
28128 "Unhide the current position, to show the bookmark location."
28129 (and (org-mode-p)
28130 (or (org-invisible-p)
28131 (save-excursion (goto-char (max (point-min) (1- (point))))
28132 (org-invisible-p)))
28133 (org-show-context 'bookmark-jump)))
28135 ;; Fix a bug in htmlize where there are text properties (face nil)
28136 (eval-after-load "htmlize"
28137 '(progn
28138 (defadvice htmlize-faces-in-buffer (after org-no-nil-faces activate)
28139 "Make sure there are no nil faces"
28140 (setq ad-return-value (delq nil ad-return-value)))))
28142 ;; Make session.el ignore our circular variable
28143 (eval-after-load "session"
28144 '(add-to-list 'session-globals-exclude 'org-mark-ring))
28146 ;;;; Experimental code
28148 (defun org-closed-in-range ()
28149 "Sparse tree of items closed in a certain time range.
28150 Still experimental, may disappear in the future."
28151 (interactive)
28152 ;; Get the time interval from the user.
28153 (let* ((time1 (time-to-seconds
28154 (org-read-date nil 'to-time nil "Starting date: ")))
28155 (time2 (time-to-seconds
28156 (org-read-date nil 'to-time nil "End date:")))
28157 ;; callback function
28158 (callback (lambda ()
28159 (let ((time
28160 (time-to-seconds
28161 (apply 'encode-time
28162 (org-parse-time-string
28163 (match-string 1))))))
28164 ;; check if time in interval
28165 (and (>= time time1) (<= time time2))))))
28166 ;; make tree, check each match with the callback
28167 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
28169 ;;;; Finish up
28171 (provide 'org)
28173 (run-hooks 'org-load-hook)
28175 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
28176 ;;; org.el ends here